diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.net10.0.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.net10.0.cs index f909b08d18a5..d16f9bc7ef91 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.net10.0.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.net10.0.cs @@ -41,8 +41,9 @@ protected override void Dispose(bool disposing) { } } public partial class AzureMonitorOpenTelemetryExporterContext : System.ClientModel.Primitives.ModelReaderWriterContext { - public AzureMonitorOpenTelemetryExporterContext() { } - public Azure.Monitor.OpenTelemetry.Exporter.AzureMonitorOpenTelemetryExporterContext Default { get { throw null; } } + internal AzureMonitorOpenTelemetryExporterContext() { } + public static Azure.Monitor.OpenTelemetry.Exporter.AzureMonitorOpenTelemetryExporterContext Default { get { throw null; } } + protected override bool TryGetTypeBuilderCore(System.Type type, out System.ClientModel.Primitives.ModelReaderWriterTypeBuilder builder) { throw null; } } public sealed partial class AzureMonitorTraceExporter : OpenTelemetry.BaseExporter { diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.net8.0.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.net8.0.cs index f909b08d18a5..d16f9bc7ef91 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.net8.0.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.net8.0.cs @@ -41,8 +41,9 @@ protected override void Dispose(bool disposing) { } } public partial class AzureMonitorOpenTelemetryExporterContext : System.ClientModel.Primitives.ModelReaderWriterContext { - public AzureMonitorOpenTelemetryExporterContext() { } - public Azure.Monitor.OpenTelemetry.Exporter.AzureMonitorOpenTelemetryExporterContext Default { get { throw null; } } + internal AzureMonitorOpenTelemetryExporterContext() { } + public static Azure.Monitor.OpenTelemetry.Exporter.AzureMonitorOpenTelemetryExporterContext Default { get { throw null; } } + protected override bool TryGetTypeBuilderCore(System.Type type, out System.ClientModel.Primitives.ModelReaderWriterTypeBuilder builder) { throw null; } } public sealed partial class AzureMonitorTraceExporter : OpenTelemetry.BaseExporter { diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.netstandard2.0.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.netstandard2.0.cs index f909b08d18a5..d16f9bc7ef91 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.netstandard2.0.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.netstandard2.0.cs @@ -41,8 +41,9 @@ protected override void Dispose(bool disposing) { } } public partial class AzureMonitorOpenTelemetryExporterContext : System.ClientModel.Primitives.ModelReaderWriterContext { - public AzureMonitorOpenTelemetryExporterContext() { } - public Azure.Monitor.OpenTelemetry.Exporter.AzureMonitorOpenTelemetryExporterContext Default { get { throw null; } } + internal AzureMonitorOpenTelemetryExporterContext() { } + public static Azure.Monitor.OpenTelemetry.Exporter.AzureMonitorOpenTelemetryExporterContext Default { get { throw null; } } + protected override bool TryGetTypeBuilderCore(System.Type type, out System.ClientModel.Primitives.ModelReaderWriterTypeBuilder builder) { throw null; } } public sealed partial class AzureMonitorTraceExporter : OpenTelemetry.BaseExporter { diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/metadata.json b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/metadata.json new file mode 100644 index 000000000000..2234014ef8e4 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/metadata.json @@ -0,0 +1,5 @@ +{ + "apiVersions": { + "AzureMonitorExporter": "v2.1" + } +} \ No newline at end of file diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/ApiCompatBaseline.txt b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/ApiCompatBaseline.txt new file mode 100644 index 000000000000..d87966c72eea --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/ApiCompatBaseline.txt @@ -0,0 +1,6 @@ +# AzureMonitorOpenTelemetryExporterContext was a source-generated infrastructure class +# marked [EditorBrowsable(EditorBrowsableState.Never)], never intended for direct use. +# The source generator now emits a private constructor (singleton via Default property) +# which is a safe change since no consumers should be instantiating this class. +CannotSealType : Type 'Azure.Monitor.OpenTelemetry.Exporter.AzureMonitorOpenTelemetryExporterContext' is effectively (has a private constructor) sealed in the implementation but not sealed in the contract. +MembersMustExist : Member 'public void Azure.Monitor.OpenTelemetry.Exporter.AzureMonitorOpenTelemetryExporterContext..ctor()' does not exist in the implementation but it does exist in the contract. diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Azure.Monitor.OpenTelemetry.Exporter.csproj b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Azure.Monitor.OpenTelemetry.Exporter.csproj index 5d2fcf4d1938..6c747c764ef7 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Azure.Monitor.OpenTelemetry.Exporter.csproj +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Azure.Monitor.OpenTelemetry.Exporter.csproj @@ -17,7 +17,6 @@ IConfiguration. --> $(NoWarn);SYSLIB1100;SYSLIB1101 $(DefineConstants);AZURE_MONITOR_EXPORTER; - true diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/ApplicationInsightsRestClient.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/ApplicationInsightsRestClient.cs index d20d439bf9ae..011b7d3311b0 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/ApplicationInsightsRestClient.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/ApplicationInsightsRestClient.cs @@ -17,7 +17,19 @@ namespace Azure.Monitor.OpenTelemetry.Exporter { internal partial class ApplicationInsightsRestClient { - private RawRequestUriBuilder _rawRequestUriBuilder; + private RawRequestUriBuilder? _rawRequestUriBuilder; + + /// Initializes a new instance of ApplicationInsightsRestClient with pre-built pipeline. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// Breeze endpoint. + internal ApplicationInsightsRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string host) + { + ClientDiagnostics = clientDiagnostics; + Pipeline = pipeline; + _endpoint = new Uri(host); + _apiVersion = "v2.1"; + } /// /// This operation sends a sequence of telemetry events that will be monitored by Azure Monitor. @@ -37,7 +49,7 @@ internal async Task InternalTrackAsync(IEnumerable b try { RedirectPolicy.SetAllowAutoRedirect(message, false); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + await Pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { @@ -65,7 +77,7 @@ internal async Task InternalTrackAsync(ReadOnlyMemory body, C try { RedirectPolicy.SetAllowAutoRedirect(message, false); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + await Pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { @@ -108,16 +120,18 @@ internal HttpMessage CreateTrackRequest(ReadOnlyMemory body) [MethodImpl(MethodImplOptions.AggressiveInlining)] private HttpMessage CreateRequest(RequestContent requestContent) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; request.Uri = LazyInitializer.EnsureInitialized(ref _rawRequestUriBuilder, () => { var uri = new RawRequestUriBuilder(); - uri.AppendRaw(_host, false); - uri.AppendRaw("/v2.1/track", false); + uri.Reset(_endpoint); + uri.AppendPath("/", false); + uri.AppendPath(_apiVersion, true); + uri.AppendPath("/track", false); return uri; - }); + })!; request.Headers.Add("Content-Type", "application/json"); request.Headers.Add("Accept", "application/json"); request.Content = requestContent; diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/AzureMonitorOpenTelemetryExporterContext.Custom.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/AzureMonitorOpenTelemetryExporterContext.Custom.cs deleted file mode 100644 index 801fde3889b3..000000000000 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/AzureMonitorOpenTelemetryExporterContext.Custom.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.ClientModel.Primitives; -using System.ComponentModel; - -namespace Azure.Monitor.OpenTelemetry.Exporter -{ - /// - /// Context class which will be filled in by the System.ClientModel.SourceGeneration. - /// For more information see 'https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/System.ClientModel/src/docs/ModelReaderWriterContext.md' - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public partial class AzureMonitorOpenTelemetryExporterContext : ModelReaderWriterContext - { - private AzureMonitorOpenTelemetryExporterContext? _azureMonitorOpenTelemetryExporterContext; - - /// Gets the default instance - [EditorBrowsable(EditorBrowsableState.Never)] - public AzureMonitorOpenTelemetryExporterContext Default => _azureMonitorOpenTelemetryExporterContext ??= new(); - } -} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/ApplicationInsightsRestClient.RestClient.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/ApplicationInsightsRestClient.RestClient.cs new file mode 100644 index 000000000000..d22e7f413877 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/ApplicationInsightsRestClient.RestClient.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using Azure; +using Azure.Core; + +namespace Azure.Monitor.OpenTelemetry.Exporter +{ + internal partial class ApplicationInsightsRestClient + { + private static ResponseClassifier _pipelineMessageClassifier200206; + + private static ResponseClassifier PipelineMessageClassifier200206 => _pipelineMessageClassifier200206 ??= new StatusCodeClassifier(stackalloc ushort[] { 200, 206 }); + + internal HttpMessage CreateTrackRequest(RequestContent content, RequestContext context) + { + RawRequestUriBuilder uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/", false); + uri.AppendPath(_apiVersion, true); + uri.AppendPath("/track", false); + HttpMessage message = Pipeline.CreateMessage(context, PipelineMessageClassifier200206); + Request request = message.Request; + request.Uri = uri; + request.Method = RequestMethod.Post; + request.Headers.SetValue("Content-Type", "application/json"); + request.Headers.SetValue("Accept", "application/json"); + request.Content = content; + return message; + } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/ApplicationInsightsRestClient.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/ApplicationInsightsRestClient.cs index e3f8f1499c28..136dd6c5ad42 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/ApplicationInsightsRestClient.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/ApplicationInsightsRestClient.cs @@ -7,9 +7,9 @@ using System; using System.Collections.Generic; -using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.Monitor.OpenTelemetry.Exporter.Models; @@ -18,80 +18,135 @@ namespace Azure.Monitor.OpenTelemetry.Exporter { internal partial class ApplicationInsightsRestClient { - private readonly HttpPipeline _pipeline; - private readonly string _host; + private readonly Uri _endpoint; + /// A credential used to authenticate to the service. + private readonly TokenCredential _tokenCredential; + private static readonly string[] AuthorizationScopes = new string[] { "https://monitor.azure.com/.default" }; + private readonly string _apiVersion; - /// The ClientDiagnostics is used to provide tracing support for the client library. - internal ClientDiagnostics ClientDiagnostics { get; } + /// Initializes a new instance of ApplicationInsightsRestClient for mocking. + protected ApplicationInsightsRestClient() + { + } /// Initializes a new instance of ApplicationInsightsRestClient. - /// The handler for diagnostic messaging in the client. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// Breeze endpoint: https://dc.services.visualstudio.com. The default value is "https://dc.services.visualstudio.com". - /// , or is null. - public ApplicationInsightsRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string host) + /// A credential used to authenticate to the service. + public ApplicationInsightsRestClient(TokenCredential credential) : this(new Uri("https://dc.services.visualstudio.com"), credential, new ApplicationInsightsRestClientOptions()) { - ClientDiagnostics = clientDiagnostics ?? throw new ArgumentNullException(nameof(clientDiagnostics)); - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _host = host ?? throw new ArgumentNullException(nameof(host)); } - /// Track telemetry events. - /// The list of telemetry events to track. - /// The cancellation token to use. - /// is null. - /// This operation sends a sequence of telemetry events that will be monitored by Azure Monitor. - public async Task> TrackAsync(IEnumerable body, CancellationToken cancellationToken = default) + /// Initializes a new instance of ApplicationInsightsRestClient. + /// A credential used to authenticate to the service. + /// The options for configuring the client. + public ApplicationInsightsRestClient(TokenCredential credential, ApplicationInsightsRestClientOptions options) : this(new Uri("https://dc.services.visualstudio.com"), credential, options) { - if (body == null) + } + + /// Initializes a new instance of ApplicationInsightsRestClient. + /// Service endpoint. + /// A credential used to authenticate to the service. + /// The options for configuring the client. + public ApplicationInsightsRestClient(Uri endpoint, TokenCredential credential, ApplicationInsightsRestClientOptions options) + { + options ??= new ApplicationInsightsRestClientOptions(); + + _endpoint = endpoint; + _tokenCredential = credential; + Pipeline = HttpPipelineBuilder.Build(options, new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }); + _apiVersion = options.Version; + ClientDiagnostics = new ClientDiagnostics(options, true); + } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline { get; } + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// + /// [Protocol Method] This operation sends a sequence of telemetry events that will be monitored by + /// Azure Monitor. + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// The content to send as the body of the request. + /// The request options, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response Track(RequestContent content, RequestContext context = null) + { + using DiagnosticScope scope = ClientDiagnostics.CreateScope("ApplicationInsightsRestClient.Track"); + scope.Start(); + try { - throw new ArgumentNullException(nameof(body)); + using HttpMessage message = CreateTrackRequest(content, context); + return Pipeline.ProcessMessage(message, context); } - - using var message = CreateTrackRequest(body); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) + catch (Exception e) { - case 200: - case 206: - { - TrackResponse value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = TrackResponse.DeserializeTrackResponse(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); + scope.Failed(e); + throw; } } - /// Track telemetry events. - /// The list of telemetry events to track. - /// The cancellation token to use. - /// is null. - /// This operation sends a sequence of telemetry events that will be monitored by Azure Monitor. - public Response Track(IEnumerable body, CancellationToken cancellationToken = default) + /// + /// [Protocol Method] This operation sends a sequence of telemetry events that will be monitored by + /// Azure Monitor. + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// The content to send as the body of the request. + /// The request options, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task TrackAsync(RequestContent content, RequestContext context = null) { - if (body == null) + using DiagnosticScope scope = ClientDiagnostics.CreateScope("ApplicationInsightsRestClient.Track"); + scope.Start(); + try { - throw new ArgumentNullException(nameof(body)); + using HttpMessage message = CreateTrackRequest(content, context); + return await Pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } - - using var message = CreateTrackRequest(body); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) + catch (Exception e) { - case 200: - case 206: - { - TrackResponse value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = TrackResponse.DeserializeTrackResponse(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); + scope.Failed(e); + throw; } } + + /// + /// This operation sends a sequence of telemetry events that will be monitored by + /// Azure Monitor. + /// + /// The list of telemetry events to track. + /// The cancellation token that can be used to cancel the operation. + /// Service returned a non-success status code. + internal virtual Response Track(IEnumerable body, CancellationToken cancellationToken = default) + { + using RequestContent content = BinaryContentHelper.FromEnumerable(body); + Response result = Track(content, cancellationToken.ToRequestContext()); + return Response.FromValue((TrackResponse)result, result); + } + + /// + /// This operation sends a sequence of telemetry events that will be monitored by + /// Azure Monitor. + /// + /// The list of telemetry events to track. + /// The cancellation token that can be used to cancel the operation. + /// Service returned a non-success status code. + internal virtual async Task> TrackAsync(IEnumerable body, CancellationToken cancellationToken = default) + { + using RequestContent content = BinaryContentHelper.FromEnumerable(body); + Response result = await TrackAsync(content, cancellationToken.ToRequestContext()).ConfigureAwait(false); + return Response.FromValue((TrackResponse)result, result); + } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/ApplicationInsightsRestClientOptions.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/ApplicationInsightsRestClientOptions.cs new file mode 100644 index 000000000000..324a1081a62a --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/ApplicationInsightsRestClientOptions.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.Monitor.OpenTelemetry.Exporter +{ + /// Client options for . + internal partial class ApplicationInsightsRestClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2_1; + + /// Initializes a new instance of ApplicationInsightsRestClientOptions. + /// The service version. + public ApplicationInsightsRestClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2_1 => "v2.1", + _ => throw new NotSupportedException() + }; + } + + /// Gets the Version. + internal string Version { get; } + + internal enum ServiceVersion + { + /// The V2.1 API version. + V2_1 = 1 + } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/Argument.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/Argument.cs index 10a0f78d8b27..0ab9ed47aaec 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/Argument.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/Argument.cs @@ -11,8 +11,10 @@ namespace Azure.Monitor.OpenTelemetry.Exporter { - internal static class Argument + internal static partial class Argument { + /// The value. + /// The name. public static void AssertNotNull(T value, string name) { if (value is null) @@ -21,8 +23,10 @@ public static void AssertNotNull(T value, string name) } } + /// The value. + /// The name. public static void AssertNotNull(T? value, string name) - where T : struct + where T : struct { if (!value.HasValue) { @@ -30,6 +34,8 @@ public static void AssertNotNull(T? value, string name) } } + /// The value. + /// The name. public static void AssertNotNullOrEmpty(IEnumerable value, string name) { if (value is null) @@ -51,6 +57,8 @@ public static void AssertNotNullOrEmpty(IEnumerable value, string name) } } + /// The value. + /// The name. public static void AssertNotNullOrEmpty(string value, string name) { if (value is null) @@ -63,6 +71,8 @@ public static void AssertNotNullOrEmpty(string value, string name) } } + /// The value. + /// The name. public static void AssertNotNullOrWhiteSpace(string value, string name) { if (value is null) @@ -75,17 +85,12 @@ public static void AssertNotNullOrWhiteSpace(string value, string 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); - } - } - + /// The value. + /// The minimum value. + /// The maximum value. + /// The name. public static void AssertInRange(T value, T minimum, T maximum, string name) - where T : notnull, IComparable + where T : notnull, IComparable { if (minimum.CompareTo(value) > 0) { @@ -97,33 +102,12 @@ public static void AssertInRange(T value, T minimum, T maximum, string name) } } - 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; - } - + /// The value. + /// The name. 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/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/RequestContentHelper.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/BinaryContentHelper.cs similarity index 76% rename from sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/RequestContentHelper.cs rename to sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/BinaryContentHelper.cs index e9cd5e329540..6fb531846305 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/RequestContentHelper.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/BinaryContentHelper.cs @@ -12,22 +12,24 @@ namespace Azure.Monitor.OpenTelemetry.Exporter { - internal static class RequestContentHelper + internal static partial class BinaryContentHelper { + /// public static RequestContent FromEnumerable(IEnumerable enumerable) - where T : notnull + where T : notnull { Utf8JsonRequestContent content = new Utf8JsonRequestContent(); content.JsonWriter.WriteStartArray(); foreach (var item in enumerable) { - content.JsonWriter.WriteObjectValue(item); + content.JsonWriter.WriteObjectValue(item, ModelSerializationExtensions.WireOptions); } content.JsonWriter.WriteEndArray(); return content; } + /// public static RequestContent FromEnumerable(IEnumerable enumerable) { Utf8JsonRequestContent content = new Utf8JsonRequestContent(); @@ -41,9 +43,9 @@ public static RequestContent FromEnumerable(IEnumerable enumerable) else { #if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(item); + content.JsonWriter.WriteRawValue(item); #else - using (JsonDocument document = JsonDocument.Parse(item, ModelSerializationExtensions.JsonDocumentOptions)) + using (JsonDocument document = JsonDocument.Parse(item)) { JsonSerializer.Serialize(content.JsonWriter, document.RootElement); } @@ -55,35 +57,39 @@ public static RequestContent FromEnumerable(IEnumerable enumerable) return content; } + /// public static RequestContent FromEnumerable(ReadOnlySpan span) - where T : notnull + where T : notnull { Utf8JsonRequestContent content = new Utf8JsonRequestContent(); content.JsonWriter.WriteStartArray(); - for (int i = 0; i < span.Length; i++) + int i = 0; + for (; i < span.Length; i++) { - content.JsonWriter.WriteObjectValue(span[i]); + content.JsonWriter.WriteObjectValue(span[i], ModelSerializationExtensions.WireOptions); } content.JsonWriter.WriteEndArray(); return content; } + /// public static RequestContent FromDictionary(IDictionary dictionary) - where TValue : notnull + 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); + content.JsonWriter.WriteObjectValue(item.Value, ModelSerializationExtensions.WireOptions); } content.JsonWriter.WriteEndObject(); return content; } + /// public static RequestContent FromDictionary(IDictionary dictionary) { Utf8JsonRequestContent content = new Utf8JsonRequestContent(); @@ -98,9 +104,9 @@ public static RequestContent FromDictionary(IDictionary dict else { #if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(item.Value); + content.JsonWriter.WriteRawValue(item.Value); #else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + using (JsonDocument document = JsonDocument.Parse(item.Value)) { JsonSerializer.Serialize(content.JsonWriter, document.RootElement); } @@ -112,20 +118,22 @@ public static RequestContent FromDictionary(IDictionary dict return content; } + /// public static RequestContent FromObject(object value) { Utf8JsonRequestContent content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(value); + 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); + content.JsonWriter.WriteRawValue(value); #else - using (JsonDocument document = JsonDocument.Parse(value, ModelSerializationExtensions.JsonDocumentOptions)) + using (JsonDocument document = JsonDocument.Parse(value)) { JsonSerializer.Serialize(content.JsonWriter, document.RootElement); } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CancellationTokenExtensions.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CancellationTokenExtensions.cs new file mode 100644 index 000000000000..a0b1de231bcc --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CancellationTokenExtensions.cs @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Threading; +using Azure; + +namespace Azure.Monitor.OpenTelemetry.Exporter +{ + internal static partial class CancellationTokenExtensions + { + public static RequestContext ToRequestContext(this CancellationToken cancellationToken) => cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ChangeTrackingDictionary.cs index fd98c5924b31..e3a7c4ac5545 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ChangeTrackingDictionary.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -11,7 +11,8 @@ namespace Azure.Monitor.OpenTelemetry.Exporter { - internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull + internal partial class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary + where TKey : notnull { private IDictionary _innerDictionary; @@ -19,6 +20,7 @@ public ChangeTrackingDictionary() { } + /// The inner dictionary. public ChangeTrackingDictionary(IDictionary dictionary) { if (dictionary == null) @@ -28,6 +30,7 @@ public ChangeTrackingDictionary(IDictionary dictionary) _innerDictionary = new Dictionary(dictionary); } + /// The inner dictionary. public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) { if (dictionary == null) @@ -41,16 +44,22 @@ public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) } } + /// Gets the IsUndefined. public bool IsUndefined => _innerDictionary == null; + /// Gets the Count. public int Count => IsUndefined ? 0 : EnsureDictionary().Count; + /// Gets the IsReadOnly. public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; + /// Gets the Keys. public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; + /// Gets the Values. public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; + /// Gets or sets the value associated with the specified key. public TValue this[TKey key] { get @@ -67,8 +76,10 @@ public TValue this[TKey key] } } + /// Gets the Keys. IEnumerable IReadOnlyDictionary.Keys => Keys; + /// Gets the Values. IEnumerable IReadOnlyDictionary.Values => Values; public IEnumerator> GetEnumerator() @@ -89,6 +100,7 @@ IEnumerator IEnumerable.GetEnumerator() return GetEnumerator(); } + /// The item to add. public void Add(KeyValuePair item) { EnsureDictionary().Add(item); @@ -99,6 +111,7 @@ public void Clear() EnsureDictionary().Clear(); } + /// The item to search for. public bool Contains(KeyValuePair item) { if (IsUndefined) @@ -108,6 +121,8 @@ public bool Contains(KeyValuePair item) return EnsureDictionary().Contains(item); } + /// The array to copy. + /// The index. public void CopyTo(KeyValuePair[] array, int index) { if (IsUndefined) @@ -117,6 +132,7 @@ public void CopyTo(KeyValuePair[] array, int index) EnsureDictionary().CopyTo(array, index); } + /// The item to remove. public bool Remove(KeyValuePair item) { if (IsUndefined) @@ -126,11 +142,14 @@ public bool Remove(KeyValuePair item) return EnsureDictionary().Remove(item); } + /// The key. + /// The value to add. public void Add(TKey key, TValue value) { EnsureDictionary().Add(key, value); } + /// The key to search for. public bool ContainsKey(TKey key) { if (IsUndefined) @@ -140,6 +159,7 @@ public bool ContainsKey(TKey key) return EnsureDictionary().ContainsKey(key); } + /// The key. public bool Remove(TKey key) { if (IsUndefined) @@ -149,6 +169,8 @@ public bool Remove(TKey key) return EnsureDictionary().Remove(key); } + /// The key to search for. + /// The value. public bool TryGetValue(TKey key, out TValue value) { if (IsUndefined) diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ChangeTrackingList.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ChangeTrackingList.cs index 7b894360b8a6..52e128e5dd92 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ChangeTrackingList.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ChangeTrackingList.cs @@ -12,7 +12,7 @@ namespace Azure.Monitor.OpenTelemetry.Exporter { - internal class ChangeTrackingList : IList, IReadOnlyList + internal partial class ChangeTrackingList : IList, IReadOnlyList { private IList _innerList; @@ -20,6 +20,7 @@ public ChangeTrackingList() { } + /// The inner list. public ChangeTrackingList(IList innerList) { if (innerList != null) @@ -28,6 +29,7 @@ public ChangeTrackingList(IList innerList) } } + /// The inner list. public ChangeTrackingList(IReadOnlyList innerList) { if (innerList != null) @@ -36,12 +38,16 @@ public ChangeTrackingList(IReadOnlyList innerList) } } + /// Gets the IsUndefined. public bool IsUndefined => _innerList == null; + /// Gets the Count. public int Count => IsUndefined ? 0 : EnsureList().Count; + /// Gets the IsReadOnly. public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; + /// Gets or sets the value associated with the specified key. public T this[int index] { get @@ -85,6 +91,7 @@ IEnumerator IEnumerable.GetEnumerator() return GetEnumerator(); } + /// The item to add. public void Add(T item) { EnsureList().Add(item); @@ -95,6 +102,7 @@ public void Clear() EnsureList().Clear(); } + /// The item. public bool Contains(T item) { if (IsUndefined) @@ -104,6 +112,8 @@ public bool Contains(T item) return EnsureList().Contains(item); } + /// The array to copy to. + /// The array index. public void CopyTo(T[] array, int arrayIndex) { if (IsUndefined) @@ -113,6 +123,7 @@ public void CopyTo(T[] array, int arrayIndex) EnsureList().CopyTo(array, arrayIndex); } + /// The item. public bool Remove(T item) { if (IsUndefined) @@ -122,6 +133,7 @@ public bool Remove(T item) return EnsureList().Remove(item); } + /// The item. public int IndexOf(T item) { if (IsUndefined) @@ -131,11 +143,14 @@ public int IndexOf(T item) return EnsureList().IndexOf(item); } + /// The inner list. + /// The item. public void Insert(int index, T item) { EnsureList().Insert(index, item); } + /// The inner list. public void RemoveAt(int index) { if (IsUndefined) diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ClientPipelineExtensions.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ClientPipelineExtensions.cs new file mode 100644 index 000000000000..86db19a0bdb3 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ClientPipelineExtensions.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Threading; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.Monitor.OpenTelemetry.Exporter +{ + internal static partial class ClientPipelineExtensions + { + public static async ValueTask ProcessMessageAsync(this HttpPipeline pipeline, HttpMessage message, RequestContext context) + { + (CancellationToken userCancellationToken, ErrorOptions errorOptions) = context.Parse(); + await pipeline.SendAsync(message, userCancellationToken).ConfigureAwait(false); + + if (message.Response.IsError && (errorOptions & ErrorOptions.NoThrow) != ErrorOptions.NoThrow) + { + throw new RequestFailedException(message.Response); + } + + return message.Response; + } + + public static Response ProcessMessage(this HttpPipeline pipeline, HttpMessage message, RequestContext context) + { + (CancellationToken userCancellationToken, ErrorOptions errorOptions) = context.Parse(); + pipeline.Send(message, userCancellationToken); + + if (message.Response.IsError && (errorOptions & ErrorOptions.NoThrow) != ErrorOptions.NoThrow) + { + throw new RequestFailedException(message.Response); + } + + return message.Response; + } + + public static async ValueTask> ProcessHeadAsBoolMessageAsync(this HttpPipeline pipeline, HttpMessage message, RequestContext context) + { + Response response = await pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + switch (response.Status) + { + case >= 200 and < 300: + return Response.FromValue(true, response); + case >= 400 and < 500: + return Response.FromValue(false, response); + default: + return new ErrorResult(response, new RequestFailedException(response)); + } + } + + public static Response ProcessHeadAsBoolMessage(this HttpPipeline pipeline, HttpMessage message, RequestContext context) + { + Response response = pipeline.ProcessMessage(message, context); + switch (response.Status) + { + case >= 200 and < 300: + return Response.FromValue(true, response); + case >= 400 and < 500: + return Response.FromValue(false, response); + default: + return new ErrorResult(response, new RequestFailedException(response)); + } + } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CodeGenMemberAttribute.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CodeGenMemberAttribute.cs new file mode 100644 index 000000000000..72778edeb7e4 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CodeGenMemberAttribute.cs @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Microsoft.TypeSpec.Generator.Customizations +{ + [AttributeUsage((AttributeTargets.Property | AttributeTargets.Field))] + internal partial class CodeGenMemberAttribute : CodeGenTypeAttribute + { + /// The original name of the member. + public CodeGenMemberAttribute(string originalName) : base(originalName) + { + } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CodeGenSerializationAttribute.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CodeGenSerializationAttribute.cs new file mode 100644 index 000000000000..dfcabf517497 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CodeGenSerializationAttribute.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Microsoft.TypeSpec.Generator.Customizations +{ + [AttributeUsage((AttributeTargets.Class | AttributeTargets.Struct), AllowMultiple = true, Inherited = true)] + internal partial class CodeGenSerializationAttribute : Attribute + { + /// The property name which these hooks apply to. + public CodeGenSerializationAttribute(string propertyName) + { + PropertyName = propertyName; + } + + /// The property name which these hooks apply to. + /// The serialization name of the property. + public CodeGenSerializationAttribute(string propertyName, string serializationName) + { + PropertyName = propertyName; + SerializationName = serializationName; + } + + /// Gets or sets the property name which these hooks should apply to. + public string PropertyName { get; } + + /// Gets or sets the serialization name of the property. + public string SerializationName { get; set; } + + /// + /// Gets or sets the method name to use when serializing the property value (property name excluded). + /// The signature of the serialization hook method must be or compatible with when invoking: private void SerializeHook(Utf8JsonWriter writer); + /// + public string SerializationValueHook { get; set; } + + /// + /// Gets or sets the method name to use when deserializing the property value from the JSON. + /// private static void DeserializationHook(JsonProperty property, ref TypeOfTheProperty propertyValue); // if the property is required + /// private static void DeserializationHook(JsonProperty property, ref Optional<TypeOfTheProperty> propertyValue); // if the property is optional + /// + public string DeserializationValueHook { get; set; } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CodeGenSuppressAttribute.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CodeGenSuppressAttribute.cs new file mode 100644 index 000000000000..38d536e69173 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CodeGenSuppressAttribute.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Microsoft.TypeSpec.Generator.Customizations +{ + [AttributeUsage((AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Struct), AllowMultiple = true)] + internal partial class CodeGenSuppressAttribute : Attribute + { + /// The member to suppress. + /// The types of the parameters of the member. + public CodeGenSuppressAttribute(string member, params Type[] parameters) + { + Member = member; + Parameters = parameters; + } + + /// Gets the Member. + public string Member { get; } + + /// Gets the Parameters. + public Type[] Parameters { get; } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CodeGenTypeAttribute.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CodeGenTypeAttribute.cs new file mode 100644 index 000000000000..f36b5f513173 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/CodeGenTypeAttribute.cs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Microsoft.TypeSpec.Generator.Customizations +{ + [AttributeUsage((AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Struct))] + internal partial class CodeGenTypeAttribute : Attribute + { + /// The original name of the type. + public CodeGenTypeAttribute(string originalName) + { + OriginalName = originalName; + } + + /// Gets the OriginalName. + public string OriginalName { get; } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ErrorResult.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ErrorResult.cs new file mode 100644 index 000000000000..3961d20f5306 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ErrorResult.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using Azure; + +namespace Azure.Monitor.OpenTelemetry.Exporter +{ + internal partial class ErrorResult : Response + { + private readonly Response _response; + private readonly RequestFailedException _exception; + + public ErrorResult(Response response, RequestFailedException exception) + { + _response = response; + _exception = exception; + } + + /// Gets the Value. + public override T Value => throw _exception; + + /// + public override Response GetRawResponse() + { + return _response; + } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ModelSerializationExtensions.cs index daf34e9f0d3d..b70a7eddaf07 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ModelSerializationExtensions.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/ModelSerializationExtensions.cs @@ -10,19 +10,18 @@ using System.Collections.Generic; using System.Diagnostics; using System.Globalization; +using System.Runtime.InteropServices; using System.Text.Json; -using System.Xml; -using Azure.Core; namespace Azure.Monitor.OpenTelemetry.Exporter { - internal static class ModelSerializationExtensions + internal static partial class ModelSerializationExtensions { - internal static readonly JsonDocumentOptions JsonDocumentOptions = new JsonDocumentOptions { MaxDepth = 256 }; internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); - internal static readonly ModelReaderWriterOptions WireV3Options = new ModelReaderWriterOptions("W|v3"); - internal static readonly ModelReaderWriterOptions JsonV3Options = new ModelReaderWriterOptions("J|v3"); - internal static readonly BinaryData SentinelValue = BinaryData.FromBytes("\"__EMPTY__\""u8.ToArray()); + internal static readonly JsonDocumentOptions JsonDocumentOptions = new JsonDocumentOptions + { + MaxDepth = 256 + }; public static object GetObject(this JsonElement element) { @@ -48,14 +47,14 @@ public static object GetObject(this JsonElement element) case JsonValueKind.Null: return null; case JsonValueKind.Object: - var dictionary = new Dictionary(); + Dictionary 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(); + List list = new List(); foreach (var item in element.EnumerateArray()) { list.Add(item.GetObject()); @@ -93,7 +92,7 @@ public static char GetChar(this JsonElement element) { if (element.ValueKind == JsonValueKind.String) { - var text = element.GetString(); + string text = element.GetString(); if (text == null || text.Length != 1) { throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); @@ -107,14 +106,14 @@ public static char GetChar(this JsonElement element) } [Conditional("DEBUG")] - public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) + 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"); + 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(); + string 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}'."); @@ -171,15 +170,15 @@ public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset v writer.WriteNumberValue(value.ToUnixTimeSeconds()); } - public static void WriteObjectValue(this Utf8JsonWriter writer, T value) + public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) { switch (value) { case null: writer.WriteNullValue(); break; - case IUtf8JsonSerializable serializable: - serializable.Write(writer); + case IJsonModel jsonModel: + jsonModel.Write(writer, options ?? WireOptions); break; case byte[] bytes: writer.WriteBase64StringValue(bytes); @@ -232,7 +231,7 @@ public static void WriteObjectValue(this Utf8JsonWriter writer, T value) foreach (var pair in enumerable) { writer.WritePropertyName(pair.Key); - writer.WriteObjectValue(pair.Value); + writer.WriteObjectValue(pair.Value, options); } writer.WriteEndObject(); break; @@ -240,7 +239,7 @@ public static void WriteObjectValue(this Utf8JsonWriter writer, T value) writer.WriteStartArray(); foreach (var item in objectEnumerable) { - writer.WriteObjectValue(item); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); break; @@ -252,155 +251,18 @@ public static void WriteObjectValue(this Utf8JsonWriter writer, T value) } } - public static void WriteObjectValue(this Utf8JsonWriter writer, object value) + public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) { - writer.WriteObjectValue(value); + writer.WriteObjectValue(value, options); } - internal static bool IsSentinelValue(BinaryData value) + public static BinaryData GetUtf8Bytes(this JsonElement element) { - ReadOnlySpan sentinelSpan = SentinelValue.ToMemory().Span; - ReadOnlySpan valueSpan = value.ToMemory().Span; - return sentinelSpan.SequenceEqual(valueSpan); - } - - 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() - }; +#if NET9_0_OR_GREATER + return new global::System.BinaryData(global::System.Runtime.InteropServices.JsonMarshal.GetRawUtf8Value(element).ToArray()); +#else + return BinaryData.FromString(element.GetRawText()); +#endif } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/MultipartFormDataRequestContent.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/MultipartFormDataRequestContent.cs deleted file mode 100644 index 9b48b9150239..000000000000 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/MultipartFormDataRequestContent.cs +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.IO; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.Monitor.OpenTelemetry.Exporter -{ - internal class MultipartFormDataRequestContent : RequestContent - { - private readonly System.Net.Http.MultipartFormDataContent _multipartContent; - private static readonly Random _random = new Random(); - private static readonly char[] _boundaryValues = "0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".ToCharArray(); - - public MultipartFormDataRequestContent() - { - _multipartContent = new System.Net.Http.MultipartFormDataContent(CreateBoundary()); - } - - public string ContentType - { - get - { - return _multipartContent.Headers.ContentType.ToString(); - } - } - - internal HttpContent HttpContent => _multipartContent; - - private static string CreateBoundary() - { - Span chars = new char[70]; - byte[] random = new byte[70]; - _random.NextBytes(random); - int mask = 255 >> 2; - for (int i = 0; i < 70; i++) - { - chars[i] = _boundaryValues[random[i] & mask]; - } - return chars.ToString(); - } - - public void Add(string content, string name, string filename = null, string contentType = null) - { - Argument.AssertNotNull(content, nameof(content)); - Argument.AssertNotNullOrEmpty(name, nameof(name)); - - Add(new StringContent(content), name, filename, contentType); - } - - public void Add(int content, string name, string filename = null, string contentType = null) - { - Argument.AssertNotNull(content, nameof(content)); - Argument.AssertNotNullOrEmpty(name, nameof(name)); - - string value = content.ToString("G", CultureInfo.InvariantCulture); - Add(new StringContent(value), name, filename, contentType); - } - - public void Add(long content, string name, string filename = null, string contentType = null) - { - Argument.AssertNotNull(content, nameof(content)); - Argument.AssertNotNullOrEmpty(name, nameof(name)); - - string value = content.ToString("G", CultureInfo.InvariantCulture); - Add(new StringContent(value), name, filename, contentType); - } - - public void Add(float content, string name, string filename = null, string contentType = null) - { - Argument.AssertNotNull(content, nameof(content)); - Argument.AssertNotNullOrEmpty(name, nameof(name)); - - string value = content.ToString("G", CultureInfo.InvariantCulture); - Add(new StringContent(value), name, filename, contentType); - } - - public void Add(double content, string name, string filename = null, string contentType = null) - { - Argument.AssertNotNull(content, nameof(content)); - Argument.AssertNotNullOrEmpty(name, nameof(name)); - - string value = content.ToString("G", CultureInfo.InvariantCulture); - Add(new StringContent(value), name, filename, contentType); - } - - public void Add(decimal content, string name, string filename = null, string contentType = null) - { - Argument.AssertNotNull(content, nameof(content)); - Argument.AssertNotNullOrEmpty(name, nameof(name)); - - string value = content.ToString("G", CultureInfo.InvariantCulture); - Add(new StringContent(value), name, filename, contentType); - } - - public void Add(bool content, string name, string filename = null, string contentType = null) - { - Argument.AssertNotNull(content, nameof(content)); - Argument.AssertNotNullOrEmpty(name, nameof(name)); - - string value = content ? "true" : "false"; - Add(new StringContent(value), name, filename, contentType); - } - - public void Add(Stream content, string name, string filename = null, string contentType = null) - { - Argument.AssertNotNull(content, nameof(content)); - Argument.AssertNotNullOrEmpty(name, nameof(name)); - - Add(new StreamContent(content), name, filename, contentType); - } - - public void Add(byte[] content, string name, string filename = null, string contentType = null) - { - Argument.AssertNotNull(content, nameof(content)); - Argument.AssertNotNullOrEmpty(name, nameof(name)); - - Add(new ByteArrayContent(content), name, filename, contentType); - } - - public void Add(BinaryData content, string name, string filename = null, string contentType = null) - { - Argument.AssertNotNull(content, nameof(content)); - Argument.AssertNotNullOrEmpty(name, nameof(name)); - - Add(new ByteArrayContent(content.ToArray()), name, filename, contentType); - } - - private void Add(HttpContent content, string name, string filename, string contentType) - { - if (filename != null) - { - Argument.AssertNotNullOrEmpty(filename, nameof(filename)); - AddFilenameHeader(content, name, filename); - } - if (contentType != null) - { - Argument.AssertNotNullOrEmpty(contentType, nameof(contentType)); - AddContentTypeHeader(content, contentType); - } - _multipartContent.Add(content, name); - } - - public static void AddFilenameHeader(HttpContent content, string name, string filename) - { - ContentDispositionHeaderValue header = new ContentDispositionHeaderValue("form-data") { Name = name, FileName = filename }; - content.Headers.ContentDisposition = header; - } - - public static void AddContentTypeHeader(HttpContent content, string contentType) - { - MediaTypeHeaderValue header = new MediaTypeHeaderValue(contentType); - content.Headers.ContentType = header; - } - - public override bool TryComputeLength(out long length) - { - if (_multipartContent.Headers.ContentLength is long contentLength) - { - length = contentLength; - return true; - } - length = 0; - return false; - } - - public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) - { -#if NET6_0_OR_GREATER - _multipartContent.CopyTo(stream, default, cancellationToken); -#else -#pragma warning disable AZC0107 - _multipartContent.CopyToAsync(stream).EnsureCompleted(); -#pragma warning restore AZC0107 -#endif - } - - public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) - { -#if NET6_0_OR_GREATER - await _multipartContent.CopyToAsync(stream, cancellationToken).ConfigureAwait(false); -#else - await _multipartContent.CopyToAsync(stream).ConfigureAwait(false); -#endif - } - - public override void Dispose() - { - _multipartContent.Dispose(); - } - } -} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/Optional.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/Optional.cs index be84bb941ab0..f09ceb6373e9 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/Optional.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/Optional.cs @@ -10,7 +10,7 @@ namespace Azure.Monitor.OpenTelemetry.Exporter { - internal static class Optional + internal static partial class Optional { public static bool IsCollectionDefined(IEnumerable collection) { @@ -28,7 +28,7 @@ public static bool IsCollectionDefined(IReadOnlyDictionary(T? value) - where T : struct + where T : struct { return value.HasValue; } @@ -38,14 +38,14 @@ public static bool IsDefined(object value) return value != null; } - public static bool IsDefined(JsonElement value) + public static bool IsDefined(string value) { - return value.ValueKind != JsonValueKind.Undefined; + return value != null; } - public static bool IsDefined(string value) + public static bool IsDefined(JsonElement value) { - return value != null; + return value.ValueKind != JsonValueKind.Undefined; } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/RawRequestUriBuilderExtensions.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/RawRequestUriBuilderExtensions.cs new file mode 100644 index 000000000000..36475892e4f3 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/RawRequestUriBuilderExtensions.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Linq; +using Azure.Core; + +namespace Azure.Monitor.OpenTelemetry.Exporter +{ + internal static partial class RawRequestUriBuilderExtensions + { + public static void AppendQueryDelimited(this RawRequestUriBuilder builder, string name, IEnumerable value, string delimiter, SerializationFormat format = SerializationFormat.Default, bool escape = true) + { + delimiter ??= ","; + IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v, format)); + builder.AppendQuery(name, string.Join(delimiter, stringValues), escape); + } + + public static void UpdateQuery(this RawRequestUriBuilder builder, string name, string value) + { + string currentQuery = builder.Query; + string searchPattern = string.Concat(name, "="); + int paramStartIndex = -1; + if (currentQuery.StartsWith(string.Concat("?", searchPattern))) + { + paramStartIndex = 1; + } + if (paramStartIndex == -1) + { + string prefixedPattern = string.Concat("&", searchPattern); + int prefixedIndex = currentQuery.IndexOf(prefixedPattern); + if (prefixedIndex >= 0) + { + paramStartIndex = prefixedIndex + 1; + } + } + if (paramStartIndex >= 0) + { + int valueStartIndex = paramStartIndex + searchPattern.Length; + int valueEndIndex = currentQuery.IndexOf('&', valueStartIndex); + if (valueEndIndex == -1) + { + valueEndIndex = currentQuery.Length; + } + string beforeParam = currentQuery.Substring(0, valueStartIndex); + string afterParam = currentQuery.Substring(valueEndIndex); + string newQuery = string.Concat(beforeParam, value, afterParam); + builder.Query = newQuery; + } + else + { + builder.AppendQuery(name, value, true); + } + } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/RequestContextExtensions.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/RequestContextExtensions.cs new file mode 100644 index 000000000000..2a0904d9fab5 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/RequestContextExtensions.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using Azure; + +namespace Azure.Monitor.OpenTelemetry.Exporter +{ + internal static partial class RequestContextExtensions + { + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + public static ValueTuple Parse(this RequestContext context) + { + if (context == null) + { + return (CancellationToken.None, ErrorOptions.Default); + } + return (context.CancellationToken, context.ErrorOptions); + } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/SerializationFormat.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/SerializationFormat.cs new file mode 100644 index 000000000000..8c0d9dc3ea7c --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/SerializationFormat.cs @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +namespace Azure.Monitor.OpenTelemetry.Exporter +{ + internal enum SerializationFormat + { + /// The default serialization format. + Default = 0, + /// The RFC1123 date time format. + DateTime_RFC1123 = 1, + /// The RFC3339 date time format. + DateTime_RFC3339 = 2, + /// The RFC7231 date time format. + DateTime_RFC7231 = 3, + /// The ISO8601 date time format. + DateTime_ISO8601 = 4, + /// The Unix date time format. + DateTime_Unix = 5, + /// The ISO8601 date format. + Date_ISO8601 = 6, + /// The ISO8601 duration format. + Duration_ISO8601 = 7, + /// The constant duration format. + Duration_Constant = 8, + /// The seconds duration format. + Duration_Seconds = 9, + /// The seconds duration format with float precision. + Duration_Seconds_Float = 10, + /// The seconds duration format with double precision. + Duration_Seconds_Double = 11, + /// The milliseconds duration format. + Duration_Milliseconds = 12, + /// The milliseconds duration format with float precision. + Duration_Milliseconds_Float = 13, + /// The milliseconds duration format with double precision. + Duration_Milliseconds_Double = 14, + /// The ISO8601 time format. + Time_ISO8601 = 15, + /// The Base64Url bytes format. + Bytes_Base64Url = 16, + /// The Base64 bytes format. + Bytes_Base64 = 17 + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/TypeFormatters.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/TypeFormatters.cs new file mode 100644 index 000000000000..fd9c32d1d715 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/TypeFormatters.cs @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Xml; + +namespace Azure.Monitor.OpenTelemetry.Exporter +{ + internal static partial 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}. Generated clients require 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 ToFormatSpecifier(SerializationFormat format) => format switch + { + SerializationFormat.DateTime_RFC1123 => "R", + SerializationFormat.DateTime_RFC3339 => "O", + SerializationFormat.DateTime_RFC7231 => "R", + SerializationFormat.DateTime_ISO8601 => "O", + SerializationFormat.Date_ISO8601 => "D", + SerializationFormat.DateTime_Unix => "U", + SerializationFormat.Bytes_Base64Url => "U", + SerializationFormat.Bytes_Base64 => "D", + SerializationFormat.Duration_ISO8601 => "P", + SerializationFormat.Duration_Constant => "c", + SerializationFormat.Duration_Seconds => "%s", + SerializationFormat.Duration_Seconds_Float => "s\\.FFF", + SerializationFormat.Duration_Seconds_Double => "s\\.FFFFFF", + SerializationFormat.Time_ISO8601 => "T", + _ => null + }; + + public static string ConvertToString(object value, SerializationFormat format = SerializationFormat.Default) + { + string formatSpecifier = ToFormatSpecifier(format); + + return 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 formatSpecifier != null => ToString(b0, formatSpecifier), + IEnumerable s0 => string.Join(",", s0), + DateTimeOffset dateTime when formatSpecifier != null => ToString(dateTime, formatSpecifier), + TimeSpan timeSpan when format == SerializationFormat.Duration_Seconds => Convert.ToInt32(timeSpan.TotalSeconds).ToString(CultureInfo.InvariantCulture), + TimeSpan timeSpan0 when format == SerializationFormat.Duration_Seconds_Float || format == SerializationFormat.Duration_Seconds_Double => timeSpan0.TotalSeconds.ToString(CultureInfo.InvariantCulture), + TimeSpan timeSpan1 when format == SerializationFormat.Duration_Milliseconds => Convert.ToInt32(timeSpan1.TotalMilliseconds).ToString(CultureInfo.InvariantCulture), + TimeSpan timeSpan2 when format == SerializationFormat.Duration_Milliseconds_Float || format == SerializationFormat.Duration_Milliseconds_Double => timeSpan2.TotalMilliseconds.ToString(CultureInfo.InvariantCulture), + TimeSpan timeSpan3 when formatSpecifier != null => ToString(timeSpan3, formatSpecifier), + TimeSpan timeSpan4 => XmlConvert.ToString(timeSpan4), + Guid guid => guid.ToString(), + BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), + _ => value.ToString() + }; + } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/Utf8JsonRequestContent.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/Utf8JsonRequestContent.cs index db3ff7883e0c..16a4a9a2c409 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/Utf8JsonRequestContent.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -13,7 +13,7 @@ namespace Azure.Monitor.OpenTelemetry.Exporter { - internal class Utf8JsonRequestContent : RequestContent + internal partial class Utf8JsonRequestContent : RequestContent { private readonly MemoryStream _stream; private readonly RequestContent _content; @@ -25,20 +25,26 @@ public Utf8JsonRequestContent() JsonWriter = new Utf8JsonWriter(_stream); } + /// Gets the JsonWriter. public Utf8JsonWriter JsonWriter { get; } + /// The stream containing the data to be written. + /// The cancellation token to use. public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) { await JsonWriter.FlushAsync().ConfigureAwait(false); await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); } + /// The stream containing the data to be written. + /// The cancellation token to use. 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; diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/AvailabilityData.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/AvailabilityData.Serialization.cs index 17bfc7df6bd5..9068c9bf5aef 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/AvailabilityData.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/AvailabilityData.Serialization.cs @@ -5,16 +5,80 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class AvailabilityData : IUtf8JsonSerializable + internal partial class AvailabilityData : MonitorDomain, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal AvailabilityData() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected override MonitorDomain PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeAvailabilityData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AvailabilityData)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(AvailabilityData)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + AvailabilityData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (AvailabilityData)PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AvailabilityData)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); writer.WritePropertyName("name"u8); @@ -40,6 +104,11 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) foreach (var item in Properties) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); @@ -55,22 +124,135 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) } writer.WriteEndObject(); } - writer.WritePropertyName("ver"u8); - writer.WriteNumberValue(Version); - foreach (var item in AdditionalProperties) + } + + /// The JSON reader. + /// The client options for reading and writing models. + AvailabilityData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (AvailabilityData)JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected override MonitorDomain JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value); + throw new FormatException($"The model {nameof(AvailabilityData)} does not support reading '{format}' format."); } - writer.WriteEndObject(); + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAvailabilityData(document.RootElement, options); } - /// Convert into a . - internal override RequestContent ToRequestContent() + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static AvailabilityData DeserializeAvailabilityData(JsonElement element, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int version = default; + MonitorDomainKind kind = default; + IDictionary additionalProperties = new ChangeTrackingDictionary(); + string id = default; + string name = default; + string duration = default; + bool success = default; + string runLocation = default; + string message = default; + IDictionary properties = default; + IDictionary measurements = default; + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("ver"u8)) + { + version = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("kind"u8)) + { + kind = new MonitorDomainKind(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("id"u8)) + { + id = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("name"u8)) + { + name = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("duration"u8)) + { + duration = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("success"u8)) + { + success = prop.Value.GetBoolean(); + continue; + } + if (prop.NameEquals("runLocation"u8)) + { + runLocation = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("message"u8)) + { + message = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("properties"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + properties = dictionary; + continue; + } + if (prop.NameEquals("measurements"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + dictionary.Add(prop0.Name, prop0.Value.GetDouble()); + } + measurements = dictionary; + continue; + } + additionalProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + return new AvailabilityData( + version, + kind, + additionalProperties, + id, + name, + duration, + success, + runLocation, + message, + properties ?? new ChangeTrackingDictionary(), + measurements ?? new ChangeTrackingDictionary()); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/AvailabilityData.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/AvailabilityData.cs index 97d2840d6cd0..d35c0106d568 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/AvailabilityData.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/AvailabilityData.cs @@ -7,25 +7,23 @@ using System; using System.Collections.Generic; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// Instances of AvailabilityData represent the result of executing an availability test. internal partial class AvailabilityData : MonitorDomain { /// Initializes a new instance of . /// Schema version. - /// Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service. + /// + /// Identifier of a test run. Use it to correlate steps of test run and telemetry + /// generated by the service. + /// /// Name of the test that these availability results represent. /// Duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. /// Success flag. - /// , or is null. public AvailabilityData(int version, string id, string name, string duration, bool success) : base(version) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(name, nameof(name)); - Argument.AssertNotNull(duration, nameof(duration)); - Id = id; Name = name; Duration = duration; @@ -36,8 +34,12 @@ public AvailabilityData(int version, string id, string name, string duration, bo /// Initializes a new instance of . /// Schema version. - /// Additional Properties. - /// Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service. + /// Discriminator property to identify the specific telemetry data type. + /// + /// + /// Identifier of a test run. Use it to correlate steps of test run and telemetry + /// generated by the service. + /// /// Name of the test that these availability results represent. /// Duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. /// Success flag. @@ -45,7 +47,7 @@ public AvailabilityData(int version, string id, string name, string duration, bo /// Diagnostic message for the result. /// Collection of custom properties. /// Collection of custom measurements. - internal AvailabilityData(int version, IDictionary additionalProperties, string id, string name, string duration, bool success, string runLocation, string message, IDictionary properties, IDictionary measurements) : base(version, additionalProperties) + internal AvailabilityData(int version, MonitorDomainKind kind, IDictionary additionalProperties, string id, string name, string duration, bool success, string runLocation, string message, IDictionary properties, IDictionary measurements) : base(version, kind, additionalProperties) { Id = id; Name = name; @@ -57,20 +59,30 @@ internal AvailabilityData(int version, IDictionary additionalPro Measurements = measurements; } - /// Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service. - public string Id { get; } + /// + /// Identifier of a test run. Use it to correlate steps of test run and telemetry + /// generated by the service. + /// + public string Id { get; set; } + /// Name of the test that these availability results represent. - public string Name { get; } + public string Name { get; set; } + /// Duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. - public string Duration { get; } + public string Duration { get; set; } + /// Success flag. - public bool Success { get; } + public bool Success { get; set; } + /// Name of the location where the test was run from. public string RunLocation { get; set; } + /// Diagnostic message for the result. public string Message { get; set; } + /// Collection of custom properties. public IDictionary Properties { get; } + /// Collection of custom measurements. public IDictionary Measurements { get; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/AzureMonitorOpenTelemetryExporterContext.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/AzureMonitorOpenTelemetryExporterContext.cs new file mode 100644 index 000000000000..0e199f2786a2 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/AzureMonitorOpenTelemetryExporterContext.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.ClientModel.Primitives; +using Azure.Monitor.OpenTelemetry.Exporter.Models; + +namespace Azure.Monitor.OpenTelemetry.Exporter +{ + /// + /// Context class which will be filled in by the System.ClientModel.SourceGeneration. + /// For more information + /// + [ModelReaderWriterBuildable(typeof(AvailabilityData))] + [ModelReaderWriterBuildable(typeof(MessageData))] + [ModelReaderWriterBuildable(typeof(MetricDataPoint))] + [ModelReaderWriterBuildable(typeof(MetricsData))] + [ModelReaderWriterBuildable(typeof(MonitorBase))] + [ModelReaderWriterBuildable(typeof(MonitorDomain))] + [ModelReaderWriterBuildable(typeof(PageViewData))] + [ModelReaderWriterBuildable(typeof(PageViewPerfData))] + [ModelReaderWriterBuildable(typeof(RemoteDependencyData))] + [ModelReaderWriterBuildable(typeof(RequestData))] + [ModelReaderWriterBuildable(typeof(StackFrame))] + [ModelReaderWriterBuildable(typeof(TelemetryErrorDetails))] + [ModelReaderWriterBuildable(typeof(TelemetryEventData))] + [ModelReaderWriterBuildable(typeof(TelemetryExceptionData))] + [ModelReaderWriterBuildable(typeof(TelemetryExceptionDetails))] + [ModelReaderWriterBuildable(typeof(TelemetryItem))] + [ModelReaderWriterBuildable(typeof(TrackResponse))] + [ModelReaderWriterBuildable(typeof(UnknownMonitorDomain))] + public partial class AzureMonitorOpenTelemetryExporterContext : ModelReaderWriterContext + { + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/ContextTagKeys.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/ContextTagKeys.cs index 5289fca63529..82e54626c1a8 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/ContextTagKeys.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/ContextTagKeys.cs @@ -10,120 +10,187 @@ namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// The context tag keys. internal readonly partial struct ContextTagKeys : IEquatable { private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ContextTagKeys(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - + /// Application version. private const string AiApplicationVerValue = "ai.application.ver"; + /// Device ID. private const string AiDeviceIdValue = "ai.device.id"; + /// Device locale. private const string AiDeviceLocaleValue = "ai.device.locale"; + /// Device model. private const string AiDeviceModelValue = "ai.device.model"; + /// Device OEM name. private const string AiDeviceOemNameValue = "ai.device.oemName"; - private const string AiDeviceOsVersionValue = "ai.device.osVersion"; + /// Device OS version. + private const string AiDeviceOSVersionValue = "ai.device.osVersion"; + /// Device type. private const string AiDeviceTypeValue = "ai.device.type"; + /// Location IP. private const string AiLocationIpValue = "ai.location.ip"; + /// Location country. private const string AiLocationCountryValue = "ai.location.country"; + /// Location province. private const string AiLocationProvinceValue = "ai.location.province"; + /// Location city. private const string AiLocationCityValue = "ai.location.city"; + /// Operation ID. private const string AiOperationIdValue = "ai.operation.id"; + /// Operation name. private const string AiOperationNameValue = "ai.operation.name"; + /// Operation parent ID. private const string AiOperationParentIdValue = "ai.operation.parentId"; + /// Operation synthetic source. private const string AiOperationSyntheticSourceValue = "ai.operation.syntheticSource"; + /// Operation correlation vector. private const string AiOperationCorrelationVectorValue = "ai.operation.correlationVector"; + /// Session ID. private const string AiSessionIdValue = "ai.session.id"; + /// If session is the first one. private const string AiSessionIsFirstValue = "ai.session.isFirst"; + /// User account ID. private const string AiUserAccountIdValue = "ai.user.accountId"; + /// User ID. private const string AiUserIdValue = "ai.user.id"; + /// Authenticated user ID. private const string AiUserAuthUserIdValue = "ai.user.authUserId"; + /// Cloud role. private const string AiCloudRoleValue = "ai.cloud.role"; + /// Cloud role version. private const string AiCloudRoleVerValue = "ai.cloud.roleVer"; + /// Cloud role instance. private const string AiCloudRoleInstanceValue = "ai.cloud.roleInstance"; + /// Cloud location. private const string AiCloudLocationValue = "ai.cloud.location"; + /// Internal SDK version. private const string AiInternalSdkVersionValue = "ai.internal.sdkVersion"; + /// Internal agent version. private const string AiInternalAgentVersionValue = "ai.internal.agentVersion"; + /// Internal node name. private const string AiInternalNodeNameValue = "ai.internal.nodeName"; - /// ai.application.ver. + /// Initializes a new instance of . + /// The value. + public ContextTagKeys(string value) + { + _value = value; + } + + /// Application version. public static ContextTagKeys AiApplicationVer { get; } = new ContextTagKeys(AiApplicationVerValue); - /// ai.device.id. + + /// Device ID. public static ContextTagKeys AiDeviceId { get; } = new ContextTagKeys(AiDeviceIdValue); - /// ai.device.locale. + + /// Device locale. public static ContextTagKeys AiDeviceLocale { get; } = new ContextTagKeys(AiDeviceLocaleValue); - /// ai.device.model. + + /// Device model. public static ContextTagKeys AiDeviceModel { get; } = new ContextTagKeys(AiDeviceModelValue); - /// ai.device.oemName. + + /// Device OEM name. public static ContextTagKeys AiDeviceOemName { get; } = new ContextTagKeys(AiDeviceOemNameValue); - /// ai.device.osVersion. - public static ContextTagKeys AiDeviceOsVersion { get; } = new ContextTagKeys(AiDeviceOsVersionValue); - /// ai.device.type. + + /// Device OS version. + public static ContextTagKeys AiDeviceOSVersion { get; } = new ContextTagKeys(AiDeviceOSVersionValue); + + /// Device type. public static ContextTagKeys AiDeviceType { get; } = new ContextTagKeys(AiDeviceTypeValue); - /// ai.location.ip. + + /// Location IP. public static ContextTagKeys AiLocationIp { get; } = new ContextTagKeys(AiLocationIpValue); - /// ai.location.country. + + /// Location country. public static ContextTagKeys AiLocationCountry { get; } = new ContextTagKeys(AiLocationCountryValue); - /// ai.location.province. + + /// Location province. public static ContextTagKeys AiLocationProvince { get; } = new ContextTagKeys(AiLocationProvinceValue); - /// ai.location.city. + + /// Location city. public static ContextTagKeys AiLocationCity { get; } = new ContextTagKeys(AiLocationCityValue); - /// ai.operation.id. + + /// Operation ID. public static ContextTagKeys AiOperationId { get; } = new ContextTagKeys(AiOperationIdValue); - /// ai.operation.name. + + /// Operation name. public static ContextTagKeys AiOperationName { get; } = new ContextTagKeys(AiOperationNameValue); - /// ai.operation.parentId. + + /// Operation parent ID. public static ContextTagKeys AiOperationParentId { get; } = new ContextTagKeys(AiOperationParentIdValue); - /// ai.operation.syntheticSource. + + /// Operation synthetic source. public static ContextTagKeys AiOperationSyntheticSource { get; } = new ContextTagKeys(AiOperationSyntheticSourceValue); - /// ai.operation.correlationVector. + + /// Operation correlation vector. public static ContextTagKeys AiOperationCorrelationVector { get; } = new ContextTagKeys(AiOperationCorrelationVectorValue); - /// ai.session.id. + + /// Session ID. public static ContextTagKeys AiSessionId { get; } = new ContextTagKeys(AiSessionIdValue); - /// ai.session.isFirst. + + /// If session is the first one. public static ContextTagKeys AiSessionIsFirst { get; } = new ContextTagKeys(AiSessionIsFirstValue); - /// ai.user.accountId. + + /// User account ID. public static ContextTagKeys AiUserAccountId { get; } = new ContextTagKeys(AiUserAccountIdValue); - /// ai.user.id. + + /// User ID. public static ContextTagKeys AiUserId { get; } = new ContextTagKeys(AiUserIdValue); - /// ai.user.authUserId. + + /// Authenticated user ID. public static ContextTagKeys AiUserAuthUserId { get; } = new ContextTagKeys(AiUserAuthUserIdValue); - /// ai.cloud.role. + + /// Cloud role. public static ContextTagKeys AiCloudRole { get; } = new ContextTagKeys(AiCloudRoleValue); - /// ai.cloud.roleVer. + + /// Cloud role version. public static ContextTagKeys AiCloudRoleVer { get; } = new ContextTagKeys(AiCloudRoleVerValue); - /// ai.cloud.roleInstance. + + /// Cloud role instance. public static ContextTagKeys AiCloudRoleInstance { get; } = new ContextTagKeys(AiCloudRoleInstanceValue); - /// ai.cloud.location. + + /// Cloud location. public static ContextTagKeys AiCloudLocation { get; } = new ContextTagKeys(AiCloudLocationValue); - /// ai.internal.sdkVersion. + + /// Internal SDK version. public static ContextTagKeys AiInternalSdkVersion { get; } = new ContextTagKeys(AiInternalSdkVersionValue); - /// ai.internal.agentVersion. + + /// Internal agent version. public static ContextTagKeys AiInternalAgentVersion { get; } = new ContextTagKeys(AiInternalAgentVersionValue); - /// ai.internal.nodeName. + + /// Internal node name. public static ContextTagKeys AiInternalNodeName { get; } = new ContextTagKeys(AiInternalNodeNameValue); + /// Determines if two values are the same. + /// The left value to compare. + /// The right value to compare. public static bool operator ==(ContextTagKeys left, ContextTagKeys right) => left.Equals(right); + /// Determines if two values are not the same. + /// The left value to compare. + /// The right value to compare. public static bool operator !=(ContextTagKeys left, ContextTagKeys right) => !left.Equals(right); - /// Converts a to a . + + /// Converts a string to a . + /// The value. public static implicit operator ContextTagKeys(string value) => new ContextTagKeys(value); - /// + /// Converts a string to a . + /// The value. + public static implicit operator ContextTagKeys?(string value) => value == null ? null : new ContextTagKeys(value); + + /// [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is ContextTagKeys other && Equals(other); - /// + + /// public bool Equals(ContextTagKeys other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - /// + /// [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// + + /// public override string ToString() => _value; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/DataPointType.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/DataPointType.cs index 79406b62d178..ca14bdb5b4a2 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/DataPointType.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/DataPointType.cs @@ -10,42 +10,57 @@ namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// Type of the metric data measurement. internal readonly partial struct DataPointType : IEquatable { private readonly string _value; + /// Single measurement. + private const string MeasurementValue = "Measurement"; + /// Aggregated value. + private const string AggregationValue = "Aggregation"; /// Initializes a new instance of . - /// is null. + /// The value. public DataPointType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); + _value = value; } - private const string MeasurementValue = "Measurement"; - private const string AggregationValue = "Aggregation"; - - /// Measurement. + /// Single measurement. public static DataPointType Measurement { get; } = new DataPointType(MeasurementValue); - /// Aggregation. + + /// Aggregated value. public static DataPointType Aggregation { get; } = new DataPointType(AggregationValue); + /// Determines if two values are the same. + /// The left value to compare. + /// The right value to compare. public static bool operator ==(DataPointType left, DataPointType right) => left.Equals(right); + /// Determines if two values are not the same. + /// The left value to compare. + /// The right value to compare. public static bool operator !=(DataPointType left, DataPointType right) => !left.Equals(right); - /// Converts a to a . + + /// Converts a string to a . + /// The value. public static implicit operator DataPointType(string value) => new DataPointType(value); - /// + /// Converts a string to a . + /// The value. + public static implicit operator DataPointType?(string value) => value == null ? null : new DataPointType(value); + + /// [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is DataPointType other && Equals(other); - /// + + /// public bool Equals(DataPointType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - /// + /// [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// + + /// public override string ToString() => _value; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MessageData.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MessageData.Serialization.cs index 3992de463406..cbd524c22a3f 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MessageData.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MessageData.Serialization.cs @@ -5,16 +5,80 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class MessageData : IUtf8JsonSerializable + internal partial class MessageData : MonitorDomain, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal MessageData() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected override MonitorDomain PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeMessageData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageData)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(MessageData)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + MessageData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (MessageData)PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageData)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); writer.WritePropertyName("message"u8); writer.WriteStringValue(Message); if (Optional.IsDefined(SeverityLevel)) @@ -29,6 +93,11 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) foreach (var item in Properties) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); @@ -44,22 +113,111 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) } writer.WriteEndObject(); } - writer.WritePropertyName("ver"u8); - writer.WriteNumberValue(Version); - foreach (var item in AdditionalProperties) + } + + /// The JSON reader. + /// The client options for reading and writing models. + MessageData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (MessageData)JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected override MonitorDomain JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value); + throw new FormatException($"The model {nameof(MessageData)} does not support reading '{format}' format."); } - writer.WriteEndObject(); + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageData(document.RootElement, options); } - /// Convert into a . - internal override RequestContent ToRequestContent() + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static MessageData DeserializeMessageData(JsonElement element, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int version = default; + MonitorDomainKind kind = default; + IDictionary additionalProperties = new ChangeTrackingDictionary(); + string message = default; + SeverityLevel? severityLevel = default; + IDictionary properties = default; + IDictionary measurements = default; + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("ver"u8)) + { + version = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("kind"u8)) + { + kind = new MonitorDomainKind(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("message"u8)) + { + message = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("severityLevel"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + severityLevel = new SeverityLevel(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("properties"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + properties = dictionary; + continue; + } + if (prop.NameEquals("measurements"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + dictionary.Add(prop0.Name, prop0.Value.GetDouble()); + } + measurements = dictionary; + continue; + } + additionalProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + return new MessageData( + version, + kind, + additionalProperties, + message, + severityLevel, + properties ?? new ChangeTrackingDictionary(), + measurements ?? new ChangeTrackingDictionary()); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MessageData.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MessageData.cs index 044a8ffefdac..38eeaa46515c 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MessageData.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MessageData.cs @@ -7,20 +7,17 @@ using System; using System.Collections.Generic; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// Instances of Message represent printf-like trace statements that are text-searched. Log4Net, NLog and other text-based log file entries are translated into instances of this type. The message does not have measurements. internal partial class MessageData : MonitorDomain { /// Initializes a new instance of . /// Schema version. /// Trace message. - /// is null. public MessageData(int version, string message) : base(version) { - Argument.AssertNotNull(message, nameof(message)); - Message = message; Properties = new ChangeTrackingDictionary(); Measurements = new ChangeTrackingDictionary(); @@ -28,12 +25,13 @@ public MessageData(int version, string message) : base(version) /// Initializes a new instance of . /// Schema version. - /// Additional Properties. + /// Discriminator property to identify the specific telemetry data type. + /// /// Trace message. /// Trace severity level. /// Collection of custom properties. /// Collection of custom measurements. - internal MessageData(int version, IDictionary additionalProperties, string message, SeverityLevel? severityLevel, IDictionary properties, IDictionary measurements) : base(version, additionalProperties) + internal MessageData(int version, MonitorDomainKind kind, IDictionary additionalProperties, string message, SeverityLevel? severityLevel, IDictionary properties, IDictionary measurements) : base(version, kind, additionalProperties) { Message = message; SeverityLevel = severityLevel; @@ -42,11 +40,14 @@ internal MessageData(int version, IDictionary additionalProperti } /// Trace message. - public string Message { get; } + public string Message { get; set; } + /// Trace severity level. public SeverityLevel? SeverityLevel { get; set; } + /// Collection of custom properties. public IDictionary Properties { get; } + /// Collection of custom measurements. public IDictionary Measurements { get; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricDataPoint.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricDataPoint.Serialization.cs index 8efbeb519bdd..ab8cc13da57a 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricDataPoint.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricDataPoint.Serialization.cs @@ -5,16 +5,79 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class MetricDataPoint : IUtf8JsonSerializable + internal partial class MetricDataPoint : IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal MetricDataPoint() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected virtual MetricDataPoint PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeMetricDataPoint(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MetricDataPoint)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(MetricDataPoint)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + MetricDataPoint IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MetricDataPoint)} does not support writing '{format}' format."); + } if (Optional.IsDefined(Namespace)) { writer.WritePropertyName("ns"u8); @@ -31,61 +94,152 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) writer.WriteNumberValue(Value); if (Optional.IsDefined(Count)) { - if (Count != null) - { - writer.WritePropertyName("count"u8); - writer.WriteNumberValue(Count.Value); - } - else + writer.WritePropertyName("count"u8); + writer.WriteNumberValue(Count.Value); + } + if (Optional.IsDefined(Min)) + { + writer.WritePropertyName("min"u8); + writer.WriteNumberValue(Min.Value); + } + if (Optional.IsDefined(Max)) + { + writer.WritePropertyName("max"u8); + writer.WriteNumberValue(Max.Value); + } + if (Optional.IsDefined(StdDev)) + { + writer.WritePropertyName("stdDev"u8); + writer.WriteNumberValue(StdDev.Value); + } + if (options.Format != "W" && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { - writer.WriteNull("count"); + 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 } } - if (Optional.IsDefined(Min)) + } + + /// The JSON reader. + /// The client options for reading and writing models. + MetricDataPoint IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected virtual MetricDataPoint JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") { - if (Min != null) + throw new FormatException($"The model {nameof(MetricDataPoint)} does not support reading '{format}' format."); + } + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMetricDataPoint(document.RootElement, options); + } + + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static MetricDataPoint DeserializeMetricDataPoint(JsonElement element, ModelReaderWriterOptions options) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string @namespace = default; + string name = default; + DataPointType? dataPointType = default; + double value = default; + int? count = default; + double? min = default; + double? max = default; + double? stdDev = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("ns"u8)) { - writer.WritePropertyName("min"u8); - writer.WriteNumberValue(Min.Value); + @namespace = prop.Value.GetString(); + continue; } - else + if (prop.NameEquals("name"u8)) { - writer.WriteNull("min"); + name = prop.Value.GetString(); + continue; } - } - if (Optional.IsDefined(Max)) - { - if (Max != null) + if (prop.NameEquals("kind"u8)) { - writer.WritePropertyName("max"u8); - writer.WriteNumberValue(Max.Value); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + dataPointType = new DataPointType(prop.Value.GetString()); + continue; } - else + if (prop.NameEquals("value"u8)) { - writer.WriteNull("max"); + value = prop.Value.GetDouble(); + continue; } - } - if (Optional.IsDefined(StdDev)) - { - if (StdDev != null) + if (prop.NameEquals("count"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + count = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("min"u8)) { - writer.WritePropertyName("stdDev"u8); - writer.WriteNumberValue(StdDev.Value); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + min = prop.Value.GetDouble(); + continue; } - else + if (prop.NameEquals("max"u8)) { - writer.WriteNull("stdDev"); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + max = prop.Value.GetDouble(); + continue; + } + if (prop.NameEquals("stdDev"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + stdDev = prop.Value.GetDouble(); + continue; + } + if (options.Format != "W") + { + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - writer.WriteEndObject(); - } - - /// Convert into a . - internal virtual RequestContent ToRequestContent() - { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + return new MetricDataPoint( + @namespace, + name, + dataPointType, + value, + count, + min, + max, + stdDev, + additionalBinaryDataProperties); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricDataPoint.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricDataPoint.cs index 8cc10543136a..7bf878b4b712 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricDataPoint.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricDataPoint.cs @@ -6,20 +6,23 @@ #nullable disable using System; +using System.Collections.Generic; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// Metric data single measurement. internal partial class MetricDataPoint { + /// Keeps track of any properties unknown to the library. + private protected readonly IDictionary _additionalBinaryDataProperties; + /// Initializes a new instance of . /// Name of the metric. - /// Single value for measurement. Sum of individual measurements for the aggregation. - /// is null. + /// + /// Single value for measurement. Sum of individual measurements for the + /// aggregation. + /// public MetricDataPoint(string name, double value) { - Argument.AssertNotNull(name, nameof(name)); - Name = name; Value = value; } @@ -28,12 +31,19 @@ public MetricDataPoint(string name, double value) /// Namespace of the metric. /// Name of the metric. /// Metric type. Single measurement or the aggregated value. - /// Single value for measurement. Sum of individual measurements for the aggregation. + /// + /// Single value for measurement. Sum of individual measurements for the + /// aggregation. + /// /// Metric weight of the aggregated metric. Should not be set for a measurement. /// Minimum value of the aggregated metric. Should not be set for a measurement. /// Maximum value of the aggregated metric. Should not be set for a measurement. - /// Standard deviation of the aggregated metric. Should not be set for a measurement. - internal MetricDataPoint(string @namespace, string name, DataPointType? dataPointType, double value, int? count, double? min, double? max, double? stdDev) + /// + /// Standard deviation of the aggregated metric. Should not be set for a + /// measurement. + /// + /// Keeps track of any properties unknown to the library. + internal MetricDataPoint(string @namespace, string name, DataPointType? dataPointType, double value, int? count, double? min, double? max, double? stdDev, IDictionary additionalBinaryDataProperties) { Namespace = @namespace; Name = name; @@ -43,23 +53,37 @@ internal MetricDataPoint(string @namespace, string name, DataPointType? dataPoin Min = min; Max = max; StdDev = stdDev; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } /// Namespace of the metric. public string Namespace { get; set; } + /// Name of the metric. - public string Name { get; } + public string Name { get; set; } + /// Metric type. Single measurement or the aggregated value. public DataPointType? DataPointType { get; set; } - /// Single value for measurement. Sum of individual measurements for the aggregation. - public double Value { get; } + + /// + /// Single value for measurement. Sum of individual measurements for the + /// aggregation. + /// + public double Value { get; set; } + /// Metric weight of the aggregated metric. Should not be set for a measurement. public int? Count { get; set; } + /// Minimum value of the aggregated metric. Should not be set for a measurement. public double? Min { get; set; } + /// Maximum value of the aggregated metric. Should not be set for a measurement. public double? Max { get; set; } - /// Standard deviation of the aggregated metric. Should not be set for a measurement. + + /// + /// Standard deviation of the aggregated metric. Should not be set for a + /// measurement. + /// public double? StdDev { get; set; } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricsData.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricsData.Serialization.cs index 8ae9d2f0f93d..4426d66fe2d3 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricsData.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricsData.Serialization.cs @@ -5,21 +5,85 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class MetricsData : IUtf8JsonSerializable + internal partial class MetricsData : MonitorDomain, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal MetricsData() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected override MonitorDomain PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeMetricsData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MetricsData)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(MetricsData)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + MetricsData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (MetricsData)PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MetricsData)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); writer.WritePropertyName("metrics"u8); writer.WriteStartArray(); - foreach (var item in Metrics) + foreach (MetricDataPoint item in Metrics) { - writer.WriteObjectValue(item); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); if (Optional.IsCollectionDefined(Properties)) @@ -29,26 +93,93 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) foreach (var item in Properties) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } - writer.WritePropertyName("ver"u8); - writer.WriteNumberValue(Version); - foreach (var item in AdditionalProperties) + } + + /// The JSON reader. + /// The client options for reading and writing models. + MetricsData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (MetricsData)JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected override MonitorDomain JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value); + throw new FormatException($"The model {nameof(MetricsData)} does not support reading '{format}' format."); } - writer.WriteEndObject(); + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMetricsData(document.RootElement, options); } - /// Convert into a . - internal override RequestContent ToRequestContent() + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static MetricsData DeserializeMetricsData(JsonElement element, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int version = default; + MonitorDomainKind kind = default; + IDictionary additionalProperties = new ChangeTrackingDictionary(); + IList metrics = default; + IDictionary properties = default; + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("ver"u8)) + { + version = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("kind"u8)) + { + kind = new MonitorDomainKind(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("metrics"u8)) + { + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(MetricDataPoint.DeserializeMetricDataPoint(item, options)); + } + metrics = array; + continue; + } + if (prop.NameEquals("properties"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + properties = dictionary; + continue; + } + additionalProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + return new MetricsData(version, kind, additionalProperties, metrics, properties ?? new ChangeTrackingDictionary()); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricsData.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricsData.cs index 2e91a4b7ab34..cc74c4698322 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricsData.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MetricsData.cs @@ -8,37 +8,48 @@ using System; using System.Collections.Generic; using System.Linq; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// An instance of the Metric item is a list of measurements (single data points) and/or aggregations. internal partial class MetricsData : MonitorDomain { /// Initializes a new instance of . /// Schema version. - /// List of metrics. Only one metric in the list is currently supported by Application Insights storage. If multiple data points were sent only the first one will be used. - /// is null. + /// + /// List of metrics. Only one metric in the list is currently supported by + /// Application Insights storage. If multiple data points were sent only the first + /// one will be used. + /// public MetricsData(int version, IEnumerable metrics) : base(version) { - Argument.AssertNotNull(metrics, nameof(metrics)); - Metrics = metrics.ToList(); Properties = new ChangeTrackingDictionary(); } /// Initializes a new instance of . /// Schema version. - /// Additional Properties. - /// List of metrics. Only one metric in the list is currently supported by Application Insights storage. If multiple data points were sent only the first one will be used. + /// Discriminator property to identify the specific telemetry data type. + /// + /// + /// List of metrics. Only one metric in the list is currently supported by + /// Application Insights storage. If multiple data points were sent only the first + /// one will be used. + /// /// Collection of custom properties. - internal MetricsData(int version, IDictionary additionalProperties, IList metrics, IDictionary properties) : base(version, additionalProperties) + internal MetricsData(int version, MonitorDomainKind kind, IDictionary additionalProperties, IList metrics, IDictionary properties) : base(version, kind, additionalProperties) { Metrics = metrics; Properties = properties; } - /// List of metrics. Only one metric in the list is currently supported by Application Insights storage. If multiple data points were sent only the first one will be used. + /// + /// List of metrics. Only one metric in the list is currently supported by + /// Application Insights storage. If multiple data points were sent only the first + /// one will be used. + /// public IList Metrics { get; } + /// Collection of custom properties. public IDictionary Properties { get; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorBase.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorBase.Serialization.cs index 16283ba3de2d..c782e9736b6c 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorBase.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorBase.Serialization.cs @@ -5,16 +5,74 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class MonitorBase : IUtf8JsonSerializable + internal partial class MonitorBase : IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// The data to parse. + /// The client options for reading and writing models. + protected virtual MonitorBase PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeMonitorBase(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MonitorBase)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(MonitorBase)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + MonitorBase IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MonitorBase)} does not support writing '{format}' format."); + } if (Optional.IsDefined(BaseType)) { writer.WritePropertyName("baseType"u8); @@ -23,17 +81,75 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) if (Optional.IsDefined(BaseData)) { writer.WritePropertyName("baseData"u8); - writer.WriteObjectValue(BaseData); + writer.WriteObjectValue(BaseData, options); } - writer.WriteEndObject(); + if (options.Format != "W" && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + 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 + } + } + } + + /// The JSON reader. + /// The client options for reading and writing models. + MonitorBase IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected virtual MonitorBase JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MonitorBase)} does not support reading '{format}' format."); + } + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMonitorBase(document.RootElement, options); } - /// Convert into a . - internal virtual RequestContent ToRequestContent() + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static MonitorBase DeserializeMonitorBase(JsonElement element, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string baseType = default; + MonitorDomain baseData = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("baseType"u8)) + { + baseType = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("baseData"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + baseData = MonitorDomain.DeserializeMonitorDomain(prop.Value, options); + continue; + } + if (options.Format != "W") + { + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + } + return new MonitorBase(baseType, baseData, additionalBinaryDataProperties); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorBase.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorBase.cs index e968b748036e..12809fac1649 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorBase.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorBase.cs @@ -5,27 +5,41 @@ #nullable disable +using System; +using System.Collections.Generic; + namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// Data struct to contain only C section with custom fields. internal partial class MonitorBase { + /// Keeps track of any properties unknown to the library. + private protected readonly IDictionary _additionalBinaryDataProperties; + /// Initializes a new instance of . public MonitorBase() { } /// Initializes a new instance of . - /// Name of item (B section) if any. If telemetry data is derived straight from this, this should be null. + /// + /// Name of item (B section) if any. If telemetry data is derived straight from + /// this, this should be null. + /// /// The data payload for the telemetry request. - internal MonitorBase(string baseType, MonitorDomain baseData) + /// Keeps track of any properties unknown to the library. + internal MonitorBase(string baseType, MonitorDomain baseData, IDictionary additionalBinaryDataProperties) { BaseType = baseType; BaseData = baseData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - /// Name of item (B section) if any. If telemetry data is derived straight from this, this should be null. + /// + /// Name of item (B section) if any. If telemetry data is derived straight from + /// this, this should be null. + /// public string BaseType { get; set; } + /// The data payload for the telemetry request. public MonitorDomain BaseData { get; set; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorDomain.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorDomain.Serialization.cs index 6085bacb0298..237abe5dc8f0 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorDomain.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorDomain.Serialization.cs @@ -5,32 +5,150 @@ #nullable disable +using System; +using System.ClientModel.Primitives; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class MonitorDomain : IUtf8JsonSerializable + [PersistableModelProxy(typeof(UnknownMonitorDomain))] + internal abstract partial class MonitorDomain : IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal MonitorDomain() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected virtual MonitorDomain PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeMonitorDomain(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MonitorDomain)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(MonitorDomain)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + MonitorDomain IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MonitorDomain)} does not support writing '{format}' format."); + } writer.WritePropertyName("ver"u8); writer.WriteNumberValue(Version); + if (options.Format != "W") + { + writer.WritePropertyName("kind"u8); + writer.WriteStringValue(Kind.ToString()); + } foreach (var item in AdditionalProperties) { writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value); +#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(); } - /// Convert into a . - internal virtual RequestContent ToRequestContent() + /// The JSON reader. + /// The client options for reading and writing models. + MonitorDomain IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected virtual MonitorDomain JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MonitorDomain)} does not support reading '{format}' format."); + } + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMonitorDomain(document.RootElement, options); + } + + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static MonitorDomain DeserializeMonitorDomain(JsonElement element, ModelReaderWriterOptions options) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("kind"u8, out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "AvailabilityData": + return AvailabilityData.DeserializeAvailabilityData(element, options); + case "EventData": + return TelemetryEventData.DeserializeTelemetryEventData(element, options); + case "ExceptionData": + return TelemetryExceptionData.DeserializeTelemetryExceptionData(element, options); + case "MessageData": + return MessageData.DeserializeMessageData(element, options); + case "MetricsData": + return MetricsData.DeserializeMetricsData(element, options); + case "PageViewData": + return PageViewData.DeserializePageViewData(element, options); + case "PageViewPerfData": + return PageViewPerfData.DeserializePageViewPerfData(element, options); + case "RemoteDependencyData": + return RemoteDependencyData.DeserializeRemoteDependencyData(element, options); + case "RequestData": + return RequestData.DeserializeRequestData(element, options); + } + } + return UnknownMonitorDomain.DeserializeUnknownMonitorDomain(element, options); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorDomain.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorDomain.cs index 715477a3e7cc..0865eac9fbd5 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorDomain.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorDomain.cs @@ -5,33 +5,43 @@ #nullable disable +using System; using System.Collections.Generic; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// The abstract common base of all domains. - internal partial class MonitorDomain + internal abstract partial class MonitorDomain { + /// Keeps track of any properties unknown to the library. + private protected readonly IDictionary _additionalBinaryDataProperties; + /// Initializes a new instance of . /// Schema version. - public MonitorDomain(int version) + private protected MonitorDomain(int version) { Version = version; - AdditionalProperties = new ChangeTrackingDictionary(); + _additionalBinaryDataProperties = new ChangeTrackingDictionary(); } /// Initializes a new instance of . /// Schema version. - /// Additional Properties. - internal MonitorDomain(int version, IDictionary additionalProperties) + /// Discriminator property to identify the specific telemetry data type. + /// + internal MonitorDomain(int version, MonitorDomainKind kind, IDictionary additionalProperties) { Version = version; - AdditionalProperties = additionalProperties; + Kind = kind; + _additionalBinaryDataProperties = additionalProperties; } /// Schema version. - public int Version { get; } - /// Additional Properties. - public IDictionary AdditionalProperties { get; } + public int Version { get; set; } + + /// Discriminator property to identify the specific telemetry data type. + internal MonitorDomainKind Kind { get; set; } + + /// Gets the AdditionalProperties. + public IDictionary AdditionalProperties => _additionalBinaryDataProperties; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorDomainKind.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorDomainKind.cs new file mode 100644 index 000000000000..25ee81660952 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/MonitorDomainKind.cs @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Monitor.OpenTelemetry.Exporter.Models +{ + internal readonly partial struct MonitorDomainKind : IEquatable + { + private readonly string _value; + /// AvailabilityData type. + private const string AvailabilityDataValue = "AvailabilityData"; + /// EventData type. + private const string EventDataValue = "EventData"; + /// ExceptionData type. + private const string ExceptionDataValue = "ExceptionData"; + /// MessageData type. + private const string MessageDataValue = "MessageData"; + /// MetricsData type. + private const string MetricsDataValue = "MetricsData"; + /// PageViewData type. + private const string PageViewDataValue = "PageViewData"; + /// PageViewPerfData type. + private const string PageViewPerfDataValue = "PageViewPerfData"; + /// RemoteDependencyData type. + private const string RemoteDependencyDataValue = "RemoteDependencyData"; + /// RequestData type. + private const string RequestDataValue = "RequestData"; + + /// Initializes a new instance of . + /// The value. + public MonitorDomainKind(string value) + { + _value = value; + } + + /// AvailabilityData type. + public static MonitorDomainKind AvailabilityData { get; } = new MonitorDomainKind(AvailabilityDataValue); + + /// EventData type. + public static MonitorDomainKind EventData { get; } = new MonitorDomainKind(EventDataValue); + + /// ExceptionData type. + public static MonitorDomainKind ExceptionData { get; } = new MonitorDomainKind(ExceptionDataValue); + + /// MessageData type. + public static MonitorDomainKind MessageData { get; } = new MonitorDomainKind(MessageDataValue); + + /// MetricsData type. + public static MonitorDomainKind MetricsData { get; } = new MonitorDomainKind(MetricsDataValue); + + /// PageViewData type. + public static MonitorDomainKind PageViewData { get; } = new MonitorDomainKind(PageViewDataValue); + + /// PageViewPerfData type. + public static MonitorDomainKind PageViewPerfData { get; } = new MonitorDomainKind(PageViewPerfDataValue); + + /// RemoteDependencyData type. + public static MonitorDomainKind RemoteDependencyData { get; } = new MonitorDomainKind(RemoteDependencyDataValue); + + /// RequestData type. + public static MonitorDomainKind RequestData { get; } = new MonitorDomainKind(RequestDataValue); + + /// Determines if two values are the same. + /// The left value to compare. + /// The right value to compare. + public static bool operator ==(MonitorDomainKind left, MonitorDomainKind right) => left.Equals(right); + + /// Determines if two values are not the same. + /// The left value to compare. + /// The right value to compare. + public static bool operator !=(MonitorDomainKind left, MonitorDomainKind right) => !left.Equals(right); + + /// Converts a string to a . + /// The value. + public static implicit operator MonitorDomainKind(string value) => new MonitorDomainKind(value); + + /// Converts a string to a . + /// The value. + public static implicit operator MonitorDomainKind?(string value) => value == null ? null : new MonitorDomainKind(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is MonitorDomainKind other && Equals(other); + + /// + public bool Equals(MonitorDomainKind other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + + /// + public override string ToString() => _value; + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewData.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewData.Serialization.cs index fe91b1273064..bea5254e7894 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewData.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewData.Serialization.cs @@ -5,16 +5,80 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class PageViewData : IUtf8JsonSerializable + internal partial class PageViewData : MonitorDomain, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal PageViewData() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected override MonitorDomain PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializePageViewData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PageViewData)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(PageViewData)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + PageViewData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (PageViewData)PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PageViewData)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); writer.WritePropertyName("name"u8); @@ -41,6 +105,11 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) foreach (var item in Properties) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); @@ -56,22 +125,128 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) } writer.WriteEndObject(); } - writer.WritePropertyName("ver"u8); - writer.WriteNumberValue(Version); - foreach (var item in AdditionalProperties) + } + + /// The JSON reader. + /// The client options for reading and writing models. + PageViewData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (PageViewData)JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected override MonitorDomain JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value); + throw new FormatException($"The model {nameof(PageViewData)} does not support reading '{format}' format."); } - writer.WriteEndObject(); + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePageViewData(document.RootElement, options); } - /// Convert into a . - internal override RequestContent ToRequestContent() + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static PageViewData DeserializePageViewData(JsonElement element, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int version = default; + MonitorDomainKind kind = default; + IDictionary additionalProperties = new ChangeTrackingDictionary(); + string id = default; + string name = default; + string url = default; + string duration = default; + string referredUri = default; + IDictionary properties = default; + IDictionary measurements = default; + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("ver"u8)) + { + version = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("kind"u8)) + { + kind = new MonitorDomainKind(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("id"u8)) + { + id = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("name"u8)) + { + name = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("url"u8)) + { + url = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("duration"u8)) + { + duration = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("referredUri"u8)) + { + referredUri = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("properties"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + properties = dictionary; + continue; + } + if (prop.NameEquals("measurements"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + dictionary.Add(prop0.Name, prop0.Value.GetDouble()); + } + measurements = dictionary; + continue; + } + additionalProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + return new PageViewData( + version, + kind, + additionalProperties, + id, + name, + url, + duration, + referredUri, + properties ?? new ChangeTrackingDictionary(), + measurements ?? new ChangeTrackingDictionary()); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewData.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewData.cs index 80e52fe11920..d133b3b54fcc 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewData.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewData.cs @@ -7,22 +7,21 @@ using System; using System.Collections.Generic; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// An instance of PageView represents a generic action on a page like a button click. It is also the base type for PageView. internal partial class PageViewData : MonitorDomain { /// Initializes a new instance of . /// Schema version. - /// Identifier of a page view instance. Used for correlation between page view and other telemetry items. + /// + /// Identifier of a page view instance. Used for correlation between page view and + /// other telemetry items. + /// /// Event name. Keep it low cardinality to allow proper grouping and useful metrics. - /// or is null. public PageViewData(int version, string id, string name) : base(version) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(name, nameof(name)); - Id = id; Name = name; Properties = new ChangeTrackingDictionary(); @@ -31,15 +30,23 @@ public PageViewData(int version, string id, string name) : base(version) /// Initializes a new instance of . /// Schema version. - /// Additional Properties. - /// Identifier of a page view instance. Used for correlation between page view and other telemetry items. + /// Discriminator property to identify the specific telemetry data type. + /// + /// + /// Identifier of a page view instance. Used for correlation between page view and + /// other telemetry items. + /// /// Event name. Keep it low cardinality to allow proper grouping and useful metrics. /// Request URL with all query string parameters. - /// Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. + /// + /// Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), + /// this is the duration. For a page view with performance information + /// (PageViewPerfData), this is the page load time. Must be less than 1000 days. + /// /// Fully qualified page URI or URL of the referring page; if unknown, leave blank. /// Collection of custom properties. /// Collection of custom measurements. - internal PageViewData(int version, IDictionary additionalProperties, string id, string name, string url, string duration, string referredUri, IDictionary properties, IDictionary measurements) : base(version, additionalProperties) + internal PageViewData(int version, MonitorDomainKind kind, IDictionary additionalProperties, string id, string name, string url, string duration, string referredUri, IDictionary properties, IDictionary measurements) : base(version, kind, additionalProperties) { Id = id; Name = name; @@ -50,18 +57,31 @@ internal PageViewData(int version, IDictionary additionalPropert Measurements = measurements; } - /// Identifier of a page view instance. Used for correlation between page view and other telemetry items. - public string Id { get; } + /// + /// Identifier of a page view instance. Used for correlation between page view and + /// other telemetry items. + /// + public string Id { get; set; } + /// Event name. Keep it low cardinality to allow proper grouping and useful metrics. - public string Name { get; } + public string Name { get; set; } + /// Request URL with all query string parameters. public string Url { get; set; } - /// Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. + + /// + /// Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), + /// this is the duration. For a page view with performance information + /// (PageViewPerfData), this is the page load time. Must be less than 1000 days. + /// public string Duration { get; set; } + /// Fully qualified page URI or URL of the referring page; if unknown, leave blank. public string ReferredUri { get; set; } + /// Collection of custom properties. public IDictionary Properties { get; } + /// Collection of custom measurements. public IDictionary Measurements { get; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewPerfData.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewPerfData.Serialization.cs index 5c1068e35f2b..22db152e0c15 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewPerfData.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewPerfData.Serialization.cs @@ -5,16 +5,80 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class PageViewPerfData : IUtf8JsonSerializable + internal partial class PageViewPerfData : MonitorDomain, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal PageViewPerfData() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected override MonitorDomain PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializePageViewPerfData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PageViewPerfData)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(PageViewPerfData)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + PageViewPerfData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (PageViewPerfData)PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PageViewPerfData)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); writer.WritePropertyName("name"u8); @@ -61,6 +125,11 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) foreach (var item in Properties) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); @@ -76,22 +145,156 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) } writer.WriteEndObject(); } - writer.WritePropertyName("ver"u8); - writer.WriteNumberValue(Version); - foreach (var item in AdditionalProperties) + } + + /// The JSON reader. + /// The client options for reading and writing models. + PageViewPerfData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (PageViewPerfData)JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected override MonitorDomain JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value); + throw new FormatException($"The model {nameof(PageViewPerfData)} does not support reading '{format}' format."); } - writer.WriteEndObject(); + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePageViewPerfData(document.RootElement, options); } - /// Convert into a . - internal override RequestContent ToRequestContent() + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static PageViewPerfData DeserializePageViewPerfData(JsonElement element, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int version = default; + MonitorDomainKind kind = default; + IDictionary additionalProperties = new ChangeTrackingDictionary(); + string id = default; + string name = default; + string url = default; + string duration = default; + string perfTotal = default; + string networkConnect = default; + string sentRequest = default; + string receivedResponse = default; + string domProcessing = default; + IDictionary properties = default; + IDictionary measurements = default; + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("ver"u8)) + { + version = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("kind"u8)) + { + kind = new MonitorDomainKind(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("id"u8)) + { + id = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("name"u8)) + { + name = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("url"u8)) + { + url = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("duration"u8)) + { + duration = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("perfTotal"u8)) + { + perfTotal = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("networkConnect"u8)) + { + networkConnect = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("sentRequest"u8)) + { + sentRequest = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("receivedResponse"u8)) + { + receivedResponse = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("domProcessing"u8)) + { + domProcessing = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("properties"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + properties = dictionary; + continue; + } + if (prop.NameEquals("measurements"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + dictionary.Add(prop0.Name, prop0.Value.GetDouble()); + } + measurements = dictionary; + continue; + } + additionalProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + return new PageViewPerfData( + version, + kind, + additionalProperties, + id, + name, + url, + duration, + perfTotal, + networkConnect, + sentRequest, + receivedResponse, + domProcessing, + properties ?? new ChangeTrackingDictionary(), + measurements ?? new ChangeTrackingDictionary()); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewPerfData.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewPerfData.cs index f7d646ad757f..027d007fca8b 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewPerfData.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/PageViewPerfData.cs @@ -7,22 +7,21 @@ using System; using System.Collections.Generic; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// An instance of PageViewPerf represents: a page view with no performance data, a page view with performance data, or just the performance data of an earlier page request. internal partial class PageViewPerfData : MonitorDomain { /// Initializes a new instance of . /// Schema version. - /// Identifier of a page view instance. Used for correlation between page view and other telemetry items. + /// + /// Identifier of a page view instance. Used for correlation between page view and + /// other telemetry items. + /// /// Event name. Keep it low cardinality to allow proper grouping and useful metrics. - /// or is null. public PageViewPerfData(int version, string id, string name) : base(version) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(name, nameof(name)); - Id = id; Name = name; Properties = new ChangeTrackingDictionary(); @@ -31,19 +30,30 @@ public PageViewPerfData(int version, string id, string name) : base(version) /// Initializes a new instance of . /// Schema version. - /// Additional Properties. - /// Identifier of a page view instance. Used for correlation between page view and other telemetry items. + /// Discriminator property to identify the specific telemetry data type. + /// + /// + /// Identifier of a page view instance. Used for correlation between page view and + /// other telemetry items. + /// /// Event name. Keep it low cardinality to allow proper grouping and useful metrics. /// Request URL with all query string parameters. - /// Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. + /// + /// Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), + /// this is the duration. For a page view with performance information + /// (PageViewPerfData), this is the page load time. Must be less than 1000 days. + /// /// Performance total in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff. - /// Network connection time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff. + /// + /// Network connection time in TimeSpan 'G' (general long) format: + /// d:hh:mm:ss.fffffff + /// /// Sent request time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff. /// Received response time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff. /// DOM processing time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff. /// Collection of custom properties. /// Collection of custom measurements. - internal PageViewPerfData(int version, IDictionary additionalProperties, string id, string name, string url, string duration, string perfTotal, string networkConnect, string sentRequest, string receivedResponse, string domProcessing, IDictionary properties, IDictionary measurements) : base(version, additionalProperties) + internal PageViewPerfData(int version, MonitorDomainKind kind, IDictionary additionalProperties, string id, string name, string url, string duration, string perfTotal, string networkConnect, string sentRequest, string receivedResponse, string domProcessing, IDictionary properties, IDictionary measurements) : base(version, kind, additionalProperties) { Id = id; Name = name; @@ -58,26 +68,46 @@ internal PageViewPerfData(int version, IDictionary additionalPro Measurements = measurements; } - /// Identifier of a page view instance. Used for correlation between page view and other telemetry items. - public string Id { get; } + /// + /// Identifier of a page view instance. Used for correlation between page view and + /// other telemetry items. + /// + public string Id { get; set; } + /// Event name. Keep it low cardinality to allow proper grouping and useful metrics. - public string Name { get; } + public string Name { get; set; } + /// Request URL with all query string parameters. public string Url { get; set; } - /// Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. + + /// + /// Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), + /// this is the duration. For a page view with performance information + /// (PageViewPerfData), this is the page load time. Must be less than 1000 days. + /// public string Duration { get; set; } + /// Performance total in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff. public string PerfTotal { get; set; } - /// Network connection time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff. + + /// + /// Network connection time in TimeSpan 'G' (general long) format: + /// d:hh:mm:ss.fffffff + /// public string NetworkConnect { get; set; } + /// Sent request time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff. public string SentRequest { get; set; } + /// Received response time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff. public string ReceivedResponse { get; set; } + /// DOM processing time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff. public string DomProcessing { get; set; } + /// Collection of custom properties. public IDictionary Properties { get; } + /// Collection of custom measurements. public IDictionary Measurements { get; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RemoteDependencyData.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RemoteDependencyData.Serialization.cs index 8995b6c74f89..aa9ee6b7b181 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RemoteDependencyData.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RemoteDependencyData.Serialization.cs @@ -5,16 +5,80 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class RemoteDependencyData : IUtf8JsonSerializable + internal partial class RemoteDependencyData : MonitorDomain, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal RemoteDependencyData() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected override MonitorDomain PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeRemoteDependencyData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RemoteDependencyData)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(RemoteDependencyData)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + RemoteDependencyData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (RemoteDependencyData)PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RemoteDependencyData)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); if (Optional.IsDefined(Id)) { writer.WritePropertyName("id"u8); @@ -56,6 +120,11 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) foreach (var item in Properties) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); @@ -71,22 +140,153 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) } writer.WriteEndObject(); } - writer.WritePropertyName("ver"u8); - writer.WriteNumberValue(Version); - foreach (var item in AdditionalProperties) + } + + /// The JSON reader. + /// The client options for reading and writing models. + RemoteDependencyData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (RemoteDependencyData)JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected override MonitorDomain JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value); + throw new FormatException($"The model {nameof(RemoteDependencyData)} does not support reading '{format}' format."); } - writer.WriteEndObject(); + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRemoteDependencyData(document.RootElement, options); } - /// Convert into a . - internal override RequestContent ToRequestContent() + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static RemoteDependencyData DeserializeRemoteDependencyData(JsonElement element, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int version = default; + MonitorDomainKind kind = default; + IDictionary additionalProperties = new ChangeTrackingDictionary(); + string id = default; + string name = default; + string resultCode = default; + string data = default; + string @type = default; + string target = default; + string duration = default; + bool? success = default; + IDictionary properties = default; + IDictionary measurements = default; + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("ver"u8)) + { + version = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("kind"u8)) + { + kind = new MonitorDomainKind(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("id"u8)) + { + id = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("name"u8)) + { + name = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("resultCode"u8)) + { + resultCode = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("data"u8)) + { + data = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("type"u8)) + { + @type = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("target"u8)) + { + target = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("duration"u8)) + { + duration = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("success"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + success = prop.Value.GetBoolean(); + continue; + } + if (prop.NameEquals("properties"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + properties = dictionary; + continue; + } + if (prop.NameEquals("measurements"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + dictionary.Add(prop0.Name, prop0.Value.GetDouble()); + } + measurements = dictionary; + continue; + } + additionalProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + return new RemoteDependencyData( + version, + kind, + additionalProperties, + id, + name, + resultCode, + data, + @type, + target, + duration, + success, + properties ?? new ChangeTrackingDictionary(), + measurements ?? new ChangeTrackingDictionary()); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RemoteDependencyData.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RemoteDependencyData.cs index 69d0a85ee4f9..2bccb626d35b 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RemoteDependencyData.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RemoteDependencyData.cs @@ -7,22 +7,21 @@ using System; using System.Collections.Generic; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// An instance of Remote Dependency represents an interaction of the monitored component with a remote component/service like SQL or an HTTP endpoint. internal partial class RemoteDependencyData : MonitorDomain { /// Initializes a new instance of . /// Schema version. - /// Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. + /// + /// Name of the command initiated with this dependency call. Low cardinality value. + /// Examples are stored procedure name and URL path template. + /// /// Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. - /// or is null. public RemoteDependencyData(int version, string name, string duration) : base(version) { - Argument.AssertNotNull(name, nameof(name)); - Argument.AssertNotNull(duration, nameof(duration)); - Name = name; Duration = duration; Properties = new ChangeTrackingDictionary(); @@ -31,24 +30,41 @@ public RemoteDependencyData(int version, string name, string duration) : base(ve /// Initializes a new instance of . /// Schema version. - /// Additional Properties. - /// Identifier of a dependency call instance. Used for correlation with the request telemetry item corresponding to this dependency call. - /// Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. - /// Result code of a dependency call. Examples are SQL error code and HTTP status code. - /// Command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters. - /// Dependency type name. Very low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. + /// Discriminator property to identify the specific telemetry data type. + /// + /// + /// Identifier of a dependency call instance. Used for correlation with the request + /// telemetry item corresponding to this dependency call. + /// + /// + /// Name of the command initiated with this dependency call. Low cardinality value. + /// Examples are stored procedure name and URL path template. + /// + /// + /// Result code of a dependency call. Examples are SQL error code and HTTP status + /// code. + /// + /// + /// Command initiated by this dependency call. Examples are SQL statement and HTTP + /// URL with all query parameters. + /// + /// + /// Dependency type name. Very low cardinality value for logical grouping of + /// dependencies and interpretation of other fields like commandName and + /// resultCode. Examples are SQL, Azure table, and HTTP. + /// /// Target site of a dependency call. Examples are server name, host address. /// Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. /// Indication of successful or unsuccessful call. /// Collection of custom properties. /// Collection of custom measurements. - internal RemoteDependencyData(int version, IDictionary additionalProperties, string id, string name, string resultCode, string data, string type, string target, string duration, bool? success, IDictionary properties, IDictionary measurements) : base(version, additionalProperties) + internal RemoteDependencyData(int version, MonitorDomainKind kind, IDictionary additionalProperties, string id, string name, string resultCode, string data, string @type, string target, string duration, bool? success, IDictionary properties, IDictionary measurements) : base(version, kind, additionalProperties) { Id = id; Name = name; ResultCode = resultCode; Data = data; - Type = type; + Type = @type; Target = target; Duration = duration; Success = success; @@ -56,24 +72,49 @@ internal RemoteDependencyData(int version, IDictionary additiona Measurements = measurements; } - /// Identifier of a dependency call instance. Used for correlation with the request telemetry item corresponding to this dependency call. + /// + /// Identifier of a dependency call instance. Used for correlation with the request + /// telemetry item corresponding to this dependency call. + /// public string Id { get; set; } - /// Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. - public string Name { get; } - /// Result code of a dependency call. Examples are SQL error code and HTTP status code. + + /// + /// Name of the command initiated with this dependency call. Low cardinality value. + /// Examples are stored procedure name and URL path template. + /// + public string Name { get; set; } + + /// + /// Result code of a dependency call. Examples are SQL error code and HTTP status + /// code. + /// public string ResultCode { get; set; } - /// Command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters. + + /// + /// Command initiated by this dependency call. Examples are SQL statement and HTTP + /// URL with all query parameters. + /// public string Data { get; set; } - /// Dependency type name. Very low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. + + /// + /// Dependency type name. Very low cardinality value for logical grouping of + /// dependencies and interpretation of other fields like commandName and + /// resultCode. Examples are SQL, Azure table, and HTTP. + /// public string Type { get; set; } + /// Target site of a dependency call. Examples are server name, host address. public string Target { get; set; } + /// Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. - public string Duration { get; } + public string Duration { get; set; } + /// Indication of successful or unsuccessful call. public bool? Success { get; set; } + /// Collection of custom properties. public IDictionary Properties { get; } + /// Collection of custom measurements. public IDictionary Measurements { get; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RequestData.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RequestData.Serialization.cs index 251a3913e737..9f4b7d1c0eea 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RequestData.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RequestData.Serialization.cs @@ -5,16 +5,80 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class RequestData : IUtf8JsonSerializable + internal partial class RequestData : MonitorDomain, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal RequestData() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected override MonitorDomain PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeRequestData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RequestData)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(RequestData)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + RequestData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (RequestData)PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RequestData)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); if (Optional.IsDefined(Name)) @@ -45,6 +109,11 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) foreach (var item in Properties) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); @@ -60,22 +129,142 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) } writer.WriteEndObject(); } - writer.WritePropertyName("ver"u8); - writer.WriteNumberValue(Version); - foreach (var item in AdditionalProperties) + } + + /// The JSON reader. + /// The client options for reading and writing models. + RequestData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (RequestData)JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected override MonitorDomain JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value); + throw new FormatException($"The model {nameof(RequestData)} does not support reading '{format}' format."); } - writer.WriteEndObject(); + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRequestData(document.RootElement, options); } - /// Convert into a . - internal override RequestContent ToRequestContent() + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static RequestData DeserializeRequestData(JsonElement element, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int version = default; + MonitorDomainKind kind = default; + IDictionary additionalProperties = new ChangeTrackingDictionary(); + string id = default; + string name = default; + string duration = default; + bool success = default; + string responseCode = default; + string source = default; + string url = default; + IDictionary properties = default; + IDictionary measurements = default; + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("ver"u8)) + { + version = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("kind"u8)) + { + kind = new MonitorDomainKind(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("id"u8)) + { + id = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("name"u8)) + { + name = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("duration"u8)) + { + duration = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("success"u8)) + { + success = prop.Value.GetBoolean(); + continue; + } + if (prop.NameEquals("responseCode"u8)) + { + responseCode = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("source"u8)) + { + source = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("url"u8)) + { + url = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("properties"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + properties = dictionary; + continue; + } + if (prop.NameEquals("measurements"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + dictionary.Add(prop0.Name, prop0.Value.GetDouble()); + } + measurements = dictionary; + continue; + } + additionalProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + return new RequestData( + version, + kind, + additionalProperties, + id, + name, + duration, + success, + responseCode, + source, + url, + properties ?? new ChangeTrackingDictionary(), + measurements ?? new ChangeTrackingDictionary()); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RequestData.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RequestData.cs index 7f42cc5ea747..42ed17ff2e01 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RequestData.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/RequestData.cs @@ -7,25 +7,23 @@ using System; using System.Collections.Generic; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// An instance of Request represents completion of an external request to the application to do work and contains a summary of that request execution and the results. internal partial class RequestData : MonitorDomain { /// Initializes a new instance of . /// Schema version. - /// Identifier of a request call instance. Used for correlation between request and other telemetry items. + /// + /// Identifier of a request call instance. Used for correlation between request and + /// other telemetry items. + /// /// Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. /// Indication of successful or unsuccessful call. /// Result of a request execution. HTTP status code for HTTP requests. - /// , or is null. public RequestData(int version, string id, string duration, bool success, string responseCode) : base(version) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(duration, nameof(duration)); - Argument.AssertNotNull(responseCode, nameof(responseCode)); - Id = id; Duration = duration; Success = success; @@ -36,17 +34,28 @@ public RequestData(int version, string id, string duration, bool success, string /// Initializes a new instance of . /// Schema version. - /// Additional Properties. - /// Identifier of a request call instance. Used for correlation between request and other telemetry items. - /// Name of the request. Represents code path taken to process request. Low cardinality value to allow better grouping of requests. For HTTP requests it represents the HTTP method and URL path template like 'GET /values/{id}'. + /// Discriminator property to identify the specific telemetry data type. + /// + /// + /// Identifier of a request call instance. Used for correlation between request and + /// other telemetry items. + /// + /// + /// Name of the request. Represents code path taken to process request. Low + /// cardinality value to allow better grouping of requests. For HTTP requests it + /// represents the HTTP method and URL path template like 'GET /values/{id}'. + /// /// Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. /// Indication of successful or unsuccessful call. /// Result of a request execution. HTTP status code for HTTP requests. - /// Source of the request. Examples are the instrumentation key of the caller or the ip address of the caller. + /// + /// Source of the request. Examples are the instrumentation key of the caller or + /// the ip address of the caller. + /// /// Request URL with all query string parameters. /// Collection of custom properties. /// Collection of custom measurements. - internal RequestData(int version, IDictionary additionalProperties, string id, string name, string duration, bool success, string responseCode, string source, string url, IDictionary properties, IDictionary measurements) : base(version, additionalProperties) + internal RequestData(int version, MonitorDomainKind kind, IDictionary additionalProperties, string id, string name, string duration, bool success, string responseCode, string source, string url, IDictionary properties, IDictionary measurements) : base(version, kind, additionalProperties) { Id = id; Name = name; @@ -59,22 +68,40 @@ internal RequestData(int version, IDictionary additionalProperti Measurements = measurements; } - /// Identifier of a request call instance. Used for correlation between request and other telemetry items. - public string Id { get; } - /// Name of the request. Represents code path taken to process request. Low cardinality value to allow better grouping of requests. For HTTP requests it represents the HTTP method and URL path template like 'GET /values/{id}'. + /// + /// Identifier of a request call instance. Used for correlation between request and + /// other telemetry items. + /// + public string Id { get; set; } + + /// + /// Name of the request. Represents code path taken to process request. Low + /// cardinality value to allow better grouping of requests. For HTTP requests it + /// represents the HTTP method and URL path template like 'GET /values/{id}'. + /// public string Name { get; set; } + /// Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. - public string Duration { get; } + public string Duration { get; set; } + /// Indication of successful or unsuccessful call. - public bool Success { get; } + public bool Success { get; set; } + /// Result of a request execution. HTTP status code for HTTP requests. - public string ResponseCode { get; } - /// Source of the request. Examples are the instrumentation key of the caller or the ip address of the caller. + public string ResponseCode { get; set; } + + /// + /// Source of the request. Examples are the instrumentation key of the caller or + /// the ip address of the caller. + /// public string Source { get; set; } + /// Request URL with all query string parameters. public string Url { get; set; } + /// Collection of custom properties. public IDictionary Properties { get; } + /// Collection of custom measurements. public IDictionary Measurements { get; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/SeverityLevel.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/SeverityLevel.cs index 35c67451f282..6a21178891c5 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/SeverityLevel.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/SeverityLevel.cs @@ -10,51 +10,72 @@ namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// Defines the level of severity for the event. internal readonly partial struct SeverityLevel : IEquatable { private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public SeverityLevel(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - + /// Verbose level. private const string VerboseValue = "Verbose"; + /// Information level. private const string InformationValue = "Information"; + /// Warning level. private const string WarningValue = "Warning"; + /// Error level. private const string ErrorValue = "Error"; + /// Critical level. private const string CriticalValue = "Critical"; - /// Verbose. + /// Initializes a new instance of . + /// The value. + public SeverityLevel(string value) + { + _value = value; + } + + /// Verbose level. public static SeverityLevel Verbose { get; } = new SeverityLevel(VerboseValue); - /// Information. + + /// Information level. public static SeverityLevel Information { get; } = new SeverityLevel(InformationValue); - /// Warning. + + /// Warning level. public static SeverityLevel Warning { get; } = new SeverityLevel(WarningValue); - /// Error. + + /// Error level. public static SeverityLevel Error { get; } = new SeverityLevel(ErrorValue); - /// Critical. + + /// Critical level. public static SeverityLevel Critical { get; } = new SeverityLevel(CriticalValue); + /// Determines if two values are the same. + /// The left value to compare. + /// The right value to compare. public static bool operator ==(SeverityLevel left, SeverityLevel right) => left.Equals(right); + /// Determines if two values are not the same. + /// The left value to compare. + /// The right value to compare. public static bool operator !=(SeverityLevel left, SeverityLevel right) => !left.Equals(right); - /// Converts a to a . + + /// Converts a string to a . + /// The value. public static implicit operator SeverityLevel(string value) => new SeverityLevel(value); - /// + /// Converts a string to a . + /// The value. + public static implicit operator SeverityLevel?(string value) => value == null ? null : new SeverityLevel(value); + + /// [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is SeverityLevel other && Equals(other); - /// + + /// public bool Equals(SeverityLevel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - /// + /// [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// + + /// public override string ToString() => _value; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/StackFrame.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/StackFrame.Serialization.cs index f1d74de74b8e..bdc6fdb3ee63 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/StackFrame.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/StackFrame.Serialization.cs @@ -5,16 +5,79 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class StackFrame : IUtf8JsonSerializable + internal partial class StackFrame : IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal StackFrame() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected virtual StackFrame PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeStackFrame(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(StackFrame)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(StackFrame)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + StackFrame IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(StackFrame)} does not support writing '{format}' format."); + } writer.WritePropertyName("level"u8); writer.WriteNumberValue(Level); writer.WritePropertyName("method"u8); @@ -34,15 +97,97 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) writer.WritePropertyName("line"u8); writer.WriteNumberValue(Line.Value); } - writer.WriteEndObject(); + if (options.Format != "W" && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + 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 + } + } } - /// Convert into a . - internal virtual RequestContent ToRequestContent() + /// The JSON reader. + /// The client options for reading and writing models. + StackFrame IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected virtual StackFrame JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(StackFrame)} does not support reading '{format}' format."); + } + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeStackFrame(document.RootElement, options); + } + + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static StackFrame DeserializeStackFrame(JsonElement element, ModelReaderWriterOptions options) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int level = default; + string @method = default; + string @assembly = default; + string fileName = default; + int? line = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("level"u8)) + { + level = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("method"u8)) + { + @method = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("assembly"u8)) + { + @assembly = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("fileName"u8)) + { + fileName = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("line"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + line = prop.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + } + return new StackFrame( + level, + @method, + @assembly, + fileName, + line, + additionalBinaryDataProperties); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/StackFrame.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/StackFrame.cs index 979204436e6c..78cecb6894cf 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/StackFrame.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/StackFrame.cs @@ -6,47 +6,53 @@ #nullable disable using System; +using System.Collections.Generic; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// Stack frame information. internal partial class StackFrame { + /// Keeps track of any properties unknown to the library. + private protected readonly IDictionary _additionalBinaryDataProperties; + /// Initializes a new instance of . - /// + /// Level in the stack. /// Method name. - /// is null. - public StackFrame(int level, string method) + public StackFrame(int level, string @method) { - Argument.AssertNotNull(method, nameof(method)); - Level = level; - Method = method; + Method = @method; } /// Initializes a new instance of . - /// + /// Level in the stack. /// Method name. /// Name of the assembly (dll, jar, etc.) containing this function. /// File name or URL of the method implementation. /// Line number of the code implementation. - internal StackFrame(int level, string method, string assembly, string fileName, int? line) + /// Keeps track of any properties unknown to the library. + internal StackFrame(int level, string @method, string @assembly, string fileName, int? line, IDictionary additionalBinaryDataProperties) { Level = level; - Method = method; - Assembly = assembly; + Method = @method; + Assembly = @assembly; FileName = fileName; Line = line; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - /// Gets the level. - public int Level { get; } + /// Level in the stack. + public int Level { get; set; } + /// Method name. - public string Method { get; } + public string Method { get; set; } + /// Name of the assembly (dll, jar, etc.) containing this function. public string Assembly { get; set; } + /// File name or URL of the method implementation. public string FileName { get; set; } + /// Line number of the code implementation. public int? Line { get; set; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryErrorDetails.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryErrorDetails.Serialization.cs index 9500adf3cd28..84a984f95b96 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryErrorDetails.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryErrorDetails.Serialization.cs @@ -5,13 +5,126 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class TelemetryErrorDetails + internal partial class TelemetryErrorDetails : IJsonModel { - internal static TelemetryErrorDetails DeserializeTelemetryErrorDetails(JsonElement element) + /// The data to parse. + /// The client options for reading and writing models. + protected virtual TelemetryErrorDetails PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeTelemetryErrorDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TelemetryErrorDetails)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(TelemetryErrorDetails)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + TelemetryErrorDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TelemetryErrorDetails)} does not support writing '{format}' format."); + } + if (Optional.IsDefined(Index)) + { + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index.Value); + } + if (Optional.IsDefined(StatusCode)) + { + writer.WritePropertyName("statusCode"u8); + writer.WriteNumberValue(StatusCode.Value); + } + if (Optional.IsDefined(Message)) + { + writer.WritePropertyName("message"u8); + writer.WriteStringValue(Message); + } + if (options.Format != "W" && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + 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 + } + } + } + + /// The JSON reader. + /// The client options for reading and writing models. + TelemetryErrorDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected virtual TelemetryErrorDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TelemetryErrorDetails)} does not support reading '{format}' format."); + } + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTelemetryErrorDetails(document.RootElement, options); + } + + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static TelemetryErrorDetails DeserializeTelemetryErrorDetails(JsonElement element, ModelReaderWriterOptions options) { if (element.ValueKind == JsonValueKind.Null) { @@ -20,41 +133,38 @@ internal static TelemetryErrorDetails DeserializeTelemetryErrorDetails(JsonEleme int? index = default; int? statusCode = default; string message = default; - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("index"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - index = property.Value.GetInt32(); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("statusCode"u8)) + if (prop.NameEquals("statusCode"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - statusCode = property.Value.GetInt32(); + statusCode = prop.Value.GetInt32(); continue; } - if (property.NameEquals("message"u8)) + if (prop.NameEquals("message"u8)) { - message = property.Value.GetString(); + message = prop.Value.GetString(); continue; } + if (options.Format != "W") + { + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } } - return new TelemetryErrorDetails(index, statusCode, message); - } - - /// Deserializes the model from a raw response. - /// The response to deserialize the model from. - internal static TelemetryErrorDetails FromResponse(Response response) - { - using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTelemetryErrorDetails(document.RootElement); + return new TelemetryErrorDetails(index, statusCode, message, additionalBinaryDataProperties); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryErrorDetails.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryErrorDetails.cs index b3558427082d..1627f50b55a5 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryErrorDetails.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryErrorDetails.cs @@ -5,11 +5,16 @@ #nullable disable +using System; +using System.Collections.Generic; + namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// The error details. internal partial class TelemetryErrorDetails { + /// Keeps track of any properties unknown to the library. + private protected readonly IDictionary _additionalBinaryDataProperties; + /// Initializes a new instance of . internal TelemetryErrorDetails() { @@ -19,17 +24,21 @@ internal TelemetryErrorDetails() /// The index in the original payload of the item. /// The item specific [HTTP Response status code](#Response Status Codes). /// The error message. - internal TelemetryErrorDetails(int? index, int? statusCode, string message) + /// Keeps track of any properties unknown to the library. + internal TelemetryErrorDetails(int? index, int? statusCode, string message, IDictionary additionalBinaryDataProperties) { Index = index; StatusCode = statusCode; Message = message; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } /// The index in the original payload of the item. public int? Index { get; } + /// The item specific [HTTP Response status code](#Response Status Codes). public int? StatusCode { get; } + /// The error message. public string Message { get; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryEventData.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryEventData.Serialization.cs index 5862ebf7c672..b4d7af4f3679 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryEventData.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryEventData.Serialization.cs @@ -5,16 +5,80 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class TelemetryEventData : IUtf8JsonSerializable + internal partial class TelemetryEventData : MonitorDomain, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal TelemetryEventData() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected override MonitorDomain PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeTelemetryEventData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TelemetryEventData)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(TelemetryEventData)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + TelemetryEventData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (TelemetryEventData)PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TelemetryEventData)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); if (Optional.IsCollectionDefined(Properties)) @@ -24,6 +88,11 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) foreach (var item in Properties) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); @@ -39,22 +108,100 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) } writer.WriteEndObject(); } - writer.WritePropertyName("ver"u8); - writer.WriteNumberValue(Version); - foreach (var item in AdditionalProperties) + } + + /// The JSON reader. + /// The client options for reading and writing models. + TelemetryEventData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (TelemetryEventData)JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected override MonitorDomain JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value); + throw new FormatException($"The model {nameof(TelemetryEventData)} does not support reading '{format}' format."); } - writer.WriteEndObject(); + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTelemetryEventData(document.RootElement, options); } - /// Convert into a . - internal override RequestContent ToRequestContent() + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static TelemetryEventData DeserializeTelemetryEventData(JsonElement element, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int version = default; + MonitorDomainKind kind = default; + IDictionary additionalProperties = new ChangeTrackingDictionary(); + string name = default; + IDictionary properties = default; + IDictionary measurements = default; + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("ver"u8)) + { + version = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("kind"u8)) + { + kind = new MonitorDomainKind(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("name"u8)) + { + name = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("properties"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + properties = dictionary; + continue; + } + if (prop.NameEquals("measurements"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + dictionary.Add(prop0.Name, prop0.Value.GetDouble()); + } + measurements = dictionary; + continue; + } + additionalProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + return new TelemetryEventData( + version, + kind, + additionalProperties, + name, + properties ?? new ChangeTrackingDictionary(), + measurements ?? new ChangeTrackingDictionary()); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryEventData.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryEventData.cs index 7f94f8263ff7..5ad5979fccd2 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryEventData.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryEventData.cs @@ -7,20 +7,17 @@ using System; using System.Collections.Generic; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// Instances of Event represent structured event records that can be grouped and searched by their properties. Event data item also creates a metric of event count by name. internal partial class TelemetryEventData : MonitorDomain { /// Initializes a new instance of . /// Schema version. /// Event name. Keep it low cardinality to allow proper grouping and useful metrics. - /// is null. public TelemetryEventData(int version, string name) : base(version) { - Argument.AssertNotNull(name, nameof(name)); - Name = name; Properties = new ChangeTrackingDictionary(); Measurements = new ChangeTrackingDictionary(); @@ -28,11 +25,12 @@ public TelemetryEventData(int version, string name) : base(version) /// Initializes a new instance of . /// Schema version. - /// Additional Properties. + /// Discriminator property to identify the specific telemetry data type. + /// /// Event name. Keep it low cardinality to allow proper grouping and useful metrics. /// Collection of custom properties. /// Collection of custom measurements. - internal TelemetryEventData(int version, IDictionary additionalProperties, string name, IDictionary properties, IDictionary measurements) : base(version, additionalProperties) + internal TelemetryEventData(int version, MonitorDomainKind kind, IDictionary additionalProperties, string name, IDictionary properties, IDictionary measurements) : base(version, kind, additionalProperties) { Name = name; Properties = properties; @@ -40,9 +38,11 @@ internal TelemetryEventData(int version, IDictionary additionalP } /// Event name. Keep it low cardinality to allow proper grouping and useful metrics. - public string Name { get; } + public string Name { get; set; } + /// Collection of custom properties. public IDictionary Properties { get; } + /// Collection of custom measurements. public IDictionary Measurements { get; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionData.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionData.Serialization.cs index 37974ab3e56f..e92d6f3cb8d1 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionData.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionData.Serialization.cs @@ -5,34 +5,91 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class TelemetryExceptionData : IUtf8JsonSerializable + internal partial class TelemetryExceptionData : MonitorDomain, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal TelemetryExceptionData() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected override MonitorDomain PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeTelemetryExceptionData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TelemetryExceptionData)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(TelemetryExceptionData)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + TelemetryExceptionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (TelemetryExceptionData)PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TelemetryExceptionData)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); writer.WritePropertyName("exceptions"u8); writer.WriteStartArray(); - foreach (var item in Exceptions) + foreach (TelemetryExceptionDetails item in Exceptions) { - writer.WriteObjectValue(item); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); if (Optional.IsDefined(SeverityLevel)) { - if (SeverityLevel != null) - { - writer.WritePropertyName("severityLevel"u8); - writer.WriteStringValue(SeverityLevel.Value.ToString()); - } - else - { - writer.WriteNull("severityLevel"); - } + writer.WritePropertyName("severityLevel"u8); + writer.WriteStringValue(SeverityLevel.Value.ToString()); } if (Optional.IsDefined(ProblemId)) { @@ -46,6 +103,11 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) foreach (var item in Properties) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); @@ -61,22 +123,123 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) } writer.WriteEndObject(); } - writer.WritePropertyName("ver"u8); - writer.WriteNumberValue(Version); - foreach (var item in AdditionalProperties) + } + + /// The JSON reader. + /// The client options for reading and writing models. + TelemetryExceptionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (TelemetryExceptionData)JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected override MonitorDomain JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value); + throw new FormatException($"The model {nameof(TelemetryExceptionData)} does not support reading '{format}' format."); } - writer.WriteEndObject(); + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTelemetryExceptionData(document.RootElement, options); } - /// Convert into a . - internal override RequestContent ToRequestContent() + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static TelemetryExceptionData DeserializeTelemetryExceptionData(JsonElement element, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int version = default; + MonitorDomainKind kind = default; + IDictionary additionalProperties = new ChangeTrackingDictionary(); + IList exceptions = default; + SeverityLevel? severityLevel = default; + string problemId = default; + IDictionary properties = default; + IDictionary measurements = default; + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("ver"u8)) + { + version = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("kind"u8)) + { + kind = new MonitorDomainKind(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("exceptions"u8)) + { + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(TelemetryExceptionDetails.DeserializeTelemetryExceptionDetails(item, options)); + } + exceptions = array; + continue; + } + if (prop.NameEquals("severityLevel"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + severityLevel = new SeverityLevel(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("problemId"u8)) + { + problemId = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("properties"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + properties = dictionary; + continue; + } + if (prop.NameEquals("measurements"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + dictionary.Add(prop0.Name, prop0.Value.GetDouble()); + } + measurements = dictionary; + continue; + } + additionalProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + return new TelemetryExceptionData( + version, + kind, + additionalProperties, + exceptions, + severityLevel, + problemId, + properties ?? new ChangeTrackingDictionary(), + measurements ?? new ChangeTrackingDictionary()); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionData.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionData.cs index b602efc52e18..d28d75734a6c 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionData.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionData.cs @@ -8,20 +8,17 @@ using System; using System.Collections.Generic; using System.Linq; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// An instance of Exception represents a handled or unhandled exception that occurred during execution of the monitored application. internal partial class TelemetryExceptionData : MonitorDomain { /// Initializes a new instance of . /// Schema version. /// Exception chain - list of inner exceptions. - /// is null. public TelemetryExceptionData(int version, IEnumerable exceptions) : base(version) { - Argument.AssertNotNull(exceptions, nameof(exceptions)); - Exceptions = exceptions.ToList(); Properties = new ChangeTrackingDictionary(); Measurements = new ChangeTrackingDictionary(); @@ -29,13 +26,21 @@ public TelemetryExceptionData(int version, IEnumerable Initializes a new instance of . /// Schema version. - /// Additional Properties. + /// Discriminator property to identify the specific telemetry data type. + /// /// Exception chain - list of inner exceptions. - /// Severity level. Mostly used to indicate exception severity level when it is reported by logging library. - /// Identifier of where the exception was thrown in code. Used for exceptions grouping. Typically a combination of exception type and a function from the call stack. + /// + /// Severity level. Mostly used to indicate exception severity level when it is + /// reported by logging library. + /// + /// + /// Identifier of where the exception was thrown in code. Used for exceptions + /// grouping. Typically a combination of exception type and a function from the + /// call stack. + /// /// Collection of custom properties. /// Collection of custom measurements. - internal TelemetryExceptionData(int version, IDictionary additionalProperties, IList exceptions, SeverityLevel? severityLevel, string problemId, IDictionary properties, IDictionary measurements) : base(version, additionalProperties) + internal TelemetryExceptionData(int version, MonitorDomainKind kind, IDictionary additionalProperties, IList exceptions, SeverityLevel? severityLevel, string problemId, IDictionary properties, IDictionary measurements) : base(version, kind, additionalProperties) { Exceptions = exceptions; SeverityLevel = severityLevel; @@ -46,12 +51,23 @@ internal TelemetryExceptionData(int version, IDictionary additio /// Exception chain - list of inner exceptions. public IList Exceptions { get; } - /// Severity level. Mostly used to indicate exception severity level when it is reported by logging library. + + /// + /// Severity level. Mostly used to indicate exception severity level when it is + /// reported by logging library. + /// public SeverityLevel? SeverityLevel { get; set; } - /// Identifier of where the exception was thrown in code. Used for exceptions grouping. Typically a combination of exception type and a function from the call stack. + + /// + /// Identifier of where the exception was thrown in code. Used for exceptions + /// grouping. Typically a combination of exception type and a function from the + /// call stack. + /// public string ProblemId { get; set; } + /// Collection of custom properties. public IDictionary Properties { get; } + /// Collection of custom measurements. public IDictionary Measurements { get; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionDetails.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionDetails.Serialization.cs index ada51d641f1a..fe2c78dd4c3c 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionDetails.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionDetails.Serialization.cs @@ -5,16 +5,79 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class TelemetryExceptionDetails : IUtf8JsonSerializable + internal partial class TelemetryExceptionDetails : IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal TelemetryExceptionDetails() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected virtual TelemetryExceptionDetails PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeTelemetryExceptionDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TelemetryExceptionDetails)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(TelemetryExceptionDetails)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + TelemetryExceptionDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TelemetryExceptionDetails)} does not support writing '{format}' format."); + } if (Optional.IsDefined(Id)) { writer.WritePropertyName("id"u8); @@ -46,21 +109,134 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WritePropertyName("parsedStack"u8); writer.WriteStartArray(); - foreach (var item in ParsedStack) + foreach (StackFrame item in ParsedStack) { - writer.WriteObjectValue(item); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - writer.WriteEndObject(); + if (options.Format != "W" && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + 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 + } + } } - /// Convert into a . - internal virtual RequestContent ToRequestContent() + /// The JSON reader. + /// The client options for reading and writing models. + TelemetryExceptionDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected virtual TelemetryExceptionDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TelemetryExceptionDetails)} does not support reading '{format}' format."); + } + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTelemetryExceptionDetails(document.RootElement, options); + } + + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static TelemetryExceptionDetails DeserializeTelemetryExceptionDetails(JsonElement element, ModelReaderWriterOptions options) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? id = default; + int? outerId = default; + string typeName = default; + string message = default; + bool? hasFullStack = default; + string stack = default; + IList parsedStack = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("id"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + id = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("outerId"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + outerId = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("typeName"u8)) + { + typeName = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("message"u8)) + { + message = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("hasFullStack"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + hasFullStack = prop.Value.GetBoolean(); + continue; + } + if (prop.NameEquals("stack"u8)) + { + stack = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("parsedStack"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(StackFrame.DeserializeStackFrame(item, options)); + } + parsedStack = array; + continue; + } + if (options.Format != "W") + { + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + } + return new TelemetryExceptionDetails( + id, + outerId, + typeName, + message, + hasFullStack, + stack, + parsedStack ?? new ChangeTrackingList(), + additionalBinaryDataProperties); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionDetails.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionDetails.cs index 44cc22a4ad29..4b2bcdca8402 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionDetails.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryExceptionDetails.cs @@ -7,32 +7,42 @@ using System; using System.Collections.Generic; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// Exception details of the exception in a chain. internal partial class TelemetryExceptionDetails { + /// Keeps track of any properties unknown to the library. + private protected readonly IDictionary _additionalBinaryDataProperties; + /// Initializes a new instance of . /// Exception message. - /// is null. public TelemetryExceptionDetails(string message) { - Argument.AssertNotNull(message, nameof(message)); - Message = message; ParsedStack = new ChangeTrackingList(); } /// Initializes a new instance of . - /// In case exception is nested (outer exception contains inner one), the id and outerId properties are used to represent the nesting. - /// The value of outerId is a reference to an element in ExceptionDetails that represents the outer exception. + /// + /// In case exception is nested (outer exception contains inner one), the id and + /// outerId properties are used to represent the nesting. + /// + /// + /// The value of outerId is a reference to an element in ExceptionDetails that + /// represents the outer exception + /// /// Exception type name. /// Exception message. - /// Indicates if full exception stack is provided in the exception. The stack may be trimmed, such as in the case of a StackOverflow exception. + /// + /// Indicates if full exception stack is provided in the exception. The stack may + /// be trimmed, such as in the case of a StackOverflow exception. + /// /// Text describing the stack. Either stack or parsedStack should have a value. /// List of stack frames. Either stack or parsedStack should have a value. - internal TelemetryExceptionDetails(int? id, int? outerId, string typeName, string message, bool? hasFullStack, string stack, IList parsedStack) + /// Keeps track of any properties unknown to the library. + internal TelemetryExceptionDetails(int? id, int? outerId, string typeName, string message, bool? hasFullStack, string stack, IList parsedStack, IDictionary additionalBinaryDataProperties) { Id = id; OuterId = outerId; @@ -41,20 +51,36 @@ internal TelemetryExceptionDetails(int? id, int? outerId, string typeName, strin HasFullStack = hasFullStack; Stack = stack; ParsedStack = parsedStack; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - /// In case exception is nested (outer exception contains inner one), the id and outerId properties are used to represent the nesting. + /// + /// In case exception is nested (outer exception contains inner one), the id and + /// outerId properties are used to represent the nesting. + /// public int? Id { get; set; } - /// The value of outerId is a reference to an element in ExceptionDetails that represents the outer exception. + + /// + /// The value of outerId is a reference to an element in ExceptionDetails that + /// represents the outer exception + /// public int? OuterId { get; set; } + /// Exception type name. public string TypeName { get; set; } + /// Exception message. - public string Message { get; } - /// Indicates if full exception stack is provided in the exception. The stack may be trimmed, such as in the case of a StackOverflow exception. + public string Message { get; set; } + + /// + /// Indicates if full exception stack is provided in the exception. The stack may + /// be trimmed, such as in the case of a StackOverflow exception. + /// public bool? HasFullStack { get; set; } + /// Text describing the stack. Either stack or parsedStack should have a value. public string Stack { get; set; } + /// List of stack frames. Either stack or parsedStack should have a value. public IList ParsedStack { get; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryItem.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryItem.Serialization.cs index 20dafc55c476..3bdd732472b6 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryItem.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryItem.Serialization.cs @@ -5,16 +5,79 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; -using Azure.Core; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class TelemetryItem : IUtf8JsonSerializable + internal partial class TelemetryItem : IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + /// Initializes a new instance of for deserialization. + internal TelemetryItem() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected virtual TelemetryItem PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeTelemetryItem(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TelemetryItem)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(TelemetryItem)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + TelemetryItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TelemetryItem)} does not support writing '{format}' format."); + } if (Optional.IsDefined(Version)) { writer.WritePropertyName("ver"u8); @@ -46,6 +109,11 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) foreach (var item in Tags) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); @@ -53,17 +121,144 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) if (Optional.IsDefined(Data)) { writer.WritePropertyName("data"u8); - writer.WriteObjectValue(Data); + writer.WriteObjectValue(Data, options); + } + if (options.Format != "W" && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + 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(); } - /// Convert into a . - internal virtual RequestContent ToRequestContent() + /// The JSON reader. + /// The client options for reading and writing models. + TelemetryItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected virtual TelemetryItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); - return content; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TelemetryItem)} does not support reading '{format}' format."); + } + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTelemetryItem(document.RootElement, options); + } + + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static TelemetryItem DeserializeTelemetryItem(JsonElement element, ModelReaderWriterOptions options) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? version = default; + string name = default; + DateTimeOffset time = default; + float? sampleRate = default; + string sequence = default; + string instrumentationKey = default; + IDictionary tags = default; + MonitorBase data = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("ver"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + version = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("name"u8)) + { + name = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("time"u8)) + { + time = prop.Value.GetDateTimeOffset("O"); + continue; + } + if (prop.NameEquals("sampleRate"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + sampleRate = prop.Value.GetSingle(); + continue; + } + if (prop.NameEquals("seq"u8)) + { + sequence = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("iKey"u8)) + { + instrumentationKey = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("tags"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + tags = dictionary; + continue; + } + if (prop.NameEquals("data"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + data = MonitorBase.DeserializeMonitorBase(prop.Value, options); + continue; + } + if (options.Format != "W") + { + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + } + return new TelemetryItem( + version, + name, + time, + sampleRate, + sequence, + instrumentationKey, + tags ?? new ChangeTrackingDictionary(), + data, + additionalBinaryDataProperties); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryItem.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryItem.cs index f63f2cd3a8fc..0a90043e358e 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryItem.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TelemetryItem.cs @@ -7,35 +7,63 @@ using System; using System.Collections.Generic; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// System variables for a telemetry item. internal partial class TelemetryItem { + /// Keeps track of any properties unknown to the library. + private protected readonly IDictionary _additionalBinaryDataProperties; + /// Initializes a new instance of . /// Type name of telemetry data item. - /// Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. - /// is null. + /// + /// Event date time when telemetry item was created. This is the wall clock time on + /// the client when the event was generated. There is no guarantee that the + /// client's time is accurate. This field must be formatted in UTC ISO 8601 format, + /// with a trailing 'Z' character, as described publicly on + /// https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds + /// digits provided are variable (and unspecified). Consumers should handle this, + /// i.e. managed code consumers should not use format 'O' for parsing as it + /// specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. + /// public TelemetryItem(string name, DateTimeOffset time) { - Argument.AssertNotNull(name, nameof(name)); - Name = name; Time = time; Tags = new ChangeTrackingDictionary(); } /// Initializes a new instance of . - /// Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1. + /// + /// Envelope version. For internal use only. By assigning this the default, it will + /// not be serialized within the payload unless changed to a value other than #1. + /// /// Type name of telemetry data item. - /// Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. - /// Sampling rate used in application. This telemetry item represents 100 / sampleRate actual telemetry items. + /// + /// Event date time when telemetry item was created. This is the wall clock time on + /// the client when the event was generated. There is no guarantee that the + /// client's time is accurate. This field must be formatted in UTC ISO 8601 format, + /// with a trailing 'Z' character, as described publicly on + /// https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds + /// digits provided are variable (and unspecified). Consumers should handle this, + /// i.e. managed code consumers should not use format 'O' for parsing as it + /// specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. + /// + /// + /// Sampling rate used in application. This telemetry item represents 100 / + /// sampleRate actual telemetry items. + /// /// Sequence field used to track absolute order of uploaded events. /// The instrumentation key of the Application Insights resource. - /// Key/value collection of context properties. See ContextTagKeys for information on available properties. + /// + /// Key/value collection of context properties. See ContextTagKeys for information + /// on available properties. + /// /// Telemetry data item. - internal TelemetryItem(int? version, string name, DateTimeOffset time, float? sampleRate, string sequence, string instrumentationKey, IDictionary tags, MonitorBase data) + /// Keeps track of any properties unknown to the library. + internal TelemetryItem(int? version, string name, DateTimeOffset time, float? sampleRate, string sequence, string instrumentationKey, IDictionary tags, MonitorBase data, IDictionary additionalBinaryDataProperties) { Version = version; Name = name; @@ -45,22 +73,48 @@ internal TelemetryItem(int? version, string name, DateTimeOffset time, float? sa InstrumentationKey = instrumentationKey; Tags = tags; Data = data; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - /// Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1. + /// + /// Envelope version. For internal use only. By assigning this the default, it will + /// not be serialized within the payload unless changed to a value other than #1. + /// public int? Version { get; set; } + /// Type name of telemetry data item. public string Name { get; } - /// Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. + + /// + /// Event date time when telemetry item was created. This is the wall clock time on + /// the client when the event was generated. There is no guarantee that the + /// client's time is accurate. This field must be formatted in UTC ISO 8601 format, + /// with a trailing 'Z' character, as described publicly on + /// https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds + /// digits provided are variable (and unspecified). Consumers should handle this, + /// i.e. managed code consumers should not use format 'O' for parsing as it + /// specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. + /// public DateTimeOffset Time { get; } - /// Sampling rate used in application. This telemetry item represents 100 / sampleRate actual telemetry items. + + /// + /// Sampling rate used in application. This telemetry item represents 100 / + /// sampleRate actual telemetry items. + /// public float? SampleRate { get; set; } + /// Sequence field used to track absolute order of uploaded events. public string Sequence { get; set; } + /// The instrumentation key of the Application Insights resource. public string InstrumentationKey { get; set; } - /// Key/value collection of context properties. See ContextTagKeys for information on available properties. + + /// + /// Key/value collection of context properties. See ContextTagKeys for information + /// on available properties. + /// public IDictionary Tags { get; } + /// Telemetry data item. public MonitorBase Data { get; set; } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TrackResponse.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TrackResponse.Serialization.cs index 23112b4c63db..ede4fcb6be61 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TrackResponse.Serialization.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TrackResponse.Serialization.cs @@ -5,14 +5,139 @@ #nullable disable +using System; +using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - internal partial class TrackResponse + internal partial class TrackResponse : IJsonModel { - internal static TrackResponse DeserializeTrackResponse(JsonElement element) + /// The data to parse. + /// The client options for reading and writing models. + protected virtual TrackResponse PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeTrackResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TrackResponse)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(TrackResponse)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + TrackResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The to deserialize the from. + public static explicit operator TrackResponse(Response response) + { + using JsonDocument document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTrackResponse(document.RootElement, ModelSerializationExtensions.WireOptions); + } + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TrackResponse)} does not support writing '{format}' format."); + } + if (Optional.IsDefined(ItemsReceived)) + { + writer.WritePropertyName("itemsReceived"u8); + writer.WriteNumberValue(ItemsReceived.Value); + } + if (Optional.IsDefined(ItemsAccepted)) + { + writer.WritePropertyName("itemsAccepted"u8); + writer.WriteNumberValue(ItemsAccepted.Value); + } + if (Optional.IsCollectionDefined(Errors)) + { + writer.WritePropertyName("errors"u8); + writer.WriteStartArray(); + foreach (TelemetryErrorDetails item in Errors) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + 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 + } + } + } + + /// The JSON reader. + /// The client options for reading and writing models. + TrackResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected virtual TrackResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TrackResponse)} does not support reading '{format}' format."); + } + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTrackResponse(document.RootElement, options); + } + + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static TrackResponse DeserializeTrackResponse(JsonElement element, ModelReaderWriterOptions options) { if (element.ValueKind == JsonValueKind.Null) { @@ -20,51 +145,48 @@ internal static TrackResponse DeserializeTrackResponse(JsonElement element) } int? itemsReceived = default; int? itemsAccepted = default; - IReadOnlyList errors = default; - foreach (var property in element.EnumerateObject()) + IList errors = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("itemsReceived"u8)) + if (prop.NameEquals("itemsReceived"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - itemsReceived = property.Value.GetInt32(); + itemsReceived = prop.Value.GetInt32(); continue; } - if (property.NameEquals("itemsAccepted"u8)) + if (prop.NameEquals("itemsAccepted"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - itemsAccepted = property.Value.GetInt32(); + itemsAccepted = prop.Value.GetInt32(); continue; } - if (property.NameEquals("errors"u8)) + if (prop.NameEquals("errors"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(TelemetryErrorDetails.DeserializeTelemetryErrorDetails(item)); + array.Add(TelemetryErrorDetails.DeserializeTelemetryErrorDetails(item, options)); } errors = array; continue; } + if (options.Format != "W") + { + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } } - return new TrackResponse(itemsReceived, itemsAccepted, errors ?? new ChangeTrackingList()); - } - - /// Deserializes the model from a raw response. - /// The response to deserialize the model from. - internal static TrackResponse FromResponse(Response response) - { - using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTrackResponse(document.RootElement); + return new TrackResponse(itemsReceived, itemsAccepted, errors ?? new ChangeTrackingList(), additionalBinaryDataProperties); } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TrackResponse.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TrackResponse.cs index 8d606d234f33..5dc48d1ea34e 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TrackResponse.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/TrackResponse.cs @@ -5,13 +5,17 @@ #nullable disable +using System; using System.Collections.Generic; +using Azure.Monitor.OpenTelemetry.Exporter; namespace Azure.Monitor.OpenTelemetry.Exporter.Models { - /// Response containing the status of each telemetry item. internal partial class TrackResponse { + /// Keeps track of any properties unknown to the library. + private protected readonly IDictionary _additionalBinaryDataProperties; + /// Initializes a new instance of . internal TrackResponse() { @@ -22,18 +26,22 @@ internal TrackResponse() /// The number of items received. /// The number of items accepted. /// An array of error detail objects. - internal TrackResponse(int? itemsReceived, int? itemsAccepted, IReadOnlyList errors) + /// Keeps track of any properties unknown to the library. + internal TrackResponse(int? itemsReceived, int? itemsAccepted, IList errors, IDictionary additionalBinaryDataProperties) { ItemsReceived = itemsReceived; ItemsAccepted = itemsAccepted; Errors = errors; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } /// The number of items received. public int? ItemsReceived { get; } + /// The number of items accepted. public int? ItemsAccepted { get; } + /// An array of error detail objects. - public IReadOnlyList Errors { get; } + public IList Errors { get; } } } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/UnknownMonitorDomain.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/UnknownMonitorDomain.Serialization.cs new file mode 100644 index 000000000000..efba6009c16c --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/UnknownMonitorDomain.Serialization.cs @@ -0,0 +1,129 @@ +// 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.Monitor.OpenTelemetry.Exporter; + +namespace Azure.Monitor.OpenTelemetry.Exporter.Models +{ + internal partial class UnknownMonitorDomain : MonitorDomain, IJsonModel + { + /// Initializes a new instance of for deserialization. + internal UnknownMonitorDomain() + { + } + + /// The data to parse. + /// The client options for reading and writing models. + protected override MonitorDomain PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) + { + return DeserializeMonitorDomain(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MonitorDomain)} does not support reading '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options, AzureMonitorOpenTelemetryExporterContext.Default); + default: + throw new FormatException($"The model {nameof(MonitorDomain)} does not support writing '{options.Format}' format."); + } + } + + /// The client options for reading and writing models. + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + /// The data to parse. + /// The client options for reading and writing models. + MonitorDomain IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + + /// The client options for reading and writing models. + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// The JSON writer. + /// The client options for reading and writing models. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MonitorDomain)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + } + + /// The JSON reader. + /// The client options for reading and writing models. + MonitorDomain IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + /// The JSON reader. + /// The client options for reading and writing models. + protected override MonitorDomain JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MonitorDomain)} does not support reading '{format}' format."); + } + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMonitorDomain(document.RootElement, options); + } + + /// The JSON element to deserialize. + /// The client options for reading and writing models. + internal static UnknownMonitorDomain DeserializeUnknownMonitorDomain(JsonElement element, ModelReaderWriterOptions options) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int version = default; + MonitorDomainKind kind = default; + IDictionary additionalProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("ver"u8)) + { + version = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("kind"u8)) + { + kind = new MonitorDomainKind(prop.Value.GetString()); + continue; + } + additionalProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + return new UnknownMonitorDomain(version, kind, additionalProperties); + } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/UnknownMonitorDomain.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/UnknownMonitorDomain.cs new file mode 100644 index 000000000000..d57fb732419b --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Generated/Models/UnknownMonitorDomain.cs @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Monitor.OpenTelemetry.Exporter.Models +{ + internal partial class UnknownMonitorDomain : MonitorDomain + { + /// Initializes a new instance of . + /// Schema version. + /// Discriminator property to identify the specific telemetry data type. + /// + internal UnknownMonitorDomain(int version, MonitorDomainKind kind, IDictionary additionalProperties) : base(version, kind != default ? kind : "unknown", additionalProperties) + { + } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/HttpPipelineHelper.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/HttpPipelineHelper.cs index 775e50ff5cab..4296a3ec3506 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/HttpPipelineHelper.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/HttpPipelineHelper.cs @@ -62,7 +62,7 @@ internal static bool TryGetTrackResponse(HttpMessage message, [NotNullWhen(true) using (JsonDocument document = JsonDocument.Parse(message.Response.ContentStream, default)) { - var value = TrackResponse.DeserializeTrackResponse(document.RootElement); + var value = TrackResponse.DeserializeTrackResponse(document.RootElement, ModelSerializationExtensions.WireOptions); trackResponse = Response.FromValue(value, message.Response); return true; } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/autorest.md b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/autorest.md deleted file mode 100644 index 284af6d1beca..000000000000 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/autorest.md +++ /dev/null @@ -1,17 +0,0 @@ -# Generated code configuration - -Run `dotnet build /t:GenerateCode` to generate code. - -``` yaml -input-file: - - https://raw.githubusercontent.com/Azure/azure-rest-api-specs/1be09531e4c6edeafde41d6562371566d39669e8/specification/applicationinsights/data-plane/Monitor.Exporters/preview/v2.1/swagger.json -generation1-convenience-client: true -``` - -``` yaml -directive: -- from: swagger-document - where: $.definitions.* - transform: > - $["x-accessibility"]="internal" -``` diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Tests/AzureMonitorTraceExporterTests.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Tests/AzureMonitorTraceExporterTests.cs index b013333200f3..f653d05d4b44 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Tests/AzureMonitorTraceExporterTests.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Tests/AzureMonitorTraceExporterTests.cs @@ -68,7 +68,7 @@ private void GetInternalFields(AzureMonitorTraceExporter exporter, out string? i ?.GetValue(transmitter); endpoint = typeof(ApplicationInsightsRestClient) - .GetField("_host", BindingFlags.Instance | BindingFlags.NonPublic) + .GetField("_endpoint", BindingFlags.Instance | BindingFlags.NonPublic) ?.GetValue(serviceRestClient) ?.ToString(); } diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tsp-location.yaml b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tsp-location.yaml new file mode 100644 index 000000000000..eee263e49331 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tsp-location.yaml @@ -0,0 +1,5 @@ +repo: Azure/azure-rest-api-specs +commit: 920cec210ff8f80419ada3775f64b1950d915f51 +directory: specification/applicationinsights/data-plane/Exporters +emitterPackageJsonPath: eng/azure-typespec-http-client-csharp-emitter-package.json +entrypointFile: client.tsp