diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/LiveMetrics.sln b/sdk/applicationinsights.livemetrics/LiveMetrics/LiveMetrics.sln new file mode 100644 index 000000000000..202d00182aa1 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/LiveMetrics.sln @@ -0,0 +1,50 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LiveMetrics", "src\LiveMetrics.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LiveMetrics.Tests", "tests\LiveMetrics.Tests.csproj", "{1F1CD1D4-9932-4B73-99D8-C252A67D4B46}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.Build.0 = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.Build.0 = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.Build.0 = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.Build.0 = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.Build.0 = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.Build.0 = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.ActiveCfg = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.Build.0 = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A97F4B90-2591-4689-B1F8-5F21FE6D6CAE} + EndGlobalSection +EndGlobal diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/AggregationType.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/AggregationType.cs new file mode 100644 index 000000000000..f785f0dec7ee --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/AggregationType.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace LiveMetrics +{ + /// Aggregation type. + public readonly partial struct AggregationType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AggregationType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AvgValue = "Avg"; + private const string SumValue = "Sum"; + private const string MinValue = "Min"; + private const string MaxValue = "Max"; + + /// Average. + public static AggregationType Avg { get; } = new AggregationType(AvgValue); + /// Sum. + public static AggregationType Sum { get; } = new AggregationType(SumValue); + /// Minimum. + public static AggregationType Min { get; } = new AggregationType(MinValue); + /// Maximum. + public static AggregationType Max { get; } = new AggregationType(MaxValue); + /// Determines if two values are the same. + public static bool operator ==(AggregationType left, AggregationType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AggregationType left, AggregationType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AggregationType(string value) => new AggregationType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AggregationType other && Equals(other); + /// + public bool Equals(AggregationType 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/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationError.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationError.Serialization.cs new file mode 100644 index 000000000000..a359ba3fd714 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationError.Serialization.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class CollectionConfigurationError : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CollectionConfigurationError)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("CollectionConfigurationErrorType"u8); + writer.WriteStringValue(CollectionConfigurationErrorType.ToString()); + writer.WritePropertyName("Message"u8); + writer.WriteStringValue(Message); + writer.WritePropertyName("FullException"u8); + writer.WriteStringValue(FullException); + writer.WritePropertyName("Data"u8); + writer.WriteStartArray(); + foreach (var item in Data) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + CollectionConfigurationError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CollectionConfigurationError)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCollectionConfigurationError(document.RootElement, options); + } + + internal static CollectionConfigurationError DeserializeCollectionConfigurationError(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + CollectionConfigurationErrorType collectionConfigurationErrorType = default; + string message = default; + string fullException = default; + IList data = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("CollectionConfigurationErrorType"u8)) + { + collectionConfigurationErrorType = new CollectionConfigurationErrorType(property.Value.GetString()); + continue; + } + if (property.NameEquals("Message"u8)) + { + message = property.Value.GetString(); + continue; + } + if (property.NameEquals("FullException"u8)) + { + fullException = property.Value.GetString(); + continue; + } + if (property.NameEquals("Data"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + data = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CollectionConfigurationError(collectionConfigurationErrorType, message, fullException, data, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CollectionConfigurationError)} does not support writing '{options.Format}' format."); + } + } + + CollectionConfigurationError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeCollectionConfigurationError(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CollectionConfigurationError)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CollectionConfigurationError FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCollectionConfigurationError(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationError.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationError.cs new file mode 100644 index 000000000000..2c827786fc4b --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationError.cs @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + /// Represents an error while SDK parses and applies an instance of CollectionConfigurationInfo. + public partial class CollectionConfigurationError + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Error type. + /// Error message. + /// Exception that led to the creation of the configuration error. + /// Custom properties to add more information to the error. + /// , or is null. + public CollectionConfigurationError(CollectionConfigurationErrorType collectionConfigurationErrorType, string message, string fullException, IEnumerable data) + { + Argument.AssertNotNull(message, nameof(message)); + Argument.AssertNotNull(fullException, nameof(fullException)); + Argument.AssertNotNull(data, nameof(data)); + + CollectionConfigurationErrorType = collectionConfigurationErrorType; + Message = message; + FullException = fullException; + Data = data.ToList(); + } + + /// Initializes a new instance of . + /// Error type. + /// Error message. + /// Exception that led to the creation of the configuration error. + /// Custom properties to add more information to the error. + /// Keeps track of any properties unknown to the library. + internal CollectionConfigurationError(CollectionConfigurationErrorType collectionConfigurationErrorType, string message, string fullException, IList data, IDictionary serializedAdditionalRawData) + { + CollectionConfigurationErrorType = collectionConfigurationErrorType; + Message = message; + FullException = fullException; + Data = data; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CollectionConfigurationError() + { + } + + /// Error type. + public CollectionConfigurationErrorType CollectionConfigurationErrorType { get; } + /// Error message. + public string Message { get; } + /// Exception that led to the creation of the configuration error. + public string FullException { get; } + /// Custom properties to add more information to the error. + public IList Data { get; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationErrorType.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationErrorType.cs new file mode 100644 index 000000000000..9e116938866b --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationErrorType.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace LiveMetrics +{ + /// Collection configuration error type reported by the client SDK. + public readonly partial struct CollectionConfigurationErrorType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public CollectionConfigurationErrorType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UnknownValue = "Unknown"; + private const string PerformanceCounterParsingValue = "PerformanceCounterParsing"; + private const string PerformanceCounterUnexpectedValue = "PerformanceCounterUnexpected"; + private const string PerformanceCounterDuplicateIdsValue = "PerformanceCounterDuplicateIds"; + private const string DocumentStreamDuplicateIdsValue = "DocumentStreamDuplicateIds"; + private const string DocumentStreamFailureToCreateValue = "DocumentStreamFailureToCreate"; + private const string DocumentStreamFailureToCreateFilterUnexpectedValue = "DocumentStreamFailureToCreateFilterUnexpected"; + private const string MetricDuplicateIdsValue = "MetricDuplicateIds"; + private const string MetricTelemetryTypeUnsupportedValue = "MetricTelemetryTypeUnsupported"; + private const string MetricFailureToCreateValue = "MetricFailureToCreate"; + private const string MetricFailureToCreateFilterUnexpectedValue = "MetricFailureToCreateFilterUnexpected"; + private const string FilterFailureToCreateUnexpectedValue = "FilterFailureToCreateUnexpected"; + private const string CollectionConfigurationFailureToCreateUnexpectedValue = "CollectionConfigurationFailureToCreateUnexpected"; + + /// Unknown error type. + public static CollectionConfigurationErrorType Unknown { get; } = new CollectionConfigurationErrorType(UnknownValue); + /// Performance counter parsing error. + public static CollectionConfigurationErrorType PerformanceCounterParsing { get; } = new CollectionConfigurationErrorType(PerformanceCounterParsingValue); + /// Performance counter unexpected error. + public static CollectionConfigurationErrorType PerformanceCounterUnexpected { get; } = new CollectionConfigurationErrorType(PerformanceCounterUnexpectedValue); + /// Performance counter duplicate ids. + public static CollectionConfigurationErrorType PerformanceCounterDuplicateIds { get; } = new CollectionConfigurationErrorType(PerformanceCounterDuplicateIdsValue); + /// Document stream duplication ids. + public static CollectionConfigurationErrorType DocumentStreamDuplicateIds { get; } = new CollectionConfigurationErrorType(DocumentStreamDuplicateIdsValue); + /// Document stream failed to create. + public static CollectionConfigurationErrorType DocumentStreamFailureToCreate { get; } = new CollectionConfigurationErrorType(DocumentStreamFailureToCreateValue); + /// Document stream failed to create filter unexpectedly. + public static CollectionConfigurationErrorType DocumentStreamFailureToCreateFilterUnexpected { get; } = new CollectionConfigurationErrorType(DocumentStreamFailureToCreateFilterUnexpectedValue); + /// Metric duplicate ids. + public static CollectionConfigurationErrorType MetricDuplicateIds { get; } = new CollectionConfigurationErrorType(MetricDuplicateIdsValue); + /// Metric telemetry type unsupported. + public static CollectionConfigurationErrorType MetricTelemetryTypeUnsupported { get; } = new CollectionConfigurationErrorType(MetricTelemetryTypeUnsupportedValue); + /// Metric failed to create. + public static CollectionConfigurationErrorType MetricFailureToCreate { get; } = new CollectionConfigurationErrorType(MetricFailureToCreateValue); + /// Metric failed to create filter unexpectedly. + public static CollectionConfigurationErrorType MetricFailureToCreateFilterUnexpected { get; } = new CollectionConfigurationErrorType(MetricFailureToCreateFilterUnexpectedValue); + /// Filter failed to create unexpectedly. + public static CollectionConfigurationErrorType FilterFailureToCreateUnexpected { get; } = new CollectionConfigurationErrorType(FilterFailureToCreateUnexpectedValue); + /// Collection configuration failed to create unexpectedly. + public static CollectionConfigurationErrorType CollectionConfigurationFailureToCreateUnexpected { get; } = new CollectionConfigurationErrorType(CollectionConfigurationFailureToCreateUnexpectedValue); + /// Determines if two values are the same. + public static bool operator ==(CollectionConfigurationErrorType left, CollectionConfigurationErrorType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(CollectionConfigurationErrorType left, CollectionConfigurationErrorType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator CollectionConfigurationErrorType(string value) => new CollectionConfigurationErrorType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is CollectionConfigurationErrorType other && Equals(other); + /// + public bool Equals(CollectionConfigurationErrorType 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/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationInfo.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationInfo.Serialization.cs new file mode 100644 index 000000000000..48593c5c360f --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationInfo.Serialization.cs @@ -0,0 +1,187 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class CollectionConfigurationInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CollectionConfigurationInfo)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("ETag"u8); + writer.WriteStringValue(ETag); + writer.WritePropertyName("Metrics"u8); + writer.WriteStartArray(); + foreach (var item in Metrics) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + writer.WritePropertyName("DocumentStreams"u8); + writer.WriteStartArray(); + foreach (var item in DocumentStreams) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (Optional.IsDefined(QuotaInfo)) + { + writer.WritePropertyName("QuotaInfo"u8); + writer.WriteObjectValue(QuotaInfo, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + CollectionConfigurationInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CollectionConfigurationInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCollectionConfigurationInfo(document.RootElement, options); + } + + internal static CollectionConfigurationInfo DeserializeCollectionConfigurationInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string eTag = default; + IReadOnlyList metrics = default; + IReadOnlyList documentStreams = default; + QuotaConfigurationInfo quotaInfo = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("ETag"u8)) + { + eTag = property.Value.GetString(); + continue; + } + if (property.NameEquals("Metrics"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(DerivedMetricInfo.DeserializeDerivedMetricInfo(item, options)); + } + metrics = array; + continue; + } + if (property.NameEquals("DocumentStreams"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(DocumentStreamInfo.DeserializeDocumentStreamInfo(item, options)); + } + documentStreams = array; + continue; + } + if (property.NameEquals("QuotaInfo"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + quotaInfo = QuotaConfigurationInfo.DeserializeQuotaConfigurationInfo(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CollectionConfigurationInfo(eTag, metrics, documentStreams, quotaInfo, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CollectionConfigurationInfo)} does not support writing '{options.Format}' format."); + } + } + + CollectionConfigurationInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeCollectionConfigurationInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CollectionConfigurationInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CollectionConfigurationInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCollectionConfigurationInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationInfo.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationInfo.cs new file mode 100644 index 000000000000..2202b8fcc18b --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/CollectionConfigurationInfo.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + /// Represents the collection configuration - a customizable description of performance counters, metrics, and full telemetry documents to be collected by the client SDK. + public partial class CollectionConfigurationInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// An encoded string that indicates whether the collection configuration is changed. + /// An array of metric configuration info. + /// An array of document stream configuration info. + /// , or is null. + internal CollectionConfigurationInfo(string eTag, IEnumerable metrics, IEnumerable documentStreams) + { + Argument.AssertNotNull(eTag, nameof(eTag)); + Argument.AssertNotNull(metrics, nameof(metrics)); + Argument.AssertNotNull(documentStreams, nameof(documentStreams)); + + ETag = eTag; + Metrics = metrics.ToList(); + DocumentStreams = documentStreams.ToList(); + } + + /// Initializes a new instance of . + /// An encoded string that indicates whether the collection configuration is changed. + /// An array of metric configuration info. + /// An array of document stream configuration info. + /// Controls document quotas to be sent to Live Metrics. + /// Keeps track of any properties unknown to the library. + internal CollectionConfigurationInfo(string eTag, IReadOnlyList metrics, IReadOnlyList documentStreams, QuotaConfigurationInfo quotaInfo, IDictionary serializedAdditionalRawData) + { + ETag = eTag; + Metrics = metrics; + DocumentStreams = documentStreams; + QuotaInfo = quotaInfo; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CollectionConfigurationInfo() + { + } + + /// An encoded string that indicates whether the collection configuration is changed. + public string ETag { get; } + /// An array of metric configuration info. + public IReadOnlyList Metrics { get; } + /// An array of document stream configuration info. + public IReadOnlyList DocumentStreams { get; } + /// Controls document quotas to be sent to Live Metrics. + public QuotaConfigurationInfo QuotaInfo { get; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DerivedMetricInfo.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DerivedMetricInfo.Serialization.cs new file mode 100644 index 000000000000..17baa33a86a4 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DerivedMetricInfo.Serialization.cs @@ -0,0 +1,193 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class DerivedMetricInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DerivedMetricInfo)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("Id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("TelemetryType"u8); + writer.WriteStringValue(TelemetryType); + writer.WritePropertyName("FilterGroups"u8); + writer.WriteStartArray(); + foreach (var item in FilterGroups) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + writer.WritePropertyName("Projection"u8); + writer.WriteStringValue(Projection); + writer.WritePropertyName("Aggregation"u8); + writer.WriteStringValue(Aggregation.ToString()); + writer.WritePropertyName("BackEndAggregation"u8); + writer.WriteStringValue(BackEndAggregation.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + DerivedMetricInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DerivedMetricInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDerivedMetricInfo(document.RootElement, options); + } + + internal static DerivedMetricInfo DeserializeDerivedMetricInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + string telemetryType = default; + IReadOnlyList filterGroups = default; + string projection = default; + AggregationType aggregation = default; + AggregationType backEndAggregation = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("TelemetryType"u8)) + { + telemetryType = property.Value.GetString(); + continue; + } + if (property.NameEquals("FilterGroups"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(FilterConjunctionGroupInfo.DeserializeFilterConjunctionGroupInfo(item, options)); + } + filterGroups = array; + continue; + } + if (property.NameEquals("Projection"u8)) + { + projection = property.Value.GetString(); + continue; + } + if (property.NameEquals("Aggregation"u8)) + { + aggregation = new AggregationType(property.Value.GetString()); + continue; + } + if (property.NameEquals("BackEndAggregation"u8)) + { + backEndAggregation = new AggregationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new DerivedMetricInfo( + id, + telemetryType, + filterGroups, + projection, + aggregation, + backEndAggregation, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(DerivedMetricInfo)} does not support writing '{options.Format}' format."); + } + } + + DerivedMetricInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeDerivedMetricInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DerivedMetricInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DerivedMetricInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeDerivedMetricInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DerivedMetricInfo.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DerivedMetricInfo.cs new file mode 100644 index 000000000000..bf65e8969c59 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DerivedMetricInfo.cs @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + /// A metric configuration set by UX to scope the metrics it's interested in. + public partial class DerivedMetricInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// metric configuration identifier. + /// Telemetry type. + /// A collection of filters to scope metrics that UX needs. + /// Telemetry's metric dimension whose value is to be aggregated. Example values: Duration, Count(),... + /// Aggregation type. This is the aggregation done from everything within a single server. + /// Aggregation type. This Aggregation is done across the values for all the servers taken together. + /// , , or is null. + internal DerivedMetricInfo(string id, string telemetryType, IEnumerable filterGroups, string projection, AggregationType aggregation, AggregationType backEndAggregation) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(telemetryType, nameof(telemetryType)); + Argument.AssertNotNull(filterGroups, nameof(filterGroups)); + Argument.AssertNotNull(projection, nameof(projection)); + + Id = id; + TelemetryType = telemetryType; + FilterGroups = filterGroups.ToList(); + Projection = projection; + Aggregation = aggregation; + BackEndAggregation = backEndAggregation; + } + + /// Initializes a new instance of . + /// metric configuration identifier. + /// Telemetry type. + /// A collection of filters to scope metrics that UX needs. + /// Telemetry's metric dimension whose value is to be aggregated. Example values: Duration, Count(),... + /// Aggregation type. This is the aggregation done from everything within a single server. + /// Aggregation type. This Aggregation is done across the values for all the servers taken together. + /// Keeps track of any properties unknown to the library. + internal DerivedMetricInfo(string id, string telemetryType, IReadOnlyList filterGroups, string projection, AggregationType aggregation, AggregationType backEndAggregation, IDictionary serializedAdditionalRawData) + { + Id = id; + TelemetryType = telemetryType; + FilterGroups = filterGroups; + Projection = projection; + Aggregation = aggregation; + BackEndAggregation = backEndAggregation; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal DerivedMetricInfo() + { + } + + /// metric configuration identifier. + public string Id { get; } + /// Telemetry type. + public string TelemetryType { get; } + /// A collection of filters to scope metrics that UX needs. + public IReadOnlyList FilterGroups { get; } + /// Telemetry's metric dimension whose value is to be aggregated. Example values: Duration, Count(),... + public string Projection { get; } + /// Aggregation type. This is the aggregation done from everything within a single server. + public AggregationType Aggregation { get; } + /// Aggregation type. This Aggregation is done across the values for all the servers taken together. + public AggregationType BackEndAggregation { get; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Docs/LiveMetricsClient.xml b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Docs/LiveMetricsClient.xml new file mode 100644 index 000000000000..d20fe9db0cf7 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Docs/LiveMetricsClient.xml @@ -0,0 +1,439 @@ + + + + + +This sample shows how to call IsSubscribedAsync. + response = await client.IsSubscribedAsync("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); +]]> + + + +This sample shows how to call IsSubscribed. + response = client.IsSubscribed("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); +]]> + + + +This sample shows how to call IsSubscribedAsync and parse the result. + + + + +This sample shows how to call IsSubscribed and parse the result. + + + + +This sample shows how to call PublishAsync. + response = await client.PublishAsync("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); +]]> + + + +This sample shows how to call Publish. + response = client.Publish("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); +]]> + + + +This sample shows how to call PublishAsync and parse the result. + + + + +This sample shows how to call Publish and parse the result. + + + + \ No newline at end of file diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.Serialization.cs new file mode 100644 index 000000000000..e7de6a3e4334 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.Serialization.cs @@ -0,0 +1,144 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class DocumentFilterConjunctionGroupInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentFilterConjunctionGroupInfo)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("TelemetryType"u8); + writer.WriteStringValue(TelemetryType.ToString()); + writer.WritePropertyName("Filters"u8); + writer.WriteObjectValue(Filters, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + DocumentFilterConjunctionGroupInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentFilterConjunctionGroupInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDocumentFilterConjunctionGroupInfo(document.RootElement, options); + } + + internal static DocumentFilterConjunctionGroupInfo DeserializeDocumentFilterConjunctionGroupInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + TelemetryType telemetryType = default; + FilterConjunctionGroupInfo filters = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("TelemetryType"u8)) + { + telemetryType = new TelemetryType(property.Value.GetString()); + continue; + } + if (property.NameEquals("Filters"u8)) + { + filters = FilterConjunctionGroupInfo.DeserializeFilterConjunctionGroupInfo(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new DocumentFilterConjunctionGroupInfo(telemetryType, filters, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(DocumentFilterConjunctionGroupInfo)} does not support writing '{options.Format}' format."); + } + } + + DocumentFilterConjunctionGroupInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeDocumentFilterConjunctionGroupInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DocumentFilterConjunctionGroupInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DocumentFilterConjunctionGroupInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeDocumentFilterConjunctionGroupInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.cs new file mode 100644 index 000000000000..ab47aa5a5a85 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// A collection of filters for a specific telemetry type. + public partial class DocumentFilterConjunctionGroupInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Telemetry type. + /// An array of filter groups. + /// is null. + internal DocumentFilterConjunctionGroupInfo(TelemetryType telemetryType, FilterConjunctionGroupInfo filters) + { + Argument.AssertNotNull(filters, nameof(filters)); + + TelemetryType = telemetryType; + Filters = filters; + } + + /// Initializes a new instance of . + /// Telemetry type. + /// An array of filter groups. + /// Keeps track of any properties unknown to the library. + internal DocumentFilterConjunctionGroupInfo(TelemetryType telemetryType, FilterConjunctionGroupInfo filters, IDictionary serializedAdditionalRawData) + { + TelemetryType = telemetryType; + Filters = filters; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal DocumentFilterConjunctionGroupInfo() + { + } + + /// Telemetry type. + public TelemetryType TelemetryType { get; } + /// An array of filter groups. + public FilterConjunctionGroupInfo Filters { get; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentIngress.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentIngress.Serialization.cs new file mode 100644 index 000000000000..1be02faa164f --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentIngress.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + [PersistableModelProxy(typeof(UnknownDocumentIngress))] + public partial class DocumentIngress : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentIngress)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("DocumentType"u8); + writer.WriteStringValue(DocumentType.ToString()); + if (Optional.IsCollectionDefined(DocumentStreamIds)) + { + writer.WritePropertyName("DocumentStreamIds"u8); + writer.WriteStartArray(); + foreach (var item in DocumentStreamIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Properties)) + { + writer.WritePropertyName("Properties"u8); + writer.WriteStartArray(); + foreach (var item in Properties) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + DocumentIngress IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentIngress)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDocumentIngress(document.RootElement, options); + } + + internal static DocumentIngress DeserializeDocumentIngress(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("DocumentType", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "Event": return Event.DeserializeEvent(element, options); + case "Exception": return Exception.DeserializeException(element, options); + case "RemoteDependency": return RemoteDependency.DeserializeRemoteDependency(element, options); + case "Request": return Request.DeserializeRequest(element, options); + case "Trace": return Trace.DeserializeTrace(element, options); + } + } + return UnknownDocumentIngress.DeserializeUnknownDocumentIngress(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(DocumentIngress)} does not support writing '{options.Format}' format."); + } + } + + DocumentIngress IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeDocumentIngress(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DocumentIngress)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DocumentIngress FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeDocumentIngress(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentIngress.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentIngress.cs new file mode 100644 index 000000000000..495a1ba03e02 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentIngress.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// + /// Base class of the specific document types. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + public abstract partial class DocumentIngress + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected DocumentIngress() + { + DocumentStreamIds = new ChangeTrackingList(); + Properties = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + internal DocumentIngress(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData) + { + DocumentType = documentType; + DocumentStreamIds = documentStreamIds; + Properties = properties; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + internal DocumentType DocumentType { get; set; } + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + public IList DocumentStreamIds { get; } + /// Collection of custom properties. + public IList Properties { get; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentStreamInfo.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentStreamInfo.Serialization.cs new file mode 100644 index 000000000000..aa75dce40ded --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentStreamInfo.Serialization.cs @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class DocumentStreamInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentStreamInfo)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("Id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("DocumentFilterGroups"u8); + writer.WriteStartArray(); + foreach (var item in DocumentFilterGroups) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + DocumentStreamInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentStreamInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDocumentStreamInfo(document.RootElement, options); + } + + internal static DocumentStreamInfo DeserializeDocumentStreamInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + IReadOnlyList documentFilterGroups = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("DocumentFilterGroups"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(DocumentFilterConjunctionGroupInfo.DeserializeDocumentFilterConjunctionGroupInfo(item, options)); + } + documentFilterGroups = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new DocumentStreamInfo(id, documentFilterGroups, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(DocumentStreamInfo)} does not support writing '{options.Format}' format."); + } + } + + DocumentStreamInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeDocumentStreamInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DocumentStreamInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DocumentStreamInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeDocumentStreamInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentStreamInfo.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentStreamInfo.cs new file mode 100644 index 000000000000..02101af6454e --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentStreamInfo.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + /// Configurations/filters set by UX to scope the document/telemetry it's interested in. + public partial class DocumentStreamInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Identifier of the document stream initiated by a UX. + /// Gets or sets an OR-connected collection of filter groups. + /// or is null. + internal DocumentStreamInfo(string id, IEnumerable documentFilterGroups) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(documentFilterGroups, nameof(documentFilterGroups)); + + Id = id; + DocumentFilterGroups = documentFilterGroups.ToList(); + } + + /// Initializes a new instance of . + /// Identifier of the document stream initiated by a UX. + /// Gets or sets an OR-connected collection of filter groups. + /// Keeps track of any properties unknown to the library. + internal DocumentStreamInfo(string id, IReadOnlyList documentFilterGroups, IDictionary serializedAdditionalRawData) + { + Id = id; + DocumentFilterGroups = documentFilterGroups; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal DocumentStreamInfo() + { + } + + /// Identifier of the document stream initiated by a UX. + public string Id { get; } + /// Gets or sets an OR-connected collection of filter groups. + public IReadOnlyList DocumentFilterGroups { get; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentType.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentType.cs new file mode 100644 index 000000000000..d0eec283fbcf --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/DocumentType.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace LiveMetrics +{ + /// Document type. + internal readonly partial struct DocumentType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public DocumentType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string RequestValue = "Request"; + private const string RemoteDependencyValue = "RemoteDependency"; + private const string ExceptionValue = "Exception"; + private const string EventValue = "Event"; + private const string TraceValue = "Trace"; + private const string UnknownValue = "Unknown"; + + /// Represents a request telemetry type. + public static DocumentType Request { get; } = new DocumentType(RequestValue); + /// Represents a remote dependency telemetry type. + public static DocumentType RemoteDependency { get; } = new DocumentType(RemoteDependencyValue); + /// Represents an exception telemetry type. + public static DocumentType Exception { get; } = new DocumentType(ExceptionValue); + /// Represents an event telemetry type. + public static DocumentType Event { get; } = new DocumentType(EventValue); + /// Represents a trace telemetry type. + public static DocumentType Trace { get; } = new DocumentType(TraceValue); + /// Represents an unknown telemetry type. + public static DocumentType Unknown { get; } = new DocumentType(UnknownValue); + /// Determines if two values are the same. + public static bool operator ==(DocumentType left, DocumentType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(DocumentType left, DocumentType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator DocumentType(string value) => new DocumentType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is DocumentType other && Equals(other); + /// + public bool Equals(DocumentType 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/applicationinsights.livemetrics/LiveMetrics/src/Generated/Event.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Event.Serialization.cs new file mode 100644 index 000000000000..e5129532dcdb --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Event.Serialization.cs @@ -0,0 +1,197 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class Event : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Event)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("Name"u8); + writer.WriteStringValue(Name); + } + writer.WritePropertyName("DocumentType"u8); + writer.WriteStringValue(DocumentType.ToString()); + if (Optional.IsCollectionDefined(DocumentStreamIds)) + { + writer.WritePropertyName("DocumentStreamIds"u8); + writer.WriteStartArray(); + foreach (var item in DocumentStreamIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Properties)) + { + writer.WritePropertyName("Properties"u8); + writer.WriteStartArray(); + foreach (var item in Properties) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + Event IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Event)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEvent(document.RootElement, options); + } + + internal static Event DeserializeEvent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + DocumentType documentType = default; + IList documentStreamIds = default; + IList properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("DocumentType"u8)) + { + documentType = new DocumentType(property.Value.GetString()); + continue; + } + if (property.NameEquals("DocumentStreamIds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + documentStreamIds = array; + continue; + } + if (property.NameEquals("Properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + properties = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Event(documentType, documentStreamIds ?? new ChangeTrackingList(), properties ?? new ChangeTrackingList(), serializedAdditionalRawData, name); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Event)} does not support writing '{options.Format}' format."); + } + } + + Event IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeEvent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Event)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new Event FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeEvent(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Event.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Event.cs new file mode 100644 index 000000000000..ac0ba2ec5b66 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Event.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Event document type. + public partial class Event : DocumentIngress + { + /// Initializes a new instance of . + public Event() + { + DocumentType = DocumentType.Event; + } + + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + /// Event name. + internal Event(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData, string name) : base(documentType, documentStreamIds, properties, serializedAdditionalRawData) + { + Name = name; + } + + /// Event name. + public string Name { get; set; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Exception.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Exception.Serialization.cs new file mode 100644 index 000000000000..d4166a6a8d44 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Exception.Serialization.cs @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class Exception : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Exception)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(ExceptionType)) + { + writer.WritePropertyName("ExceptionType"u8); + writer.WriteStringValue(ExceptionType); + } + if (Optional.IsDefined(ExceptionMessage)) + { + writer.WritePropertyName("ExceptionMessage"u8); + writer.WriteStringValue(ExceptionMessage); + } + writer.WritePropertyName("DocumentType"u8); + writer.WriteStringValue(DocumentType.ToString()); + if (Optional.IsCollectionDefined(DocumentStreamIds)) + { + writer.WritePropertyName("DocumentStreamIds"u8); + writer.WriteStartArray(); + foreach (var item in DocumentStreamIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Properties)) + { + writer.WritePropertyName("Properties"u8); + writer.WriteStartArray(); + foreach (var item in Properties) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + Exception IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Exception)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeException(document.RootElement, options); + } + + internal static Exception DeserializeException(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string exceptionType = default; + string exceptionMessage = default; + DocumentType documentType = default; + IList documentStreamIds = default; + IList properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("ExceptionType"u8)) + { + exceptionType = property.Value.GetString(); + continue; + } + if (property.NameEquals("ExceptionMessage"u8)) + { + exceptionMessage = property.Value.GetString(); + continue; + } + if (property.NameEquals("DocumentType"u8)) + { + documentType = new DocumentType(property.Value.GetString()); + continue; + } + if (property.NameEquals("DocumentStreamIds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + documentStreamIds = array; + continue; + } + if (property.NameEquals("Properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + properties = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Exception( + documentType, + documentStreamIds ?? new ChangeTrackingList(), + properties ?? new ChangeTrackingList(), + serializedAdditionalRawData, + exceptionType, + exceptionMessage); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Exception)} does not support writing '{options.Format}' format."); + } + } + + Exception IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeException(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Exception)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new Exception FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeException(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Exception.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Exception.cs new file mode 100644 index 000000000000..33c36b88e5e0 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Exception.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Exception document type. + public partial class Exception : DocumentIngress + { + /// Initializes a new instance of . + public Exception() + { + DocumentType = DocumentType.Exception; + } + + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + /// Exception type name. + /// Exception message. + internal Exception(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData, string exceptionType, string exceptionMessage) : base(documentType, documentStreamIds, properties, serializedAdditionalRawData) + { + ExceptionType = exceptionType; + ExceptionMessage = exceptionMessage; + } + + /// Exception type name. + public string ExceptionType { get; set; } + /// Exception message. + public string ExceptionMessage { get; set; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.Serialization.cs new file mode 100644 index 000000000000..b06b826b356b --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.Serialization.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class FilterConjunctionGroupInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FilterConjunctionGroupInfo)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("Filters"u8); + writer.WriteStartArray(); + foreach (var item in Filters) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + FilterConjunctionGroupInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FilterConjunctionGroupInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFilterConjunctionGroupInfo(document.RootElement, options); + } + + internal static FilterConjunctionGroupInfo DeserializeFilterConjunctionGroupInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList filters = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Filters"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(FilterInfo.DeserializeFilterInfo(item, options)); + } + filters = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FilterConjunctionGroupInfo(filters, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FilterConjunctionGroupInfo)} does not support writing '{options.Format}' format."); + } + } + + FilterConjunctionGroupInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeFilterConjunctionGroupInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FilterConjunctionGroupInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FilterConjunctionGroupInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeFilterConjunctionGroupInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.cs new file mode 100644 index 000000000000..16ce6d4a1f18 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + /// An AND-connected group of FilterInfo objects. + public partial class FilterConjunctionGroupInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// An array of filters. + /// is null. + internal FilterConjunctionGroupInfo(IEnumerable filters) + { + Argument.AssertNotNull(filters, nameof(filters)); + + Filters = filters.ToList(); + } + + /// Initializes a new instance of . + /// An array of filters. + /// Keeps track of any properties unknown to the library. + internal FilterConjunctionGroupInfo(IReadOnlyList filters, IDictionary serializedAdditionalRawData) + { + Filters = filters; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FilterConjunctionGroupInfo() + { + } + + /// An array of filters. + public IReadOnlyList Filters { get; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/FilterInfo.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/FilterInfo.Serialization.cs new file mode 100644 index 000000000000..18a7b1c91d54 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/FilterInfo.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class FilterInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FilterInfo)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("FieldName"u8); + writer.WriteStringValue(FieldName); + writer.WritePropertyName("Predicate"u8); + writer.WriteStringValue(Predicate.ToString()); + writer.WritePropertyName("Comparand"u8); + writer.WriteStringValue(Comparand); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + FilterInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FilterInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFilterInfo(document.RootElement, options); + } + + internal static FilterInfo DeserializeFilterInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fieldName = default; + PredicateType predicate = default; + string comparand = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("FieldName"u8)) + { + fieldName = property.Value.GetString(); + continue; + } + if (property.NameEquals("Predicate"u8)) + { + predicate = new PredicateType(property.Value.GetString()); + continue; + } + if (property.NameEquals("Comparand"u8)) + { + comparand = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FilterInfo(fieldName, predicate, comparand, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FilterInfo)} does not support writing '{options.Format}' format."); + } + } + + FilterInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeFilterInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FilterInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FilterInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeFilterInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/FilterInfo.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/FilterInfo.cs new file mode 100644 index 000000000000..227a405ba0cb --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/FilterInfo.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// A filter set on UX. + public partial class FilterInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// dimension name of the filter. + /// Operator of the filter. + /// Comparand of the filter. + /// or is null. + internal FilterInfo(string fieldName, PredicateType predicate, string comparand) + { + Argument.AssertNotNull(fieldName, nameof(fieldName)); + Argument.AssertNotNull(comparand, nameof(comparand)); + + FieldName = fieldName; + Predicate = predicate; + Comparand = comparand; + } + + /// Initializes a new instance of . + /// dimension name of the filter. + /// Operator of the filter. + /// Comparand of the filter. + /// Keeps track of any properties unknown to the library. + internal FilterInfo(string fieldName, PredicateType predicate, string comparand, IDictionary serializedAdditionalRawData) + { + FieldName = fieldName; + Predicate = predicate; + Comparand = comparand; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FilterInfo() + { + } + + /// dimension name of the filter. + public string FieldName { get; } + /// Operator of the filter. + public PredicateType Predicate { get; } + /// Comparand of the filter. + public string Comparand { get; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/Argument.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/Argument.cs new file mode 100644 index 000000000000..fd93d797ccdf --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/Argument.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace LiveMetrics +{ + internal static class Argument + { + public static void AssertNotNull(T value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNull(T? value, string name) + where T : struct + { + if (!value.HasValue) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNullOrEmpty(IEnumerable value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value is ICollection collectionOfT && collectionOfT.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + if (value is ICollection collection && collection.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + using IEnumerator e = value.GetEnumerator(); + if (!e.MoveNext()) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + } + + public static void AssertNotNullOrEmpty(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value.Length == 0) + { + throw new ArgumentException("Value cannot be an empty string.", name); + } + } + + public static void AssertNotNullOrWhiteSpace(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Value cannot be empty or contain only white-space characters.", name); + } + } + + public static void AssertNotDefault(ref T value, string name) + where T : struct, IEquatable + { + if (value.Equals(default)) + { + throw new ArgumentException("Value cannot be empty.", name); + } + } + + public static void AssertInRange(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (minimum.CompareTo(value) > 0) + { + throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed."); + } + if (maximum.CompareTo(value) < 0) + { + throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed."); + } + } + + public static void AssertEnumDefined(Type enumType, object value, string name) + { + if (!Enum.IsDefined(enumType, value)) + { + throw new ArgumentException($"Value not defined for {enumType.FullName}.", name); + } + } + + public static T CheckNotNull(T value, string name) + where T : class + { + AssertNotNull(value, name); + return value; + } + + public static string CheckNotNullOrEmpty(string value, string name) + { + AssertNotNullOrEmpty(value, name); + return value; + } + + public static void AssertNull(T value, string name, string message = null) + { + if (value != null) + { + throw new ArgumentException(message ?? "Value must be null.", name); + } + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 000000000000..adba2e33ac67 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace LiveMetrics +{ + internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull + { + private IDictionary _innerDictionary; + + public ChangeTrackingDictionary() + { + } + + public ChangeTrackingDictionary(IDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(dictionary); + } + + public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(); + foreach (var pair in dictionary) + { + _innerDictionary.Add(pair); + } + } + + public bool IsUndefined => _innerDictionary == null; + + public int Count => IsUndefined ? 0 : EnsureDictionary().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; + + public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; + + public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; + + public TValue this[TKey key] + { + get + { + if (IsUndefined) + { + throw new KeyNotFoundException(nameof(key)); + } + return EnsureDictionary()[key]; + } + set + { + EnsureDictionary()[key] = value; + } + } + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Values => Values; + + public IEnumerator> GetEnumerator() + { + if (IsUndefined) + { + IEnumerator> enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureDictionary().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + EnsureDictionary().Add(item); + } + + public void Clear() + { + EnsureDictionary().Clear(); + } + + public bool Contains(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int index) + { + if (IsUndefined) + { + return; + } + EnsureDictionary().CopyTo(array, index); + } + + public bool Remove(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(item); + } + + public void Add(TKey key, TValue value) + { + EnsureDictionary().Add(key, value); + } + + public bool ContainsKey(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().ContainsKey(key); + } + + public bool Remove(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(key); + } + + public bool TryGetValue(TKey key, out TValue value) + { + if (IsUndefined) + { + value = default; + return false; + } + return EnsureDictionary().TryGetValue(key, out value); + } + + public IDictionary EnsureDictionary() + { + return _innerDictionary ??= new Dictionary(); + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/ChangeTrackingList.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 000000000000..d80288a80595 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/ChangeTrackingList.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + internal class ChangeTrackingList : IList, IReadOnlyList + { + private IList _innerList; + + public ChangeTrackingList() + { + } + + public ChangeTrackingList(IList innerList) + { + if (innerList != null) + { + _innerList = innerList; + } + } + + public ChangeTrackingList(IReadOnlyList innerList) + { + if (innerList != null) + { + _innerList = innerList.ToList(); + } + } + + public bool IsUndefined => _innerList == null; + + public int Count => IsUndefined ? 0 : EnsureList().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; + + public T this[int index] + { + get + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + return EnsureList()[index]; + } + set + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList()[index] = value; + } + } + + public void Reset() + { + _innerList = null; + } + + public IEnumerator GetEnumerator() + { + if (IsUndefined) + { + IEnumerator enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureList().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(T item) + { + EnsureList().Add(item); + } + + public void Clear() + { + EnsureList().Clear(); + } + + public bool Contains(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Contains(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + if (IsUndefined) + { + return; + } + EnsureList().CopyTo(array, arrayIndex); + } + + public bool Remove(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Remove(item); + } + + public int IndexOf(T item) + { + if (IsUndefined) + { + return -1; + } + return EnsureList().IndexOf(item); + } + + public void Insert(int index, T item) + { + EnsureList().Insert(index, item); + } + + public void RemoveAt(int index) + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList().RemoveAt(index); + } + + public IList EnsureList() + { + return _innerList ??= new List(); + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 000000000000..88ff058c3168 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/ModelSerializationExtensions.cs @@ -0,0 +1,398 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using System.Xml; +using Azure.Core; + +namespace LiveMetrics +{ + internal static class ModelSerializationExtensions + { + internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); + + public static object GetObject(this JsonElement element) + { + switch (element.ValueKind) + { + case JsonValueKind.String: + return element.GetString(); + case JsonValueKind.Number: + if (element.TryGetInt32(out int intValue)) + { + return intValue; + } + if (element.TryGetInt64(out long longValue)) + { + return longValue; + } + return element.GetDouble(); + case JsonValueKind.True: + return true; + case JsonValueKind.False: + return false; + case JsonValueKind.Undefined: + case JsonValueKind.Null: + return null; + case JsonValueKind.Object: + var dictionary = new Dictionary(); + foreach (var jsonProperty in element.EnumerateObject()) + { + dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); + } + return dictionary; + case JsonValueKind.Array: + var list = new List(); + foreach (var item in element.EnumerateArray()) + { + list.Add(item.GetObject()); + } + return list.ToArray(); + default: + throw new NotSupportedException($"Not supported value kind {element.ValueKind}"); + } + } + + public static byte[] GetBytesFromBase64(this JsonElement element, string format) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + + return format switch + { + "U" => TypeFormatters.FromBase64UrlString(element.GetRequiredString()), + "D" => element.GetBytesFromBase64(), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + } + + public static DateTimeOffset GetDateTimeOffset(this JsonElement element, string format) => format switch + { + "U" when element.ValueKind == JsonValueKind.Number => DateTimeOffset.FromUnixTimeSeconds(element.GetInt64()), + _ => TypeFormatters.ParseDateTimeOffset(element.GetString(), format) + }; + + public static TimeSpan GetTimeSpan(this JsonElement element, string format) => TypeFormatters.ParseTimeSpan(element.GetString(), format); + + public static char GetChar(this JsonElement element) + { + if (element.ValueKind == JsonValueKind.String) + { + var text = element.GetString(); + if (text == null || text.Length != 1) + { + throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); + } + return text[0]; + } + else + { + throw new NotSupportedException($"Cannot convert {element.ValueKind} to a char"); + } + } + + [Conditional("DEBUG")] + public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) + { + throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); + } + + public static string GetRequiredString(this JsonElement element) + { + var value = element.GetString(); + if (value == null) + { + throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); + } + return value; + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTime value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, TimeSpan value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, char value) + { + writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); + } + + public static void WriteBase64StringValue(this Utf8JsonWriter writer, byte[] value, string format) + { + if (value == null) + { + writer.WriteNullValue(); + return; + } + switch (format) + { + case "U": + writer.WriteStringValue(TypeFormatters.ToBase64UrlString(value)); + break; + case "D": + writer.WriteBase64StringValue(value); + break; + default: + throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)); + } + } + + public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + if (format != "U") + { + throw new ArgumentOutOfRangeException(nameof(format), "Only 'U' format is supported when writing a DateTimeOffset as a Number."); + } + writer.WriteNumberValue(value.ToUnixTimeSeconds()); + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) + { + switch (value) + { + case null: + writer.WriteNullValue(); + break; + case IJsonModel jsonModel: + jsonModel.Write(writer, options ?? WireOptions); + break; + case IUtf8JsonSerializable serializable: + serializable.Write(writer); + break; + case byte[] bytes: + writer.WriteBase64StringValue(bytes); + break; + case BinaryData bytes0: + writer.WriteBase64StringValue(bytes0); + break; + case JsonElement json: + json.WriteTo(writer); + break; + case int i: + writer.WriteNumberValue(i); + break; + case decimal d: + writer.WriteNumberValue(d); + break; + case double d0: + if (double.IsNaN(d0)) + { + writer.WriteStringValue("NaN"); + } + else + { + writer.WriteNumberValue(d0); + } + break; + case float f: + writer.WriteNumberValue(f); + break; + case long l: + writer.WriteNumberValue(l); + break; + case string s: + writer.WriteStringValue(s); + break; + case bool b: + writer.WriteBooleanValue(b); + break; + case Guid g: + writer.WriteStringValue(g); + break; + case DateTimeOffset dateTimeOffset: + writer.WriteStringValue(dateTimeOffset, "O"); + break; + case DateTime dateTime: + writer.WriteStringValue(dateTime, "O"); + break; + case IEnumerable> enumerable: + writer.WriteStartObject(); + foreach (var pair in enumerable) + { + writer.WritePropertyName(pair.Key); + writer.WriteObjectValue(pair.Value, options); + } + writer.WriteEndObject(); + break; + case IEnumerable objectEnumerable: + writer.WriteStartArray(); + foreach (var item in objectEnumerable) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + break; + case TimeSpan timeSpan: + writer.WriteStringValue(timeSpan, "P"); + break; + default: + throw new NotSupportedException($"Not supported type {value.GetType()}"); + } + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) + { + writer.WriteObjectValue(value, options); + } + + internal static class TypeFormatters + { + private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; + public const string DefaultNumberFormat = "G"; + + public static string ToString(bool value) => value ? "true" : "false"; + + public static string ToString(DateTime value, string format) => value.Kind switch + { + DateTimeKind.Utc => ToString((DateTimeOffset)value, format), + _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") + }; + + public static string ToString(DateTimeOffset value, string format) => format switch + { + "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "R" => value.ToString("r", CultureInfo.InvariantCulture), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(TimeSpan value, string format) => format switch + { + "P" => XmlConvert.ToString(value), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(byte[] value, string format) => format switch + { + "U" => ToBase64UrlString(value), + "D" => Convert.ToBase64String(value), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + + public static string ToBase64UrlString(byte[] value) + { + int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; + int size = checked(numWholeOrPartialInputBlocks * 4); + char[] output = new char[size]; + + int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); + + int i = 0; + for (; i < numBase64Chars; i++) + { + char ch = output[i]; + if (ch == '+') + { + output[i] = '-'; + } + else + { + if (ch == '/') + { + output[i] = '_'; + } + else + { + if (ch == '=') + { + break; + } + } + } + } + + return new string(output, 0, i); + } + + public static byte[] FromBase64UrlString(string value) + { + int paddingCharsToAdd = (value.Length % 4) switch + { + 0 => 0, + 2 => 2, + 3 => 1, + _ => throw new InvalidOperationException("Malformed input") + }; + char[] output = new char[(value.Length + paddingCharsToAdd)]; + int i = 0; + for (; i < value.Length; i++) + { + char ch = value[i]; + if (ch == '-') + { + output[i] = '+'; + } + else + { + if (ch == '_') + { + output[i] = '/'; + } + else + { + output[i] = ch; + } + } + } + + for (; i < output.Length; i++) + { + output[i] = '='; + } + + return Convert.FromBase64CharArray(output, 0, output.Length); + } + + public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch + { + "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), + _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) + }; + + public static TimeSpan ParseTimeSpan(string value, string format) => format switch + { + "P" => XmlConvert.ToTimeSpan(value), + _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) + }; + + public static string ConvertToString(object value, string format = null) => value switch + { + null => "null", + string s => s, + bool b => ToString(b), + int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), + byte[] b0 when format != null => ToString(b0, format), + IEnumerable s0 => string.Join(",", s0), + DateTimeOffset dateTime when format != null => ToString(dateTime, format), + TimeSpan timeSpan when format != null => ToString(timeSpan, format), + TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), + Guid guid => guid.ToString(), + BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), + _ => value.ToString() + }; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/Optional.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/Optional.cs new file mode 100644 index 000000000000..eeab5e028d1a --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/Optional.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; + +namespace LiveMetrics +{ + internal static class Optional + { + public static bool IsCollectionDefined(IEnumerable collection) + { + return !(collection is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined); + } + + public static bool IsCollectionDefined(IDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsCollectionDefined(IReadOnlyDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsDefined(T? value) + where T : struct + { + return value.HasValue; + } + + public static bool IsDefined(object value) + { + return value != null; + } + + public static bool IsDefined(JsonElement value) + { + return value.ValueKind != JsonValueKind.Undefined; + } + + public static bool IsDefined(string value) + { + return value != null; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/RequestContentHelper.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/RequestContentHelper.cs new file mode 100644 index 000000000000..fe0b285b88d9 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/RequestContentHelper.cs @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace LiveMetrics +{ + internal static class RequestContentHelper + { + public static RequestContent FromEnumerable(IEnumerable enumerable) + where T : notnull + { + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteStartArray(); + foreach (var item in enumerable) + { + content.JsonWriter.WriteObjectValue(item, ModelSerializationExtensions.WireOptions); + } + content.JsonWriter.WriteEndArray(); + + return content; + } + + public static RequestContent FromEnumerable(IEnumerable enumerable) + { + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteStartArray(); + foreach (var item in enumerable) + { + if (item == null) + { + content.JsonWriter.WriteNullValue(); + } + else + { +#if NET6_0_OR_GREATER + content.JsonWriter.WriteRawValue(item); +#else + using (JsonDocument document = JsonDocument.Parse(item)) + { + JsonSerializer.Serialize(content.JsonWriter, document.RootElement); + } +#endif + } + } + content.JsonWriter.WriteEndArray(); + + return content; + } + + public static RequestContent FromEnumerable(ReadOnlySpan span) + where T : notnull + { + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteStartArray(); + for (int i = 0; i < span.Length; i++) + { + content.JsonWriter.WriteObjectValue(span[i], ModelSerializationExtensions.WireOptions); + } + content.JsonWriter.WriteEndArray(); + + return content; + } + + public static RequestContent FromDictionary(IDictionary dictionary) + where TValue : notnull + { + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteStartObject(); + foreach (var item in dictionary) + { + content.JsonWriter.WritePropertyName(item.Key); + content.JsonWriter.WriteObjectValue(item.Value, ModelSerializationExtensions.WireOptions); + } + content.JsonWriter.WriteEndObject(); + + return content; + } + + public static RequestContent FromDictionary(IDictionary dictionary) + { + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteStartObject(); + foreach (var item in dictionary) + { + content.JsonWriter.WritePropertyName(item.Key); + if (item.Value == null) + { + content.JsonWriter.WriteNullValue(); + } + else + { +#if NET6_0_OR_GREATER + content.JsonWriter.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(content.JsonWriter, document.RootElement); + } +#endif + } + } + content.JsonWriter.WriteEndObject(); + + return content; + } + + public static RequestContent FromObject(object value) + { + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(value, ModelSerializationExtensions.WireOptions); + return content; + } + + public static RequestContent FromObject(BinaryData value) + { + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); +#if NET6_0_OR_GREATER + content.JsonWriter.WriteRawValue(value); +#else + using (JsonDocument document = JsonDocument.Parse(value)) + { + JsonSerializer.Serialize(content.JsonWriter, document.RootElement); + } +#endif + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/Utf8JsonRequestContent.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 000000000000..0d748623b16d --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; + +namespace LiveMetrics +{ + internal class Utf8JsonRequestContent : RequestContent + { + private readonly MemoryStream _stream; + private readonly RequestContent _content; + + public Utf8JsonRequestContent() + { + _stream = new MemoryStream(); + _content = Create(_stream); + JsonWriter = new Utf8JsonWriter(_stream); + } + + public Utf8JsonWriter JsonWriter { get; } + + public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) + { + await JsonWriter.FlushAsync().ConfigureAwait(false); + await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); + } + + public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) + { + JsonWriter.Flush(); + _content.WriteTo(stream, cancellationToken); + } + + public override bool TryComputeLength(out long length) + { + length = JsonWriter.BytesCommitted + JsonWriter.BytesPending; + return true; + } + + public override void Dispose() + { + JsonWriter.Dispose(); + _content.Dispose(); + _stream.Dispose(); + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/KeyValuePairStringString.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/KeyValuePairStringString.Serialization.cs new file mode 100644 index 000000000000..4512b35484ca --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/KeyValuePairStringString.Serialization.cs @@ -0,0 +1,144 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class KeyValuePairStringString : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyValuePairStringString)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("key"u8); + writer.WriteStringValue(Key); + writer.WritePropertyName("value"u8); + writer.WriteStringValue(Value); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + KeyValuePairStringString IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyValuePairStringString)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeKeyValuePairStringString(document.RootElement, options); + } + + internal static KeyValuePairStringString DeserializeKeyValuePairStringString(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string key = default; + string value = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("key"u8)) + { + key = property.Value.GetString(); + continue; + } + if (property.NameEquals("value"u8)) + { + value = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new KeyValuePairStringString(key, value, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(KeyValuePairStringString)} does not support writing '{options.Format}' format."); + } + } + + KeyValuePairStringString IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeKeyValuePairStringString(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(KeyValuePairStringString)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static KeyValuePairStringString FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeKeyValuePairStringString(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/KeyValuePairStringString.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/KeyValuePairStringString.cs new file mode 100644 index 000000000000..ebe35b0f0370 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/KeyValuePairStringString.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Key-value pair of string and string. + public partial class KeyValuePairStringString + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Key of the key-value pair. + /// Value of the key-value pair. + /// or is null. + public KeyValuePairStringString(string key, string value) + { + Argument.AssertNotNull(key, nameof(key)); + Argument.AssertNotNull(value, nameof(value)); + + Key = key; + Value = value; + } + + /// Initializes a new instance of . + /// Key of the key-value pair. + /// Value of the key-value pair. + /// Keeps track of any properties unknown to the library. + internal KeyValuePairStringString(string key, string value, IDictionary serializedAdditionalRawData) + { + Key = key; + Value = value; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal KeyValuePairStringString() + { + } + + /// Key of the key-value pair. + public string Key { get; } + /// Value of the key-value pair. + public string Value { get; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/LiveMetricsClient.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/LiveMetricsClient.cs new file mode 100644 index 000000000000..48b465ab2013 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/LiveMetricsClient.cs @@ -0,0 +1,408 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace LiveMetrics +{ + // Data plane generated client. + /// Live Metrics REST APIs. + public partial class LiveMetricsClient + { + private static readonly string[] AuthorizationScopes = new string[] { "https://monitor.azure.com/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of LiveMetricsClient for mocking. + protected LiveMetricsClient() + { + } + + /// Initializes a new instance of LiveMetricsClient. + /// A credential used to authenticate to an Azure Service. + /// is null. + public LiveMetricsClient(TokenCredential credential) : this(new Uri("https://global.livediagnostics.monitor.azure.com"), credential, new LiveMetricsClientOptions()) + { + } + + /// Initializes a new instance of LiveMetricsClient. + /// The endpoint of the Live Metrics service. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public LiveMetricsClient(Uri endpoint, TokenCredential credential, LiveMetricsClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new LiveMetricsClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// Determine whether there is any subscription to the metrics and documents. + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// Data contract between Application Insights client SDK and Live Metrics. /QuickPulseService.svc/ping uses this as a backup source of machine name, instance name and invariant version. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// Computer name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Service instance name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Identifies an Application Insights SDK as trusted agent to report metrics and documents. + /// Cloud role name of the service. + /// Version/generation of the data contract (MonitoringDataPoint) between the client and Live Metrics. + /// An encoded string that indicates whether the collection configuration is changed. + /// The cancellation token to use. + /// is null. + /// + public virtual async Task> IsSubscribedAsync(string ikey, MonitoringDataPoint monitoringDataPoint = null, long? transmissionTime = null, string machineName = null, string instanceName = null, string streamId = null, string roleName = null, string invariantVersion = null, ETag? configurationEtag = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using RequestContent content = monitoringDataPoint?.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await IsSubscribedAsync(ikey, content, transmissionTime, machineName, instanceName, streamId, roleName, invariantVersion, configurationEtag, context).ConfigureAwait(false); + return Response.FromValue(CollectionConfigurationInfo.FromResponse(response), response); + } + + /// Determine whether there is any subscription to the metrics and documents. + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// Data contract between Application Insights client SDK and Live Metrics. /QuickPulseService.svc/ping uses this as a backup source of machine name, instance name and invariant version. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// Computer name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Service instance name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Identifies an Application Insights SDK as trusted agent to report metrics and documents. + /// Cloud role name of the service. + /// Version/generation of the data contract (MonitoringDataPoint) between the client and Live Metrics. + /// An encoded string that indicates whether the collection configuration is changed. + /// The cancellation token to use. + /// is null. + /// + public virtual Response IsSubscribed(string ikey, MonitoringDataPoint monitoringDataPoint = null, long? transmissionTime = null, string machineName = null, string instanceName = null, string streamId = null, string roleName = null, string invariantVersion = null, ETag? configurationEtag = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using RequestContent content = monitoringDataPoint?.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = IsSubscribed(ikey, content, transmissionTime, machineName, instanceName, streamId, roleName, invariantVersion, configurationEtag, context); + return Response.FromValue(CollectionConfigurationInfo.FromResponse(response), response); + } + + /// + /// [Protocol Method] Determine whether there is any subscription to the metrics and documents. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// The content to send as the body of the request. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// Computer name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Service instance name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Identifies an Application Insights SDK as trusted agent to report metrics and documents. + /// Cloud role name of the service. + /// Version/generation of the data contract (MonitoringDataPoint) between the client and Live Metrics. + /// An encoded string that indicates whether the collection configuration is changed. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task IsSubscribedAsync(string ikey, RequestContent content, long? transmissionTime = null, string machineName = null, string instanceName = null, string streamId = null, string roleName = null, string invariantVersion = null, ETag? configurationEtag = null, RequestContext context = null) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using var scope = ClientDiagnostics.CreateScope("LiveMetricsClient.IsSubscribed"); + scope.Start(); + try + { + using HttpMessage message = CreateIsSubscribedRequest(ikey, content, transmissionTime, machineName, instanceName, streamId, roleName, invariantVersion, configurationEtag, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (System.Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Determine whether there is any subscription to the metrics and documents. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// The content to send as the body of the request. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// Computer name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Service instance name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Identifies an Application Insights SDK as trusted agent to report metrics and documents. + /// Cloud role name of the service. + /// Version/generation of the data contract (MonitoringDataPoint) between the client and Live Metrics. + /// An encoded string that indicates whether the collection configuration is changed. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response IsSubscribed(string ikey, RequestContent content, long? transmissionTime = null, string machineName = null, string instanceName = null, string streamId = null, string roleName = null, string invariantVersion = null, ETag? configurationEtag = null, RequestContext context = null) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using var scope = ClientDiagnostics.CreateScope("LiveMetricsClient.IsSubscribed"); + scope.Start(); + try + { + using HttpMessage message = CreateIsSubscribedRequest(ikey, content, transmissionTime, machineName, instanceName, streamId, roleName, invariantVersion, configurationEtag, context); + return _pipeline.ProcessMessage(message, context); + } + catch (System.Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Publish live metrics to the Live Metrics service when there is an active subscription to the metrics. + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// Data contract between the client and Live Metrics. /QuickPulseService.svc/ping uses this as a backup source of machine name, instance name and invariant version. + /// An encoded string that indicates whether the collection configuration is changed. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// The cancellation token to use. + /// is null. + /// + public virtual async Task> PublishAsync(string ikey, IEnumerable monitoringDataPoints = null, ETag? configurationEtag = null, long? transmissionTime = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using RequestContent content = monitoringDataPoints != null ? RequestContentHelper.FromEnumerable(monitoringDataPoints) : null; + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await PublishAsync(ikey, content, configurationEtag, transmissionTime, context).ConfigureAwait(false); + return Response.FromValue(CollectionConfigurationInfo.FromResponse(response), response); + } + + /// Publish live metrics to the Live Metrics service when there is an active subscription to the metrics. + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// Data contract between the client and Live Metrics. /QuickPulseService.svc/ping uses this as a backup source of machine name, instance name and invariant version. + /// An encoded string that indicates whether the collection configuration is changed. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// The cancellation token to use. + /// is null. + /// + public virtual Response Publish(string ikey, IEnumerable monitoringDataPoints = null, ETag? configurationEtag = null, long? transmissionTime = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using RequestContent content = monitoringDataPoints != null ? RequestContentHelper.FromEnumerable(monitoringDataPoints) : null; + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Publish(ikey, content, configurationEtag, transmissionTime, context); + return Response.FromValue(CollectionConfigurationInfo.FromResponse(response), response); + } + + /// + /// [Protocol Method] Publish live metrics to the Live Metrics service when there is an active subscription to the metrics. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// The content to send as the body of the request. + /// An encoded string that indicates whether the collection configuration is changed. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task PublishAsync(string ikey, RequestContent content, ETag? configurationEtag = null, long? transmissionTime = null, RequestContext context = null) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using var scope = ClientDiagnostics.CreateScope("LiveMetricsClient.Publish"); + scope.Start(); + try + { + using HttpMessage message = CreatePublishRequest(ikey, content, configurationEtag, transmissionTime, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (System.Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Publish live metrics to the Live Metrics service when there is an active subscription to the metrics. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// The content to send as the body of the request. + /// An encoded string that indicates whether the collection configuration is changed. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response Publish(string ikey, RequestContent content, ETag? configurationEtag = null, long? transmissionTime = null, RequestContext context = null) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using var scope = ClientDiagnostics.CreateScope("LiveMetricsClient.Publish"); + scope.Start(); + try + { + using HttpMessage message = CreatePublishRequest(ikey, content, configurationEtag, transmissionTime, context); + return _pipeline.ProcessMessage(message, context); + } + catch (System.Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateIsSubscribedRequest(string ikey, RequestContent content, long? transmissionTime, string machineName, string instanceName, string streamId, string roleName, string invariantVersion, ETag? configurationEtag, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/QuickPulseService.svc/ping", false); + uri.AppendQuery("ikey", ikey, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + if (transmissionTime != null) + { + request.Headers.Add("x-ms-qps-transmission-time", transmissionTime.Value); + } + if (machineName != null) + { + request.Headers.Add("x-ms-qps-machine-name", machineName); + } + if (instanceName != null) + { + request.Headers.Add("x-ms-qps-instance-name", instanceName); + } + if (streamId != null) + { + request.Headers.Add("x-ms-qps-stream-id", streamId); + } + if (roleName != null) + { + request.Headers.Add("x-ms-qps-role-name", roleName); + } + if (invariantVersion != null) + { + request.Headers.Add("x-ms-qps-invariant-version", invariantVersion); + } + if (configurationEtag != null) + { + request.Headers.Add("x-ms-qps-configuration-etag", configurationEtag.Value); + } + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreatePublishRequest(string ikey, RequestContent content, ETag? configurationEtag, long? transmissionTime, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/QuickPulseService.svc/post", false); + uri.AppendQuery("ikey", ikey, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + if (configurationEtag != null) + { + request.Headers.Add("x-ms-qps-configuration-etag", configurationEtag.Value); + } + if (transmissionTime != null) + { + request.Headers.Add("x-ms-qps-transmission-time", transmissionTime.Value); + } + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/LiveMetricsClientBuilderExtensions.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/LiveMetricsClientBuilderExtensions.cs new file mode 100644 index 000000000000..8ecb9e953fd2 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/LiveMetricsClientBuilderExtensions.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core.Extensions; +using LiveMetrics; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add to client builder. + public static partial class LiveMetricsClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// The endpoint of the Live Metrics service. + public static IAzureClientBuilder AddLiveMetricsClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new LiveMetricsClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddLiveMetricsClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/LiveMetricsClientOptions.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/LiveMetricsClientOptions.cs new file mode 100644 index 000000000000..570f16b4a1b1 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/LiveMetricsClientOptions.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace LiveMetrics +{ + /// Client options for LiveMetricsClient. + public partial class LiveMetricsClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2024_04_01_Preview; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "2024-04-01-preview". + V2024_04_01_Preview = 1, + } + + internal string Version { get; } + + /// Initializes new instance of LiveMetricsClientOptions. + public LiveMetricsClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2024_04_01_Preview => "2024-04-01-preview", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/LiveMetricsModelFactory.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/LiveMetricsModelFactory.cs new file mode 100644 index 000000000000..512a865451bb --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/LiveMetricsModelFactory.cs @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + /// Model factory for models. + public static partial class LiveMetricsModelFactory + { + /// Initializes a new instance of . + /// Application Insights SDK version. + /// Version/generation of the data contract (MonitoringDataPoint) between SDK and Live Metrics. + /// Service instance name where Application Insights SDK lives. + /// Service role name. + /// Computer name where Application Insights SDK lives. + /// Identifies an Application Insights SDK as a trusted agent to report metrics and documents. + /// Data point generation timestamp. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. + /// True if the current application is an Azure Web App. + /// True if performance counters collection is supported. + /// An array of metric data points. + /// + /// An array of documents of a specific type {Request}, {RemoteDependency}, {Exception}, {Event}, or {Trace} + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + /// An array of top cpu consumption data point. + /// An array of error while SDK parses and applies the {CollectionConfigurationInfo} provided by Live Metrics. + /// A new instance for mocking. + public static MonitoringDataPoint MonitoringDataPoint(string version = null, int invariantVersion = default, string instance = null, string roleName = null, string machineName = null, string streamId = null, DateTimeOffset? timestamp = null, DateTimeOffset? transmissionTime = null, bool isWebApp = default, bool performanceCollectionSupported = default, IEnumerable metrics = null, IEnumerable documents = null, IEnumerable topCpuProcesses = null, IEnumerable collectionConfigurationErrors = null) + { + metrics ??= new List(); + documents ??= new List(); + topCpuProcesses ??= new List(); + collectionConfigurationErrors ??= new List(); + + return new MonitoringDataPoint( + version, + invariantVersion, + instance, + roleName, + machineName, + streamId, + timestamp, + transmissionTime, + isWebApp, + performanceCollectionSupported, + metrics?.ToList(), + documents?.ToList(), + topCpuProcesses?.ToList(), + collectionConfigurationErrors?.ToList(), + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// An encoded string that indicates whether the collection configuration is changed. + /// An array of metric configuration info. + /// An array of document stream configuration info. + /// Controls document quotas to be sent to Live Metrics. + /// A new instance for mocking. + public static CollectionConfigurationInfo CollectionConfigurationInfo(string eTag = null, IEnumerable metrics = null, IEnumerable documentStreams = null, QuotaConfigurationInfo quotaInfo = null) + { + metrics ??= new List(); + documentStreams ??= new List(); + + return new CollectionConfigurationInfo(eTag, metrics?.ToList(), documentStreams?.ToList(), quotaInfo, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// metric configuration identifier. + /// Telemetry type. + /// A collection of filters to scope metrics that UX needs. + /// Telemetry's metric dimension whose value is to be aggregated. Example values: Duration, Count(),... + /// Aggregation type. This is the aggregation done from everything within a single server. + /// Aggregation type. This Aggregation is done across the values for all the servers taken together. + /// A new instance for mocking. + public static DerivedMetricInfo DerivedMetricInfo(string id = null, string telemetryType = null, IEnumerable filterGroups = null, string projection = null, AggregationType aggregation = default, AggregationType backEndAggregation = default) + { + filterGroups ??= new List(); + + return new DerivedMetricInfo( + id, + telemetryType, + filterGroups?.ToList(), + projection, + aggregation, + backEndAggregation, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// An array of filters. + /// A new instance for mocking. + public static FilterConjunctionGroupInfo FilterConjunctionGroupInfo(IEnumerable filters = null) + { + filters ??= new List(); + + return new FilterConjunctionGroupInfo(filters?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// dimension name of the filter. + /// Operator of the filter. + /// Comparand of the filter. + /// A new instance for mocking. + public static FilterInfo FilterInfo(string fieldName = null, PredicateType predicate = default, string comparand = null) + { + return new FilterInfo(fieldName, predicate, comparand, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Identifier of the document stream initiated by a UX. + /// Gets or sets an OR-connected collection of filter groups. + /// A new instance for mocking. + public static DocumentStreamInfo DocumentStreamInfo(string id = null, IEnumerable documentFilterGroups = null) + { + documentFilterGroups ??= new List(); + + return new DocumentStreamInfo(id, documentFilterGroups?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Telemetry type. + /// An array of filter groups. + /// A new instance for mocking. + public static DocumentFilterConjunctionGroupInfo DocumentFilterConjunctionGroupInfo(TelemetryType telemetryType = default, FilterConjunctionGroupInfo filters = null) + { + return new DocumentFilterConjunctionGroupInfo(telemetryType, filters, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Initial quota. + /// Max quota. + /// Quota accrual rate per second. + /// A new instance for mocking. + public static QuotaConfigurationInfo QuotaConfigurationInfo(float? initialQuota = null, float maxQuota = default, float quotaAccrualRatePerSec = default) + { + return new QuotaConfigurationInfo(initialQuota, maxQuota, quotaAccrualRatePerSec, serializedAdditionalRawData: null); + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/MetricPoint.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/MetricPoint.Serialization.cs new file mode 100644 index 000000000000..967317d72bdc --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/MetricPoint.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class MetricPoint : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MetricPoint)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("Name"u8); + writer.WriteStringValue(Name); + writer.WritePropertyName("Value"u8); + writer.WriteNumberValue(Value); + writer.WritePropertyName("Weight"u8); + writer.WriteNumberValue(Weight); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + MetricPoint IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MetricPoint)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMetricPoint(document.RootElement, options); + } + + internal static MetricPoint DeserializeMetricPoint(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + double value = default; + int weight = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("Value"u8)) + { + value = property.Value.GetDouble(); + continue; + } + if (property.NameEquals("Weight"u8)) + { + weight = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MetricPoint(name, value, weight, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MetricPoint)} does not support writing '{options.Format}' format."); + } + } + + MetricPoint IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeMetricPoint(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MetricPoint)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MetricPoint FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMetricPoint(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/MetricPoint.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/MetricPoint.cs new file mode 100644 index 000000000000..8c523231a237 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/MetricPoint.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Metric data point. + public partial class MetricPoint + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Metric name. + /// Metric value. + /// Metric weight. + /// is null. + public MetricPoint(string name, double value, int weight) + { + Argument.AssertNotNull(name, nameof(name)); + + Name = name; + Value = value; + Weight = weight; + } + + /// Initializes a new instance of . + /// Metric name. + /// Metric value. + /// Metric weight. + /// Keeps track of any properties unknown to the library. + internal MetricPoint(string name, double value, int weight, IDictionary serializedAdditionalRawData) + { + Name = name; + Value = value; + Weight = weight; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MetricPoint() + { + } + + /// Metric name. + public string Name { get; } + /// Metric value. + public double Value { get; } + /// Metric weight. + public int Weight { get; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/MonitoringDataPoint.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/MonitoringDataPoint.Serialization.cs new file mode 100644 index 000000000000..7919da945ac9 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/MonitoringDataPoint.Serialization.cs @@ -0,0 +1,337 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class MonitoringDataPoint : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MonitoringDataPoint)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("Version"u8); + writer.WriteStringValue(Version); + writer.WritePropertyName("InvariantVersion"u8); + writer.WriteNumberValue(InvariantVersion); + writer.WritePropertyName("Instance"u8); + writer.WriteStringValue(Instance); + writer.WritePropertyName("RoleName"u8); + writer.WriteStringValue(RoleName); + writer.WritePropertyName("MachineName"u8); + writer.WriteStringValue(MachineName); + writer.WritePropertyName("StreamId"u8); + writer.WriteStringValue(StreamId); + if (Optional.IsDefined(Timestamp)) + { + writer.WritePropertyName("Timestamp"u8); + writer.WriteStringValue(Timestamp.Value, "O"); + } + if (Optional.IsDefined(TransmissionTime)) + { + writer.WritePropertyName("TransmissionTime"u8); + writer.WriteStringValue(TransmissionTime.Value, "O"); + } + writer.WritePropertyName("IsWebApp"u8); + writer.WriteBooleanValue(IsWebApp); + writer.WritePropertyName("PerformanceCollectionSupported"u8); + writer.WriteBooleanValue(PerformanceCollectionSupported); + if (Optional.IsCollectionDefined(Metrics)) + { + writer.WritePropertyName("Metrics"u8); + writer.WriteStartArray(); + foreach (var item in Metrics) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Documents)) + { + writer.WritePropertyName("Documents"u8); + writer.WriteStartArray(); + foreach (var item in Documents) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(TopCpuProcesses)) + { + writer.WritePropertyName("TopCpuProcesses"u8); + writer.WriteStartArray(); + foreach (var item in TopCpuProcesses) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(CollectionConfigurationErrors)) + { + writer.WritePropertyName("CollectionConfigurationErrors"u8); + writer.WriteStartArray(); + foreach (var item in CollectionConfigurationErrors) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + MonitoringDataPoint IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MonitoringDataPoint)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMonitoringDataPoint(document.RootElement, options); + } + + internal static MonitoringDataPoint DeserializeMonitoringDataPoint(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string version = default; + int invariantVersion = default; + string instance = default; + string roleName = default; + string machineName = default; + string streamId = default; + DateTimeOffset? timestamp = default; + DateTimeOffset? transmissionTime = default; + bool isWebApp = default; + bool performanceCollectionSupported = default; + IList metrics = default; + IList documents = default; + IList topCpuProcesses = default; + IList collectionConfigurationErrors = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Version"u8)) + { + version = property.Value.GetString(); + continue; + } + if (property.NameEquals("InvariantVersion"u8)) + { + invariantVersion = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("Instance"u8)) + { + instance = property.Value.GetString(); + continue; + } + if (property.NameEquals("RoleName"u8)) + { + roleName = property.Value.GetString(); + continue; + } + if (property.NameEquals("MachineName"u8)) + { + machineName = property.Value.GetString(); + continue; + } + if (property.NameEquals("StreamId"u8)) + { + streamId = property.Value.GetString(); + continue; + } + if (property.NameEquals("Timestamp"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + timestamp = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("TransmissionTime"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + transmissionTime = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("IsWebApp"u8)) + { + isWebApp = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("PerformanceCollectionSupported"u8)) + { + performanceCollectionSupported = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("Metrics"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(MetricPoint.DeserializeMetricPoint(item, options)); + } + metrics = array; + continue; + } + if (property.NameEquals("Documents"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(DocumentIngress.DeserializeDocumentIngress(item, options)); + } + documents = array; + continue; + } + if (property.NameEquals("TopCpuProcesses"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ProcessCpuData.DeserializeProcessCpuData(item, options)); + } + topCpuProcesses = array; + continue; + } + if (property.NameEquals("CollectionConfigurationErrors"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(CollectionConfigurationError.DeserializeCollectionConfigurationError(item, options)); + } + collectionConfigurationErrors = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MonitoringDataPoint( + version, + invariantVersion, + instance, + roleName, + machineName, + streamId, + timestamp, + transmissionTime, + isWebApp, + performanceCollectionSupported, + metrics ?? new ChangeTrackingList(), + documents ?? new ChangeTrackingList(), + topCpuProcesses ?? new ChangeTrackingList(), + collectionConfigurationErrors ?? new ChangeTrackingList(), + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MonitoringDataPoint)} does not support writing '{options.Format}' format."); + } + } + + MonitoringDataPoint IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeMonitoringDataPoint(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MonitoringDataPoint)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MonitoringDataPoint FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMonitoringDataPoint(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/MonitoringDataPoint.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/MonitoringDataPoint.cs new file mode 100644 index 000000000000..5198042c9af1 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/MonitoringDataPoint.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Monitoring data point coming from the client, which includes metrics, documents and other metadata info. + public partial class MonitoringDataPoint + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Application Insights SDK version. + /// Version/generation of the data contract (MonitoringDataPoint) between SDK and Live Metrics. + /// Service instance name where Application Insights SDK lives. + /// Service role name. + /// Computer name where Application Insights SDK lives. + /// Identifies an Application Insights SDK as a trusted agent to report metrics and documents. + /// True if the current application is an Azure Web App. + /// True if performance counters collection is supported. + /// , , , or is null. + public MonitoringDataPoint(string version, int invariantVersion, string instance, string roleName, string machineName, string streamId, bool isWebApp, bool performanceCollectionSupported) + { + Argument.AssertNotNull(version, nameof(version)); + Argument.AssertNotNull(instance, nameof(instance)); + Argument.AssertNotNull(roleName, nameof(roleName)); + Argument.AssertNotNull(machineName, nameof(machineName)); + Argument.AssertNotNull(streamId, nameof(streamId)); + + Version = version; + InvariantVersion = invariantVersion; + Instance = instance; + RoleName = roleName; + MachineName = machineName; + StreamId = streamId; + IsWebApp = isWebApp; + PerformanceCollectionSupported = performanceCollectionSupported; + Metrics = new ChangeTrackingList(); + Documents = new ChangeTrackingList(); + TopCpuProcesses = new ChangeTrackingList(); + CollectionConfigurationErrors = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// Application Insights SDK version. + /// Version/generation of the data contract (MonitoringDataPoint) between SDK and Live Metrics. + /// Service instance name where Application Insights SDK lives. + /// Service role name. + /// Computer name where Application Insights SDK lives. + /// Identifies an Application Insights SDK as a trusted agent to report metrics and documents. + /// Data point generation timestamp. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. + /// True if the current application is an Azure Web App. + /// True if performance counters collection is supported. + /// An array of metric data points. + /// + /// An array of documents of a specific type {Request}, {RemoteDependency}, {Exception}, {Event}, or {Trace} + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + /// An array of top cpu consumption data point. + /// An array of error while SDK parses and applies the {CollectionConfigurationInfo} provided by Live Metrics. + /// Keeps track of any properties unknown to the library. + internal MonitoringDataPoint(string version, int invariantVersion, string instance, string roleName, string machineName, string streamId, DateTimeOffset? timestamp, DateTimeOffset? transmissionTime, bool isWebApp, bool performanceCollectionSupported, IList metrics, IList documents, IList topCpuProcesses, IList collectionConfigurationErrors, IDictionary serializedAdditionalRawData) + { + Version = version; + InvariantVersion = invariantVersion; + Instance = instance; + RoleName = roleName; + MachineName = machineName; + StreamId = streamId; + Timestamp = timestamp; + TransmissionTime = transmissionTime; + IsWebApp = isWebApp; + PerformanceCollectionSupported = performanceCollectionSupported; + Metrics = metrics; + Documents = documents; + TopCpuProcesses = topCpuProcesses; + CollectionConfigurationErrors = collectionConfigurationErrors; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MonitoringDataPoint() + { + } + + /// Application Insights SDK version. + public string Version { get; } + /// Version/generation of the data contract (MonitoringDataPoint) between SDK and Live Metrics. + public int InvariantVersion { get; } + /// Service instance name where Application Insights SDK lives. + public string Instance { get; } + /// Service role name. + public string RoleName { get; } + /// Computer name where Application Insights SDK lives. + public string MachineName { get; } + /// Identifies an Application Insights SDK as a trusted agent to report metrics and documents. + public string StreamId { get; } + /// Data point generation timestamp. + public DateTimeOffset? Timestamp { get; set; } + /// Timestamp when the client transmits the metrics and documents to Live Metrics. + public DateTimeOffset? TransmissionTime { get; set; } + /// True if the current application is an Azure Web App. + public bool IsWebApp { get; } + /// True if performance counters collection is supported. + public bool PerformanceCollectionSupported { get; } + /// An array of metric data points. + public IList Metrics { get; } + /// + /// An array of documents of a specific type {Request}, {RemoteDependency}, {Exception}, {Event}, or {Trace} + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + public IList Documents { get; } + /// An array of top cpu consumption data point. + public IList TopCpuProcesses { get; } + /// An array of error while SDK parses and applies the {CollectionConfigurationInfo} provided by Live Metrics. + public IList CollectionConfigurationErrors { get; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/PredicateType.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/PredicateType.cs new file mode 100644 index 000000000000..1804309fc4e3 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/PredicateType.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace LiveMetrics +{ + /// Enum representing the different types of predicates. + public readonly partial struct PredicateType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public PredicateType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string EqualValue = "Equal"; + private const string NotEqualValue = "NotEqual"; + private const string LessThanValue = "LessThan"; + private const string GreaterThanValue = "GreaterThan"; + private const string LessThanOrEqualValue = "LessThanOrEqual"; + private const string GreaterThanOrEqualValue = "GreaterThanOrEqual"; + private const string ContainsValue = "Contains"; + private const string DoesNotContainValue = "DoesNotContain"; + + /// Represents an equality predicate. + public static PredicateType Equal { get; } = new PredicateType(EqualValue); + /// Represents a not-equal predicate. + public static PredicateType NotEqual { get; } = new PredicateType(NotEqualValue); + /// Represents a less-than predicate. + public static PredicateType LessThan { get; } = new PredicateType(LessThanValue); + /// Represents a greater-than predicate. + public static PredicateType GreaterThan { get; } = new PredicateType(GreaterThanValue); + /// Represents a less-than-or-equal predicate. + public static PredicateType LessThanOrEqual { get; } = new PredicateType(LessThanOrEqualValue); + /// Represents a greater-than-or-equal predicate. + public static PredicateType GreaterThanOrEqual { get; } = new PredicateType(GreaterThanOrEqualValue); + /// Represents a contains predicate. + public static PredicateType Contains { get; } = new PredicateType(ContainsValue); + /// Represents a does-not-contain predicate. + public static PredicateType DoesNotContain { get; } = new PredicateType(DoesNotContainValue); + /// Determines if two values are the same. + public static bool operator ==(PredicateType left, PredicateType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(PredicateType left, PredicateType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator PredicateType(string value) => new PredicateType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is PredicateType other && Equals(other); + /// + public bool Equals(PredicateType 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/applicationinsights.livemetrics/LiveMetrics/src/Generated/ProcessCpuData.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/ProcessCpuData.Serialization.cs new file mode 100644 index 000000000000..62a0419aad72 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/ProcessCpuData.Serialization.cs @@ -0,0 +1,144 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class ProcessCpuData : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ProcessCpuData)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("ProcessName"u8); + writer.WriteStringValue(ProcessName); + writer.WritePropertyName("CpuPercentage"u8); + writer.WriteNumberValue(CpuPercentage); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + ProcessCpuData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ProcessCpuData)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeProcessCpuData(document.RootElement, options); + } + + internal static ProcessCpuData DeserializeProcessCpuData(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string processName = default; + int cpuPercentage = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("ProcessName"u8)) + { + processName = property.Value.GetString(); + continue; + } + if (property.NameEquals("CpuPercentage"u8)) + { + cpuPercentage = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ProcessCpuData(processName, cpuPercentage, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ProcessCpuData)} does not support writing '{options.Format}' format."); + } + } + + ProcessCpuData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeProcessCpuData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ProcessCpuData)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ProcessCpuData FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeProcessCpuData(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/ProcessCpuData.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/ProcessCpuData.cs new file mode 100644 index 000000000000..c4f1d9457d5e --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/ProcessCpuData.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// CPU consumption datapoint. + public partial class ProcessCpuData + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Process name. + /// CPU consumption percentage. + /// is null. + public ProcessCpuData(string processName, int cpuPercentage) + { + Argument.AssertNotNull(processName, nameof(processName)); + + ProcessName = processName; + CpuPercentage = cpuPercentage; + } + + /// Initializes a new instance of . + /// Process name. + /// CPU consumption percentage. + /// Keeps track of any properties unknown to the library. + internal ProcessCpuData(string processName, int cpuPercentage, IDictionary serializedAdditionalRawData) + { + ProcessName = processName; + CpuPercentage = cpuPercentage; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ProcessCpuData() + { + } + + /// Process name. + public string ProcessName { get; } + /// CPU consumption percentage. + public int CpuPercentage { get; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/QuotaConfigurationInfo.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/QuotaConfigurationInfo.Serialization.cs new file mode 100644 index 000000000000..9dbaece79bf9 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/QuotaConfigurationInfo.Serialization.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class QuotaConfigurationInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(QuotaConfigurationInfo)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(InitialQuota)) + { + writer.WritePropertyName("InitialQuota"u8); + writer.WriteNumberValue(InitialQuota.Value); + } + writer.WritePropertyName("MaxQuota"u8); + writer.WriteNumberValue(MaxQuota); + writer.WritePropertyName("QuotaAccrualRatePerSec"u8); + writer.WriteNumberValue(QuotaAccrualRatePerSec); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + QuotaConfigurationInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(QuotaConfigurationInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeQuotaConfigurationInfo(document.RootElement, options); + } + + internal static QuotaConfigurationInfo DeserializeQuotaConfigurationInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + float? initialQuota = default; + float maxQuota = default; + float quotaAccrualRatePerSec = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("InitialQuota"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + initialQuota = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("MaxQuota"u8)) + { + maxQuota = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("QuotaAccrualRatePerSec"u8)) + { + quotaAccrualRatePerSec = property.Value.GetSingle(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new QuotaConfigurationInfo(initialQuota, maxQuota, quotaAccrualRatePerSec, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(QuotaConfigurationInfo)} does not support writing '{options.Format}' format."); + } + } + + QuotaConfigurationInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeQuotaConfigurationInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(QuotaConfigurationInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static QuotaConfigurationInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeQuotaConfigurationInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/QuotaConfigurationInfo.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/QuotaConfigurationInfo.cs new file mode 100644 index 000000000000..3c09c73551fb --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/QuotaConfigurationInfo.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Controls document quotas to be sent to Live Metrics. + public partial class QuotaConfigurationInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Max quota. + /// Quota accrual rate per second. + internal QuotaConfigurationInfo(float maxQuota, float quotaAccrualRatePerSec) + { + MaxQuota = maxQuota; + QuotaAccrualRatePerSec = quotaAccrualRatePerSec; + } + + /// Initializes a new instance of . + /// Initial quota. + /// Max quota. + /// Quota accrual rate per second. + /// Keeps track of any properties unknown to the library. + internal QuotaConfigurationInfo(float? initialQuota, float maxQuota, float quotaAccrualRatePerSec, IDictionary serializedAdditionalRawData) + { + InitialQuota = initialQuota; + MaxQuota = maxQuota; + QuotaAccrualRatePerSec = quotaAccrualRatePerSec; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal QuotaConfigurationInfo() + { + } + + /// Initial quota. + public float? InitialQuota { get; } + /// Max quota. + public float MaxQuota { get; } + /// Quota accrual rate per second. + public float QuotaAccrualRatePerSec { get; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/RemoteDependency.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/RemoteDependency.Serialization.cs new file mode 100644 index 000000000000..7f3d42e578fa --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/RemoteDependency.Serialization.cs @@ -0,0 +1,238 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class RemoteDependency : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RemoteDependency)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("Name"u8); + writer.WriteStringValue(Name); + } + if (Optional.IsDefined(CommandName)) + { + writer.WritePropertyName("CommandName"u8); + writer.WriteStringValue(CommandName); + } + if (Optional.IsDefined(ResultCode)) + { + writer.WritePropertyName("ResultCode"u8); + writer.WriteStringValue(ResultCode); + } + if (Optional.IsDefined(Duration)) + { + writer.WritePropertyName("Duration"u8); + writer.WriteStringValue(Duration); + } + writer.WritePropertyName("DocumentType"u8); + writer.WriteStringValue(DocumentType.ToString()); + if (Optional.IsCollectionDefined(DocumentStreamIds)) + { + writer.WritePropertyName("DocumentStreamIds"u8); + writer.WriteStartArray(); + foreach (var item in DocumentStreamIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Properties)) + { + writer.WritePropertyName("Properties"u8); + writer.WriteStartArray(); + foreach (var item in Properties) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + RemoteDependency IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RemoteDependency)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRemoteDependency(document.RootElement, options); + } + + internal static RemoteDependency DeserializeRemoteDependency(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + string commandName = default; + string resultCode = default; + string duration = default; + DocumentType documentType = default; + IList documentStreamIds = default; + IList properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("CommandName"u8)) + { + commandName = property.Value.GetString(); + continue; + } + if (property.NameEquals("ResultCode"u8)) + { + resultCode = property.Value.GetString(); + continue; + } + if (property.NameEquals("Duration"u8)) + { + duration = property.Value.GetString(); + continue; + } + if (property.NameEquals("DocumentType"u8)) + { + documentType = new DocumentType(property.Value.GetString()); + continue; + } + if (property.NameEquals("DocumentStreamIds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + documentStreamIds = array; + continue; + } + if (property.NameEquals("Properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + properties = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RemoteDependency( + documentType, + documentStreamIds ?? new ChangeTrackingList(), + properties ?? new ChangeTrackingList(), + serializedAdditionalRawData, + name, + commandName, + resultCode, + duration); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RemoteDependency)} does not support writing '{options.Format}' format."); + } + } + + RemoteDependency IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeRemoteDependency(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RemoteDependency)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RemoteDependency FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRemoteDependency(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/RemoteDependency.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/RemoteDependency.cs new file mode 100644 index 000000000000..6cab0e3ad447 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/RemoteDependency.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// RemoteDependency document type. + public partial class RemoteDependency : DocumentIngress + { + /// Initializes a new instance of . + public RemoteDependency() + { + DocumentType = DocumentType.RemoteDependency; + } + + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + /// Name of the command initiated with this dependency call, e.g., GET /username. + /// URL of the dependency call to the target, with all query string parameters. + /// Result code of a dependency call. Examples are SQL error code and HTTP status code. + /// Request duration in ISO 8601 duration format, i.e., P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W. + internal RemoteDependency(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData, string name, string commandName, string resultCode, string duration) : base(documentType, documentStreamIds, properties, serializedAdditionalRawData) + { + Name = name; + CommandName = commandName; + ResultCode = resultCode; + Duration = duration; + } + + /// Name of the command initiated with this dependency call, e.g., GET /username. + public string Name { get; set; } + /// URL of the dependency call to the target, with all query string parameters. + public string CommandName { get; set; } + /// Result code of a dependency call. Examples are SQL error code and HTTP status code. + public string ResultCode { get; set; } + /// Request duration in ISO 8601 duration format, i.e., P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W. + public string Duration { get; set; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Request.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Request.Serialization.cs new file mode 100644 index 000000000000..ac09ba508b63 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Request.Serialization.cs @@ -0,0 +1,242 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class Request : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Request)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("Name"u8); + writer.WriteStringValue(Name); + } + if (Optional.IsDefined(Url)) + { + writer.WritePropertyName("Url"u8); + writer.WriteStringValue(Url.AbsoluteUri); + } + if (Optional.IsDefined(ResponseCode)) + { + writer.WritePropertyName("ResponseCode"u8); + writer.WriteStringValue(ResponseCode); + } + if (Optional.IsDefined(Duration)) + { + writer.WritePropertyName("Duration"u8); + writer.WriteStringValue(Duration); + } + writer.WritePropertyName("DocumentType"u8); + writer.WriteStringValue(DocumentType.ToString()); + if (Optional.IsCollectionDefined(DocumentStreamIds)) + { + writer.WritePropertyName("DocumentStreamIds"u8); + writer.WriteStartArray(); + foreach (var item in DocumentStreamIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Properties)) + { + writer.WritePropertyName("Properties"u8); + writer.WriteStartArray(); + foreach (var item in Properties) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + Request IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Request)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRequest(document.RootElement, options); + } + + internal static Request DeserializeRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + Uri url = default; + string responseCode = default; + string duration = default; + DocumentType documentType = default; + IList documentStreamIds = default; + IList properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("Url"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + url = new Uri(property.Value.GetString()); + continue; + } + if (property.NameEquals("ResponseCode"u8)) + { + responseCode = property.Value.GetString(); + continue; + } + if (property.NameEquals("Duration"u8)) + { + duration = property.Value.GetString(); + continue; + } + if (property.NameEquals("DocumentType"u8)) + { + documentType = new DocumentType(property.Value.GetString()); + continue; + } + if (property.NameEquals("DocumentStreamIds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + documentStreamIds = array; + continue; + } + if (property.NameEquals("Properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + properties = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Request( + documentType, + documentStreamIds ?? new ChangeTrackingList(), + properties ?? new ChangeTrackingList(), + serializedAdditionalRawData, + name, + url, + responseCode, + duration); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Request)} does not support writing '{options.Format}' format."); + } + } + + Request IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Request)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new Request FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRequest(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Request.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Request.cs new file mode 100644 index 000000000000..98ccc03686b9 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Request.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Request document type. + public partial class Request : DocumentIngress + { + /// Initializes a new instance of . + public Request() + { + DocumentType = DocumentType.Request; + } + + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + /// Name of the request, e.g., 'GET /values/{id}'. + /// Request URL with all query string parameters. + /// Result of a request execution. For http requests, it could be some HTTP status code. + /// Request duration in ISO 8601 duration format, i.e., P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W. + internal Request(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData, string name, Uri url, string responseCode, string duration) : base(documentType, documentStreamIds, properties, serializedAdditionalRawData) + { + Name = name; + Url = url; + ResponseCode = responseCode; + Duration = duration; + } + + /// Name of the request, e.g., 'GET /values/{id}'. + public string Name { get; set; } + /// Request URL with all query string parameters. + public Uri Url { get; set; } + /// Result of a request execution. For http requests, it could be some HTTP status code. + public string ResponseCode { get; set; } + /// Request duration in ISO 8601 duration format, i.e., P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W. + public string Duration { get; set; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/TelemetryType.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/TelemetryType.cs new file mode 100644 index 000000000000..9d35769389dc --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/TelemetryType.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace LiveMetrics +{ + /// Telemetry type. + public readonly partial struct TelemetryType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public TelemetryType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string RequestValue = "Request"; + private const string DependencyValue = "Dependency"; + private const string ExceptionValue = "Exception"; + private const string EventValue = "Event"; + private const string MetricValue = "Metric"; + private const string PerformanceCounterValue = "PerformanceCounter"; + private const string TraceValue = "Trace"; + + /// Represents a request telemetry type. + public static TelemetryType Request { get; } = new TelemetryType(RequestValue); + /// Represents a dependency telemetry type. + public static TelemetryType Dependency { get; } = new TelemetryType(DependencyValue); + /// Represents an exception telemetry type. + public static TelemetryType Exception { get; } = new TelemetryType(ExceptionValue); + /// Represents an event telemetry type. + public static TelemetryType Event { get; } = new TelemetryType(EventValue); + /// Represents a metric telemetry type. + public static TelemetryType Metric { get; } = new TelemetryType(MetricValue); + /// Represents a performance counter telemetry type. + public static TelemetryType PerformanceCounter { get; } = new TelemetryType(PerformanceCounterValue); + /// Represents a trace telemetry type. + public static TelemetryType Trace { get; } = new TelemetryType(TraceValue); + /// Determines if two values are the same. + public static bool operator ==(TelemetryType left, TelemetryType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(TelemetryType left, TelemetryType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator TelemetryType(string value) => new TelemetryType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is TelemetryType other && Equals(other); + /// + public bool Equals(TelemetryType 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/applicationinsights.livemetrics/LiveMetrics/src/Generated/Trace.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Trace.Serialization.cs new file mode 100644 index 000000000000..a03b5793b57b --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Trace.Serialization.cs @@ -0,0 +1,197 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class Trace : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Trace)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Message)) + { + writer.WritePropertyName("Message"u8); + writer.WriteStringValue(Message); + } + writer.WritePropertyName("DocumentType"u8); + writer.WriteStringValue(DocumentType.ToString()); + if (Optional.IsCollectionDefined(DocumentStreamIds)) + { + writer.WritePropertyName("DocumentStreamIds"u8); + writer.WriteStartArray(); + foreach (var item in DocumentStreamIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Properties)) + { + writer.WritePropertyName("Properties"u8); + writer.WriteStartArray(); + foreach (var item in Properties) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + Trace IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Trace)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTrace(document.RootElement, options); + } + + internal static Trace DeserializeTrace(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string message = default; + DocumentType documentType = default; + IList documentStreamIds = default; + IList properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Message"u8)) + { + message = property.Value.GetString(); + continue; + } + if (property.NameEquals("DocumentType"u8)) + { + documentType = new DocumentType(property.Value.GetString()); + continue; + } + if (property.NameEquals("DocumentStreamIds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + documentStreamIds = array; + continue; + } + if (property.NameEquals("Properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + properties = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Trace(documentType, documentStreamIds ?? new ChangeTrackingList(), properties ?? new ChangeTrackingList(), serializedAdditionalRawData, message); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Trace)} does not support writing '{options.Format}' format."); + } + } + + Trace IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeTrace(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Trace)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new Trace FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeTrace(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Trace.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Trace.cs new file mode 100644 index 000000000000..411e5ec67d06 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/Trace.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Trace document type. + public partial class Trace : DocumentIngress + { + /// Initializes a new instance of . + public Trace() + { + DocumentType = DocumentType.Trace; + } + + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + /// Trace message. + internal Trace(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData, string message) : base(documentType, documentStreamIds, properties, serializedAdditionalRawData) + { + Message = message; + } + + /// Trace message. + public string Message { get; set; } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/UnknownDocumentIngress.Serialization.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/UnknownDocumentIngress.Serialization.cs new file mode 100644 index 000000000000..ff190b1e9b43 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/UnknownDocumentIngress.Serialization.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + internal partial class UnknownDocumentIngress : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentIngress)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("DocumentType"u8); + writer.WriteStringValue(DocumentType.ToString()); + if (Optional.IsCollectionDefined(DocumentStreamIds)) + { + writer.WritePropertyName("DocumentStreamIds"u8); + writer.WriteStartArray(); + foreach (var item in DocumentStreamIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Properties)) + { + writer.WritePropertyName("Properties"u8); + writer.WriteStartArray(); + foreach (var item in Properties) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + DocumentIngress IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentIngress)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDocumentIngress(document.RootElement, options); + } + + internal static UnknownDocumentIngress DeserializeUnknownDocumentIngress(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + DocumentType documentType = "AutoRest.CSharp.Output.Models.Types.EnumTypeValue"; + IList documentStreamIds = default; + IList properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("DocumentType"u8)) + { + documentType = new DocumentType(property.Value.GetString()); + continue; + } + if (property.NameEquals("DocumentStreamIds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + documentStreamIds = array; + continue; + } + if (property.NameEquals("Properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + properties = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownDocumentIngress(documentType, documentStreamIds ?? new ChangeTrackingList(), properties ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(DocumentIngress)} does not support writing '{options.Format}' format."); + } + } + + DocumentIngress IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeDocumentIngress(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DocumentIngress)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownDocumentIngress FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownDocumentIngress(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/UnknownDocumentIngress.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/UnknownDocumentIngress.cs new file mode 100644 index 000000000000..6212f92f2bc6 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Generated/UnknownDocumentIngress.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Unknown version of DocumentIngress. + internal partial class UnknownDocumentIngress : DocumentIngress + { + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + internal UnknownDocumentIngress(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData) : base(documentType, documentStreamIds, properties, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownDocumentIngress() + { + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/LiveMetrics.csproj b/sdk/applicationinsights.livemetrics/LiveMetrics/src/LiveMetrics.csproj new file mode 100644 index 000000000000..17d89db02593 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/LiveMetrics.csproj @@ -0,0 +1,19 @@ + + + This is the LiveMetrics client library for developing .NET applications with rich experience. + Azure SDK Code Generation LiveMetrics for Azure Data Plane + 1.0.0-beta.1 + LiveMetrics + $(RequiredTargetFrameworks) + true + + + + + + + + + + + diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/src/Properties/AssemblyInfo.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..f3bafe56f482 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/src/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("LiveMetrics.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/tests/Generated/Samples/Samples_LiveMetricsClient.cs b/sdk/applicationinsights.livemetrics/LiveMetrics/tests/Generated/Samples/Samples_LiveMetricsClient.cs new file mode 100644 index 000000000000..94c8c0332502 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/tests/Generated/Samples/Samples_LiveMetricsClient.cs @@ -0,0 +1,454 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace LiveMetrics.Samples +{ + public partial class Samples_LiveMetricsClient + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_LiveMetrics_IsSubscribed_LiveMetricsClientChecksIfItsDataIsSubscribedTo() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + using RequestContent content = RequestContent.Create(new + { + Instance = "server-pc-name", + InvariantVersion = 5, + IsWebApp = false, + MachineName = "SERVER-PC-NAME", + PerformanceCollectionSupported = true, + RoleName = "", + StreamId = "41112328328b4edb9aa777aa6d675186", + Timestamp = "2024-02-01T21:36:32.5717105Z", + Version = "2.21.0-429", + }); + Response response = client.IsSubscribed("4473b98e-c70d-4220-b57c-2984c2a0e5cd", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("ETag").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Projection").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Aggregation").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("BackEndAggregation").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_LiveMetrics_IsSubscribed_LiveMetricsClientChecksIfItsDataIsSubscribedTo_Async() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + using RequestContent content = RequestContent.Create(new + { + Instance = "server-pc-name", + InvariantVersion = 5, + IsWebApp = false, + MachineName = "SERVER-PC-NAME", + PerformanceCollectionSupported = true, + RoleName = "", + StreamId = "41112328328b4edb9aa777aa6d675186", + Timestamp = "2024-02-01T21:36:32.5717105Z", + Version = "2.21.0-429", + }); + Response response = await client.IsSubscribedAsync("4473b98e-c70d-4220-b57c-2984c2a0e5cd", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("ETag").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Projection").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Aggregation").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("BackEndAggregation").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_LiveMetrics_IsSubscribed_LiveMetricsClientChecksIfItsDataIsSubscribedTo_Convenience() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + Response response = client.IsSubscribed("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_LiveMetrics_IsSubscribed_LiveMetricsClientChecksIfItsDataIsSubscribedTo_Convenience_Async() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + Response response = await client.IsSubscribedAsync("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_LiveMetrics_Publish_LiveMetricsClientPublishesLiveMetrics() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + using RequestContent content = RequestContent.Create(new object[] + { +new +{ +Instance = "server-pc-name", +Metrics = new object[] +{ +new +{ +Name = "\\ApplicationInsights\\Requests/Sec", +Value = 0.9989, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Request Duration", +Value = 2.266, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Requests Failed/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Requests Succeeded/Sec", +Value = 0.9989, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Calls/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Call Duration", +Value = 0, +Weight = 0, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Calls Failed/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Calls Succeeded/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Exceptions/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ASP.NET Applications(__Total__)\\Requests In Application Queue", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\Memory\\Committed Bytes", +Value = 19902644224, +Weight = 1, +}, +new +{ +Name = "\\Processor(_Total)\\% Processor Time", +Value = 54.738, +Weight = 1, +} +}, +Documents = new object[] +{ +new +{ +DocumentType = "Exception", +ExceptionMessage = "Value cannot be null.\r\nParameter name: This exception has properties", +ExceptionType = "System.ArgumentNullException", +Properties = new object[] +{ +new +{ +key = "UserProp2", +value = "UserPropValue2", +}, +new +{ +key = "DeveloperMode", +value = "true", +}, +new +{ +key = "UserProp1", +value = "UserPropValue1", +} +}, +}, +new +{ +DocumentType = "Request", +Duration = "PT0.0010105S", +Name = "GET Home/blablabla", +Properties = new object[] +{ +new +{ +key = "DeveloperMode", +value = "true", +} +}, +ResponseCode = "404", +Url = "http://40.78.109.134/Home/blablabla", +} +}, +Timestamp = "2024-02-01T21:36:30.5717105Z", +Version = "2.1.0.42", +InvariantVersion = 5, +IsWebApp = false, +MachineName = "SERVER-PC-NAME", +PerformanceCollectionSupported = true, +RoleName = "", +StreamId = "41112328328b4edb9aa777aa6d675186", +} + }); + Response response = client.Publish("4473b98e-c70d-4220-b57c-2984c2a0e5cd", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("ETag").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Projection").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Aggregation").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("BackEndAggregation").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_LiveMetrics_Publish_LiveMetricsClientPublishesLiveMetrics_Async() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + using RequestContent content = RequestContent.Create(new object[] + { +new +{ +Instance = "server-pc-name", +Metrics = new object[] +{ +new +{ +Name = "\\ApplicationInsights\\Requests/Sec", +Value = 0.9989, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Request Duration", +Value = 2.266, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Requests Failed/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Requests Succeeded/Sec", +Value = 0.9989, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Calls/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Call Duration", +Value = 0, +Weight = 0, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Calls Failed/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Calls Succeeded/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Exceptions/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ASP.NET Applications(__Total__)\\Requests In Application Queue", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\Memory\\Committed Bytes", +Value = 19902644224, +Weight = 1, +}, +new +{ +Name = "\\Processor(_Total)\\% Processor Time", +Value = 54.738, +Weight = 1, +} +}, +Documents = new object[] +{ +new +{ +DocumentType = "Exception", +ExceptionMessage = "Value cannot be null.\r\nParameter name: This exception has properties", +ExceptionType = "System.ArgumentNullException", +Properties = new object[] +{ +new +{ +key = "UserProp2", +value = "UserPropValue2", +}, +new +{ +key = "DeveloperMode", +value = "true", +}, +new +{ +key = "UserProp1", +value = "UserPropValue1", +} +}, +}, +new +{ +DocumentType = "Request", +Duration = "PT0.0010105S", +Name = "GET Home/blablabla", +Properties = new object[] +{ +new +{ +key = "DeveloperMode", +value = "true", +} +}, +ResponseCode = "404", +Url = "http://40.78.109.134/Home/blablabla", +} +}, +Timestamp = "2024-02-01T21:36:30.5717105Z", +Version = "2.1.0.42", +InvariantVersion = 5, +IsWebApp = false, +MachineName = "SERVER-PC-NAME", +PerformanceCollectionSupported = true, +RoleName = "", +StreamId = "41112328328b4edb9aa777aa6d675186", +} + }); + Response response = await client.PublishAsync("4473b98e-c70d-4220-b57c-2984c2a0e5cd", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("ETag").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Projection").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Aggregation").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("BackEndAggregation").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_LiveMetrics_Publish_LiveMetricsClientPublishesLiveMetrics_Convenience() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + Response response = client.Publish("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_LiveMetrics_Publish_LiveMetricsClientPublishesLiveMetrics_Convenience_Async() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + Response response = await client.PublishAsync("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); + } + } +} diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/tests/LiveMetrics.Tests.csproj b/sdk/applicationinsights.livemetrics/LiveMetrics/tests/LiveMetrics.Tests.csproj new file mode 100644 index 000000000000..56fe204affe9 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/tests/LiveMetrics.Tests.csproj @@ -0,0 +1,19 @@ + + + $(RequiredTargetFrameworks) + + $(NoWarn);CS1591 + + + + + + + + + + + + + + diff --git a/sdk/applicationinsights.livemetrics/LiveMetrics/tsp-location.yaml b/sdk/applicationinsights.livemetrics/LiveMetrics/tsp-location.yaml new file mode 100644 index 000000000000..31ae21f2fea3 --- /dev/null +++ b/sdk/applicationinsights.livemetrics/LiveMetrics/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/applicationinsights/ApplicationInsights.LiveMetrics +commit: 9e35bd472e0aca04a5ec037f3cfe60c875b6fde7 +repo: test-repo-billy/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/computefleet/Azure.ResourceManager.ComputeFleet/tsp-location.yaml b/sdk/computefleet/Azure.ResourceManager.ComputeFleet/tsp-location.yaml index b5e602272d0c..49f2b9a0773f 100644 --- a/sdk/computefleet/Azure.ResourceManager.ComputeFleet/tsp-location.yaml +++ b/sdk/computefleet/Azure.ResourceManager.ComputeFleet/tsp-location.yaml @@ -1,3 +1,4 @@ directory: specification/azurefleet/AzureFleet.Management -commit: c0a15f4623eb11f745f890089f3d46d8a538524f -repo: Azure/azure-rest-api-specs \ No newline at end of file +commit: 9e35bd472e0aca04a5ec037f3cfe60c875b6fde7 +repo: test-repo-billy/azure-rest-api-specs +additionalDirectories: