diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/Azure.Analytics.OnlineExperimentation.sln b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/Azure.Analytics.OnlineExperimentation.sln new file mode 100644 index 000000000000..939ec6a0bab8 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/Azure.Analytics.OnlineExperimentation.sln @@ -0,0 +1,56 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core.TestFramework", "..\..\core\Azure.Core.TestFramework\src\Azure.Core.TestFramework.csproj", "{ECC730C1-4AEA-420C-916A-66B19B79E4DC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.Analytics.OnlineExperimentation", "src\Azure.Analytics.OnlineExperimentation.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.Analytics.OnlineExperimentation.Tests", "tests\Azure.Analytics.OnlineExperimentation.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 + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/CHANGELOG.md b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/CHANGELOG.md new file mode 100644 index 000000000000..8b33f0fedccc --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/CHANGELOG.md @@ -0,0 +1,11 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes \ No newline at end of file diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/Directory.Build.props b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/Directory.Build.props new file mode 100644 index 000000000000..63bd836ad44b --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/Directory.Build.props @@ -0,0 +1,6 @@ + + + + diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/README.md b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/README.md new file mode 100644 index 000000000000..2332fdf68c52 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/README.md @@ -0,0 +1,107 @@ +# Azure.Analytics.OnlineExperimentation client library for .NET + +Azure.Analytics.OnlineExperimentation is a managed service that helps developers get secret simply and securely. + +Use the client library for to: + +* [Get secret](https://docs.microsoft.com/azure) + +[Source code][source_root] | [Package (NuGet)][package] | [API reference documentation][reference_docs] | [Product documentation][azconfig_docs] | [Samples][source_samples] + + [Source code](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src) | [Package (NuGet)](https://www.nuget.org/packages) | [API reference documentation](https://azure.github.io/azure-sdk-for-net) | [Product documentation](https://docs.microsoft.com/azure) + +## Getting started + +This section should include everything a developer needs to do to install and create their first client connection *very quickly*. + +### Install the package + +First, provide instruction for obtaining and installing the package or library. This section might include only a single line of code, like `dotnet add package package-name`, but should enable a developer to successfully install the package from NuGet, npm, or even cloning a GitHub repository. + +Install the client library for .NET with [NuGet](https://www.nuget.org/ ): + +```dotnetcli +dotnet add package Azure.Analytics.OnlineExperimentation --prerelease +``` + +### Prerequisites + +Include a section after the install command that details any requirements that must be satisfied before a developer can [authenticate](#authenticate-the-client) and test all of the snippets in the [Examples](#examples) section. For example, for Cosmos DB: + +> You must have an [Azure subscription](https://azure.microsoft.com/free/dotnet/) and [Cosmos DB account](https://docs.microsoft.com/azure/cosmos-db/account-overview) (SQL API). In order to take advantage of the C# 8.0 syntax, it is recommended that you compile using the [.NET Core SDK](https://dotnet.microsoft.com/download) 3.0 or higher with a [language version](https://docs.microsoft.com/dotnet/csharp/language-reference/configure-language-version#override-a-default) of `latest`. It is also possible to compile with the .NET Core SDK 2.1.x using a language version of `preview`. + +### Authenticate the client + +If your library requires authentication for use, such as for Azure services, include instructions and example code needed for initializing and authenticating. + +For example, include details on obtaining an account key and endpoint URI, setting environment variables for each, and initializing the client object. + +### Service API versions + +The client library targets the latest service API version by default. A client instance accepts an optional service API version parameter from its options to specify which API version service to communicate. + +#### Select a service API version + +You have the flexibility to explicitly select a supported service API version when instantiating a client by configuring its associated options. This ensures that the client can communicate with services using the specified API version. + +For example, + +```C# Snippet:CreateClientForSpecificApiVersion +Uri endpoint = new Uri(""); +DefaultAzureCredential credential = new DefaultAzureCredential(); +ClientOptions options = new ClientOptions(ClientOptions.ServiceVersion.) +var client = new Client(endpoint, credential, options); +``` + +When selecting an API version, it's important to verify that there are no breaking changes compared to the latest API version. If there are significant differences, API calls may fail due to incompatibility. + +Always ensure that the chosen API version is fully supported and operational for your specific use case and that it aligns with the service's versioning policy. + +## Key concepts + +The *Key concepts* section should describe the functionality of the main classes. Point out the most important and useful classes in the package (with links to their reference pages) and explain how those classes work together. Feel free to use bulleted lists, tables, code blocks, or even diagrams for clarity. + +Include the *Thread safety* and *Additional concepts* sections below at the end of your *Key concepts* section. You may remove or add links depending on what your library makes use of: + +### Thread safety + +We guarantee that all client instance methods are thread-safe and independent of each other ([guideline](https://azure.github.io/azure-sdk/dotnet_introduction.html#dotnet-service-methods-thread-safety)). This ensures that the recommendation of reusing client instances is always safe, even across threads. + +### Additional concepts + +[Client options](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#configuring-service-clients-using-clientoptions) | +[Accessing the response](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#accessing-http-response-details-using-responset) | +[Long-running operations](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#consuming-long-running-operations-using-operationt) | +[Handling failures](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#reporting-errors-requestfailedexception) | +[Diagnostics](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Diagnostics.md) | +[Mocking](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#mocking) | +[Client lifetime](https://devblogs.microsoft.com/azure-sdk/lifetime-management-and-thread-safety-guarantees-of-azure-sdk-net-clients/) + + +## Examples + +You can familiarize yourself with different APIs using [Samples](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/samples). + +## Troubleshooting + +Describe common errors and exceptions, how to "unpack" them if necessary, and include guidance for graceful handling and recovery. + +Provide information to help developers avoid throttling or other service-enforced errors they might encounter. For example, provide guidance and examples for using retry or connection policies in the API. + +If the package or a related package supports it, include tips for logging or enabling instrumentation to help them debug their code. + +## Next steps + +* Provide a link to additional code examples, ideally to those sitting alongside the README in the package's `/samples` directory. +* If appropriate, point users to other packages that might be useful. +* If you think there's a good chance that developers might stumble across your package in error (because they're searching for specific functionality and mistakenly think the package provides that functionality), point them to the packages they might be looking for. + +## Contributing + +This is a template, but your SDK readme should include details on how to contribute code to the repo/package. + + +[style-guide-msft]: https://docs.microsoft.com/style-guide/capitalization +[style-guide-cloud]: https://aka.ms/azsdk/cloud-style-guide + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-net/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/README.png) \ No newline at end of file diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Azure.Analytics.OnlineExperimentation.csproj b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Azure.Analytics.OnlineExperimentation.csproj new file mode 100644 index 000000000000..7a50b5e01e6a --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Azure.Analytics.OnlineExperimentation.csproj @@ -0,0 +1,19 @@ + + + This is the Azure.Analytics.OnlineExperimentation client library for developing .NET applications with rich experience. + Azure SDK Code Generation Azure.Analytics.OnlineExperimentation for Azure Data Plane + 1.0.0-beta.1 + Azure.Analytics.OnlineExperimentation + $(RequiredTargetFrameworks) + true + + + + + + + + + + + diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AggregatedValue.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AggregatedValue.Serialization.cs new file mode 100644 index 000000000000..3586415a7679 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AggregatedValue.Serialization.cs @@ -0,0 +1,161 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + public partial class AggregatedValue : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AggregatedValue)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("eventName"u8); + writer.WriteStringValue(EventName); + if (Optional.IsDefined(Filter)) + { + writer.WritePropertyName("filter"u8); + writer.WriteStringValue(Filter); + } + writer.WritePropertyName("eventProperty"u8); + writer.WriteStringValue(EventProperty); + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AggregatedValue 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(AggregatedValue)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAggregatedValue(document.RootElement, options); + } + + internal static AggregatedValue DeserializeAggregatedValue(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string eventName = default; + string filter = default; + string eventProperty = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("eventName"u8)) + { + eventName = property.Value.GetString(); + continue; + } + if (property.NameEquals("filter"u8)) + { + filter = property.Value.GetString(); + continue; + } + if (property.NameEquals("eventProperty"u8)) + { + eventProperty = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AggregatedValue(eventName, filter, eventProperty, 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(AggregatedValue)} does not support writing '{options.Format}' format."); + } + } + + AggregatedValue 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAggregatedValue(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AggregatedValue)} 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 AggregatedValue FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAggregatedValue(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AggregatedValue.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AggregatedValue.cs new file mode 100644 index 000000000000..d1429326a68d --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AggregatedValue.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// An event property value aggregated by a metric. + public partial class AggregatedValue + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the event. + /// The key of the event property to aggregate. + /// or is null. + public AggregatedValue(string eventName, string eventProperty) + { + Argument.AssertNotNull(eventName, nameof(eventName)); + Argument.AssertNotNull(eventProperty, nameof(eventProperty)); + + EventName = eventName; + EventProperty = eventProperty; + } + + /// Initializes a new instance of . + /// The name of the event. + /// [Optional] A condition to filter events. + /// The key of the event property to aggregate. + /// Keeps track of any properties unknown to the library. + internal AggregatedValue(string eventName, string filter, string eventProperty, IDictionary serializedAdditionalRawData) + { + EventName = eventName; + Filter = filter; + EventProperty = eventProperty; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AggregatedValue() + { + } + + /// The name of the event. + public string EventName { get; set; } + /// [Optional] A condition to filter events. + public string Filter { get; set; } + /// The key of the event property to aggregate. + public string EventProperty { get; set; } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AnalyticsOnlineExperimentationClientBuilderExtensions.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AnalyticsOnlineExperimentationClientBuilderExtensions.cs new file mode 100644 index 000000000000..21c9affb0bd5 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AnalyticsOnlineExperimentationClientBuilderExtensions.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Analytics.OnlineExperimentation; +using Azure.Core.Extensions; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add to client builder. + public static partial class AnalyticsOnlineExperimentationClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// Endpoint URL for the Online Experimentation workspace. + public static IAzureClientBuilder AddOnlineExperimentationClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new OnlineExperimentationClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddOnlineExperimentationClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AnalyticsOnlineExperimentationModelFactory.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AnalyticsOnlineExperimentationModelFactory.cs new file mode 100644 index 000000000000..9dfa351c175d --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AnalyticsOnlineExperimentationModelFactory.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// Model factory for models. + public static partial class AnalyticsOnlineExperimentationModelFactory + { + /// Initializes a new instance of . + /// Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase letters, numbers, and underscores. + /// Determines whether it is included in experiment analysis. + /// A user-friendly display name for the experiment metric shown in reports and dashboards. + /// A detailed description of the experiment metric. + /// Categories associated with the experiment metric. Used for organizing and filtering metrics. + /// The desired direction for changes in the metric value. + /// + /// The metric definition specifying how the metric value is calculated from event data. + /// 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 . + /// + /// ETag of the experiment metric. + /// The timestamp (UTC) of the last modification to the experiment metric resource. + /// A new instance for mocking. + public static ExperimentMetric ExperimentMetric(string id = null, LifecycleStage lifecycle = default, string displayName = null, string description = null, IEnumerable categories = null, DesiredDirection desiredDirection = default, ExperimentMetricDefinition definition = null, ETag eTag = default, DateTimeOffset lastModifiedAt = default) + { + categories ??= new List(); + + return new ExperimentMetric( + id, + lifecycle, + displayName, + description, + categories?.ToList(), + desiredDirection, + definition, + eTag, + lastModifiedAt, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Indicates whether the experiment metric is valid. + /// Diagnostic details from the validation process. + /// A new instance for mocking. + public static ExperimentMetricValidationResult ExperimentMetricValidationResult(bool isValid = default, IEnumerable diagnostics = null) + { + diagnostics ??= new List(); + + return new ExperimentMetricValidationResult(isValid, diagnostics?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A human-readable error message. + /// The diagnostic error code. + /// A new instance for mocking. + public static DiagnosticDetail DiagnosticDetail(string message = null, DiagnosticCode code = default) + { + return new DiagnosticDetail(message, code, serializedAdditionalRawData: null); + } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AverageMetricDefinition.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AverageMetricDefinition.Serialization.cs new file mode 100644 index 000000000000..88b1b05bad0e --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AverageMetricDefinition.Serialization.cs @@ -0,0 +1,134 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + public partial class AverageMetricDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AverageMetricDefinition)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("value"u8); + writer.WriteObjectValue(Value, options); + } + + AverageMetricDefinition 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(AverageMetricDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAverageMetricDefinition(document.RootElement, options); + } + + internal static AverageMetricDefinition DeserializeAverageMetricDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AggregatedValue value = default; + ExperimentMetricType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("value"u8)) + { + value = AggregatedValue.DeserializeAggregatedValue(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new ExperimentMetricType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AverageMetricDefinition(type, serializedAdditionalRawData, value); + } + + 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(AverageMetricDefinition)} does not support writing '{options.Format}' format."); + } + } + + AverageMetricDefinition 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAverageMetricDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AverageMetricDefinition)} 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 AverageMetricDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAverageMetricDefinition(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AverageMetricDefinition.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AverageMetricDefinition.cs new file mode 100644 index 000000000000..877afcc9edeb --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/AverageMetricDefinition.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// The definition of an Average metric definition. Calculates the average value of a specified event property. + public partial class AverageMetricDefinition : ExperimentMetricDefinition + { + /// Initializes a new instance of . + /// The value to aggregate. + /// is null. + public AverageMetricDefinition(AggregatedValue value) + { + Argument.AssertNotNull(value, nameof(value)); + + Type = ExperimentMetricType.Average; + Value = value; + } + + /// Initializes a new instance of . + /// Discriminator property for ExperimentMetricDefinition. + /// Keeps track of any properties unknown to the library. + /// The value to aggregate. + internal AverageMetricDefinition(ExperimentMetricType type, IDictionary serializedAdditionalRawData, AggregatedValue value) : base(type, serializedAdditionalRawData) + { + Value = value; + } + + /// Initializes a new instance of for deserialization. + internal AverageMetricDefinition() + { + } + + /// The value to aggregate. + public AggregatedValue Value { get; set; } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/DesiredDirection.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/DesiredDirection.cs new file mode 100644 index 000000000000..66a7a98cd31d --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/DesiredDirection.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// Desired direction for an experiment metric value. + public readonly partial struct DesiredDirection : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public DesiredDirection(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string IncreaseValue = "Increase"; + private const string DecreaseValue = "Decrease"; + private const string NeutralValue = "Neutral"; + + /// An increase to the metric value is desired. E.g., Success rate, Total revenue. + public static DesiredDirection Increase { get; } = new DesiredDirection(IncreaseValue); + /// A decrease to the metric value is desired. E.g., Error rate, Latency. + public static DesiredDirection Decrease { get; } = new DesiredDirection(DecreaseValue); + /// Neither an increase nor a decrease to the metric value is desired, or the desired direction depends on other factors. E.g., Number of video play attempts, Number of user feedbacks. + public static DesiredDirection Neutral { get; } = new DesiredDirection(NeutralValue); + /// Determines if two values are the same. + public static bool operator ==(DesiredDirection left, DesiredDirection right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(DesiredDirection left, DesiredDirection right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator DesiredDirection(string value) => new DesiredDirection(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is DesiredDirection other && Equals(other); + /// + public bool Equals(DesiredDirection 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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/DiagnosticCode.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/DiagnosticCode.cs new file mode 100644 index 000000000000..f67968186953 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/DiagnosticCode.cs @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// The diagnostic error codes. + public readonly partial struct DiagnosticCode : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public DiagnosticCode(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string FailedSchemaValidationValue = "FailedSchemaValidation"; + private const string InvalidEventConditionValue = "InvalidEventCondition"; + private const string UnsupportedEventConditionValue = "UnsupportedEventCondition"; + private const string InvalidExperimentMetricDefinitionValue = "InvalidExperimentMetricDefinition"; + + /// The metric definition does not conform to the required schema. + public static DiagnosticCode FailedSchemaValidation { get; } = new DiagnosticCode(FailedSchemaValidationValue); + /// The filter condition is invalid. + public static DiagnosticCode InvalidEventCondition { get; } = new DiagnosticCode(InvalidEventConditionValue); + /// The filter condition is valid but not currently supported. + public static DiagnosticCode UnsupportedEventCondition { get; } = new DiagnosticCode(UnsupportedEventConditionValue); + /// + /// The provided metric definition is invalid. + /// For example, defining a metric to calculate the average of a numeric property but + /// including a filter condition that compares it to a string value creates a type mismatch. + /// + public static DiagnosticCode InvalidExperimentMetricDefinition { get; } = new DiagnosticCode(InvalidExperimentMetricDefinitionValue); + /// Determines if two values are the same. + public static bool operator ==(DiagnosticCode left, DiagnosticCode right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(DiagnosticCode left, DiagnosticCode right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator DiagnosticCode(string value) => new DiagnosticCode(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is DiagnosticCode other && Equals(other); + /// + public bool Equals(DiagnosticCode 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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/DiagnosticDetail.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/DiagnosticDetail.Serialization.cs new file mode 100644 index 000000000000..891a17b5e130 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/DiagnosticDetail.Serialization.cs @@ -0,0 +1,156 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + public partial class DiagnosticDetail : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DiagnosticDetail)} does not support writing '{format}' format."); + } + + if (options.Format != "W") + { + writer.WritePropertyName("message"u8); + writer.WriteStringValue(Message); + } + if (options.Format != "W") + { + writer.WritePropertyName("code"u8); + writer.WriteStringValue(Code.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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + DiagnosticDetail 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(DiagnosticDetail)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDiagnosticDetail(document.RootElement, options); + } + + internal static DiagnosticDetail DeserializeDiagnosticDetail(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string message = default; + DiagnosticCode code = 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("code"u8)) + { + code = new DiagnosticCode(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new DiagnosticDetail(message, code, 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(DiagnosticDetail)} does not support writing '{options.Format}' format."); + } + } + + DiagnosticDetail 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDiagnosticDetail(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DiagnosticDetail)} 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 DiagnosticDetail FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDiagnosticDetail(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/DiagnosticDetail.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/DiagnosticDetail.cs new file mode 100644 index 000000000000..def63fa2490f --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/DiagnosticDetail.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// Diagnostic details for validation errors. + public partial class DiagnosticDetail + { + /// + /// 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 . + internal DiagnosticDetail() + { + } + + /// Initializes a new instance of . + /// A human-readable error message. + /// The diagnostic error code. + /// Keeps track of any properties unknown to the library. + internal DiagnosticDetail(string message, DiagnosticCode code, IDictionary serializedAdditionalRawData) + { + Message = message; + Code = code; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// A human-readable error message. + public string Message { get; } + /// The diagnostic error code. + public DiagnosticCode Code { get; } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Docs/OnlineExperimentationClient.xml b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Docs/OnlineExperimentationClient.xml new file mode 100644 index 000000000000..ae2807f70393 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Docs/OnlineExperimentationClient.xml @@ -0,0 +1,855 @@ + + + + + +This sample shows how to call GetMetricAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +Response response = await client.GetMetricAsync("events_purchase_creditcard"); +]]> + + + +This sample shows how to call GetMetric. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +Response response = client.GetMetric("events_purchase_creditcard"); +]]> + + + +This sample shows how to call GetMetricAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +Response response = await client.GetMetricAsync("events_purchase_creditcard", null, null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> + + + +This sample shows how to call GetMetric and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +Response response = client.GetMetric("events_purchase_creditcard", null, null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> + + + +This sample shows how to call CreateOrUpdateMetricAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Average revenue per purchase [USD]", + description = "The average revenue per purchase transaction in USD. Refund transactions are excluded from this metric. The total revenue might increase while this metric decreases if the number of purchases increases.", + lifecycle = "Active", + categories = new object[] + { + "Monetization" + }, + desiredDirection = "Increase", + definition = new + { + type = "Average", + value = new + { + eventName = "Transaction", + eventProperty = "Revenue", + filter = "Revenue > 0", + }, + }, +}); +Response response = await client.CreateOrUpdateMetricAsync("avg_purchase_revenue", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> +This sample shows how to call CreateOrUpdateMetricAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Number of purchases (credit card)", + description = "The number of purchase transactions made with credit card. Refund transactions are excluded from this metric.", + lifecycle = "Active", + categories = new object[] + { + "Monetization" + }, + desiredDirection = "Increase", + definition = new Dictionary + { + ["type"] = "EventCount", + ["event"] = new + { + eventName = "Transaction", + filter = "Revenue > 0 and ['payment.method'] == 'credit_card'", + } + }, +}); +Response response = await client.CreateOrUpdateMetricAsync("events_purchase_creditcard", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> +This sample shows how to call CreateOrUpdateMetricAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Refund rate", + description = "The percentage of transactions that are refunds. This metric is calculated as the number of refund transactions divided by the total number of transactions.", + lifecycle = "Active", + categories = new object[] + { + "Monetization" + }, + desiredDirection = "Neutral", + definition = new Dictionary + { + ["type"] = "EventRate", + ["event"] = new + { + eventName = "Transaction", + }, + ["rateCondition"] = "Revenue < 0" + }, +}); +Response response = await client.CreateOrUpdateMetricAsync("rate_refund", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> +This sample shows how to call CreateOrUpdateMetricAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "95th percentile of page load time [ms]", + description = "The 95th percentile of the page load time for all pages. Measured in milliseconds. Review page-specific metric results to identify pages that need optimization.", + lifecycle = "Active", + categories = new object[] + { + "Performance", + "Important" + }, + desiredDirection = "Decrease", + definition = new + { + type = "Percentile", + value = new + { + eventName = "PageLoad", + eventProperty = "LoadTime_ms", + }, + percentile = 95, + }, +}); +Response response = await client.CreateOrUpdateMetricAsync("p95_page_load_time", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> +This sample shows how to call CreateOrUpdateMetricAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Total revenue [USD]", + description = "The total revenue in USD. Refund transactions contribute negatively to this metric.", + lifecycle = "Active", + categories = new object[] + { + "Monetization", + "Important" + }, + desiredDirection = "Increase", + definition = new + { + type = "Sum", + value = new + { + eventName = "Transaction", + eventProperty = "Revenue", + }, + }, +}); +Response response = await client.CreateOrUpdateMetricAsync("sum_revenue", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> +This sample shows how to call CreateOrUpdateMetricAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Users with purchase", + description = "The number of users who have made at least one purchase transaction. Refund transactions are excluded from this metric. As the analysis period grows, this metric begins to saturate as users making multiple purchases no longer contribute.", + lifecycle = "Active", + categories = new object[] + { + "Monetization" + }, + desiredDirection = "Increase", + definition = new Dictionary + { + ["type"] = "UserCount", + ["event"] = new + { + eventName = "Transaction", + filter = "Revenue > 0", + } + }, +}); +Response response = await client.CreateOrUpdateMetricAsync("users_purchase", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> +This sample shows how to call CreateOrUpdateMetricAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Subscription ad conversion rate", + description = "The percentage of users who saw an advertisement for a subscription promotion and then later successfully subscribed. This metric is calculated as the number of users who successfully subscribed after seeing the advert divided by the total number of users who saw the advert. Users who saw multiple adverts or subscribed multiple times are counted only once. Users who saw the advert before the analysis period starts are excluded from this metric.", + lifecycle = "Active", + categories = new object[] + { + "Monetization" + }, + desiredDirection = "Increase", + definition = new + { + type = "UserRate", + startEvent = new + { + eventName = "AdView", + filter = "Source == 'subscription_promo'", + }, + endEvent = new + { + eventName = "Subscribe", + filter = "Status == 'Success'", + }, + }, +}); +Response response = await client.CreateOrUpdateMetricAsync("rate_subscription_ad", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> + + + +This sample shows how to call CreateOrUpdateMetric and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Average revenue per purchase [USD]", + description = "The average revenue per purchase transaction in USD. Refund transactions are excluded from this metric. The total revenue might increase while this metric decreases if the number of purchases increases.", + lifecycle = "Active", + categories = new object[] + { + "Monetization" + }, + desiredDirection = "Increase", + definition = new + { + type = "Average", + value = new + { + eventName = "Transaction", + eventProperty = "Revenue", + filter = "Revenue > 0", + }, + }, +}); +Response response = client.CreateOrUpdateMetric("avg_purchase_revenue", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> +This sample shows how to call CreateOrUpdateMetric and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Number of purchases (credit card)", + description = "The number of purchase transactions made with credit card. Refund transactions are excluded from this metric.", + lifecycle = "Active", + categories = new object[] + { + "Monetization" + }, + desiredDirection = "Increase", + definition = new Dictionary + { + ["type"] = "EventCount", + ["event"] = new + { + eventName = "Transaction", + filter = "Revenue > 0 and ['payment.method'] == 'credit_card'", + } + }, +}); +Response response = client.CreateOrUpdateMetric("events_purchase_creditcard", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> +This sample shows how to call CreateOrUpdateMetric and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Refund rate", + description = "The percentage of transactions that are refunds. This metric is calculated as the number of refund transactions divided by the total number of transactions.", + lifecycle = "Active", + categories = new object[] + { + "Monetization" + }, + desiredDirection = "Neutral", + definition = new Dictionary + { + ["type"] = "EventRate", + ["event"] = new + { + eventName = "Transaction", + }, + ["rateCondition"] = "Revenue < 0" + }, +}); +Response response = client.CreateOrUpdateMetric("rate_refund", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> +This sample shows how to call CreateOrUpdateMetric and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "95th percentile of page load time [ms]", + description = "The 95th percentile of the page load time for all pages. Measured in milliseconds. Review page-specific metric results to identify pages that need optimization.", + lifecycle = "Active", + categories = new object[] + { + "Performance", + "Important" + }, + desiredDirection = "Decrease", + definition = new + { + type = "Percentile", + value = new + { + eventName = "PageLoad", + eventProperty = "LoadTime_ms", + }, + percentile = 95, + }, +}); +Response response = client.CreateOrUpdateMetric("p95_page_load_time", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> +This sample shows how to call CreateOrUpdateMetric and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Total revenue [USD]", + description = "The total revenue in USD. Refund transactions contribute negatively to this metric.", + lifecycle = "Active", + categories = new object[] + { + "Monetization", + "Important" + }, + desiredDirection = "Increase", + definition = new + { + type = "Sum", + value = new + { + eventName = "Transaction", + eventProperty = "Revenue", + }, + }, +}); +Response response = client.CreateOrUpdateMetric("sum_revenue", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> +This sample shows how to call CreateOrUpdateMetric and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Users with purchase", + description = "The number of users who have made at least one purchase transaction. Refund transactions are excluded from this metric. As the analysis period grows, this metric begins to saturate as users making multiple purchases no longer contribute.", + lifecycle = "Active", + categories = new object[] + { + "Monetization" + }, + desiredDirection = "Increase", + definition = new Dictionary + { + ["type"] = "UserCount", + ["event"] = new + { + eventName = "Transaction", + filter = "Revenue > 0", + } + }, +}); +Response response = client.CreateOrUpdateMetric("users_purchase", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> +This sample shows how to call CreateOrUpdateMetric and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Subscription ad conversion rate", + description = "The percentage of users who saw an advertisement for a subscription promotion and then later successfully subscribed. This metric is calculated as the number of users who successfully subscribed after seeing the advert divided by the total number of users who saw the advert. Users who saw multiple adverts or subscribed multiple times are counted only once. Users who saw the advert before the analysis period starts are excluded from this metric.", + lifecycle = "Active", + categories = new object[] + { + "Monetization" + }, + desiredDirection = "Increase", + definition = new + { + type = "UserRate", + startEvent = new + { + eventName = "AdView", + filter = "Source == 'subscription_promo'", + }, + endEvent = new + { + eventName = "Subscribe", + filter = "Status == 'Success'", + }, + }, +}); +Response response = client.CreateOrUpdateMetric("rate_subscription_ad", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("lifecycle").ToString()); +Console.WriteLine(result.GetProperty("displayName").ToString()); +Console.WriteLine(result.GetProperty("description").ToString()); +Console.WriteLine(result.GetProperty("categories")[0].ToString()); +Console.WriteLine(result.GetProperty("desiredDirection").ToString()); +Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("eTag").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> + + + +This sample shows how to call ValidateMetricAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +ExperimentMetric body = new ExperimentMetric( +LifecycleStage.Active, +"Average revenue per purchase [USD]", +"The average revenue per purchase transaction in USD. Refund transactions are excluded from this metric. The total revenue might increase while this metric decreases if the number of purchases increases.", +new string[] { "Monetization" }, +DesiredDirection.Increase, +new AverageMetricDefinition(new AggregatedValue("Transaction", "Revenue") +{ + Filter = "Revenue >", +})); +Response response = await client.ValidateMetricAsync(body); +]]> + + + +This sample shows how to call ValidateMetric. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +ExperimentMetric body = new ExperimentMetric( +LifecycleStage.Active, +"Average revenue per purchase [USD]", +"The average revenue per purchase transaction in USD. Refund transactions are excluded from this metric. The total revenue might increase while this metric decreases if the number of purchases increases.", +new string[] { "Monetization" }, +DesiredDirection.Increase, +new AverageMetricDefinition(new AggregatedValue("Transaction", "Revenue") +{ + Filter = "Revenue >", +})); +Response response = client.ValidateMetric(body); +]]> + + + +This sample shows how to call ValidateMetricAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Average revenue per purchase [USD]", + description = "The average revenue per purchase transaction in USD. Refund transactions are excluded from this metric. The total revenue might increase while this metric decreases if the number of purchases increases.", + lifecycle = "Active", + categories = new object[] + { + "Monetization" + }, + desiredDirection = "Increase", + definition = new + { + type = "Average", + value = new + { + eventName = "Transaction", + eventProperty = "Revenue", + filter = "Revenue >", + }, + }, +}); +Response response = await client.ValidateMetricAsync(content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("isValid").ToString()); +Console.WriteLine(result.GetProperty("diagnostics")[0].GetProperty("message").ToString()); +Console.WriteLine(result.GetProperty("diagnostics")[0].GetProperty("code").ToString()); +]]> + + + +This sample shows how to call ValidateMetric and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + displayName = "Average revenue per purchase [USD]", + description = "The average revenue per purchase transaction in USD. Refund transactions are excluded from this metric. The total revenue might increase while this metric decreases if the number of purchases increases.", + lifecycle = "Active", + categories = new object[] + { + "Monetization" + }, + desiredDirection = "Increase", + definition = new + { + type = "Average", + value = new + { + eventName = "Transaction", + eventProperty = "Revenue", + filter = "Revenue >", + }, + }, +}); +Response response = client.ValidateMetric(content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("isValid").ToString()); +Console.WriteLine(result.GetProperty("diagnostics")[0].GetProperty("message").ToString()); +Console.WriteLine(result.GetProperty("diagnostics")[0].GetProperty("code").ToString()); +]]> + + + +This sample shows how to call DeleteMetricAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +Response response = await client.DeleteMetricAsync("avg_purchase_revenue"); + +Console.WriteLine(response.Status); +]]> + + + +This sample shows how to call DeleteMetric. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +Response response = client.DeleteMetric("avg_purchase_revenue"); + +Console.WriteLine(response.Status); +]]> + + + +This sample shows how to call GetMetricsAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +await foreach (ExperimentMetric item in client.GetMetricsAsync()) +{ +} +]]> + + + +This sample shows how to call GetMetrics. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +foreach (ExperimentMetric item in client.GetMetrics()) +{ +} +]]> + + + +This sample shows how to call GetMetricsAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +await foreach (BinaryData item in client.GetMetricsAsync(null, 15, null, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +} +]]> + + + +This sample shows how to call GetMetrics and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + +foreach (BinaryData item in client.GetMetrics(null, 15, null, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +} +]]> + + + \ No newline at end of file diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/EventCountMetricDefinition.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/EventCountMetricDefinition.Serialization.cs new file mode 100644 index 000000000000..b125337aea7e --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/EventCountMetricDefinition.Serialization.cs @@ -0,0 +1,134 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + public partial class EventCountMetricDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EventCountMetricDefinition)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("event"u8); + writer.WriteObjectValue(Event, options); + } + + EventCountMetricDefinition 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(EventCountMetricDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEventCountMetricDefinition(document.RootElement, options); + } + + internal static EventCountMetricDefinition DeserializeEventCountMetricDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ObservedEvent @event = default; + ExperimentMetricType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("event"u8)) + { + @event = ObservedEvent.DeserializeObservedEvent(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new ExperimentMetricType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EventCountMetricDefinition(type, serializedAdditionalRawData, @event); + } + + 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(EventCountMetricDefinition)} does not support writing '{options.Format}' format."); + } + } + + EventCountMetricDefinition 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEventCountMetricDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EventCountMetricDefinition)} 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 EventCountMetricDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEventCountMetricDefinition(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/EventCountMetricDefinition.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/EventCountMetricDefinition.cs new file mode 100644 index 000000000000..d30854f98556 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/EventCountMetricDefinition.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// The definition of an EventCount metric definition. Counts the occurrences of a specified event. + public partial class EventCountMetricDefinition : ExperimentMetricDefinition + { + /// Initializes a new instance of . + /// Event to observe. + /// is null. + public EventCountMetricDefinition(ObservedEvent @event) + { + Argument.AssertNotNull(@event, nameof(@event)); + + Type = ExperimentMetricType.EventCount; + Event = @event; + } + + /// Initializes a new instance of . + /// Discriminator property for ExperimentMetricDefinition. + /// Keeps track of any properties unknown to the library. + /// Event to observe. + internal EventCountMetricDefinition(ExperimentMetricType type, IDictionary serializedAdditionalRawData, ObservedEvent @event) : base(type, serializedAdditionalRawData) + { + Event = @event; + } + + /// Initializes a new instance of for deserialization. + internal EventCountMetricDefinition() + { + } + + /// Event to observe. + public ObservedEvent Event { get; set; } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/EventRateMetricDefinition.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/EventRateMetricDefinition.Serialization.cs new file mode 100644 index 000000000000..f9ffa508360f --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/EventRateMetricDefinition.Serialization.cs @@ -0,0 +1,142 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + public partial class EventRateMetricDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EventRateMetricDefinition)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("event"u8); + writer.WriteObjectValue(Event, options); + writer.WritePropertyName("rateCondition"u8); + writer.WriteStringValue(RateCondition); + } + + EventRateMetricDefinition 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(EventRateMetricDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEventRateMetricDefinition(document.RootElement, options); + } + + internal static EventRateMetricDefinition DeserializeEventRateMetricDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ObservedEvent @event = default; + string rateCondition = default; + ExperimentMetricType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("event"u8)) + { + @event = ObservedEvent.DeserializeObservedEvent(property.Value, options); + continue; + } + if (property.NameEquals("rateCondition"u8)) + { + rateCondition = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new ExperimentMetricType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EventRateMetricDefinition(type, serializedAdditionalRawData, @event, rateCondition); + } + + 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(EventRateMetricDefinition)} does not support writing '{options.Format}' format."); + } + } + + EventRateMetricDefinition 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEventRateMetricDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EventRateMetricDefinition)} 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 EventRateMetricDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEventRateMetricDefinition(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/EventRateMetricDefinition.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/EventRateMetricDefinition.cs new file mode 100644 index 000000000000..1baa984314a2 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/EventRateMetricDefinition.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// The definition of an EventRate metric definition. Calculates the percentage of events satisfying a specified condition. + public partial class EventRateMetricDefinition : ExperimentMetricDefinition + { + /// Initializes a new instance of . + /// Event to observe as the rate denominator. + /// The event contributes to the rate numerator if it satisfies this condition. + /// or is null. + public EventRateMetricDefinition(ObservedEvent @event, string rateCondition) + { + Argument.AssertNotNull(@event, nameof(@event)); + Argument.AssertNotNull(rateCondition, nameof(rateCondition)); + + Type = ExperimentMetricType.EventRate; + Event = @event; + RateCondition = rateCondition; + } + + /// Initializes a new instance of . + /// Discriminator property for ExperimentMetricDefinition. + /// Keeps track of any properties unknown to the library. + /// Event to observe as the rate denominator. + /// The event contributes to the rate numerator if it satisfies this condition. + internal EventRateMetricDefinition(ExperimentMetricType type, IDictionary serializedAdditionalRawData, ObservedEvent @event, string rateCondition) : base(type, serializedAdditionalRawData) + { + Event = @event; + RateCondition = rateCondition; + } + + /// Initializes a new instance of for deserialization. + internal EventRateMetricDefinition() + { + } + + /// Event to observe as the rate denominator. + public ObservedEvent Event { get; set; } + /// The event contributes to the rate numerator if it satisfies this condition. + public string RateCondition { get; set; } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetric.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetric.Serialization.cs new file mode 100644 index 000000000000..112b36a076b1 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetric.Serialization.cs @@ -0,0 +1,235 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + public partial class ExperimentMetric : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ExperimentMetric)} does not support writing '{format}' format."); + } + + if (options.Format != "W") + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + writer.WritePropertyName("lifecycle"u8); + writer.WriteStringValue(Lifecycle.ToString()); + writer.WritePropertyName("displayName"u8); + writer.WriteStringValue(DisplayName); + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + writer.WritePropertyName("categories"u8); + writer.WriteStartArray(); + foreach (var item in Categories) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("desiredDirection"u8); + writer.WriteStringValue(DesiredDirection.ToString()); + writer.WritePropertyName("definition"u8); + writer.WriteObjectValue(Definition, options); + if (options.Format != "W") + { + writer.WritePropertyName("eTag"u8); + writer.WriteStringValue(ETag.ToString()); + } + if (options.Format != "W") + { + writer.WritePropertyName("lastModifiedAt"u8); + writer.WriteStringValue(LastModifiedAt, "O"); + } + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ExperimentMetric 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(ExperimentMetric)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeExperimentMetric(document.RootElement, options); + } + + internal static ExperimentMetric DeserializeExperimentMetric(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + LifecycleStage lifecycle = default; + string displayName = default; + string description = default; + IList categories = default; + DesiredDirection desiredDirection = default; + ExperimentMetricDefinition definition = default; + ETag eTag = default; + DateTimeOffset lastModifiedAt = 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("lifecycle"u8)) + { + lifecycle = new LifecycleStage(property.Value.GetString()); + continue; + } + if (property.NameEquals("displayName"u8)) + { + displayName = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("categories"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + categories = array; + continue; + } + if (property.NameEquals("desiredDirection"u8)) + { + desiredDirection = new DesiredDirection(property.Value.GetString()); + continue; + } + if (property.NameEquals("definition"u8)) + { + definition = ExperimentMetricDefinition.DeserializeExperimentMetricDefinition(property.Value, options); + continue; + } + if (property.NameEquals("eTag"u8)) + { + eTag = new ETag(property.Value.GetString()); + continue; + } + if (property.NameEquals("lastModifiedAt"u8)) + { + lastModifiedAt = property.Value.GetDateTimeOffset("O"); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ExperimentMetric( + id, + lifecycle, + displayName, + description, + categories, + desiredDirection, + definition, + eTag, + lastModifiedAt, + 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(ExperimentMetric)} does not support writing '{options.Format}' format."); + } + } + + ExperimentMetric 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeExperimentMetric(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ExperimentMetric)} 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 ExperimentMetric FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeExperimentMetric(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetric.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetric.cs new file mode 100644 index 000000000000..7f3497acd2a1 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetric.cs @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// Defines experiment metric metadata and computation details. + public partial class ExperimentMetric + { + /// + /// 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 . + /// Determines whether it is included in experiment analysis. + /// A user-friendly display name for the experiment metric shown in reports and dashboards. + /// A detailed description of the experiment metric. + /// Categories associated with the experiment metric. Used for organizing and filtering metrics. + /// The desired direction for changes in the metric value. + /// + /// The metric definition specifying how the metric value is calculated from event data. + /// 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 . + /// + /// , , or is null. + public ExperimentMetric(LifecycleStage lifecycle, string displayName, string description, IEnumerable categories, DesiredDirection desiredDirection, ExperimentMetricDefinition definition) + { + Argument.AssertNotNull(displayName, nameof(displayName)); + Argument.AssertNotNull(description, nameof(description)); + Argument.AssertNotNull(categories, nameof(categories)); + Argument.AssertNotNull(definition, nameof(definition)); + + Lifecycle = lifecycle; + DisplayName = displayName; + Description = description; + Categories = categories.ToList(); + DesiredDirection = desiredDirection; + Definition = definition; + } + + /// Initializes a new instance of . + /// Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase letters, numbers, and underscores. + /// Determines whether it is included in experiment analysis. + /// A user-friendly display name for the experiment metric shown in reports and dashboards. + /// A detailed description of the experiment metric. + /// Categories associated with the experiment metric. Used for organizing and filtering metrics. + /// The desired direction for changes in the metric value. + /// + /// The metric definition specifying how the metric value is calculated from event data. + /// 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 . + /// + /// ETag of the experiment metric. + /// The timestamp (UTC) of the last modification to the experiment metric resource. + /// Keeps track of any properties unknown to the library. + internal ExperimentMetric(string id, LifecycleStage lifecycle, string displayName, string description, IList categories, DesiredDirection desiredDirection, ExperimentMetricDefinition definition, ETag eTag, DateTimeOffset lastModifiedAt, IDictionary serializedAdditionalRawData) + { + Id = id; + Lifecycle = lifecycle; + DisplayName = displayName; + Description = description; + Categories = categories; + DesiredDirection = desiredDirection; + Definition = definition; + ETag = eTag; + LastModifiedAt = lastModifiedAt; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ExperimentMetric() + { + } + + /// Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase letters, numbers, and underscores. + public string Id { get; } + /// Determines whether it is included in experiment analysis. + public LifecycleStage Lifecycle { get; set; } + /// A user-friendly display name for the experiment metric shown in reports and dashboards. + public string DisplayName { get; set; } + /// A detailed description of the experiment metric. + public string Description { get; set; } + /// Categories associated with the experiment metric. Used for organizing and filtering metrics. + public IList Categories { get; } + /// The desired direction for changes in the metric value. + public DesiredDirection DesiredDirection { get; set; } + /// + /// The metric definition specifying how the metric value is calculated from event data. + /// 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 ExperimentMetricDefinition Definition { get; set; } + /// ETag of the experiment metric. + public ETag ETag { get; } + /// The timestamp (UTC) of the last modification to the experiment metric resource. + public DateTimeOffset LastModifiedAt { get; } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricDefinition.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricDefinition.Serialization.cs new file mode 100644 index 000000000000..6e4d3f2cc319 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricDefinition.Serialization.cs @@ -0,0 +1,139 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + [PersistableModelProxy(typeof(UnknownExperimentMetricDefinition))] + public partial class ExperimentMetricDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ExperimentMetricDefinition)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ExperimentMetricDefinition 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(ExperimentMetricDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeExperimentMetricDefinition(document.RootElement, options); + } + + internal static ExperimentMetricDefinition DeserializeExperimentMetricDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "Average": return AverageMetricDefinition.DeserializeAverageMetricDefinition(element, options); + case "EventCount": return EventCountMetricDefinition.DeserializeEventCountMetricDefinition(element, options); + case "EventRate": return EventRateMetricDefinition.DeserializeEventRateMetricDefinition(element, options); + case "Percentile": return PercentileMetricDefinition.DeserializePercentileMetricDefinition(element, options); + case "Sum": return SumMetricDefinition.DeserializeSumMetricDefinition(element, options); + case "UserCount": return UserCountMetricDefinition.DeserializeUserCountMetricDefinition(element, options); + case "UserRate": return UserRateMetricDefinition.DeserializeUserRateMetricDefinition(element, options); + } + } + return UnknownExperimentMetricDefinition.DeserializeUnknownExperimentMetricDefinition(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(ExperimentMetricDefinition)} does not support writing '{options.Format}' format."); + } + } + + ExperimentMetricDefinition 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeExperimentMetricDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ExperimentMetricDefinition)} 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 ExperimentMetricDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeExperimentMetricDefinition(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricDefinition.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricDefinition.cs new file mode 100644 index 000000000000..93c715cdd260 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricDefinition.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// + /// The metric definition, which determines how the metric value is calculated from event data. + /// 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 ExperimentMetricDefinition + { + /// + /// 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 ExperimentMetricDefinition() + { + } + + /// Initializes a new instance of . + /// Discriminator property for ExperimentMetricDefinition. + /// Keeps track of any properties unknown to the library. + internal ExperimentMetricDefinition(ExperimentMetricType type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Discriminator property for ExperimentMetricDefinition. + internal ExperimentMetricType Type { get; set; } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricType.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricType.cs new file mode 100644 index 000000000000..a798f02778e9 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricType.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 Azure.Analytics.OnlineExperimentation +{ + /// How the metric definition calculates metric values from event data. + internal readonly partial struct ExperimentMetricType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ExperimentMetricType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string EventCountValue = "EventCount"; + private const string UserCountValue = "UserCount"; + private const string EventRateValue = "EventRate"; + private const string UserRateValue = "UserRate"; + private const string SumValue = "Sum"; + private const string AverageValue = "Average"; + private const string PercentileValue = "Percentile"; + + /// Counts the occurrences of an event. Experiment analysis accounts for unequal traffic allocation. + public static ExperimentMetricType EventCount { get; } = new ExperimentMetricType(EventCountValue); + /// Counts the number of unique users who encounter an event. Experiment analysis accounts for unequal traffic allocation. + public static ExperimentMetricType UserCount { get; } = new ExperimentMetricType(UserCountValue); + /// Calculates the percentage of events that satisfy a specified condition. + public static ExperimentMetricType EventRate { get; } = new ExperimentMetricType(EventRateValue); + /// Calculates the percentage of users who encounter a start event and subsequently encounter an end event. Users must encounter the start event before the end event to be counted. + public static ExperimentMetricType UserRate { get; } = new ExperimentMetricType(UserRateValue); + /// Calculates the sum of a specified event property. Experiment analysis accounts for unequal traffic allocation. + public static ExperimentMetricType Sum { get; } = new ExperimentMetricType(SumValue); + /// Calculates the average value of a specified event property. + public static ExperimentMetricType Average { get; } = new ExperimentMetricType(AverageValue); + /// Calculates a specified percentile of an event property. + public static ExperimentMetricType Percentile { get; } = new ExperimentMetricType(PercentileValue); + /// Determines if two values are the same. + public static bool operator ==(ExperimentMetricType left, ExperimentMetricType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ExperimentMetricType left, ExperimentMetricType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ExperimentMetricType(string value) => new ExperimentMetricType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ExperimentMetricType other && Equals(other); + /// + public bool Equals(ExperimentMetricType 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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricValidationResult.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricValidationResult.Serialization.cs new file mode 100644 index 000000000000..6fd2c928591b --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricValidationResult.Serialization.cs @@ -0,0 +1,163 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + public partial class ExperimentMetricValidationResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ExperimentMetricValidationResult)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("isValid"u8); + writer.WriteBooleanValue(IsValid); + if (options.Format != "W") + { + writer.WritePropertyName("diagnostics"u8); + writer.WriteStartArray(); + foreach (var item in Diagnostics) + { + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ExperimentMetricValidationResult 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(ExperimentMetricValidationResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeExperimentMetricValidationResult(document.RootElement, options); + } + + internal static ExperimentMetricValidationResult DeserializeExperimentMetricValidationResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool isValid = default; + IReadOnlyList diagnostics = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("isValid"u8)) + { + isValid = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("diagnostics"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(DiagnosticDetail.DeserializeDiagnosticDetail(item, options)); + } + diagnostics = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ExperimentMetricValidationResult(isValid, diagnostics, 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(ExperimentMetricValidationResult)} does not support writing '{options.Format}' format."); + } + } + + ExperimentMetricValidationResult 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeExperimentMetricValidationResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ExperimentMetricValidationResult)} 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 ExperimentMetricValidationResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeExperimentMetricValidationResult(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricValidationResult.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricValidationResult.cs new file mode 100644 index 000000000000..799ea1df7c62 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ExperimentMetricValidationResult.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// The result of validating an experiment metric. + public partial class ExperimentMetricValidationResult + { + /// + /// 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 . + /// Indicates whether the experiment metric is valid. + internal ExperimentMetricValidationResult(bool isValid) + { + IsValid = isValid; + Diagnostics = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// Indicates whether the experiment metric is valid. + /// Diagnostic details from the validation process. + /// Keeps track of any properties unknown to the library. + internal ExperimentMetricValidationResult(bool isValid, IReadOnlyList diagnostics, IDictionary serializedAdditionalRawData) + { + IsValid = isValid; + Diagnostics = diagnostics; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ExperimentMetricValidationResult() + { + } + + /// Indicates whether the experiment metric is valid. + public bool IsValid { get; } + /// Diagnostic details from the validation process. + public IReadOnlyList Diagnostics { get; } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/Argument.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/Argument.cs new file mode 100644 index 000000000000..b6a0f18d3d7c --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/Argument.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Azure.Analytics.OnlineExperimentation +{ + 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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 000000000000..2faf429e0521 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/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 Azure.Analytics.OnlineExperimentation +{ + 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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/ChangeTrackingList.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 000000000000..9599d0cee8d3 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/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 Azure.Analytics.OnlineExperimentation +{ + 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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 000000000000..c19512698070 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/ModelSerializationExtensions.cs @@ -0,0 +1,399 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using System.Xml; +using Azure.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + internal static class ModelSerializationExtensions + { + internal static readonly JsonDocumentOptions JsonDocumentOptions = new JsonDocumentOptions { MaxDepth = 256 }; + 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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/Optional.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/Optional.cs new file mode 100644 index 000000000000..cd1f6c9e1c75 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/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 Azure.Analytics.OnlineExperimentation +{ + 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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/Utf8JsonRequestContent.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 000000000000..2b2ea35805b8 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + 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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/LifecycleStage.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/LifecycleStage.cs new file mode 100644 index 000000000000..d7426b6e2a28 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/LifecycleStage.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// Lifecycle stages of an experiment metric, determining whether the metric is included in experiment analysis. + public readonly partial struct LifecycleStage : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public LifecycleStage(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ActiveValue = "Active"; + private const string InactiveValue = "Inactive"; + + /// The metric is included in experiment analysis. + public static LifecycleStage Active { get; } = new LifecycleStage(ActiveValue); + /// The metric is excluded from experiment analysis but remains available for future use. + public static LifecycleStage Inactive { get; } = new LifecycleStage(InactiveValue); + /// Determines if two values are the same. + public static bool operator ==(LifecycleStage left, LifecycleStage right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(LifecycleStage left, LifecycleStage right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator LifecycleStage(string value) => new LifecycleStage(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is LifecycleStage other && Equals(other); + /// + public bool Equals(LifecycleStage 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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ObservedEvent.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ObservedEvent.Serialization.cs new file mode 100644 index 000000000000..fec8996f516d --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ObservedEvent.Serialization.cs @@ -0,0 +1,153 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + public partial class ObservedEvent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ObservedEvent)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("eventName"u8); + writer.WriteStringValue(EventName); + if (Optional.IsDefined(Filter)) + { + writer.WritePropertyName("filter"u8); + writer.WriteStringValue(Filter); + } + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ObservedEvent 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(ObservedEvent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeObservedEvent(document.RootElement, options); + } + + internal static ObservedEvent DeserializeObservedEvent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string eventName = default; + string filter = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("eventName"u8)) + { + eventName = property.Value.GetString(); + continue; + } + if (property.NameEquals("filter"u8)) + { + filter = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ObservedEvent(eventName, filter, 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(ObservedEvent)} does not support writing '{options.Format}' format."); + } + } + + ObservedEvent 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeObservedEvent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ObservedEvent)} 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 ObservedEvent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeObservedEvent(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ObservedEvent.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ObservedEvent.cs new file mode 100644 index 000000000000..e8cfe8b39094 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/ObservedEvent.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 Azure.Analytics.OnlineExperimentation +{ + /// An event observed by a metric. + public partial class ObservedEvent + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the event. + /// is null. + public ObservedEvent(string eventName) + { + Argument.AssertNotNull(eventName, nameof(eventName)); + + EventName = eventName; + } + + /// Initializes a new instance of . + /// The name of the event. + /// [Optional] A condition to filter events. + /// Keeps track of any properties unknown to the library. + internal ObservedEvent(string eventName, string filter, IDictionary serializedAdditionalRawData) + { + EventName = eventName; + Filter = filter; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ObservedEvent() + { + } + + /// The name of the event. + public string EventName { get; set; } + /// [Optional] A condition to filter events. + public string Filter { get; set; } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/OnlineExperimentationClient.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/OnlineExperimentationClient.cs new file mode 100644 index 000000000000..41b26a7438fb --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/OnlineExperimentationClient.cs @@ -0,0 +1,654 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Autorest.CSharp.Core; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.Analytics.OnlineExperimentation +{ + // Data plane generated client. + /// The OnlineExperimentation service client. + public partial class OnlineExperimentationClient + { + private static readonly string[] AuthorizationScopes = new string[] { "https://exp.azure.net/.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 OnlineExperimentationClient for mocking. + protected OnlineExperimentationClient() + { + } + + /// Initializes a new instance of OnlineExperimentationClient. + /// Endpoint URL for the Online Experimentation workspace. + /// A credential used to authenticate to an Azure Service. + /// or is null. + public OnlineExperimentationClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new OnlineExperimentationClientOptions()) + { + } + + /// Initializes a new instance of OnlineExperimentationClient. + /// Endpoint URL for the Online Experimentation workspace. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public OnlineExperimentationClient(Uri endpoint, TokenCredential credential, OnlineExperimentationClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new OnlineExperimentationClientOptions(); + + 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; + } + + /// Fetches an experiment metric by ID. + /// Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase letters, numbers, and underscores. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> GetMetricAsync(string experimentMetricId, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(experimentMetricId, nameof(experimentMetricId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetMetricAsync(experimentMetricId, requestConditions, context).ConfigureAwait(false); + return Response.FromValue(ExperimentMetric.FromResponse(response), response); + } + + /// Fetches an experiment metric by ID. + /// Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase letters, numbers, and underscores. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response GetMetric(string experimentMetricId, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(experimentMetricId, nameof(experimentMetricId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetMetric(experimentMetricId, requestConditions, context); + return Response.FromValue(ExperimentMetric.FromResponse(response), response); + } + + /// + /// [Protocol Method] Fetches an experiment metric by ID. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase letters, numbers, and underscores. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetMetricAsync(string experimentMetricId, RequestConditions requestConditions, RequestContext context) + { + Argument.AssertNotNullOrEmpty(experimentMetricId, nameof(experimentMetricId)); + + using var scope = ClientDiagnostics.CreateScope("OnlineExperimentationClient.GetMetric"); + scope.Start(); + try + { + using HttpMessage message = CreateGetMetricRequest(experimentMetricId, requestConditions, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Fetches an experiment metric by ID. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase letters, numbers, and underscores. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetMetric(string experimentMetricId, RequestConditions requestConditions, RequestContext context) + { + Argument.AssertNotNullOrEmpty(experimentMetricId, nameof(experimentMetricId)); + + using var scope = ClientDiagnostics.CreateScope("OnlineExperimentationClient.GetMetric"); + scope.Start(); + try + { + using HttpMessage message = CreateGetMetricRequest(experimentMetricId, requestConditions, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates or updates an experiment metric. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase letters, numbers, and underscores. + /// The content to send as the body of the request. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task CreateOrUpdateMetricAsync(string experimentMetricId, RequestContent content, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(experimentMetricId, nameof(experimentMetricId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OnlineExperimentationClient.CreateOrUpdateMetric"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrUpdateMetricRequest(experimentMetricId, content, requestConditions, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates or updates an experiment metric. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase letters, numbers, and underscores. + /// The content to send as the body of the request. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response CreateOrUpdateMetric(string experimentMetricId, RequestContent content, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(experimentMetricId, nameof(experimentMetricId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OnlineExperimentationClient.CreateOrUpdateMetric"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrUpdateMetricRequest(experimentMetricId, content, requestConditions, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Validates an experiment metric definition. + /// Experiment metric input to validate. + /// The cancellation token to use. + /// is null. + /// + public virtual async Task> ValidateMetricAsync(ExperimentMetric body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await ValidateMetricAsync(content, context).ConfigureAwait(false); + return Response.FromValue(ExperimentMetricValidationResult.FromResponse(response), response); + } + + /// Validates an experiment metric definition. + /// Experiment metric input to validate. + /// The cancellation token to use. + /// is null. + /// + public virtual Response ValidateMetric(ExperimentMetric body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = ValidateMetric(content, context); + return Response.FromValue(ExperimentMetricValidationResult.FromResponse(response), response); + } + + /// + /// [Protocol Method] Validates an experiment metric definition. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task ValidateMetricAsync(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OnlineExperimentationClient.ValidateMetric"); + scope.Start(); + try + { + using HttpMessage message = CreateValidateMetricRequest(content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Validates an experiment metric definition. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response ValidateMetric(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OnlineExperimentationClient.ValidateMetric"); + scope.Start(); + try + { + using HttpMessage message = CreateValidateMetricRequest(content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method + /// + /// [Protocol Method] Deletes an experiment metric. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase letters, numbers, and underscores. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeleteMetricAsync(string experimentMetricId, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(experimentMetricId, nameof(experimentMetricId)); + + using var scope = ClientDiagnostics.CreateScope("OnlineExperimentationClient.DeleteMetric"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteMetricRequest(experimentMetricId, requestConditions, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method + /// + /// [Protocol Method] Deletes an experiment metric. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase letters, numbers, and underscores. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response DeleteMetric(string experimentMetricId, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(experimentMetricId, nameof(experimentMetricId)); + + using var scope = ClientDiagnostics.CreateScope("OnlineExperimentationClient.DeleteMetric"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteMetricRequest(experimentMetricId, requestConditions, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Lists experiment metrics. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The cancellation token to use. + /// + public virtual AsyncPageable GetMetricsAsync(int? maxCount = null, int? skip = null, int? maxpagesize = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetMetricsRequest(maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetMetricsNextPageRequest(nextLink, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => ExperimentMetric.DeserializeExperimentMetric(e), ClientDiagnostics, _pipeline, "OnlineExperimentationClient.GetMetrics", "value", "nextLink", maxpagesize, context); + } + + /// Lists experiment metrics. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The cancellation token to use. + /// + public virtual Pageable GetMetrics(int? maxCount = null, int? skip = null, int? maxpagesize = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetMetricsRequest(maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetMetricsNextPageRequest(nextLink, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => ExperimentMetric.DeserializeExperimentMetric(e), ClientDiagnostics, _pipeline, "OnlineExperimentationClient.GetMetrics", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] Lists experiment 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 number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetMetricsAsync(int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetMetricsRequest(maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetMetricsNextPageRequest(nextLink, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "OnlineExperimentationClient.GetMetrics", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] Lists experiment 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 number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetMetrics(int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetMetricsRequest(maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetMetricsNextPageRequest(nextLink, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "OnlineExperimentationClient.GetMetrics", "value", "nextLink", maxpagesize, context); + } + + internal HttpMessage CreateGetMetricRequest(string experimentMetricId, RequestConditions requestConditions, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/experiment-metrics/", false); + uri.AppendPath(experimentMetricId, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + if (requestConditions != null) + { + request.Headers.Add(requestConditions, "R"); + } + return message; + } + + internal HttpMessage CreateCreateOrUpdateMetricRequest(string experimentMetricId, RequestContent content, RequestConditions requestConditions, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Patch; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/experiment-metrics/", false); + uri.AppendPath(experimentMetricId, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + if (requestConditions != null) + { + request.Headers.Add(requestConditions, "R"); + } + request.Headers.Add("Content-Type", "application/merge-patch+json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateValidateMetricRequest(RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/experiment-metrics:validate", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateDeleteMetricRequest(string experimentMetricId, RequestConditions requestConditions, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier204); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/experiment-metrics/", false); + uri.AppendPath(experimentMetricId, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + if (requestConditions != null) + { + request.Headers.Add(requestConditions, "R"); + } + return message; + } + + internal HttpMessage CreateGetMetricsRequest(int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/experiment-metrics", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip.Value, true); + } + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetMetricsNextPageRequest(string nextLink, int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + 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 }); + private static ResponseClassifier _responseClassifier200201; + private static ResponseClassifier ResponseClassifier200201 => _responseClassifier200201 ??= new StatusCodeClassifier(stackalloc ushort[] { 200, 201 }); + private static ResponseClassifier _responseClassifier204; + private static ResponseClassifier ResponseClassifier204 => _responseClassifier204 ??= new StatusCodeClassifier(stackalloc ushort[] { 204 }); + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/OnlineExperimentationClientOptions.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/OnlineExperimentationClientOptions.cs new file mode 100644 index 000000000000..f2722e3ac3b4 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/OnlineExperimentationClientOptions.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// Client options for OnlineExperimentationClient. + public partial class OnlineExperimentationClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2025_05_31_Preview; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "2025-05-31-preview". + V2025_05_31_Preview = 1, + } + + internal string Version { get; } + + /// Initializes new instance of OnlineExperimentationClientOptions. + public OnlineExperimentationClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2025_05_31_Preview => "2025-05-31-preview", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/PercentileMetricDefinition.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/PercentileMetricDefinition.Serialization.cs new file mode 100644 index 000000000000..9add2d0e3798 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/PercentileMetricDefinition.Serialization.cs @@ -0,0 +1,142 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + public partial class PercentileMetricDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PercentileMetricDefinition)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("value"u8); + writer.WriteObjectValue(Value, options); + writer.WritePropertyName("percentile"u8); + writer.WriteNumberValue(Percentile); + } + + PercentileMetricDefinition 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(PercentileMetricDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePercentileMetricDefinition(document.RootElement, options); + } + + internal static PercentileMetricDefinition DeserializePercentileMetricDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AggregatedValue value = default; + double percentile = default; + ExperimentMetricType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("value"u8)) + { + value = AggregatedValue.DeserializeAggregatedValue(property.Value, options); + continue; + } + if (property.NameEquals("percentile"u8)) + { + percentile = property.Value.GetDouble(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new ExperimentMetricType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new PercentileMetricDefinition(type, serializedAdditionalRawData, value, percentile); + } + + 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(PercentileMetricDefinition)} does not support writing '{options.Format}' format."); + } + } + + PercentileMetricDefinition 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePercentileMetricDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PercentileMetricDefinition)} 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 PercentileMetricDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePercentileMetricDefinition(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/PercentileMetricDefinition.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/PercentileMetricDefinition.cs new file mode 100644 index 000000000000..d6d680dd8429 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/PercentileMetricDefinition.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// The definition of a Percentile metric definition. Calculates a specified percentile of an event property. + public partial class PercentileMetricDefinition : ExperimentMetricDefinition + { + /// Initializes a new instance of . + /// The value to aggregate, including the event name and property to measure. + /// The percentile to measure. + /// is null. + public PercentileMetricDefinition(AggregatedValue value, double percentile) + { + Argument.AssertNotNull(value, nameof(value)); + + Type = ExperimentMetricType.Percentile; + Value = value; + Percentile = percentile; + } + + /// Initializes a new instance of . + /// Discriminator property for ExperimentMetricDefinition. + /// Keeps track of any properties unknown to the library. + /// The value to aggregate, including the event name and property to measure. + /// The percentile to measure. + internal PercentileMetricDefinition(ExperimentMetricType type, IDictionary serializedAdditionalRawData, AggregatedValue value, double percentile) : base(type, serializedAdditionalRawData) + { + Value = value; + Percentile = percentile; + } + + /// Initializes a new instance of for deserialization. + internal PercentileMetricDefinition() + { + } + + /// The value to aggregate, including the event name and property to measure. + public AggregatedValue Value { get; set; } + /// The percentile to measure. + public double Percentile { get; set; } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/SumMetricDefinition.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/SumMetricDefinition.Serialization.cs new file mode 100644 index 000000000000..07c7217ad4f9 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/SumMetricDefinition.Serialization.cs @@ -0,0 +1,134 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + public partial class SumMetricDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SumMetricDefinition)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("value"u8); + writer.WriteObjectValue(Value, options); + } + + SumMetricDefinition 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(SumMetricDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSumMetricDefinition(document.RootElement, options); + } + + internal static SumMetricDefinition DeserializeSumMetricDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AggregatedValue value = default; + ExperimentMetricType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("value"u8)) + { + value = AggregatedValue.DeserializeAggregatedValue(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new ExperimentMetricType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SumMetricDefinition(type, serializedAdditionalRawData, value); + } + + 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(SumMetricDefinition)} does not support writing '{options.Format}' format."); + } + } + + SumMetricDefinition 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSumMetricDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SumMetricDefinition)} 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 SumMetricDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSumMetricDefinition(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/SumMetricDefinition.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/SumMetricDefinition.cs new file mode 100644 index 000000000000..ffe5291130ae --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/SumMetricDefinition.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// The definition of a Sum metric definition. Calculates the sum of a specified event property. Experiment analysis accounts for unequal traffic allocation. + public partial class SumMetricDefinition : ExperimentMetricDefinition + { + /// Initializes a new instance of . + /// The value to aggregate. + /// is null. + public SumMetricDefinition(AggregatedValue value) + { + Argument.AssertNotNull(value, nameof(value)); + + Type = ExperimentMetricType.Sum; + Value = value; + } + + /// Initializes a new instance of . + /// Discriminator property for ExperimentMetricDefinition. + /// Keeps track of any properties unknown to the library. + /// The value to aggregate. + internal SumMetricDefinition(ExperimentMetricType type, IDictionary serializedAdditionalRawData, AggregatedValue value) : base(type, serializedAdditionalRawData) + { + Value = value; + } + + /// Initializes a new instance of for deserialization. + internal SumMetricDefinition() + { + } + + /// The value to aggregate. + public AggregatedValue Value { get; set; } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UnknownExperimentMetricDefinition.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UnknownExperimentMetricDefinition.Serialization.cs new file mode 100644 index 000000000000..02f9f4527718 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UnknownExperimentMetricDefinition.Serialization.cs @@ -0,0 +1,126 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + internal partial class UnknownExperimentMetricDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ExperimentMetricDefinition)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + ExperimentMetricDefinition 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(ExperimentMetricDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeExperimentMetricDefinition(document.RootElement, options); + } + + internal static UnknownExperimentMetricDefinition DeserializeUnknownExperimentMetricDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ExperimentMetricType type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new ExperimentMetricType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownExperimentMetricDefinition(type, 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(ExperimentMetricDefinition)} does not support writing '{options.Format}' format."); + } + } + + ExperimentMetricDefinition 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeExperimentMetricDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ExperimentMetricDefinition)} 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 UnknownExperimentMetricDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownExperimentMetricDefinition(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UnknownExperimentMetricDefinition.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UnknownExperimentMetricDefinition.cs new file mode 100644 index 000000000000..ac95dd649fd1 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UnknownExperimentMetricDefinition.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// Unknown version of ExperimentMetricDefinition. + internal partial class UnknownExperimentMetricDefinition : ExperimentMetricDefinition + { + /// Initializes a new instance of . + /// Discriminator property for ExperimentMetricDefinition. + /// Keeps track of any properties unknown to the library. + internal UnknownExperimentMetricDefinition(ExperimentMetricType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownExperimentMetricDefinition() + { + } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UserCountMetricDefinition.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UserCountMetricDefinition.Serialization.cs new file mode 100644 index 000000000000..f7378fccde7a --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UserCountMetricDefinition.Serialization.cs @@ -0,0 +1,134 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + public partial class UserCountMetricDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UserCountMetricDefinition)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("event"u8); + writer.WriteObjectValue(Event, options); + } + + UserCountMetricDefinition 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(UserCountMetricDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUserCountMetricDefinition(document.RootElement, options); + } + + internal static UserCountMetricDefinition DeserializeUserCountMetricDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ObservedEvent @event = default; + ExperimentMetricType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("event"u8)) + { + @event = ObservedEvent.DeserializeObservedEvent(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new ExperimentMetricType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UserCountMetricDefinition(type, serializedAdditionalRawData, @event); + } + + 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(UserCountMetricDefinition)} does not support writing '{options.Format}' format."); + } + } + + UserCountMetricDefinition 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUserCountMetricDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(UserCountMetricDefinition)} 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 UserCountMetricDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUserCountMetricDefinition(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UserCountMetricDefinition.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UserCountMetricDefinition.cs new file mode 100644 index 000000000000..090c38a10ad4 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UserCountMetricDefinition.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// The definition of a UserCount metric definition. Counts unique users who encounter a specified event. + public partial class UserCountMetricDefinition : ExperimentMetricDefinition + { + /// Initializes a new instance of . + /// Event to observe. + /// is null. + public UserCountMetricDefinition(ObservedEvent @event) + { + Argument.AssertNotNull(@event, nameof(@event)); + + Type = ExperimentMetricType.UserCount; + Event = @event; + } + + /// Initializes a new instance of . + /// Discriminator property for ExperimentMetricDefinition. + /// Keeps track of any properties unknown to the library. + /// Event to observe. + internal UserCountMetricDefinition(ExperimentMetricType type, IDictionary serializedAdditionalRawData, ObservedEvent @event) : base(type, serializedAdditionalRawData) + { + Event = @event; + } + + /// Initializes a new instance of for deserialization. + internal UserCountMetricDefinition() + { + } + + /// Event to observe. + public ObservedEvent Event { get; set; } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UserRateMetricDefinition.Serialization.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UserRateMetricDefinition.Serialization.cs new file mode 100644 index 000000000000..2ae0630ab388 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UserRateMetricDefinition.Serialization.cs @@ -0,0 +1,142 @@ +// 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.Core; + +namespace Azure.Analytics.OnlineExperimentation +{ + public partial class UserRateMetricDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UserRateMetricDefinition)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("startEvent"u8); + writer.WriteObjectValue(StartEvent, options); + writer.WritePropertyName("endEvent"u8); + writer.WriteObjectValue(EndEvent, options); + } + + UserRateMetricDefinition 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(UserRateMetricDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUserRateMetricDefinition(document.RootElement, options); + } + + internal static UserRateMetricDefinition DeserializeUserRateMetricDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ObservedEvent startEvent = default; + ObservedEvent endEvent = default; + ExperimentMetricType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("startEvent"u8)) + { + startEvent = ObservedEvent.DeserializeObservedEvent(property.Value, options); + continue; + } + if (property.NameEquals("endEvent"u8)) + { + endEvent = ObservedEvent.DeserializeObservedEvent(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new ExperimentMetricType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UserRateMetricDefinition(type, serializedAdditionalRawData, startEvent, endEvent); + } + + 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(UserRateMetricDefinition)} does not support writing '{options.Format}' format."); + } + } + + UserRateMetricDefinition 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUserRateMetricDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(UserRateMetricDefinition)} 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 UserRateMetricDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUserRateMetricDefinition(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/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UserRateMetricDefinition.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UserRateMetricDefinition.cs new file mode 100644 index 000000000000..4f4b3fe0e116 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Generated/UserRateMetricDefinition.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Analytics.OnlineExperimentation +{ + /// The definition of a UserRate metric definition. Calculates the percentage of users who encounter a start event and subsequently an end event. Users must encounter events in the specified order. + public partial class UserRateMetricDefinition : ExperimentMetricDefinition + { + /// Initializes a new instance of . + /// The start event to observe as the rate denominator. + /// The end event to observe, which is a condition for the rate numerator. + /// or is null. + public UserRateMetricDefinition(ObservedEvent startEvent, ObservedEvent endEvent) + { + Argument.AssertNotNull(startEvent, nameof(startEvent)); + Argument.AssertNotNull(endEvent, nameof(endEvent)); + + Type = ExperimentMetricType.UserRate; + StartEvent = startEvent; + EndEvent = endEvent; + } + + /// Initializes a new instance of . + /// Discriminator property for ExperimentMetricDefinition. + /// Keeps track of any properties unknown to the library. + /// The start event to observe as the rate denominator. + /// The end event to observe, which is a condition for the rate numerator. + internal UserRateMetricDefinition(ExperimentMetricType type, IDictionary serializedAdditionalRawData, ObservedEvent startEvent, ObservedEvent endEvent) : base(type, serializedAdditionalRawData) + { + StartEvent = startEvent; + EndEvent = endEvent; + } + + /// Initializes a new instance of for deserialization. + internal UserRateMetricDefinition() + { + } + + /// The start event to observe as the rate denominator. + public ObservedEvent StartEvent { get; set; } + /// The end event to observe, which is a condition for the rate numerator. + public ObservedEvent EndEvent { get; set; } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Properties/AssemblyInfo.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..cbf15ba93b83 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/src/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Azure.Analytics.OnlineExperimentation.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] + +// Replace Microsoft.Test with the correct resource provider namepace for your service and uncomment. +// See https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/azure-services-resource-providers +// for the list of possible values. +[assembly: Azure.Core.AzureResourceProviderNamespace("Microsoft.Template")] diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/tests/Azure.Analytics.OnlineExperimentation.Tests.csproj b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/tests/Azure.Analytics.OnlineExperimentation.Tests.csproj new file mode 100644 index 000000000000..4eaaf5696587 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/tests/Azure.Analytics.OnlineExperimentation.Tests.csproj @@ -0,0 +1,20 @@ + + + $(RequiredTargetFrameworks) + + $(NoWarn);CS1591 + + + + + + + + + + + + + + + diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/tests/Generated/Samples/Samples_OnlineExperimentationClient.cs b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/tests/Generated/Samples/Samples_OnlineExperimentationClient.cs new file mode 100644 index 000000000000..f9ec215f26b6 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/tests/Generated/Samples/Samples_OnlineExperimentationClient.cs @@ -0,0 +1,906 @@ +// 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 System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Azure.Analytics.OnlineExperimentation.Samples +{ + public partial class Samples_OnlineExperimentationClient + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ExperimentMetric_GetMetric_GetMetric() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + Response response = client.GetMetric("events_purchase_creditcard", null, null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ExperimentMetric_GetMetric_GetMetric_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + Response response = await client.GetMetricAsync("events_purchase_creditcard", null, null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ExperimentMetric_GetMetric_GetMetric_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + Response response = client.GetMetric("events_purchase_creditcard"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ExperimentMetric_GetMetric_GetMetric_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + Response response = await client.GetMetricAsync("events_purchase_creditcard"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricAverage() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Average revenue per purchase [USD]", + description = "The average revenue per purchase transaction in USD. Refund transactions are excluded from this metric. The total revenue might increase while this metric decreases if the number of purchases increases.", + lifecycle = "Active", + categories = new object[] + { +"Monetization" + }, + desiredDirection = "Increase", + definition = new + { + type = "Average", + value = new + { + eventName = "Transaction", + eventProperty = "Revenue", + filter = "Revenue > 0", + }, + }, + }); + Response response = client.CreateOrUpdateMetric("avg_purchase_revenue", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricAverage_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Average revenue per purchase [USD]", + description = "The average revenue per purchase transaction in USD. Refund transactions are excluded from this metric. The total revenue might increase while this metric decreases if the number of purchases increases.", + lifecycle = "Active", + categories = new object[] + { +"Monetization" + }, + desiredDirection = "Increase", + definition = new + { + type = "Average", + value = new + { + eventName = "Transaction", + eventProperty = "Revenue", + filter = "Revenue > 0", + }, + }, + }); + Response response = await client.CreateOrUpdateMetricAsync("avg_purchase_revenue", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricEventCount() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Number of purchases (credit card)", + description = "The number of purchase transactions made with credit card. Refund transactions are excluded from this metric.", + lifecycle = "Active", + categories = new object[] + { +"Monetization" + }, + desiredDirection = "Increase", + definition = new Dictionary + { + ["type"] = "EventCount", + ["event"] = new + { + eventName = "Transaction", + filter = "Revenue > 0 and ['payment.method'] == 'credit_card'", + } + }, + }); + Response response = client.CreateOrUpdateMetric("events_purchase_creditcard", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricEventCount_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Number of purchases (credit card)", + description = "The number of purchase transactions made with credit card. Refund transactions are excluded from this metric.", + lifecycle = "Active", + categories = new object[] + { +"Monetization" + }, + desiredDirection = "Increase", + definition = new Dictionary + { + ["type"] = "EventCount", + ["event"] = new + { + eventName = "Transaction", + filter = "Revenue > 0 and ['payment.method'] == 'credit_card'", + } + }, + }); + Response response = await client.CreateOrUpdateMetricAsync("events_purchase_creditcard", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricEventRate() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Refund rate", + description = "The percentage of transactions that are refunds. This metric is calculated as the number of refund transactions divided by the total number of transactions.", + lifecycle = "Active", + categories = new object[] + { +"Monetization" + }, + desiredDirection = "Neutral", + definition = new Dictionary + { + ["type"] = "EventRate", + ["event"] = new + { + eventName = "Transaction", + }, + ["rateCondition"] = "Revenue < 0" + }, + }); + Response response = client.CreateOrUpdateMetric("rate_refund", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricEventRate_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Refund rate", + description = "The percentage of transactions that are refunds. This metric is calculated as the number of refund transactions divided by the total number of transactions.", + lifecycle = "Active", + categories = new object[] + { +"Monetization" + }, + desiredDirection = "Neutral", + definition = new Dictionary + { + ["type"] = "EventRate", + ["event"] = new + { + eventName = "Transaction", + }, + ["rateCondition"] = "Revenue < 0" + }, + }); + Response response = await client.CreateOrUpdateMetricAsync("rate_refund", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricPercentile() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "95th percentile of page load time [ms]", + description = "The 95th percentile of the page load time for all pages. Measured in milliseconds. Review page-specific metric results to identify pages that need optimization.", + lifecycle = "Active", + categories = new object[] + { +"Performance", +"Important" + }, + desiredDirection = "Decrease", + definition = new + { + type = "Percentile", + value = new + { + eventName = "PageLoad", + eventProperty = "LoadTime_ms", + }, + percentile = 95, + }, + }); + Response response = client.CreateOrUpdateMetric("p95_page_load_time", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricPercentile_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "95th percentile of page load time [ms]", + description = "The 95th percentile of the page load time for all pages. Measured in milliseconds. Review page-specific metric results to identify pages that need optimization.", + lifecycle = "Active", + categories = new object[] + { +"Performance", +"Important" + }, + desiredDirection = "Decrease", + definition = new + { + type = "Percentile", + value = new + { + eventName = "PageLoad", + eventProperty = "LoadTime_ms", + }, + percentile = 95, + }, + }); + Response response = await client.CreateOrUpdateMetricAsync("p95_page_load_time", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricSum() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Total revenue [USD]", + description = "The total revenue in USD. Refund transactions contribute negatively to this metric.", + lifecycle = "Active", + categories = new object[] + { +"Monetization", +"Important" + }, + desiredDirection = "Increase", + definition = new + { + type = "Sum", + value = new + { + eventName = "Transaction", + eventProperty = "Revenue", + }, + }, + }); + Response response = client.CreateOrUpdateMetric("sum_revenue", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricSum_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Total revenue [USD]", + description = "The total revenue in USD. Refund transactions contribute negatively to this metric.", + lifecycle = "Active", + categories = new object[] + { +"Monetization", +"Important" + }, + desiredDirection = "Increase", + definition = new + { + type = "Sum", + value = new + { + eventName = "Transaction", + eventProperty = "Revenue", + }, + }, + }); + Response response = await client.CreateOrUpdateMetricAsync("sum_revenue", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricUserCount() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Users with purchase", + description = "The number of users who have made at least one purchase transaction. Refund transactions are excluded from this metric. As the analysis period grows, this metric begins to saturate as users making multiple purchases no longer contribute.", + lifecycle = "Active", + categories = new object[] + { +"Monetization" + }, + desiredDirection = "Increase", + definition = new Dictionary + { + ["type"] = "UserCount", + ["event"] = new + { + eventName = "Transaction", + filter = "Revenue > 0", + } + }, + }); + Response response = client.CreateOrUpdateMetric("users_purchase", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricUserCount_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Users with purchase", + description = "The number of users who have made at least one purchase transaction. Refund transactions are excluded from this metric. As the analysis period grows, this metric begins to saturate as users making multiple purchases no longer contribute.", + lifecycle = "Active", + categories = new object[] + { +"Monetization" + }, + desiredDirection = "Increase", + definition = new Dictionary + { + ["type"] = "UserCount", + ["event"] = new + { + eventName = "Transaction", + filter = "Revenue > 0", + } + }, + }); + Response response = await client.CreateOrUpdateMetricAsync("users_purchase", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricUserRate() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Subscription ad conversion rate", + description = "The percentage of users who saw an advertisement for a subscription promotion and then later successfully subscribed. This metric is calculated as the number of users who successfully subscribed after seeing the advert divided by the total number of users who saw the advert. Users who saw multiple adverts or subscribed multiple times are counted only once. Users who saw the advert before the analysis period starts are excluded from this metric.", + lifecycle = "Active", + categories = new object[] + { +"Monetization" + }, + desiredDirection = "Increase", + definition = new + { + type = "UserRate", + startEvent = new + { + eventName = "AdView", + filter = "Source == 'subscription_promo'", + }, + endEvent = new + { + eventName = "Subscribe", + filter = "Status == 'Success'", + }, + }, + }); + Response response = client.CreateOrUpdateMetric("rate_subscription_ad", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ExperimentMetric_CreateOrUpdateMetric_CreateOrUpdateMetricUserRate_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Subscription ad conversion rate", + description = "The percentage of users who saw an advertisement for a subscription promotion and then later successfully subscribed. This metric is calculated as the number of users who successfully subscribed after seeing the advert divided by the total number of users who saw the advert. Users who saw multiple adverts or subscribed multiple times are counted only once. Users who saw the advert before the analysis period starts are excluded from this metric.", + lifecycle = "Active", + categories = new object[] + { +"Monetization" + }, + desiredDirection = "Increase", + definition = new + { + type = "UserRate", + startEvent = new + { + eventName = "AdView", + filter = "Source == 'subscription_promo'", + }, + endEvent = new + { + eventName = "Subscribe", + filter = "Status == 'Success'", + }, + }, + }); + Response response = await client.CreateOrUpdateMetricAsync("rate_subscription_ad", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_OnlineExperimentation_ValidateMetric_ValidateMetric() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Average revenue per purchase [USD]", + description = "The average revenue per purchase transaction in USD. Refund transactions are excluded from this metric. The total revenue might increase while this metric decreases if the number of purchases increases.", + lifecycle = "Active", + categories = new object[] + { +"Monetization" + }, + desiredDirection = "Increase", + definition = new + { + type = "Average", + value = new + { + eventName = "Transaction", + eventProperty = "Revenue", + filter = "Revenue >", + }, + }, + }); + Response response = client.ValidateMetric(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("isValid").ToString()); + Console.WriteLine(result.GetProperty("diagnostics")[0].GetProperty("message").ToString()); + Console.WriteLine(result.GetProperty("diagnostics")[0].GetProperty("code").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_OnlineExperimentation_ValidateMetric_ValidateMetric_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + displayName = "Average revenue per purchase [USD]", + description = "The average revenue per purchase transaction in USD. Refund transactions are excluded from this metric. The total revenue might increase while this metric decreases if the number of purchases increases.", + lifecycle = "Active", + categories = new object[] + { +"Monetization" + }, + desiredDirection = "Increase", + definition = new + { + type = "Average", + value = new + { + eventName = "Transaction", + eventProperty = "Revenue", + filter = "Revenue >", + }, + }, + }); + Response response = await client.ValidateMetricAsync(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("isValid").ToString()); + Console.WriteLine(result.GetProperty("diagnostics")[0].GetProperty("message").ToString()); + Console.WriteLine(result.GetProperty("diagnostics")[0].GetProperty("code").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_OnlineExperimentation_ValidateMetric_ValidateMetric_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + ExperimentMetric body = new ExperimentMetric( + LifecycleStage.Active, + "Average revenue per purchase [USD]", + "The average revenue per purchase transaction in USD. Refund transactions are excluded from this metric. The total revenue might increase while this metric decreases if the number of purchases increases.", + new string[] { "Monetization" }, + DesiredDirection.Increase, + new AverageMetricDefinition(new AggregatedValue("Transaction", "Revenue") + { + Filter = "Revenue >", + })); + Response response = client.ValidateMetric(body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_OnlineExperimentation_ValidateMetric_ValidateMetric_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + ExperimentMetric body = new ExperimentMetric( + LifecycleStage.Active, + "Average revenue per purchase [USD]", + "The average revenue per purchase transaction in USD. Refund transactions are excluded from this metric. The total revenue might increase while this metric decreases if the number of purchases increases.", + new string[] { "Monetization" }, + DesiredDirection.Increase, + new AverageMetricDefinition(new AggregatedValue("Transaction", "Revenue") + { + Filter = "Revenue >", + })); + Response response = await client.ValidateMetricAsync(body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ExperimentMetric_DeleteMetric_DeleteMetric() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + Response response = client.DeleteMetric("avg_purchase_revenue"); + + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ExperimentMetric_DeleteMetric_DeleteMetric_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + Response response = await client.DeleteMetricAsync("avg_purchase_revenue"); + + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ExperimentMetric_GetMetrics_ListMetrics() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + foreach (BinaryData item in client.GetMetrics(null, 15, null, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ExperimentMetric_GetMetrics_ListMetrics_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + await foreach (BinaryData item in client.GetMetricsAsync(null, 15, null, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("lifecycle").ToString()); + Console.WriteLine(result.GetProperty("displayName").ToString()); + Console.WriteLine(result.GetProperty("description").ToString()); + Console.WriteLine(result.GetProperty("categories")[0].ToString()); + Console.WriteLine(result.GetProperty("desiredDirection").ToString()); + Console.WriteLine(result.GetProperty("definition").GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("eTag").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ExperimentMetric_GetMetrics_ListMetrics_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + foreach (ExperimentMetric item in client.GetMetrics()) + { + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ExperimentMetric_GetMetrics_ListMetrics_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + OnlineExperimentationClient client = new OnlineExperimentationClient(endpoint, credential); + + await foreach (ExperimentMetric item in client.GetMetricsAsync()) + { + } + } + } +} diff --git a/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/tsp-location.yaml b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/tsp-location.yaml new file mode 100644 index 000000000000..260fc1d0af85 --- /dev/null +++ b/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/onlineexperimentation/Azure.Analytics.OnlineExperimentation +commit: 4e1f5223f18c456141bfd3fdee2f1fec1c6e503b +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/onlineexperimentation/ci.yml b/sdk/onlineexperimentation/ci.yml new file mode 100644 index 000000000000..ee3c08960228 --- /dev/null +++ b/sdk/onlineexperimentation/ci.yml @@ -0,0 +1,35 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + paths: + include: + - sdk/onlineexperimentation + - sdk/onlineexperimentation/ci.yml + - sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/onlineexperimentation + - sdk/onlineexperimentation/ci.yml + - sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation + +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: onlineexperimentation + ArtifactName: packages + Artifacts: + - name: Azure.Analytics.OnlineExperimentation + safeName: AzureAnalyticsOnlineExperimentation