From e1d9c290843aa94bfd4530442f879c1c0e1dffd0 Mon Sep 17 00:00:00 2001
From: Scott Addie <10702007+scottaddie@users.noreply.github.com>
Date: Tue, 20 Aug 2024 09:39:42 -0500
Subject: [PATCH 01/71] Restore DAC auth flow diagram (#45601)
---
.../images/mermaidjs/DefaultAzureCredentialAuthFlow.svg | 1 +
1 file changed, 1 insertion(+)
create mode 100644 sdk/identity/Azure.Identity/images/mermaidjs/DefaultAzureCredentialAuthFlow.svg
diff --git a/sdk/identity/Azure.Identity/images/mermaidjs/DefaultAzureCredentialAuthFlow.svg b/sdk/identity/Azure.Identity/images/mermaidjs/DefaultAzureCredentialAuthFlow.svg
new file mode 100644
index 0000000000000..f60052a3a0662
--- /dev/null
+++ b/sdk/identity/Azure.Identity/images/mermaidjs/DefaultAzureCredentialAuthFlow.svg
@@ -0,0 +1 @@
+DefaultAzureCredential authentication flow; Flowchart showing the credential chain implemented by DefaultAzureCredential; CREDENTIALS
Interactive browser
Environment
Workload Identity
Managed Identity
Visual Studio
Azure CLI
Azure PowerShell
Azure Developer CLI
CREDENTIAL TYPES
Interactive
Deployed service
Developer tool
\ No newline at end of file
From d5f3c397728a00bc1f2c2ae886991fa22e38ed16 Mon Sep 17 00:00:00 2001
From: "Jianing Wang (MSFT)"
<141212663+jianingwang123@users.noreply.github.com>
Date: Wed, 21 Aug 2024 01:37:10 +0800
Subject: [PATCH 02/71] Fix Azure Storage DataMovement FilesShares Samples
Issue (#45558)
* fix/45322
* Update-Snippet
---
sdk/storage/Azure.Storage.DataMovement.Files.Shares/README.md | 2 +-
.../samples/Sample01b_HelloWorldAsync.cs | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/sdk/storage/Azure.Storage.DataMovement.Files.Shares/README.md b/sdk/storage/Azure.Storage.DataMovement.Files.Shares/README.md
index 4deb335aad25f..33e0c4a02c4f6 100644
--- a/sdk/storage/Azure.Storage.DataMovement.Files.Shares/README.md
+++ b/sdk/storage/Azure.Storage.DataMovement.Files.Shares/README.md
@@ -116,7 +116,7 @@ Upload a directory.
```C# Snippet:SimpleDirectoryUpload_Shares
DataTransfer folderTransfer = await transferManager.StartTransferAsync(
- sourceResource: files.FromFile(sourceLocalDirectory),
+ sourceResource: files.FromDirectory(sourceLocalDirectory),
destinationResource: shares.FromDirectory(destinationFolderUri));
await folderTransfer.WaitForCompletionAsync();
```
diff --git a/sdk/storage/Azure.Storage.DataMovement.Files.Shares/samples/Sample01b_HelloWorldAsync.cs b/sdk/storage/Azure.Storage.DataMovement.Files.Shares/samples/Sample01b_HelloWorldAsync.cs
index 77ffff12a88ce..b9427ce812b27 100644
--- a/sdk/storage/Azure.Storage.DataMovement.Files.Shares/samples/Sample01b_HelloWorldAsync.cs
+++ b/sdk/storage/Azure.Storage.DataMovement.Files.Shares/samples/Sample01b_HelloWorldAsync.cs
@@ -124,7 +124,7 @@ public async Task Upload()
#region Snippet:SimpleDirectoryUpload_Shares
DataTransfer folderTransfer = await transferManager.StartTransferAsync(
- sourceResource: files.FromFile(sourceLocalDirectory),
+ sourceResource: files.FromDirectory(sourceLocalDirectory),
destinationResource: shares.FromDirectory(destinationFolderUri));
await folderTransfer.WaitForCompletionAsync();
#endregion
From e1d47e1c01a96762b8a85fde8b5338854ef43f5f Mon Sep 17 00:00:00 2001
From: Nick Liu
Date: Tue, 20 Aug 2024 15:32:43 -0400
Subject: [PATCH 03/71] [Storage] Copy Blob APIs Authentication references
updated REST API doc (#45590)
* Initial commit
* Added for BlobBaseClient.SyncCopyFromUri & BlockBlobClient.SyncUploadFromUri
---
.../Azure.Storage.Blobs/src/BlobBaseClient.cs | 67 ++++++-------------
.../src/BlockBlobClient.cs | 30 ++++-----
2 files changed, 37 insertions(+), 60 deletions(-)
diff --git a/sdk/storage/Azure.Storage.Blobs/src/BlobBaseClient.cs b/sdk/storage/Azure.Storage.Blobs/src/BlobBaseClient.cs
index c1416524f0221..93d74d194a85e 100644
--- a/sdk/storage/Azure.Storage.Blobs/src/BlobBaseClient.cs
+++ b/sdk/storage/Azure.Storage.Blobs/src/BlobBaseClient.cs
@@ -3247,12 +3247,8 @@ internal async Task OpenReadInternal(
///
/// Specifies the of the source blob. The value may
/// be a of up to 2 KB in length that specifies a
- /// blob. A source blob in the same storage account can be
- /// authenticated via Shared Key. However, if the source is a blob in
- /// another account, the source blob must either be public or must be
- /// authenticated via a shared access signature. If the source blob
- /// is public, no authentication is required to perform the copy
- /// operation.
+ /// blob.
+ /// Source Blob Authentication
///
/// The source object may be a file in the Azure File service. If the
/// source object is a file that is to be copied to a blob, then the
@@ -3314,12 +3310,8 @@ public virtual CopyFromUriOperation StartCopyFromUri(
///
/// Specifies the of the source blob. The value may
/// be a of up to 2 KB in length that specifies a
- /// blob. A source blob in the same storage account can be
- /// authenticated via Shared Key. However, if the source is a blob in
- /// another account, the source blob must either be public or must be
- /// authenticated via a shared access signature. If the source blob
- /// is public, no authentication is required to perform the copy
- /// operation.
+ /// blob.
+ /// Source Blob Authentication
///
/// The source object may be a file in the Azure File service. If the
/// source object is a file that is to be copied to a blob, then the
@@ -3402,12 +3394,8 @@ public virtual CopyFromUriOperation StartCopyFromUri(
///
/// Specifies the of the source blob. The value may
/// be a of up to 2 KB in length that specifies a
- /// blob. A source blob in the same storage account can be
- /// authenticated via Shared Key. However, if the source is a blob in
- /// another account, the source blob must either be public or must be
- /// authenticated via a shared access signature. If the source blob
- /// is public, no authentication is required to perform the copy
- /// operation.
+ /// blob.
+ /// Source Blob Authentication
///
/// The source object may be a file in the Azure File service. If the
/// source object is a file that is to be copied to a blob, then the
@@ -3469,12 +3457,8 @@ public virtual async Task StartCopyFromUriAsync(
///
/// Specifies the of the source blob. The value may
/// be a of up to 2 KB in length that specifies a
- /// blob. A source blob in the same storage account can be
- /// authenticated via Shared Key. However, if the source is a blob in
- /// another account, the source blob must either be public or must be
- /// authenticated via a shared access signature. If the source blob
- /// is public, no authentication is required to perform the copy
- /// operation.
+ /// blob.
+ /// Source Blob Authentication
///
/// The source object may be a file in the Azure File service. If the
/// source object is a file that is to be copied to a blob, then the
@@ -3557,12 +3541,8 @@ public virtual async Task StartCopyFromUriAsync(
///
/// Specifies the of the source blob. The value may
/// be a of up to 2 KB in length that specifies a
- /// blob. A source blob in the same storage account can be
- /// authenticated via Shared Key. However, if the source is a blob in
- /// another account, the source blob must either be public or must be
- /// authenticated via a shared access signature. If the source blob
- /// is public, no authentication is required to perform the copy
- /// operation.
+ /// blob.
+ /// Source Blob Authentication
///
/// The source object may be a file in the Azure File service. If the
/// source object is a file that is to be copied to a blob, then the
@@ -3921,11 +3901,10 @@ private async Task AbortCopyFromUriInternal(
///
///
/// Required. Specifies the URL of the source blob. The value may be a URL of up to 2 KB in length
- /// that specifies a blob. The value should be URL-encoded as it would appear in a request URI. The
- /// source blob must either be public or must be authorized via a shared access signature. If the
- /// source blob is public, no authorization is required to perform the operation. If the size of the
- /// source blob is greater than 256 MiB, the request will fail with 409 (Conflict). The blob type of
- /// the source blob has to be block blob.
+ /// that specifies a blob. The value should be URL-encoded as it would appear in a request URI.
+ ///
+ /// Source Blob Authentication If the size of the source blob is greater than 256 MiB, the request will fail
+ /// with 409 (Conflict). The blob type of the source blob has to be block blob.
///
///
/// Optional parameters.
@@ -3975,11 +3954,10 @@ public virtual Response SyncCopyFromUri(
///
///
/// Required. Specifies the URL of the source blob. The value may be a URL of up to 2 KB in length
- /// that specifies a blob. The value should be URL-encoded as it would appear in a request URI. The
- /// source blob must either be public or must be authorized via a shared access signature. If the
- /// source blob is public, no authorization is required to perform the operation. If the size of the
- /// source blob is greater than 256 MiB, the request will fail with 409 (Conflict). The blob type of
- /// the source blob has to be block blob.
+ /// that specifies a blob. The value should be URL-encoded as it would appear in a request URI.
+ ///
+ /// Source Blob Authentication If the size of the source blob is greater than 256 MiB, the request will fail
+ /// with 409 (Conflict). The blob type of the source blob has to be block blob.
///
///
/// Optional parameters.
@@ -4029,11 +4007,10 @@ public virtual async Task> SyncCopyFromUriAsync(
///
///
/// Required. Specifies the URL of the source blob. The value may be a URL of up to 2 KB in length
- /// that specifies a blob. The value should be URL-encoded as it would appear in a request URI. The
- /// source blob must either be public or must be authorized via a shared access signature. If the
- /// source blob is public, no authorization is required to perform the operation. If the size of the
- /// source blob is greater than 256 MiB, the request will fail with 409 (Conflict). The blob type of
- /// the source blob has to be block blob.
+ /// that specifies a blob. The value should be URL-encoded as it would appear in a request URI.
+ ///
+ /// Source Blob Authentication If the size of the source blob is greater than 256 MiB, the request will fail
+ /// with 409 (Conflict). The blob type of the source blob has to be block blob.
///
///
/// Optional custom metadata to set for this blob.
diff --git a/sdk/storage/Azure.Storage.Blobs/src/BlockBlobClient.cs b/sdk/storage/Azure.Storage.Blobs/src/BlockBlobClient.cs
index cd6bc3788fc26..b873b9bc7129e 100644
--- a/sdk/storage/Azure.Storage.Blobs/src/BlockBlobClient.cs
+++ b/sdk/storage/Azure.Storage.Blobs/src/BlockBlobClient.cs
@@ -2840,9 +2840,9 @@ internal async Task OpenWriteInternal(
/// Required. Specifies the URL of the source blob. The source blob may be of any type,
/// including a block blob, append blob, or page blob. The value may be a URL of up to 2
/// KiB in length that specifies a blob. The value should be URL-encoded as it would appear
- /// in a request URI. The source blob must either be public or must be authorized via a
- /// shared access signature. If the source blob is public, no authorization is required
- /// to perform the operation.
+ /// in a request URI.
+ ///
+ /// Source Blob Authentication
///
///
/// Whether the upload should overwrite the existing blob. The
@@ -2884,9 +2884,9 @@ public virtual Response SyncUploadFromUri(
/// Required. Specifies the URL of the source blob. The source blob may be of any type,
/// including a block blob, append blob, or page blob. The value may be a URL of up to 2
/// KiB in length that specifies a blob. The value should be URL-encoded as it would appear
- /// in a request URI. The source blob must either be public or must be authorized via a
- /// shared access signature. If the source blob is public, no authorization is required
- /// to perform the operation.
+ /// in a request URI.
+ ///
+ /// Source Blob Authentication
///
///
/// Whether the upload should overwrite the existing blob. The
@@ -2928,9 +2928,9 @@ public virtual async Task> SyncUploadFromUriAsync(
/// Required. Specifies the URL of the source blob. The source blob may be of any type,
/// including a block blob, append blob, or page blob. The value may be a URL of up to 2
/// KiB in length that specifies a blob. The value should be URL-encoded as it would appear
- /// in a request URI. The source blob must either be public or must be authorized via a
- /// shared access signature. If the source blob is public, no authorization is required
- /// to perform the operation.
+ /// in a request URI.
+ ///
+ /// Source Blob Authentication
///
///
/// Optional parameters.
@@ -2970,9 +2970,9 @@ public virtual Response SyncUploadFromUri(
/// Required. Specifies the URL of the source blob. The source blob may be of any type,
/// including a block blob, append blob, or page blob. The value may be a URL of up to 2
/// KiB in length that specifies a blob. The value should be URL-encoded as it would appear
- /// in a request URI. The source blob must either be public or must be authorized via a
- /// shared access signature. If the source blob is public, no authorization is required
- /// to perform the operation.
+ /// in a request URI.
+ ///
+ /// Source Blob Authentication
///
///
/// Optional parameters.
@@ -3012,9 +3012,9 @@ public virtual async Task> SyncUploadFromUriAsync(
/// Required. Specifies the URL of the source blob. The source blob may be of any type,
/// including a block blob, append blob, or page blob. The value may be a URL of up to 2
/// KiB in length that specifies a blob. The value should be URL-encoded as it would appear
- /// in a request URI. The source blob must either be public or must be authorized via a
- /// shared access signature. If the source blob is public, no authorization is required
- /// to perform the operation.
+ /// in a request URI.
+ ///
+ /// Source Blob Authentication
///
///
/// Optional parameters.
From 5dd7b105a748f5ffb25095c794f26144a85e8ccb Mon Sep 17 00:00:00 2001
From: Jose Arriaga Maldonado <45773732+joseharriaga@users.noreply.github.com>
Date: Tue, 20 Aug 2024 12:38:02 -0700
Subject: [PATCH 04/71] [System.ClientModel] Remove the implicit cast from
string to ApiKeyCredential (#45554)
Removes the implicit cast from `string` to `ApiKeyCredential` because it's confusing and doesn't version well.
---
sdk/core/System.ClientModel/CHANGELOG.md | 2 ++
.../api/System.ClientModel.net6.0.cs | 1 -
.../api/System.ClientModel.netstandard2.0.cs | 1 -
.../src/Convenience/ApiKeyCredential.cs | 3 ---
.../Pipeline/ApiKeyAuthenticationPolicyTests.cs | 13 -------------
5 files changed, 2 insertions(+), 18 deletions(-)
diff --git a/sdk/core/System.ClientModel/CHANGELOG.md b/sdk/core/System.ClientModel/CHANGELOG.md
index 6878bacb6092e..e924704c34ea4 100644
--- a/sdk/core/System.ClientModel/CHANGELOG.md
+++ b/sdk/core/System.ClientModel/CHANGELOG.md
@@ -10,6 +10,8 @@
### Other Changes
+- Removed implicit cast from `string` to `ApiKeyCredential`.
+
## 1.1.0-beta.7 (2024-08-14)
### Features Added
diff --git a/sdk/core/System.ClientModel/api/System.ClientModel.net6.0.cs b/sdk/core/System.ClientModel/api/System.ClientModel.net6.0.cs
index 38a53857153d1..a510e31d07d78 100644
--- a/sdk/core/System.ClientModel/api/System.ClientModel.net6.0.cs
+++ b/sdk/core/System.ClientModel/api/System.ClientModel.net6.0.cs
@@ -4,7 +4,6 @@ public partial class ApiKeyCredential
{
public ApiKeyCredential(string key) { }
public void Deconstruct(out string key) { throw null; }
- public static implicit operator System.ClientModel.ApiKeyCredential (string key) { throw null; }
public void Update(string key) { }
}
public abstract partial class AsyncCollectionResult : System.ClientModel.ClientResult, System.Collections.Generic.IAsyncEnumerable
diff --git a/sdk/core/System.ClientModel/api/System.ClientModel.netstandard2.0.cs b/sdk/core/System.ClientModel/api/System.ClientModel.netstandard2.0.cs
index 2a716c72f50d2..ad3a7a378fc0d 100644
--- a/sdk/core/System.ClientModel/api/System.ClientModel.netstandard2.0.cs
+++ b/sdk/core/System.ClientModel/api/System.ClientModel.netstandard2.0.cs
@@ -4,7 +4,6 @@ public partial class ApiKeyCredential
{
public ApiKeyCredential(string key) { }
public void Deconstruct(out string key) { throw null; }
- public static implicit operator System.ClientModel.ApiKeyCredential (string key) { throw null; }
public void Update(string key) { }
}
public abstract partial class AsyncCollectionResult : System.ClientModel.ClientResult, System.Collections.Generic.IAsyncEnumerable
diff --git a/sdk/core/System.ClientModel/src/Convenience/ApiKeyCredential.cs b/sdk/core/System.ClientModel/src/Convenience/ApiKeyCredential.cs
index 25968d7b4550b..5549597debbb8 100644
--- a/sdk/core/System.ClientModel/src/Convenience/ApiKeyCredential.cs
+++ b/sdk/core/System.ClientModel/src/Convenience/ApiKeyCredential.cs
@@ -65,7 +65,4 @@ public void Update(string key)
Volatile.Write(ref _key, key);
}
-
- /// Converts a string to an .
- public static implicit operator ApiKeyCredential(string key) => new(key);
}
diff --git a/sdk/core/System.ClientModel/tests/Pipeline/ApiKeyAuthenticationPolicyTests.cs b/sdk/core/System.ClientModel/tests/Pipeline/ApiKeyAuthenticationPolicyTests.cs
index e5638343fbfb2..874e6ba0c7b6a 100644
--- a/sdk/core/System.ClientModel/tests/Pipeline/ApiKeyAuthenticationPolicyTests.cs
+++ b/sdk/core/System.ClientModel/tests/Pipeline/ApiKeyAuthenticationPolicyTests.cs
@@ -16,19 +16,6 @@ public ApiKeyAuthenticationPolicyTests(bool isAsync) : base(isAsync)
{
}
- [Test]
- public void CanImplicitlyCastApiKeyCredential()
- {
- string keyValue = "test_key";
- ApiKeyCredential credential1 = new(keyValue);
- ApiKeyCredential credential2 = keyValue;
-
- credential1.Deconstruct(out string deconstructed1);
- credential2.Deconstruct(out string deconstructed2);
-
- Assert.AreEqual(deconstructed1, deconstructed2);
- }
-
[Test]
public async Task HeaderPolicySetsKey()
{
From 868afcb182e8ace7213b38b7bcebc7a8f413b067 Mon Sep 17 00:00:00 2001
From: Timothy Mothra
Date: Tue, 20 Aug 2024 12:51:06 -0700
Subject: [PATCH 05/71] [AzureMonitorLiveMetrics] new project for service
reference (#45550)
* new project for service reference
* Rename Readme.md to README.md
---
.github/CODEOWNERS | 3 +
.../README.md | 8 +
...e.Monitor.OpenTelemetry.LiveMetrics.csproj | 16 +
.../src/Generated/Internal/Argument.cs | 129 ++++++
.../Internal/ChangeTrackingDictionary.cs | 167 ++++++++
.../Generated/Internal/ChangeTrackingList.cs | 153 +++++++
.../Internal/ModelSerializationExtensions.cs | 395 ++++++++++++++++++
.../MultipartFormDataRequestContent.cs | 203 +++++++++
.../src/Generated/Internal/Optional.cs | 51 +++
.../Internal/RequestContentHelper.cs | 136 ++++++
.../Internal/Utf8JsonRequestContent.cs | 55 +++
...estAPIsForClientSDKsIsSubscribedHeaders.cs | 28 ++
...ricsRestAPIsForClientSDKsPublishHeaders.cs | 24 ++
...eMetricsRestAPIsForClientSDKsRestClient.cs | 278 ++++++++++++
.../src/Generated/Models/AggregationType.cs | 57 +++
...lectionConfigurationError.Serialization.cs | 42 ++
.../Models/CollectionConfigurationError.cs | 57 +++
.../CollectionConfigurationErrorType.cs | 84 ++++
...llectionConfigurationInfo.Serialization.cs | 73 ++++
.../Models/CollectionConfigurationInfo.cs | 55 +++
.../Models/DerivedMetricInfo.Serialization.cs | 82 ++++
.../src/Generated/Models/DerivedMetricInfo.cs | 70 ++++
...ilterConjunctionGroupInfo.Serialization.cs | 46 ++
.../DocumentFilterConjunctionGroupInfo.cs | 32 ++
.../Models/DocumentIngress.Serialization.cs | 51 +++
.../src/Generated/Models/DocumentIngress.cs | 44 ++
.../DocumentStreamInfo.Serialization.cs | 52 +++
.../Generated/Models/DocumentStreamInfo.cs | 44 ++
.../src/Generated/Models/DocumentType.cs | 63 +++
.../Generated/Models/Event.Serialization.cs | 56 +++
.../src/Generated/Models/Event.cs | 35 ++
.../Models/Exception.Serialization.cs | 61 +++
.../src/Generated/Models/Exception.cs | 39 ++
...ilterConjunctionGroupInfo.Serialization.cs | 46 ++
.../Models/FilterConjunctionGroupInfo.cs | 37 ++
.../Models/FilterInfo.Serialization.cs | 52 +++
.../src/Generated/Models/FilterInfo.cs | 37 ++
.../KeyValuePairString.Serialization.cs | 33 ++
.../Generated/Models/KeyValuePairString.cs | 33 ++
.../Models/MetricPoint.Serialization.cs | 35 ++
.../src/Generated/Models/MetricPoint.cs | 36 ++
.../MonitoringDataPoint.Serialization.cs | 95 +++++
.../Generated/Models/MonitoringDataPoint.cs | 118 ++++++
.../src/Generated/Models/PredicateType.cs | 69 +++
.../Models/ProcessCpuData.Serialization.cs | 33 ++
.../src/Generated/Models/ProcessCpuData.cs | 32 ++
.../QuotaConfigurationInfo.Serialization.cs | 56 +++
.../Models/QuotaConfigurationInfo.cs | 40 ++
.../Models/RemoteDependency.Serialization.cs | 71 ++++
.../src/Generated/Models/RemoteDependency.cs | 47 +++
.../Generated/Models/Request.Serialization.cs | 71 ++++
.../src/Generated/Models/Request.cs | 48 +++
.../Models/ServiceError.Serialization.cs | 64 +++
.../src/Generated/Models/ServiceError.cs | 48 +++
.../src/Generated/Models/TelemetryType.cs | 66 +++
.../Generated/Models/Trace.Serialization.cs | 56 +++
.../src/Generated/Models/Trace.cs | 35 ++
.../src/autorest.md | 17 +
sdk/monitor/Azure.Monitor.OpenTelemetry.sln | 8 +-
59 files changed, 3971 insertions(+), 1 deletion(-)
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/README.md
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Azure.Monitor.OpenTelemetry.LiveMetrics.csproj
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/Argument.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/ChangeTrackingDictionary.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/ChangeTrackingList.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/ModelSerializationExtensions.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/MultipartFormDataRequestContent.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/Optional.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/RequestContentHelper.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/Utf8JsonRequestContent.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/LiveMetricsRestAPIsForClientSDKsIsSubscribedHeaders.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/LiveMetricsRestAPIsForClientSDKsPublishHeaders.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/LiveMetricsRestAPIsForClientSDKsRestClient.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/AggregationType.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationError.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationError.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationErrorType.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationInfo.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationInfo.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DerivedMetricInfo.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DerivedMetricInfo.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentFilterConjunctionGroupInfo.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentFilterConjunctionGroupInfo.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentIngress.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentIngress.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentStreamInfo.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentStreamInfo.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentType.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Event.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Event.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Exception.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Exception.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterConjunctionGroupInfo.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterConjunctionGroupInfo.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterInfo.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterInfo.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/KeyValuePairString.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/KeyValuePairString.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MetricPoint.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MetricPoint.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MonitoringDataPoint.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MonitoringDataPoint.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/PredicateType.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ProcessCpuData.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ProcessCpuData.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/QuotaConfigurationInfo.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/QuotaConfigurationInfo.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/RemoteDependency.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/RemoteDependency.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Request.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Request.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ServiceError.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ServiceError.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/TelemetryType.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Trace.Serialization.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Trace.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/autorest.md
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 7bb4a5be1858d..d446704467e1f 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -662,6 +662,9 @@
# ServiceLabel: %Monitor - Exporter
# ServiceOwners: @cijothomas @reyang @rajkumar-rangaraj @TimothyMothra @vishweshbankwar
+# PRLabel: %Monitor - LiveMetrics
+/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/ @cijothomas @reyang @rajkumar-rangaraj @TimothyMothra @vishweshbankwar @xiang17
+
# ServiceLabel: %Monitor - LiveMetrics
# ServiceOwners: @cijothomas @reyang @rajkumar-rangaraj @TimothyMothra @vishweshbankwar @xiang17
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/README.md b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/README.md
new file mode 100644
index 0000000000000..d9d54bb38a7f3
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/README.md
@@ -0,0 +1,8 @@
+# Azure Monitor OpenTelemetry LiveMetrics code sharing library
+
+This library is intended to serve as a common location for non-public code for the [Live Metrics](https://learn.microsoft.com/azure/azure-monitor/app/live-stream) REST API.
+The [Azure Monitor OpenTelemetry Exporter](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter) includes these artifacts by shared links to enable them to be loosely hosted within those projects rather than consumed by direct project or package reference.
+
+## Contributing
+
+See [CONTRIBUTING.md](https://github.com/Azure/azure-sdk-for-net/blob/main/CONTRIBUTING.md) for details on contribution process.
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Azure.Monitor.OpenTelemetry.LiveMetrics.csproj b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Azure.Monitor.OpenTelemetry.LiveMetrics.csproj
new file mode 100644
index 0000000000000..c0e7b47e567fe
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Azure.Monitor.OpenTelemetry.LiveMetrics.csproj
@@ -0,0 +1,16 @@
+
+
+
+ Azure.Monitor.OpenTelemetry.Exporter shared code library
+ 1.0.0
+ $(RequiredTargetFrameworks)
+ false
+ true
+
+
+
+
+
+
+
+
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/Argument.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/Argument.cs
new file mode 100644
index 0000000000000..05b2583ac62aa
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/Argument.cs
@@ -0,0 +1,129 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics
+{
+ internal static class Argument
+ {
+ public static void AssertNotNull(T value, string name)
+ {
+ if (value is null)
+ {
+ throw new ArgumentNullException(name);
+ }
+ }
+
+ public static void AssertNotNull(T? value, string name)
+ where T : struct
+ {
+ if (!value.HasValue)
+ {
+ throw new ArgumentNullException(name);
+ }
+ }
+
+ public static void AssertNotNullOrEmpty(IEnumerable value, string name)
+ {
+ if (value is null)
+ {
+ throw new ArgumentNullException(name);
+ }
+ if (value is ICollection collectionOfT && collectionOfT.Count == 0)
+ {
+ throw new ArgumentException("Value cannot be an empty collection.", name);
+ }
+ if (value is ICollection collection && collection.Count == 0)
+ {
+ throw new ArgumentException("Value cannot be an empty collection.", name);
+ }
+ using IEnumerator e = value.GetEnumerator();
+ if (!e.MoveNext())
+ {
+ throw new ArgumentException("Value cannot be an empty collection.", name);
+ }
+ }
+
+ public static void AssertNotNullOrEmpty(string value, string name)
+ {
+ if (value is null)
+ {
+ throw new ArgumentNullException(name);
+ }
+ if (value.Length == 0)
+ {
+ throw new ArgumentException("Value cannot be an empty string.", name);
+ }
+ }
+
+ public static void AssertNotNullOrWhiteSpace(string value, string name)
+ {
+ if (value is null)
+ {
+ throw new ArgumentNullException(name);
+ }
+ if (string.IsNullOrWhiteSpace(value))
+ {
+ throw new ArgumentException("Value cannot be empty or contain only white-space characters.", name);
+ }
+ }
+
+ public static void AssertNotDefault(ref T value, string name)
+ where T : struct, IEquatable
+ {
+ if (value.Equals(default))
+ {
+ throw new ArgumentException("Value cannot be empty.", name);
+ }
+ }
+
+ public static void AssertInRange(T value, T minimum, T maximum, string name)
+ where T : notnull, IComparable
+ {
+ if (minimum.CompareTo(value) > 0)
+ {
+ throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed.");
+ }
+ if (maximum.CompareTo(value) < 0)
+ {
+ throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed.");
+ }
+ }
+
+ public static void AssertEnumDefined(Type enumType, object value, string name)
+ {
+ if (!Enum.IsDefined(enumType, value))
+ {
+ throw new ArgumentException($"Value not defined for {enumType.FullName}.", name);
+ }
+ }
+
+ public static T CheckNotNull(T value, string name)
+ where T : class
+ {
+ AssertNotNull(value, name);
+ return value;
+ }
+
+ public static string CheckNotNullOrEmpty(string value, string name)
+ {
+ AssertNotNullOrEmpty(value, name);
+ return value;
+ }
+
+ public static void AssertNull(T value, string name, string message = null)
+ {
+ if (value != null)
+ {
+ throw new ArgumentException(message ?? "Value must be null.", name);
+ }
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/ChangeTrackingDictionary.cs
new file mode 100644
index 0000000000000..2ccd52fb2fc7d
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/ChangeTrackingDictionary.cs
@@ -0,0 +1,167 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics
+{
+ internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull
+ {
+ private IDictionary _innerDictionary;
+
+ public ChangeTrackingDictionary()
+ {
+ }
+
+ public ChangeTrackingDictionary(IDictionary dictionary)
+ {
+ if (dictionary == null)
+ {
+ return;
+ }
+ _innerDictionary = new Dictionary(dictionary);
+ }
+
+ public ChangeTrackingDictionary(IReadOnlyDictionary dictionary)
+ {
+ if (dictionary == null)
+ {
+ return;
+ }
+ _innerDictionary = new Dictionary();
+ foreach (var pair in dictionary)
+ {
+ _innerDictionary.Add(pair);
+ }
+ }
+
+ public bool IsUndefined => _innerDictionary == null;
+
+ public int Count => IsUndefined ? 0 : EnsureDictionary().Count;
+
+ public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly;
+
+ public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys;
+
+ public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values;
+
+ public TValue this[TKey key]
+ {
+ get
+ {
+ if (IsUndefined)
+ {
+ throw new KeyNotFoundException(nameof(key));
+ }
+ return EnsureDictionary()[key];
+ }
+ set
+ {
+ EnsureDictionary()[key] = value;
+ }
+ }
+
+ IEnumerable IReadOnlyDictionary.Keys => Keys;
+
+ IEnumerable IReadOnlyDictionary.Values => Values;
+
+ public IEnumerator> GetEnumerator()
+ {
+ if (IsUndefined)
+ {
+ IEnumerator> enumerateEmpty()
+ {
+ yield break;
+ }
+ return enumerateEmpty();
+ }
+ return EnsureDictionary().GetEnumerator();
+ }
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+
+ public void Add(KeyValuePair item)
+ {
+ EnsureDictionary().Add(item);
+ }
+
+ public void Clear()
+ {
+ EnsureDictionary().Clear();
+ }
+
+ public bool Contains(KeyValuePair item)
+ {
+ if (IsUndefined)
+ {
+ return false;
+ }
+ return EnsureDictionary().Contains(item);
+ }
+
+ public void CopyTo(KeyValuePair[] array, int index)
+ {
+ if (IsUndefined)
+ {
+ return;
+ }
+ EnsureDictionary().CopyTo(array, index);
+ }
+
+ public bool Remove(KeyValuePair item)
+ {
+ if (IsUndefined)
+ {
+ return false;
+ }
+ return EnsureDictionary().Remove(item);
+ }
+
+ public void Add(TKey key, TValue value)
+ {
+ EnsureDictionary().Add(key, value);
+ }
+
+ public bool ContainsKey(TKey key)
+ {
+ if (IsUndefined)
+ {
+ return false;
+ }
+ return EnsureDictionary().ContainsKey(key);
+ }
+
+ public bool Remove(TKey key)
+ {
+ if (IsUndefined)
+ {
+ return false;
+ }
+ return EnsureDictionary().Remove(key);
+ }
+
+ public bool TryGetValue(TKey key, out TValue value)
+ {
+ if (IsUndefined)
+ {
+ value = default;
+ return false;
+ }
+ return EnsureDictionary().TryGetValue(key, out value);
+ }
+
+ public IDictionary EnsureDictionary()
+ {
+ return _innerDictionary ??= new Dictionary();
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/ChangeTrackingList.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/ChangeTrackingList.cs
new file mode 100644
index 0000000000000..d3d310bb63c1b
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/ChangeTrackingList.cs
@@ -0,0 +1,153 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics
+{
+ internal class ChangeTrackingList : IList, IReadOnlyList
+ {
+ private IList _innerList;
+
+ public ChangeTrackingList()
+ {
+ }
+
+ public ChangeTrackingList(IList innerList)
+ {
+ if (innerList != null)
+ {
+ _innerList = innerList;
+ }
+ }
+
+ public ChangeTrackingList(IReadOnlyList innerList)
+ {
+ if (innerList != null)
+ {
+ _innerList = innerList.ToList();
+ }
+ }
+
+ public bool IsUndefined => _innerList == null;
+
+ public int Count => IsUndefined ? 0 : EnsureList().Count;
+
+ public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly;
+
+ public T this[int index]
+ {
+ get
+ {
+ if (IsUndefined)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ return EnsureList()[index];
+ }
+ set
+ {
+ if (IsUndefined)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ EnsureList()[index] = value;
+ }
+ }
+
+ public void Reset()
+ {
+ _innerList = null;
+ }
+
+ public IEnumerator GetEnumerator()
+ {
+ if (IsUndefined)
+ {
+ IEnumerator enumerateEmpty()
+ {
+ yield break;
+ }
+ return enumerateEmpty();
+ }
+ return EnsureList().GetEnumerator();
+ }
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+
+ public void Add(T item)
+ {
+ EnsureList().Add(item);
+ }
+
+ public void Clear()
+ {
+ EnsureList().Clear();
+ }
+
+ public bool Contains(T item)
+ {
+ if (IsUndefined)
+ {
+ return false;
+ }
+ return EnsureList().Contains(item);
+ }
+
+ public void CopyTo(T[] array, int arrayIndex)
+ {
+ if (IsUndefined)
+ {
+ return;
+ }
+ EnsureList().CopyTo(array, arrayIndex);
+ }
+
+ public bool Remove(T item)
+ {
+ if (IsUndefined)
+ {
+ return false;
+ }
+ return EnsureList().Remove(item);
+ }
+
+ public int IndexOf(T item)
+ {
+ if (IsUndefined)
+ {
+ return -1;
+ }
+ return EnsureList().IndexOf(item);
+ }
+
+ public void Insert(int index, T item)
+ {
+ EnsureList().Insert(index, item);
+ }
+
+ public void RemoveAt(int index)
+ {
+ if (IsUndefined)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ EnsureList().RemoveAt(index);
+ }
+
+ public IList EnsureList()
+ {
+ return _innerList ??= new List();
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/ModelSerializationExtensions.cs
new file mode 100644
index 0000000000000..a8139122f57d0
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/ModelSerializationExtensions.cs
@@ -0,0 +1,395 @@
+// 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.Monitor.OpenTelemetry.LiveMetrics
+{
+ internal static class ModelSerializationExtensions
+ {
+ internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W");
+
+ public static object GetObject(this JsonElement element)
+ {
+ switch (element.ValueKind)
+ {
+ case JsonValueKind.String:
+ return element.GetString();
+ case JsonValueKind.Number:
+ if (element.TryGetInt32(out int intValue))
+ {
+ return intValue;
+ }
+ if (element.TryGetInt64(out long longValue))
+ {
+ return longValue;
+ }
+ return element.GetDouble();
+ case JsonValueKind.True:
+ return true;
+ case JsonValueKind.False:
+ return false;
+ case JsonValueKind.Undefined:
+ case JsonValueKind.Null:
+ return null;
+ case JsonValueKind.Object:
+ var dictionary = new Dictionary();
+ foreach (var jsonProperty in element.EnumerateObject())
+ {
+ dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject());
+ }
+ return dictionary;
+ case JsonValueKind.Array:
+ var list = new List();
+ foreach (var item in element.EnumerateArray())
+ {
+ list.Add(item.GetObject());
+ }
+ return list.ToArray();
+ default:
+ throw new NotSupportedException($"Not supported value kind {element.ValueKind}");
+ }
+ }
+
+ public static byte[] GetBytesFromBase64(this JsonElement element, string format)
+ {
+ if (element.ValueKind == JsonValueKind.Null)
+ {
+ return null;
+ }
+
+ return format switch
+ {
+ "U" => TypeFormatters.FromBase64UrlString(element.GetRequiredString()),
+ "D" => element.GetBytesFromBase64(),
+ _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format))
+ };
+ }
+
+ public static DateTimeOffset GetDateTimeOffset(this JsonElement element, string format) => format switch
+ {
+ "U" when element.ValueKind == JsonValueKind.Number => DateTimeOffset.FromUnixTimeSeconds(element.GetInt64()),
+ _ => TypeFormatters.ParseDateTimeOffset(element.GetString(), format)
+ };
+
+ public static TimeSpan GetTimeSpan(this JsonElement element, string format) => TypeFormatters.ParseTimeSpan(element.GetString(), format);
+
+ public static char GetChar(this JsonElement element)
+ {
+ if (element.ValueKind == JsonValueKind.String)
+ {
+ var text = element.GetString();
+ if (text == null || text.Length != 1)
+ {
+ throw new NotSupportedException($"Cannot convert \"{text}\" to a char");
+ }
+ return text[0];
+ }
+ else
+ {
+ throw new NotSupportedException($"Cannot convert {element.ValueKind} to a char");
+ }
+ }
+
+ [Conditional("DEBUG")]
+ public static void ThrowNonNullablePropertyIsNull(this JsonProperty property)
+ {
+ throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build");
+ }
+
+ public static string GetRequiredString(this JsonElement element)
+ {
+ var value = element.GetString();
+ if (value == null)
+ {
+ throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'.");
+ }
+ return value;
+ }
+
+ public static void WriteStringValue(this Utf8JsonWriter writer, DateTimeOffset value, string format)
+ {
+ writer.WriteStringValue(TypeFormatters.ToString(value, format));
+ }
+
+ public static void WriteStringValue(this Utf8JsonWriter writer, DateTime value, string format)
+ {
+ writer.WriteStringValue(TypeFormatters.ToString(value, format));
+ }
+
+ public static void WriteStringValue(this Utf8JsonWriter writer, TimeSpan value, string format)
+ {
+ writer.WriteStringValue(TypeFormatters.ToString(value, format));
+ }
+
+ public static void WriteStringValue(this Utf8JsonWriter writer, char value)
+ {
+ writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture));
+ }
+
+ public static void WriteBase64StringValue(this Utf8JsonWriter writer, byte[] value, string format)
+ {
+ if (value == null)
+ {
+ writer.WriteNullValue();
+ return;
+ }
+ switch (format)
+ {
+ case "U":
+ writer.WriteStringValue(TypeFormatters.ToBase64UrlString(value));
+ break;
+ case "D":
+ writer.WriteBase64StringValue(value);
+ break;
+ default:
+ throw new ArgumentException($"Format is not supported: '{format}'", nameof(format));
+ }
+ }
+
+ public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset value, string format)
+ {
+ if (format != "U")
+ {
+ throw new ArgumentOutOfRangeException(nameof(format), "Only 'U' format is supported when writing a DateTimeOffset as a Number.");
+ }
+ writer.WriteNumberValue(value.ToUnixTimeSeconds());
+ }
+
+ public static void WriteObjectValue(this Utf8JsonWriter writer, T value)
+ {
+ switch (value)
+ {
+ case null:
+ writer.WriteNullValue();
+ 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);
+ }
+ writer.WriteEndObject();
+ break;
+ case IEnumerable objectEnumerable:
+ writer.WriteStartArray();
+ foreach (var item in objectEnumerable)
+ {
+ writer.WriteObjectValue(item);
+ }
+ 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)
+ {
+ writer.WriteObjectValue(value);
+ }
+
+ 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/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/MultipartFormDataRequestContent.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/MultipartFormDataRequestContent.cs
new file mode 100644
index 0000000000000..6246a4304cb25
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/MultipartFormDataRequestContent.cs
@@ -0,0 +1,203 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+using System.Globalization;
+using System.IO;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Threading;
+using System.Threading.Tasks;
+using Azure.Core;
+using Azure.Core.Pipeline;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics
+{
+ internal class MultipartFormDataRequestContent : RequestContent
+ {
+ private readonly System.Net.Http.MultipartFormDataContent _multipartContent;
+ private static readonly Random _random = new Random();
+ private static readonly char[] _boundaryValues = "0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".ToCharArray();
+
+ public MultipartFormDataRequestContent()
+ {
+ _multipartContent = new System.Net.Http.MultipartFormDataContent(CreateBoundary());
+ }
+
+ public string ContentType
+ {
+ get
+ {
+ return _multipartContent.Headers.ContentType.ToString();
+ }
+ }
+
+ internal HttpContent HttpContent => _multipartContent;
+
+ private static string CreateBoundary()
+ {
+ Span chars = new char[70];
+ byte[] random = new byte[70];
+ _random.NextBytes(random);
+ int mask = 255 >> 2;
+ for (int i = 0; i < 70; i++)
+ {
+ chars[i] = _boundaryValues[random[i] & mask];
+ }
+ return chars.ToString();
+ }
+
+ public void Add(string content, string name, string filename = null, string contentType = null)
+ {
+ Argument.AssertNotNull(content, nameof(content));
+ Argument.AssertNotNullOrEmpty(name, nameof(name));
+
+ Add(new StringContent(content), name, filename, contentType);
+ }
+
+ public void Add(int content, string name, string filename = null, string contentType = null)
+ {
+ Argument.AssertNotNull(content, nameof(content));
+ Argument.AssertNotNullOrEmpty(name, nameof(name));
+
+ string value = content.ToString("G", CultureInfo.InvariantCulture);
+ Add(new StringContent(value), name, filename, contentType);
+ }
+
+ public void Add(long content, string name, string filename = null, string contentType = null)
+ {
+ Argument.AssertNotNull(content, nameof(content));
+ Argument.AssertNotNullOrEmpty(name, nameof(name));
+
+ string value = content.ToString("G", CultureInfo.InvariantCulture);
+ Add(new StringContent(value), name, filename, contentType);
+ }
+
+ public void Add(float content, string name, string filename = null, string contentType = null)
+ {
+ Argument.AssertNotNull(content, nameof(content));
+ Argument.AssertNotNullOrEmpty(name, nameof(name));
+
+ string value = content.ToString("G", CultureInfo.InvariantCulture);
+ Add(new StringContent(value), name, filename, contentType);
+ }
+
+ public void Add(double content, string name, string filename = null, string contentType = null)
+ {
+ Argument.AssertNotNull(content, nameof(content));
+ Argument.AssertNotNullOrEmpty(name, nameof(name));
+
+ string value = content.ToString("G", CultureInfo.InvariantCulture);
+ Add(new StringContent(value), name, filename, contentType);
+ }
+
+ public void Add(decimal content, string name, string filename = null, string contentType = null)
+ {
+ Argument.AssertNotNull(content, nameof(content));
+ Argument.AssertNotNullOrEmpty(name, nameof(name));
+
+ string value = content.ToString("G", CultureInfo.InvariantCulture);
+ Add(new StringContent(value), name, filename, contentType);
+ }
+
+ public void Add(bool content, string name, string filename = null, string contentType = null)
+ {
+ Argument.AssertNotNull(content, nameof(content));
+ Argument.AssertNotNullOrEmpty(name, nameof(name));
+
+ string value = content ? "true" : "false";
+ Add(new StringContent(value), name, filename, contentType);
+ }
+
+ public void Add(Stream content, string name, string filename = null, string contentType = null)
+ {
+ Argument.AssertNotNull(content, nameof(content));
+ Argument.AssertNotNullOrEmpty(name, nameof(name));
+
+ Add(new StreamContent(content), name, filename, contentType);
+ }
+
+ public void Add(byte[] content, string name, string filename = null, string contentType = null)
+ {
+ Argument.AssertNotNull(content, nameof(content));
+ Argument.AssertNotNullOrEmpty(name, nameof(name));
+
+ Add(new ByteArrayContent(content), name, filename, contentType);
+ }
+
+ public void Add(BinaryData content, string name, string filename = null, string contentType = null)
+ {
+ Argument.AssertNotNull(content, nameof(content));
+ Argument.AssertNotNullOrEmpty(name, nameof(name));
+
+ Add(new ByteArrayContent(content.ToArray()), name, filename, contentType);
+ }
+
+ private void Add(HttpContent content, string name, string filename, string contentType)
+ {
+ if (filename != null)
+ {
+ Argument.AssertNotNullOrEmpty(filename, nameof(filename));
+ AddFilenameHeader(content, name, filename);
+ }
+ if (contentType != null)
+ {
+ Argument.AssertNotNullOrEmpty(contentType, nameof(contentType));
+ AddContentTypeHeader(content, contentType);
+ }
+ _multipartContent.Add(content, name);
+ }
+
+ public static void AddFilenameHeader(HttpContent content, string name, string filename)
+ {
+ ContentDispositionHeaderValue header = new ContentDispositionHeaderValue("form-data") { Name = name, FileName = filename };
+ content.Headers.ContentDisposition = header;
+ }
+
+ public static void AddContentTypeHeader(HttpContent content, string contentType)
+ {
+ MediaTypeHeaderValue header = new MediaTypeHeaderValue(contentType);
+ content.Headers.ContentType = header;
+ }
+
+ public override bool TryComputeLength(out long length)
+ {
+ if (_multipartContent.Headers.ContentLength is long contentLength)
+ {
+ length = contentLength;
+ return true;
+ }
+ length = 0;
+ return false;
+ }
+
+ public override void WriteTo(Stream stream, CancellationToken cancellationToken = default)
+ {
+#if NET6_0_OR_GREATER
+ _multipartContent.CopyTo(stream, default, cancellationToken);
+#else
+#pragma warning disable AZC0107
+ _multipartContent.CopyToAsync(stream).EnsureCompleted();
+#pragma warning restore AZC0107
+#endif
+ }
+
+ public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default)
+ {
+#if NET6_0_OR_GREATER
+ await _multipartContent.CopyToAsync(stream, cancellationToken).ConfigureAwait(false);
+#else
+ await _multipartContent.CopyToAsync(stream).ConfigureAwait(false);
+#endif
+ }
+
+ public override void Dispose()
+ {
+ _multipartContent.Dispose();
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/Optional.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/Optional.cs
new file mode 100644
index 0000000000000..7a820ce70c4f1
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/Optional.cs
@@ -0,0 +1,51 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Collections.Generic;
+using System.Text.Json;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics
+{
+ internal static class Optional
+ {
+ public static bool IsCollectionDefined(IEnumerable collection)
+ {
+ return !(collection is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined);
+ }
+
+ public static bool IsCollectionDefined(IDictionary collection)
+ {
+ return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined);
+ }
+
+ public static bool IsCollectionDefined(IReadOnlyDictionary collection)
+ {
+ return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined);
+ }
+
+ public static bool IsDefined(T? value)
+ where T : struct
+ {
+ return value.HasValue;
+ }
+
+ public static bool IsDefined(object value)
+ {
+ return value != null;
+ }
+
+ public static bool IsDefined(JsonElement value)
+ {
+ return value.ValueKind != JsonValueKind.Undefined;
+ }
+
+ public static bool IsDefined(string value)
+ {
+ return value != null;
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/RequestContentHelper.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/RequestContentHelper.cs
new file mode 100644
index 0000000000000..c4ecf95c18da6
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/RequestContentHelper.cs
@@ -0,0 +1,136 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+using System.Text.Json;
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics
+{
+ internal static class RequestContentHelper
+ {
+ public static RequestContent FromEnumerable(IEnumerable enumerable)
+ where T : notnull
+ {
+ Utf8JsonRequestContent content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteStartArray();
+ foreach (var item in enumerable)
+ {
+ content.JsonWriter.WriteObjectValue(item);
+ }
+ content.JsonWriter.WriteEndArray();
+
+ return content;
+ }
+
+ public static RequestContent FromEnumerable(IEnumerable enumerable)
+ {
+ Utf8JsonRequestContent content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteStartArray();
+ foreach (var item in enumerable)
+ {
+ if (item == null)
+ {
+ content.JsonWriter.WriteNullValue();
+ }
+ else
+ {
+#if NET6_0_OR_GREATER
+ content.JsonWriter.WriteRawValue(item);
+#else
+ using (JsonDocument document = JsonDocument.Parse(item))
+ {
+ JsonSerializer.Serialize(content.JsonWriter, document.RootElement);
+ }
+#endif
+ }
+ }
+ content.JsonWriter.WriteEndArray();
+
+ return content;
+ }
+
+ public static RequestContent FromEnumerable(ReadOnlySpan span)
+ where T : notnull
+ {
+ Utf8JsonRequestContent content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteStartArray();
+ for (int i = 0; i < span.Length; i++)
+ {
+ content.JsonWriter.WriteObjectValue(span[i]);
+ }
+ content.JsonWriter.WriteEndArray();
+
+ return content;
+ }
+
+ public static RequestContent FromDictionary(IDictionary dictionary)
+ where TValue : notnull
+ {
+ Utf8JsonRequestContent content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteStartObject();
+ foreach (var item in dictionary)
+ {
+ content.JsonWriter.WritePropertyName(item.Key);
+ content.JsonWriter.WriteObjectValue(item.Value);
+ }
+ content.JsonWriter.WriteEndObject();
+
+ return content;
+ }
+
+ public static RequestContent FromDictionary(IDictionary dictionary)
+ {
+ Utf8JsonRequestContent content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteStartObject();
+ foreach (var item in dictionary)
+ {
+ content.JsonWriter.WritePropertyName(item.Key);
+ if (item.Value == null)
+ {
+ content.JsonWriter.WriteNullValue();
+ }
+ else
+ {
+#if NET6_0_OR_GREATER
+ content.JsonWriter.WriteRawValue(item.Value);
+#else
+ using (JsonDocument document = JsonDocument.Parse(item.Value))
+ {
+ JsonSerializer.Serialize(content.JsonWriter, document.RootElement);
+ }
+#endif
+ }
+ }
+ content.JsonWriter.WriteEndObject();
+
+ return content;
+ }
+
+ public static RequestContent FromObject(object value)
+ {
+ Utf8JsonRequestContent content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteObjectValue(value);
+ return content;
+ }
+
+ public static RequestContent FromObject(BinaryData value)
+ {
+ Utf8JsonRequestContent content = new Utf8JsonRequestContent();
+#if NET6_0_OR_GREATER
+ content.JsonWriter.WriteRawValue(value);
+#else
+ using (JsonDocument document = JsonDocument.Parse(value))
+ {
+ JsonSerializer.Serialize(content.JsonWriter, document.RootElement);
+ }
+#endif
+ return content;
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/Utf8JsonRequestContent.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/Utf8JsonRequestContent.cs
new file mode 100644
index 0000000000000..34342d231645e
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Internal/Utf8JsonRequestContent.cs
@@ -0,0 +1,55 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.IO;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics
+{
+ internal class Utf8JsonRequestContent : RequestContent
+ {
+ private readonly MemoryStream _stream;
+ private readonly RequestContent _content;
+
+ public Utf8JsonRequestContent()
+ {
+ _stream = new MemoryStream();
+ _content = Create(_stream);
+ JsonWriter = new Utf8JsonWriter(_stream);
+ }
+
+ public Utf8JsonWriter JsonWriter { get; }
+
+ public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default)
+ {
+ await JsonWriter.FlushAsync().ConfigureAwait(false);
+ await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false);
+ }
+
+ public override void WriteTo(Stream stream, CancellationToken cancellationToken = default)
+ {
+ JsonWriter.Flush();
+ _content.WriteTo(stream, cancellationToken);
+ }
+
+ public override bool TryComputeLength(out long length)
+ {
+ length = JsonWriter.BytesCommitted + JsonWriter.BytesPending;
+ return true;
+ }
+
+ public override void Dispose()
+ {
+ JsonWriter.Dispose();
+ _content.Dispose();
+ _stream.Dispose();
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/LiveMetricsRestAPIsForClientSDKsIsSubscribedHeaders.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/LiveMetricsRestAPIsForClientSDKsIsSubscribedHeaders.cs
new file mode 100644
index 0000000000000..6060611374733
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/LiveMetricsRestAPIsForClientSDKsIsSubscribedHeaders.cs
@@ -0,0 +1,28 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics
+{
+ internal partial class LiveMetricsRestAPIsForClientSDKsIsSubscribedHeaders
+ {
+ private readonly Response _response;
+ public LiveMetricsRestAPIsForClientSDKsIsSubscribedHeaders(Response response)
+ {
+ _response = response;
+ }
+ /// An encoded string that indicates whether the collection configuration is changed.
+ public string XMsQpsConfigurationEtag => _response.Headers.TryGetValue("x-ms-qps-configuration-etag", out string value) ? value : null;
+ /// Contains a URI of the service endpoint that the client must permanently use for the particular resource. This header exists only when the client is talking to Live Metrics global endpoint.
+ public string XMsQpsServiceEndpointRedirectV2 => _response.Headers.TryGetValue("x-ms-qps-service-endpoint-redirect-v2", out string value) ? value : null;
+ /// Recommended time (in milliseconds) before the client should ping the service again. This header exists only when the instrumentation key is not subscribed to.
+ public string XMsQpsServicePollingIntervalHint => _response.Headers.TryGetValue("x-ms-qps-service-polling-interval-hint", out string value) ? value : null;
+ /// A boolean flag indicating whether there are active user sessions 'watching' the instrumentation key. If true, the client must start collecting data and posting it to Live Metrics. Otherwise, the client must keep pinging.
+ public string XMsQpsSubscribed => _response.Headers.TryGetValue("x-ms-qps-subscribed", out string value) ? value : null;
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/LiveMetricsRestAPIsForClientSDKsPublishHeaders.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/LiveMetricsRestAPIsForClientSDKsPublishHeaders.cs
new file mode 100644
index 0000000000000..70151eb29ffcf
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/LiveMetricsRestAPIsForClientSDKsPublishHeaders.cs
@@ -0,0 +1,24 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics
+{
+ internal partial class LiveMetricsRestAPIsForClientSDKsPublishHeaders
+ {
+ private readonly Response _response;
+ public LiveMetricsRestAPIsForClientSDKsPublishHeaders(Response response)
+ {
+ _response = response;
+ }
+ /// An encoded string that indicates whether the collection configuration is changed.
+ public string XMsQpsConfigurationEtag => _response.Headers.TryGetValue("x-ms-qps-configuration-etag", out string value) ? value : null;
+ /// Tells the client whether the input instrumentation key is subscribed to.
+ public string XMsQpsSubscribed => _response.Headers.TryGetValue("x-ms-qps-subscribed", out string value) ? value : null;
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/LiveMetricsRestAPIsForClientSDKsRestClient.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/LiveMetricsRestAPIsForClientSDKsRestClient.cs
new file mode 100644
index 0000000000000..749796cc365f0
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/LiveMetricsRestAPIsForClientSDKsRestClient.cs
@@ -0,0 +1,278 @@
+// 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;
+using System.Threading.Tasks;
+using Azure.Core;
+using Azure.Core.Pipeline;
+using Azure.Monitor.OpenTelemetry.LiveMetrics.Models;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics
+{
+ internal partial class LiveMetricsRestAPIsForClientSDKsRestClient
+ {
+ private readonly HttpPipeline _pipeline;
+ private readonly string _apiVersion;
+
+ /// The ClientDiagnostics is used to provide tracing support for the client library.
+ internal ClientDiagnostics ClientDiagnostics { get; }
+
+ /// Initializes a new instance of LiveMetricsRestAPIsForClientSDKsRestClient.
+ /// The handler for diagnostic messaging in the client.
+ /// The HTTP pipeline for sending and receiving REST requests and responses.
+ /// Api Version.
+ /// , or is null.
+ public LiveMetricsRestAPIsForClientSDKsRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string apiVersion = "2024-04-01-preview")
+ {
+ ClientDiagnostics = clientDiagnostics ?? throw new ArgumentNullException(nameof(clientDiagnostics));
+ _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline));
+ _apiVersion = apiVersion ?? throw new ArgumentNullException(nameof(apiVersion));
+ }
+
+ internal HttpMessage CreateIsSubscribedRequest(string endpoint, string ikey, long? transmissionTime, string machineName, string instanceName, string streamId, string roleName, string invariantVersion, string configurationEtag, MonitoringDataPoint monitoringDataPoint)
+ {
+ var message = _pipeline.CreateMessage();
+ var request = message.Request;
+ request.Method = RequestMethod.Post;
+ var uri = new RawRequestUriBuilder();
+ uri.AppendRaw(endpoint, true);
+ uri.AppendPath("/QuickPulseService.svc/ping", false);
+ uri.AppendQuery("api-version", _apiVersion, true);
+ uri.AppendQuery("ikey", ikey, true);
+ request.Uri = uri;
+ if (transmissionTime != null)
+ {
+ request.Headers.Add("x-ms-qps-transmission-time", transmissionTime.Value);
+ }
+ if (machineName != null)
+ {
+ request.Headers.Add("x-ms-qps-machine-name", machineName);
+ }
+ if (instanceName != null)
+ {
+ request.Headers.Add("x-ms-qps-instance-name", instanceName);
+ }
+ if (streamId != null)
+ {
+ request.Headers.Add("x-ms-qps-stream-id", streamId);
+ }
+ if (roleName != null)
+ {
+ request.Headers.Add("x-ms-qps-role-name", roleName);
+ }
+ if (invariantVersion != null)
+ {
+ request.Headers.Add("x-ms-qps-invariant-version", invariantVersion);
+ }
+ if (configurationEtag != null)
+ {
+ request.Headers.Add("x-ms-qps-configuration-etag", configurationEtag);
+ }
+ request.Headers.Add("Accept", "application/json");
+ if (monitoringDataPoint != null)
+ {
+ request.Headers.Add("Content-Type", "application/json");
+ var content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteObjectValue(monitoringDataPoint);
+ request.Content = content;
+ }
+ return message;
+ }
+
+ /// Determine whether there is any subscription to the metrics and documents.
+ /// The endpoint of the Live Metrics service. The default value is "https://global.livediagnostics.monitor.azure.com".
+ /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it.
+ /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks.
+ /// Computer name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup.
+ /// Service instance name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup.
+ /// Identifies an Application Insights SDK as trusted agent to report metrics and documents.
+ /// Cloud role name of the service.
+ /// Version/generation of the data contract (MonitoringDataPoint) between the client and Live Metrics.
+ /// An encoded string that indicates whether the collection configuration is changed.
+ /// Data contract between Application Insights client SDK and Live Metrics. /QuickPulseService.svc/ping uses this as a backup source of machine name, instance name and invariant version.
+ /// The cancellation token to use.
+ /// or is null.
+ public async Task> IsSubscribedAsync(string endpoint, string ikey, long? transmissionTime = null, string machineName = null, string instanceName = null, string streamId = null, string roleName = null, string invariantVersion = null, string configurationEtag = null, MonitoringDataPoint monitoringDataPoint = null, CancellationToken cancellationToken = default)
+ {
+ if (endpoint == null)
+ {
+ throw new ArgumentNullException(nameof(endpoint));
+ }
+ if (ikey == null)
+ {
+ throw new ArgumentNullException(nameof(ikey));
+ }
+
+ using var message = CreateIsSubscribedRequest(endpoint, ikey, transmissionTime, machineName, instanceName, streamId, roleName, invariantVersion, configurationEtag, monitoringDataPoint);
+ await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
+ var headers = new LiveMetricsRestAPIsForClientSDKsIsSubscribedHeaders(message.Response);
+ switch (message.Response.Status)
+ {
+ case 200:
+ {
+ CollectionConfigurationInfo value = default;
+ using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
+ value = CollectionConfigurationInfo.DeserializeCollectionConfigurationInfo(document.RootElement);
+ return ResponseWithHeaders.FromValue(value, headers, message.Response);
+ }
+ default:
+ throw new RequestFailedException(message.Response);
+ }
+ }
+
+ /// Determine whether there is any subscription to the metrics and documents.
+ /// The endpoint of the Live Metrics service. The default value is "https://global.livediagnostics.monitor.azure.com".
+ /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it.
+ /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks.
+ /// Computer name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup.
+ /// Service instance name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup.
+ /// Identifies an Application Insights SDK as trusted agent to report metrics and documents.
+ /// Cloud role name of the service.
+ /// Version/generation of the data contract (MonitoringDataPoint) between the client and Live Metrics.
+ /// An encoded string that indicates whether the collection configuration is changed.
+ /// Data contract between Application Insights client SDK and Live Metrics. /QuickPulseService.svc/ping uses this as a backup source of machine name, instance name and invariant version.
+ /// The cancellation token to use.
+ /// or is null.
+ public ResponseWithHeaders IsSubscribed(string endpoint, string ikey, long? transmissionTime = null, string machineName = null, string instanceName = null, string streamId = null, string roleName = null, string invariantVersion = null, string configurationEtag = null, MonitoringDataPoint monitoringDataPoint = null, CancellationToken cancellationToken = default)
+ {
+ if (endpoint == null)
+ {
+ throw new ArgumentNullException(nameof(endpoint));
+ }
+ if (ikey == null)
+ {
+ throw new ArgumentNullException(nameof(ikey));
+ }
+
+ using var message = CreateIsSubscribedRequest(endpoint, ikey, transmissionTime, machineName, instanceName, streamId, roleName, invariantVersion, configurationEtag, monitoringDataPoint);
+ _pipeline.Send(message, cancellationToken);
+ var headers = new LiveMetricsRestAPIsForClientSDKsIsSubscribedHeaders(message.Response);
+ switch (message.Response.Status)
+ {
+ case 200:
+ {
+ CollectionConfigurationInfo value = default;
+ using var document = JsonDocument.Parse(message.Response.ContentStream);
+ value = CollectionConfigurationInfo.DeserializeCollectionConfigurationInfo(document.RootElement);
+ return ResponseWithHeaders.FromValue(value, headers, message.Response);
+ }
+ default:
+ throw new RequestFailedException(message.Response);
+ }
+ }
+
+ internal HttpMessage CreatePublishRequest(string endpoint, string ikey, string configurationEtag, long? transmissionTime, IEnumerable monitoringDataPoints)
+ {
+ var message = _pipeline.CreateMessage();
+ var request = message.Request;
+ request.Method = RequestMethod.Post;
+ var uri = new RawRequestUriBuilder();
+ uri.AppendRaw(endpoint, true);
+ uri.AppendPath("/QuickPulseService.svc/post", false);
+ uri.AppendQuery("api-version", _apiVersion, true);
+ uri.AppendQuery("ikey", ikey, true);
+ request.Uri = uri;
+ if (configurationEtag != null)
+ {
+ request.Headers.Add("x-ms-qps-configuration-etag", configurationEtag);
+ }
+ if (transmissionTime != null)
+ {
+ request.Headers.Add("x-ms-qps-transmission-time", transmissionTime.Value);
+ }
+ request.Headers.Add("Accept", "application/json");
+ if (monitoringDataPoints != null)
+ {
+ request.Headers.Add("Content-Type", "application/json");
+ var content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteStartArray();
+ foreach (var item in monitoringDataPoints)
+ {
+ content.JsonWriter.WriteObjectValue(item);
+ }
+ content.JsonWriter.WriteEndArray();
+ request.Content = content;
+ }
+ return message;
+ }
+
+ /// Publish live metrics to the Live Metrics service when there is an active subscription to the metrics.
+ /// The endpoint of the Live Metrics service. The default value is "https://global.livediagnostics.monitor.azure.com".
+ /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it.
+ /// An encoded string that indicates whether the collection configuration is changed.
+ /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks.
+ /// Data contract between the client and Live Metrics. /QuickPulseService.svc/ping uses this as a backup source of machine name, instance name and invariant version.
+ /// The cancellation token to use.
+ /// or is null.
+ public async Task> PublishAsync(string endpoint, string ikey, string configurationEtag = null, long? transmissionTime = null, IEnumerable monitoringDataPoints = null, CancellationToken cancellationToken = default)
+ {
+ if (endpoint == null)
+ {
+ throw new ArgumentNullException(nameof(endpoint));
+ }
+ if (ikey == null)
+ {
+ throw new ArgumentNullException(nameof(ikey));
+ }
+
+ using var message = CreatePublishRequest(endpoint, ikey, configurationEtag, transmissionTime, monitoringDataPoints);
+ await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
+ var headers = new LiveMetricsRestAPIsForClientSDKsPublishHeaders(message.Response);
+ switch (message.Response.Status)
+ {
+ case 200:
+ {
+ CollectionConfigurationInfo value = default;
+ using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
+ value = CollectionConfigurationInfo.DeserializeCollectionConfigurationInfo(document.RootElement);
+ return ResponseWithHeaders.FromValue(value, headers, message.Response);
+ }
+ default:
+ throw new RequestFailedException(message.Response);
+ }
+ }
+
+ /// Publish live metrics to the Live Metrics service when there is an active subscription to the metrics.
+ /// The endpoint of the Live Metrics service. The default value is "https://global.livediagnostics.monitor.azure.com".
+ /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it.
+ /// An encoded string that indicates whether the collection configuration is changed.
+ /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks.
+ /// Data contract between the client and Live Metrics. /QuickPulseService.svc/ping uses this as a backup source of machine name, instance name and invariant version.
+ /// The cancellation token to use.
+ /// or is null.
+ public ResponseWithHeaders Publish(string endpoint, string ikey, string configurationEtag = null, long? transmissionTime = null, IEnumerable monitoringDataPoints = null, CancellationToken cancellationToken = default)
+ {
+ if (endpoint == null)
+ {
+ throw new ArgumentNullException(nameof(endpoint));
+ }
+ if (ikey == null)
+ {
+ throw new ArgumentNullException(nameof(ikey));
+ }
+
+ using var message = CreatePublishRequest(endpoint, ikey, configurationEtag, transmissionTime, monitoringDataPoints);
+ _pipeline.Send(message, cancellationToken);
+ var headers = new LiveMetricsRestAPIsForClientSDKsPublishHeaders(message.Response);
+ switch (message.Response.Status)
+ {
+ case 200:
+ {
+ CollectionConfigurationInfo value = default;
+ using var document = JsonDocument.Parse(message.Response.ContentStream);
+ value = CollectionConfigurationInfo.DeserializeCollectionConfigurationInfo(document.RootElement);
+ return ResponseWithHeaders.FromValue(value, headers, message.Response);
+ }
+ default:
+ throw new RequestFailedException(message.Response);
+ }
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/AggregationType.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/AggregationType.cs
new file mode 100644
index 0000000000000..e5cc1d40f9735
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/AggregationType.cs
@@ -0,0 +1,57 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+using System.ComponentModel;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Aggregation type.
+ internal readonly partial struct AggregationType : IEquatable
+ {
+ private readonly string _value;
+
+ /// Initializes a new instance of .
+ /// is null.
+ public AggregationType(string value)
+ {
+ _value = value ?? throw new ArgumentNullException(nameof(value));
+ }
+
+ private const string AvgValue = "Avg";
+ private const string SumValue = "Sum";
+ private const string MinValue = "Min";
+ private const string MaxValue = "Max";
+
+ /// Average.
+ public static AggregationType Avg { get; } = new AggregationType(AvgValue);
+ /// Sum.
+ public static AggregationType Sum { get; } = new AggregationType(SumValue);
+ /// Minimum.
+ public static AggregationType Min { get; } = new AggregationType(MinValue);
+ /// Maximum.
+ public static AggregationType Max { get; } = new AggregationType(MaxValue);
+ /// Determines if two values are the same.
+ public static bool operator ==(AggregationType left, AggregationType right) => left.Equals(right);
+ /// Determines if two values are not the same.
+ public static bool operator !=(AggregationType left, AggregationType right) => !left.Equals(right);
+ /// Converts a string to a .
+ public static implicit operator AggregationType(string value) => new AggregationType(value);
+
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is AggregationType other && Equals(other);
+ ///
+ public bool Equals(AggregationType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
+
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0;
+ ///
+ public override string ToString() => _value;
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationError.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationError.Serialization.cs
new file mode 100644
index 0000000000000..d7a4b9df2d176
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationError.Serialization.cs
@@ -0,0 +1,42 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class CollectionConfigurationError : IUtf8JsonSerializable
+ {
+ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
+ {
+ writer.WriteStartObject();
+ writer.WritePropertyName("CollectionConfigurationErrorType"u8);
+ writer.WriteStringValue(CollectionConfigurationErrorType.ToString());
+ writer.WritePropertyName("Message"u8);
+ writer.WriteStringValue(Message);
+ writer.WritePropertyName("FullException"u8);
+ writer.WriteStringValue(FullException);
+ writer.WritePropertyName("Data"u8);
+ writer.WriteStartArray();
+ foreach (var item in Data)
+ {
+ writer.WriteObjectValue(item);
+ }
+ writer.WriteEndArray();
+ writer.WriteEndObject();
+ }
+
+ /// Convert into a .
+ internal virtual RequestContent ToRequestContent()
+ {
+ var content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteObjectValue(this);
+ return content;
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationError.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationError.cs
new file mode 100644
index 0000000000000..1e9cc01e46559
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationError.cs
@@ -0,0 +1,57 @@
+// 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.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Represents an error while SDK parses and applies an instance of CollectionConfigurationInfo.
+ internal partial class CollectionConfigurationError
+ {
+ /// Initializes a new instance of .
+ /// Error type.
+ /// Error message.
+ /// Exception that led to the creation of the configuration error.
+ /// Custom properties to add more information to the error.
+ /// , or is null.
+ public CollectionConfigurationError(CollectionConfigurationErrorType collectionConfigurationErrorType, string message, string fullException, IEnumerable data)
+ {
+ Argument.AssertNotNull(message, nameof(message));
+ Argument.AssertNotNull(fullException, nameof(fullException));
+ Argument.AssertNotNull(data, nameof(data));
+
+ CollectionConfigurationErrorType = collectionConfigurationErrorType;
+ Message = message;
+ FullException = fullException;
+ Data = data.ToList();
+ }
+
+ /// Initializes a new instance of .
+ /// Error type.
+ /// Error message.
+ /// Exception that led to the creation of the configuration error.
+ /// Custom properties to add more information to the error.
+ internal CollectionConfigurationError(CollectionConfigurationErrorType collectionConfigurationErrorType, string message, string fullException, IList data)
+ {
+ CollectionConfigurationErrorType = collectionConfigurationErrorType;
+ Message = message;
+ FullException = fullException;
+ Data = data;
+ }
+
+ /// Error type.
+ public CollectionConfigurationErrorType CollectionConfigurationErrorType { get; }
+ /// Error message.
+ public string Message { get; }
+ /// Exception that led to the creation of the configuration error.
+ public string FullException { get; }
+ /// Custom properties to add more information to the error.
+ public IList Data { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationErrorType.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationErrorType.cs
new file mode 100644
index 0000000000000..0b5853e2c56e1
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationErrorType.cs
@@ -0,0 +1,84 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+using System.ComponentModel;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Collection configuration error type reported by the client SDK.
+ internal readonly partial struct CollectionConfigurationErrorType : IEquatable
+ {
+ private readonly string _value;
+
+ /// Initializes a new instance of .
+ /// is null.
+ public CollectionConfigurationErrorType(string value)
+ {
+ _value = value ?? throw new ArgumentNullException(nameof(value));
+ }
+
+ private const string UnknownValue = "Unknown";
+ private const string PerformanceCounterParsingValue = "PerformanceCounterParsing";
+ private const string PerformanceCounterUnexpectedValue = "PerformanceCounterUnexpected";
+ private const string PerformanceCounterDuplicateIdsValue = "PerformanceCounterDuplicateIds";
+ private const string DocumentStreamDuplicateIdsValue = "DocumentStreamDuplicateIds";
+ private const string DocumentStreamFailureToCreateValue = "DocumentStreamFailureToCreate";
+ private const string DocumentStreamFailureToCreateFilterUnexpectedValue = "DocumentStreamFailureToCreateFilterUnexpected";
+ private const string MetricDuplicateIdsValue = "MetricDuplicateIds";
+ private const string MetricTelemetryTypeUnsupportedValue = "MetricTelemetryTypeUnsupported";
+ private const string MetricFailureToCreateValue = "MetricFailureToCreate";
+ private const string MetricFailureToCreateFilterUnexpectedValue = "MetricFailureToCreateFilterUnexpected";
+ private const string FilterFailureToCreateUnexpectedValue = "FilterFailureToCreateUnexpected";
+ private const string CollectionConfigurationFailureToCreateUnexpectedValue = "CollectionConfigurationFailureToCreateUnexpected";
+
+ /// Unknown error type.
+ public static CollectionConfigurationErrorType Unknown { get; } = new CollectionConfigurationErrorType(UnknownValue);
+ /// Performance counter parsing error.
+ public static CollectionConfigurationErrorType PerformanceCounterParsing { get; } = new CollectionConfigurationErrorType(PerformanceCounterParsingValue);
+ /// Performance counter unexpected error.
+ public static CollectionConfigurationErrorType PerformanceCounterUnexpected { get; } = new CollectionConfigurationErrorType(PerformanceCounterUnexpectedValue);
+ /// Performance counter duplicate ids.
+ public static CollectionConfigurationErrorType PerformanceCounterDuplicateIds { get; } = new CollectionConfigurationErrorType(PerformanceCounterDuplicateIdsValue);
+ /// Document stream duplication ids.
+ public static CollectionConfigurationErrorType DocumentStreamDuplicateIds { get; } = new CollectionConfigurationErrorType(DocumentStreamDuplicateIdsValue);
+ /// Document stream failed to create.
+ public static CollectionConfigurationErrorType DocumentStreamFailureToCreate { get; } = new CollectionConfigurationErrorType(DocumentStreamFailureToCreateValue);
+ /// Document stream failed to create filter unexpectedly.
+ public static CollectionConfigurationErrorType DocumentStreamFailureToCreateFilterUnexpected { get; } = new CollectionConfigurationErrorType(DocumentStreamFailureToCreateFilterUnexpectedValue);
+ /// Metric duplicate ids.
+ public static CollectionConfigurationErrorType MetricDuplicateIds { get; } = new CollectionConfigurationErrorType(MetricDuplicateIdsValue);
+ /// Metric telemetry type unsupported.
+ public static CollectionConfigurationErrorType MetricTelemetryTypeUnsupported { get; } = new CollectionConfigurationErrorType(MetricTelemetryTypeUnsupportedValue);
+ /// Metric failed to create.
+ public static CollectionConfigurationErrorType MetricFailureToCreate { get; } = new CollectionConfigurationErrorType(MetricFailureToCreateValue);
+ /// Metric failed to create filter unexpectedly.
+ public static CollectionConfigurationErrorType MetricFailureToCreateFilterUnexpected { get; } = new CollectionConfigurationErrorType(MetricFailureToCreateFilterUnexpectedValue);
+ /// Filter failed to create unexpectedly.
+ public static CollectionConfigurationErrorType FilterFailureToCreateUnexpected { get; } = new CollectionConfigurationErrorType(FilterFailureToCreateUnexpectedValue);
+ /// Collection configuration failed to create unexpectedly.
+ public static CollectionConfigurationErrorType CollectionConfigurationFailureToCreateUnexpected { get; } = new CollectionConfigurationErrorType(CollectionConfigurationFailureToCreateUnexpectedValue);
+ /// Determines if two values are the same.
+ public static bool operator ==(CollectionConfigurationErrorType left, CollectionConfigurationErrorType right) => left.Equals(right);
+ /// Determines if two values are not the same.
+ public static bool operator !=(CollectionConfigurationErrorType left, CollectionConfigurationErrorType right) => !left.Equals(right);
+ /// Converts a string to a .
+ public static implicit operator CollectionConfigurationErrorType(string value) => new CollectionConfigurationErrorType(value);
+
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is CollectionConfigurationErrorType other && Equals(other);
+ ///
+ public bool Equals(CollectionConfigurationErrorType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
+
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0;
+ ///
+ public override string ToString() => _value;
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationInfo.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationInfo.Serialization.cs
new file mode 100644
index 0000000000000..160706521a0bd
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationInfo.Serialization.cs
@@ -0,0 +1,73 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Collections.Generic;
+using System.Text.Json;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class CollectionConfigurationInfo
+ {
+ internal static CollectionConfigurationInfo DeserializeCollectionConfigurationInfo(JsonElement element)
+ {
+ if (element.ValueKind == JsonValueKind.Null)
+ {
+ return null;
+ }
+ string eTag = default;
+ IReadOnlyList metrics = default;
+ IReadOnlyList documentStreams = default;
+ QuotaConfigurationInfo quotaInfo = default;
+ foreach (var property in element.EnumerateObject())
+ {
+ if (property.NameEquals("ETag"u8))
+ {
+ eTag = property.Value.GetString();
+ continue;
+ }
+ if (property.NameEquals("Metrics"u8))
+ {
+ List array = new List();
+ foreach (var item in property.Value.EnumerateArray())
+ {
+ array.Add(DerivedMetricInfo.DeserializeDerivedMetricInfo(item));
+ }
+ metrics = array;
+ continue;
+ }
+ if (property.NameEquals("DocumentStreams"u8))
+ {
+ List array = new List();
+ foreach (var item in property.Value.EnumerateArray())
+ {
+ array.Add(DocumentStreamInfo.DeserializeDocumentStreamInfo(item));
+ }
+ documentStreams = array;
+ continue;
+ }
+ if (property.NameEquals("QuotaInfo"u8))
+ {
+ if (property.Value.ValueKind == JsonValueKind.Null)
+ {
+ continue;
+ }
+ quotaInfo = QuotaConfigurationInfo.DeserializeQuotaConfigurationInfo(property.Value);
+ continue;
+ }
+ }
+ return new CollectionConfigurationInfo(eTag, metrics, documentStreams, quotaInfo);
+ }
+
+ /// Deserializes the model from a raw response.
+ /// The response to deserialize the model from.
+ internal static CollectionConfigurationInfo FromResponse(Response response)
+ {
+ using var document = JsonDocument.Parse(response.Content);
+ return DeserializeCollectionConfigurationInfo(document.RootElement);
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationInfo.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationInfo.cs
new file mode 100644
index 0000000000000..866535b02f436
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/CollectionConfigurationInfo.cs
@@ -0,0 +1,55 @@
+// 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.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Represents the collection configuration - a customizable description of performance counters, metrics, and full telemetry documents to be collected by the client SDK.
+ internal partial class CollectionConfigurationInfo
+ {
+ /// Initializes a new instance of .
+ /// An encoded string that indicates whether the collection configuration is changed.
+ /// An array of metric configuration info.
+ /// An array of document stream configuration info.
+ /// , or is null.
+ internal CollectionConfigurationInfo(string eTag, IEnumerable metrics, IEnumerable documentStreams)
+ {
+ Argument.AssertNotNull(eTag, nameof(eTag));
+ Argument.AssertNotNull(metrics, nameof(metrics));
+ Argument.AssertNotNull(documentStreams, nameof(documentStreams));
+
+ ETag = eTag;
+ Metrics = metrics.ToList();
+ DocumentStreams = documentStreams.ToList();
+ }
+
+ /// Initializes a new instance of .
+ /// An encoded string that indicates whether the collection configuration is changed.
+ /// An array of metric configuration info.
+ /// An array of document stream configuration info.
+ /// Controls document quotas to be sent to Live Metrics.
+ internal CollectionConfigurationInfo(string eTag, IReadOnlyList metrics, IReadOnlyList documentStreams, QuotaConfigurationInfo quotaInfo)
+ {
+ ETag = eTag;
+ Metrics = metrics;
+ DocumentStreams = documentStreams;
+ QuotaInfo = quotaInfo;
+ }
+
+ /// An encoded string that indicates whether the collection configuration is changed.
+ public string ETag { get; }
+ /// An array of metric configuration info.
+ public IReadOnlyList Metrics { get; }
+ /// An array of document stream configuration info.
+ public IReadOnlyList DocumentStreams { get; }
+ /// Controls document quotas to be sent to Live Metrics.
+ public QuotaConfigurationInfo QuotaInfo { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DerivedMetricInfo.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DerivedMetricInfo.Serialization.cs
new file mode 100644
index 0000000000000..9101bf764e5df
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DerivedMetricInfo.Serialization.cs
@@ -0,0 +1,82 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Collections.Generic;
+using System.Text.Json;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class DerivedMetricInfo
+ {
+ internal static DerivedMetricInfo DeserializeDerivedMetricInfo(JsonElement element)
+ {
+ if (element.ValueKind == JsonValueKind.Null)
+ {
+ return null;
+ }
+ string id = default;
+ string telemetryType = default;
+ IReadOnlyList filterGroups = default;
+ string projection = default;
+ AggregationType aggregation = default;
+ AggregationType backEndAggregation = default;
+ foreach (var property in element.EnumerateObject())
+ {
+ if (property.NameEquals("Id"u8))
+ {
+ id = property.Value.GetString();
+ continue;
+ }
+ if (property.NameEquals("TelemetryType"u8))
+ {
+ telemetryType = property.Value.GetString();
+ continue;
+ }
+ if (property.NameEquals("FilterGroups"u8))
+ {
+ List array = new List();
+ foreach (var item in property.Value.EnumerateArray())
+ {
+ array.Add(FilterConjunctionGroupInfo.DeserializeFilterConjunctionGroupInfo(item));
+ }
+ filterGroups = array;
+ continue;
+ }
+ if (property.NameEquals("Projection"u8))
+ {
+ projection = property.Value.GetString();
+ continue;
+ }
+ if (property.NameEquals("Aggregation"u8))
+ {
+ aggregation = new AggregationType(property.Value.GetString());
+ continue;
+ }
+ if (property.NameEquals("BackEndAggregation"u8))
+ {
+ backEndAggregation = new AggregationType(property.Value.GetString());
+ continue;
+ }
+ }
+ return new DerivedMetricInfo(
+ id,
+ telemetryType,
+ filterGroups,
+ projection,
+ aggregation,
+ backEndAggregation);
+ }
+
+ /// Deserializes the model from a raw response.
+ /// The response to deserialize the model from.
+ internal static DerivedMetricInfo FromResponse(Response response)
+ {
+ using var document = JsonDocument.Parse(response.Content);
+ return DeserializeDerivedMetricInfo(document.RootElement);
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DerivedMetricInfo.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DerivedMetricInfo.cs
new file mode 100644
index 0000000000000..fc89e7d1c05f8
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DerivedMetricInfo.cs
@@ -0,0 +1,70 @@
+// 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.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// A metric configuration set by UX to scope the metrics it's interested in.
+ internal partial class DerivedMetricInfo
+ {
+ /// Initializes a new instance of .
+ /// metric configuration identifier.
+ /// Telemetry type.
+ /// A collection of filters to scope metrics that UX needs.
+ /// Telemetry's metric dimension whose value is to be aggregated. Example values: Duration, Count(),...
+ /// Aggregation type. This is the aggregation done from everything within a single server.
+ /// Aggregation type. This Aggregation is done across the values for all the servers taken together.
+ /// , , or is null.
+ internal DerivedMetricInfo(string id, string telemetryType, IEnumerable filterGroups, string projection, AggregationType aggregation, AggregationType backEndAggregation)
+ {
+ Argument.AssertNotNull(id, nameof(id));
+ Argument.AssertNotNull(telemetryType, nameof(telemetryType));
+ Argument.AssertNotNull(filterGroups, nameof(filterGroups));
+ Argument.AssertNotNull(projection, nameof(projection));
+
+ Id = id;
+ TelemetryType = telemetryType;
+ FilterGroups = filterGroups.ToList();
+ Projection = projection;
+ Aggregation = aggregation;
+ BackEndAggregation = backEndAggregation;
+ }
+
+ /// Initializes a new instance of .
+ /// metric configuration identifier.
+ /// Telemetry type.
+ /// A collection of filters to scope metrics that UX needs.
+ /// Telemetry's metric dimension whose value is to be aggregated. Example values: Duration, Count(),...
+ /// Aggregation type. This is the aggregation done from everything within a single server.
+ /// Aggregation type. This Aggregation is done across the values for all the servers taken together.
+ internal DerivedMetricInfo(string id, string telemetryType, IReadOnlyList filterGroups, string projection, AggregationType aggregation, AggregationType backEndAggregation)
+ {
+ Id = id;
+ TelemetryType = telemetryType;
+ FilterGroups = filterGroups;
+ Projection = projection;
+ Aggregation = aggregation;
+ BackEndAggregation = backEndAggregation;
+ }
+
+ /// metric configuration identifier.
+ public string Id { get; }
+ /// Telemetry type.
+ public string TelemetryType { get; }
+ /// A collection of filters to scope metrics that UX needs.
+ public IReadOnlyList FilterGroups { get; }
+ /// Telemetry's metric dimension whose value is to be aggregated. Example values: Duration, Count(),...
+ public string Projection { get; }
+ /// Aggregation type. This is the aggregation done from everything within a single server.
+ public AggregationType Aggregation { get; }
+ /// Aggregation type. This Aggregation is done across the values for all the servers taken together.
+ public AggregationType BackEndAggregation { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentFilterConjunctionGroupInfo.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentFilterConjunctionGroupInfo.Serialization.cs
new file mode 100644
index 0000000000000..25f595b4111e6
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentFilterConjunctionGroupInfo.Serialization.cs
@@ -0,0 +1,46 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class DocumentFilterConjunctionGroupInfo
+ {
+ internal static DocumentFilterConjunctionGroupInfo DeserializeDocumentFilterConjunctionGroupInfo(JsonElement element)
+ {
+ if (element.ValueKind == JsonValueKind.Null)
+ {
+ return null;
+ }
+ TelemetryType telemetryType = default;
+ FilterConjunctionGroupInfo filters = default;
+ foreach (var property in element.EnumerateObject())
+ {
+ if (property.NameEquals("TelemetryType"u8))
+ {
+ telemetryType = new TelemetryType(property.Value.GetString());
+ continue;
+ }
+ if (property.NameEquals("Filters"u8))
+ {
+ filters = FilterConjunctionGroupInfo.DeserializeFilterConjunctionGroupInfo(property.Value);
+ continue;
+ }
+ }
+ return new DocumentFilterConjunctionGroupInfo(telemetryType, filters);
+ }
+
+ /// Deserializes the model from a raw response.
+ /// The response to deserialize the model from.
+ internal static DocumentFilterConjunctionGroupInfo FromResponse(Response response)
+ {
+ using var document = JsonDocument.Parse(response.Content);
+ return DeserializeDocumentFilterConjunctionGroupInfo(document.RootElement);
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentFilterConjunctionGroupInfo.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentFilterConjunctionGroupInfo.cs
new file mode 100644
index 0000000000000..d61bb69653213
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentFilterConjunctionGroupInfo.cs
@@ -0,0 +1,32 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// A collection of filters for a specific telemetry type.
+ internal partial class DocumentFilterConjunctionGroupInfo
+ {
+ /// Initializes a new instance of .
+ /// Telemetry type.
+ /// An array of filter groups.
+ /// is null.
+ internal DocumentFilterConjunctionGroupInfo(TelemetryType telemetryType, FilterConjunctionGroupInfo filters)
+ {
+ Argument.AssertNotNull(filters, nameof(filters));
+
+ TelemetryType = telemetryType;
+ Filters = filters;
+ }
+
+ /// Telemetry type.
+ public TelemetryType TelemetryType { get; }
+ /// An array of filter groups.
+ public FilterConjunctionGroupInfo Filters { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentIngress.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentIngress.Serialization.cs
new file mode 100644
index 0000000000000..cde93f504bc32
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentIngress.Serialization.cs
@@ -0,0 +1,51 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class DocumentIngress : IUtf8JsonSerializable
+ {
+ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
+ {
+ writer.WriteStartObject();
+ writer.WritePropertyName("DocumentType"u8);
+ writer.WriteStringValue(DocumentType.ToString());
+ if (Optional.IsCollectionDefined(DocumentStreamIds))
+ {
+ writer.WritePropertyName("DocumentStreamIds"u8);
+ writer.WriteStartArray();
+ foreach (var item in DocumentStreamIds)
+ {
+ writer.WriteStringValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ if (Optional.IsCollectionDefined(Properties))
+ {
+ writer.WritePropertyName("Properties"u8);
+ writer.WriteStartArray();
+ foreach (var item in Properties)
+ {
+ writer.WriteObjectValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ writer.WriteEndObject();
+ }
+
+ /// Convert into a .
+ internal virtual RequestContent ToRequestContent()
+ {
+ var content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteObjectValue(this);
+ return content;
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentIngress.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentIngress.cs
new file mode 100644
index 0000000000000..2514fbf02f8e0
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentIngress.cs
@@ -0,0 +1,44 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Collections.Generic;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ ///
+ /// Base class of the specific document types.
+ /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.
+ /// The available derived classes include , , , and .
+ ///
+ internal abstract partial class DocumentIngress
+ {
+ /// Initializes a new instance of .
+ protected DocumentIngress()
+ {
+ DocumentStreamIds = new ChangeTrackingList();
+ Properties = new ChangeTrackingList();
+ }
+
+ /// Initializes a new instance of .
+ /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type.
+ /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers.
+ /// Collection of custom properties.
+ internal DocumentIngress(DocumentType documentType, IList documentStreamIds, IList properties)
+ {
+ DocumentType = documentType;
+ DocumentStreamIds = documentStreamIds;
+ Properties = properties;
+ }
+
+ /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type.
+ internal DocumentType DocumentType { get; set; }
+ /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers.
+ public IList DocumentStreamIds { get; }
+ /// Collection of custom properties.
+ public IList Properties { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentStreamInfo.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentStreamInfo.Serialization.cs
new file mode 100644
index 0000000000000..6986d457b18ba
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentStreamInfo.Serialization.cs
@@ -0,0 +1,52 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Collections.Generic;
+using System.Text.Json;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class DocumentStreamInfo
+ {
+ internal static DocumentStreamInfo DeserializeDocumentStreamInfo(JsonElement element)
+ {
+ if (element.ValueKind == JsonValueKind.Null)
+ {
+ return null;
+ }
+ string id = default;
+ IReadOnlyList documentFilterGroups = default;
+ foreach (var property in element.EnumerateObject())
+ {
+ if (property.NameEquals("Id"u8))
+ {
+ id = property.Value.GetString();
+ continue;
+ }
+ if (property.NameEquals("DocumentFilterGroups"u8))
+ {
+ List array = new List();
+ foreach (var item in property.Value.EnumerateArray())
+ {
+ array.Add(DocumentFilterConjunctionGroupInfo.DeserializeDocumentFilterConjunctionGroupInfo(item));
+ }
+ documentFilterGroups = array;
+ continue;
+ }
+ }
+ return new DocumentStreamInfo(id, documentFilterGroups);
+ }
+
+ /// Deserializes the model from a raw response.
+ /// The response to deserialize the model from.
+ internal static DocumentStreamInfo FromResponse(Response response)
+ {
+ using var document = JsonDocument.Parse(response.Content);
+ return DeserializeDocumentStreamInfo(document.RootElement);
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentStreamInfo.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentStreamInfo.cs
new file mode 100644
index 0000000000000..beb1992a4c075
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentStreamInfo.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;
+using System.Linq;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Configurations/filters set by UX to scope the document/telemetry it's interested in.
+ internal partial class DocumentStreamInfo
+ {
+ /// Initializes a new instance of .
+ /// Identifier of the document stream initiated by a UX.
+ /// Gets or sets an OR-connected collection of filter groups.
+ /// or is null.
+ internal DocumentStreamInfo(string id, IEnumerable documentFilterGroups)
+ {
+ Argument.AssertNotNull(id, nameof(id));
+ Argument.AssertNotNull(documentFilterGroups, nameof(documentFilterGroups));
+
+ Id = id;
+ DocumentFilterGroups = documentFilterGroups.ToList();
+ }
+
+ /// Initializes a new instance of .
+ /// Identifier of the document stream initiated by a UX.
+ /// Gets or sets an OR-connected collection of filter groups.
+ internal DocumentStreamInfo(string id, IReadOnlyList documentFilterGroups)
+ {
+ Id = id;
+ DocumentFilterGroups = documentFilterGroups;
+ }
+
+ /// Identifier of the document stream initiated by a UX.
+ public string Id { get; }
+ /// Gets or sets an OR-connected collection of filter groups.
+ public IReadOnlyList DocumentFilterGroups { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentType.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentType.cs
new file mode 100644
index 0000000000000..df6d7662e786a
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/DocumentType.cs
@@ -0,0 +1,63 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+using System.ComponentModel;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Document type.
+ internal readonly partial struct DocumentType : IEquatable
+ {
+ private readonly string _value;
+
+ /// Initializes a new instance of .
+ /// is null.
+ public DocumentType(string value)
+ {
+ _value = value ?? throw new ArgumentNullException(nameof(value));
+ }
+
+ private const string RequestValue = "Request";
+ private const string RemoteDependencyValue = "RemoteDependency";
+ private const string ExceptionValue = "Exception";
+ private const string EventValue = "Event";
+ private const string TraceValue = "Trace";
+ private const string UnknownValue = "Unknown";
+
+ /// Represents a request telemetry type.
+ public static DocumentType Request { get; } = new DocumentType(RequestValue);
+ /// Represents a remote dependency telemetry type.
+ public static DocumentType RemoteDependency { get; } = new DocumentType(RemoteDependencyValue);
+ /// Represents an exception telemetry type.
+ public static DocumentType Exception { get; } = new DocumentType(ExceptionValue);
+ /// Represents an event telemetry type.
+ public static DocumentType Event { get; } = new DocumentType(EventValue);
+ /// Represents a trace telemetry type.
+ public static DocumentType Trace { get; } = new DocumentType(TraceValue);
+ /// Represents an unknown telemetry type.
+ public static DocumentType Unknown { get; } = new DocumentType(UnknownValue);
+ /// Determines if two values are the same.
+ public static bool operator ==(DocumentType left, DocumentType right) => left.Equals(right);
+ /// Determines if two values are not the same.
+ public static bool operator !=(DocumentType left, DocumentType right) => !left.Equals(right);
+ /// Converts a string to a .
+ public static implicit operator DocumentType(string value) => new DocumentType(value);
+
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is DocumentType other && Equals(other);
+ ///
+ public bool Equals(DocumentType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
+
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0;
+ ///
+ public override string ToString() => _value;
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Event.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Event.Serialization.cs
new file mode 100644
index 0000000000000..07b9e6628e369
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Event.Serialization.cs
@@ -0,0 +1,56 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class Event : IUtf8JsonSerializable
+ {
+ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
+ {
+ writer.WriteStartObject();
+ if (Optional.IsDefined(Name))
+ {
+ writer.WritePropertyName("Name"u8);
+ writer.WriteStringValue(Name);
+ }
+ writer.WritePropertyName("DocumentType"u8);
+ writer.WriteStringValue(DocumentType.ToString());
+ if (Optional.IsCollectionDefined(DocumentStreamIds))
+ {
+ writer.WritePropertyName("DocumentStreamIds"u8);
+ writer.WriteStartArray();
+ foreach (var item in DocumentStreamIds)
+ {
+ writer.WriteStringValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ if (Optional.IsCollectionDefined(Properties))
+ {
+ writer.WritePropertyName("Properties"u8);
+ writer.WriteStartArray();
+ foreach (var item in Properties)
+ {
+ writer.WriteObjectValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ writer.WriteEndObject();
+ }
+
+ /// Convert into a .
+ internal override RequestContent ToRequestContent()
+ {
+ var content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteObjectValue(this);
+ return content;
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Event.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Event.cs
new file mode 100644
index 0000000000000..046b2cdf87de8
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Event.cs
@@ -0,0 +1,35 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Collections.Generic;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Event document type.
+ internal partial class Event : DocumentIngress
+ {
+ /// Initializes a new instance of .
+ public Event()
+ {
+ DocumentType = DocumentType.Event;
+ }
+
+ /// Initializes a new instance of .
+ /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type.
+ /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers.
+ /// Collection of custom properties.
+ /// Event name.
+ internal Event(DocumentType documentType, IList documentStreamIds, IList properties, string name) : base(documentType, documentStreamIds, properties)
+ {
+ Name = name;
+ DocumentType = documentType;
+ }
+
+ /// Event name.
+ public string Name { get; set; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Exception.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Exception.Serialization.cs
new file mode 100644
index 0000000000000..5e03596fe4314
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Exception.Serialization.cs
@@ -0,0 +1,61 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class Exception : IUtf8JsonSerializable
+ {
+ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
+ {
+ writer.WriteStartObject();
+ if (Optional.IsDefined(ExceptionType))
+ {
+ writer.WritePropertyName("ExceptionType"u8);
+ writer.WriteStringValue(ExceptionType);
+ }
+ if (Optional.IsDefined(ExceptionMessage))
+ {
+ writer.WritePropertyName("ExceptionMessage"u8);
+ writer.WriteStringValue(ExceptionMessage);
+ }
+ writer.WritePropertyName("DocumentType"u8);
+ writer.WriteStringValue(DocumentType.ToString());
+ if (Optional.IsCollectionDefined(DocumentStreamIds))
+ {
+ writer.WritePropertyName("DocumentStreamIds"u8);
+ writer.WriteStartArray();
+ foreach (var item in DocumentStreamIds)
+ {
+ writer.WriteStringValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ if (Optional.IsCollectionDefined(Properties))
+ {
+ writer.WritePropertyName("Properties"u8);
+ writer.WriteStartArray();
+ foreach (var item in Properties)
+ {
+ writer.WriteObjectValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ writer.WriteEndObject();
+ }
+
+ /// Convert into a .
+ internal override RequestContent ToRequestContent()
+ {
+ var content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteObjectValue(this);
+ return content;
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Exception.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Exception.cs
new file mode 100644
index 0000000000000..0fb637419fe62
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Exception.cs
@@ -0,0 +1,39 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Collections.Generic;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Exception document type.
+ internal partial class Exception : DocumentIngress
+ {
+ /// Initializes a new instance of .
+ public Exception()
+ {
+ DocumentType = DocumentType.Exception;
+ }
+
+ /// Initializes a new instance of .
+ /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type.
+ /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers.
+ /// Collection of custom properties.
+ /// Exception type name.
+ /// Exception message.
+ internal Exception(DocumentType documentType, IList documentStreamIds, IList properties, string exceptionType, string exceptionMessage) : base(documentType, documentStreamIds, properties)
+ {
+ ExceptionType = exceptionType;
+ ExceptionMessage = exceptionMessage;
+ DocumentType = documentType;
+ }
+
+ /// Exception type name.
+ public string ExceptionType { get; set; }
+ /// Exception message.
+ public string ExceptionMessage { get; set; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterConjunctionGroupInfo.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterConjunctionGroupInfo.Serialization.cs
new file mode 100644
index 0000000000000..a9b1451beace6
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterConjunctionGroupInfo.Serialization.cs
@@ -0,0 +1,46 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Collections.Generic;
+using System.Text.Json;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class FilterConjunctionGroupInfo
+ {
+ internal static FilterConjunctionGroupInfo DeserializeFilterConjunctionGroupInfo(JsonElement element)
+ {
+ if (element.ValueKind == JsonValueKind.Null)
+ {
+ return null;
+ }
+ IReadOnlyList filters = default;
+ foreach (var property in element.EnumerateObject())
+ {
+ if (property.NameEquals("Filters"u8))
+ {
+ List array = new List();
+ foreach (var item in property.Value.EnumerateArray())
+ {
+ array.Add(FilterInfo.DeserializeFilterInfo(item));
+ }
+ filters = array;
+ continue;
+ }
+ }
+ return new FilterConjunctionGroupInfo(filters);
+ }
+
+ /// Deserializes the model from a raw response.
+ /// The response to deserialize the model from.
+ internal static FilterConjunctionGroupInfo FromResponse(Response response)
+ {
+ using var document = JsonDocument.Parse(response.Content);
+ return DeserializeFilterConjunctionGroupInfo(document.RootElement);
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterConjunctionGroupInfo.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterConjunctionGroupInfo.cs
new file mode 100644
index 0000000000000..9d70c4c9e2705
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterConjunctionGroupInfo.cs
@@ -0,0 +1,37 @@
+// 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.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// An AND-connected group of FilterInfo objects.
+ internal partial class FilterConjunctionGroupInfo
+ {
+ /// Initializes a new instance of .
+ /// An array of filters.
+ /// is null.
+ internal FilterConjunctionGroupInfo(IEnumerable filters)
+ {
+ Argument.AssertNotNull(filters, nameof(filters));
+
+ Filters = filters.ToList();
+ }
+
+ /// Initializes a new instance of .
+ /// An array of filters.
+ internal FilterConjunctionGroupInfo(IReadOnlyList filters)
+ {
+ Filters = filters;
+ }
+
+ /// An array of filters.
+ public IReadOnlyList Filters { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterInfo.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterInfo.Serialization.cs
new file mode 100644
index 0000000000000..f1b1261bef6cc
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterInfo.Serialization.cs
@@ -0,0 +1,52 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class FilterInfo
+ {
+ internal static FilterInfo DeserializeFilterInfo(JsonElement element)
+ {
+ if (element.ValueKind == JsonValueKind.Null)
+ {
+ return null;
+ }
+ string fieldName = default;
+ PredicateType predicate = default;
+ string comparand = default;
+ foreach (var property in element.EnumerateObject())
+ {
+ if (property.NameEquals("FieldName"u8))
+ {
+ fieldName = property.Value.GetString();
+ continue;
+ }
+ if (property.NameEquals("Predicate"u8))
+ {
+ predicate = new PredicateType(property.Value.GetString());
+ continue;
+ }
+ if (property.NameEquals("Comparand"u8))
+ {
+ comparand = property.Value.GetString();
+ continue;
+ }
+ }
+ return new FilterInfo(fieldName, predicate, comparand);
+ }
+
+ /// Deserializes the model from a raw response.
+ /// The response to deserialize the model from.
+ internal static FilterInfo FromResponse(Response response)
+ {
+ using var document = JsonDocument.Parse(response.Content);
+ return DeserializeFilterInfo(document.RootElement);
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterInfo.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterInfo.cs
new file mode 100644
index 0000000000000..766708559dd09
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/FilterInfo.cs
@@ -0,0 +1,37 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// A filter set on UX.
+ internal partial class FilterInfo
+ {
+ /// Initializes a new instance of .
+ /// dimension name of the filter.
+ /// Operator of the filter.
+ /// Comparand of the filter.
+ /// or is null.
+ internal FilterInfo(string fieldName, PredicateType predicate, string comparand)
+ {
+ Argument.AssertNotNull(fieldName, nameof(fieldName));
+ Argument.AssertNotNull(comparand, nameof(comparand));
+
+ FieldName = fieldName;
+ Predicate = predicate;
+ Comparand = comparand;
+ }
+
+ /// dimension name of the filter.
+ public string FieldName { get; }
+ /// Operator of the filter.
+ public PredicateType Predicate { get; }
+ /// Comparand of the filter.
+ public string Comparand { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/KeyValuePairString.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/KeyValuePairString.Serialization.cs
new file mode 100644
index 0000000000000..6afcfcc484a9e
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/KeyValuePairString.Serialization.cs
@@ -0,0 +1,33 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class KeyValuePairString : IUtf8JsonSerializable
+ {
+ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
+ {
+ writer.WriteStartObject();
+ writer.WritePropertyName("key"u8);
+ writer.WriteStringValue(Key);
+ writer.WritePropertyName("value"u8);
+ writer.WriteStringValue(Value);
+ writer.WriteEndObject();
+ }
+
+ /// Convert into a .
+ internal virtual RequestContent ToRequestContent()
+ {
+ var content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteObjectValue(this);
+ return content;
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/KeyValuePairString.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/KeyValuePairString.cs
new file mode 100644
index 0000000000000..a16fc2ccec390
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/KeyValuePairString.cs
@@ -0,0 +1,33 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Key-value pair of string and string.
+ internal partial class KeyValuePairString
+ {
+ /// Initializes a new instance of .
+ /// Key of the key-value pair.
+ /// Value of the key-value pair.
+ /// or is null.
+ public KeyValuePairString(string key, string value)
+ {
+ Argument.AssertNotNull(key, nameof(key));
+ Argument.AssertNotNull(value, nameof(value));
+
+ Key = key;
+ Value = value;
+ }
+
+ /// Key of the key-value pair.
+ public string Key { get; }
+ /// Value of the key-value pair.
+ public string Value { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MetricPoint.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MetricPoint.Serialization.cs
new file mode 100644
index 0000000000000..1be293870dbcc
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MetricPoint.Serialization.cs
@@ -0,0 +1,35 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class MetricPoint : IUtf8JsonSerializable
+ {
+ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
+ {
+ writer.WriteStartObject();
+ writer.WritePropertyName("Name"u8);
+ writer.WriteStringValue(Name);
+ writer.WritePropertyName("Value"u8);
+ writer.WriteNumberValue(Value);
+ writer.WritePropertyName("Weight"u8);
+ writer.WriteNumberValue(Weight);
+ writer.WriteEndObject();
+ }
+
+ /// Convert into a .
+ internal virtual RequestContent ToRequestContent()
+ {
+ var content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteObjectValue(this);
+ return content;
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MetricPoint.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MetricPoint.cs
new file mode 100644
index 0000000000000..0b26ef61db318
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MetricPoint.cs
@@ -0,0 +1,36 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Metric data point.
+ internal partial class MetricPoint
+ {
+ /// Initializes a new instance of .
+ /// Metric name.
+ /// Metric value.
+ /// Metric weight.
+ /// is null.
+ public MetricPoint(string name, double value, int weight)
+ {
+ Argument.AssertNotNull(name, nameof(name));
+
+ Name = name;
+ Value = value;
+ Weight = weight;
+ }
+
+ /// Metric name.
+ public string Name { get; }
+ /// Metric value.
+ public double Value { get; }
+ /// Metric weight.
+ public int Weight { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MonitoringDataPoint.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MonitoringDataPoint.Serialization.cs
new file mode 100644
index 0000000000000..8717cfa87d2a3
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MonitoringDataPoint.Serialization.cs
@@ -0,0 +1,95 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class MonitoringDataPoint : IUtf8JsonSerializable
+ {
+ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
+ {
+ writer.WriteStartObject();
+ writer.WritePropertyName("Version"u8);
+ writer.WriteStringValue(Version);
+ writer.WritePropertyName("InvariantVersion"u8);
+ writer.WriteNumberValue(InvariantVersion);
+ writer.WritePropertyName("Instance"u8);
+ writer.WriteStringValue(Instance);
+ writer.WritePropertyName("RoleName"u8);
+ writer.WriteStringValue(RoleName);
+ writer.WritePropertyName("MachineName"u8);
+ writer.WriteStringValue(MachineName);
+ writer.WritePropertyName("StreamId"u8);
+ writer.WriteStringValue(StreamId);
+ if (Optional.IsDefined(Timestamp))
+ {
+ writer.WritePropertyName("Timestamp"u8);
+ writer.WriteStringValue(Timestamp.Value, "O");
+ }
+ if (Optional.IsDefined(TransmissionTime))
+ {
+ writer.WritePropertyName("TransmissionTime"u8);
+ writer.WriteStringValue(TransmissionTime.Value, "O");
+ }
+ writer.WritePropertyName("IsWebApp"u8);
+ writer.WriteBooleanValue(IsWebApp);
+ writer.WritePropertyName("PerformanceCollectionSupported"u8);
+ writer.WriteBooleanValue(PerformanceCollectionSupported);
+ if (Optional.IsCollectionDefined(Metrics))
+ {
+ writer.WritePropertyName("Metrics"u8);
+ writer.WriteStartArray();
+ foreach (var item in Metrics)
+ {
+ writer.WriteObjectValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ if (Optional.IsCollectionDefined(Documents))
+ {
+ writer.WritePropertyName("Documents"u8);
+ writer.WriteStartArray();
+ foreach (var item in Documents)
+ {
+ writer.WriteObjectValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ if (Optional.IsCollectionDefined(TopCpuProcesses))
+ {
+ writer.WritePropertyName("TopCpuProcesses"u8);
+ writer.WriteStartArray();
+ foreach (var item in TopCpuProcesses)
+ {
+ writer.WriteObjectValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ if (Optional.IsCollectionDefined(CollectionConfigurationErrors))
+ {
+ writer.WritePropertyName("CollectionConfigurationErrors"u8);
+ writer.WriteStartArray();
+ foreach (var item in CollectionConfigurationErrors)
+ {
+ writer.WriteObjectValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ writer.WriteEndObject();
+ }
+
+ /// Convert into a .
+ internal virtual RequestContent ToRequestContent()
+ {
+ var content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteObjectValue(this);
+ return content;
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MonitoringDataPoint.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MonitoringDataPoint.cs
new file mode 100644
index 0000000000000..1d9efae8b4268
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/MonitoringDataPoint.cs
@@ -0,0 +1,118 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Monitoring data point coming from the client, which includes metrics, documents and other metadata info.
+ internal partial class MonitoringDataPoint
+ {
+ /// Initializes a new instance of .
+ /// Application Insights SDK version.
+ /// Version/generation of the data contract (MonitoringDataPoint) between SDK and Live Metrics.
+ /// Service instance name where Application Insights SDK lives.
+ /// Service role name.
+ /// Computer name where Application Insights SDK lives.
+ /// Identifies an Application Insights SDK as a trusted agent to report metrics and documents.
+ /// True if the current application is an Azure Web App.
+ /// True if performance counters collection is supported.
+ /// , , , or is null.
+ public MonitoringDataPoint(string version, int invariantVersion, string instance, string roleName, string machineName, string streamId, bool isWebApp, bool performanceCollectionSupported)
+ {
+ Argument.AssertNotNull(version, nameof(version));
+ Argument.AssertNotNull(instance, nameof(instance));
+ Argument.AssertNotNull(roleName, nameof(roleName));
+ Argument.AssertNotNull(machineName, nameof(machineName));
+ Argument.AssertNotNull(streamId, nameof(streamId));
+
+ Version = version;
+ InvariantVersion = invariantVersion;
+ Instance = instance;
+ RoleName = roleName;
+ MachineName = machineName;
+ StreamId = streamId;
+ IsWebApp = isWebApp;
+ PerformanceCollectionSupported = performanceCollectionSupported;
+ Metrics = new ChangeTrackingList();
+ Documents = new ChangeTrackingList();
+ TopCpuProcesses = new ChangeTrackingList();
+ CollectionConfigurationErrors = new ChangeTrackingList();
+ }
+
+ /// Initializes a new instance of .
+ /// Application Insights SDK version.
+ /// Version/generation of the data contract (MonitoringDataPoint) between SDK and Live Metrics.
+ /// Service instance name where Application Insights SDK lives.
+ /// Service role name.
+ /// Computer name where Application Insights SDK lives.
+ /// Identifies an Application Insights SDK as a trusted agent to report metrics and documents.
+ /// Data point generation timestamp.
+ /// Timestamp when the client transmits the metrics and documents to Live Metrics.
+ /// True if the current application is an Azure Web App.
+ /// True if performance counters collection is supported.
+ /// An array of metric data points.
+ ///
+ /// An array of documents of a specific type {Request}, {RemoteDependency}, {Exception}, {Event}, or {Trace}
+ /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.
+ /// The available derived classes include , , , and .
+ ///
+ /// An array of top cpu consumption data point.
+ /// An array of error while SDK parses and applies the {CollectionConfigurationInfo} provided by Live Metrics.
+ internal MonitoringDataPoint(string version, int invariantVersion, string instance, string roleName, string machineName, string streamId, DateTimeOffset? timestamp, DateTimeOffset? transmissionTime, bool isWebApp, bool performanceCollectionSupported, IList metrics, IList documents, IList topCpuProcesses, IList collectionConfigurationErrors)
+ {
+ Version = version;
+ InvariantVersion = invariantVersion;
+ Instance = instance;
+ RoleName = roleName;
+ MachineName = machineName;
+ StreamId = streamId;
+ Timestamp = timestamp;
+ TransmissionTime = transmissionTime;
+ IsWebApp = isWebApp;
+ PerformanceCollectionSupported = performanceCollectionSupported;
+ Metrics = metrics;
+ Documents = documents;
+ TopCpuProcesses = topCpuProcesses;
+ CollectionConfigurationErrors = collectionConfigurationErrors;
+ }
+
+ /// Application Insights SDK version.
+ public string Version { get; }
+ /// Version/generation of the data contract (MonitoringDataPoint) between SDK and Live Metrics.
+ public int InvariantVersion { get; }
+ /// Service instance name where Application Insights SDK lives.
+ public string Instance { get; }
+ /// Service role name.
+ public string RoleName { get; }
+ /// Computer name where Application Insights SDK lives.
+ public string MachineName { get; }
+ /// Identifies an Application Insights SDK as a trusted agent to report metrics and documents.
+ public string StreamId { get; }
+ /// Data point generation timestamp.
+ public DateTimeOffset? Timestamp { get; set; }
+ /// Timestamp when the client transmits the metrics and documents to Live Metrics.
+ public DateTimeOffset? TransmissionTime { get; set; }
+ /// True if the current application is an Azure Web App.
+ public bool IsWebApp { get; }
+ /// True if performance counters collection is supported.
+ public bool PerformanceCollectionSupported { get; }
+ /// An array of metric data points.
+ public IList Metrics { get; }
+ ///
+ /// An array of documents of a specific type {Request}, {RemoteDependency}, {Exception}, {Event}, or {Trace}
+ /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.
+ /// The available derived classes include , , , and .
+ ///
+ public IList Documents { get; }
+ /// An array of top cpu consumption data point.
+ public IList TopCpuProcesses { get; }
+ /// An array of error while SDK parses and applies the {CollectionConfigurationInfo} provided by Live Metrics.
+ public IList CollectionConfigurationErrors { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/PredicateType.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/PredicateType.cs
new file mode 100644
index 0000000000000..05515dd5afd9d
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/PredicateType.cs
@@ -0,0 +1,69 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+using System.ComponentModel;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Enum representing the different types of predicates.
+ internal readonly partial struct PredicateType : IEquatable
+ {
+ private readonly string _value;
+
+ /// Initializes a new instance of .
+ /// is null.
+ public PredicateType(string value)
+ {
+ _value = value ?? throw new ArgumentNullException(nameof(value));
+ }
+
+ private const string EqualValue = "Equal";
+ private const string NotEqualValue = "NotEqual";
+ private const string LessThanValue = "LessThan";
+ private const string GreaterThanValue = "GreaterThan";
+ private const string LessThanOrEqualValue = "LessThanOrEqual";
+ private const string GreaterThanOrEqualValue = "GreaterThanOrEqual";
+ private const string ContainsValue = "Contains";
+ private const string DoesNotContainValue = "DoesNotContain";
+
+ /// Represents an equality predicate.
+ public static PredicateType Equal { get; } = new PredicateType(EqualValue);
+ /// Represents a not-equal predicate.
+ public static PredicateType NotEqual { get; } = new PredicateType(NotEqualValue);
+ /// Represents a less-than predicate.
+ public static PredicateType LessThan { get; } = new PredicateType(LessThanValue);
+ /// Represents a greater-than predicate.
+ public static PredicateType GreaterThan { get; } = new PredicateType(GreaterThanValue);
+ /// Represents a less-than-or-equal predicate.
+ public static PredicateType LessThanOrEqual { get; } = new PredicateType(LessThanOrEqualValue);
+ /// Represents a greater-than-or-equal predicate.
+ public static PredicateType GreaterThanOrEqual { get; } = new PredicateType(GreaterThanOrEqualValue);
+ /// Represents a contains predicate.
+ public static PredicateType Contains { get; } = new PredicateType(ContainsValue);
+ /// Represents a does-not-contain predicate.
+ public static PredicateType DoesNotContain { get; } = new PredicateType(DoesNotContainValue);
+ /// Determines if two values are the same.
+ public static bool operator ==(PredicateType left, PredicateType right) => left.Equals(right);
+ /// Determines if two values are not the same.
+ public static bool operator !=(PredicateType left, PredicateType right) => !left.Equals(right);
+ /// Converts a string to a .
+ public static implicit operator PredicateType(string value) => new PredicateType(value);
+
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is PredicateType other && Equals(other);
+ ///
+ public bool Equals(PredicateType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
+
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0;
+ ///
+ public override string ToString() => _value;
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ProcessCpuData.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ProcessCpuData.Serialization.cs
new file mode 100644
index 0000000000000..2f9201151fdf2
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ProcessCpuData.Serialization.cs
@@ -0,0 +1,33 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class ProcessCpuData : IUtf8JsonSerializable
+ {
+ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
+ {
+ writer.WriteStartObject();
+ writer.WritePropertyName("ProcessName"u8);
+ writer.WriteStringValue(ProcessName);
+ writer.WritePropertyName("CpuPercentage"u8);
+ writer.WriteNumberValue(CpuPercentage);
+ writer.WriteEndObject();
+ }
+
+ /// Convert into a .
+ internal virtual RequestContent ToRequestContent()
+ {
+ var content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteObjectValue(this);
+ return content;
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ProcessCpuData.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ProcessCpuData.cs
new file mode 100644
index 0000000000000..756e9a6be7587
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ProcessCpuData.cs
@@ -0,0 +1,32 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// CPU consumption datapoint.
+ internal partial class ProcessCpuData
+ {
+ /// Initializes a new instance of .
+ /// Process name.
+ /// CPU consumption percentage.
+ /// is null.
+ public ProcessCpuData(string processName, int cpuPercentage)
+ {
+ Argument.AssertNotNull(processName, nameof(processName));
+
+ ProcessName = processName;
+ CpuPercentage = cpuPercentage;
+ }
+
+ /// Process name.
+ public string ProcessName { get; }
+ /// CPU consumption percentage.
+ public int CpuPercentage { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/QuotaConfigurationInfo.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/QuotaConfigurationInfo.Serialization.cs
new file mode 100644
index 0000000000000..484e18a43c78d
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/QuotaConfigurationInfo.Serialization.cs
@@ -0,0 +1,56 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class QuotaConfigurationInfo
+ {
+ internal static QuotaConfigurationInfo DeserializeQuotaConfigurationInfo(JsonElement element)
+ {
+ if (element.ValueKind == JsonValueKind.Null)
+ {
+ return null;
+ }
+ float? initialQuota = default;
+ float maxQuota = default;
+ float quotaAccrualRatePerSec = default;
+ foreach (var property in element.EnumerateObject())
+ {
+ if (property.NameEquals("InitialQuota"u8))
+ {
+ if (property.Value.ValueKind == JsonValueKind.Null)
+ {
+ continue;
+ }
+ initialQuota = property.Value.GetSingle();
+ continue;
+ }
+ if (property.NameEquals("MaxQuota"u8))
+ {
+ maxQuota = property.Value.GetSingle();
+ continue;
+ }
+ if (property.NameEquals("QuotaAccrualRatePerSec"u8))
+ {
+ quotaAccrualRatePerSec = property.Value.GetSingle();
+ continue;
+ }
+ }
+ return new QuotaConfigurationInfo(initialQuota, maxQuota, quotaAccrualRatePerSec);
+ }
+
+ /// Deserializes the model from a raw response.
+ /// The response to deserialize the model from.
+ internal static QuotaConfigurationInfo FromResponse(Response response)
+ {
+ using var document = JsonDocument.Parse(response.Content);
+ return DeserializeQuotaConfigurationInfo(document.RootElement);
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/QuotaConfigurationInfo.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/QuotaConfigurationInfo.cs
new file mode 100644
index 0000000000000..0c867233b6488
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/QuotaConfigurationInfo.cs
@@ -0,0 +1,40 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Controls document quotas to be sent to Live Metrics.
+ internal partial class QuotaConfigurationInfo
+ {
+ /// Initializes a new instance of .
+ /// Max quota.
+ /// Quota accrual rate per second.
+ internal QuotaConfigurationInfo(float maxQuota, float quotaAccrualRatePerSec)
+ {
+ MaxQuota = maxQuota;
+ QuotaAccrualRatePerSec = quotaAccrualRatePerSec;
+ }
+
+ /// Initializes a new instance of .
+ /// Initial quota.
+ /// Max quota.
+ /// Quota accrual rate per second.
+ internal QuotaConfigurationInfo(float? initialQuota, float maxQuota, float quotaAccrualRatePerSec)
+ {
+ InitialQuota = initialQuota;
+ MaxQuota = maxQuota;
+ QuotaAccrualRatePerSec = quotaAccrualRatePerSec;
+ }
+
+ /// Initial quota.
+ public float? InitialQuota { get; }
+ /// Max quota.
+ public float MaxQuota { get; }
+ /// Quota accrual rate per second.
+ public float QuotaAccrualRatePerSec { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/RemoteDependency.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/RemoteDependency.Serialization.cs
new file mode 100644
index 0000000000000..4f1be14a41601
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/RemoteDependency.Serialization.cs
@@ -0,0 +1,71 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class RemoteDependency : IUtf8JsonSerializable
+ {
+ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
+ {
+ writer.WriteStartObject();
+ if (Optional.IsDefined(Name))
+ {
+ writer.WritePropertyName("Name"u8);
+ writer.WriteStringValue(Name);
+ }
+ if (Optional.IsDefined(CommandName))
+ {
+ writer.WritePropertyName("CommandName"u8);
+ writer.WriteStringValue(CommandName);
+ }
+ if (Optional.IsDefined(ResultCode))
+ {
+ writer.WritePropertyName("ResultCode"u8);
+ writer.WriteStringValue(ResultCode);
+ }
+ if (Optional.IsDefined(Duration))
+ {
+ writer.WritePropertyName("Duration"u8);
+ writer.WriteStringValue(Duration);
+ }
+ writer.WritePropertyName("DocumentType"u8);
+ writer.WriteStringValue(DocumentType.ToString());
+ if (Optional.IsCollectionDefined(DocumentStreamIds))
+ {
+ writer.WritePropertyName("DocumentStreamIds"u8);
+ writer.WriteStartArray();
+ foreach (var item in DocumentStreamIds)
+ {
+ writer.WriteStringValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ if (Optional.IsCollectionDefined(Properties))
+ {
+ writer.WritePropertyName("Properties"u8);
+ writer.WriteStartArray();
+ foreach (var item in Properties)
+ {
+ writer.WriteObjectValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ writer.WriteEndObject();
+ }
+
+ /// Convert into a .
+ internal override RequestContent ToRequestContent()
+ {
+ var content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteObjectValue(this);
+ return content;
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/RemoteDependency.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/RemoteDependency.cs
new file mode 100644
index 0000000000000..bdf92382863b0
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/RemoteDependency.cs
@@ -0,0 +1,47 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Collections.Generic;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// RemoteDependency document type.
+ internal partial class RemoteDependency : DocumentIngress
+ {
+ /// Initializes a new instance of .
+ public RemoteDependency()
+ {
+ DocumentType = DocumentType.RemoteDependency;
+ }
+
+ /// Initializes a new instance of .
+ /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type.
+ /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers.
+ /// Collection of custom properties.
+ /// Name of the command initiated with this dependency call, e.g., GET /username.
+ /// URL of the dependency call to the target, with all query string parameters.
+ /// Result code of a dependency call. Examples are SQL error code and HTTP status code.
+ /// Request duration in ISO 8601 duration format, i.e., P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W.
+ internal RemoteDependency(DocumentType documentType, IList documentStreamIds, IList properties, string name, string commandName, string resultCode, string duration) : base(documentType, documentStreamIds, properties)
+ {
+ Name = name;
+ CommandName = commandName;
+ ResultCode = resultCode;
+ Duration = duration;
+ DocumentType = documentType;
+ }
+
+ /// Name of the command initiated with this dependency call, e.g., GET /username.
+ public string Name { get; set; }
+ /// URL of the dependency call to the target, with all query string parameters.
+ public string CommandName { get; set; }
+ /// Result code of a dependency call. Examples are SQL error code and HTTP status code.
+ public string ResultCode { get; set; }
+ /// Request duration in ISO 8601 duration format, i.e., P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W.
+ public string Duration { get; set; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Request.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Request.Serialization.cs
new file mode 100644
index 0000000000000..b764d499e60bd
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Request.Serialization.cs
@@ -0,0 +1,71 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class Request : IUtf8JsonSerializable
+ {
+ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
+ {
+ writer.WriteStartObject();
+ if (Optional.IsDefined(Name))
+ {
+ writer.WritePropertyName("Name"u8);
+ writer.WriteStringValue(Name);
+ }
+ if (Optional.IsDefined(Url))
+ {
+ writer.WritePropertyName("Url"u8);
+ writer.WriteStringValue(Url.AbsoluteUri);
+ }
+ if (Optional.IsDefined(ResponseCode))
+ {
+ writer.WritePropertyName("ResponseCode"u8);
+ writer.WriteStringValue(ResponseCode);
+ }
+ if (Optional.IsDefined(Duration))
+ {
+ writer.WritePropertyName("Duration"u8);
+ writer.WriteStringValue(Duration);
+ }
+ writer.WritePropertyName("DocumentType"u8);
+ writer.WriteStringValue(DocumentType.ToString());
+ if (Optional.IsCollectionDefined(DocumentStreamIds))
+ {
+ writer.WritePropertyName("DocumentStreamIds"u8);
+ writer.WriteStartArray();
+ foreach (var item in DocumentStreamIds)
+ {
+ writer.WriteStringValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ if (Optional.IsCollectionDefined(Properties))
+ {
+ writer.WritePropertyName("Properties"u8);
+ writer.WriteStartArray();
+ foreach (var item in Properties)
+ {
+ writer.WriteObjectValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ writer.WriteEndObject();
+ }
+
+ /// Convert into a .
+ internal override RequestContent ToRequestContent()
+ {
+ var content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteObjectValue(this);
+ return content;
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Request.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Request.cs
new file mode 100644
index 0000000000000..4dc10467a7c81
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Request.cs
@@ -0,0 +1,48 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Request document type.
+ internal partial class Request : DocumentIngress
+ {
+ /// Initializes a new instance of .
+ public Request()
+ {
+ DocumentType = DocumentType.Request;
+ }
+
+ /// Initializes a new instance of .
+ /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type.
+ /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers.
+ /// Collection of custom properties.
+ /// Name of the request, e.g., 'GET /values/{id}'.
+ /// Request URL with all query string parameters.
+ /// Result of a request execution. For http requests, it could be some HTTP status code.
+ /// Request duration in ISO 8601 duration format, i.e., P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W.
+ internal Request(DocumentType documentType, IList documentStreamIds, IList properties, string name, Uri url, string responseCode, string duration) : base(documentType, documentStreamIds, properties)
+ {
+ Name = name;
+ Url = url;
+ ResponseCode = responseCode;
+ Duration = duration;
+ DocumentType = documentType;
+ }
+
+ /// Name of the request, e.g., 'GET /values/{id}'.
+ public string Name { get; set; }
+ /// Request URL with all query string parameters.
+ public Uri Url { get; set; }
+ /// Result of a request execution. For http requests, it could be some HTTP status code.
+ public string ResponseCode { get; set; }
+ /// Request duration in ISO 8601 duration format, i.e., P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W.
+ public string Duration { get; set; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ServiceError.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ServiceError.Serialization.cs
new file mode 100644
index 0000000000000..de36722eb0ad8
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ServiceError.Serialization.cs
@@ -0,0 +1,64 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class ServiceError
+ {
+ internal static ServiceError DeserializeServiceError(JsonElement element)
+ {
+ if (element.ValueKind == JsonValueKind.Null)
+ {
+ return null;
+ }
+ string requestId = default;
+ string responseDateTime = default;
+ string code = default;
+ string message = default;
+ string exception = default;
+ foreach (var property in element.EnumerateObject())
+ {
+ if (property.NameEquals("RequestId"u8))
+ {
+ requestId = property.Value.GetString();
+ continue;
+ }
+ if (property.NameEquals("ResponseDateTime"u8))
+ {
+ responseDateTime = property.Value.GetString();
+ continue;
+ }
+ if (property.NameEquals("Code"u8))
+ {
+ code = property.Value.GetString();
+ continue;
+ }
+ if (property.NameEquals("Message"u8))
+ {
+ message = property.Value.GetString();
+ continue;
+ }
+ if (property.NameEquals("Exception"u8))
+ {
+ exception = property.Value.GetString();
+ continue;
+ }
+ }
+ return new ServiceError(requestId, responseDateTime, code, message, exception);
+ }
+
+ /// Deserializes the model from a raw response.
+ /// The response to deserialize the model from.
+ internal static ServiceError FromResponse(Response response)
+ {
+ using var document = JsonDocument.Parse(response.Content);
+ return DeserializeServiceError(document.RootElement);
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ServiceError.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ServiceError.cs
new file mode 100644
index 0000000000000..a4ca56c39489b
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/ServiceError.cs
@@ -0,0 +1,48 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Optional http response body, whose existence carries additional error descriptions.
+ internal partial class ServiceError
+ {
+ /// Initializes a new instance of .
+ /// A globally unique identifier to identify the diagnostic context. It defaults to the empty GUID.
+ /// Service error response date time.
+ /// Error code.
+ /// Error message.
+ /// Message of the exception that triggers the error response.
+ /// , , , or is null.
+ internal ServiceError(string requestId, string responseDateTime, string code, string message, string exception)
+ {
+ Argument.AssertNotNull(requestId, nameof(requestId));
+ Argument.AssertNotNull(responseDateTime, nameof(responseDateTime));
+ Argument.AssertNotNull(code, nameof(code));
+ Argument.AssertNotNull(message, nameof(message));
+ Argument.AssertNotNull(exception, nameof(exception));
+
+ RequestId = requestId;
+ ResponseDateTime = responseDateTime;
+ Code = code;
+ Message = message;
+ Exception = exception;
+ }
+
+ /// A globally unique identifier to identify the diagnostic context. It defaults to the empty GUID.
+ public string RequestId { get; }
+ /// Service error response date time.
+ public string ResponseDateTime { get; }
+ /// Error code.
+ public string Code { get; }
+ /// Error message.
+ public string Message { get; }
+ /// Message of the exception that triggers the error response.
+ public string Exception { get; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/TelemetryType.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/TelemetryType.cs
new file mode 100644
index 0000000000000..3033ee40dbaa1
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/TelemetryType.cs
@@ -0,0 +1,66 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+using System.ComponentModel;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Telemetry type.
+ internal readonly partial struct TelemetryType : IEquatable
+ {
+ private readonly string _value;
+
+ /// Initializes a new instance of .
+ /// is null.
+ public TelemetryType(string value)
+ {
+ _value = value ?? throw new ArgumentNullException(nameof(value));
+ }
+
+ private const string RequestValue = "Request";
+ private const string DependencyValue = "Dependency";
+ private const string ExceptionValue = "Exception";
+ private const string EventValue = "Event";
+ private const string MetricValue = "Metric";
+ private const string PerformanceCounterValue = "PerformanceCounter";
+ private const string TraceValue = "Trace";
+
+ /// Represents a request telemetry type.
+ public static TelemetryType Request { get; } = new TelemetryType(RequestValue);
+ /// Represents a dependency telemetry type.
+ public static TelemetryType Dependency { get; } = new TelemetryType(DependencyValue);
+ /// Represents an exception telemetry type.
+ public static TelemetryType Exception { get; } = new TelemetryType(ExceptionValue);
+ /// Represents an event telemetry type.
+ public static TelemetryType Event { get; } = new TelemetryType(EventValue);
+ /// Represents a metric telemetry type.
+ public static TelemetryType Metric { get; } = new TelemetryType(MetricValue);
+ /// Represents a performance counter telemetry type.
+ public static TelemetryType PerformanceCounter { get; } = new TelemetryType(PerformanceCounterValue);
+ /// Represents a trace telemetry type.
+ public static TelemetryType Trace { get; } = new TelemetryType(TraceValue);
+ /// Determines if two values are the same.
+ public static bool operator ==(TelemetryType left, TelemetryType right) => left.Equals(right);
+ /// Determines if two values are not the same.
+ public static bool operator !=(TelemetryType left, TelemetryType right) => !left.Equals(right);
+ /// Converts a string to a .
+ public static implicit operator TelemetryType(string value) => new TelemetryType(value);
+
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is TelemetryType other && Equals(other);
+ ///
+ public bool Equals(TelemetryType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
+
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0;
+ ///
+ public override string ToString() => _value;
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Trace.Serialization.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Trace.Serialization.cs
new file mode 100644
index 0000000000000..97cef47d2b155
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Trace.Serialization.cs
@@ -0,0 +1,56 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Text.Json;
+using Azure.Core;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ internal partial class Trace : IUtf8JsonSerializable
+ {
+ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
+ {
+ writer.WriteStartObject();
+ if (Optional.IsDefined(Message))
+ {
+ writer.WritePropertyName("Message"u8);
+ writer.WriteStringValue(Message);
+ }
+ writer.WritePropertyName("DocumentType"u8);
+ writer.WriteStringValue(DocumentType.ToString());
+ if (Optional.IsCollectionDefined(DocumentStreamIds))
+ {
+ writer.WritePropertyName("DocumentStreamIds"u8);
+ writer.WriteStartArray();
+ foreach (var item in DocumentStreamIds)
+ {
+ writer.WriteStringValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ if (Optional.IsCollectionDefined(Properties))
+ {
+ writer.WritePropertyName("Properties"u8);
+ writer.WriteStartArray();
+ foreach (var item in Properties)
+ {
+ writer.WriteObjectValue(item);
+ }
+ writer.WriteEndArray();
+ }
+ writer.WriteEndObject();
+ }
+
+ /// Convert into a .
+ internal override RequestContent ToRequestContent()
+ {
+ var content = new Utf8JsonRequestContent();
+ content.JsonWriter.WriteObjectValue(this);
+ return content;
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Trace.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Trace.cs
new file mode 100644
index 0000000000000..8e57c03ae6f45
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/Generated/Models/Trace.cs
@@ -0,0 +1,35 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System.Collections.Generic;
+
+namespace Azure.Monitor.OpenTelemetry.LiveMetrics.Models
+{
+ /// Trace document type.
+ internal partial class Trace : DocumentIngress
+ {
+ /// Initializes a new instance of .
+ public Trace()
+ {
+ DocumentType = DocumentType.Trace;
+ }
+
+ /// Initializes a new instance of .
+ /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type.
+ /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers.
+ /// Collection of custom properties.
+ /// Trace message.
+ internal Trace(DocumentType documentType, IList documentStreamIds, IList properties, string message) : base(documentType, documentStreamIds, properties)
+ {
+ Message = message;
+ DocumentType = documentType;
+ }
+
+ /// Trace message.
+ public string Message { get; set; }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/autorest.md b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/autorest.md
new file mode 100644
index 0000000000000..bcea6e40eeea5
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/src/autorest.md
@@ -0,0 +1,17 @@
+# Generated code configuration
+
+Run `dotnet build /t:GenerateCode` to generate code.
+
+``` yaml
+input-file:
+ - https://github.com/Azure/azure-rest-api-specs/blob/665e7c3b6f26b148b3c05e55602621bc293cc0a4/specification/applicationinsights/data-plane/LiveMetrics/preview/2024-04-01-preview/livemetrics.json
+generation1-convenience-client: true
+```
+
+``` yaml
+directive:
+- from: swagger-document
+ where: $.definitions.*
+ transform: >
+ $["x-accessibility"]="internal"
+```
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.sln b/sdk/monitor/Azure.Monitor.OpenTelemetry.sln
index 184e404a8a035..a289deb5ff7f5 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.sln
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.sln
@@ -54,7 +54,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Monitor.OpenTelemetry
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Monitor.OpenTelemetry.AspNetCore.Benchmarks", "Azure.Monitor.OpenTelemetry.AspNetCore\tests\AspNetCore.Benchmarks\Azure.Monitor.OpenTelemetry.AspNetCore.Benchmarks.csproj", "{273FDDEB-62E9-4B29-B4C2-5F0F10E9B2C9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.Monitor.AspNetCoreTestApp", "Azure.Monitor.OpenTelemetry.AspNetCore\tests\Azure.Monitor.AspNetCoreTestApp\Azure.Monitor.AspNetCoreTestApp.csproj", "{01657383-7C75-4C0A-9278-61755C4E3DC9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Monitor.AspNetCoreTestApp", "Azure.Monitor.OpenTelemetry.AspNetCore\tests\Azure.Monitor.AspNetCoreTestApp\Azure.Monitor.AspNetCoreTestApp.csproj", "{01657383-7C75-4C0A-9278-61755C4E3DC9}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Monitor.OpenTelemetry.LiveMetrics", "Azure.Monitor.OpenTelemetry.LiveMetrics\src\Azure.Monitor.OpenTelemetry.LiveMetrics.csproj", "{0C961663-8E54-4560-A71A-74D33936586F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -126,6 +128,10 @@ Global
{01657383-7C75-4C0A-9278-61755C4E3DC9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{01657383-7C75-4C0A-9278-61755C4E3DC9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{01657383-7C75-4C0A-9278-61755C4E3DC9}.Release|Any CPU.Build.0 = Release|Any CPU
+ {0C961663-8E54-4560-A71A-74D33936586F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {0C961663-8E54-4560-A71A-74D33936586F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {0C961663-8E54-4560-A71A-74D33936586F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {0C961663-8E54-4560-A71A-74D33936586F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
From ab120de65ff8cdcc6f21c729a46b4eab19d861cc Mon Sep 17 00:00:00 2001
From: Nisha Bhatia <67986960+nisha-bhatia@users.noreply.github.com>
Date: Tue, 20 Aug 2024 17:13:05 -0700
Subject: [PATCH 06/71] [Azure.Monitor.Query] Update LogsQueryClient Audience
logic in constructor (#45429)
---
eng/.docsettings.yml | 1 +
sdk/monitor/Azure.Monitor.Query/CHANGELOG.md | 3 +-
sdk/monitor/Azure.Monitor.Query/README.md | 8 ++-
.../api/Azure.Monitor.Query.netstandard2.0.cs | 2 +
.../src/Azure.Monitor.Query.csproj | 2 +-
.../src/LogsQueryClient.cs | 22 +++++-
.../tests/LogsQueryClientTests.cs | 71 ++++++++++++++++---
.../tests/MetricsQueryClientSamples.cs | 8 ++-
8 files changed, 99 insertions(+), 18 deletions(-)
diff --git a/eng/.docsettings.yml b/eng/.docsettings.yml
index 12545ab0ec1b2..074f72e1f330a 100644
--- a/eng/.docsettings.yml
+++ b/eng/.docsettings.yml
@@ -129,6 +129,7 @@ known_content_issues:
- ['sdk/storage/Azure.Storage.Common/README.md','azure-sdk-tools/issues/404']
- ['sdk/textanalytics/Azure.AI.TextAnalytics.Legacy.Shared/README.md','https://github.com/Azure/azure-sdk-tools/issues/404']
- ['sdk/webpubsub/Azure.Messaging.WebPubSub/README.md', 'azure-sdk-tools/issues/404 - requires different name for auth section']
+ - ['sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/README.md', 'Opt out of sections: https://github.com/Azure/azure-sdk-tools/issues/404']
- ['sdk/anomalydetector/Azure.AI.AnomalyDetector/README.md', '#25936: Needs Examples']
- ['sdk/personalizer/Azure.AI.Personalizer/README.md','#24535: Needs content']
diff --git a/sdk/monitor/Azure.Monitor.Query/CHANGELOG.md b/sdk/monitor/Azure.Monitor.Query/CHANGELOG.md
index 47ba53a66641f..c2c25ee27bd23 100644
--- a/sdk/monitor/Azure.Monitor.Query/CHANGELOG.md
+++ b/sdk/monitor/Azure.Monitor.Query/CHANGELOG.md
@@ -1,12 +1,13 @@
# Release History
-## 1.5.0-beta.1 (Unreleased)
+## 1.5.0 (Unreleased)
### Features Added
### Breaking Changes
### Bugs Fixed
+- Fix bug in `LogsQueryClient` that defaulted to `Azure.PublicCloud`. `Audience` is now determined from the `endpoint` parameter.
### Other Changes
diff --git a/sdk/monitor/Azure.Monitor.Query/README.md b/sdk/monitor/Azure.Monitor.Query/README.md
index 4a00caaee2483..a3f60cb420fbb 100644
--- a/sdk/monitor/Azure.Monitor.Query/README.md
+++ b/sdk/monitor/Azure.Monitor.Query/README.md
@@ -84,12 +84,16 @@ var metricsQueryClient = new MetricsQueryClient(
new DefaultAzureCredential(),
metricsQueryClientOptions);
-// LogsQueryClient
+// LogsQueryClient - by default, Azure Public Cloud is used
+var logsQueryClient = new LogsQueryClient(
+ new DefaultAzureCredential());
+
+// LogsQueryClient With Audience Set
var logsQueryClientOptions = new LogsQueryClientOptions
{
Audience = LogsQueryAudience.AzureChina
};
-var logsQueryClient = new LogsQueryClient(
+var logsQueryClientChina = new LogsQueryClient(
new DefaultAzureCredential(),
logsQueryClientOptions);
```
diff --git a/sdk/monitor/Azure.Monitor.Query/api/Azure.Monitor.Query.netstandard2.0.cs b/sdk/monitor/Azure.Monitor.Query/api/Azure.Monitor.Query.netstandard2.0.cs
index ff2a0bbf96537..41e38f81678e8 100644
--- a/sdk/monitor/Azure.Monitor.Query/api/Azure.Monitor.Query.netstandard2.0.cs
+++ b/sdk/monitor/Azure.Monitor.Query/api/Azure.Monitor.Query.netstandard2.0.cs
@@ -29,7 +29,9 @@ public partial class LogsQueryClient
protected LogsQueryClient() { }
public LogsQueryClient(Azure.Core.TokenCredential credential) { }
public LogsQueryClient(Azure.Core.TokenCredential credential, Azure.Monitor.Query.LogsQueryClientOptions options) { }
+ [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public LogsQueryClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { }
+ [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public LogsQueryClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Monitor.Query.LogsQueryClientOptions options) { }
public System.Uri Endpoint { get { throw null; } }
public static string CreateQuery(System.FormattableString query) { throw null; }
diff --git a/sdk/monitor/Azure.Monitor.Query/src/Azure.Monitor.Query.csproj b/sdk/monitor/Azure.Monitor.Query/src/Azure.Monitor.Query.csproj
index 4b98f11baf27c..efd42c3a2bf8c 100644
--- a/sdk/monitor/Azure.Monitor.Query/src/Azure.Monitor.Query.csproj
+++ b/sdk/monitor/Azure.Monitor.Query/src/Azure.Monitor.Query.csproj
@@ -2,7 +2,7 @@
A library for querying Azure Monitor's Logs and Metrics data sources.
Azure Monitor Query client library
- 1.5.0-beta.1
+ 1.5.0
1.4.0
Azure Monitor Query
diff --git a/sdk/monitor/Azure.Monitor.Query/src/LogsQueryClient.cs b/sdk/monitor/Azure.Monitor.Query/src/LogsQueryClient.cs
index d0b91a607cdc4..1d22fe76060e4 100644
--- a/sdk/monitor/Azure.Monitor.Query/src/LogsQueryClient.cs
+++ b/sdk/monitor/Azure.Monitor.Query/src/LogsQueryClient.cs
@@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
+using System.ComponentModel;
using System.Globalization;
using System.Text;
using System.Text.Json;
@@ -56,6 +57,7 @@ public LogsQueryClient(TokenCredential credential, LogsQueryClientOptions option
///
/// The service endpoint to use.
/// The instance to use for authentication.
+ [EditorBrowsable(EditorBrowsableState.Never)]
public LogsQueryClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, null)
{
}
@@ -66,6 +68,7 @@ public LogsQueryClient(Uri endpoint, TokenCredential credential) : this(endpoint
/// The service endpoint to use.
/// The instance to use for authentication.
/// The instance to use as client configuration.
+ [EditorBrowsable(EditorBrowsableState.Never)]
public LogsQueryClient(Uri endpoint, TokenCredential credential, LogsQueryClientOptions options)
{
Argument.AssertNotNull(credential, nameof(credential));
@@ -73,8 +76,23 @@ public LogsQueryClient(Uri endpoint, TokenCredential credential, LogsQueryClient
Endpoint = endpoint;
options ??= new LogsQueryClientOptions();
- var authorizationScope = $"{(string.IsNullOrEmpty(options.Audience?.ToString()) ? LogsQueryAudience.AzurePublicCloud : options.Audience)}";
- authorizationScope += "//.default";
+
+ // Set authorization scope from Endpoint if Audience is not set.
+ string authorizationScope = "";
+ if (string.IsNullOrEmpty(options.Audience?.ToString()))
+ {
+ // Endpoint.AbsoluteUri includes an extra / so only adding one here
+ authorizationScope = $"{endpoint.AbsoluteUri}/.default";
+ }
+ else if (endpoint.Host != new Uri(options.Audience.ToString()).Host)
+ {
+ throw new InvalidOperationException("The endpoint URI and audience do not match. If setting the Audience to a regionally specific value, please use the LogsQueryClient(TokenCredential, LogsQueryClientOptions) constructor.");
+ }
+ else
+ {
+ authorizationScope = $"{options.Audience}//.default";
+ }
+
var scopes = new List { authorizationScope };
endpoint = new Uri(endpoint, options.GetVersionString());
diff --git a/sdk/monitor/Azure.Monitor.Query/tests/LogsQueryClientTests.cs b/sdk/monitor/Azure.Monitor.Query/tests/LogsQueryClientTests.cs
index c75bc674bd73a..d2cfdcfd5afb9 100644
--- a/sdk/monitor/Azure.Monitor.Query/tests/LogsQueryClientTests.cs
+++ b/sdk/monitor/Azure.Monitor.Query/tests/LogsQueryClientTests.cs
@@ -287,33 +287,84 @@ public void ValidateMonitorModelFactoryTableCreation()
}
[Test]
- public void Constructor_WhenOptionsIsNull_UsesDefaultEndpoint()
+ public void Constructor_WhenOptionsAndEndpointIsNull_UsesDefaultEndpoint()
{
- // Arrange
var credential = new DefaultAzureCredential();
-
- // Act
var client = new LogsQueryClient(credential);
-
- // Assert
Assert.AreEqual(LogsQueryAudience.AzurePublicCloud.ToString(), client.Endpoint.OriginalString);
}
[Test]
- public void Constructor_WhenOptionsIsNotNull_UsesOptionsAudience()
+ public void Constructor_WhenEndpointIsNull_UsesOptionsAudience()
{
- // Arrange
var credential = new DefaultAzureCredential();
var options = new LogsQueryClientOptions
{
Audience = "https://custom.audience"
};
- // Act
var client = new LogsQueryClient(credential, options);
- // Assert
+ // When endpoint is not passed in, use Audience to contstruct the endpoint
Assert.AreEqual("https://custom.audience", client.Endpoint.OriginalString);
}
+
+ [Test]
+ public void Constructor_WhenOptionsDoesNotMatchAudience()
+ {
+ var endpoint = new Uri("https://custom.audience");
+ var credential = new DefaultAzureCredential();
+ var options = new LogsQueryClientOptions
+ {
+ Audience = "https://customs.audience"
+ };
+
+ Assert.ThrowsAsync(async () => await Task.Run(() => new LogsQueryClient(endpoint, credential, options)));
+ }
+
+ [Test]
+ public void Constructor_WhenOptionsIsNull_UsesEndpoint()
+ {
+ var endpoint = new Uri("https://custom.audience");
+ var credential = new DefaultAzureCredential();
+
+ var client = new LogsQueryClient(endpoint, credential);
+
+ Assert.AreEqual(new Uri("https://custom.audience"), client.Endpoint);
+ }
+
+ [Test]
+ public void Constructor_WhenOptionsIsNull_UsesEndpointSlash()
+ {
+ var endpoint = new Uri("https://custom.audience//");
+ var credential = new DefaultAzureCredential();
+
+ var client = new LogsQueryClient(endpoint, credential);
+
+ Assert.AreEqual("https://custom.audience//", client.Endpoint.AbsoluteUri);
+ }
+
+ [Test]
+ public void Constructor_WhenOptionsIsValid_UsesOptionsAsUri()
+ {
+ var credential = new DefaultAzureCredential();
+ var options = new LogsQueryClientOptions
+ {
+ Audience = LogsQueryAudience.AzureGovernment
+ };
+
+ var client = new LogsQueryClient(credential, options);
+
+ Assert.AreEqual(new Uri(LogsQueryAudience.AzureGovernment.ToString()), client.Endpoint);
+ }
+
+ [Test]
+ public void Constructor_WhenOptionsIsNull_EndpointIsNull()
+ {
+ var credential = new DefaultAzureCredential();
+ var client = new LogsQueryClient(credential);
+
+ Assert.AreEqual(new Uri(LogsQueryAudience.AzurePublicCloud.ToString()), client.Endpoint);
+ }
}
}
diff --git a/sdk/monitor/Azure.Monitor.Query/tests/MetricsQueryClientSamples.cs b/sdk/monitor/Azure.Monitor.Query/tests/MetricsQueryClientSamples.cs
index 3dad319381b7b..323e2985aa52d 100644
--- a/sdk/monitor/Azure.Monitor.Query/tests/MetricsQueryClientSamples.cs
+++ b/sdk/monitor/Azure.Monitor.Query/tests/MetricsQueryClientSamples.cs
@@ -293,12 +293,16 @@ public void CreateClientsWithOptions()
new DefaultAzureCredential(),
metricsQueryClientOptions);
- // LogsQueryClient
+ // LogsQueryClient - by default, Azure Public Cloud is used
+ var logsQueryClient = new LogsQueryClient(
+ new DefaultAzureCredential());
+
+ // LogsQueryClient With Audience Set
var logsQueryClientOptions = new LogsQueryClientOptions
{
Audience = LogsQueryAudience.AzureChina
};
- var logsQueryClient = new LogsQueryClient(
+ var logsQueryClientChina = new LogsQueryClient(
new DefaultAzureCredential(),
logsQueryClientOptions);
#endregion
From 3467964109500e3a1029e64df30d4fd67947dd6e Mon Sep 17 00:00:00 2001
From: Christopher Scott
Date: Wed, 21 Aug 2024 12:28:02 -0500
Subject: [PATCH 07/71] Add parameter-less ctor to TableSasBulder (#45569)
---
sdk/tables/Azure.Data.Tables/CHANGELOG.md | 2 +-
.../api/Azure.Data.Tables.netstandard2.0.cs | 2 +-
.../src/Sas/TableSasBuilder.cs | 21 +++++++------------
.../tests/TableSasBuilderTests.cs | 17 ++++++++++++++-
4 files changed, 26 insertions(+), 16 deletions(-)
diff --git a/sdk/tables/Azure.Data.Tables/CHANGELOG.md b/sdk/tables/Azure.Data.Tables/CHANGELOG.md
index 7501c001fab4f..1484234d0d3d0 100644
--- a/sdk/tables/Azure.Data.Tables/CHANGELOG.md
+++ b/sdk/tables/Azure.Data.Tables/CHANGELOG.md
@@ -3,7 +3,7 @@
## 12.9.1 (Unreleased)
### Bugs Fixed
-- Fixed an issue that prevented use of stored access policy based SaS Uris by adding a constructor to `TableSasBuilder` that accepts a stored access policy identifier without needing to specify the policy's permissions.
+- Fixed an issue that prevented use of stored access policy based SaS Uris by adding a parameterless constructor to `TableSasBuilder`. The resulting builder can then be modified to include the stored access policy identifier or any other details.
## 12.9.0 (2024-07-22)
diff --git a/sdk/tables/Azure.Data.Tables/api/Azure.Data.Tables.netstandard2.0.cs b/sdk/tables/Azure.Data.Tables/api/Azure.Data.Tables.netstandard2.0.cs
index 2dca760a2c9ff..3af47f771edc5 100644
--- a/sdk/tables/Azure.Data.Tables/api/Azure.Data.Tables.netstandard2.0.cs
+++ b/sdk/tables/Azure.Data.Tables/api/Azure.Data.Tables.netstandard2.0.cs
@@ -418,8 +418,8 @@ public enum TableAccountSasResourceTypes
}
public partial class TableSasBuilder
{
+ public TableSasBuilder() { }
public TableSasBuilder(string tableName, Azure.Data.Tables.Sas.TableSasPermissions permissions, System.DateTimeOffset expiresOn) { }
- public TableSasBuilder(string tableName, string identifier) { }
public TableSasBuilder(string tableName, string rawPermissions, System.DateTimeOffset expiresOn) { }
public TableSasBuilder(System.Uri sasUri) { }
public System.DateTimeOffset ExpiresOn { get { throw null; } set { } }
diff --git a/sdk/tables/Azure.Data.Tables/src/Sas/TableSasBuilder.cs b/sdk/tables/Azure.Data.Tables/src/Sas/TableSasBuilder.cs
index 8fa8b04f3a26c..993577e915b28 100644
--- a/sdk/tables/Azure.Data.Tables/src/Sas/TableSasBuilder.cs
+++ b/sdk/tables/Azure.Data.Tables/src/Sas/TableSasBuilder.cs
@@ -47,20 +47,13 @@ public TableSasBuilder(string tableName, string rawPermissions, DateTimeOffset e
}
///
- /// Initializes an instance of a .
+ /// Initializes an instance of a with no details set. At minimum, additional properties must be set to create a valid SaS.
+ /// These include setting the , permissions, and an expiry. Permissions and expiry can also be specified in a shared access policy, which can be
+ /// selected by specifying the name of the policy on the property.
+ ///
///
- /// The name of the table being made accessible with the shared access signature.
- /// The identifier of the stored access policy that defines the permissions and, optionally, expiry of the shared access signature.
- /// Note: Either the stored access policy specified by the or the created shared access signature must define an expiry.
- /// If neither define an expiry or both do, authentication will fail.
- public TableSasBuilder(string tableName, string identifier)
- {
- Argument.AssertNotNullOrEmpty(tableName, nameof(tableName));
- Argument.AssertNotNullOrEmpty(identifier, nameof(identifier));
-
- TableName = tableName;
- Identifier = identifier;
- }
+ public TableSasBuilder()
+ { }
///
/// Initializes a new instance of based on an existing Uri containing a shared access signature.
@@ -133,6 +126,8 @@ public TableSasBuilder(Uri sasUri)
///
/// An optional unique value up to 64 characters in length that
/// correlates to an access policy specified for the container.
+ /// Note: Either the stored access policy specified by the or the created shared access signature must define an expiry.
+ /// If neither define an expiry or both do, authentication will fail.
///
public string Identifier { get; set; }
diff --git a/sdk/tables/Azure.Data.Tables/tests/TableSasBuilderTests.cs b/sdk/tables/Azure.Data.Tables/tests/TableSasBuilderTests.cs
index 087bc66187f82..3ba75075bce1b 100644
--- a/sdk/tables/Azure.Data.Tables/tests/TableSasBuilderTests.cs
+++ b/sdk/tables/Azure.Data.Tables/tests/TableSasBuilderTests.cs
@@ -17,7 +17,6 @@ public void ValidatesArgs()
Assert.Throws(() => new TableSasBuilder(string.Empty, TableSasPermissions.Add, DateTimeOffset.Now));
Assert.Throws(() => new TableSasBuilder("table", null, DateTimeOffset.Now));
Assert.Throws(() => new TableSasBuilder("table", string.Empty, DateTimeOffset.Now));
- Assert.Throws(() => new TableSasBuilder("table", null));
Assert.Throws(() => new TableSasBuilder(null));
}
@@ -70,5 +69,21 @@ public void SetPermissions(string tableName, string permissionsString, TableSasP
Assert.AreEqual(permissionsString.ToLowerInvariant(), tableSasBuilder.Permissions);
Assert.AreEqual(tableName, tableSasBuilder.TableName);
}
+
+ [Test]
+ public void UseParameterlessCtor()
+ {
+ var now = DateTimeOffset.Now;
+ var tableSasBuilder = new TableSasBuilder
+ {
+ TableName = "table",
+ ExpiresOn = now.AddHours(1)
+ };
+ tableSasBuilder.SetPermissions(TableSasPermissions.Read);
+
+ Assert.AreEqual("table", tableSasBuilder.TableName);
+ Assert.AreEqual("r", tableSasBuilder.Permissions);
+ Assert.AreEqual(now.AddHours(1), tableSasBuilder.ExpiresOn);
+ }
}
}
From 3e68f387ac8db7f164b74b1d68ab8c228136851f Mon Sep 17 00:00:00 2001
From: Nisha Bhatia <67986960+nisha-bhatia@users.noreply.github.com>
Date: Wed, 21 Aug 2024 11:38:30 -0700
Subject: [PATCH 08/71] [Azure.Monitor.Query] Prepare for release 1.5.0
(#45610)
---
sdk/monitor/Azure.Monitor.Query/CHANGELOG.md | 9 +--------
1 file changed, 1 insertion(+), 8 deletions(-)
diff --git a/sdk/monitor/Azure.Monitor.Query/CHANGELOG.md b/sdk/monitor/Azure.Monitor.Query/CHANGELOG.md
index c2c25ee27bd23..0a89caae8b39c 100644
--- a/sdk/monitor/Azure.Monitor.Query/CHANGELOG.md
+++ b/sdk/monitor/Azure.Monitor.Query/CHANGELOG.md
@@ -1,16 +1,9 @@
# Release History
-## 1.5.0 (Unreleased)
-
-### Features Added
-
-### Breaking Changes
-
+## 1.5.0 (2024-08-21)
### Bugs Fixed
- Fix bug in `LogsQueryClient` that defaulted to `Azure.PublicCloud`. `Audience` is now determined from the `endpoint` parameter.
-### Other Changes
-
## 1.4.0 (2024-06-12)
### Features Added
From 985aff3df6ca7b073d4a95cf153d485d19bcda87 Mon Sep 17 00:00:00 2001
From: JoshLove-msft <54595583+JoshLove-msft@users.noreply.github.com>
Date: Wed, 21 Aug 2024 12:57:37 -0700
Subject: [PATCH 09/71] Prepare for release (#45565)
---
.../Azure.Messaging.EventGrid/CHANGELOG.md | 9 +--
...zure.Messaging.EventGrid.netstandard2.0.cs | 28 +++++++++
.../src/Azure.Messaging.EventGrid.csproj | 2 +-
.../Customization/EventGridModelFactory.cs | 63 +++++++++++++++++++
.../src/Generated/EventGridModelFactory.cs | 10 ++-
.../Generated/Models/StorageBlobAccessTier.cs | 60 ++++++++++++++++++
...orageBlobCreatedEventData.Serialization.cs | 7 +++
.../Models/StorageBlobCreatedEventData.cs | 10 ++-
...eBlobTierChangedEventData.Serialization.cs | 14 +++++
.../Models/StorageBlobTierChangedEventData.cs | 16 ++++-
.../Azure.Messaging.EventGrid/src/autorest.md | 2 +-
11 files changed, 207 insertions(+), 14 deletions(-)
create mode 100644 sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobAccessTier.cs
diff --git a/sdk/eventgrid/Azure.Messaging.EventGrid/CHANGELOG.md b/sdk/eventgrid/Azure.Messaging.EventGrid/CHANGELOG.md
index 952bebd6a3220..fbf2a31af9515 100644
--- a/sdk/eventgrid/Azure.Messaging.EventGrid/CHANGELOG.md
+++ b/sdk/eventgrid/Azure.Messaging.EventGrid/CHANGELOG.md
@@ -1,14 +1,11 @@
# Release History
-## 4.25.0-beta.1 (Unreleased)
+## 4.25.0 (2024-08-21)
### Features Added
-### Breaking Changes
-
-### Bugs Fixed
-
-### Other Changes
+- Added `AccessTier` and `PreviousTier` properties to `StorageBlobTierChangedEventData` system event.
+- Added `AccessTier` to `StorageBlobCreatedEventData` system event.
## 4.24.1 (2024-07-16)
diff --git a/sdk/eventgrid/Azure.Messaging.EventGrid/api/Azure.Messaging.EventGrid.netstandard2.0.cs b/sdk/eventgrid/Azure.Messaging.EventGrid/api/Azure.Messaging.EventGrid.netstandard2.0.cs
index 7f385c8ad2d42..86c1f7f8124e2 100644
--- a/sdk/eventgrid/Azure.Messaging.EventGrid/api/Azure.Messaging.EventGrid.netstandard2.0.cs
+++ b/sdk/eventgrid/Azure.Messaging.EventGrid/api/Azure.Messaging.EventGrid.netstandard2.0.cs
@@ -341,10 +341,14 @@ public static partial class EventGridModelFactory
public static Azure.Messaging.EventGrid.SystemEvents.SignalRServiceClientConnectionConnectedEventData SignalRServiceClientConnectionConnectedEventData(System.DateTimeOffset? timestamp = default(System.DateTimeOffset?), string hubName = null, string connectionId = null, string userId = null) { throw null; }
public static Azure.Messaging.EventGrid.SystemEvents.SignalRServiceClientConnectionDisconnectedEventData SignalRServiceClientConnectionDisconnectedEventData(System.DateTimeOffset? timestamp = default(System.DateTimeOffset?), string hubName = null, string connectionId = null, string userId = null, string errorMessage = null) { throw null; }
public static Azure.Messaging.EventGrid.SystemEvents.StorageAsyncOperationInitiatedEventData StorageAsyncOperationInitiatedEventData(string api = null, string clientRequestId = null, string requestId = null, string contentType = null, long? contentLength = default(long?), string blobType = null, string url = null, string sequencer = null, string identity = null, object storageDiagnostics = null) { throw null; }
+ public static Azure.Messaging.EventGrid.SystemEvents.StorageBlobCreatedEventData StorageBlobCreatedEventData(string api = null, string clientRequestId = null, string requestId = null, string eTag = null, string contentType = null, long? contentLength = default(long?), long? contentOffset = default(long?), string blobType = null, Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier accessTier = default(Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier), string url = null, string sequencer = null, string identity = null, object storageDiagnostics = null) { throw null; }
+ [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static Azure.Messaging.EventGrid.SystemEvents.StorageBlobCreatedEventData StorageBlobCreatedEventData(string api = null, string clientRequestId = null, string requestId = null, string eTag = null, string contentType = null, long? contentLength = default(long?), long? contentOffset = default(long?), string blobType = null, string url = null, string sequencer = null, string identity = null, object storageDiagnostics = null) { throw null; }
public static Azure.Messaging.EventGrid.SystemEvents.StorageBlobDeletedEventData StorageBlobDeletedEventData(string api = null, string clientRequestId = null, string requestId = null, string contentType = null, string blobType = null, string url = null, string sequencer = null, string identity = null, object storageDiagnostics = null) { throw null; }
public static Azure.Messaging.EventGrid.SystemEvents.StorageBlobInventoryPolicyCompletedEventData StorageBlobInventoryPolicyCompletedEventData(System.DateTimeOffset? scheduleDateTime = default(System.DateTimeOffset?), string accountName = null, string ruleName = null, string policyRunStatus = null, string policyRunStatusMessage = null, string policyRunId = null, string manifestBlobUrl = null) { throw null; }
public static Azure.Messaging.EventGrid.SystemEvents.StorageBlobRenamedEventData StorageBlobRenamedEventData(string api = null, string clientRequestId = null, string requestId = null, string sourceUrl = null, string destinationUrl = null, string sequencer = null, string identity = null, object storageDiagnostics = null) { throw null; }
+ public static Azure.Messaging.EventGrid.SystemEvents.StorageBlobTierChangedEventData StorageBlobTierChangedEventData(string api = null, string clientRequestId = null, string requestId = null, string contentType = null, long? contentLength = default(long?), string blobType = null, Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier accessTier = default(Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier), Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier previousTier = default(Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier), string url = null, string sequencer = null, string identity = null, object storageDiagnostics = null) { throw null; }
+ [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static Azure.Messaging.EventGrid.SystemEvents.StorageBlobTierChangedEventData StorageBlobTierChangedEventData(string api = null, string clientRequestId = null, string requestId = null, string contentType = null, long? contentLength = default(long?), string blobType = null, string url = null, string sequencer = null, string identity = null, object storageDiagnostics = null) { throw null; }
public static Azure.Messaging.EventGrid.SystemEvents.StorageDirectoryCreatedEventData StorageDirectoryCreatedEventData(string api = null, string clientRequestId = null, string requestId = null, string eTag = null, string url = null, string sequencer = null, string identity = null, object storageDiagnostics = null) { throw null; }
public static Azure.Messaging.EventGrid.SystemEvents.StorageDirectoryDeletedEventData StorageDirectoryDeletedEventData(string api = null, string clientRequestId = null, string requestId = null, string url = null, bool? recursive = default(bool?), string sequencer = null, string identity = null, object storageDiagnostics = null) { throw null; }
@@ -3375,9 +3379,31 @@ internal StorageAsyncOperationInitiatedEventData() { }
public object StorageDiagnostics { get { throw null; } }
public string Url { get { throw null; } }
}
+ [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
+ public readonly partial struct StorageBlobAccessTier : System.IEquatable
+ {
+ private readonly object _dummy;
+ private readonly int _dummyPrimitive;
+ public StorageBlobAccessTier(string value) { throw null; }
+ public static Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier Archive { get { throw null; } }
+ public static Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier Cold { get { throw null; } }
+ public static Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier Cool { get { throw null; } }
+ public static Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier Default { get { throw null; } }
+ public static Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier Hot { get { throw null; } }
+ public bool Equals(Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier other) { throw null; }
+ [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
+ public override bool Equals(object obj) { throw null; }
+ [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
+ public override int GetHashCode() { throw null; }
+ public static bool operator ==(Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier left, Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier right) { throw null; }
+ public static implicit operator Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier (string value) { throw null; }
+ public static bool operator !=(Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier left, Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier right) { throw null; }
+ public override string ToString() { throw null; }
+ }
public partial class StorageBlobCreatedEventData
{
internal StorageBlobCreatedEventData() { }
+ public Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier AccessTier { get { throw null; } }
public string Api { get { throw null; } }
public string BlobType { get { throw null; } }
public string ClientRequestId { get { throw null; } }
@@ -3430,12 +3456,14 @@ internal StorageBlobRenamedEventData() { }
public partial class StorageBlobTierChangedEventData
{
internal StorageBlobTierChangedEventData() { }
+ public Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier AccessTier { get { throw null; } }
public string Api { get { throw null; } }
public string BlobType { get { throw null; } }
public string ClientRequestId { get { throw null; } }
public long? ContentLength { get { throw null; } }
public string ContentType { get { throw null; } }
public string Identity { get { throw null; } }
+ public Azure.Messaging.EventGrid.SystemEvents.StorageBlobAccessTier PreviousTier { get { throw null; } }
public string RequestId { get { throw null; } }
public string Sequencer { get { throw null; } }
public object StorageDiagnostics { get { throw null; } }
diff --git a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Azure.Messaging.EventGrid.csproj b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Azure.Messaging.EventGrid.csproj
index 2d3d6f8ea6a63..e26f900ed4971 100644
--- a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Azure.Messaging.EventGrid.csproj
+++ b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Azure.Messaging.EventGrid.csproj
@@ -2,7 +2,7 @@
This library can be used to publish events to Azure Event Grid and to consume events delivered by EventGrid. It also defines the event schemas for the events published to EventGrid by various Azure services.
Microsoft Azure.Messaging.EventGrid client library
- 4.25.0-beta.1
+ 4.25.0
4.24.1
Microsoft Azure EventGrid;Event Grid;Event Grid Publishing;
diff --git a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Customization/EventGridModelFactory.cs b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Customization/EventGridModelFactory.cs
index a365f2da88484..c74913724cf12 100644
--- a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Customization/EventGridModelFactory.cs
+++ b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Customization/EventGridModelFactory.cs
@@ -726,6 +726,69 @@ public static CommunicationIdentifierModel CommunicationIdentifierModel(string r
{
return new CommunicationIdentifierModel(default, rawId, communicationUser, phoneNumber, microsoftTeamsUser, default);
}
+
+ /// Initializes a new instance of .
+ /// The name of the API/operation that triggered this event.
+ /// A request id provided by the client of the storage API operation that triggered this event.
+ /// The request id generated by the Storage service for the storage API operation that triggered this event.
+ /// The etag of the blob at the time this event was triggered.
+ /// The content type of the blob. This is the same as what would be returned in the Content-Type header from the blob.
+ /// The size of the blob in bytes. This is the same as what would be returned in the Content-Length header from the blob.
+ /// The offset of the blob in bytes.
+ /// The type of blob.
+ /// The path to the blob.
+ /// An opaque string value representing the logical sequence of events for any particular blob name. Users can use standard string comparison to understand the relative sequence of two events on the same blob name.
+ /// The identity of the requester that triggered this event.
+ /// For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be ignored by event consumers.
+ /// A new instance for mocking.
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static StorageBlobCreatedEventData StorageBlobCreatedEventData(
+ string api = null,
+ string clientRequestId = null,
+ string requestId = null,
+ string eTag = null,
+ string contentType = null,
+ long? contentLength = null,
+ long? contentOffset = null,
+ string blobType = null,
+ string url = null,
+ string sequencer = null,
+ string identity = null,
+ object storageDiagnostics = null)
+ {
+ return StorageBlobCreatedEventData(api, clientRequestId, requestId, eTag, contentType, contentLength,
+ contentOffset, blobType, null, url, sequencer, identity, storageDiagnostics);
+ }
+
+ /// Initializes a new instance of .
+ /// The name of the API/operation that triggered this event.
+ /// A request id provided by the client of the storage API operation that triggered this event.
+ /// The request id generated by the Storage service for the storage API operation that triggered this event.
+ /// The content type of the blob. This is the same as what would be returned in the Content-Type header from the blob.
+ /// The size of the blob in bytes. This is the same as what would be returned in the Content-Length header from the blob.
+ /// The type of blob.
+ /// The path to the blob.
+ /// An opaque string value representing the logical sequence of events for any particular blob name. Users can use standard string comparison to understand the relative sequence of two events on the same blob name.
+ /// The identity of the requester that triggered this event.
+ /// For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be ignored by event consumers.
+ /// A new instance for mocking.
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static StorageBlobTierChangedEventData StorageBlobTierChangedEventData(string api = null, string clientRequestId = null, string requestId = null, string contentType = null, long? contentLength = null, string blobType = null, string url = null, string sequencer = null, string identity = null, object storageDiagnostics = null)
+ {
+ return StorageBlobTierChangedEventData(
+ api,
+ clientRequestId,
+ requestId,
+ contentType,
+ contentLength,
+ blobType,
+ null,
+ null,
+ url,
+ sequencer,
+ identity,
+ storageDiagnostics);
+ }
}
#pragma warning restore CA1054 // URI-like parameters should not be strings
}
diff --git a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/EventGridModelFactory.cs b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/EventGridModelFactory.cs
index 6c19b5da67ac0..c4aff0098a22c 100644
--- a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/EventGridModelFactory.cs
+++ b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/EventGridModelFactory.cs
@@ -24,12 +24,13 @@ public static partial class EventGridModelFactory
/// The size of the blob in bytes. This is the same as what would be returned in the Content-Length header from the blob.
/// The offset of the blob in bytes.
/// The type of blob.
+ /// The current tier of the blob.
/// The path to the blob.
/// An opaque string value representing the logical sequence of events for any particular blob name. Users can use standard string comparison to understand the relative sequence of two events on the same blob name.
/// The identity of the requester that triggered this event.
/// For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be ignored by event consumers.
/// A new instance for mocking.
- public static StorageBlobCreatedEventData StorageBlobCreatedEventData(string api = null, string clientRequestId = null, string requestId = null, string eTag = null, string contentType = null, long? contentLength = null, long? contentOffset = null, string blobType = null, string url = null, string sequencer = null, string identity = null, object storageDiagnostics = null)
+ public static StorageBlobCreatedEventData StorageBlobCreatedEventData(string api = null, string clientRequestId = null, string requestId = null, string eTag = null, string contentType = null, long? contentLength = null, long? contentOffset = null, string blobType = null, StorageBlobAccessTier accessTier = default, string url = null, string sequencer = null, string identity = null, object storageDiagnostics = null)
{
return new StorageBlobCreatedEventData(
api,
@@ -40,6 +41,7 @@ public static StorageBlobCreatedEventData StorageBlobCreatedEventData(string api
contentLength,
contentOffset,
blobType,
+ accessTier,
url,
sequencer,
identity,
@@ -168,12 +170,14 @@ public static StorageLifecyclePolicyActionSummaryDetail StorageLifecyclePolicyAc
/// The content type of the blob. This is the same as what would be returned in the Content-Type header from the blob.
/// The size of the blob in bytes. This is the same as what would be returned in the Content-Length header from the blob.
/// The type of blob.
+ /// The current tier of the blob.
+ /// The previous tier of the blob.
/// The path to the blob.
/// An opaque string value representing the logical sequence of events for any particular blob name. Users can use standard string comparison to understand the relative sequence of two events on the same blob name.
/// The identity of the requester that triggered this event.
/// For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be ignored by event consumers.
/// A new instance for mocking.
- public static StorageBlobTierChangedEventData StorageBlobTierChangedEventData(string api = null, string clientRequestId = null, string requestId = null, string contentType = null, long? contentLength = null, string blobType = null, string url = null, string sequencer = null, string identity = null, object storageDiagnostics = null)
+ public static StorageBlobTierChangedEventData StorageBlobTierChangedEventData(string api = null, string clientRequestId = null, string requestId = null, string contentType = null, long? contentLength = null, string blobType = null, StorageBlobAccessTier accessTier = default, StorageBlobAccessTier previousTier = default, string url = null, string sequencer = null, string identity = null, object storageDiagnostics = null)
{
return new StorageBlobTierChangedEventData(
api,
@@ -182,6 +186,8 @@ public static StorageBlobTierChangedEventData StorageBlobTierChangedEventData(st
contentType,
contentLength,
blobType,
+ accessTier,
+ previousTier,
url,
sequencer,
identity,
diff --git a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobAccessTier.cs b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobAccessTier.cs
new file mode 100644
index 0000000000000..b5072eac433ac
--- /dev/null
+++ b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobAccessTier.cs
@@ -0,0 +1,60 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//
+
+#nullable disable
+
+using System;
+using System.ComponentModel;
+
+namespace Azure.Messaging.EventGrid.SystemEvents
+{
+ /// The access tier of the blob.
+ public readonly partial struct StorageBlobAccessTier : IEquatable
+ {
+ private readonly string _value;
+
+ /// Initializes a new instance of .
+ /// is null.
+ public StorageBlobAccessTier(string value)
+ {
+ _value = value ?? throw new ArgumentNullException(nameof(value));
+ }
+
+ private const string HotValue = "Hot";
+ private const string CoolValue = "Cool";
+ private const string ColdValue = "Cold";
+ private const string ArchiveValue = "Archive";
+ private const string DefaultValue = "Default";
+
+ /// The blob is in access tier Hot.
+ public static StorageBlobAccessTier Hot { get; } = new StorageBlobAccessTier(HotValue);
+ /// The blob is in access tier Cool.
+ public static StorageBlobAccessTier Cool { get; } = new StorageBlobAccessTier(CoolValue);
+ /// The blob is in access tier Cold.
+ public static StorageBlobAccessTier Cold { get; } = new StorageBlobAccessTier(ColdValue);
+ /// The blob is in access tier Archive.
+ public static StorageBlobAccessTier Archive { get; } = new StorageBlobAccessTier(ArchiveValue);
+ /// The blob is in access tier Default(Inferred).
+ public static StorageBlobAccessTier Default { get; } = new StorageBlobAccessTier(DefaultValue);
+ /// Determines if two values are the same.
+ public static bool operator ==(StorageBlobAccessTier left, StorageBlobAccessTier right) => left.Equals(right);
+ /// Determines if two values are not the same.
+ public static bool operator !=(StorageBlobAccessTier left, StorageBlobAccessTier right) => !left.Equals(right);
+ /// Converts a string to a .
+ public static implicit operator StorageBlobAccessTier(string value) => new StorageBlobAccessTier(value);
+
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is StorageBlobAccessTier other && Equals(other);
+ ///
+ public bool Equals(StorageBlobAccessTier 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/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobCreatedEventData.Serialization.cs b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobCreatedEventData.Serialization.cs
index fd69094430b28..5429ec22864c8 100644
--- a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobCreatedEventData.Serialization.cs
+++ b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobCreatedEventData.Serialization.cs
@@ -28,6 +28,7 @@ internal static StorageBlobCreatedEventData DeserializeStorageBlobCreatedEventDa
long? contentLength = default;
long? contentOffset = default;
string blobType = default;
+ StorageBlobAccessTier accessTier = default;
string url = default;
string sequencer = default;
string identity = default;
@@ -82,6 +83,11 @@ internal static StorageBlobCreatedEventData DeserializeStorageBlobCreatedEventDa
blobType = property.Value.GetString();
continue;
}
+ if (property.NameEquals("accessTier"u8))
+ {
+ accessTier = new StorageBlobAccessTier(property.Value.GetString());
+ continue;
+ }
if (property.NameEquals("url"u8))
{
url = property.Value.GetString();
@@ -116,6 +122,7 @@ internal static StorageBlobCreatedEventData DeserializeStorageBlobCreatedEventDa
contentLength,
contentOffset,
blobType,
+ accessTier,
url,
sequencer,
identity,
diff --git a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobCreatedEventData.cs b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobCreatedEventData.cs
index 586b36d3acca6..5f2e4fafe8754 100644
--- a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobCreatedEventData.cs
+++ b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobCreatedEventData.cs
@@ -11,8 +11,10 @@ namespace Azure.Messaging.EventGrid.SystemEvents
public partial class StorageBlobCreatedEventData
{
/// Initializes a new instance of .
- internal StorageBlobCreatedEventData()
+ /// The current tier of the blob.
+ internal StorageBlobCreatedEventData(StorageBlobAccessTier accessTier)
{
+ AccessTier = accessTier;
}
/// Initializes a new instance of .
@@ -24,11 +26,12 @@ internal StorageBlobCreatedEventData()
/// The size of the blob in bytes. This is the same as what would be returned in the Content-Length header from the blob.
/// The offset of the blob in bytes.
/// The type of blob.
+ /// The current tier of the blob.
/// The path to the blob.
/// An opaque string value representing the logical sequence of events for any particular blob name. Users can use standard string comparison to understand the relative sequence of two events on the same blob name.
/// The identity of the requester that triggered this event.
/// For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be ignored by event consumers.
- internal StorageBlobCreatedEventData(string api, string clientRequestId, string requestId, string eTag, string contentType, long? contentLength, long? contentOffset, string blobType, string url, string sequencer, string identity, object storageDiagnostics)
+ internal StorageBlobCreatedEventData(string api, string clientRequestId, string requestId, string eTag, string contentType, long? contentLength, long? contentOffset, string blobType, StorageBlobAccessTier accessTier, string url, string sequencer, string identity, object storageDiagnostics)
{
Api = api;
ClientRequestId = clientRequestId;
@@ -38,6 +41,7 @@ internal StorageBlobCreatedEventData(string api, string clientRequestId, string
ContentLength = contentLength;
ContentOffset = contentOffset;
BlobType = blobType;
+ AccessTier = accessTier;
Url = url;
Sequencer = sequencer;
Identity = identity;
@@ -60,6 +64,8 @@ internal StorageBlobCreatedEventData(string api, string clientRequestId, string
public long? ContentOffset { get; }
/// The type of blob.
public string BlobType { get; }
+ /// The current tier of the blob.
+ public StorageBlobAccessTier AccessTier { get; }
/// The path to the blob.
public string Url { get; }
/// An opaque string value representing the logical sequence of events for any particular blob name. Users can use standard string comparison to understand the relative sequence of two events on the same blob name.
diff --git a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobTierChangedEventData.Serialization.cs b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobTierChangedEventData.Serialization.cs
index c499115c5eb5a..f7c4e3a4bc38c 100644
--- a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobTierChangedEventData.Serialization.cs
+++ b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobTierChangedEventData.Serialization.cs
@@ -26,6 +26,8 @@ internal static StorageBlobTierChangedEventData DeserializeStorageBlobTierChange
string contentType = default;
long? contentLength = default;
string blobType = default;
+ StorageBlobAccessTier accessTier = default;
+ StorageBlobAccessTier previousTier = default;
string url = default;
string sequencer = default;
string identity = default;
@@ -66,6 +68,16 @@ internal static StorageBlobTierChangedEventData DeserializeStorageBlobTierChange
blobType = property.Value.GetString();
continue;
}
+ if (property.NameEquals("accessTier"u8))
+ {
+ accessTier = new StorageBlobAccessTier(property.Value.GetString());
+ continue;
+ }
+ if (property.NameEquals("previousTier"u8))
+ {
+ previousTier = new StorageBlobAccessTier(property.Value.GetString());
+ continue;
+ }
if (property.NameEquals("url"u8))
{
url = property.Value.GetString();
@@ -98,6 +110,8 @@ internal static StorageBlobTierChangedEventData DeserializeStorageBlobTierChange
contentType,
contentLength,
blobType,
+ accessTier,
+ previousTier,
url,
sequencer,
identity,
diff --git a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobTierChangedEventData.cs b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobTierChangedEventData.cs
index fdedf0d44345e..edebd32d65c57 100644
--- a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobTierChangedEventData.cs
+++ b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/StorageBlobTierChangedEventData.cs
@@ -11,8 +11,12 @@ namespace Azure.Messaging.EventGrid.SystemEvents
public partial class StorageBlobTierChangedEventData
{
/// Initializes a new instance of .
- internal StorageBlobTierChangedEventData()
+ /// The current tier of the blob.
+ /// The previous tier of the blob.
+ internal StorageBlobTierChangedEventData(StorageBlobAccessTier accessTier, StorageBlobAccessTier previousTier)
{
+ AccessTier = accessTier;
+ PreviousTier = previousTier;
}
/// Initializes a new instance of .
@@ -22,11 +26,13 @@ internal StorageBlobTierChangedEventData()
/// The content type of the blob. This is the same as what would be returned in the Content-Type header from the blob.
/// The size of the blob in bytes. This is the same as what would be returned in the Content-Length header from the blob.
/// The type of blob.
+ /// The current tier of the blob.
+ /// The previous tier of the blob.
/// The path to the blob.
/// An opaque string value representing the logical sequence of events for any particular blob name. Users can use standard string comparison to understand the relative sequence of two events on the same blob name.
/// The identity of the requester that triggered this event.
/// For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be ignored by event consumers.
- internal StorageBlobTierChangedEventData(string api, string clientRequestId, string requestId, string contentType, long? contentLength, string blobType, string url, string sequencer, string identity, object storageDiagnostics)
+ internal StorageBlobTierChangedEventData(string api, string clientRequestId, string requestId, string contentType, long? contentLength, string blobType, StorageBlobAccessTier accessTier, StorageBlobAccessTier previousTier, string url, string sequencer, string identity, object storageDiagnostics)
{
Api = api;
ClientRequestId = clientRequestId;
@@ -34,6 +40,8 @@ internal StorageBlobTierChangedEventData(string api, string clientRequestId, str
ContentType = contentType;
ContentLength = contentLength;
BlobType = blobType;
+ AccessTier = accessTier;
+ PreviousTier = previousTier;
Url = url;
Sequencer = sequencer;
Identity = identity;
@@ -52,6 +60,10 @@ internal StorageBlobTierChangedEventData(string api, string clientRequestId, str
public long? ContentLength { get; }
/// The type of blob.
public string BlobType { get; }
+ /// The current tier of the blob.
+ public StorageBlobAccessTier AccessTier { get; }
+ /// The previous tier of the blob.
+ public StorageBlobAccessTier PreviousTier { get; }
/// The path to the blob.
public string Url { get; }
/// An opaque string value representing the logical sequence of events for any particular blob name. Users can use standard string comparison to understand the relative sequence of two events on the same blob name.
diff --git a/sdk/eventgrid/Azure.Messaging.EventGrid/src/autorest.md b/sdk/eventgrid/Azure.Messaging.EventGrid/src/autorest.md
index 0a5b3d31756e0..c61d63368e00f 100644
--- a/sdk/eventgrid/Azure.Messaging.EventGrid/src/autorest.md
+++ b/sdk/eventgrid/Azure.Messaging.EventGrid/src/autorest.md
@@ -4,7 +4,7 @@ Run `dotnet build /t:GenerateCode` to generate code.
``` yaml
title: EventGridClient
-require: https://github.com/Azure/azure-rest-api-specs/blob/1b0e82df2f7f953796af2aee0372e34e00baa2d2/specification/eventgrid/data-plane/readme.md
+require: https://github.com/Azure/azure-rest-api-specs/blob/0d023bd802cde559706b5865f685a10a88516e09/specification/eventgrid/data-plane/readme.md
generation1-convenience-client: true
model-factory-for-hlc:
- MediaJobOutputAsset
From d7dc5c08fdec3b5c0fcbc53775f5026e887a558f Mon Sep 17 00:00:00 2001
From: Timothy Mothra
Date: Wed, 21 Aug 2024 15:44:31 -0700
Subject: [PATCH 10/71] refactor AggregationType (#45631)
---
.../Filtering/AccumulatedValues.cs | 20 +++---
...regationType.cs => AggregationTypeEnum.cs} | 2 +-
.../Filtering/CollectionConfiguration.cs | 5 +-
.../LiveMetrics/Filtering/DerivedMetric.cs | 2 +-
.../src/LiveMetrics/Manager.Metrics.cs | 6 +-
.../Filtering/AccumulatedValuesTest.cs | 16 ++---
.../Filtering/DerivedMetricTests.cs | 65 +++++++++----------
7 files changed, 57 insertions(+), 59 deletions(-)
rename sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/{AggregationType.cs => AggregationTypeEnum.cs} (87%)
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/AccumulatedValues.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/AccumulatedValues.cs
index 70699d71c7557..53972e7ccc881 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/AccumulatedValues.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/AccumulatedValues.cs
@@ -13,7 +13,7 @@ namespace Azure.Monitor.OpenTelemetry.AspNetCore.LiveMetrics.Filtering
///
internal class AccumulatedValues
{
- private readonly AggregationType aggregationType;
+ private readonly AggregationTypeEnum aggregationType;
private SpinLock spinLock = new SpinLock();
@@ -25,7 +25,7 @@ internal class AccumulatedValues
private double min = double.MaxValue;
- public AccumulatedValues(string metricId, AggregationType aggregationType)
+ public AccumulatedValues(string metricId, AggregationTypeEnum aggregationType)
{
this.MetricId = metricId;
this.aggregationType = aggregationType;
@@ -44,18 +44,18 @@ public void AddValue(double value)
switch (this.aggregationType)
{
- case AggregationType.Avg:
- case AggregationType.Sum:
+ case AggregationTypeEnum.Avg:
+ case AggregationTypeEnum.Sum:
this.sum += value;
break;
- case AggregationType.Min:
+ case AggregationTypeEnum.Min:
if (value < this.min)
{
this.min = value;
}
break;
- case AggregationType.Max:
+ case AggregationTypeEnum.Max:
if (value > this.max)
{
this.max = value;
@@ -86,13 +86,13 @@ public double CalculateAggregation(out long count)
count = this.count;
switch (this.aggregationType)
{
- case AggregationType.Avg:
+ case AggregationTypeEnum.Avg:
return this.count != 0 ? this.sum / this.count : 0.0;
- case AggregationType.Sum:
+ case AggregationTypeEnum.Sum:
return this.sum;
- case AggregationType.Min:
+ case AggregationTypeEnum.Min:
return this.count != 0 ? this.min : 0.0;
- case AggregationType.Max:
+ case AggregationTypeEnum.Max:
return this.count != 0 ? this.max : 0.0;
default:
throw new ArgumentOutOfRangeException(
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/AggregationType.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/AggregationTypeEnum.cs
similarity index 87%
rename from sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/AggregationType.cs
rename to sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/AggregationTypeEnum.cs
index 4f4b1c0f98f8e..f3f496a51e331 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/AggregationType.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/AggregationTypeEnum.cs
@@ -3,7 +3,7 @@
namespace Azure.Monitor.OpenTelemetry.AspNetCore.LiveMetrics.Filtering
{
- internal enum AggregationType
+ internal enum AggregationTypeEnum
{
Avg = 0,
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/CollectionConfiguration.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/CollectionConfiguration.cs
index 3f39151fb693c..d468857c35b2c 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/CollectionConfiguration.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/CollectionConfiguration.cs
@@ -7,7 +7,6 @@ namespace Azure.Monitor.OpenTelemetry.AspNetCore.LiveMetrics.Filtering
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
- using Azure.Monitor.OpenTelemetry.Exporter.Internals;
using Azure.Monitor.OpenTelemetry.AspNetCore.Models;
using ExceptionDocument = Models.Exception;
@@ -41,7 +40,7 @@ internal class CollectionConfiguration
#endregion
#region Metadata used by other components
- private readonly List> telemetryMetadata = new List>();
+ private readonly List> telemetryMetadata = new List>();
#endregion
public CollectionConfiguration(
@@ -110,7 +109,7 @@ private void UpdateAllErrorsWithKeyValue(CollectionConfigurationError[] errors,
///
/// Gets Telemetry types only. Used by QuickPulseTelemetryProcessor.
///
- public IEnumerable> TelemetryMetadata => this.telemetryMetadata;
+ public IEnumerable> TelemetryMetadata => this.telemetryMetadata;
///
/// Gets document streams. Telemetry items are provided by QuickPulseTelemetryProcessor.
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/DerivedMetric.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/DerivedMetric.cs
index d55e891cd36d7..a6aa96251b515 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/DerivedMetric.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Filtering/DerivedMetric.cs
@@ -56,7 +56,7 @@ public DerivedMetric(DerivedMetricInfo info, out CollectionConfigurationError[]
public string Id => this.info.Id;
- public Models.AggregationType? AggregationType => this.info.Aggregation; // TODO: this was enum. Need to double check new type is parsed and used correctly.
+ public AggregationType? AggregationType => this.info.Aggregation; // TODO: this was enum. Need to double check new type is parsed and used correctly.
public bool CheckFilters(TTelemetry document, out CollectionConfigurationError[] errors)
{
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Manager.Metrics.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Manager.Metrics.cs
index 9be0c56b3fcc1..628769a1cc32b 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Manager.Metrics.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/Manager.Metrics.cs
@@ -194,8 +194,8 @@ private Dictionary CreateMetricAccumulators(Collectio
Dictionary metricAccumulators = new();
// prepare the accumulators based on the collection configuration
- IEnumerable> allMetrics = collectionConfiguration.TelemetryMetadata;
- foreach (Tuple metricId in allMetrics)
+ IEnumerable> allMetrics = collectionConfiguration.TelemetryMetadata;
+ foreach (Tuple metricId in allMetrics)
{
var derivedMetricInfoAggregation = metricId.Item2;
if (!derivedMetricInfoAggregation.HasValue)
@@ -203,7 +203,7 @@ private Dictionary CreateMetricAccumulators(Collectio
continue;
}
- if (Enum.TryParse(derivedMetricInfoAggregation.ToString(), out AspNetCore.LiveMetrics.Filtering.AggregationType aggregationType))
+ if (Enum.TryParse(derivedMetricInfoAggregation.ToString(), out AspNetCore.LiveMetrics.Filtering.AggregationTypeEnum aggregationType))
{
var accumulatedValues = new AccumulatedValues(metricId.Item1, aggregationType);
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/Filtering/AccumulatedValuesTest.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/Filtering/AccumulatedValuesTest.cs
index 9cb938544b2b0..12018fd9ae8bc 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/Filtering/AccumulatedValuesTest.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/Filtering/AccumulatedValuesTest.cs
@@ -13,10 +13,10 @@ public void AccumulatedValuesAggregatesCorrectly()
{
// ARRANGE
double[] accumulatedValues = { 1d, 3d };
- AccumulatedValues accumulatorAverage = new AccumulatedValues("Metric1", AggregationType.Avg);
- AccumulatedValues accumulatorSum = new AccumulatedValues("Metric1", AggregationType.Sum);
- AccumulatedValues accumulatorMin = new AccumulatedValues("Metric1", AggregationType.Min);
- AccumulatedValues accumulatorMax = new AccumulatedValues("Metric1", AggregationType.Max);
+ AccumulatedValues accumulatorAverage = new AccumulatedValues("Metric1", AggregationTypeEnum.Avg);
+ AccumulatedValues accumulatorSum = new AccumulatedValues("Metric1", AggregationTypeEnum.Sum);
+ AccumulatedValues accumulatorMin = new AccumulatedValues("Metric1", AggregationTypeEnum.Min);
+ AccumulatedValues accumulatorMax = new AccumulatedValues("Metric1", AggregationTypeEnum.Max);
// ACT
ArrayHelpers.ForEach(accumulatedValues, accumulatorAverage.AddValue);
@@ -45,10 +45,10 @@ public void AccumulatedValuesAggregatesCorrectly()
public void AccumulatedValuesAggregatesCorrectlyForEmptyDataSet()
{
// ARRANGE
- AccumulatedValues accumulatorAverage = new AccumulatedValues("Metric1", AggregationType.Avg);
- AccumulatedValues accumulatorSum = new AccumulatedValues("Metric1", AggregationType.Sum);
- AccumulatedValues accumulatorMin = new AccumulatedValues("Metric1", AggregationType.Min);
- AccumulatedValues accumulatorMax = new AccumulatedValues("Metric1", AggregationType.Max);
+ AccumulatedValues accumulatorAverage = new AccumulatedValues("Metric1", AggregationTypeEnum.Avg);
+ AccumulatedValues accumulatorSum = new AccumulatedValues("Metric1", AggregationTypeEnum.Sum);
+ AccumulatedValues accumulatorMin = new AccumulatedValues("Metric1", AggregationTypeEnum.Min);
+ AccumulatedValues accumulatorMax = new AccumulatedValues("Metric1", AggregationTypeEnum.Max);
// ACT
double avg = accumulatorAverage.CalculateAggregation(out long avgCount);
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/Filtering/DerivedMetricTests.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/Filtering/DerivedMetricTests.cs
index 728c1ac0c8435..669a357cdfcb5 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/Filtering/DerivedMetricTests.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/Filtering/DerivedMetricTests.cs
@@ -9,7 +9,6 @@ namespace Azure.Monitor.OpenTelemetry.AspNetCore.Tests.LiveMetrics.Filtering
using Azure.Monitor.OpenTelemetry.AspNetCore.LiveMetrics.Filtering;
using Azure.Monitor.OpenTelemetry.AspNetCore.Models;
using Xunit;
- using AggregationType = Models.AggregationType;
using RequestTelemetry = Azure.Monitor.OpenTelemetry.AspNetCore.Models.Request;
using TelemetryType = Models.TelemetryType;
@@ -26,8 +25,8 @@ public void DerivedMetricFiltersCorrectly()
telemetryType: TelemetryType.Request.ToString(),
filterGroups: new[] { new FilterConjunctionGroupInfo(new List { filterInfo1, filterInfo2 }) },
projection: "Name",
- aggregation: Models.AggregationType.Sum,
- backEndAggregation: Models.AggregationType.Sum
+ aggregation: AggregationType.Sum,
+ backEndAggregation: AggregationType.Sum
);
var telemetryThatMustPass = new RequestTelemetry() { Name = "Both the words 'dog' and 'CAT' are here, which satisfies both filters" };
@@ -60,8 +59,8 @@ public void DerivedMetricHandlesNoFiltersCorrectly()
telemetryType: TelemetryType.Request.ToString(),
filterGroups: new FilterConjunctionGroupInfo[0],
projection: "Name",
- aggregation: Models.AggregationType.Sum,
- backEndAggregation: Models.AggregationType.Sum
+ aggregation: AggregationType.Sum,
+ backEndAggregation: AggregationType.Sum
);
var telemetryThatMustPass = new RequestTelemetry() { Name = "Both the words 'dog' and 'CAT' are here, which satisfies both filters" };
@@ -86,8 +85,8 @@ public void DerivedMetricHandlesNullFiltersCorrectly()
telemetryType: TelemetryType.Request.ToString(),
filterGroups: null,
projection: "Name",
- aggregation: Models.AggregationType.Sum,
- backEndAggregation: Models.AggregationType.Sum
+ aggregation: AggregationType.Sum,
+ backEndAggregation: AggregationType.Sum
);
var telemetryThatMustPass = new RequestTelemetry() { Name = "Both the words 'dog' and 'CAT' are here, which satisfies both filters" };
@@ -121,8 +120,8 @@ public void DerivedMetricPerformsLogicalConnectionsBetweenFiltersCorrectly()
new FilterConjunctionGroupInfo(new[] { filterInfoApple, filterInfoOrange })
},
projection: "Name",
- aggregation: Models.AggregationType.Sum,
- backEndAggregation: Models.AggregationType.Sum
+ aggregation: AggregationType.Sum,
+ backEndAggregation: AggregationType.Sum
);
var telemetryThatMustPass1 = new RequestTelemetry() { Name = "Both the words 'dog' and 'CAT' are here, which satisfies the first OR." };
@@ -167,8 +166,8 @@ public void DerivedMetricProjectsCorrectly()
telemetryType: TelemetryType.Request.ToString(),
filterGroups: new FilterConjunctionGroupInfo[0],
projection: "Id",
- aggregation: Models.AggregationType.Sum,
- backEndAggregation: Models.AggregationType.Sum
+ aggregation: AggregationType.Sum,
+ backEndAggregation: AggregationType.Sum
);
var telemetry = new DocumentMock() { Name = "1.23", Id = "5.67" };
@@ -179,7 +178,7 @@ public void DerivedMetricProjectsCorrectly()
double projection = metric.Project(telemetry);
// ASSERT
- Assert.Equal(Models.AggregationType.Sum, metric.AggregationType);
+ Assert.Equal(AggregationType.Sum, metric.AggregationType);
Assert.Empty(errors);
Assert.Equal(5.67d, projection);
}
@@ -193,8 +192,8 @@ public void DerivedMetricProjectsCorrectlyWhenCustomDimension()
telemetryType: TelemetryType.Request.ToString(),
filterGroups: new FilterConjunctionGroupInfo[0],
projection: "CustomDimensions.Dimension1",
- aggregation: Models.AggregationType.Sum,
- backEndAggregation: Models.AggregationType.Sum
+ aggregation: AggregationType.Sum,
+ backEndAggregation: AggregationType.Sum
);
var telemetry = new DocumentMock(new List() { new("Dimension.1", "1.5") });
@@ -205,7 +204,7 @@ public void DerivedMetricProjectsCorrectlyWhenCustomDimension()
double projection = metric.Project(telemetry);
// ASSERT
- Assert.Equal(Models.AggregationType.Sum, metric.AggregationType);
+ Assert.Equal(AggregationType.Sum, metric.AggregationType);
Assert.Empty(errors);
Assert.Equal(1.5d, projection);
}
@@ -219,8 +218,8 @@ public void DerivedMetricProjectsCorrectlyWhenCustomMetric()
telemetryType: TelemetryType.Request.ToString(),
filterGroups: new FilterConjunctionGroupInfo[0],
projection: "CustomMetrics.Metric1",
- aggregation: Models.AggregationType.Sum,
- backEndAggregation: Models.AggregationType.Sum
+ aggregation: AggregationType.Sum,
+ backEndAggregation: AggregationType.Sum
);
var telemetry = new DocumentMock() { Metrics = { ["Metric1"] = 1.75d } };
@@ -231,7 +230,7 @@ public void DerivedMetricProjectsCorrectlyWhenCustomMetric()
double projection = metric.Project(telemetry);
// ASSERT
- Assert.Equal(Models.AggregationType.Sum, metric.AggregationType);
+ Assert.Equal(AggregationType.Sum, metric.AggregationType);
Assert.Empty(errors);
Assert.Equal(1.75d, projection);
}
@@ -245,8 +244,8 @@ public void DerivedMetricProjectsCorrectlyWhenCount()
telemetryType: TelemetryType.Request.ToString(),
filterGroups: new FilterConjunctionGroupInfo[0],
projection: "COUNT()",
- aggregation: Models.AggregationType.Sum,
- backEndAggregation: Models.AggregationType.Sum
+ aggregation: AggregationType.Sum,
+ backEndAggregation: AggregationType.Sum
);
var telemetry = new RequestTelemetry();
@@ -257,7 +256,7 @@ public void DerivedMetricProjectsCorrectlyWhenCount()
double projection = metric.Project(telemetry);
// ASSERT
- Assert.Equal(Models.AggregationType.Sum, metric.AggregationType);
+ Assert.Equal(AggregationType.Sum, metric.AggregationType);
Assert.Empty(errors);
Assert.Equal(1d, projection);
}
@@ -271,8 +270,8 @@ public void DerivedMetricProjectsCorrectlyWhenTimeSpan()
telemetryType: TelemetryType.Request.ToString(),
filterGroups: new FilterConjunctionGroupInfo[0],
projection: "Duration",
- aggregation: Models.AggregationType.Avg,
- backEndAggregation: Models.AggregationType.Avg
+ aggregation: AggregationType.Avg,
+ backEndAggregation: AggregationType.Avg
);
var telemetry = new DocumentMock() { Duration = TimeSpan.FromMilliseconds(120) };
@@ -283,7 +282,7 @@ public void DerivedMetricProjectsCorrectlyWhenTimeSpan()
double projection = metric.Project(telemetry);
// ASSERT
- Assert.Equal(Models.AggregationType.Avg, metric.AggregationType);
+ Assert.Equal(AggregationType.Avg, metric.AggregationType);
Assert.Empty(errors);
Assert.Equal(120, projection);
}
@@ -298,7 +297,7 @@ public void DerivedMetricProjectsCorrectlyWhenDurationIsString()
filterGroups: new FilterConjunctionGroupInfo[0],
projection: "Duration",
aggregation: AggregationType.Avg,
- backEndAggregation: Models.AggregationType.Avg
+ backEndAggregation: AggregationType.Avg
);
var durationString = TimeSpan.FromMilliseconds(120).ToString();
@@ -326,8 +325,8 @@ public void DerivedMetricReportsErrorsForInvalidFilters()
telemetryType: TelemetryType.Request.ToString(),
filterGroups: new[] { new FilterConjunctionGroupInfo(new[] { filterInfo1, filterInfo2 }) },
projection: "Name",
- aggregation: Models.AggregationType.Avg,
- backEndAggregation: Models.AggregationType.Avg
+ aggregation: AggregationType.Avg,
+ backEndAggregation: AggregationType.Avg
);
// ACT
@@ -363,8 +362,8 @@ public void DerivedMetricThrowsWhenInvalidProjection()
telemetryType: TelemetryType.Request.ToString(),
filterGroups: new FilterConjunctionGroupInfo[0],
projection: "NonExistentFieldName",
- aggregation: Models.AggregationType.Sum,
- backEndAggregation: Models.AggregationType.Sum
+ aggregation: AggregationType.Sum,
+ backEndAggregation: AggregationType.Sum
);
// ACT, ASSERT
@@ -381,8 +380,8 @@ public void DerivedMetricReportsErrorWhenProjectionIsNotDouble()
telemetryType: TelemetryType.Request.ToString(),
filterGroups: new FilterConjunctionGroupInfo[0],
projection: "Id",
- aggregation: Models.AggregationType.Sum,
- backEndAggregation: Models.AggregationType.Sum
+ aggregation: AggregationType.Sum,
+ backEndAggregation: AggregationType.Sum
);
var telemetry = new DocumentMock() { Id = "NotDoubleValue" };
@@ -414,8 +413,8 @@ public void DerivedMetricReportsErrorWhenProjectionIsAsterisk()
telemetryType: TelemetryType.Request.ToString(),
filterGroups: new FilterConjunctionGroupInfo[0],
projection: "*",
- aggregation: Models.AggregationType.Sum,
- backEndAggregation: Models.AggregationType.Sum
+ aggregation: AggregationType.Sum,
+ backEndAggregation: AggregationType.Sum
);
// ACT, ASSERT
From b39a20c7252bc0d06a829511bd235b3d3bc2bac8 Mon Sep 17 00:00:00 2001
From: Bidisha Chakraborty <29803402+bidisha-c@users.noreply.github.com>
Date: Wed, 21 Aug 2024 17:40:24 -0700
Subject: [PATCH 11/71] Conversations SDK: Update documentation (#45593)
* Conversations SDK: Update documentation
* Add supported Api versions
* revert relative links
---------
Co-authored-by: Bidisha Chakraborty
---
.../Azure.AI.Language.Conversations/README.md | 31 +++-
.../samples/README.md | 2 +-
...lyzeConversation_ConversationPrediction.md | 6 +-
.../samples/Sample5_ImportProject.md | 165 ++++++++++++++++++
...eConversation_ConversationSummarization.md | 6 +-
.../samples/Sample7_ExportProject.md | 76 ++++++++
...e8_AnalyzeConversation_ConversationPii.md} | 2 +-
.../tests/Samples/Readme.cs | 10 ++
8 files changed, 289 insertions(+), 9 deletions(-)
create mode 100644 sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample5_ImportProject.md
create mode 100644 sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample7_ExportProject.md
rename sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/{Sample5_AnalyzeConversation_ConversationPii.md => Sample8_AnalyzeConversation_ConversationPii.md} (98%)
diff --git a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/README.md b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/README.md
index 803aca9a0355c..354e9a8b5a16f 100644
--- a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/README.md
+++ b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/README.md
@@ -8,7 +8,7 @@ Conversation Language Understanding - aka CLU for short - is a cloud-based conve
Conversation Summarization is one feature offered by Azure AI Language, which is a combination of generative Large Language models and task-optimized encoder models that offer summarization solutions with higher quality, cost efficiency, and lower latency.
-Conversation PII detection another feature offered by Azure AI Language, which is a collection of machine learning and AI algorithms to identify, categorize, and redact sensitive information in text. The Conversational PII model is a specialized model for handling speech transcriptions and the more informal, conversational tone of meeting and call transcripts.
+Conversation PII detection another feature offered by Azure AI Language, which is a collection of machine learning and AI algorithms to identify, categorize, and redact sensitive information in text. The Conversational PII model is a specialized model for handling speech transcriptions and the more informal, conversational tone of meeting and call transcripts.
[Source code][conversationanalysis_client_src] | [Package (NuGet)][conversationanalysis_nuget_package] | [API reference documentation][conversationanalysis_refdocs] | [Samples][conversationanalysis_samples] | [Product documentation][conversationanalysis_docs] | [Analysis REST API documentation][conversationanalysis_restdocs]
@@ -94,6 +94,35 @@ ConversationAnalysisClient client = new ConversationAnalysisClient(endpoint, cre
Note that regional endpoints do not support AAD authentication. Instead, create a [custom domain][custom_domain] name for your resource to use AAD authentication.
+### 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.
+
+|SDK version |Supported API version of service
+|-------------|-----------------------------------------------------
+|2.0.0-beta.1 | 2022-05-01, 2023-04-01, 2024-05-01, 2024-05-15-preview (default)
+|1.1.0 | 2022-05-01, 2023-04-01 (default)
+|1.0.0 | 2022-05-01 (default)
+
+#### 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:CreateConversationAnalysisClientForSpecificApiVersion
+Uri endpoint = new Uri("https://myaccount.cognitiveservices.azure.com");
+AzureKeyCredential credential = new AzureKeyCredential("{api-key}");
+ConversationsClientOptions options = new ConversationsClientOptions(ConversationsClientOptions.ServiceVersion.V2024_05_01);
+ConversationAnalysisClient client = new ConversationAnalysisClient(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.
+
+If you do not select an api version we will default to the latest version available, which has the possibility of being a preview version.
+
## Key concepts
### ConversationAnalysisClient
diff --git a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/README.md b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/README.md
index d2c48cd682258..98f303c8c81a9 100644
--- a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/README.md
+++ b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/README.md
@@ -20,5 +20,5 @@ You can work with request and response content more easily by using our [Dynamic
- [Analyze an utterance - Orchestration project](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample2_AnalyzeConversation_OrchestrationPrediction.md)
- [Analyze an utterance in a different language](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample3_AnalyzeConversationWithLanguage.md)
- [Analyze an utterance using extra options](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample4_AnalyzeConversationWithOptions.md)
-- [Analyze a conversation with Conversation PII](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample5_AnalyzeConversation_ConversationPii.md)
+- [Analyze a conversation with Conversation PII](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample8_AnalyzeConversation_ConversationPii.md)
- [Analyze a conversation with Conversation Summarization](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample6_AnalyzeConversation_ConversationSummarization.md)
diff --git a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample1_AnalyzeConversation_ConversationPrediction.md b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample1_AnalyzeConversation_ConversationPrediction.md
index f7f054ba8eb0d..360527108ea00 100644
--- a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample1_AnalyzeConversation_ConversationPrediction.md
+++ b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample1_AnalyzeConversation_ConversationPrediction.md
@@ -14,11 +14,11 @@ using Azure.AI.Language.Conversations;
To analyze an utterance, you need to first create a `ConversationAnalysisClient` using an endpoint and API key. These can be stored in an environment variable, configuration setting, or any way that works for your application.
-```C# Snippet:ConversationAnalysisClient_Create
+```C# Snippet:CreateConversationAnalysisClientForSpecificApiVersion
Uri endpoint = new Uri("https://myaccount.cognitiveservices.azure.com");
AzureKeyCredential credential = new AzureKeyCredential("{api-key}");
-
-ConversationAnalysisClient client = new ConversationAnalysisClient(endpoint, credential);
+ConversationsClientOptions options = new ConversationsClientOptions(ConversationsClientOptions.ServiceVersion.V2024_05_01);
+ConversationAnalysisClient client = new ConversationAnalysisClient(endpoint, credential, options);
```
Once you have created a client, you can call synchronous or asynchronous methods.
diff --git a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample5_ImportProject.md b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample5_ImportProject.md
new file mode 100644
index 0000000000000..488202b170785
--- /dev/null
+++ b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample5_ImportProject.md
@@ -0,0 +1,165 @@
+# Import a project
+
+This sample demonstrates how to import a project. To get started, you'll need to create a Cognitive Language service endpoint and an API key. See the [README](https://github.com/Azure/azure-sdk-for-net/blob/Azure.AI.Language.Conversations_1.1.0/sdk/cognitivelanguage/Azure.AI.Language.Conversations/README.md) for links and instructions.
+
+> [!NOTE]
+> Conversational Authoring is not supported in version 2.0.0-beta.1. If you use Conversational Authoring, please continue to use version 1.1.0.
+
+Start by importing the namespace for the `ConversationAuthoringClient` and related classes:
+
+```C#
+using Azure.Core;
+using Azure.AI.Language.Conversations.Authoring;
+```
+
+To import a project, you'll need to first create a `ConversationAuthoringClient` using an endpoint and an API key. These can be stored in an environment variable, configuration setting, or any way that works for your application.
+
+```C#
+Uri endpoint = new Uri("https://myaccount.cognitiveservices.azure.com");
+AzureKeyCredential credential = new AzureKeyCredential("{api-key}");
+
+ConversationAuthoringClient client = new ConversationAuthoringClient(endpoint, credential);
+```
+
+Once you have created a client, you can call synchronous or asynchronous methods. Typically, the content would come from a file but a small sample is shown here for demonstration purposes.
+
+## Synchronous
+
+```C#
+string projectName = "Menu";
+
+// Define our project assets and import. In practice this would most often be read from a file.
+var importData = new
+{
+ projectFileVersion = "2022-05-01",
+ metadata = new {
+ projectName,
+ projectKind = "Conversation",
+ multilingual = true,
+ language = "en",
+ },
+
+ assets = new
+ {
+ projectKind = "Conversation",
+ entities = new[] // ConversationalAnalysisAuthoringConversationExportedEntity
+ {
+ new
+ {
+ category = "Contact",
+ compositionSetting = "combineComponents",
+ prebuilts = new[]
+ {
+ new
+ {
+ category = "Person.Name",
+ },
+ },
+
+ // ... more entities.
+ }
+ },
+
+ intents = new[] // ConversationalAnalysisAuthoringConversationExportedIntent
+ {
+ new
+ {
+ category = "Send",
+ },
+
+ // ... more intents.
+ },
+
+ utterances = new[] // ConversationalAnalysisAuthoringConversationExportedUtterance
+ {
+ new
+ {
+ text = "Send an email to Johnson",
+ language = "en",
+ intent = "Send",
+ entities = new[]
+ {
+ new
+ {
+ category = "Contact",
+ offset = 17,
+ length = 7,
+ },
+ },
+ },
+ new
+ {
+ text = "Send Kathy a calendar invite",
+ language = "en",
+ intent = "Send",
+ entities = new[]
+ {
+ new
+ {
+ category = "Contact",
+ offset = 5,
+ length = 5,
+ },
+ },
+ },
+
+ // ... more utterances.
+ },
+ },
+
+ // Use Utf16CodeUnit for strings in .NET.
+ stringIndexType = "Utf16CodeUnit",
+};
+
+Operation importOperation = client.ImportProject(WaitUntil.Completed, projectName, RequestContent.Create(importData));
+
+// Train the model.
+var trainData = new
+{
+ modelLabel = "Sample5",
+ trainingMode = "standard",
+};
+
+Console.WriteLine($"Training project {projectName}...");
+Operation trainOperation = client.Train(WaitUntil.Completed, projectName, RequestContent.Create(trainData));
+
+ // Deploy the model.
+ var deployData = new
+ {
+ trainedModelLabel = "Sample5",
+ };
+
+Console.WriteLine($"Deploying project {projectName} to production...");
+Operation deployOperation = client.DeployProject(WaitUntil.Completed, projectName, "production", RequestContent.Create(deployData));
+
+Console.WriteLine("Import complete");
+```
+
+## Asynchronous
+
+Using the same `importData` definition above, you can make an asynchronous request by calling `ImportProjectAsync`:
+
+```C#
+Operation importOperation = await client.ImportProjectAsync(WaitUntil.Completed, projectName, RequestContent.Create(importData));
+
+// Train the model.
+var trainData = new
+{
+ modelLabel = "Sample5",
+ trainingMode = "standard",
+};
+
+Console.WriteLine($"Training project {projectName}...");
+Operation trainOperation = await client.TrainAsync(WaitUntil.Completed, projectName, RequestContent.Create(trainData));
+
+// Deploy the model.
+var deployData = new
+{
+ trainedModelLabel = "Sample5",
+};
+
+Console.WriteLine($"Deploying project {projectName} to production...");
+Operation deployOperation = await client.DeployProjectAsync(WaitUntil.Completed, projectName, "production", RequestContent.Create(deployData));
+
+Console.WriteLine("Import complete");
+```
diff --git a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample6_AnalyzeConversation_ConversationSummarization.md b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample6_AnalyzeConversation_ConversationSummarization.md
index 1988f7fa15f7f..653147aefb0f2 100644
--- a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample6_AnalyzeConversation_ConversationSummarization.md
+++ b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample6_AnalyzeConversation_ConversationSummarization.md
@@ -14,11 +14,11 @@ using Azure.AI.Language.Conversations;
To analyze an utterance, you need to first create a `ConversationAnalysisClient` using an endpoint and API key. These can be stored in an environment variable, configuration setting, or any way that works for your application.
-```C# Snippet:ConversationAnalysisClient_Create
+```C# Snippet:CreateConversationAnalysisClientForSpecificApiVersion
Uri endpoint = new Uri("https://myaccount.cognitiveservices.azure.com");
AzureKeyCredential credential = new AzureKeyCredential("{api-key}");
-
-ConversationAnalysisClient client = new ConversationAnalysisClient(endpoint, credential);
+ConversationsClientOptions options = new ConversationsClientOptions(ConversationsClientOptions.ServiceVersion.V2024_05_01);
+ConversationAnalysisClient client = new ConversationAnalysisClient(endpoint, credential, options);
```
Once you have created a client, you can call synchronous or asynchronous methods.
diff --git a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample7_ExportProject.md b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample7_ExportProject.md
new file mode 100644
index 0000000000000..1385cc5630168
--- /dev/null
+++ b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample7_ExportProject.md
@@ -0,0 +1,76 @@
+# Export a project
+
+This sample demonstrates how to export a project. To get started, you'll need to create a Cognitive Language service endpoint and an API key. See the [README](https://github.com/Azure/azure-sdk-for-net/blob/Azure.AI.Language.Conversations_1.1.0/sdk/cognitivelanguage/Azure.AI.Language.Conversations/README.md) for links and instructions.
+
+> [!NOTE]
+> Conversational Authoring is not supported in version 2.0.0-beta.1. If you use Conversational Authoring, please continue to use version 1.1.0.
+
+Start by importing the namespace for the `ConversationAuthoringClient` and related classes:
+
+```C#
+using Azure.Core;
+using Azure.AI.Language.Conversations.Authoring;
+```
+
+To export a project, you'll need to first create a `ConversationAuthoringClient` using an endpoint and an API key. These can be stored in an environment variable, configuration setting, or any way that works for your application.
+
+```C#
+Uri endpoint = new Uri("https://myaccount.cognitiveservices.azure.com");
+AzureKeyCredential credential = new AzureKeyCredential("{api-key}");
+
+ConversationAuthoringClient client = new ConversationAuthoringClient(endpoint, credential);
+```
+
+Once you have created a client, you can call synchronous or asynchronous methods. Typically, the content would come from a file but a small sample is shown here for demonstration purposes.
+
+## Synchronous
+
+Exporting a project returns an operation. Once this operation completes, you can get the `resultUrl` out of the response body and pass through the HTTP pipeline exposed by the client to download the project.
+
+```C#
+string projectName = "project-to-export";
+Operation exportOperation = client.ExportProject(WaitUntil.Completed, projectName);
+
+// Get the resultUrl from the response, which contains the exported project.
+using JsonDocument doc = JsonDocument.Parse(exportOperation.Value.ToStream());
+string resultUrl = doc.RootElement.GetProperty("resultUrl").GetString();
+
+// Use the client pipeline to create and send a request to download the raw URL.
+RequestUriBuilder builder = new RequestUriBuilder();
+builder.Reset(new Uri(resultUrl));
+
+Request request = client.Pipeline.CreateRequest();
+request.Method = RequestMethod.Get;
+request.Uri = builder;
+
+// Save the project to a file in the current working directory.
+Response response = client.Pipeline.SendRequest(request, cancellationToken: default);
+
+string path = "project.json";
+response.ContentStream.CopyTo(File.Create(path));
+```
+
+## Asynchronous
+
+```C#
+string projectName = "project-to-export";
+Operation exportOperation = await client.ExportProjectAsync(WaitUntil.Completed, projectName);
+
+// Get the resultUrl from the response, which contains the exported project.
+using JsonDocument doc = JsonDocument.Parse(exportOperation.Value.ToStream());
+string resultUrl = doc.RootElement.GetProperty("resultUrl").GetString();
+
+// Use the client pipeline to create and send a request to download the raw URL.
+RequestUriBuilder builder = new RequestUriBuilder();
+builder.Reset(new Uri(resultUrl));
+
+Request request = client.Pipeline.CreateRequest();
+request.Method = RequestMethod.Get;
+request.Uri = builder;
+
+// Save the project to a file in the current working directory.
+Response response = await client.Pipeline.SendRequestAsync(request, cancellationToken: default);
+
+string path = "project.json";
+await response.ContentStream.CopyToAsync(File.Create(path));
+```
diff --git a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample5_AnalyzeConversation_ConversationPii.md b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample8_AnalyzeConversation_ConversationPii.md
similarity index 98%
rename from sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample5_AnalyzeConversation_ConversationPii.md
rename to sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample8_AnalyzeConversation_ConversationPii.md
index c01baa621f33d..666773152f580 100644
--- a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample5_AnalyzeConversation_ConversationPii.md
+++ b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/samples/Sample8_AnalyzeConversation_ConversationPii.md
@@ -1,4 +1,4 @@
-# Analyze a conversation with Conversation Summarization
+# Analyze a conversation with Conversation PII
This sample demonstrates how to detect and redact personally identifiable information from a conversation with Conversation Pii. To get started, you'll need to create a Cognitive Language service endpoint and an API key. See the [README](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/cognitivelanguage/Azure.AI.Language.Conversations/README.md) for links and instructions.
diff --git a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/tests/Samples/Readme.cs b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/tests/Samples/Readme.cs
index 90ea66beed09d..b99bc4763d790 100644
--- a/sdk/cognitivelanguage/Azure.AI.Language.Conversations/tests/Samples/Readme.cs
+++ b/sdk/cognitivelanguage/Azure.AI.Language.Conversations/tests/Samples/Readme.cs
@@ -28,6 +28,16 @@ public void CreateConversationClient()
#endregion
}
+ public void CreateConversationClientWithSpecificApiVersion()
+ {
+ #region Snippet:CreateConversationAnalysisClientForSpecificApiVersion
+ Uri endpoint = new Uri("https://myaccount.cognitiveservices.azure.com");
+ AzureKeyCredential credential = new AzureKeyCredential("{api-key}");
+ ConversationsClientOptions options = new ConversationsClientOptions(ConversationsClientOptions.ServiceVersion.V2024_05_01);
+ ConversationAnalysisClient client = new ConversationAnalysisClient(endpoint, credential, options);
+ #endregion
+ }
+
public void CreateConversationClientWithDefaultAzureCredential()
{
#region Snippet:ConversationAnalysisClient_CreateWithDefaultAzureCredential
From f2864e777b8f0067c3948909d8d18bba9c84bf64 Mon Sep 17 00:00:00 2001
From: Wenming Liu
Date: Thu, 22 Aug 2024 15:55:33 +0800
Subject: [PATCH 12/71] eng/Template modification for typespec (#45596)
---
.../.template.config/template.json | 53 ++++++++++--------
.../CHANGELOG.md | 4 +-
.../assets.json | 2 +-
.../src/autorest.md | 56 -------------------
.../tsp-location.yaml | 3 +
eng/templates/README.md | 2 +-
6 files changed, 37 insertions(+), 83 deletions(-)
delete mode 100644 eng/templates/Azure.ResourceManager.Template/src/autorest.md
create mode 100644 eng/templates/Azure.ResourceManager.Template/tsp-location.yaml
diff --git a/eng/templates/Azure.ResourceManager.Template/.template.config/template.json b/eng/templates/Azure.ResourceManager.Template/.template.config/template.json
index 94d5c03086dac..2463ab5b258a4 100644
--- a/eng/templates/Azure.ResourceManager.Template/.template.config/template.json
+++ b/eng/templates/Azure.ResourceManager.Template/.template.config/template.json
@@ -46,13 +46,37 @@
"description": "The Azure provider name. ie. Microsoft.Network or Microsoft.Compute",
"replaces": "ProviderFullName"
},
- "tagVersion": {
+ "TypeSpecDirectory": {
"type": "parameter",
"datatype":"text",
"isRequired": false,
- "description": "The optional parameter specifies the tag in the README.MD. If empty, the default tag in the README.MD is used.",
+ "description": "TypeSpecDirectory under sdk/providername.",
+ "defaultValue": "TypeSpecDirectory",
+ "replaces": "TypeSpecDirectory"
+ },
+ "CommitId": {
+ "type": "parameter",
+ "datatype":"text",
+ "isRequired": false,
+ "description": "the commit id of Azure spec repo.",
+ "defaultValue": "CommitId",
+ "replaces": "CommitId"
+ },
+ "ChangeLogH2Title": {
+ "type": "parameter",
+ "datatype":"text",
+ "isRequired": false,
+ "description": "the H2 title of Changelog",
+ "defaultValue": "1.0.0-beta.1 (Unreleased)",
+ "replaces": "ChangeLogH2Title"
+ },
+ "ChangeLogSdkDescription": {
+ "type": "parameter",
+ "datatype":"text",
+ "isRequired": false,
+ "description": "Sdk description",
"defaultValue": "",
- "replaces": "SwaggerVersionTag"
+ "replaces": "ChangeLogSdkDescription"
},
"includeCI": {
"type": "parameter",
@@ -61,12 +85,12 @@
"description": "The optional parameter specifies whether generate related pipline ci.yml and test-resources.json in parent folder.",
"defaultValue": "false"
},
- "ProviderShortNameLowercase": {
+ "LowercaseProviderShortName": {
"type": "derived",
"datatype": "text",
"valueSource": "provider",
"valueTransform": "ProviderShortNameLowerForm",
- "replaces": "ProviderNameLowercase"
+ "replaces": "LowercaseProviderShortName"
},
"ProviderShortName": {
"type": "derived",
@@ -88,25 +112,6 @@
{ "regex": "\\.", "replacement": "" }
]
}
- },
- "tagPrefix": {
- "type": "generated",
- "generator": "switch",
- "replaces": "tagPrefix",
- "parameters": {
- "evaluator": "MSBUILD",
- "datatype": "string",
- "cases": [
- {
- "condition": "('tagVersion' == '')",
- "value": ""
- },
- {
- "condition": "('tagVersion' != '')",
- "value": "tag:"
- }
- ]
- }
}
},
"forms": {
diff --git a/eng/templates/Azure.ResourceManager.Template/CHANGELOG.md b/eng/templates/Azure.ResourceManager.Template/CHANGELOG.md
index 6a9f3bac33c1d..9410023df8670 100644
--- a/eng/templates/Azure.ResourceManager.Template/CHANGELOG.md
+++ b/eng/templates/Azure.ResourceManager.Template/CHANGELOG.md
@@ -1,6 +1,8 @@
# Release History
-## 1.0.0-beta.1 (Unreleased)
+## ChangeLogH2Title
+
+ChangeLogSdkDescription
### Features Added
diff --git a/eng/templates/Azure.ResourceManager.Template/assets.json b/eng/templates/Azure.ResourceManager.Template/assets.json
index 8fe6b015af19b..44e528c06061f 100644
--- a/eng/templates/Azure.ResourceManager.Template/assets.json
+++ b/eng/templates/Azure.ResourceManager.Template/assets.json
@@ -1,6 +1,6 @@
{
"AssetsRepo": "Azure/azure-sdk-assets",
"AssetsRepoPrefixPath": "net",
- "TagPrefix": "net//Azure.ResourceManager.Template",
+ "TagPrefix": "net/LowercaseProviderShortName/Azure.ResourceManager.Template",
"Tag": ""
}
diff --git a/eng/templates/Azure.ResourceManager.Template/src/autorest.md b/eng/templates/Azure.ResourceManager.Template/src/autorest.md
deleted file mode 100644
index cbbc44c8aad43..0000000000000
--- a/eng/templates/Azure.ResourceManager.Template/src/autorest.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# Generated code configuration
-
-Run `dotnet build /t:GenerateCode` to generate code.
-
-``` yaml
-azure-arm: true
-csharp: true
-library-name: ProviderShortName
-namespace: Azure.ResourceManager.ProviderShortName
-require: https://github.com/Azure/azure-rest-api-specs/blob/main/specification/ProviderNameLowercase/resource-manager/readme.md
-output-folder: $(this-folder)/Generated
-clear-output-folder: true
-sample-gen:
- output-folder: $(this-folder)/../samples/Generated
- clear-output-folder: true
-skip-csproj: true
-modelerfour:
- flatten-payloads: false
-use-model-reader-writer: true
-
-#mgmt-debug:
-# show-serialized-names: true
-
-tagPrefix SwaggerVersionTag
-
-format-by-name-rules:
- 'tenantId': 'uuid'
- 'ETag': 'etag'
- 'location': 'azure-location'
- '*Uri': 'Uri'
- '*Uris': 'Uri'
-
-acronym-mapping:
- CPU: Cpu
- CPUs: Cpus
- Os: OS
- Ip: IP
- Ips: IPs|ips
- ID: Id
- IDs: Ids
- VM: Vm
- VMs: Vms
- Vmos: VmOS
- VMScaleSet: VmScaleSet
- DNS: Dns
- VPN: Vpn
- NAT: Nat
- WAN: Wan
- Ipv4: IPv4|ipv4
- Ipv6: IPv6|ipv6
- Ipsec: IPsec|ipsec
- SSO: Sso
- URI: Uri
- Etag: ETag|etag
-
-```
\ No newline at end of file
diff --git a/eng/templates/Azure.ResourceManager.Template/tsp-location.yaml b/eng/templates/Azure.ResourceManager.Template/tsp-location.yaml
new file mode 100644
index 0000000000000..cd8ab8802f688
--- /dev/null
+++ b/eng/templates/Azure.ResourceManager.Template/tsp-location.yaml
@@ -0,0 +1,3 @@
+directory: specification/LowercaseProviderShortName/TypeSpecDirectory
+commit: CommitId
+repo: Azure/azure-rest-api-specs
\ No newline at end of file
diff --git a/eng/templates/README.md b/eng/templates/README.md
index 35e0508087b99..94efe37d8fd9f 100644
--- a/eng/templates/README.md
+++ b/eng/templates/README.md
@@ -42,7 +42,7 @@ Following parameter is available
### Next Step
-1. Inspect `src\autorest.md` to ensure the REST Api path is valid
+1. Inspect `tsp-location.yaml` to ensure the REST Api path is valid
2. Run `dotnet build` to ensure empty project builds successfully.
3. Run `dotnet build /t:GenerateCode` to generate C# code and ensure no fatal errors.
4. Run `dotnet build` to ensure now generated project builds successfully.
From 28ce8f9b287a0bcb5ec208817247a47047fc1f4a Mon Sep 17 00:00:00 2001
From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com>
Date: Thu, 22 Aug 2024 10:00:22 -0700
Subject: [PATCH 13/71] Increment package version after release of
Azure.Messaging.EventGrid (#45637)
---
sdk/eventgrid/Azure.Messaging.EventGrid/CHANGELOG.md | 10 ++++++++++
.../src/Azure.Messaging.EventGrid.csproj | 4 ++--
2 files changed, 12 insertions(+), 2 deletions(-)
diff --git a/sdk/eventgrid/Azure.Messaging.EventGrid/CHANGELOG.md b/sdk/eventgrid/Azure.Messaging.EventGrid/CHANGELOG.md
index fbf2a31af9515..9311fd17d303e 100644
--- a/sdk/eventgrid/Azure.Messaging.EventGrid/CHANGELOG.md
+++ b/sdk/eventgrid/Azure.Messaging.EventGrid/CHANGELOG.md
@@ -1,5 +1,15 @@
# Release History
+## 4.26.0-beta.1 (Unreleased)
+
+### Features Added
+
+### Breaking Changes
+
+### Bugs Fixed
+
+### Other Changes
+
## 4.25.0 (2024-08-21)
### Features Added
diff --git a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Azure.Messaging.EventGrid.csproj b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Azure.Messaging.EventGrid.csproj
index e26f900ed4971..6904a5b6fe8fd 100644
--- a/sdk/eventgrid/Azure.Messaging.EventGrid/src/Azure.Messaging.EventGrid.csproj
+++ b/sdk/eventgrid/Azure.Messaging.EventGrid/src/Azure.Messaging.EventGrid.csproj
@@ -2,9 +2,9 @@
This library can be used to publish events to Azure Event Grid and to consume events delivered by EventGrid. It also defines the event schemas for the events published to EventGrid by various Azure services.
Microsoft Azure.Messaging.EventGrid client library
- 4.25.0
+ 4.26.0-beta.1
- 4.24.1
+ 4.25.0
Microsoft Azure EventGrid;Event Grid;Event Grid Publishing;
true
$(RequiredTargetFrameworks)
From 425f4e6b41827222f1ecae12607726e705272a30 Mon Sep 17 00:00:00 2001
From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com>
Date: Thu, 22 Aug 2024 10:00:48 -0700
Subject: [PATCH 14/71] Increment package version after release of
Azure.Monitor.Query (#45628)
---
sdk/monitor/Azure.Monitor.Query/CHANGELOG.md | 10 ++++++++++
.../Azure.Monitor.Query/src/Azure.Monitor.Query.csproj | 4 ++--
2 files changed, 12 insertions(+), 2 deletions(-)
diff --git a/sdk/monitor/Azure.Monitor.Query/CHANGELOG.md b/sdk/monitor/Azure.Monitor.Query/CHANGELOG.md
index 0a89caae8b39c..463fdcc858018 100644
--- a/sdk/monitor/Azure.Monitor.Query/CHANGELOG.md
+++ b/sdk/monitor/Azure.Monitor.Query/CHANGELOG.md
@@ -1,5 +1,15 @@
# Release History
+## 1.6.0-beta.1 (Unreleased)
+
+### Features Added
+
+### Breaking Changes
+
+### Bugs Fixed
+
+### Other Changes
+
## 1.5.0 (2024-08-21)
### Bugs Fixed
- Fix bug in `LogsQueryClient` that defaulted to `Azure.PublicCloud`. `Audience` is now determined from the `endpoint` parameter.
diff --git a/sdk/monitor/Azure.Monitor.Query/src/Azure.Monitor.Query.csproj b/sdk/monitor/Azure.Monitor.Query/src/Azure.Monitor.Query.csproj
index efd42c3a2bf8c..e6fcaa9dbbbf2 100644
--- a/sdk/monitor/Azure.Monitor.Query/src/Azure.Monitor.Query.csproj
+++ b/sdk/monitor/Azure.Monitor.Query/src/Azure.Monitor.Query.csproj
@@ -2,9 +2,9 @@
A library for querying Azure Monitor's Logs and Metrics data sources.
Azure Monitor Query client library
- 1.5.0
+ 1.6.0-beta.1
- 1.4.0
+ 1.5.0
Azure Monitor Query
true
$(RequiredTargetFrameworks)
From c0a661fef7aec0a16eebf59eb33dba7de042559e Mon Sep 17 00:00:00 2001
From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com>
Date: Thu, 22 Aug 2024 10:56:24 -0700
Subject: [PATCH 15/71] Increment package version after release of
Azure.ResourceManager.DataFactory (#45562)
---
.../Azure.ResourceManager.DataFactory/CHANGELOG.md | 10 ++++++++++
.../src/Azure.ResourceManager.DataFactory.csproj | 4 ++--
2 files changed, 12 insertions(+), 2 deletions(-)
diff --git a/sdk/datafactory/Azure.ResourceManager.DataFactory/CHANGELOG.md b/sdk/datafactory/Azure.ResourceManager.DataFactory/CHANGELOG.md
index 06a0e0e839005..77afc20c6396f 100644
--- a/sdk/datafactory/Azure.ResourceManager.DataFactory/CHANGELOG.md
+++ b/sdk/datafactory/Azure.ResourceManager.DataFactory/CHANGELOG.md
@@ -1,5 +1,15 @@
# Release History
+## 1.4.0-beta.1 (Unreleased)
+
+### Features Added
+
+### Breaking Changes
+
+### Bugs Fixed
+
+### Other Changes
+
## 1.3.0 (2024-08-16)
### Features Added
diff --git a/sdk/datafactory/Azure.ResourceManager.DataFactory/src/Azure.ResourceManager.DataFactory.csproj b/sdk/datafactory/Azure.ResourceManager.DataFactory/src/Azure.ResourceManager.DataFactory.csproj
index 3d76b61309d6d..77413add30143 100644
--- a/sdk/datafactory/Azure.ResourceManager.DataFactory/src/Azure.ResourceManager.DataFactory.csproj
+++ b/sdk/datafactory/Azure.ResourceManager.DataFactory/src/Azure.ResourceManager.DataFactory.csproj
@@ -1,8 +1,8 @@
- 1.3.0
+ 1.4.0-beta.1
- 1.2.0
+ 1.3.0
Azure.ResourceManager.DataFactory
Microsoft Azure Resource Manager client SDK for Azure resource provider Microsoft.DataFactory.
azure;management;arm;resource manager;datafactory
From 16a351e3959bd0b08215838d67c67816324a756e Mon Sep 17 00:00:00 2001
From: Paul Harrington
Date: Thu, 22 Aug 2024 14:05:03 -0700
Subject: [PATCH 16/71] Introduce overloaded constructor on
AzureEventSourceListener (#45191)
* Introduce overloaded constructor on AzureEventSourceListener taking a delegate without the formatted message.
* Update CHANGELOG
* Use new constructor in tests, where appropriate
* Update public API
---
sdk/core/Azure.Core/CHANGELOG.md | 2 ++
sdk/core/Azure.Core/api/Azure.Core.net461.cs | 1 +
sdk/core/Azure.Core/api/Azure.Core.net472.cs | 1 +
sdk/core/Azure.Core/api/Azure.Core.net6.0.cs | 1 +
.../Azure.Core/api/Azure.Core.netstandard2.0.cs | 1 +
.../Azure.Core/perf/EventSourceBenchmark.cs | 3 ++-
.../src/Diagnostics/AzureEventSourceListener.cs | 17 +++++++++++++----
.../Azure.Core/tests/AzureEventSourceTests.cs | 2 +-
.../Azure.Core/tests/HttpPipelineBuilderTest.cs | 5 +----
9 files changed, 23 insertions(+), 10 deletions(-)
diff --git a/sdk/core/Azure.Core/CHANGELOG.md b/sdk/core/Azure.Core/CHANGELOG.md
index 73dbbcc750940..d35fa12939afc 100644
--- a/sdk/core/Azure.Core/CHANGELOG.md
+++ b/sdk/core/Azure.Core/CHANGELOG.md
@@ -10,6 +10,8 @@
### Other Changes
+- Added a new constructor on `AzureEventSourceListener` for callers that don't need the formatted message ([#45191](https://github.com/Azure/azure-sdk-for-net/pull/45191)).
+
## 1.42.0 (2024-08-01)
### Other Changes
diff --git a/sdk/core/Azure.Core/api/Azure.Core.net461.cs b/sdk/core/Azure.Core/api/Azure.Core.net461.cs
index 5f34b2c37794b..35906202bd9f1 100644
--- a/sdk/core/Azure.Core/api/Azure.Core.net461.cs
+++ b/sdk/core/Azure.Core/api/Azure.Core.net461.cs
@@ -807,6 +807,7 @@ public partial class AzureEventSourceListener : System.Diagnostics.Tracing.Event
public const string TraitName = "AzureEventSource";
public const string TraitValue = "true";
public AzureEventSourceListener(System.Action log, System.Diagnostics.Tracing.EventLevel level) { }
+ public AzureEventSourceListener(System.Action log, System.Diagnostics.Tracing.EventLevel level) { }
public static Azure.Core.Diagnostics.AzureEventSourceListener CreateConsoleLogger(System.Diagnostics.Tracing.EventLevel level = System.Diagnostics.Tracing.EventLevel.Informational) { throw null; }
public static Azure.Core.Diagnostics.AzureEventSourceListener CreateTraceLogger(System.Diagnostics.Tracing.EventLevel level = System.Diagnostics.Tracing.EventLevel.Informational) { throw null; }
protected sealed override void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { }
diff --git a/sdk/core/Azure.Core/api/Azure.Core.net472.cs b/sdk/core/Azure.Core/api/Azure.Core.net472.cs
index 5f34b2c37794b..35906202bd9f1 100644
--- a/sdk/core/Azure.Core/api/Azure.Core.net472.cs
+++ b/sdk/core/Azure.Core/api/Azure.Core.net472.cs
@@ -807,6 +807,7 @@ public partial class AzureEventSourceListener : System.Diagnostics.Tracing.Event
public const string TraitName = "AzureEventSource";
public const string TraitValue = "true";
public AzureEventSourceListener(System.Action log, System.Diagnostics.Tracing.EventLevel level) { }
+ public AzureEventSourceListener(System.Action log, System.Diagnostics.Tracing.EventLevel level) { }
public static Azure.Core.Diagnostics.AzureEventSourceListener CreateConsoleLogger(System.Diagnostics.Tracing.EventLevel level = System.Diagnostics.Tracing.EventLevel.Informational) { throw null; }
public static Azure.Core.Diagnostics.AzureEventSourceListener CreateTraceLogger(System.Diagnostics.Tracing.EventLevel level = System.Diagnostics.Tracing.EventLevel.Informational) { throw null; }
protected sealed override void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { }
diff --git a/sdk/core/Azure.Core/api/Azure.Core.net6.0.cs b/sdk/core/Azure.Core/api/Azure.Core.net6.0.cs
index 7c538465c29bb..9b0a433af9747 100644
--- a/sdk/core/Azure.Core/api/Azure.Core.net6.0.cs
+++ b/sdk/core/Azure.Core/api/Azure.Core.net6.0.cs
@@ -812,6 +812,7 @@ public partial class AzureEventSourceListener : System.Diagnostics.Tracing.Event
public const string TraitName = "AzureEventSource";
public const string TraitValue = "true";
public AzureEventSourceListener(System.Action log, System.Diagnostics.Tracing.EventLevel level) { }
+ public AzureEventSourceListener(System.Action log, System.Diagnostics.Tracing.EventLevel level) { }
public static Azure.Core.Diagnostics.AzureEventSourceListener CreateConsoleLogger(System.Diagnostics.Tracing.EventLevel level = System.Diagnostics.Tracing.EventLevel.Informational) { throw null; }
public static Azure.Core.Diagnostics.AzureEventSourceListener CreateTraceLogger(System.Diagnostics.Tracing.EventLevel level = System.Diagnostics.Tracing.EventLevel.Informational) { throw null; }
protected sealed override void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { }
diff --git a/sdk/core/Azure.Core/api/Azure.Core.netstandard2.0.cs b/sdk/core/Azure.Core/api/Azure.Core.netstandard2.0.cs
index 5f34b2c37794b..35906202bd9f1 100644
--- a/sdk/core/Azure.Core/api/Azure.Core.netstandard2.0.cs
+++ b/sdk/core/Azure.Core/api/Azure.Core.netstandard2.0.cs
@@ -807,6 +807,7 @@ public partial class AzureEventSourceListener : System.Diagnostics.Tracing.Event
public const string TraitName = "AzureEventSource";
public const string TraitValue = "true";
public AzureEventSourceListener(System.Action log, System.Diagnostics.Tracing.EventLevel level) { }
+ public AzureEventSourceListener(System.Action log, System.Diagnostics.Tracing.EventLevel level) { }
public static Azure.Core.Diagnostics.AzureEventSourceListener CreateConsoleLogger(System.Diagnostics.Tracing.EventLevel level = System.Diagnostics.Tracing.EventLevel.Informational) { throw null; }
public static Azure.Core.Diagnostics.AzureEventSourceListener CreateTraceLogger(System.Diagnostics.Tracing.EventLevel level = System.Diagnostics.Tracing.EventLevel.Informational) { throw null; }
protected sealed override void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { }
diff --git a/sdk/core/Azure.Core/perf/EventSourceBenchmark.cs b/sdk/core/Azure.Core/perf/EventSourceBenchmark.cs
index d05eebd0787ad..d4e2e0163c938 100644
--- a/sdk/core/Azure.Core/perf/EventSourceBenchmark.cs
+++ b/sdk/core/Azure.Core/perf/EventSourceBenchmark.cs
@@ -33,7 +33,7 @@ public class EventSourceBenchmark
[GlobalSetup]
public void SetUp()
{
- _sourceListener = new AzureEventSourceListener((_, _) => { }, EventLevel.LogAlways);
+ _sourceListener = new AzureEventSourceListener(_ => { }, EventLevel.LogAlways);
_eventSource = new EventSource();
_sourceListener.EnableEvents(_eventSource, EventLevel.LogAlways);
@@ -84,6 +84,7 @@ private byte[] FormatHeaders()
string newValue = Sanitizer.SanitizeHeader(header.Name, header.Value);
stringBuilder.AppendLine(newValue);
}
+
return Encoding.UTF8.GetBytes(stringBuilder.ToString());
}
diff --git a/sdk/core/Azure.Core/src/Diagnostics/AzureEventSourceListener.cs b/sdk/core/Azure.Core/src/Diagnostics/AzureEventSourceListener.cs
index c0a51d5372fd3..5f66f0bffb580 100644
--- a/sdk/core/Azure.Core/src/Diagnostics/AzureEventSourceListener.cs
+++ b/sdk/core/Azure.Core/src/Diagnostics/AzureEventSourceListener.cs
@@ -25,15 +25,15 @@ public class AzureEventSourceListener: EventListener
public const string TraitValue = "true";
private readonly List _eventSources = new List();
- private readonly Action _log;
+ private readonly Action _log;
private readonly EventLevel _level;
///
/// Creates an instance of that executes a callback every time event is written.
///
- /// The to call when event is written. The second parameter is formatted message.
+ /// The to call when event is written.
/// The level of events to enable.
- public AzureEventSourceListener(Action log, EventLevel level)
+ public AzureEventSourceListener(Action log, EventLevel level)
{
_log = log ?? throw new ArgumentNullException(nameof(log));
@@ -47,6 +47,15 @@ public AzureEventSourceListener(Action log, Event
_eventSources.Clear();
}
+ ///
+ /// Creates an instance of that executes a callback every time event is written.
+ ///
+ /// The to call when event is written. The second parameter is the formatted message.
+ /// The level of events to enable.
+ public AzureEventSourceListener(Action log, EventLevel level) : this(e => log(e, EventSourceEventFormatting.Format(e)), level)
+ {
+ }
+
///
protected sealed override void OnEventSourceCreated(EventSource eventSource)
{
@@ -74,7 +83,7 @@ protected sealed override void OnEventWritten(EventWrittenEventArgs eventData)
// There is a very tight race during the AzureEventSourceListener creation where EnableEvents was called
// and the thread producing events not observing the `_log` field assignment
- _log?.Invoke(eventData, EventSourceEventFormatting.Format(eventData));
+ _log?.Invoke(eventData);
}
///
diff --git a/sdk/core/Azure.Core/tests/AzureEventSourceTests.cs b/sdk/core/Azure.Core/tests/AzureEventSourceTests.cs
index f08008869e280..03d1a1a8bfb8a 100644
--- a/sdk/core/Azure.Core/tests/AzureEventSourceTests.cs
+++ b/sdk/core/Azure.Core/tests/AzureEventSourceTests.cs
@@ -39,7 +39,7 @@ void LogEvent(EventSource azureCoreEventSource)
try
{
List events = new();
- using var listener = new AzureEventSourceListener((args, s) => events.Add(args), EventLevel.Verbose);
+ using var listener = new AzureEventSourceListener(events.Add, EventLevel.Verbose);
alc.LoadFromAssemblyPath(typeof(TestEventSource).Assembly.Location);
alc2.LoadFromAssemblyPath(typeof(TestEventSource).Assembly.Location);
diff --git a/sdk/core/Azure.Core/tests/HttpPipelineBuilderTest.cs b/sdk/core/Azure.Core/tests/HttpPipelineBuilderTest.cs
index a7ee3ab94645d..bc0e6cac371f2 100644
--- a/sdk/core/Azure.Core/tests/HttpPipelineBuilderTest.cs
+++ b/sdk/core/Azure.Core/tests/HttpPipelineBuilderTest.cs
@@ -250,10 +250,7 @@ public void SetTransportOptions([Values(true, false)] bool isCustomTransportSet)
List events = new();
using var listener = new AzureEventSourceListener(
- (args, s) =>
- {
- events.Add(args);
- },
+ events.Add,
EventLevel.Verbose);
var pipeline = HttpPipelineBuilder.Build(
From 150082bd7ac135540c5e3ec145ca596cc7e20716 Mon Sep 17 00:00:00 2001
From: Rajkumar Rangaraj
Date: Thu, 22 Aug 2024 14:05:23 -0700
Subject: [PATCH 17/71] [AzureMonitorDistro] Update
AzureEventSourceLogForwarder defaults to warning (#45649)
* Default log level set to Warning for Azure SDKs
* changelog
* Drop the customization change logic, give complete control to customers.
* Update test
* test change.
---
.../CHANGELOG.md | 6 +
.../AzureEventSourceLogForwarder.cs | 18 ++-
.../src/OpenTelemetryBuilderExtensions.cs | 3 +-
.../AzureSdkLoggingTests.cs | 131 ++++++++++++++++--
4 files changed, 145 insertions(+), 13 deletions(-)
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/CHANGELOG.md b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/CHANGELOG.md
index 32db15360c8c9..ad520cffeae6a 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/CHANGELOG.md
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/CHANGELOG.md
@@ -20,6 +20,12 @@
### Other Changes
+* Updated log collection to default to Warning level and above for Azure SDKs
+ via `Microsoft.Extensions.Logging`. For more information, refer to [Logging
+ with the Azure SDK for
+ .NET](https://learn.microsoft.com/dotnet/azure/sdk/logging).
+ ([#45649](https://github.com/Azure/azure-sdk-for-net/pull/45649))
+
## 1.3.0-beta.1 (2024-07-12)
### Bugs Fixed
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/Internals/AzureSdkCompat/AzureEventSourceLogForwarder.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/Internals/AzureSdkCompat/AzureEventSourceLogForwarder.cs
index 81120d325d82a..e8d1f476644a5 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/Internals/AzureSdkCompat/AzureEventSourceLogForwarder.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/Internals/AzureSdkCompat/AzureEventSourceLogForwarder.cs
@@ -14,8 +14,9 @@ namespace Azure.Monitor.OpenTelemetry.AspNetCore.Internals.AzureSdkCompat
{
internal sealed class AzureEventSourceLogForwarder : IHostedService, IDisposable
{
- internal static readonly AzureEventSourceLogForwarder Noop = new AzureEventSourceLogForwarder(null);
+ internal static readonly AzureEventSourceLogForwarder Noop = new AzureEventSourceLogForwarder(null, null);
private readonly ILoggerFactory _loggerFactory;
+ private readonly bool _hasAzureLoggerFilterOptionsRules = false;
private readonly ConcurrentDictionary _loggers = new ConcurrentDictionary();
@@ -23,9 +24,18 @@ internal sealed class AzureEventSourceLogForwarder : IHostedService, IDisposable
private AzureEventSourceListener _listener;
- public AzureEventSourceLogForwarder(ILoggerFactory loggerFactory)
+ public AzureEventSourceLogForwarder(ILoggerFactory loggerFactory, LoggerFilterOptions loggerFilterOptions)
{
_loggerFactory = loggerFactory;
+
+ foreach (var rule in loggerFilterOptions?.Rules ?? Enumerable.Empty())
+ {
+ if (!string.IsNullOrEmpty(rule.CategoryName) &&
+ (rule.CategoryName.StartsWith("Azure.") || rule.CategoryName.StartsWith("Microsoft.Azure.")))
+ {
+ _hasAzureLoggerFilterOptionsRules = true;
+ }
+ }
}
private void LogEvent(EventWrittenEventArgs eventData)
@@ -67,7 +77,9 @@ public Task StartAsync(CancellationToken cancellationToken)
{
if (_loggerFactory != null)
{
- _listener ??= new AzureEventSourceListener((e, s) => LogEvent(e), EventLevel.Verbose);
+ // Setting even a single custom filter for Azure SDK logs will reset the default warning level and switch to listening at the verbose level.
+ // This gives the customer full control over the log levels for all Azure SDK components.
+ _listener ??= new AzureEventSourceListener((e, s) => LogEvent(e), _hasAzureLoggerFilterOptionsRules ? EventLevel.Verbose : EventLevel.Warning);
}
return Task.CompletedTask;
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/OpenTelemetryBuilderExtensions.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/OpenTelemetryBuilderExtensions.cs
index 6b3a6167abbd9..a3ad51fe2019e 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/OpenTelemetryBuilderExtensions.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/OpenTelemetryBuilderExtensions.cs
@@ -176,7 +176,8 @@ public static OpenTelemetryBuilder UseAzureMonitor(this OpenTelemetryBuilder bui
}
var loggerFactory = sp.GetRequiredService();
- return new AzureEventSourceLogForwarder(loggerFactory);
+ var loggerFilterOptions = sp.GetRequiredService>().CurrentValue;
+ return new AzureEventSourceLogForwarder(loggerFactory, loggerFilterOptions);
});
// Register Manager as a singleton
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/AzureSdkLoggingTests.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/AzureSdkLoggingTests.cs
index d2b336bb29325..99e574bd694ce 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/AzureSdkLoggingTests.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/AzureSdkLoggingTests.cs
@@ -27,19 +27,27 @@ public class AzureSdkLoggingTests
#else
[Theory]
#endif
- [InlineData(LogLevel.Information, "TestInfoEvent: hello")]
- [InlineData(LogLevel.Warning, "TestWarningEvent: hello")]
- [InlineData(LogLevel.Debug, null)]
- public async Task DistroLogForwarderIsAdded(LogLevel eventLevel, string expectedMessage)
+ [InlineData(false, LogLevel.Debug, null)]
+ [InlineData(false, LogLevel.Information, null)]
+ [InlineData(false, LogLevel.Warning, "TestWarningEvent: hello")]
+ [InlineData(true, LogLevel.Information, "TestInfoEvent: hello")]
+ [InlineData(true, LogLevel.Warning, "TestWarningEvent: hello")]
+ [InlineData(true, LogLevel.Debug, "TestVerboseEvent: hello")]
+ public async Task DistroLogForwarderIsAdded(bool addLoggingFilter, LogLevel eventLevel, string expectedMessage)
{
var builder = WebApplication.CreateBuilder();
+ using TestEventSource source = new TestEventSource(addLoggingFilter ? "Azure-LoggingFilter" : "Azure-Test");
+
+ if (addLoggingFilter)
+ {
+ builder.Logging.AddFilter(source.Name.Replace('-', '.'), eventLevel);
+ }
var transport = new MockTransport(_ => new MockResponse(200).SetContent("ok"));
SetUpOTelAndLogging(builder, transport, LogLevel.Information);
using var app = builder.Build();
await app.StartAsync();
- using TestEventSource source = new TestEventSource();
Assert.True(source.IsEnabled());
source.LogMessage("hello", eventLevel);
WaitForRequest(transport);
@@ -79,7 +87,7 @@ public async Task PublicLogForwarderIsAdded(LogLevel eventLevel, string expected
await app.StartAsync();
- using TestEventSource source = new TestEventSource();
+ using TestEventSource source = new TestEventSource("Azure-Test");
Assert.True(source.IsEnabled());
source.LogMessage("hello", eventLevel);
@@ -140,6 +148,99 @@ public async Task SelfDiagnosticsIsDisabled()
Assert.False(logAzureFilterCalled);
}
+ [Fact]
+ public async Task DistroLogForwarderAppliesWildCardFilter()
+ {
+ var builder = WebApplication.CreateBuilder();
+ builder.Logging.AddFilter("Azure.*", LogLevel.Warning);
+
+ var transport = new MockTransport(_ => new MockResponse(200).SetContent("ok"));
+ SetUpOTelAndLogging(builder, transport, LogLevel.Information);
+
+ using var app = builder.Build();
+ await app.StartAsync();
+
+ using TestEventSource source = new TestEventSource("Azure-Test");
+ Assert.True(source.IsEnabled());
+ source.LogMessage("hello", LogLevel.Warning);
+ WaitForRequest(transport);
+
+ Assert.Single(transport.Requests);
+ await AssertContentContains(transport.Requests.Single(), "TestWarningEvent: hello", LogLevel.Warning);
+ }
+
+ [Fact]
+ public async Task SettingCustomLoggingFilterResetsDefaultWarningLevel()
+ {
+ var builder = WebApplication.CreateBuilder();
+ // Even when a single custom filter is set, it should reset the default warning level.
+ builder.Logging.AddFilter("Azure.One", LogLevel.Information);
+
+ var transport = new MockTransport(_ => new MockResponse(200).SetContent("ok"));
+ SetUpOTelAndLogging(builder, transport, LogLevel.Information);
+
+ using var app = builder.Build();
+ await app.StartAsync();
+
+ // Azure-One is added as a logging filter, the default warning level is reset.
+ // Informational-level logs from Azure-One sources are collected.
+ using TestEventSource source1 = new TestEventSource("Azure-One");
+ Assert.True(source1.IsEnabled());
+
+ source1.LogMessage("hello one", LogLevel.Information);
+ WaitForRequest(transport);
+ Assert.Single(transport.Requests);
+ await AssertContentContains(transport.Requests.Single(), "TestInfoEvent: hello one", LogLevel.Information);
+ transport.Requests.Clear();
+
+ // Azure-Two is not part of the logging filter.
+ // Since the logging filter is customized for the Azure SDK, the default warning level is reset.
+ // Informational-level logs from Azure-Two sources are collected.
+ using TestEventSource source2 = new TestEventSource("Azure-Two");
+ Assert.True(source2.IsEnabled());
+
+ source2.LogMessage("hello two", LogLevel.Information);
+ WaitForRequest(transport);
+ Assert.Single(transport.Requests);
+ await AssertContentContains(transport.Requests.Single(), "TestInfoEvent: hello two", LogLevel.Information);
+ }
+
+ [Fact]
+ public async Task CustomLoggingFilterOverridesDefaultWarningAndCapturesErrorLogs()
+ {
+ var builder = WebApplication.CreateBuilder();
+ // Even when a single custom filter is set, it should reset the default warning level.
+ builder.Logging.AddFilter("Azure.One", LogLevel.Error);
+
+ var transport = new MockTransport(_ => new MockResponse(200).SetContent("ok"));
+ SetUpOTelAndLogging(builder, transport, LogLevel.Information);
+
+ using var app = builder.Build();
+ await app.StartAsync();
+
+ using TestEventSource source1 = new TestEventSource("Azure-One");
+ Assert.True(source1.IsEnabled());
+
+ // Only log level with errors should be captured as it is set in the logging filter.
+ source1.LogMessage("Hello Information", LogLevel.Information);
+ source1.LogMessage("Hello Debug", LogLevel.Debug);
+ source1.LogMessage("Hello Warning", LogLevel.Warning);
+ source1.LogMessage("Hello Error", LogLevel.Error);
+ WaitForRequest(transport);
+ Assert.Single(transport.Requests);
+ await AssertContentContains(transport.Requests.Single(), "TestErrorEvent: Hello Error", LogLevel.Error);
+
+ // Azure-Two is not part of the logging filter, it should capture all logs.
+ using TestEventSource source2 = new TestEventSource("Azure-Two");
+ Assert.True(source2.IsEnabled());
+ transport.Requests.Clear();
+
+ source2.LogMessage("hello two", LogLevel.Information);
+ WaitForRequest(transport);
+ Assert.Single(transport.Requests);
+ await AssertContentContains(transport.Requests.Single(), "TestInfoEvent: hello two", LogLevel.Information);
+ }
+
private IEnumerable WaitForRequest(MockTransport transport, Func? filter = null)
{
filter = filter ?? (_ => true);
@@ -161,7 +262,8 @@ private static async Task AssertContentContains(MockRequest request, str
contentStream.Position = 0;
var content = BinaryData.FromStream(contentStream).ToString();
var jsonMessage = $"\"message\":\"{expectedMessage}\"";
- var jsonLevel = $"\"severityLevel\":\"{expectedLevel}\"";
+ var level = expectedLevel == LogLevel.Debug ? "Verbose" : expectedLevel.ToString();
+ var jsonLevel = $"\"severityLevel\":\"{level}\"";
Assert.Contains(jsonMessage, content);
Assert.Contains(jsonLevel, content);
@@ -206,9 +308,11 @@ private static void SetUpOTelAndLogging(WebApplicationBuilder builder, MockTrans
internal class TestEventSource : AzureEventSource
{
- private const string EventSourceName = "Azure-Test";
- public TestEventSource() : base(EventSourceName)
+ private readonly string EventSourceName;
+
+ public TestEventSource(string eventSourceName) : base(eventSourceName)
{
+ EventSourceName = eventSourceName;
}
[Event(1, Level = EventLevel.Informational, Message = "TestInfoEvent: {0}")]
@@ -229,10 +333,19 @@ public void LogTestWarningEvent(string message)
WriteEvent(3, message);
}
+ [Event(4, Level = EventLevel.Error, Message = "TestErrorEvent: {0}")]
+ public void LogTestErrorEvent(string message)
+ {
+ WriteEvent(4, message);
+ }
+
public void LogMessage(string message, LogLevel level)
{
switch (level)
{
+ case LogLevel.Error:
+ LogTestErrorEvent(message);
+ break;
case LogLevel.Warning:
LogTestWarningEvent(message);
break;
From cf860363b0a20eefcb783c0289802701e3878cf7 Mon Sep 17 00:00:00 2001
From: Timothy Mothra
Date: Fri, 23 Aug 2024 11:10:30 -0700
Subject: [PATCH 18/71] disable tests in net6 and MacOS (#45656)
---
.../AzureSdkLoggingTests.cs | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/AzureSdkLoggingTests.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/AzureSdkLoggingTests.cs
index 99e574bd694ce..773abfebf60bb 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/AzureSdkLoggingTests.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/AzureSdkLoggingTests.cs
@@ -148,7 +148,11 @@ public async Task SelfDiagnosticsIsDisabled()
Assert.False(logAzureFilterCalled);
}
+#if NET6_0
+ [ConditionallySkipOSFact(platformToSkip: "macos", reason: "This test consistently exceeds 1 hour runtime limit when running on MacOS & Net60")]
+#else
[Fact]
+#endif
public async Task DistroLogForwarderAppliesWildCardFilter()
{
var builder = WebApplication.CreateBuilder();
@@ -169,7 +173,11 @@ public async Task DistroLogForwarderAppliesWildCardFilter()
await AssertContentContains(transport.Requests.Single(), "TestWarningEvent: hello", LogLevel.Warning);
}
+#if NET6_0
+ [ConditionallySkipOSFact(platformToSkip: "macos", reason: "This test consistently exceeds 1 hour runtime limit when running on MacOS & Net60")]
+#else
[Fact]
+#endif
public async Task SettingCustomLoggingFilterResetsDefaultWarningLevel()
{
var builder = WebApplication.CreateBuilder();
@@ -205,7 +213,11 @@ public async Task SettingCustomLoggingFilterResetsDefaultWarningLevel()
await AssertContentContains(transport.Requests.Single(), "TestInfoEvent: hello two", LogLevel.Information);
}
+#if NET6_0
+ [ConditionallySkipOSFact(platformToSkip: "macos", reason: "This test consistently exceeds 1 hour runtime limit when running on MacOS & Net60")]
+#else
[Fact]
+#endif
public async Task CustomLoggingFilterOverridesDefaultWarningAndCapturesErrorLogs()
{
var builder = WebApplication.CreateBuilder();
From 91dc3f14f2d219c61ec7cdb715764becfce8fc73 Mon Sep 17 00:00:00 2001
From: Timothy Mothra
Date: Fri, 23 Aug 2024 13:11:56 -0700
Subject: [PATCH 19/71] [AzureMonitorDistro] fix for LiveMetrics Dependencies
(#45103)
* fix for LiveMetrics and manual Dependencies
* changelog
* update all dependency mappings
* fix
* update tests
* cleanup
* cleanup
* drop ActivityType
* changelog
* update changelog
* update mappings
* fix tests
---
.../CHANGELOG.md | 6 ++
.../DataCollection/DocumentHelper.cs | 41 +++++++-----
.../DocumentTests/HttpClientDependecyTests.cs | 4 +-
.../DocumentTests/ManualDependencyTests.cs | 66 +++++++++++++++++++
.../DocumentTests/SqlClientDependencyTests.cs | 8 +--
5 files changed, 101 insertions(+), 24 deletions(-)
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/DocumentTests/ManualDependencyTests.cs
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/CHANGELOG.md b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/CHANGELOG.md
index ad520cffeae6a..9351eb7c2f83b 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/CHANGELOG.md
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/CHANGELOG.md
@@ -18,8 +18,14 @@
* Fixed a bug where LiveMetrics displays "UNKNOWN_INSTANCE" and "UNKNOWN_NAME" for "server name" and "role name" respectively.
([#45433](https://github.com/Azure/azure-sdk-for-net/pull/45433))
+* Fixed a bug in LiveMetrics that counted all manually created Dependencies as failures.
+ ([#45103](https://github.com/Azure/azure-sdk-for-net/pull/45103))
+
### Other Changes
+* Updated field mappings for telemetry sent to LiveMetrics.
+ ([#45103](https://github.com/Azure/azure-sdk-for-net/pull/45103))
+
* Updated log collection to default to Warning level and above for Azure SDKs
via `Microsoft.Extensions.Logging`. For more information, refer to [Logging
with the Azure SDK for
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/DataCollection/DocumentHelper.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/DataCollection/DocumentHelper.cs
index c4727d0dbc4bb..a083e3ede32b2 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/DataCollection/DocumentHelper.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/LiveMetrics/DataCollection/DocumentHelper.cs
@@ -108,8 +108,13 @@ internal static RemoteDependency ConvertToDependencyDocument(Activity activity)
RemoteDependency remoteDependencyDocument = new()
{
DocumentType = DocumentType.RemoteDependency,
+ Duration = activity.Duration < SchemaConstants.RemoteDependencyData_Duration_LessThanDays
+ ? activity.Duration.ToString("c", CultureInfo.InvariantCulture)
+ : SchemaConstants.Duration_MaxValue,
+
// The following "EXTENSION" properties are used to calculate metrics. These are not serialized.
Extension_Duration = activity.Duration.TotalMilliseconds,
+ Extension_IsSuccess = activity.Status != ActivityStatusCode.Error,
};
var liveMetricsTagsProcessor = new LiveMetricsTagsProcessor();
@@ -119,41 +124,41 @@ internal static RemoteDependency ConvertToDependencyDocument(Activity activity)
{
case OperationType.Http:
remoteDependencyDocument.Name = activity.DisplayName;
- remoteDependencyDocument.CommandName = AzMonList.GetTagValue(ref liveMetricsTagsProcessor.Tags, SemanticConventions.AttributeUrlFull)?.ToString();
+
+ var httpUrl = AzMonList.GetTagValue(ref liveMetricsTagsProcessor.Tags, SemanticConventions.AttributeUrlFull)?.ToString();
+ remoteDependencyDocument.CommandName = httpUrl;
+
var httpResponseStatusCode = AzMonList.GetTagValue(ref liveMetricsTagsProcessor.Tags, SemanticConventions.AttributeHttpResponseStatusCode)?.ToString();
- remoteDependencyDocument.ResultCode = httpResponseStatusCode;
- remoteDependencyDocument.Duration = activity.Duration < SchemaConstants.RequestData_Duration_LessThanDays
- ? activity.Duration.ToString("c", CultureInfo.InvariantCulture)
- : SchemaConstants.Duration_MaxValue;
+ remoteDependencyDocument.ResultCode = httpResponseStatusCode ?? "0";
// The following "EXTENSION" properties are used to calculate metrics. These are not serialized.
remoteDependencyDocument.Extension_IsSuccess = IsHttpSuccess(activity, httpResponseStatusCode);
break;
case OperationType.Db:
- // Note: The Exception details are recorded in Activity.Events only if the configuration has opt-ed into this (SqlClientInstrumentationOptions.RecordException).
-
- var (_, dbTarget) = liveMetricsTagsProcessor.Tags.GetDbDependencyTargetAndName();
+ remoteDependencyDocument.Name = activity.DisplayName;
- remoteDependencyDocument.Name = dbTarget;
remoteDependencyDocument.CommandName = AzMonList.GetTagValue(ref liveMetricsTagsProcessor.Tags, SemanticConventions.AttributeDbStatement)?.ToString();
- remoteDependencyDocument.Duration = activity.Duration.ToString("c", CultureInfo.InvariantCulture);
// TODO: remoteDependencyDocumentIngress.ResultCode = "";
// AI SDK reads a Number property from Connection or Command objects.
// As of Feb 2024, OpenTelemetry doesn't record this. This may change in the future when the semantic convention stabalizes.
- // The following "EXTENSION" properties are used to calculate metrics. These are not serialized.
- remoteDependencyDocument.Extension_IsSuccess = activity.Status != ActivityStatusCode.Error;
- break;
- case OperationType.Rpc:
- // TODO RPC
break;
case OperationType.Messaging:
- // TODO MESSAGING
+ remoteDependencyDocument.Name = activity.DisplayName;
+
+ var (messagingUrl, _) = liveMetricsTagsProcessor.Tags.GetMessagingUrlAndSourceOrTarget(activity.Kind);
+ remoteDependencyDocument.CommandName = messagingUrl;
+
break;
+ case OperationType.Rpc:
+ // remoteDependencyDocument.Name = activity.DisplayName;
+ // remoteDependencyDocument.CommandName = AzMonList.GetTagValue(ref liveMetricsTagsProcessor.Tags, SemanticConventions.AttributeRpcService)?.ToString();
+ // remoteDependencyDocument.ResultCode = AzMonList.GetTagValue(ref liveMetricsTagsProcessor.Tags, SemanticConventions.AttributeRpcStatus)?.ToString();
default:
- // Unknown or Unexpected Dependency Type
- remoteDependencyDocument.Name = liveMetricsTagsProcessor.ActivityType.ToString();
+ // Unknown or Manual or Unexpected Dependency Type
+ remoteDependencyDocument.Name = activity.DisplayName;
+ remoteDependencyDocument.Properties.Add(new KeyValuePairString("ActivitySource", activity.Source.Name));
break;
}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/DocumentTests/HttpClientDependecyTests.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/DocumentTests/HttpClientDependecyTests.cs
index 0a1f042a6a072..828d42055c467 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/DocumentTests/HttpClientDependecyTests.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/DocumentTests/HttpClientDependecyTests.cs
@@ -43,7 +43,7 @@ public void VerifyHttpClientAttributes()
ActivitySource.AddActivityListener(listener);
// ACT
- using var dependencyActivity = activitySource.StartActivity(name: "HelloWorld", kind: ActivityKind.Client);
+ using var dependencyActivity = activitySource.StartActivity(name: "TestActivityName", kind: ActivityKind.Client);
Assert.NotNull(dependencyActivity);
dependencyActivity.SetTag("http.request.method", "GET");
dependencyActivity.SetTag("url.full", "http://bing.com");
@@ -67,7 +67,7 @@ public void VerifyHttpClientAttributes()
// ASSERT
Assert.Equal("http://bing.com", dependencyDocument.CommandName);
Assert.Equal(DocumentType.RemoteDependency, dependencyDocument.DocumentType);
- Assert.Equal("HelloWorld", dependencyDocument.Name);
+ Assert.Equal("TestActivityName", dependencyDocument.Name);
Assert.Equal("200", dependencyDocument.ResultCode);
VerifyCustomProperties(dependencyDocument);
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/DocumentTests/ManualDependencyTests.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/DocumentTests/ManualDependencyTests.cs
new file mode 100644
index 0000000000000..5df314e5098fe
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/DocumentTests/ManualDependencyTests.cs
@@ -0,0 +1,66 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Net.Http;
+using System.Threading.Tasks;
+using Azure.Monitor.OpenTelemetry.AspNetCore.LiveMetrics.DataCollection;
+using Azure.Monitor.OpenTelemetry.AspNetCore.Models;
+using Microsoft.AspNetCore.Builder;
+using OpenTelemetry;
+using OpenTelemetry.Trace;
+using Xunit;
+using Xunit.Abstractions;
+
+namespace Azure.Monitor.OpenTelemetry.AspNetCore.Tests.LiveMetrics.DocumentTests
+{
+ public class ManualDependencyTests : DocumentTestBase
+ {
+ public ManualDependencyTests(ITestOutputHelper output) : base(output)
+ {
+ }
+
+ [Theory]
+ [InlineData(ActivityStatusCode.Ok, true)]
+ [InlineData(ActivityStatusCode.Error, false)]
+ [InlineData(ActivityStatusCode.Unset, true)]
+ public void VerifyManualDependency(ActivityStatusCode activityStatusCode, bool expectedIsSuccess)
+ {
+ var exportedActivities = new List();
+
+ var testActivitySource = new ActivitySource("TestActivitySource");
+
+ // SETUP
+ using var tracerProvider = Sdk.CreateTracerProviderBuilder()
+ .AddSource("TestActivitySource")
+ .AddInMemoryExporter(exportedActivities)
+ .Build();
+
+ // ACT
+ using (var activity = testActivitySource.StartActivity("TestActivityName", ActivityKind.Internal))
+ {
+ activity?.SetStatus(activityStatusCode);
+ }
+
+ tracerProvider.ForceFlush();
+ WaitForActivityExport(exportedActivities);
+
+ // Assert
+ var dependencyActivity = exportedActivities.Last();
+ PrintActivity(dependencyActivity);
+ var dependencyDocument = DocumentHelper.ConvertToDependencyDocument(dependencyActivity);
+
+ Assert.Null(dependencyDocument.CommandName);
+ Assert.Equal(DocumentType.RemoteDependency, dependencyDocument.DocumentType);
+ Assert.Equal("TestActivityName", dependencyDocument.Name);
+ Assert.Equal("TestActivitySource", dependencyDocument.Properties.Single(x => x.Key == "ActivitySource").Value);
+
+ //// The following "EXTENSION" properties are used to calculate metrics. These are not serialized.
+ Assert.Equal(dependencyActivity.Duration.TotalMilliseconds, dependencyDocument.Extension_Duration);
+ Assert.Equal(expectedIsSuccess, dependencyDocument.Extension_IsSuccess);
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/DocumentTests/SqlClientDependencyTests.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/DocumentTests/SqlClientDependencyTests.cs
index 83201283846aa..fa6a782ff2bbe 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/DocumentTests/SqlClientDependencyTests.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/LiveMetrics/DocumentTests/SqlClientDependencyTests.cs
@@ -46,7 +46,7 @@ public void VerifySqlClientAttributes()
ActivitySource.AddActivityListener(listener);
// ACT
- using var dependencyActivity = activitySource.StartActivity(name: "HelloWorld", kind: ActivityKind.Client);
+ using var dependencyActivity = activitySource.StartActivity(name: "TestActivityName", kind: ActivityKind.Client);
Assert.NotNull(dependencyActivity);
dependencyActivity.SetTag("db.system", "mssql");
dependencyActivity.SetTag("db.name", "MyDatabase");
@@ -71,7 +71,7 @@ public void VerifySqlClientAttributes()
Assert.Equal("select * from sys.databases", dependencyDocument.CommandName);
Assert.Equal(DocumentType.RemoteDependency, dependencyDocument.DocumentType);
Assert.Equal(dependencyActivity.Duration.ToString("c"), dependencyDocument.Duration);
- Assert.Equal("(localdb)\\MSSQLLocalDB | MyDatabase", dependencyDocument.Name);
+ Assert.Equal("TestActivityName", dependencyDocument.Name);
VerifyCustomProperties(dependencyDocument);
@@ -141,7 +141,7 @@ public void VerifySqlClientDependency(
Assert.Equal(commandText, dependencyDocument.CommandName);
Assert.Equal(DocumentType.RemoteDependency, dependencyDocument.DocumentType);
Assert.Equal(dependencyActivity.Duration.ToString("c"), dependencyDocument.Duration);
- Assert.Equal("(localdb)\\MSSQLLocalDB | MyDatabase", dependencyDocument.Name);
+ Assert.Equal("MyDatabase", dependencyDocument.Name);
// The following "EXTENSION" properties are used to calculate metrics. These are not serialized.
Assert.Equal(dependencyActivity.Duration.TotalMilliseconds, dependencyDocument.Extension_Duration);
@@ -214,7 +214,7 @@ public void VerifySqlClientDependencyWithException(
Assert.Equal(commandText, dependencyDocument.CommandName);
Assert.Equal(DocumentType.RemoteDependency, dependencyDocument.DocumentType);
Assert.Equal(dependencyActivity.Duration.ToString("c"), dependencyDocument.Duration);
- Assert.Equal("(localdb)\\MSSQLLocalDB | MyDatabase", dependencyDocument.Name);
+ Assert.Equal("MyDatabase", dependencyDocument.Name);
// The following "EXTENSION" properties are used to calculate metrics. These are not serialized.
Assert.Equal(dependencyActivity.Duration.TotalMilliseconds, dependencyDocument.Extension_Duration);
From df209754cbfaf90e0b7e67664e00afa26c2df6a8 Mon Sep 17 00:00:00 2001
From: Vishwesh Bankwar
Date: Fri, 23 Aug 2024 16:07:21 -0700
Subject: [PATCH 20/71] Add support for logging custom events (#45630)
* Add support for logging custom events
* fix test
* review
* namespace rename
* rename
* api
* rename
* refactor
* todo
* change loglevl and apply filter
* Add tests
* nt
* refactor
* review
* skip -azure forwarder tests + address feedback
* revert signature change
---
...re.Monitor.OpenTelemetry.AspNetCore.csproj | 4 +-
.../src/OpenTelemetryBuilderExtensions.cs | 30 +++
.../AzureSdkLoggingTests.cs | 36 +---
.../E2ETests/ILoggerTests.cs | 187 ++++++++++++++++++
...e.Monitor.OpenTelemetry.Exporter.net6.0.cs | 12 ++
...r.OpenTelemetry.Exporter.netstandard2.0.cs | 12 ++
.../ApplicationInsightsEventLogger.cs | 43 ++++
.../IApplicationInsightsEventLogger.cs | 20 ++
.../Models/TelemetryEventData.cs | 26 +++
.../Customizations/Models/TelemetryItem.cs | 4 +-
.../src/Internals/LogsHelper.cs | 12 +-
.../TelemetryItemOutputHelper.cs | 14 ++
.../LogsHelperTests.cs | 40 ++++
13 files changed, 405 insertions(+), 35 deletions(-)
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/E2ETests/ILoggerTests.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/CustomEvents/ApplicationInsightsEventLogger.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/CustomEvents/IApplicationInsightsEventLogger.cs
create mode 100644 sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/Models/TelemetryEventData.cs
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/Azure.Monitor.OpenTelemetry.AspNetCore.csproj b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/Azure.Monitor.OpenTelemetry.AspNetCore.csproj
index 2474f074dc023..1e16c984cda59 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/Azure.Monitor.OpenTelemetry.AspNetCore.csproj
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/Azure.Monitor.OpenTelemetry.AspNetCore.csproj
@@ -23,10 +23,10 @@
-
+
-
+
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/OpenTelemetryBuilderExtensions.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/OpenTelemetryBuilderExtensions.cs
index a3ad51fe2019e..4906a3aff5659 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/OpenTelemetryBuilderExtensions.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/OpenTelemetryBuilderExtensions.cs
@@ -6,6 +6,7 @@
using Azure.Monitor.OpenTelemetry.AspNetCore.Internals.LiveMetrics;
using Azure.Monitor.OpenTelemetry.AspNetCore.Internals.Profiling;
using Azure.Monitor.OpenTelemetry.AspNetCore.LiveMetrics;
+using Azure.Monitor.OpenTelemetry.Events;
using Azure.Monitor.OpenTelemetry.Exporter;
using Azure.Monitor.OpenTelemetry.Exporter.Internals.Platform;
using Microsoft.Extensions.Configuration;
@@ -28,6 +29,7 @@ namespace Azure.Monitor.OpenTelemetry.AspNetCore
public static class OpenTelemetryBuilderExtensions
{
private const string SqlClientInstrumentationPackageName = "OpenTelemetry.Instrumentation.SqlClient";
+ private const string EventLoggerName = "Azure.Monitor.OpenTelemetry.CustomEvents";
///
/// Configures Azure Monitor for logging, distributed tracing, and metrics.
@@ -212,6 +214,34 @@ public static OpenTelemetryBuilder UseAzureMonitor(this OpenTelemetryBuilder bui
}
});
+ // Enable custom events and set filter to enable collection.
+ builder.Services.TryAddSingleton();
+
+ // The default behavior is to always capture logs for custom events.
+ // This can achieved with this code level filter -> loggingBuilder.AddFilter("",LogLevel.Information);
+ // However, this may run into issues when users try to override this behavior from Configuration like below using appsettings.json:
+ // {
+ // "Logging": {
+ // "OpenTelemetry": {
+ // "LogLevel": {
+ // "Azure.Monitor.OpenTelemetry.CustomEvents": "None"
+ // }
+ // }
+ // },
+ // ...
+ // }
+ // The reason is as both rules will match the filter, the last one added wins.
+ // To ensure that the default filter is in the beginning of filter rules, so that user override from Configuration will always win,
+ // we add code filter rule to the 0th position as below.
+ builder.Services.Configure(
+ options => options.Rules.Insert(
+ 0,
+ new LoggerFilterRule(
+ "OpenTelemetry",
+ EventLoggerName,
+ LogLevel.Information,
+ null)));
+
return builder;
}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/AzureSdkLoggingTests.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/AzureSdkLoggingTests.cs
index 773abfebf60bb..c2c5fd0e6e786 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/AzureSdkLoggingTests.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/AzureSdkLoggingTests.cs
@@ -22,11 +22,7 @@ namespace Azure.Monitor.OpenTelemetry.AspNetCore.Tests
{
public class AzureSdkLoggingTests
{
-#if NET6_0
- [ConditionallySkipOSTheory(platformToSkip: "macos", reason: "This test consistently exceeds 1 hour runtime limit when running on MacOS & Net60")]
-#else
- [Theory]
-#endif
+ [Theory(Skip = "Test is unstable and need to be re-written without the need to create a web server.")]
[InlineData(false, LogLevel.Debug, null)]
[InlineData(false, LogLevel.Information, null)]
[InlineData(false, LogLevel.Warning, "TestWarningEvent: hello")]
@@ -62,11 +58,7 @@ public async Task DistroLogForwarderIsAdded(bool addLoggingFilter, LogLevel even
}
}
-#if NET6_0
- [ConditionallySkipOSTheory(platformToSkip: "macos", reason: "This test consistently exceeds 1 hour runtime limit when running on MacOS & Net60")]
-#else
- [Theory]
-#endif
+ [Theory(Skip = "Test is unstable and need to be re-written without the need to create a web server.")]
[InlineData(LogLevel.Information, "TestInfoEvent: hello")]
[InlineData(LogLevel.Warning, "TestWarningEvent: hello")]
[InlineData(LogLevel.Debug, null)]
@@ -103,11 +95,7 @@ public async Task PublicLogForwarderIsAdded(LogLevel eventLevel, string expected
}
}
-#if NET6_0
- [ConditionallySkipOSFact(platformToSkip: "macos", reason: "This test consistently exceeds 1 hour runtime limit when running on MacOS & Net60")]
-#else
- [Fact]
-#endif
+ [Fact(Skip = "Test is unstable and need to be re-written without the need to create a web server.")]
public async Task SelfDiagnosticsIsDisabled()
{
var enableLevel = LogLevel.Debug;
@@ -148,11 +136,7 @@ public async Task SelfDiagnosticsIsDisabled()
Assert.False(logAzureFilterCalled);
}
-#if NET6_0
- [ConditionallySkipOSFact(platformToSkip: "macos", reason: "This test consistently exceeds 1 hour runtime limit when running on MacOS & Net60")]
-#else
- [Fact]
-#endif
+ [Fact(Skip = "Test is unstable and need to be re-written without the need to create a web server.")]
public async Task DistroLogForwarderAppliesWildCardFilter()
{
var builder = WebApplication.CreateBuilder();
@@ -173,11 +157,7 @@ public async Task DistroLogForwarderAppliesWildCardFilter()
await AssertContentContains(transport.Requests.Single(), "TestWarningEvent: hello", LogLevel.Warning);
}
-#if NET6_0
- [ConditionallySkipOSFact(platformToSkip: "macos", reason: "This test consistently exceeds 1 hour runtime limit when running on MacOS & Net60")]
-#else
- [Fact]
-#endif
+ [Fact(Skip = "Test is unstable and need to be re-written without the need to create a web server.")]
public async Task SettingCustomLoggingFilterResetsDefaultWarningLevel()
{
var builder = WebApplication.CreateBuilder();
@@ -213,11 +193,7 @@ public async Task SettingCustomLoggingFilterResetsDefaultWarningLevel()
await AssertContentContains(transport.Requests.Single(), "TestInfoEvent: hello two", LogLevel.Information);
}
-#if NET6_0
- [ConditionallySkipOSFact(platformToSkip: "macos", reason: "This test consistently exceeds 1 hour runtime limit when running on MacOS & Net60")]
-#else
- [Fact]
-#endif
+ [Fact(Skip = "Test is unstable and need to be re-written without the need to create a web server.")]
public async Task CustomLoggingFilterOverridesDefaultWarningAndCapturesErrorLogs()
{
var builder = WebApplication.CreateBuilder();
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/E2ETests/ILoggerTests.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/E2ETests/ILoggerTests.cs
new file mode 100644
index 0000000000000..c6b5368c5f5d3
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/tests/Azure.Monitor.OpenTelemetry.AspNetCore.Tests/E2ETests/ILoggerTests.cs
@@ -0,0 +1,187 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+#if !NETFRAMEWORK
+using System;
+using System.Collections.Generic;
+using System.Data;
+using System.Linq;
+using Azure.Monitor.OpenTelemetry.Events;
+using Azure.Monitor.OpenTelemetry.Exporter.Models;
+using Azure.Monitor.OpenTelemetry.Exporter.Tests.CommonTestFramework;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.AspNetCore.TestHost;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using OpenTelemetry.Logs;
+using OpenTelemetry.Trace;
+using Xunit;
+using Xunit.Abstractions;
+
+namespace Azure.Monitor.OpenTelemetry.AspNetCore.Tests.E2ETests
+{
+ public partial class ILoggerTests
+ : IClassFixture>, IDisposable
+ {
+ private readonly WebApplicationFactory _factory;
+ private readonly TelemetryItemOutputHelper _telemetryOutput;
+
+ public ILoggerTests(WebApplicationFactory factory, ITestOutputHelper output)
+ {
+ _factory = factory;
+ _telemetryOutput = new TelemetryItemOutputHelper(output);
+ }
+
+ [Fact]
+ public void CustomEventsAreCapturedCorrectly()
+ {
+ // SETUP MOCK TRANSMITTER TO CAPTURE AZURE MONITOR TELEMETRY
+ var testConnectionString = $"InstrumentationKey=unitTest-{nameof(CustomEventsAreCapturedCorrectly)}";
+ var telemetryItems = new List();
+ var mockTransmitter = new Exporter.Tests.CommonTestFramework.MockTransmitter(telemetryItems);
+ // The TransmitterFactory is invoked by the Exporter during initialization to ensure that there's only one instance of a transmitter/connectionString shared by all Exporters.
+ // Here we're setting that instance to use the MockTransmitter so this test can capture telemetry before it's sent to Azure Monitor.
+ Exporter.Internals.TransmitterFactory.Instance.Set(connectionString: testConnectionString, transmitter: mockTransmitter);
+
+ // SETUP WEBAPPLICATIONFACTORY WITH OPENTELEMETRY
+ using (var client = _factory
+ .WithWebHostBuilder(builder =>
+ {
+ builder.ConfigureLogging(loggingBuilder => loggingBuilder.ClearProviders());
+ builder.ConfigureTestServices(serviceCollection =>
+ {
+ serviceCollection.AddOpenTelemetry()
+ .UseAzureMonitor(x =>
+ {
+ x.EnableLiveMetrics = false;
+ x.ConnectionString = testConnectionString;
+ });
+ });
+
+ builder.Configure(app =>
+ {
+ app.UseRouting();
+
+ app.UseEndpoints(endpoints =>
+ {
+ endpoints.MapGet("/", (IApplicationInsightsEventLogger CustomEventLogger) =>
+ {
+ CustomEventLogger.TrackEvent("TestCustomEvent");
+ });
+ });
+ });
+ })
+ .CreateClient())
+ {
+ // Act
+ try
+ {
+ using var response = client.GetAsync("/").Result;
+ }
+ catch
+ {
+ // Ignore exceptions
+ }
+ }
+
+ // SHUTDOWN
+ var loggerProvider = _factory.Factories.Last().Services.GetRequiredService();
+ loggerProvider.ForceFlush();
+
+ // ASSERT
+ _telemetryOutput.Write(telemetryItems);
+ Assert.True(telemetryItems.Any(), "Unit test failed to collect telemetry.");
+ var telemetryItem = telemetryItems.Where(x => x.Name == "Event").Single();
+ var eventData = (TelemetryEventData)(telemetryItem.Data.BaseData);
+ Assert.Equal("TestCustomEvent", eventData.Name);
+ }
+
+ [Fact]
+ public void IloggerFilterCanBeAppliedToCustomEvent()
+ {
+ // SETUP MOCK TRANSMITTER TO CAPTURE AZURE MONITOR TELEMETRY
+ var testConnectionString = $"InstrumentationKey=unitTest-{nameof(CustomEventsAreCapturedCorrectly)}";
+ var telemetryItems = new List();
+ var mockTransmitter = new Exporter.Tests.CommonTestFramework.MockTransmitter(telemetryItems);
+ // The TransmitterFactory is invoked by the Exporter during initialization to ensure that there's only one instance of a transmitter/connectionString shared by all Exporters.
+ // Here we're setting that instance to use the MockTransmitter so this test can capture telemetry before it's sent to Azure Monitor.
+ Exporter.Internals.TransmitterFactory.Instance.Set(connectionString: testConnectionString, transmitter: mockTransmitter);
+
+ // SETUP WEBAPPLICATIONFACTORY WITH OPENTELEMETRY
+ using (var client = _factory
+ .WithWebHostBuilder(builder =>
+ {
+ builder.ConfigureLogging(loggingBuilder =>
+ {
+ loggingBuilder.ClearProviders();
+
+ // Filter out custom events.
+ loggingBuilder.AddFilter("Azure.Monitor.OpenTelemetry.CustomEvents", LogLevel.None);
+ });
+ builder.ConfigureTestServices(serviceCollection =>
+ {
+ serviceCollection.AddOpenTelemetry()
+ .UseAzureMonitor(x =>
+ {
+ x.EnableLiveMetrics = false;
+ x.ConnectionString = testConnectionString;
+ });
+ });
+
+ builder.Configure(app =>
+ {
+ app.UseRouting();
+
+ app.UseEndpoints(endpoints =>
+ {
+ endpoints.MapGet("/", (IApplicationInsightsEventLogger CustomEventLogger) =>
+ {
+ CustomEventLogger.TrackEvent("TestCustomEvent");
+ });
+ });
+ });
+ })
+ .CreateClient())
+ {
+ // Act
+ try
+ {
+ using var response = client.GetAsync("/").Result;
+ }
+ catch
+ {
+ // Ignore exceptions
+ }
+ }
+
+ // SHUTDOWN
+ var loggerProvider = _factory.Factories.Last().Services.GetRequiredService();
+ loggerProvider.ForceFlush();
+
+ // ASSERT
+ _telemetryOutput.Write(telemetryItems);
+
+ // Internal Asp.NetCore logging.
+ Assert.NotNull(telemetryItems);
+
+ var traceTelemetry = telemetryItems.Where(x => x.Name == "Message").FirstOrDefault();
+ Assert.NotNull(traceTelemetry);
+
+ // Custom event should not be collected.
+ var eventTelemetry = telemetryItems.Where(x => x.Name == "Event").FirstOrDefault();
+ Assert.Null(eventTelemetry);
+ }
+
+ public void Dispose()
+ {
+ // OpenTelemetry is registered on a nested Factory which is not disposed between test runs!
+ // MUST explicitly dispose the nested Factory to avoid test conflicts.
+ _factory.Factories.Last().Dispose();
+
+ _factory.Dispose();
+ }
+ }
+}
+#endif
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.net6.0.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.net6.0.cs
index 43332b65beaff..5ce7a8e922bff 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.net6.0.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.net6.0.cs
@@ -1,3 +1,15 @@
+namespace Azure.Monitor.OpenTelemetry.Events
+{
+ public sealed partial class ApplicationInsightsEventLogger : Azure.Monitor.OpenTelemetry.Events.IApplicationInsightsEventLogger
+ {
+ public ApplicationInsightsEventLogger(Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) { }
+ public void TrackEvent(string name, System.Collections.Generic.IReadOnlyList>? attributes = null) { }
+ }
+ public partial interface IApplicationInsightsEventLogger
+ {
+ void TrackEvent(string name, System.Collections.Generic.IReadOnlyList>? attributes = null);
+ }
+}
namespace Azure.Monitor.OpenTelemetry.Exporter
{
public static partial class AzureMonitorExporterExtensions
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.netstandard2.0.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.netstandard2.0.cs
index 43332b65beaff..5ce7a8e922bff 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.netstandard2.0.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/api/Azure.Monitor.OpenTelemetry.Exporter.netstandard2.0.cs
@@ -1,3 +1,15 @@
+namespace Azure.Monitor.OpenTelemetry.Events
+{
+ public sealed partial class ApplicationInsightsEventLogger : Azure.Monitor.OpenTelemetry.Events.IApplicationInsightsEventLogger
+ {
+ public ApplicationInsightsEventLogger(Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) { }
+ public void TrackEvent(string name, System.Collections.Generic.IReadOnlyList>? attributes = null) { }
+ }
+ public partial interface IApplicationInsightsEventLogger
+ {
+ void TrackEvent(string name, System.Collections.Generic.IReadOnlyList>? attributes = null);
+ }
+}
namespace Azure.Monitor.OpenTelemetry.Exporter
{
public static partial class AzureMonitorExporterExtensions
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/CustomEvents/ApplicationInsightsEventLogger.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/CustomEvents/ApplicationInsightsEventLogger.cs
new file mode 100644
index 0000000000000..26bb5164f0885
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/CustomEvents/ApplicationInsightsEventLogger.cs
@@ -0,0 +1,43 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+using System;
+using System.Collections.Generic;
+using Microsoft.Extensions.Logging;
+
+namespace Azure.Monitor.OpenTelemetry.Events
+{
+ ///
+ /// Default logger for logging Application Insights custom events.
+ ///
+ public sealed class ApplicationInsightsEventLogger : IApplicationInsightsEventLogger
+ {
+ private const string EventLoggerName = "Azure.Monitor.OpenTelemetry.CustomEvents";
+ private static readonly Func>?, Exception?, string> s_formatter = (state, ex) =>
+ {
+ return "Application Insights Custom Event";
+ };
+
+ private readonly ILogger _logger;
+
+ ///
+ /// Creates an instance of CustomEventLogger to log custom events.
+ ///
+ /// LoggerFactory instance for logging events.
+ ///
+ public ApplicationInsightsEventLogger(ILoggerFactory loggerFactory)
+ {
+ if (loggerFactory == null)
+ throw new ArgumentNullException(nameof(loggerFactory));
+
+ _logger = loggerFactory.CreateLogger(EventLoggerName);
+ }
+
+ // TODO: Follow up to check if nullables are ok.
+ ///
+ public void TrackEvent(string name, IReadOnlyList>? attributes = null)
+ {
+ _logger.Log(LogLevel.Information, eventId: new EventId(1, name), attributes, exception: null, formatter: s_formatter);
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/CustomEvents/IApplicationInsightsEventLogger.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/CustomEvents/IApplicationInsightsEventLogger.cs
new file mode 100644
index 0000000000000..85be24b791e52
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/CustomEvents/IApplicationInsightsEventLogger.cs
@@ -0,0 +1,20 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+using System.Collections.Generic;
+
+namespace Azure.Monitor.OpenTelemetry.Events
+{
+ ///
+ /// An interface for logging custom events telemetry.
+ ///
+ public interface IApplicationInsightsEventLogger
+ {
+ ///
+ /// Tracks Application Insights custom events.
+ ///
+ /// Name of the CustomEvent.
+ /// Custom dimensions of the event.
+ public void TrackEvent(string name, IReadOnlyList>? attributes = null);
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/Models/TelemetryEventData.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/Models/TelemetryEventData.cs
new file mode 100644
index 0000000000000..8c2a632ebeefc
--- /dev/null
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/Models/TelemetryEventData.cs
@@ -0,0 +1,26 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+using OpenTelemetry.Logs;
+
+namespace Azure.Monitor.OpenTelemetry.Exporter.Models
+{
+ internal partial class TelemetryEventData
+ {
+ public TelemetryEventData(int version, LogRecord logRecord) : base(version)
+ {
+ Properties = new ChangeTrackingDictionary();
+ Measurements = new ChangeTrackingDictionary();
+
+ Name = logRecord.EventId.Name;
+
+ if (logRecord.Attributes != null)
+ {
+ foreach (var kv in logRecord.Attributes)
+ {
+ Properties.Add(kv.Key, kv.Value?.ToString());
+ }
+ }
+ }
+ }
+}
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/Models/TelemetryItem.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/Models/TelemetryItem.cs
index e6fadd8f6986f..c02c464f0b9b3 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/Models/TelemetryItem.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Customizations/Models/TelemetryItem.cs
@@ -91,8 +91,8 @@ public TelemetryItem(string name, TelemetryItem telemetryItem, ActivitySpanId ac
}
}
- public TelemetryItem (LogRecord logRecord, AzureMonitorResource? resource, string instrumentationKey) :
- this(logRecord.Exception != null ? "Exception" : "Message", FormatUtcTimestamp(logRecord.Timestamp))
+ public TelemetryItem (string name, LogRecord logRecord, AzureMonitorResource? resource, string instrumentationKey) :
+ this(name, FormatUtcTimestamp(logRecord.Timestamp))
{
if (logRecord.TraceId != default)
{
diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/LogsHelper.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/LogsHelper.cs
index 26b05b6e7beca..927837c9e6d5e 100644
--- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/LogsHelper.cs
+++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/LogsHelper.cs
@@ -56,17 +56,27 @@ internal static List