diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/AzureSecurityKeyVaultAdministrationClientOptions.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/AzureSecurityKeyVaultAdministrationClientOptions.cs new file mode 100644 index 000000000000..18762c0d5b6d --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/AzureSecurityKeyVaultAdministrationClientOptions.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.Security.KeyVault.Administration +{ + /// Client options for Azure.Security.KeyVault.Administration library clients. + public partial class AzureSecurityKeyVaultAdministrationClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V7_6_Preview_2; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "7.5". + V7_5 = 1, + /// Service version "7.6-preview.2". + V7_6_Preview_2 = 2, + } + + internal string Version { get; } + + /// Initializes new instance of AzureSecurityKeyVaultAdministrationClientOptions. + public AzureSecurityKeyVaultAdministrationClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V7_5 => "7.5", + ServiceVersion.V7_6_Preview_2 => "7.6-preview.2", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/AzureSecurityKeyVaultAdministrationFullBackupHeaders.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/AzureSecurityKeyVaultAdministrationFullBackupHeaders.cs deleted file mode 100644 index 541632c0807f..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/AzureSecurityKeyVaultAdministrationFullBackupHeaders.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; - -namespace Azure.Security.KeyVault.Administration -{ - internal partial class AzureSecurityKeyVaultAdministrationFullBackupHeaders - { - private readonly Response _response; - public AzureSecurityKeyVaultAdministrationFullBackupHeaders(Response response) - { - _response = response; - } - /// The recommended number of seconds to wait before calling the URI specified in Azure-AsyncOperation. - public int? RetryAfter => _response.Headers.TryGetValue("Retry-After", out int? value) ? value : null; - /// The URI to poll for completion status. - public string AzureAsyncOperation => _response.Headers.TryGetValue("Azure-AsyncOperation", out string value) ? value : null; - } -} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/AzureSecurityKeyVaultAdministrationFullRestoreOperationHeaders.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/AzureSecurityKeyVaultAdministrationFullRestoreOperationHeaders.cs deleted file mode 100644 index ed710c7534ec..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/AzureSecurityKeyVaultAdministrationFullRestoreOperationHeaders.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; - -namespace Azure.Security.KeyVault.Administration -{ - internal partial class AzureSecurityKeyVaultAdministrationFullRestoreOperationHeaders - { - private readonly Response _response; - public AzureSecurityKeyVaultAdministrationFullRestoreOperationHeaders(Response response) - { - _response = response; - } - /// The recommended number of seconds to wait before calling the URI specified in Azure-AsyncOperation. - public int? RetryAfter => _response.Headers.TryGetValue("Retry-After", out int? value) ? value : null; - /// The URI to poll for completion status. - public string AzureAsyncOperation => _response.Headers.TryGetValue("Azure-AsyncOperation", out string value) ? value : null; - } -} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/AzureSecurityKeyVaultAdministrationSelectiveKeyRestoreOperationHeaders.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/AzureSecurityKeyVaultAdministrationSelectiveKeyRestoreOperationHeaders.cs deleted file mode 100644 index 80dfb65bef95..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/AzureSecurityKeyVaultAdministrationSelectiveKeyRestoreOperationHeaders.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; - -namespace Azure.Security.KeyVault.Administration -{ - internal partial class AzureSecurityKeyVaultAdministrationSelectiveKeyRestoreOperationHeaders - { - private readonly Response _response; - public AzureSecurityKeyVaultAdministrationSelectiveKeyRestoreOperationHeaders(Response response) - { - _response = response; - } - /// The recommended number of seconds to wait before calling the URI specified in Azure-AsyncOperation. - public int? RetryAfter => _response.Headers.TryGetValue("Retry-After", out int? value) ? value : null; - /// The URI to poll for completion status. - public string AzureAsyncOperation => _response.Headers.TryGetValue("Azure-AsyncOperation", out string value) ? value : null; - } -} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/BackupRestoreRestClient.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/BackupRestoreRestClient.cs index b30181ba2e98..64b67aef6bbc 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/BackupRestoreRestClient.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/BackupRestoreRestClient.cs @@ -6,7 +6,6 @@ #nullable disable using System; -using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure.Core; @@ -15,252 +14,869 @@ namespace Azure.Security.KeyVault.Administration { + // Data plane generated client. + /// The BackupRestoreRest service client. internal partial class BackupRestoreRestClient { + private static readonly string[] AuthorizationScopes = new string[] { "https://vault.azure.net/.default" }; + private readonly TokenCredential _tokenCredential; private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; private readonly string _apiVersion; /// The ClientDiagnostics is used to provide tracing support for the client library. internal ClientDiagnostics ClientDiagnostics { get; } + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of BackupRestoreRestClient for mocking. + protected BackupRestoreRestClient() + { + } + /// Initializes a new instance of BackupRestoreRestClient. - /// 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 BackupRestoreRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string apiVersion = "7.5") + /// The to use. + /// A credential used to authenticate to an Azure Service. + /// or is null. + public BackupRestoreRestClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new AzureSecurityKeyVaultAdministrationClientOptions()) { - ClientDiagnostics = clientDiagnostics ?? throw new ArgumentNullException(nameof(clientDiagnostics)); - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _apiVersion = apiVersion ?? throw new ArgumentNullException(nameof(apiVersion)); } - internal HttpMessage CreateFullBackupRequest(string vaultBaseUrl, SASTokenParameter azureStorageBlobContainerUri) + /// Initializes a new instance of BackupRestoreRestClient. + /// The to use. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public BackupRestoreRestClient(Uri endpoint, TokenCredential credential, AzureSecurityKeyVaultAdministrationClientOptions options) { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/backup", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - if (azureStorageBlobContainerUri != null) + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new AzureSecurityKeyVaultAdministrationClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// Returns the status of full backup operation. + /// The id returned as part of the backup request. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> FullBackupStatusAsync(string jobId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await FullBackupStatusAsync(jobId, context).ConfigureAwait(false); + return Response.FromValue(FullBackupDetailsInternal.FromResponse(response), response); + } + + /// Returns the status of full backup operation. + /// The id returned as part of the backup request. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response FullBackupStatus(string jobId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = FullBackupStatus(jobId, context); + return Response.FromValue(FullBackupDetailsInternal.FromResponse(response), response); + } + + /// + /// [Protocol Method] Returns the status of full backup operation + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The id returned as part of the backup request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task FullBackupStatusAsync(string jobId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); + + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.FullBackupStatus"); + scope.Start(); + try { - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(azureStorageBlobContainerUri); - request.Content = content; + using HttpMessage message = CreateFullBackupStatusRequest(jobId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; } - return message; } - /// Creates a full backup using a user-provided SAS token to an Azure blob storage container. - /// The vault name, for example https://myvault.vault.azure.net. - /// Azure blob shared access signature token pointing to a valid Azure blob container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the time of making this call. + /// + /// [Protocol Method] Returns the status of full backup operation + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The id returned as part of the backup request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response FullBackupStatus(string jobId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); + + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.FullBackupStatus"); + scope.Start(); + try + { + using HttpMessage message = CreateFullBackupStatusRequest(jobId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Returns the status of restore operation. + /// The Job Id returned part of the restore operation. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> RestoreStatusAsync(string jobId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await RestoreStatusAsync(jobId, context).ConfigureAwait(false); + return Response.FromValue(RestoreDetailsInternal.FromResponse(response), response); + } + + /// Returns the status of restore operation. + /// The Job Id returned part of the restore operation. /// The cancellation token to use. - /// is null. - public async Task> FullBackupAsync(string vaultBaseUrl, SASTokenParameter azureStorageBlobContainerUri = null, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response RestoreStatus(string jobId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = RestoreStatus(jobId, context); + return Response.FromValue(RestoreDetailsInternal.FromResponse(response), response); + } + + /// + /// [Protocol Method] Returns the status of restore operation + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The Job Id returned part of the restore operation. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task RestoreStatusAsync(string jobId, RequestContext context) { - if (vaultBaseUrl == null) + Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); + + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.RestoreStatus"); + scope.Start(); + try + { + using HttpMessage message = CreateRestoreStatusRequest(jobId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) { - throw new ArgumentNullException(nameof(vaultBaseUrl)); + scope.Failed(e); + throw; } + } - using var message = CreateFullBackupRequest(vaultBaseUrl, azureStorageBlobContainerUri); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - var headers = new AzureSecurityKeyVaultAdministrationFullBackupHeaders(message.Response); - switch (message.Response.Status) + /// + /// [Protocol Method] Returns the status of restore operation + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The Job Id returned part of the restore operation. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response RestoreStatus(string jobId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); + + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.RestoreStatus"); + scope.Start(); + try { - case 202: - return ResponseWithHeaders.FromValue(headers, message.Response); - default: - throw new RequestFailedException(message.Response); + using HttpMessage message = CreateRestoreStatusRequest(jobId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; } } /// Creates a full backup using a user-provided SAS token to an Azure blob storage container. - /// The vault name, for example https://myvault.vault.azure.net. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. /// Azure blob shared access signature token pointing to a valid Azure blob container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the time of making this call. /// The cancellation token to use. - /// is null. - public ResponseWithHeaders FullBackup(string vaultBaseUrl, SASTokenParameter azureStorageBlobContainerUri = null, CancellationToken cancellationToken = default) + /// is null. + /// + public virtual async Task> FullBackupAsync(WaitUntil waitUntil, SASTokenParameter azureStorageBlobContainerUri, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) + Argument.AssertNotNull(azureStorageBlobContainerUri, nameof(azureStorageBlobContainerUri)); + + using RequestContent content = azureStorageBlobContainerUri.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = await FullBackupAsync(waitUntil, content, context).ConfigureAwait(false); + return ProtocolOperationHelpers.Convert(response, FullBackupDetailsInternal.FromResponse, ClientDiagnostics, "BackupRestoreRestClient.FullBackup"); + } + + /// Creates a full backup using a user-provided SAS token to an Azure blob storage container. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// Azure blob shared access signature token pointing to a valid Azure blob container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the time of making this call. + /// The cancellation token to use. + /// is null. + /// + public virtual Operation FullBackup(WaitUntil waitUntil, SASTokenParameter azureStorageBlobContainerUri, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(azureStorageBlobContainerUri, nameof(azureStorageBlobContainerUri)); + + using RequestContent content = azureStorageBlobContainerUri.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = FullBackup(waitUntil, content, context); + return ProtocolOperationHelpers.Convert(response, FullBackupDetailsInternal.FromResponse, ClientDiagnostics, "BackupRestoreRestClient.FullBackup"); + } + + /// + /// [Protocol Method] Creates a full backup using a user-provided SAS token to an Azure blob storage container. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual async Task> FullBackupAsync(WaitUntil waitUntil, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.FullBackup"); + scope.Start(); + try { - throw new ArgumentNullException(nameof(vaultBaseUrl)); + using HttpMessage message = CreateFullBackupRequest(content, context); + return await ProtocolOperationHelpers.ProcessMessageAsync(_pipeline, message, ClientDiagnostics, "BackupRestoreRestClient.FullBackup", OperationFinalStateVia.AzureAsyncOperation, context, waitUntil).ConfigureAwait(false); } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates a full backup using a user-provided SAS token to an Azure blob storage container. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual Operation FullBackup(WaitUntil waitUntil, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); - using var message = CreateFullBackupRequest(vaultBaseUrl, azureStorageBlobContainerUri); - _pipeline.Send(message, cancellationToken); - var headers = new AzureSecurityKeyVaultAdministrationFullBackupHeaders(message.Response); - switch (message.Response.Status) + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.FullBackup"); + scope.Start(); + try + { + using HttpMessage message = CreateFullBackupRequest(content, context); + return ProtocolOperationHelpers.ProcessMessage(_pipeline, message, ClientDiagnostics, "BackupRestoreRestClient.FullBackup", OperationFinalStateVia.AzureAsyncOperation, context, waitUntil); + } + catch (Exception e) { - case 202: - return ResponseWithHeaders.FromValue(headers, message.Response); - default: - throw new RequestFailedException(message.Response); + scope.Failed(e); + throw; } } - internal HttpMessage CreateFullBackupStatusRequest(string vaultBaseUrl, string jobId) + /// Pre-backup operation for checking whether the customer can perform a full backup operation. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// Optional parameters to validate prior to performing a full backup operation. + /// The cancellation token to use. + /// is null. + /// + public virtual async Task> PreFullBackupAsync(WaitUntil waitUntil, PreBackupOperationParameters preBackupOperationParameters, CancellationToken cancellationToken = default) { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/backup/", false); - uri.AppendPath(jobId, true); - uri.AppendPath("/pending", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; + Argument.AssertNotNull(preBackupOperationParameters, nameof(preBackupOperationParameters)); + + using RequestContent content = preBackupOperationParameters.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = await PreFullBackupAsync(waitUntil, content, context).ConfigureAwait(false); + return ProtocolOperationHelpers.Convert(response, FullBackupDetailsInternal.FromResponse, ClientDiagnostics, "BackupRestoreRestClient.PreFullBackup"); } - /// Returns the status of full backup operation. - /// The vault name, for example https://myvault.vault.azure.net. - /// The id returned as part of the backup request. + /// Pre-backup operation for checking whether the customer can perform a full backup operation. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// Optional parameters to validate prior to performing a full backup operation. /// The cancellation token to use. - /// or is null. - public async Task> FullBackupStatusAsync(string vaultBaseUrl, string jobId, CancellationToken cancellationToken = default) + /// is null. + /// + public virtual Operation PreFullBackup(WaitUntil waitUntil, PreBackupOperationParameters preBackupOperationParameters, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) + Argument.AssertNotNull(preBackupOperationParameters, nameof(preBackupOperationParameters)); + + using RequestContent content = preBackupOperationParameters.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = PreFullBackup(waitUntil, content, context); + return ProtocolOperationHelpers.Convert(response, FullBackupDetailsInternal.FromResponse, ClientDiagnostics, "BackupRestoreRestClient.PreFullBackup"); + } + + /// + /// [Protocol Method] Pre-backup operation for checking whether the customer can perform a full backup operation. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual async Task> PreFullBackupAsync(WaitUntil waitUntil, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.PreFullBackup"); + scope.Start(); + try { - throw new ArgumentNullException(nameof(vaultBaseUrl)); + using HttpMessage message = CreatePreFullBackupRequest(content, context); + return await ProtocolOperationHelpers.ProcessMessageAsync(_pipeline, message, ClientDiagnostics, "BackupRestoreRestClient.PreFullBackup", OperationFinalStateVia.AzureAsyncOperation, context, waitUntil).ConfigureAwait(false); } - if (jobId == null) + catch (Exception e) { - throw new ArgumentNullException(nameof(jobId)); + scope.Failed(e); + throw; } + } + + /// + /// [Protocol Method] Pre-backup operation for checking whether the customer can perform a full backup operation. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual Operation PreFullBackup(WaitUntil waitUntil, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); - using var message = CreateFullBackupStatusRequest(vaultBaseUrl, jobId); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.PreFullBackup"); + scope.Start(); + try { - case 200: - { - FullBackupDetailsInternal value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = FullBackupDetailsInternal.DeserializeFullBackupDetailsInternal(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); + using HttpMessage message = CreatePreFullBackupRequest(content, context); + return ProtocolOperationHelpers.ProcessMessage(_pipeline, message, ClientDiagnostics, "BackupRestoreRestClient.PreFullBackup", OperationFinalStateVia.AzureAsyncOperation, context, waitUntil); + } + catch (Exception e) + { + scope.Failed(e); + throw; } } - /// Returns the status of full backup operation. - /// The vault name, for example https://myvault.vault.azure.net. - /// The id returned as part of the backup request. + /// Pre-restore operation for checking whether the customer can perform a full restore operation. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// Optional pre restore parameters to validate prior to performing a full restore operation. + /// The cancellation token to use. + /// is null. + /// + public virtual async Task> PreFullRestoreOperationAsync(WaitUntil waitUntil, PreRestoreOperationParameters preRestoreOperationParameters, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(preRestoreOperationParameters, nameof(preRestoreOperationParameters)); + + using RequestContent content = preRestoreOperationParameters.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = await PreFullRestoreOperationAsync(waitUntil, content, context).ConfigureAwait(false); + return ProtocolOperationHelpers.Convert(response, RestoreDetailsInternal.FromResponse, ClientDiagnostics, "BackupRestoreRestClient.PreFullRestoreOperation"); + } + + /// Pre-restore operation for checking whether the customer can perform a full restore operation. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// Optional pre restore parameters to validate prior to performing a full restore operation. /// The cancellation token to use. - /// or is null. - public Response FullBackupStatus(string vaultBaseUrl, string jobId, CancellationToken cancellationToken = default) + /// is null. + /// + public virtual Operation PreFullRestoreOperation(WaitUntil waitUntil, PreRestoreOperationParameters preRestoreOperationParameters, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) + Argument.AssertNotNull(preRestoreOperationParameters, nameof(preRestoreOperationParameters)); + + using RequestContent content = preRestoreOperationParameters.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = PreFullRestoreOperation(waitUntil, content, context); + return ProtocolOperationHelpers.Convert(response, RestoreDetailsInternal.FromResponse, ClientDiagnostics, "BackupRestoreRestClient.PreFullRestoreOperation"); + } + + /// + /// [Protocol Method] Pre-restore operation for checking whether the customer can perform a full restore operation. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual async Task> PreFullRestoreOperationAsync(WaitUntil waitUntil, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.PreFullRestoreOperation"); + scope.Start(); + try { - throw new ArgumentNullException(nameof(vaultBaseUrl)); + using HttpMessage message = CreatePreFullRestoreOperationRequest(content, context); + return await ProtocolOperationHelpers.ProcessMessageAsync(_pipeline, message, ClientDiagnostics, "BackupRestoreRestClient.PreFullRestoreOperation", OperationFinalStateVia.AzureAsyncOperation, context, waitUntil).ConfigureAwait(false); } - if (jobId == null) + catch (Exception e) { - throw new ArgumentNullException(nameof(jobId)); + scope.Failed(e); + throw; } + } + + /// + /// [Protocol Method] Pre-restore operation for checking whether the customer can perform a full restore operation. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual Operation PreFullRestoreOperation(WaitUntil waitUntil, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); - using var message = CreateFullBackupStatusRequest(vaultBaseUrl, jobId); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.PreFullRestoreOperation"); + scope.Start(); + try { - case 200: - { - FullBackupDetailsInternal value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = FullBackupDetailsInternal.DeserializeFullBackupDetailsInternal(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); + using HttpMessage message = CreatePreFullRestoreOperationRequest(content, context); + return ProtocolOperationHelpers.ProcessMessage(_pipeline, message, ClientDiagnostics, "BackupRestoreRestClient.PreFullRestoreOperation", OperationFinalStateVia.AzureAsyncOperation, context, waitUntil); + } + catch (Exception e) + { + scope.Failed(e); + throw; } } - internal HttpMessage CreateFullRestoreOperationRequest(string vaultBaseUrl, RestoreOperationParameters restoreBlobDetails) + /// Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The Azure blob SAS token pointing to a folder where the previous successful full backup was stored. + /// The cancellation token to use. + /// is null. + /// + public virtual async Task> FullRestoreOperationAsync(WaitUntil waitUntil, RestoreOperationParameters restoreBlobDetails, CancellationToken cancellationToken = default) { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/restore", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - if (restoreBlobDetails != null) - { - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(restoreBlobDetails); - request.Content = content; - } - return message; + Argument.AssertNotNull(restoreBlobDetails, nameof(restoreBlobDetails)); + + using RequestContent content = restoreBlobDetails.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = await FullRestoreOperationAsync(waitUntil, content, context).ConfigureAwait(false); + return ProtocolOperationHelpers.Convert(response, RestoreDetailsInternal.FromResponse, ClientDiagnostics, "BackupRestoreRestClient.FullRestoreOperation"); } /// Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - /// The vault name, for example https://myvault.vault.azure.net. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. /// The Azure blob SAS token pointing to a folder where the previous successful full backup was stored. /// The cancellation token to use. - /// is null. - public async Task> FullRestoreOperationAsync(string vaultBaseUrl, RestoreOperationParameters restoreBlobDetails = null, CancellationToken cancellationToken = default) + /// is null. + /// + public virtual Operation FullRestoreOperation(WaitUntil waitUntil, RestoreOperationParameters restoreBlobDetails, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) + Argument.AssertNotNull(restoreBlobDetails, nameof(restoreBlobDetails)); + + using RequestContent content = restoreBlobDetails.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = FullRestoreOperation(waitUntil, content, context); + return ProtocolOperationHelpers.Convert(response, RestoreDetailsInternal.FromResponse, ClientDiagnostics, "BackupRestoreRestClient.FullRestoreOperation"); + } + + /// + /// [Protocol Method] Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual async Task> FullRestoreOperationAsync(WaitUntil waitUntil, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.FullRestoreOperation"); + scope.Start(); + try { - throw new ArgumentNullException(nameof(vaultBaseUrl)); + using HttpMessage message = CreateFullRestoreOperationRequest(content, context); + return await ProtocolOperationHelpers.ProcessMessageAsync(_pipeline, message, ClientDiagnostics, "BackupRestoreRestClient.FullRestoreOperation", OperationFinalStateVia.AzureAsyncOperation, context, waitUntil).ConfigureAwait(false); } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual Operation FullRestoreOperation(WaitUntil waitUntil, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); - using var message = CreateFullRestoreOperationRequest(vaultBaseUrl, restoreBlobDetails); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - var headers = new AzureSecurityKeyVaultAdministrationFullRestoreOperationHeaders(message.Response); - switch (message.Response.Status) + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.FullRestoreOperation"); + scope.Start(); + try + { + using HttpMessage message = CreateFullRestoreOperationRequest(content, context); + return ProtocolOperationHelpers.ProcessMessage(_pipeline, message, ClientDiagnostics, "BackupRestoreRestClient.FullRestoreOperation", OperationFinalStateVia.AzureAsyncOperation, context, waitUntil); + } + catch (Exception e) { - case 202: - return ResponseWithHeaders.FromValue(headers, message.Response); - default: - throw new RequestFailedException(message.Response); + scope.Failed(e); + throw; } } - /// Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - /// The vault name, for example https://myvault.vault.azure.net. + /// Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob storage backup folder. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The name of the key to be restored from the user supplied backup. /// The Azure blob SAS token pointing to a folder where the previous successful full backup was stored. /// The cancellation token to use. - /// is null. - public ResponseWithHeaders FullRestoreOperation(string vaultBaseUrl, RestoreOperationParameters restoreBlobDetails = null, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> SelectiveKeyRestoreOperationAsync(WaitUntil waitUntil, string keyName, SelectiveKeyRestoreOperationParameters restoreBlobDetails, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(keyName, nameof(keyName)); + Argument.AssertNotNull(restoreBlobDetails, nameof(restoreBlobDetails)); + + using RequestContent content = restoreBlobDetails.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = await SelectiveKeyRestoreOperationAsync(waitUntil, keyName, content, context).ConfigureAwait(false); + return ProtocolOperationHelpers.Convert(response, SelectiveKeyRestoreDetailsInternal.FromResponse, ClientDiagnostics, "BackupRestoreRestClient.SelectiveKeyRestoreOperation"); + } + + /// Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob storage backup folder. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The name of the key to be restored from the user supplied backup. + /// The Azure blob SAS token pointing to a folder where the previous successful full backup was stored. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Operation SelectiveKeyRestoreOperation(WaitUntil waitUntil, string keyName, SelectiveKeyRestoreOperationParameters restoreBlobDetails, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(keyName, nameof(keyName)); + Argument.AssertNotNull(restoreBlobDetails, nameof(restoreBlobDetails)); + + using RequestContent content = restoreBlobDetails.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = SelectiveKeyRestoreOperation(waitUntil, keyName, content, context); + return ProtocolOperationHelpers.Convert(response, SelectiveKeyRestoreDetailsInternal.FromResponse, ClientDiagnostics, "BackupRestoreRestClient.SelectiveKeyRestoreOperation"); + } + + /// + /// [Protocol Method] Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob storage backup folder + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The name of the key to be restored from the user supplied backup. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual async Task> SelectiveKeyRestoreOperationAsync(WaitUntil waitUntil, string keyName, RequestContent content, RequestContext context = null) { - if (vaultBaseUrl == null) + Argument.AssertNotNullOrEmpty(keyName, nameof(keyName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.SelectiveKeyRestoreOperation"); + scope.Start(); + try + { + using HttpMessage message = CreateSelectiveKeyRestoreOperationRequest(keyName, content, context); + return await ProtocolOperationHelpers.ProcessMessageAsync(_pipeline, message, ClientDiagnostics, "BackupRestoreRestClient.SelectiveKeyRestoreOperation", OperationFinalStateVia.AzureAsyncOperation, context, waitUntil).ConfigureAwait(false); + } + catch (Exception e) { - throw new ArgumentNullException(nameof(vaultBaseUrl)); + scope.Failed(e); + throw; } + } + + /// + /// [Protocol Method] Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob storage backup folder + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The name of the key to be restored from the user supplied backup. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual Operation SelectiveKeyRestoreOperation(WaitUntil waitUntil, string keyName, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(keyName, nameof(keyName)); + Argument.AssertNotNull(content, nameof(content)); - using var message = CreateFullRestoreOperationRequest(vaultBaseUrl, restoreBlobDetails); - _pipeline.Send(message, cancellationToken); - var headers = new AzureSecurityKeyVaultAdministrationFullRestoreOperationHeaders(message.Response); - switch (message.Response.Status) + using var scope = ClientDiagnostics.CreateScope("BackupRestoreRestClient.SelectiveKeyRestoreOperation"); + scope.Start(); + try { - case 202: - return ResponseWithHeaders.FromValue(headers, message.Response); - default: - throw new RequestFailedException(message.Response); + using HttpMessage message = CreateSelectiveKeyRestoreOperationRequest(keyName, content, context); + return ProtocolOperationHelpers.ProcessMessage(_pipeline, message, ClientDiagnostics, "BackupRestoreRestClient.SelectiveKeyRestoreOperation", OperationFinalStateVia.AzureAsyncOperation, context, waitUntil); } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateFullBackupRequest(RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier202); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/backup", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; } - internal HttpMessage CreateRestoreStatusRequest(string vaultBaseUrl, string jobId) + internal HttpMessage CreateFullBackupStatusRequest(string jobId, RequestContext context) { - var message = _pipeline.CreateMessage(); + var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/restore/", false); + uri.Reset(_endpoint); + uri.AppendPath("/backup/", false); uri.AppendPath(jobId, true); uri.AppendPath("/pending", false); uri.AppendQuery("api-version", _apiVersion, true); @@ -269,149 +885,102 @@ internal HttpMessage CreateRestoreStatusRequest(string vaultBaseUrl, string jobI return message; } - /// Returns the status of restore operation. - /// The vault name, for example https://myvault.vault.azure.net. - /// The Job Id returned part of the restore operation. - /// The cancellation token to use. - /// or is null. - public async Task> RestoreStatusAsync(string vaultBaseUrl, string jobId, CancellationToken cancellationToken = default) + internal HttpMessage CreatePreFullBackupRequest(RequestContent content, RequestContext context) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (jobId == null) - { - throw new ArgumentNullException(nameof(jobId)); - } + var message = _pipeline.CreateMessage(context, ResponseClassifier202); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/prebackup", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } - using var message = CreateRestoreStatusRequest(vaultBaseUrl, jobId); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - RestoreDetailsInternal value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = RestoreDetailsInternal.DeserializeRestoreDetailsInternal(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + internal HttpMessage CreateRestoreStatusRequest(string jobId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/restore/", false); + uri.AppendPath(jobId, true); + uri.AppendPath("/pending", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; } - /// Returns the status of restore operation. - /// The vault name, for example https://myvault.vault.azure.net. - /// The Job Id returned part of the restore operation. - /// The cancellation token to use. - /// or is null. - public Response RestoreStatus(string vaultBaseUrl, string jobId, CancellationToken cancellationToken = default) + internal HttpMessage CreatePreFullRestoreOperationRequest(RequestContent content, RequestContext context) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (jobId == null) - { - throw new ArgumentNullException(nameof(jobId)); - } + var message = _pipeline.CreateMessage(context, ResponseClassifier202); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/prerestore", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } - using var message = CreateRestoreStatusRequest(vaultBaseUrl, jobId); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - RestoreDetailsInternal value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = RestoreDetailsInternal.DeserializeRestoreDetailsInternal(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + internal HttpMessage CreateFullRestoreOperationRequest(RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier202); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/restore", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; } - internal HttpMessage CreateSelectiveKeyRestoreOperationRequest(string vaultBaseUrl, string keyName, SelectiveKeyRestoreOperationParameters restoreBlobDetails) + internal HttpMessage CreateSelectiveKeyRestoreOperationRequest(string keyName, RequestContent content, RequestContext context) { - var message = _pipeline.CreateMessage(); + var message = _pipeline.CreateMessage(context, ResponseClassifier202); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); + uri.Reset(_endpoint); uri.AppendPath("/keys/", false); uri.AppendPath(keyName, true); uri.AppendPath("/restore", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); - if (restoreBlobDetails != null) - { - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(restoreBlobDetails); - request.Content = content; - } + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; return message; } - /// Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob storage backup folder. - /// The vault name, for example https://myvault.vault.azure.net. - /// The name of the key to be restored from the user supplied backup. - /// The Azure blob SAS token pointing to a folder where the previous successful full backup was stored. - /// The cancellation token to use. - /// or is null. - public async Task> SelectiveKeyRestoreOperationAsync(string vaultBaseUrl, string keyName, SelectiveKeyRestoreOperationParameters restoreBlobDetails = null, CancellationToken cancellationToken = default) + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) + if (!cancellationToken.CanBeCanceled) { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (keyName == null) - { - throw new ArgumentNullException(nameof(keyName)); + return DefaultRequestContext; } - using var message = CreateSelectiveKeyRestoreOperationRequest(vaultBaseUrl, keyName, restoreBlobDetails); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - var headers = new AzureSecurityKeyVaultAdministrationSelectiveKeyRestoreOperationHeaders(message.Response); - switch (message.Response.Status) - { - case 202: - return ResponseWithHeaders.FromValue(headers, message.Response); - default: - throw new RequestFailedException(message.Response); - } + return new RequestContext() { CancellationToken = cancellationToken }; } - /// Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob storage backup folder. - /// The vault name, for example https://myvault.vault.azure.net. - /// The name of the key to be restored from the user supplied backup. - /// The Azure blob SAS token pointing to a folder where the previous successful full backup was stored. - /// The cancellation token to use. - /// or is null. - public ResponseWithHeaders SelectiveKeyRestoreOperation(string vaultBaseUrl, string keyName, SelectiveKeyRestoreOperationParameters restoreBlobDetails = null, CancellationToken cancellationToken = default) - { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (keyName == null) - { - throw new ArgumentNullException(nameof(keyName)); - } - - using var message = CreateSelectiveKeyRestoreOperationRequest(vaultBaseUrl, keyName, restoreBlobDetails); - _pipeline.Send(message, cancellationToken); - var headers = new AzureSecurityKeyVaultAdministrationSelectiveKeyRestoreOperationHeaders(message.Response); - switch (message.Response.Status) - { - case 202: - return ResponseWithHeaders.FromValue(headers, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } + private static ResponseClassifier _responseClassifier202; + private static ResponseClassifier ResponseClassifier202 => _responseClassifier202 ??= new StatusCodeClassifier(stackalloc ushort[] { 202 }); + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Docs/BackupRestoreRestClient.xml b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Docs/BackupRestoreRestClient.xml new file mode 100644 index 000000000000..97e20544fb77 --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Docs/BackupRestoreRestClient.xml @@ -0,0 +1,499 @@ + + + + + +This sample shows how to call FullBackupStatusAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +Response response = await client.FullBackupStatusAsync("45aacd568ab049a2803861e8dd3ae21f"); +]]> + + + +This sample shows how to call FullBackupStatus. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +Response response = client.FullBackupStatus("45aacd568ab049a2803861e8dd3ae21f"); +]]> + + + +This sample shows how to call FullBackupStatusAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +Response response = await client.FullBackupStatusAsync("45aacd568ab049a2803861e8dd3ae21f", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call FullBackupStatus and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +Response response = client.FullBackupStatus("45aacd568ab049a2803861e8dd3ae21f", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call RestoreStatusAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +Response response = await client.RestoreStatusAsync("45aacd568ab049a2803861e8dd3ae21f"); +]]> + + + +This sample shows how to call RestoreStatus. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +Response response = client.RestoreStatus("45aacd568ab049a2803861e8dd3ae21f"); +]]> + + + +This sample shows how to call RestoreStatusAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +Response response = await client.RestoreStatusAsync("45aacd568ab049a2803861e8dd3ae21f", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call RestoreStatus and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +Response response = client.RestoreStatus("45aacd568ab049a2803861e8dd3ae21f", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call FullBackupAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +SASTokenParameter azureStorageBlobContainerUri = new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") +{ + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", +}; +Operation operation = await client.FullBackupAsync(WaitUntil.Completed, azureStorageBlobContainerUri); +FullBackupDetailsInternal responseData = operation.Value; +]]> + + + +This sample shows how to call FullBackup. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +SASTokenParameter azureStorageBlobContainerUri = new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") +{ + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", +}; +Operation operation = client.FullBackup(WaitUntil.Completed, azureStorageBlobContainerUri); +FullBackupDetailsInternal responseData = operation.Value; +]]> + + + +This sample shows how to call FullBackupAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", +}); +Operation operation = await client.FullBackupAsync(WaitUntil.Completed, content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call FullBackup and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", +}); +Operation operation = client.FullBackup(WaitUntil.Completed, content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call PreFullBackupAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +PreBackupOperationParameters preBackupOperationParameters = new PreBackupOperationParameters +{ + StorageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", +}; +Operation operation = await client.PreFullBackupAsync(WaitUntil.Completed, preBackupOperationParameters); +FullBackupDetailsInternal responseData = operation.Value; +]]> + + + +This sample shows how to call PreFullBackup. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +PreBackupOperationParameters preBackupOperationParameters = new PreBackupOperationParameters +{ + StorageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", +}; +Operation operation = client.PreFullBackup(WaitUntil.Completed, preBackupOperationParameters); +FullBackupDetailsInternal responseData = operation.Value; +]]> + + + +This sample shows how to call PreFullBackupAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", +}); +Operation operation = await client.PreFullBackupAsync(WaitUntil.Completed, content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call PreFullBackup and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", +}); +Operation operation = client.PreFullBackup(WaitUntil.Completed, content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call PreFullRestoreOperationAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +PreRestoreOperationParameters preRestoreOperationParameters = new PreRestoreOperationParameters +{ + SasTokenParameters = new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") + { + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + FolderToRestore = "mhsm-mypool-20200303062926785", +}; +Operation operation = await client.PreFullRestoreOperationAsync(WaitUntil.Completed, preRestoreOperationParameters); +RestoreDetailsInternal responseData = operation.Value; +]]> + + + +This sample shows how to call PreFullRestoreOperation. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +PreRestoreOperationParameters preRestoreOperationParameters = new PreRestoreOperationParameters +{ + SasTokenParameters = new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") + { + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + FolderToRestore = "mhsm-mypool-20200303062926785", +}; +Operation operation = client.PreFullRestoreOperation(WaitUntil.Completed, preRestoreOperationParameters); +RestoreDetailsInternal responseData = operation.Value; +]]> + + + +This sample shows how to call PreFullRestoreOperationAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + sasTokenParameters = new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + folderToRestore = "mhsm-mypool-20200303062926785", +}); +Operation operation = await client.PreFullRestoreOperationAsync(WaitUntil.Completed, content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call PreFullRestoreOperation and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + sasTokenParameters = new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + folderToRestore = "mhsm-mypool-20200303062926785", +}); +Operation operation = client.PreFullRestoreOperation(WaitUntil.Completed, content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call FullRestoreOperationAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +RestoreOperationParameters restoreBlobDetails = new RestoreOperationParameters(new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") +{ + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", +}, "mhsm-mypool-20200303062926785"); +Operation operation = await client.FullRestoreOperationAsync(WaitUntil.Completed, restoreBlobDetails); +RestoreDetailsInternal responseData = operation.Value; +]]> + + + +This sample shows how to call FullRestoreOperation. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +RestoreOperationParameters restoreBlobDetails = new RestoreOperationParameters(new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") +{ + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", +}, "mhsm-mypool-20200303062926785"); +Operation operation = client.FullRestoreOperation(WaitUntil.Completed, restoreBlobDetails); +RestoreDetailsInternal responseData = operation.Value; +]]> + + + +This sample shows how to call FullRestoreOperationAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + sasTokenParameters = new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + folderToRestore = "mhsm-mypool-20200303062926785", +}); +Operation operation = await client.FullRestoreOperationAsync(WaitUntil.Completed, content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call FullRestoreOperation and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + sasTokenParameters = new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + folderToRestore = "mhsm-mypool-20200303062926785", +}); +Operation operation = client.FullRestoreOperation(WaitUntil.Completed, content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call SelectiveKeyRestoreOperationAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +SelectiveKeyRestoreOperationParameters restoreBlobDetails = new SelectiveKeyRestoreOperationParameters(new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") +{ + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", +}, "mhsm-mypool-20200303062926785"); +Operation operation = await client.SelectiveKeyRestoreOperationAsync(WaitUntil.Completed, "hsm-mail-key", restoreBlobDetails); +SelectiveKeyRestoreDetailsInternal responseData = operation.Value; +]]> + + + +This sample shows how to call SelectiveKeyRestoreOperation. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +SelectiveKeyRestoreOperationParameters restoreBlobDetails = new SelectiveKeyRestoreOperationParameters(new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") +{ + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", +}, "mhsm-mypool-20200303062926785"); +Operation operation = client.SelectiveKeyRestoreOperation(WaitUntil.Completed, "hsm-mail-key", restoreBlobDetails); +SelectiveKeyRestoreDetailsInternal responseData = operation.Value; +]]> + + + +This sample shows how to call SelectiveKeyRestoreOperationAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + sasTokenParameters = new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + folder = "mhsm-mypool-20200303062926785", +}); +Operation operation = await client.SelectiveKeyRestoreOperationAsync(WaitUntil.Completed, "hsm-mail-key", content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call SelectiveKeyRestoreOperation and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + sasTokenParameters = new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + folder = "mhsm-mypool-20200303062926785", +}); +Operation operation = client.SelectiveKeyRestoreOperation(WaitUntil.Completed, "hsm-mail-key", content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + \ No newline at end of file diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Docs/RoleAssignmentsRestClient.xml b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Docs/RoleAssignmentsRestClient.xml new file mode 100644 index 000000000000..38fe33126fae --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Docs/RoleAssignmentsRestClient.xml @@ -0,0 +1,229 @@ + + + + + +This sample shows how to call DeleteAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +Response response = await client.DeleteAsync("keys", "roleAssignmentName"); +]]> + + + +This sample shows how to call Delete. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +Response response = client.Delete("keys", "roleAssignmentName"); +]]> + + + +This sample shows how to call DeleteAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +Response response = await client.DeleteAsync("keys", "roleAssignmentName", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call Delete and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +Response response = client.Delete("keys", "roleAssignmentName", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call CreateAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +RoleAssignmentCreateParameters parameters = new RoleAssignmentCreateParameters(new KeyVaultRoleAssignmentPropertiesInternal("/keys/providers/Microsoft.Authorization/roleDefinitions/roleDefinitionId", "principalId")); +Response response = await client.CreateAsync("keys", "roleAssignmentName", parameters); +]]> + + + +This sample shows how to call Create. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +RoleAssignmentCreateParameters parameters = new RoleAssignmentCreateParameters(new KeyVaultRoleAssignmentPropertiesInternal("/keys/providers/Microsoft.Authorization/roleDefinitions/roleDefinitionId", "principalId")); +Response response = client.Create("keys", "roleAssignmentName", parameters); +]]> + + + +This sample shows how to call CreateAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + properties = new + { + roleDefinitionId = "/keys/providers/Microsoft.Authorization/roleDefinitions/roleDefinitionId", + principalId = "principalId", + }, +}); +Response response = await client.CreateAsync("keys", "roleAssignmentName", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call Create and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + properties = new + { + roleDefinitionId = "/keys/providers/Microsoft.Authorization/roleDefinitions/roleDefinitionId", + principalId = "principalId", + }, +}); +Response response = client.Create("keys", "roleAssignmentName", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call GetRoleAssignmentsRestClientAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +Response response = await client.GetRoleAssignmentsRestClientAsync("keys", "roleAssignmentName"); +]]> + + + +This sample shows how to call GetRoleAssignmentsRestClient. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +Response response = client.GetRoleAssignmentsRestClient("keys", "roleAssignmentName"); +]]> + + + +This sample shows how to call GetRoleAssignmentsRestClientAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +Response response = await client.GetRoleAssignmentsRestClientAsync("keys", "roleAssignmentName", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call GetRoleAssignmentsRestClient and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +Response response = client.GetRoleAssignmentsRestClient("keys", "roleAssignmentName", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call GetForScopesAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +await foreach (Models.KeyVaultRoleAssignment item in client.GetForScopesAsync("keys")) +{ +} +]]> + + + +This sample shows how to call GetForScopes. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +foreach (Models.KeyVaultRoleAssignment item in client.GetForScopes("keys")) +{ +} +]]> + + + +This sample shows how to call GetForScopesAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +await foreach (BinaryData item in client.GetForScopesAsync("keys", null, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); +} +]]> + + + +This sample shows how to call GetForScopes and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + +foreach (BinaryData item in client.GetForScopes("keys", null, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); +} +]]> + + + \ No newline at end of file diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Docs/RoleDefinitionsRestClient.xml b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Docs/RoleDefinitionsRestClient.xml new file mode 100644 index 000000000000..f61d1467c73b --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Docs/RoleDefinitionsRestClient.xml @@ -0,0 +1,269 @@ + + + + + +This sample shows how to call DeleteAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +Response response = await client.DeleteAsync("/", "00000000-0000-0000-0000-000000000000"); +]]> + + + +This sample shows how to call Delete. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +Response response = client.Delete("/", "00000000-0000-0000-0000-000000000000"); +]]> + + + +This sample shows how to call DeleteAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +Response response = await client.DeleteAsync("/", "00000000-0000-0000-0000-000000000000", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call Delete and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +Response response = client.Delete("/", "00000000-0000-0000-0000-000000000000", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call CreateOrUpdateAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +RoleDefinitionCreateParameters parameters = new RoleDefinitionCreateParameters(new RoleDefinitionProperties +{ + RoleName = "My custom role", + Description = "Role description", + RoleType = Models.KeyVaultRoleType.CustomRole, + Permissions = {new Models.KeyVaultPermission + { + DataActions = {Models.KeyVaultDataAction.SignHsmKey}, + }}, +}); +Response response = await client.CreateOrUpdateAsync("keys", "00000000-0000-0000-0000-000000000000", parameters); +]]> + + + +This sample shows how to call CreateOrUpdate. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +RoleDefinitionCreateParameters parameters = new RoleDefinitionCreateParameters(new RoleDefinitionProperties +{ + RoleName = "My custom role", + Description = "Role description", + RoleType = Models.KeyVaultRoleType.CustomRole, + Permissions = {new Models.KeyVaultPermission + { + DataActions = {Models.KeyVaultDataAction.SignHsmKey}, + }}, +}); +Response response = client.CreateOrUpdate("keys", "00000000-0000-0000-0000-000000000000", parameters); +]]> + + + +This sample shows how to call CreateOrUpdateAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + properties = new + { + roleName = "My custom role", + type = "CustomRole", + description = "Role description", + permissions = new object[] + { + new + { + dataActions = new object[] + { + "Microsoft.KeyVault/managedHsm/keys/sign/action" + }, + } + }, + }, +}); +Response response = await client.CreateOrUpdateAsync("keys", "00000000-0000-0000-0000-000000000000", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call CreateOrUpdate and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + properties = new + { + roleName = "My custom role", + type = "CustomRole", + description = "Role description", + permissions = new object[] + { + new + { + dataActions = new object[] + { + "Microsoft.KeyVault/managedHsm/keys/sign/action" + }, + } + }, + }, +}); +Response response = client.CreateOrUpdate("keys", "00000000-0000-0000-0000-000000000000", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call GetRoleDefinitionsRestClientAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +Response response = await client.GetRoleDefinitionsRestClientAsync("/", "00000000-0000-0000-0000-000000000000"); +]]> + + + +This sample shows how to call GetRoleDefinitionsRestClient. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +Response response = client.GetRoleDefinitionsRestClient("/", "00000000-0000-0000-0000-000000000000"); +]]> + + + +This sample shows how to call GetRoleDefinitionsRestClientAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +Response response = await client.GetRoleDefinitionsRestClientAsync("/", "00000000-0000-0000-0000-000000000000", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call GetRoleDefinitionsRestClient and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +Response response = client.GetRoleDefinitionsRestClient("/", "00000000-0000-0000-0000-000000000000", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call GetRoleDefinitionsRestClientsAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +await foreach (KeyVaultRoleDefinition item in client.GetRoleDefinitionsRestClientsAsync("keys")) +{ +} +]]> + + + +This sample shows how to call GetRoleDefinitionsRestClients. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +foreach (KeyVaultRoleDefinition item in client.GetRoleDefinitionsRestClients("keys")) +{ +} +]]> + + + +This sample shows how to call GetRoleDefinitionsRestClientsAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +await foreach (BinaryData item in client.GetRoleDefinitionsRestClientsAsync("keys", null, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); +} +]]> + + + +This sample shows how to call GetRoleDefinitionsRestClients and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + +foreach (BinaryData item in client.GetRoleDefinitionsRestClients("keys", null, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); +} +]]> + + + \ No newline at end of file diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Docs/SettingsRestClient.xml b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Docs/SettingsRestClient.xml new file mode 100644 index 000000000000..fdb35776fd12 --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Docs/SettingsRestClient.xml @@ -0,0 +1,187 @@ + + + + + +This sample shows how to call UpdateSettingAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + value = "true", +}); +Response response = await client.UpdateSettingAsync("AllowKeyManagementOperationsThroughARM", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("value").ToString()); +]]> + + + +This sample shows how to call UpdateSetting and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +using RequestContent content = RequestContent.Create(new +{ + value = "true", +}); +Response response = client.UpdateSetting("AllowKeyManagementOperationsThroughARM", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("value").ToString()); +]]> + + + +This sample shows how to call GetSettingAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +Response response = await client.GetSettingAsync(""); +]]> +This sample shows how to call GetSettingAsync with all parameters. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +Response response = await client.GetSettingAsync(""); +]]> + + + +This sample shows how to call GetSetting. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +Response response = client.GetSetting(""); +]]> +This sample shows how to call GetSetting with all parameters. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +Response response = client.GetSetting(""); +]]> + + + +This sample shows how to call GetSettingAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +Response response = await client.GetSettingAsync("", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("value").ToString()); +]]> +This sample shows how to call GetSettingAsync with all parameters and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +Response response = await client.GetSettingAsync("", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("value").ToString()); +Console.WriteLine(result.GetProperty("type").ToString()); +]]> + + + +This sample shows how to call GetSetting and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +Response response = client.GetSetting("", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("value").ToString()); +]]> +This sample shows how to call GetSetting with all parameters and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +Response response = client.GetSetting("", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("value").ToString()); +Console.WriteLine(result.GetProperty("type").ToString()); +]]> + + + +This sample shows how to call GetSettingsAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +Response response = await client.GetSettingsAsync(); +]]> + + + +This sample shows how to call GetSettings. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +Response response = client.GetSettings(); +]]> + + + +This sample shows how to call GetSettingsAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +Response response = await client.GetSettingsAsync(null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call GetSettings and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SettingsRestClient client = new SettingsRestClient(endpoint, credential); + +Response response = client.GetSettings(null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + \ No newline at end of file diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Internal/ModelSerializationExtensions.cs index 796908fd5bd5..9467bd96eb1d 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Internal/ModelSerializationExtensions.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Internal/ModelSerializationExtensions.cs @@ -167,13 +167,16 @@ public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset v writer.WriteNumberValue(value.ToUnixTimeSeconds()); } - public static void WriteObjectValue(this Utf8JsonWriter writer, T value) + public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) { switch (value) { case null: writer.WriteNullValue(); break; + case IJsonModel jsonModel: + jsonModel.Write(writer, options ?? WireOptions); + break; case IUtf8JsonSerializable serializable: serializable.Write(writer); break; @@ -228,7 +231,7 @@ public static void WriteObjectValue(this Utf8JsonWriter writer, T value) foreach (var pair in enumerable) { writer.WritePropertyName(pair.Key); - writer.WriteObjectValue(pair.Value); + writer.WriteObjectValue(pair.Value, options); } writer.WriteEndObject(); break; @@ -236,7 +239,7 @@ public static void WriteObjectValue(this Utf8JsonWriter writer, T value) writer.WriteStartArray(); foreach (var item in objectEnumerable) { - writer.WriteObjectValue(item); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); break; @@ -248,9 +251,9 @@ public static void WriteObjectValue(this Utf8JsonWriter writer, T value) } } - public static void WriteObjectValue(this Utf8JsonWriter writer, object value) + public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) { - writer.WriteObjectValue(value); + writer.WriteObjectValue(value, options); } internal static class TypeFormatters diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Internal/MultipartFormDataRequestContent.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Internal/MultipartFormDataRequestContent.cs deleted file mode 100644 index ad07cca72ac7..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Internal/MultipartFormDataRequestContent.cs +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.IO; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.Security.KeyVault.Administration -{ - 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/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Internal/RequestContentHelper.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Internal/RequestContentHelper.cs deleted file mode 100644 index 482217bba2c2..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Internal/RequestContentHelper.cs +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.Security.KeyVault.Administration -{ - 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/keyvault/Azure.Security.KeyVault.Administration/src/Generated/KeyVaultAdministrationModelFactory.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/KeyVaultAdministrationModelFactory.cs index 27a113c903c5..95709267c8da 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/KeyVaultAdministrationModelFactory.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/KeyVaultAdministrationModelFactory.cs @@ -7,12 +7,34 @@ using System.Collections.Generic; using System.Linq; +using Azure.Security.KeyVault.Administration.Models; namespace Azure.Security.KeyVault.Administration { /// Model factory for models. public static partial class KeyVaultAdministrationModelFactory { + /// Initializes a new instance of . + /// The role assignment ID. + /// The role assignment name. + /// The role assignment type. + /// Role assignment properties. + /// A new instance for mocking. + public static Models.KeyVaultRoleAssignment KeyVaultRoleAssignment(string id = null, string name = null, string type = null, Models.KeyVaultRoleAssignmentProperties properties = null) + { + return new Models.KeyVaultRoleAssignment(id, name, type, properties, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The role scope. + /// The role definition ID. + /// The principal ID. + /// A new instance for mocking. + public static Models.KeyVaultRoleAssignmentProperties KeyVaultRoleAssignmentProperties(Models.KeyVaultRoleScope? scope = null, string roleDefinitionId = null, string principalId = null) + { + return new Models.KeyVaultRoleAssignmentProperties(scope, roleDefinitionId, principalId, serializedAdditionalRawData: null); + } + /// Initializes a new instance of . /// The role definition ID. /// The role definition name. @@ -23,10 +45,10 @@ public static partial class KeyVaultAdministrationModelFactory /// Role definition permissions. /// Role definition assignable scopes. /// A new instance for mocking. - public static KeyVaultRoleDefinition KeyVaultRoleDefinition(string id = null, string name = null, KeyVaultRoleDefinitionType? type = null, string roleName = null, string description = null, KeyVaultRoleType? roleType = null, IEnumerable permissions = null, IEnumerable assignableScopes = null) + public static KeyVaultRoleDefinition KeyVaultRoleDefinition(string id = null, string name = null, Models.KeyVaultRoleDefinitionType? type = null, string roleName = null, string description = null, Models.KeyVaultRoleType? roleType = null, IEnumerable permissions = null, IEnumerable assignableScopes = null) { - permissions ??= new List(); - assignableScopes ??= new List(); + permissions ??= new List(); + assignableScopes ??= new List(); return new KeyVaultRoleDefinition( id, @@ -36,48 +58,28 @@ public static KeyVaultRoleDefinition KeyVaultRoleDefinition(string id = null, st description, roleType, permissions?.ToList(), - assignableScopes?.ToList()); - } - - /// Initializes a new instance of . - /// The role assignment ID. - /// The role assignment name. - /// The role assignment type. - /// Role assignment properties. - /// A new instance for mocking. - public static KeyVaultRoleAssignment KeyVaultRoleAssignment(string id = null, string name = null, string type = null, KeyVaultRoleAssignmentProperties properties = null) - { - return new KeyVaultRoleAssignment(id, name, type, properties); - } - - /// Initializes a new instance of . - /// The role scope. - /// The role definition ID. - /// The principal ID. - /// A new instance for mocking. - public static KeyVaultRoleAssignmentProperties KeyVaultRoleAssignmentProperties(KeyVaultRoleScope? scope = null, string roleDefinitionId = null, string principalId = null) - { - return new KeyVaultRoleAssignmentProperties(scope, roleDefinitionId, principalId); + assignableScopes?.ToList(), + serializedAdditionalRawData: null); } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The account setting to be updated. /// The value of the pool setting. /// The type specifier of the value. - /// A new instance for mocking. - public static KeyVaultSetting KeyVaultSetting(string name = null, string content = null, KeyVaultSettingType? settingType = null) + /// A new instance for mocking. + public static Models.KeyVaultSetting KeyVaultSetting(string name = null, string content = null, Models.KeyVaultSettingType? settingType = null) { - return new KeyVaultSetting(name, content, settingType); + return new Models.KeyVaultSetting(name, content, settingType, serializedAdditionalRawData: null); } - /// Initializes a new instance of . + /// Initializes a new instance of . /// A response message containing a list of account settings with their associated value. - /// A new instance for mocking. - public static GetSettingsResult GetSettingsResult(IEnumerable settings = null) + /// A new instance for mocking. + public static Models.GetSettingsResult GetSettingsResult(IEnumerable settings = null) { - settings ??= new List(); + settings ??= new List(); - return new GetSettingsResult(settings?.ToList()); + return new Models.GetSettingsResult(settings?.ToList(), serializedAdditionalRawData: null); } } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupDetailsInternal.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupDetailsInternal.Serialization.cs index bc7ee692a33c..f07aab55389d 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupDetailsInternal.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupDetailsInternal.Serialization.cs @@ -6,30 +6,138 @@ #nullable disable using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; +using Azure.Core; namespace Azure.Security.KeyVault.Administration.Models { - internal partial class FullBackupDetailsInternal + internal partial class FullBackupDetailsInternal : IUtf8JsonSerializable, IJsonModel { - internal static FullBackupDetailsInternal DeserializeFullBackupDetailsInternal(JsonElement element) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FullBackupDetailsInternal)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Status)) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.Value.ToString()); + } + if (Optional.IsDefined(StatusDetails)) + { + writer.WritePropertyName("statusDetails"u8); + writer.WriteStringValue(StatusDetails); + } + if (Optional.IsDefined(Error)) + { + if (Error != null) + { + writer.WritePropertyName("error"u8); + writer.WriteObjectValue(Error, options); + } + else + { + writer.WriteNull("error"); + } + } + if (Optional.IsDefined(StartTime)) + { + writer.WritePropertyName("startTime"u8); + writer.WriteNumberValue(StartTime.Value, "U"); + } + if (Optional.IsDefined(EndTime)) + { + if (EndTime != null) + { + writer.WritePropertyName("endTime"u8); + writer.WriteNumberValue(EndTime.Value, "U"); + } + else + { + writer.WriteNull("endTime"); + } + } + if (Optional.IsDefined(JobId)) + { + writer.WritePropertyName("jobId"u8); + writer.WriteStringValue(JobId); + } + if (Optional.IsDefined(AzureStorageBlobContainerUri)) + { + writer.WritePropertyName("azureStorageBlobContainerUri"u8); + writer.WriteStringValue(AzureStorageBlobContainerUri); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + FullBackupDetailsInternal IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FullBackupDetailsInternal)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFullBackupDetailsInternal(document.RootElement, options); + } + + internal static FullBackupDetailsInternal DeserializeFullBackupDetailsInternal(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + if (element.ValueKind == JsonValueKind.Null) { return null; } - string status = default; + OperationStatus? status = default; string statusDetails = default; - KeyVaultServiceError error = default; + FullBackupOperationError error = default; DateTimeOffset? startTime = default; DateTimeOffset? endTime = default; string jobId = default; string azureStorageBlobContainerUri = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("status"u8)) { - status = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new OperationStatus(property.Value.GetString()); continue; } if (property.NameEquals("statusDetails"u8)) @@ -44,7 +152,7 @@ internal static FullBackupDetailsInternal DeserializeFullBackupDetailsInternal(J error = null; continue; } - error = KeyVaultServiceError.DeserializeKeyVaultServiceError(property.Value); + error = FullBackupOperationError.DeserializeFullBackupOperationError(property.Value, options); continue; } if (property.NameEquals("startTime"u8)) @@ -76,7 +184,12 @@ internal static FullBackupDetailsInternal DeserializeFullBackupDetailsInternal(J azureStorageBlobContainerUri = property.Value.GetString(); continue; } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } } + serializedAdditionalRawData = rawDataDictionary; return new FullBackupDetailsInternal( status, statusDetails, @@ -84,9 +197,41 @@ internal static FullBackupDetailsInternal DeserializeFullBackupDetailsInternal(J startTime, endTime, jobId, - azureStorageBlobContainerUri); + azureStorageBlobContainerUri, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FullBackupDetailsInternal)} does not support writing '{options.Format}' format."); + } } + FullBackupDetailsInternal IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeFullBackupDetailsInternal(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FullBackupDetailsInternal)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + /// Deserializes the model from a raw response. /// The response to deserialize the model from. internal static FullBackupDetailsInternal FromResponse(Response response) @@ -94,5 +239,13 @@ internal static FullBackupDetailsInternal FromResponse(Response response) using var document = JsonDocument.Parse(response.Content); return DeserializeFullBackupDetailsInternal(document.RootElement); } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupDetailsInternal.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupDetailsInternal.cs index a68cc89219df..09fc39b3ebc8 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupDetailsInternal.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupDetailsInternal.cs @@ -6,12 +6,45 @@ #nullable disable using System; +using System.Collections.Generic; namespace Azure.Security.KeyVault.Administration.Models { /// Full backup operation. internal partial class FullBackupDetailsInternal { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . internal FullBackupDetailsInternal() { @@ -25,7 +58,8 @@ internal FullBackupDetailsInternal() /// The end time of the backup operation in UTC. /// Identifier for the full backup operation. /// The Azure blob storage container Uri which contains the full backup. - internal FullBackupDetailsInternal(string status, string statusDetails, KeyVaultServiceError error, DateTimeOffset? startTime, DateTimeOffset? endTime, string jobId, string azureStorageBlobContainerUri) + /// Keeps track of any properties unknown to the library. + internal FullBackupDetailsInternal(OperationStatus? status, string statusDetails, FullBackupOperationError error, DateTimeOffset? startTime, DateTimeOffset? endTime, string jobId, string azureStorageBlobContainerUri, IDictionary serializedAdditionalRawData) { Status = status; StatusDetails = statusDetails; @@ -34,14 +68,15 @@ internal FullBackupDetailsInternal(string status, string statusDetails, KeyVault EndTime = endTime; JobId = jobId; AzureStorageBlobContainerUri = azureStorageBlobContainerUri; + _serializedAdditionalRawData = serializedAdditionalRawData; } /// Status of the backup operation. - public string Status { get; } + public OperationStatus? Status { get; } /// The status details of backup operation. public string StatusDetails { get; } /// Error encountered, if any, during the full backup operation. - public KeyVaultServiceError Error { get; } + public FullBackupOperationError Error { get; } /// The start time of the backup operation in UTC. public DateTimeOffset? StartTime { get; } /// The end time of the backup operation in UTC. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupOperationError.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupOperationError.Serialization.cs new file mode 100644 index 000000000000..722080be0b95 --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupOperationError.Serialization.cs @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Security.KeyVault.Administration.Models +{ + internal partial class FullBackupOperationError : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FullBackupOperationError)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsDefined(Code)) + { + writer.WritePropertyName("code"u8); + writer.WriteStringValue(Code); + } + if (options.Format != "W" && Optional.IsDefined(Message)) + { + writer.WritePropertyName("message"u8); + writer.WriteStringValue(Message); + } + if (options.Format != "W" && Optional.IsDefined(InnerError)) + { + if (InnerError != null) + { + writer.WritePropertyName("innererror"u8); + writer.WriteObjectValue(InnerError, options); + } + else + { + writer.WriteNull("innererror"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + FullBackupOperationError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FullBackupOperationError)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFullBackupOperationError(document.RootElement, options); + } + + internal static FullBackupOperationError DeserializeFullBackupOperationError(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string code = default; + string message = default; + FullBackupOperationError innererror = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code"u8)) + { + code = property.Value.GetString(); + continue; + } + if (property.NameEquals("message"u8)) + { + message = property.Value.GetString(); + continue; + } + if (property.NameEquals("innererror"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + innererror = null; + continue; + } + innererror = DeserializeFullBackupOperationError(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FullBackupOperationError(code, message, innererror, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FullBackupOperationError)} does not support writing '{options.Format}' format."); + } + } + + FullBackupOperationError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeFullBackupOperationError(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FullBackupOperationError)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FullBackupOperationError FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeFullBackupOperationError(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupOperationError.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupOperationError.cs new file mode 100644 index 000000000000..34478930c8e0 --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/FullBackupOperationError.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Security.KeyVault.Administration.Models +{ + /// The FullBackupOperationError. + internal partial class FullBackupOperationError + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal FullBackupOperationError() + { + } + + /// Initializes a new instance of . + /// The error code. + /// The error message. + /// The key vault server error. + /// Keeps track of any properties unknown to the library. + internal FullBackupOperationError(string code, string message, FullBackupOperationError innerError, IDictionary serializedAdditionalRawData) + { + Code = code; + Message = message; + InnerError = innerError; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The error code. + public string Code { get; } + /// The error message. + public string Message { get; } + /// The key vault server error. + public FullBackupOperationError InnerError { get; } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/GetSettingsResult.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/GetSettingsResult.Serialization.cs index c5d997e1b523..cd6842e12e3f 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/GetSettingsResult.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/GetSettingsResult.Serialization.cs @@ -5,20 +5,85 @@ #nullable disable +using System; +using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.Security.KeyVault.Administration +namespace Azure.Security.KeyVault.Administration.Models { - public partial class GetSettingsResult + public partial class GetSettingsResult : IUtf8JsonSerializable, IJsonModel { - internal static GetSettingsResult DeserializeGetSettingsResult(JsonElement element) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(GetSettingsResult)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsCollectionDefined(Settings)) + { + writer.WritePropertyName("settings"u8); + writer.WriteStartArray(); + foreach (var item in Settings) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + GetSettingsResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(GetSettingsResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeGetSettingsResult(document.RootElement, options); + } + + internal static GetSettingsResult DeserializeGetSettingsResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + if (element.ValueKind == JsonValueKind.Null) { return null; } IReadOnlyList settings = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("settings"u8)) @@ -30,15 +95,51 @@ internal static GetSettingsResult DeserializeGetSettingsResult(JsonElement eleme List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(KeyVaultSetting.DeserializeKeyVaultSetting(item)); + array.Add(KeyVaultSetting.DeserializeKeyVaultSetting(item, options)); } settings = array; continue; } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new GetSettingsResult(settings ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(GetSettingsResult)} does not support writing '{options.Format}' format."); } - return new GetSettingsResult(settings ?? new ChangeTrackingList()); } + GetSettingsResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeGetSettingsResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(GetSettingsResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + /// Deserializes the model from a raw response. /// The response to deserialize the model from. internal static GetSettingsResult FromResponse(Response response) @@ -46,5 +147,13 @@ internal static GetSettingsResult FromResponse(Response response) using var document = JsonDocument.Parse(response.Content); return DeserializeGetSettingsResult(document.RootElement); } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/GetSettingsResult.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/GetSettingsResult.cs index df489fafd9f2..86cfe5b7709a 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/GetSettingsResult.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/GetSettingsResult.cs @@ -5,13 +5,46 @@ #nullable disable +using System; using System.Collections.Generic; -namespace Azure.Security.KeyVault.Administration +namespace Azure.Security.KeyVault.Administration.Models { /// The settings list result. public partial class GetSettingsResult { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . internal GetSettingsResult() { @@ -20,9 +53,11 @@ internal GetSettingsResult() /// Initializes a new instance of . /// A response message containing a list of account settings with their associated value. - internal GetSettingsResult(IReadOnlyList settings) + /// Keeps track of any properties unknown to the library. + internal GetSettingsResult(IReadOnlyList settings, IDictionary serializedAdditionalRawData) { Settings = settings; + _serializedAdditionalRawData = serializedAdditionalRawData; } /// A response message containing a list of account settings with their associated value. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultDataAction.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultDataAction.cs index 40b4085c21e2..26baf10fd3ff 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultDataAction.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultDataAction.cs @@ -8,7 +8,7 @@ using System; using System.ComponentModel; -namespace Azure.Security.KeyVault.Administration +namespace Azure.Security.KeyVault.Administration.Models { /// Supported permissions for data actions. public readonly partial struct KeyVaultDataAction : IEquatable diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultError.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultError.Serialization.cs deleted file mode 100644 index 4f5d042a8bc9..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultError.Serialization.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Text.Json; - -namespace Azure.Security.KeyVault.Administration.Models -{ - internal partial class KeyVaultError - { - internal static KeyVaultError DeserializeKeyVaultError(JsonElement element) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - KeyVaultServiceError error = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("error"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - error = null; - continue; - } - error = KeyVaultServiceError.DeserializeKeyVaultServiceError(property.Value); - continue; - } - } - return new KeyVaultError(error); - } - - /// Deserializes the model from a raw response. - /// The response to deserialize the model from. - internal static KeyVaultError FromResponse(Response response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeKeyVaultError(document.RootElement); - } - } -} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultError.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultError.cs deleted file mode 100644 index 2ccfeb949fac..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultError.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.Security.KeyVault.Administration.Models -{ - /// The key vault error exception. - internal partial class KeyVaultError - { - /// Initializes a new instance of . - internal KeyVaultError() - { - } - - /// Initializes a new instance of . - /// The key vault server error. - internal KeyVaultError(KeyVaultServiceError error) - { - Error = error; - } - - /// The key vault server error. - public KeyVaultServiceError Error { get; } - } -} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultPermission.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultPermission.Serialization.cs index 4353feddb2a3..1528372c4e34 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultPermission.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultPermission.Serialization.cs @@ -5,17 +5,35 @@ #nullable disable +using System; +using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; using Azure.Core; -namespace Azure.Security.KeyVault.Administration +namespace Azure.Security.KeyVault.Administration.Models { - public partial class KeyVaultPermission : IUtf8JsonSerializable + public partial class KeyVaultPermission : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyVaultPermission)} does not support writing '{format}' format."); + } + if (Optional.IsCollectionDefined(Actions)) { writer.WritePropertyName("actions"u8); @@ -56,11 +74,39 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) } writer.WriteEndArray(); } - writer.WriteEndObject(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } } - internal static KeyVaultPermission DeserializeKeyVaultPermission(JsonElement element) + KeyVaultPermission IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyVaultPermission)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeKeyVaultPermission(document.RootElement, options); + } + + internal static KeyVaultPermission DeserializeKeyVaultPermission(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + if (element.ValueKind == JsonValueKind.Null) { return null; @@ -69,6 +115,8 @@ internal static KeyVaultPermission DeserializeKeyVaultPermission(JsonElement ele IList notActions = default; IList dataActions = default; IList notDataActions = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("actions"u8)) @@ -127,10 +175,46 @@ internal static KeyVaultPermission DeserializeKeyVaultPermission(JsonElement ele notDataActions = array; continue; } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new KeyVaultPermission(actions ?? new ChangeTrackingList(), notActions ?? new ChangeTrackingList(), dataActions ?? new ChangeTrackingList(), notDataActions ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(KeyVaultPermission)} does not support writing '{options.Format}' format."); } - return new KeyVaultPermission(actions ?? new ChangeTrackingList(), notActions ?? new ChangeTrackingList(), dataActions ?? new ChangeTrackingList(), notDataActions ?? new ChangeTrackingList()); } + KeyVaultPermission IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeKeyVaultPermission(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(KeyVaultPermission)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + /// Deserializes the model from a raw response. /// The response to deserialize the model from. internal static KeyVaultPermission FromResponse(Response response) @@ -143,7 +227,7 @@ internal static KeyVaultPermission FromResponse(Response response) internal virtual RequestContent ToRequestContent() { var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); return content; } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultPermission.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultPermission.cs index 0b5a34b5c11e..f2d06006ef5f 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultPermission.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultPermission.cs @@ -5,13 +5,46 @@ #nullable disable +using System; using System.Collections.Generic; -namespace Azure.Security.KeyVault.Administration +namespace Azure.Security.KeyVault.Administration.Models { /// Role definition permissions. public partial class KeyVaultPermission { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . public KeyVaultPermission() { @@ -26,12 +59,14 @@ public KeyVaultPermission() /// Action permissions that are excluded but not denied. They may be granted by other role definitions assigned to a principal. /// Data action permissions that are granted. /// Data action permissions that are excluded but not denied. They may be granted by other role definitions assigned to a principal. - internal KeyVaultPermission(IList actions, IList notActions, IList dataActions, IList notDataActions) + /// Keeps track of any properties unknown to the library. + internal KeyVaultPermission(IList actions, IList notActions, IList dataActions, IList notDataActions, IDictionary serializedAdditionalRawData) { Actions = actions; NotActions = notActions; DataActions = dataActions; NotDataActions = notDataActions; + _serializedAdditionalRawData = serializedAdditionalRawData; } /// Action permissions that are granted. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignment.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignment.Serialization.cs index 7d09521e7c68..6fbf1771a4c1 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignment.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignment.Serialization.cs @@ -5,14 +5,88 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.Security.KeyVault.Administration +namespace Azure.Security.KeyVault.Administration.Models { - public partial class KeyVaultRoleAssignment + public partial class KeyVaultRoleAssignment : IUtf8JsonSerializable, IJsonModel { - internal static KeyVaultRoleAssignment DeserializeKeyVaultRoleAssignment(JsonElement element) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyVaultRoleAssignment)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsDefined(Id)) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + if (options.Format != "W" && Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (options.Format != "W" && Optional.IsDefined(Type)) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (Optional.IsDefined(Properties)) + { + writer.WritePropertyName("properties"u8); + writer.WriteObjectValue(Properties, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + KeyVaultRoleAssignment IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyVaultRoleAssignment)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeKeyVaultRoleAssignment(document.RootElement, options); + } + + internal static KeyVaultRoleAssignment DeserializeKeyVaultRoleAssignment(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + if (element.ValueKind == JsonValueKind.Null) { return null; @@ -21,6 +95,8 @@ internal static KeyVaultRoleAssignment DeserializeKeyVaultRoleAssignment(JsonEle string name = default; string type = default; KeyVaultRoleAssignmentProperties properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("id"u8)) @@ -44,13 +120,49 @@ internal static KeyVaultRoleAssignment DeserializeKeyVaultRoleAssignment(JsonEle { continue; } - properties = KeyVaultRoleAssignmentProperties.DeserializeKeyVaultRoleAssignmentProperties(property.Value); + properties = KeyVaultRoleAssignmentProperties.DeserializeKeyVaultRoleAssignmentProperties(property.Value, options); continue; } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new KeyVaultRoleAssignment(id, name, type, properties, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(KeyVaultRoleAssignment)} does not support writing '{options.Format}' format."); } - return new KeyVaultRoleAssignment(id, name, type, properties); } + KeyVaultRoleAssignment IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeKeyVaultRoleAssignment(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(KeyVaultRoleAssignment)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + /// Deserializes the model from a raw response. /// The response to deserialize the model from. internal static KeyVaultRoleAssignment FromResponse(Response response) @@ -58,5 +170,13 @@ internal static KeyVaultRoleAssignment FromResponse(Response response) using var document = JsonDocument.Parse(response.Content); return DeserializeKeyVaultRoleAssignment(document.RootElement); } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignment.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignment.cs index 25aad0ee7dff..cbf181975aba 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignment.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignment.cs @@ -5,11 +5,46 @@ #nullable disable -namespace Azure.Security.KeyVault.Administration +using System; +using System.Collections.Generic; + +namespace Azure.Security.KeyVault.Administration.Models { /// Role Assignments. public partial class KeyVaultRoleAssignment { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . internal KeyVaultRoleAssignment() { @@ -20,12 +55,14 @@ internal KeyVaultRoleAssignment() /// The role assignment name. /// The role assignment type. /// Role assignment properties. - internal KeyVaultRoleAssignment(string id, string name, string type, KeyVaultRoleAssignmentProperties properties) + /// Keeps track of any properties unknown to the library. + internal KeyVaultRoleAssignment(string id, string name, string type, KeyVaultRoleAssignmentProperties properties, IDictionary serializedAdditionalRawData) { Id = id; Name = name; Type = type; Properties = properties; + _serializedAdditionalRawData = serializedAdditionalRawData; } /// The role assignment ID. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentProperties.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentProperties.Serialization.cs index b4ee364efd3a..e9adbf905066 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentProperties.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentProperties.Serialization.cs @@ -5,14 +5,83 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.Security.KeyVault.Administration +namespace Azure.Security.KeyVault.Administration.Models { - public partial class KeyVaultRoleAssignmentProperties + public partial class KeyVaultRoleAssignmentProperties : IUtf8JsonSerializable, IJsonModel { - internal static KeyVaultRoleAssignmentProperties DeserializeKeyVaultRoleAssignmentProperties(JsonElement element) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyVaultRoleAssignmentProperties)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Scope)) + { + writer.WritePropertyName("scope"u8); + writer.WriteStringValue(Scope.Value.ToString()); + } + if (Optional.IsDefined(RoleDefinitionId)) + { + writer.WritePropertyName("roleDefinitionId"u8); + writer.WriteStringValue(RoleDefinitionId); + } + if (Optional.IsDefined(PrincipalId)) + { + writer.WritePropertyName("principalId"u8); + writer.WriteStringValue(PrincipalId); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + KeyVaultRoleAssignmentProperties IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyVaultRoleAssignmentProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeKeyVaultRoleAssignmentProperties(document.RootElement, options); + } + + internal static KeyVaultRoleAssignmentProperties DeserializeKeyVaultRoleAssignmentProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + if (element.ValueKind == JsonValueKind.Null) { return null; @@ -20,6 +89,8 @@ internal static KeyVaultRoleAssignmentProperties DeserializeKeyVaultRoleAssignme KeyVaultRoleScope? scope = default; string roleDefinitionId = default; string principalId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("scope"u8)) @@ -41,10 +112,46 @@ internal static KeyVaultRoleAssignmentProperties DeserializeKeyVaultRoleAssignme principalId = property.Value.GetString(); continue; } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new KeyVaultRoleAssignmentProperties(scope, roleDefinitionId, principalId, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(KeyVaultRoleAssignmentProperties)} does not support writing '{options.Format}' format."); } - return new KeyVaultRoleAssignmentProperties(scope, roleDefinitionId, principalId); } + KeyVaultRoleAssignmentProperties IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeKeyVaultRoleAssignmentProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(KeyVaultRoleAssignmentProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + /// Deserializes the model from a raw response. /// The response to deserialize the model from. internal static KeyVaultRoleAssignmentProperties FromResponse(Response response) @@ -52,5 +159,13 @@ internal static KeyVaultRoleAssignmentProperties FromResponse(Response response) using var document = JsonDocument.Parse(response.Content); return DeserializeKeyVaultRoleAssignmentProperties(document.RootElement); } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentProperties.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentProperties.cs index 66ba6539861e..7e4f3a2309d7 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentProperties.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentProperties.cs @@ -5,11 +5,46 @@ #nullable disable -namespace Azure.Security.KeyVault.Administration +using System; +using System.Collections.Generic; + +namespace Azure.Security.KeyVault.Administration.Models { /// Role assignment properties with scope. public partial class KeyVaultRoleAssignmentProperties { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . internal KeyVaultRoleAssignmentProperties() { @@ -19,11 +54,13 @@ internal KeyVaultRoleAssignmentProperties() /// The role scope. /// The role definition ID. /// The principal ID. - internal KeyVaultRoleAssignmentProperties(KeyVaultRoleScope? scope, string roleDefinitionId, string principalId) + /// Keeps track of any properties unknown to the library. + internal KeyVaultRoleAssignmentProperties(KeyVaultRoleScope? scope, string roleDefinitionId, string principalId, IDictionary serializedAdditionalRawData) { Scope = scope; RoleDefinitionId = roleDefinitionId; PrincipalId = principalId; + _serializedAdditionalRawData = serializedAdditionalRawData; } /// The role scope. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentPropertiesInternal.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentPropertiesInternal.Serialization.cs index 22a0cea833ce..50a25b88f687 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentPropertiesInternal.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentPropertiesInternal.Serialization.cs @@ -5,28 +5,145 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Security.KeyVault.Administration { - internal partial class KeyVaultRoleAssignmentPropertiesInternal : IUtf8JsonSerializable + internal partial class KeyVaultRoleAssignmentPropertiesInternal : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyVaultRoleAssignmentPropertiesInternal)} does not support writing '{format}' format."); + } + writer.WritePropertyName("roleDefinitionId"u8); writer.WriteStringValue(RoleDefinitionId); writer.WritePropertyName("principalId"u8); writer.WriteStringValue(PrincipalId); - writer.WriteEndObject(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + KeyVaultRoleAssignmentPropertiesInternal IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyVaultRoleAssignmentPropertiesInternal)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeKeyVaultRoleAssignmentPropertiesInternal(document.RootElement, options); + } + + internal static KeyVaultRoleAssignmentPropertiesInternal DeserializeKeyVaultRoleAssignmentPropertiesInternal(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string roleDefinitionId = default; + string principalId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("roleDefinitionId"u8)) + { + roleDefinitionId = property.Value.GetString(); + continue; + } + if (property.NameEquals("principalId"u8)) + { + principalId = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new KeyVaultRoleAssignmentPropertiesInternal(roleDefinitionId, principalId, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(KeyVaultRoleAssignmentPropertiesInternal)} does not support writing '{options.Format}' format."); + } + } + + KeyVaultRoleAssignmentPropertiesInternal IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeKeyVaultRoleAssignmentPropertiesInternal(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(KeyVaultRoleAssignmentPropertiesInternal)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static KeyVaultRoleAssignmentPropertiesInternal FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeKeyVaultRoleAssignmentPropertiesInternal(document.RootElement); } /// Convert into a . internal virtual RequestContent ToRequestContent() { var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); return content; } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentPropertiesInternal.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentPropertiesInternal.cs index e78220700791..cd9cfe6d3863 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentPropertiesInternal.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleAssignmentPropertiesInternal.cs @@ -6,12 +6,45 @@ #nullable disable using System; +using System.Collections.Generic; namespace Azure.Security.KeyVault.Administration { /// Role assignment properties. internal partial class KeyVaultRoleAssignmentPropertiesInternal { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . /// The role definition ID used in the role assignment. /// The principal ID assigned to the role. This maps to the ID inside the Active Directory. It can point to a user, service principal, or security group. @@ -25,6 +58,22 @@ public KeyVaultRoleAssignmentPropertiesInternal(string roleDefinitionId, string PrincipalId = principalId; } + /// Initializes a new instance of . + /// The role definition ID used in the role assignment. + /// The principal ID assigned to the role. This maps to the ID inside the Active Directory. It can point to a user, service principal, or security group. + /// Keeps track of any properties unknown to the library. + internal KeyVaultRoleAssignmentPropertiesInternal(string roleDefinitionId, string principalId, IDictionary serializedAdditionalRawData) + { + RoleDefinitionId = roleDefinitionId; + PrincipalId = principalId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal KeyVaultRoleAssignmentPropertiesInternal() + { + } + /// The role definition ID used in the role assignment. public string RoleDefinitionId { get; } /// The principal ID assigned to the role. This maps to the ID inside the Active Directory. It can point to a user, service principal, or security group. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleDefinition.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleDefinition.Serialization.cs index ae3355a6ccd8..7d8b3af7c23a 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleDefinition.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleDefinition.Serialization.cs @@ -5,17 +5,51 @@ #nullable disable +using System; +using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; using Azure.Core; +using Azure.Security.KeyVault.Administration.Models; namespace Azure.Security.KeyVault.Administration { - public partial class KeyVaultRoleDefinition : IUtf8JsonSerializable + public partial class KeyVaultRoleDefinition : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyVaultRoleDefinition)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsDefined(Id)) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + if (options.Format != "W" && Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (options.Format != "W" && Optional.IsDefined(Type)) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.Value.ToString()); + } writer.WritePropertyName("properties"u8); writer.WriteStartObject(); if (Optional.IsDefined(RoleName)) @@ -39,7 +73,7 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) writer.WriteStartArray(); foreach (var item in Permissions) { - writer.WriteObjectValue(item); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } @@ -54,23 +88,53 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) writer.WriteEndArray(); } writer.WriteEndObject(); - writer.WriteEndObject(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + KeyVaultRoleDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyVaultRoleDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeKeyVaultRoleDefinition(document.RootElement, options); } - internal static KeyVaultRoleDefinition DeserializeKeyVaultRoleDefinition(JsonElement element) + internal static KeyVaultRoleDefinition DeserializeKeyVaultRoleDefinition(JsonElement element, ModelReaderWriterOptions options = null) { + options ??= ModelSerializationExtensions.WireOptions; + if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; string name = default; - KeyVaultRoleDefinitionType? type = default; + Models.KeyVaultRoleDefinitionType? type = default; string roleName = default; string description = default; - KeyVaultRoleType? type0 = default; - IList permissions = default; - IList assignableScopes = default; + Models.KeyVaultRoleType? type0 = default; + IList permissions = default; + IList assignableScopes = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("id"u8)) @@ -89,7 +153,7 @@ internal static KeyVaultRoleDefinition DeserializeKeyVaultRoleDefinition(JsonEle { continue; } - type = new KeyVaultRoleDefinitionType(property.Value.GetString()); + type = new Models.KeyVaultRoleDefinitionType(property.Value.GetString()); continue; } if (property.NameEquals("properties"u8)) @@ -117,7 +181,7 @@ internal static KeyVaultRoleDefinition DeserializeKeyVaultRoleDefinition(JsonEle { continue; } - type0 = new KeyVaultRoleType(property0.Value.GetString()); + type0 = new Models.KeyVaultRoleType(property0.Value.GetString()); continue; } if (property0.NameEquals("permissions"u8)) @@ -126,10 +190,10 @@ internal static KeyVaultRoleDefinition DeserializeKeyVaultRoleDefinition(JsonEle { continue; } - List array = new List(); + List array = new List(); foreach (var item in property0.Value.EnumerateArray()) { - array.Add(KeyVaultPermission.DeserializeKeyVaultPermission(item)); + array.Add(Models.KeyVaultPermission.DeserializeKeyVaultPermission(item, options)); } permissions = array; continue; @@ -140,10 +204,10 @@ internal static KeyVaultRoleDefinition DeserializeKeyVaultRoleDefinition(JsonEle { continue; } - List array = new List(); + List array = new List(); foreach (var item in property0.Value.EnumerateArray()) { - array.Add(new KeyVaultRoleScope(item.GetString())); + array.Add(new Models.KeyVaultRoleScope(item.GetString())); } assignableScopes = array; continue; @@ -151,7 +215,12 @@ internal static KeyVaultRoleDefinition DeserializeKeyVaultRoleDefinition(JsonEle } continue; } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } } + serializedAdditionalRawData = rawDataDictionary; return new KeyVaultRoleDefinition( id, name, @@ -159,10 +228,42 @@ internal static KeyVaultRoleDefinition DeserializeKeyVaultRoleDefinition(JsonEle roleName, description, type0, - permissions ?? new ChangeTrackingList(), - assignableScopes ?? new ChangeTrackingList()); + permissions ?? new ChangeTrackingList(), + assignableScopes ?? new ChangeTrackingList(), + serializedAdditionalRawData); } + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(KeyVaultRoleDefinition)} does not support writing '{options.Format}' format."); + } + } + + KeyVaultRoleDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeKeyVaultRoleDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(KeyVaultRoleDefinition)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + /// Deserializes the model from a raw response. /// The response to deserialize the model from. internal static KeyVaultRoleDefinition FromResponse(Response response) @@ -175,7 +276,7 @@ internal static KeyVaultRoleDefinition FromResponse(Response response) internal virtual RequestContent ToRequestContent() { var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); return content; } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleDefinition.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleDefinition.cs index d1e59ad74ce9..ad28550a6951 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleDefinition.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleDefinition.cs @@ -5,18 +5,52 @@ #nullable disable +using System; using System.Collections.Generic; +using Azure.Security.KeyVault.Administration.Models; namespace Azure.Security.KeyVault.Administration { /// Role definition. public partial class KeyVaultRoleDefinition { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . public KeyVaultRoleDefinition() { - Permissions = new ChangeTrackingList(); - AssignableScopes = new ChangeTrackingList(); + Permissions = new ChangeTrackingList(); + AssignableScopes = new ChangeTrackingList(); } /// Initializes a new instance of . @@ -28,7 +62,8 @@ public KeyVaultRoleDefinition() /// The role type. /// Role definition permissions. /// Role definition assignable scopes. - internal KeyVaultRoleDefinition(string id, string name, KeyVaultRoleDefinitionType? type, string roleName, string description, KeyVaultRoleType? roleType, IList permissions, IList assignableScopes) + /// Keeps track of any properties unknown to the library. + internal KeyVaultRoleDefinition(string id, string name, Models.KeyVaultRoleDefinitionType? type, string roleName, string description, Models.KeyVaultRoleType? roleType, IList permissions, IList assignableScopes, IDictionary serializedAdditionalRawData) { Id = id; Name = name; @@ -38,6 +73,7 @@ internal KeyVaultRoleDefinition(string id, string name, KeyVaultRoleDefinitionTy RoleType = roleType; Permissions = permissions; AssignableScopes = assignableScopes; + _serializedAdditionalRawData = serializedAdditionalRawData; } /// The role definition ID. @@ -45,16 +81,16 @@ internal KeyVaultRoleDefinition(string id, string name, KeyVaultRoleDefinitionTy /// The role definition name. public string Name { get; } /// The role definition type. - public KeyVaultRoleDefinitionType? Type { get; } + public Models.KeyVaultRoleDefinitionType? Type { get; } /// The role name. public string RoleName { get; set; } /// The role definition description. public string Description { get; set; } /// The role type. - public KeyVaultRoleType? RoleType { get; set; } + public Models.KeyVaultRoleType? RoleType { get; set; } /// Role definition permissions. - public IList Permissions { get; } + public IList Permissions { get; } /// Role definition assignable scopes. - public IList AssignableScopes { get; } + public IList AssignableScopes { get; } } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleDefinitionType.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleDefinitionType.cs index 3442a1472797..8a881cf4197c 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleDefinitionType.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleDefinitionType.cs @@ -8,7 +8,7 @@ using System; using System.ComponentModel; -namespace Azure.Security.KeyVault.Administration +namespace Azure.Security.KeyVault.Administration.Models { /// The role definition type. public readonly partial struct KeyVaultRoleDefinitionType : IEquatable @@ -24,7 +24,7 @@ public KeyVaultRoleDefinitionType(string value) private const string MicrosoftAuthorizationRoleDefinitionsValue = "Microsoft.Authorization/roleDefinitions"; - /// Microsoft.Authorization/roleDefinitions. + /// Microsoft-defined role definitions. public static KeyVaultRoleDefinitionType MicrosoftAuthorizationRoleDefinitions { get; } = new KeyVaultRoleDefinitionType(MicrosoftAuthorizationRoleDefinitionsValue); /// Determines if two values are the same. public static bool operator ==(KeyVaultRoleDefinitionType left, KeyVaultRoleDefinitionType right) => left.Equals(right); diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleScope.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleScope.cs index 17f1fd1cf002..fc5b742badf6 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleScope.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleScope.cs @@ -8,7 +8,7 @@ using System; using System.ComponentModel; -namespace Azure.Security.KeyVault.Administration +namespace Azure.Security.KeyVault.Administration.Models { /// The role scope. public readonly partial struct KeyVaultRoleScope : IEquatable diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleType.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleType.cs index 9cb04eb34d91..c10fe776592c 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleType.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultRoleType.cs @@ -8,7 +8,7 @@ using System; using System.ComponentModel; -namespace Azure.Security.KeyVault.Administration +namespace Azure.Security.KeyVault.Administration.Models { /// The role type. public readonly partial struct KeyVaultRoleType : IEquatable diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultServiceError.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultServiceError.Serialization.cs deleted file mode 100644 index 3015799edd33..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultServiceError.Serialization.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Text.Json; - -namespace Azure.Security.KeyVault.Administration.Models -{ - internal partial class KeyVaultServiceError - { - internal static KeyVaultServiceError DeserializeKeyVaultServiceError(JsonElement element) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string code = default; - string message = default; - KeyVaultServiceError innererror = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("code"u8)) - { - code = property.Value.GetString(); - continue; - } - if (property.NameEquals("message"u8)) - { - message = property.Value.GetString(); - continue; - } - if (property.NameEquals("innererror"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - innererror = null; - continue; - } - innererror = DeserializeKeyVaultServiceError(property.Value); - continue; - } - } - return new KeyVaultServiceError(code, message, innererror); - } - - /// Deserializes the model from a raw response. - /// The response to deserialize the model from. - internal static KeyVaultServiceError FromResponse(Response response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeKeyVaultServiceError(document.RootElement); - } - } -} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultServiceError.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultServiceError.cs deleted file mode 100644 index e44390a71e17..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultServiceError.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.Security.KeyVault.Administration.Models -{ - /// The key vault server error. - internal partial class KeyVaultServiceError - { - /// Initializes a new instance of . - internal KeyVaultServiceError() - { - } - - /// Initializes a new instance of . - /// The error code. - /// The error message. - /// The key vault server error. - internal KeyVaultServiceError(string code, string message, KeyVaultServiceError innerError) - { - Code = code; - Message = message; - InnerError = innerError; - } - - /// The error code. - public string Code { get; } - /// The error message. - public string Message { get; } - /// The key vault server error. - public KeyVaultServiceError InnerError { get; } - } -} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultSetting.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultSetting.Serialization.cs index 09bdc0815da5..a9ee7674586e 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultSetting.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultSetting.Serialization.cs @@ -5,14 +5,77 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.Security.KeyVault.Administration +namespace Azure.Security.KeyVault.Administration.Models { - public partial class KeyVaultSetting + public partial class KeyVaultSetting : IUtf8JsonSerializable, IJsonModel { - internal static KeyVaultSetting DeserializeKeyVaultSetting(JsonElement element) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyVaultSetting)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + writer.WritePropertyName("value"u8); + writer.WriteStringValue(Content); + if (Optional.IsDefined(SettingType)) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(SettingType.Value.ToString()); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + KeyVaultSetting IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyVaultSetting)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeKeyVaultSetting(document.RootElement, options); + } + + internal static KeyVaultSetting DeserializeKeyVaultSetting(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + if (element.ValueKind == JsonValueKind.Null) { return null; @@ -20,6 +83,8 @@ internal static KeyVaultSetting DeserializeKeyVaultSetting(JsonElement element) string name = default; string value = default; KeyVaultSettingType? type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("name"u8)) @@ -41,10 +106,46 @@ internal static KeyVaultSetting DeserializeKeyVaultSetting(JsonElement element) type = new KeyVaultSettingType(property.Value.GetString()); continue; } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new KeyVaultSetting(name, value, type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(KeyVaultSetting)} does not support writing '{options.Format}' format."); + } + } + + KeyVaultSetting IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeKeyVaultSetting(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(KeyVaultSetting)} does not support reading '{options.Format}' format."); } - return new KeyVaultSetting(name, value, type); } + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + /// Deserializes the model from a raw response. /// The response to deserialize the model from. internal static KeyVaultSetting FromResponse(Response response) @@ -52,5 +153,13 @@ internal static KeyVaultSetting FromResponse(Response response) using var document = JsonDocument.Parse(response.Content); return DeserializeKeyVaultSetting(document.RootElement); } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultSetting.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultSetting.cs index 43a533a4a45b..64c27c10a94c 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultSetting.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultSetting.cs @@ -6,13 +6,81 @@ #nullable disable using System; +using System.Collections.Generic; -namespace Azure.Security.KeyVault.Administration +namespace Azure.Security.KeyVault.Administration.Models { - /// The Setting. + /// A Key Vault account setting. public partial class KeyVaultSetting { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The account setting to be updated. + /// The value of the pool setting. + /// or is null. + internal KeyVaultSetting(string name, string content) + { + Argument.AssertNotNull(name, nameof(name)); + Argument.AssertNotNull(content, nameof(content)); + + Name = name; + Content = content; + } + + /// Initializes a new instance of . + /// The account setting to be updated. + /// The value of the pool setting. + /// The type specifier of the value. + /// Keeps track of any properties unknown to the library. + internal KeyVaultSetting(string name, string content, KeyVaultSettingType? settingType, IDictionary serializedAdditionalRawData) + { + Name = name; + Content = content; + SettingType = settingType; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal KeyVaultSetting() + { + } + /// The account setting to be updated. public string Name { get; } + /// The value of the pool setting. + public string Content { get; } + /// The type specifier of the value. + public KeyVaultSettingType? SettingType { get; } } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultSettingType.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultSettingType.cs index 9c9bc2bf1580..2839423d6bc4 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultSettingType.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/KeyVaultSettingType.cs @@ -8,7 +8,7 @@ using System; using System.ComponentModel; -namespace Azure.Security.KeyVault.Administration +namespace Azure.Security.KeyVault.Administration.Models { /// The type specifier of the value. public readonly partial struct KeyVaultSettingType : IEquatable @@ -24,7 +24,7 @@ public KeyVaultSettingType(string value) private const string BooleanValue = "boolean"; - /// boolean. + /// A boolean setting value. public static KeyVaultSettingType Boolean { get; } = new KeyVaultSettingType(BooleanValue); /// Determines if two values are the same. public static bool operator ==(KeyVaultSettingType left, KeyVaultSettingType right) => left.Equals(right); diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/OperationStatus.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/OperationStatus.cs new file mode 100644 index 000000000000..c9bac3540a67 --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/OperationStatus.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.Security.KeyVault.Administration.Models +{ + /// The status of a long-running operation. + internal readonly partial struct OperationStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OperationStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string InProgressValue = "InProgress"; + private const string SucceededValue = "Succeeded"; + private const string CanceledValue = "Canceled"; + private const string FailedValue = "Failed"; + + /// The operation is in progress. + public static OperationStatus InProgress { get; } = new OperationStatus(InProgressValue); + /// The operation successfully completed. + public static OperationStatus Succeeded { get; } = new OperationStatus(SucceededValue); + /// The operation was canceled. + public static OperationStatus Canceled { get; } = new OperationStatus(CanceledValue); + /// The operation failed. + public static OperationStatus Failed { get; } = new OperationStatus(FailedValue); + /// Determines if two values are the same. + public static bool operator ==(OperationStatus left, OperationStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OperationStatus left, OperationStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OperationStatus(string value) => new OperationStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OperationStatus other && Equals(other); + /// + public bool Equals(OperationStatus 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/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/PreBackupOperationParameters.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/PreBackupOperationParameters.Serialization.cs new file mode 100644 index 000000000000..4a661dce5b8e --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/PreBackupOperationParameters.Serialization.cs @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Security.KeyVault.Administration.Models +{ + internal partial class PreBackupOperationParameters : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PreBackupOperationParameters)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(StorageResourceUri)) + { + writer.WritePropertyName("storageResourceUri"u8); + writer.WriteStringValue(StorageResourceUri); + } + if (Optional.IsDefined(Token)) + { + writer.WritePropertyName("token"u8); + writer.WriteStringValue(Token); + } + if (Optional.IsDefined(UseManagedIdentity)) + { + writer.WritePropertyName("useManagedIdentity"u8); + writer.WriteBooleanValue(UseManagedIdentity.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + PreBackupOperationParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PreBackupOperationParameters)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePreBackupOperationParameters(document.RootElement, options); + } + + internal static PreBackupOperationParameters DeserializePreBackupOperationParameters(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string storageResourceUri = default; + string token = default; + bool? useManagedIdentity = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("storageResourceUri"u8)) + { + storageResourceUri = property.Value.GetString(); + continue; + } + if (property.NameEquals("token"u8)) + { + token = property.Value.GetString(); + continue; + } + if (property.NameEquals("useManagedIdentity"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + useManagedIdentity = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new PreBackupOperationParameters(storageResourceUri, token, useManagedIdentity, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(PreBackupOperationParameters)} does not support writing '{options.Format}' format."); + } + } + + PreBackupOperationParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializePreBackupOperationParameters(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PreBackupOperationParameters)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static PreBackupOperationParameters FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializePreBackupOperationParameters(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/PreBackupOperationParameters.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/PreBackupOperationParameters.cs new file mode 100644 index 000000000000..137f2974519b --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/PreBackupOperationParameters.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Security.KeyVault.Administration.Models +{ + /// The authentication method and location for the backup operation. + internal partial class PreBackupOperationParameters + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public PreBackupOperationParameters() + { + } + + /// Initializes a new instance of . + /// Azure Blob storage container Uri. + /// The SAS token pointing to an Azure Blob storage container. + /// Indicates which authentication method should be used. If set to true, Managed HSM will use the configured user-assigned managed identity to authenticate with Azure Storage. Otherwise, a SAS token has to be specified. + /// Keeps track of any properties unknown to the library. + internal PreBackupOperationParameters(string storageResourceUri, string token, bool? useManagedIdentity, IDictionary serializedAdditionalRawData) + { + StorageResourceUri = storageResourceUri; + Token = token; + UseManagedIdentity = useManagedIdentity; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Azure Blob storage container Uri. + public string StorageResourceUri { get; set; } + /// The SAS token pointing to an Azure Blob storage container. + public string Token { get; set; } + /// Indicates which authentication method should be used. If set to true, Managed HSM will use the configured user-assigned managed identity to authenticate with Azure Storage. Otherwise, a SAS token has to be specified. + public bool? UseManagedIdentity { get; set; } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/PreRestoreOperationParameters.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/PreRestoreOperationParameters.Serialization.cs new file mode 100644 index 000000000000..fb324ece131e --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/PreRestoreOperationParameters.Serialization.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Security.KeyVault.Administration.Models +{ + internal partial class PreRestoreOperationParameters : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PreRestoreOperationParameters)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(SasTokenParameters)) + { + writer.WritePropertyName("sasTokenParameters"u8); + writer.WriteObjectValue(SasTokenParameters, options); + } + if (Optional.IsDefined(FolderToRestore)) + { + writer.WritePropertyName("folderToRestore"u8); + writer.WriteStringValue(FolderToRestore); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + PreRestoreOperationParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PreRestoreOperationParameters)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePreRestoreOperationParameters(document.RootElement, options); + } + + internal static PreRestoreOperationParameters DeserializePreRestoreOperationParameters(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + SASTokenParameter sasTokenParameters = default; + string folderToRestore = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("sasTokenParameters"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + sasTokenParameters = SASTokenParameter.DeserializeSASTokenParameter(property.Value, options); + continue; + } + if (property.NameEquals("folderToRestore"u8)) + { + folderToRestore = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new PreRestoreOperationParameters(sasTokenParameters, folderToRestore, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(PreRestoreOperationParameters)} does not support writing '{options.Format}' format."); + } + } + + PreRestoreOperationParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializePreRestoreOperationParameters(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PreRestoreOperationParameters)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static PreRestoreOperationParameters FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializePreRestoreOperationParameters(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/PreRestoreOperationParameters.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/PreRestoreOperationParameters.cs new file mode 100644 index 000000000000..e38d31fc533e --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/PreRestoreOperationParameters.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Security.KeyVault.Administration.Models +{ + /// The authentication method and location for the restore operation. + internal partial class PreRestoreOperationParameters + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public PreRestoreOperationParameters() + { + } + + /// Initializes a new instance of . + /// A user-provided SAS token to an Azure blob storage container. + /// The Folder name of the blob where the previous successful full backup was stored. + /// Keeps track of any properties unknown to the library. + internal PreRestoreOperationParameters(SASTokenParameter sasTokenParameters, string folderToRestore, IDictionary serializedAdditionalRawData) + { + SasTokenParameters = sasTokenParameters; + FolderToRestore = folderToRestore; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// A user-provided SAS token to an Azure blob storage container. + public SASTokenParameter SasTokenParameters { get; set; } + /// The Folder name of the blob where the previous successful full backup was stored. + public string FolderToRestore { get; set; } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreDetailsInternal.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreDetailsInternal.Serialization.cs index 6ab86cb33866..e5604cc4226c 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreDetailsInternal.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreDetailsInternal.Serialization.cs @@ -6,29 +6,132 @@ #nullable disable using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; +using Azure.Core; namespace Azure.Security.KeyVault.Administration.Models { - internal partial class RestoreDetailsInternal + internal partial class RestoreDetailsInternal : IUtf8JsonSerializable, IJsonModel { - internal static RestoreDetailsInternal DeserializeRestoreDetailsInternal(JsonElement element) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RestoreDetailsInternal)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Status)) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.Value.ToString()); + } + if (Optional.IsDefined(StatusDetails)) + { + writer.WritePropertyName("statusDetails"u8); + writer.WriteStringValue(StatusDetails); + } + if (Optional.IsDefined(Error)) + { + if (Error != null) + { + writer.WritePropertyName("error"u8); + writer.WriteObjectValue(Error, options); + } + else + { + writer.WriteNull("error"); + } + } + if (Optional.IsDefined(JobId)) + { + writer.WritePropertyName("jobId"u8); + writer.WriteStringValue(JobId); + } + if (Optional.IsDefined(StartTime)) + { + writer.WritePropertyName("startTime"u8); + writer.WriteNumberValue(StartTime.Value, "U"); + } + if (Optional.IsDefined(EndTime)) + { + if (EndTime != null) + { + writer.WritePropertyName("endTime"u8); + writer.WriteNumberValue(EndTime.Value, "U"); + } + else + { + writer.WriteNull("endTime"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RestoreDetailsInternal IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RestoreDetailsInternal)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRestoreDetailsInternal(document.RootElement, options); + } + + internal static RestoreDetailsInternal DeserializeRestoreDetailsInternal(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + if (element.ValueKind == JsonValueKind.Null) { return null; } - string status = default; + OperationStatus? status = default; string statusDetails = default; - KeyVaultServiceError error = default; + FullBackupOperationError error = default; string jobId = default; DateTimeOffset? startTime = default; DateTimeOffset? endTime = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("status"u8)) { - status = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new OperationStatus(property.Value.GetString()); continue; } if (property.NameEquals("statusDetails"u8)) @@ -43,7 +146,7 @@ internal static RestoreDetailsInternal DeserializeRestoreDetailsInternal(JsonEle error = null; continue; } - error = KeyVaultServiceError.DeserializeKeyVaultServiceError(property.Value); + error = FullBackupOperationError.DeserializeFullBackupOperationError(property.Value, options); continue; } if (property.NameEquals("jobId"u8)) @@ -70,16 +173,53 @@ internal static RestoreDetailsInternal DeserializeRestoreDetailsInternal(JsonEle endTime = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); continue; } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } } + serializedAdditionalRawData = rawDataDictionary; return new RestoreDetailsInternal( status, statusDetails, error, jobId, startTime, - endTime); + endTime, + serializedAdditionalRawData); } + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RestoreDetailsInternal)} does not support writing '{options.Format}' format."); + } + } + + RestoreDetailsInternal IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeRestoreDetailsInternal(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RestoreDetailsInternal)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + /// Deserializes the model from a raw response. /// The response to deserialize the model from. internal static RestoreDetailsInternal FromResponse(Response response) @@ -87,5 +227,13 @@ internal static RestoreDetailsInternal FromResponse(Response response) using var document = JsonDocument.Parse(response.Content); return DeserializeRestoreDetailsInternal(document.RootElement); } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreDetailsInternal.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreDetailsInternal.cs index 7173de76b4a7..62fd91e96d40 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreDetailsInternal.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreDetailsInternal.cs @@ -6,12 +6,45 @@ #nullable disable using System; +using System.Collections.Generic; namespace Azure.Security.KeyVault.Administration.Models { /// Restore operation. internal partial class RestoreDetailsInternal { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . internal RestoreDetailsInternal() { @@ -24,7 +57,8 @@ internal RestoreDetailsInternal() /// Identifier for the restore operation. /// The start time of the restore operation. /// The end time of the restore operation. - internal RestoreDetailsInternal(string status, string statusDetails, KeyVaultServiceError error, string jobId, DateTimeOffset? startTime, DateTimeOffset? endTime) + /// Keeps track of any properties unknown to the library. + internal RestoreDetailsInternal(OperationStatus? status, string statusDetails, FullBackupOperationError error, string jobId, DateTimeOffset? startTime, DateTimeOffset? endTime, IDictionary serializedAdditionalRawData) { Status = status; StatusDetails = statusDetails; @@ -32,14 +66,15 @@ internal RestoreDetailsInternal(string status, string statusDetails, KeyVaultSer JobId = jobId; StartTime = startTime; EndTime = endTime; + _serializedAdditionalRawData = serializedAdditionalRawData; } /// Status of the restore operation. - public string Status { get; } + public OperationStatus? Status { get; } /// The status details of restore operation. public string StatusDetails { get; } /// Error encountered, if any, during the restore operation. - public KeyVaultServiceError Error { get; } + public FullBackupOperationError Error { get; } /// Identifier for the restore operation. public string JobId { get; } /// The start time of the restore operation. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreOperationParameters.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreOperationParameters.Serialization.cs index 70f3efbca93b..4e145345a534 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreOperationParameters.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreOperationParameters.Serialization.cs @@ -5,28 +5,145 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Security.KeyVault.Administration.Models { - internal partial class RestoreOperationParameters : IUtf8JsonSerializable + internal partial class RestoreOperationParameters : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RestoreOperationParameters)} does not support writing '{format}' format."); + } + writer.WritePropertyName("sasTokenParameters"u8); - writer.WriteObjectValue(SasTokenParameters); + writer.WriteObjectValue(SasTokenParameters, options); writer.WritePropertyName("folderToRestore"u8); writer.WriteStringValue(FolderToRestore); - writer.WriteEndObject(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RestoreOperationParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RestoreOperationParameters)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRestoreOperationParameters(document.RootElement, options); + } + + internal static RestoreOperationParameters DeserializeRestoreOperationParameters(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + SASTokenParameter sasTokenParameters = default; + string folderToRestore = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("sasTokenParameters"u8)) + { + sasTokenParameters = SASTokenParameter.DeserializeSASTokenParameter(property.Value, options); + continue; + } + if (property.NameEquals("folderToRestore"u8)) + { + folderToRestore = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RestoreOperationParameters(sasTokenParameters, folderToRestore, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RestoreOperationParameters)} does not support writing '{options.Format}' format."); + } + } + + RestoreOperationParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeRestoreOperationParameters(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RestoreOperationParameters)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RestoreOperationParameters FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRestoreOperationParameters(document.RootElement); } /// Convert into a . internal virtual RequestContent ToRequestContent() { var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); return content; } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreOperationParameters.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreOperationParameters.cs index 3e69b4754997..94d7de0de64c 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreOperationParameters.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RestoreOperationParameters.cs @@ -6,14 +6,47 @@ #nullable disable using System; +using System.Collections.Generic; namespace Azure.Security.KeyVault.Administration.Models { - /// The RestoreOperationParameters. + /// The authentication method and location for the restore operation. internal partial class RestoreOperationParameters { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . - /// + /// A user-provided SAS token to an Azure blob storage container. /// The Folder name of the blob where the previous successful full backup was stored. /// or is null. public RestoreOperationParameters(SASTokenParameter sasTokenParameters, string folderToRestore) @@ -25,7 +58,23 @@ public RestoreOperationParameters(SASTokenParameter sasTokenParameters, string f FolderToRestore = folderToRestore; } - /// Gets the sas token parameters. + /// Initializes a new instance of . + /// A user-provided SAS token to an Azure blob storage container. + /// The Folder name of the blob where the previous successful full backup was stored. + /// Keeps track of any properties unknown to the library. + internal RestoreOperationParameters(SASTokenParameter sasTokenParameters, string folderToRestore, IDictionary serializedAdditionalRawData) + { + SasTokenParameters = sasTokenParameters; + FolderToRestore = folderToRestore; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RestoreOperationParameters() + { + } + + /// A user-provided SAS token to an Azure blob storage container. public SASTokenParameter SasTokenParameters { get; } /// The Folder name of the blob where the previous successful full backup was stored. public string FolderToRestore { get; } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentCreateParameters.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentCreateParameters.Serialization.cs index ce5d0b0af2cd..5fbb40c20dce 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentCreateParameters.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentCreateParameters.Serialization.cs @@ -5,26 +5,137 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Security.KeyVault.Administration.Models { - internal partial class RoleAssignmentCreateParameters : IUtf8JsonSerializable + internal partial class RoleAssignmentCreateParameters : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); - writer.WritePropertyName("properties"u8); - writer.WriteObjectValue(Properties); + JsonModelWriteCore(writer, options); writer.WriteEndObject(); } + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RoleAssignmentCreateParameters)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("properties"u8); + writer.WriteObjectValue(Properties, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RoleAssignmentCreateParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RoleAssignmentCreateParameters)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRoleAssignmentCreateParameters(document.RootElement, options); + } + + internal static RoleAssignmentCreateParameters DeserializeRoleAssignmentCreateParameters(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + KeyVaultRoleAssignmentPropertiesInternal properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("properties"u8)) + { + properties = KeyVaultRoleAssignmentPropertiesInternal.DeserializeKeyVaultRoleAssignmentPropertiesInternal(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RoleAssignmentCreateParameters(properties, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RoleAssignmentCreateParameters)} does not support writing '{options.Format}' format."); + } + } + + RoleAssignmentCreateParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeRoleAssignmentCreateParameters(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RoleAssignmentCreateParameters)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RoleAssignmentCreateParameters FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRoleAssignmentCreateParameters(document.RootElement); + } + /// Convert into a . internal virtual RequestContent ToRequestContent() { var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); return content; } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentCreateParameters.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentCreateParameters.cs index 45937ed314ce..fbb3f5176b5f 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentCreateParameters.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentCreateParameters.cs @@ -6,12 +6,45 @@ #nullable disable using System; +using System.Collections.Generic; namespace Azure.Security.KeyVault.Administration.Models { /// Role assignment create parameters. internal partial class RoleAssignmentCreateParameters { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . /// Role assignment properties. /// is null. @@ -22,6 +55,20 @@ public RoleAssignmentCreateParameters(KeyVaultRoleAssignmentPropertiesInternal p Properties = properties; } + /// Initializes a new instance of . + /// Role assignment properties. + /// Keeps track of any properties unknown to the library. + internal RoleAssignmentCreateParameters(KeyVaultRoleAssignmentPropertiesInternal properties, IDictionary serializedAdditionalRawData) + { + Properties = properties; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RoleAssignmentCreateParameters() + { + } + /// Role assignment properties. public KeyVaultRoleAssignmentPropertiesInternal Properties { get; } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentFilter.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentFilter.cs deleted file mode 100644 index 8a11843624d4..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentFilter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.Security.KeyVault.Administration.Models -{ - /// Role Assignments filter. - internal partial class RoleAssignmentFilter - { - /// Initializes a new instance of . - internal RoleAssignmentFilter() - { - } - - /// Initializes a new instance of . - /// Returns role assignment of the specific principal. - internal RoleAssignmentFilter(string principalId) - { - PrincipalId = principalId; - } - - /// Returns role assignment of the specific principal. - public string PrincipalId { get; } - } -} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentListResult.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentListResult.Serialization.cs index c8263b8c3a6f..d599aad8db1a 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentListResult.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentListResult.Serialization.cs @@ -5,21 +5,91 @@ #nullable disable +using System; +using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; namespace Azure.Security.KeyVault.Administration.Models { - internal partial class RoleAssignmentListResult + internal partial class RoleAssignmentListResult : IUtf8JsonSerializable, IJsonModel { - internal static RoleAssignmentListResult DeserializeRoleAssignmentListResult(JsonElement element) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RoleAssignmentListResult)} does not support writing '{format}' format."); + } + + if (Optional.IsCollectionDefined(Value)) + { + writer.WritePropertyName("value"u8); + writer.WriteStartArray(); + foreach (var item in Value) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(NextLink)) + { + writer.WritePropertyName("nextLink"u8); + writer.WriteStringValue(NextLink); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RoleAssignmentListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RoleAssignmentListResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRoleAssignmentListResult(document.RootElement, options); + } + + internal static RoleAssignmentListResult DeserializeRoleAssignmentListResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + if (element.ValueKind == JsonValueKind.Null) { return null; } IReadOnlyList value = default; string nextLink = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("value"u8)) @@ -31,7 +101,7 @@ internal static RoleAssignmentListResult DeserializeRoleAssignmentListResult(Jso List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(KeyVaultRoleAssignment.DeserializeKeyVaultRoleAssignment(item)); + array.Add(KeyVaultRoleAssignment.DeserializeKeyVaultRoleAssignment(item, options)); } value = array; continue; @@ -41,10 +111,46 @@ internal static RoleAssignmentListResult DeserializeRoleAssignmentListResult(Jso nextLink = property.Value.GetString(); continue; } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RoleAssignmentListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RoleAssignmentListResult)} does not support writing '{options.Format}' format."); } - return new RoleAssignmentListResult(value ?? new ChangeTrackingList(), nextLink); } + RoleAssignmentListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeRoleAssignmentListResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RoleAssignmentListResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + /// Deserializes the model from a raw response. /// The response to deserialize the model from. internal static RoleAssignmentListResult FromResponse(Response response) @@ -52,5 +158,13 @@ internal static RoleAssignmentListResult FromResponse(Response response) using var document = JsonDocument.Parse(response.Content); return DeserializeRoleAssignmentListResult(document.RootElement); } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentListResult.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentListResult.cs index 28ebf982e753..1e7138c863d2 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentListResult.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleAssignmentListResult.cs @@ -5,6 +5,7 @@ #nullable disable +using System; using System.Collections.Generic; namespace Azure.Security.KeyVault.Administration.Models @@ -12,6 +13,38 @@ namespace Azure.Security.KeyVault.Administration.Models /// Role assignment list operation result. internal partial class RoleAssignmentListResult { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . internal RoleAssignmentListResult() { @@ -21,10 +54,12 @@ internal RoleAssignmentListResult() /// Initializes a new instance of . /// Role assignment list. /// The URL to use for getting the next set of results. - internal RoleAssignmentListResult(IReadOnlyList value, string nextLink) + /// Keeps track of any properties unknown to the library. + internal RoleAssignmentListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) { Value = value; NextLink = nextLink; + _serializedAdditionalRawData = serializedAdditionalRawData; } /// Role assignment list. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionCreateParameters.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionCreateParameters.Serialization.cs index 538c39739fc2..0ab95f0d70be 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionCreateParameters.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionCreateParameters.Serialization.cs @@ -5,26 +5,137 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Security.KeyVault.Administration.Models { - internal partial class RoleDefinitionCreateParameters : IUtf8JsonSerializable + internal partial class RoleDefinitionCreateParameters : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); - writer.WritePropertyName("properties"u8); - writer.WriteObjectValue(Properties); + JsonModelWriteCore(writer, options); writer.WriteEndObject(); } + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RoleDefinitionCreateParameters)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("properties"u8); + writer.WriteObjectValue(Properties, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RoleDefinitionCreateParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RoleDefinitionCreateParameters)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRoleDefinitionCreateParameters(document.RootElement, options); + } + + internal static RoleDefinitionCreateParameters DeserializeRoleDefinitionCreateParameters(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + RoleDefinitionProperties properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("properties"u8)) + { + properties = RoleDefinitionProperties.DeserializeRoleDefinitionProperties(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RoleDefinitionCreateParameters(properties, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RoleDefinitionCreateParameters)} does not support writing '{options.Format}' format."); + } + } + + RoleDefinitionCreateParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeRoleDefinitionCreateParameters(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RoleDefinitionCreateParameters)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RoleDefinitionCreateParameters FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRoleDefinitionCreateParameters(document.RootElement); + } + /// Convert into a . internal virtual RequestContent ToRequestContent() { var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); return content; } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionCreateParameters.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionCreateParameters.cs index 6100dd3aa79b..f2acbed0b60f 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionCreateParameters.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionCreateParameters.cs @@ -6,12 +6,45 @@ #nullable disable using System; +using System.Collections.Generic; namespace Azure.Security.KeyVault.Administration.Models { /// Role definition create parameters. internal partial class RoleDefinitionCreateParameters { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . /// Role definition properties. /// is null. @@ -22,6 +55,20 @@ public RoleDefinitionCreateParameters(RoleDefinitionProperties properties) Properties = properties; } + /// Initializes a new instance of . + /// Role definition properties. + /// Keeps track of any properties unknown to the library. + internal RoleDefinitionCreateParameters(RoleDefinitionProperties properties, IDictionary serializedAdditionalRawData) + { + Properties = properties; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RoleDefinitionCreateParameters() + { + } + /// Role definition properties. public RoleDefinitionProperties Properties { get; } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionFilter.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionFilter.cs deleted file mode 100644 index 3b360c44c465..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionFilter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.Security.KeyVault.Administration.Models -{ - /// Role Definitions filter. - internal partial class RoleDefinitionFilter - { - /// Initializes a new instance of . - internal RoleDefinitionFilter() - { - } - - /// Initializes a new instance of . - /// Returns role definition with the specific name. - internal RoleDefinitionFilter(string roleName) - { - RoleName = roleName; - } - - /// Returns role definition with the specific name. - public string RoleName { get; } - } -} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionListResult.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionListResult.Serialization.cs index 81786f213cc6..18c39f9da964 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionListResult.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionListResult.Serialization.cs @@ -5,21 +5,91 @@ #nullable disable +using System; +using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; namespace Azure.Security.KeyVault.Administration.Models { - internal partial class RoleDefinitionListResult + internal partial class RoleDefinitionListResult : IUtf8JsonSerializable, IJsonModel { - internal static RoleDefinitionListResult DeserializeRoleDefinitionListResult(JsonElement element) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RoleDefinitionListResult)} does not support writing '{format}' format."); + } + + if (Optional.IsCollectionDefined(Value)) + { + writer.WritePropertyName("value"u8); + writer.WriteStartArray(); + foreach (var item in Value) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(NextLink)) + { + writer.WritePropertyName("nextLink"u8); + writer.WriteStringValue(NextLink); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RoleDefinitionListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RoleDefinitionListResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRoleDefinitionListResult(document.RootElement, options); + } + + internal static RoleDefinitionListResult DeserializeRoleDefinitionListResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + if (element.ValueKind == JsonValueKind.Null) { return null; } IReadOnlyList value = default; string nextLink = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("value"u8)) @@ -31,7 +101,7 @@ internal static RoleDefinitionListResult DeserializeRoleDefinitionListResult(Jso List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(KeyVaultRoleDefinition.DeserializeKeyVaultRoleDefinition(item)); + array.Add(KeyVaultRoleDefinition.DeserializeKeyVaultRoleDefinition(item, options)); } value = array; continue; @@ -41,10 +111,46 @@ internal static RoleDefinitionListResult DeserializeRoleDefinitionListResult(Jso nextLink = property.Value.GetString(); continue; } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RoleDefinitionListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RoleDefinitionListResult)} does not support writing '{options.Format}' format."); } - return new RoleDefinitionListResult(value ?? new ChangeTrackingList(), nextLink); } + RoleDefinitionListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeRoleDefinitionListResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RoleDefinitionListResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + /// Deserializes the model from a raw response. /// The response to deserialize the model from. internal static RoleDefinitionListResult FromResponse(Response response) @@ -52,5 +158,13 @@ internal static RoleDefinitionListResult FromResponse(Response response) using var document = JsonDocument.Parse(response.Content); return DeserializeRoleDefinitionListResult(document.RootElement); } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionListResult.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionListResult.cs index 455544208c5e..b6607639f6d3 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionListResult.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionListResult.cs @@ -5,6 +5,7 @@ #nullable disable +using System; using System.Collections.Generic; namespace Azure.Security.KeyVault.Administration.Models @@ -12,6 +13,38 @@ namespace Azure.Security.KeyVault.Administration.Models /// Role definition list operation result. internal partial class RoleDefinitionListResult { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . internal RoleDefinitionListResult() { @@ -21,10 +54,12 @@ internal RoleDefinitionListResult() /// Initializes a new instance of . /// Role definition list. /// The URL to use for getting the next set of results. - internal RoleDefinitionListResult(IReadOnlyList value, string nextLink) + /// Keeps track of any properties unknown to the library. + internal RoleDefinitionListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) { Value = value; NextLink = nextLink; + _serializedAdditionalRawData = serializedAdditionalRawData; } /// Role definition list. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionProperties.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionProperties.Serialization.cs index 382f7a32558e..e2e60ce3cdfa 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionProperties.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionProperties.Serialization.cs @@ -5,16 +5,35 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Security.KeyVault.Administration.Models { - internal partial class RoleDefinitionProperties : IUtf8JsonSerializable + internal partial class RoleDefinitionProperties : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RoleDefinitionProperties)} does not support writing '{format}' format."); + } + if (Optional.IsDefined(RoleName)) { writer.WritePropertyName("roleName"u8); @@ -36,7 +55,7 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) writer.WriteStartArray(); foreach (var item in Permissions) { - writer.WriteObjectValue(item); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } @@ -50,14 +69,158 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) } writer.WriteEndArray(); } - writer.WriteEndObject(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RoleDefinitionProperties IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RoleDefinitionProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRoleDefinitionProperties(document.RootElement, options); + } + + internal static RoleDefinitionProperties DeserializeRoleDefinitionProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string roleName = default; + string description = default; + KeyVaultRoleType? type = default; + IList permissions = default; + IList assignableScopes = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("roleName"u8)) + { + roleName = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + type = new KeyVaultRoleType(property.Value.GetString()); + continue; + } + if (property.NameEquals("permissions"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyVaultPermission.DeserializeKeyVaultPermission(item, options)); + } + permissions = array; + continue; + } + if (property.NameEquals("assignableScopes"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(new KeyVaultRoleScope(item.GetString())); + } + assignableScopes = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RoleDefinitionProperties( + roleName, + description, + type, + permissions ?? new ChangeTrackingList(), + assignableScopes ?? new ChangeTrackingList(), + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RoleDefinitionProperties)} does not support writing '{options.Format}' format."); + } + } + + RoleDefinitionProperties IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeRoleDefinitionProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RoleDefinitionProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RoleDefinitionProperties FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRoleDefinitionProperties(document.RootElement); } /// Convert into a . internal virtual RequestContent ToRequestContent() { var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); return content; } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionProperties.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionProperties.cs index 4f20bf362b14..b9f7fee4c55f 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionProperties.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/RoleDefinitionProperties.cs @@ -5,6 +5,7 @@ #nullable disable +using System; using System.Collections.Generic; namespace Azure.Security.KeyVault.Administration.Models @@ -12,6 +13,38 @@ namespace Azure.Security.KeyVault.Administration.Models /// Role definition properties. internal partial class RoleDefinitionProperties { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . public RoleDefinitionProperties() { @@ -25,13 +58,15 @@ public RoleDefinitionProperties() /// The role type. /// Role definition permissions. /// Role definition assignable scopes. - internal RoleDefinitionProperties(string roleName, string description, KeyVaultRoleType? roleType, IList permissions, IList assignableScopes) + /// Keeps track of any properties unknown to the library. + internal RoleDefinitionProperties(string roleName, string description, KeyVaultRoleType? roleType, IList permissions, IList assignableScopes, IDictionary serializedAdditionalRawData) { RoleName = roleName; Description = description; RoleType = roleType; Permissions = permissions; AssignableScopes = assignableScopes; + _serializedAdditionalRawData = serializedAdditionalRawData; } /// The role name. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SASTokenParameter.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SASTokenParameter.Serialization.cs index 5332718570d5..aad92c9a574d 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SASTokenParameter.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SASTokenParameter.Serialization.cs @@ -5,16 +5,35 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Security.KeyVault.Administration.Models { - internal partial class SASTokenParameter : IUtf8JsonSerializable + internal partial class SASTokenParameter : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SASTokenParameter)} does not support writing '{format}' format."); + } + writer.WritePropertyName("storageResourceUri"u8); writer.WriteStringValue(StorageResourceUri); if (Optional.IsDefined(Token)) @@ -27,14 +46,122 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) writer.WritePropertyName("useManagedIdentity"u8); writer.WriteBooleanValue(UseManagedIdentity.Value); } - writer.WriteEndObject(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + SASTokenParameter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SASTokenParameter)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSASTokenParameter(document.RootElement, options); + } + + internal static SASTokenParameter DeserializeSASTokenParameter(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string storageResourceUri = default; + string token = default; + bool? useManagedIdentity = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("storageResourceUri"u8)) + { + storageResourceUri = property.Value.GetString(); + continue; + } + if (property.NameEquals("token"u8)) + { + token = property.Value.GetString(); + continue; + } + if (property.NameEquals("useManagedIdentity"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + useManagedIdentity = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SASTokenParameter(storageResourceUri, token, useManagedIdentity, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(SASTokenParameter)} does not support writing '{options.Format}' format."); + } + } + + SASTokenParameter IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeSASTokenParameter(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SASTokenParameter)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static SASTokenParameter FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeSASTokenParameter(document.RootElement); } /// Convert into a . internal virtual RequestContent ToRequestContent() { var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); return content; } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SASTokenParameter.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SASTokenParameter.cs index c503ec71dd27..c3f1522c4010 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SASTokenParameter.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SASTokenParameter.cs @@ -6,12 +6,45 @@ #nullable disable using System; +using System.Collections.Generic; namespace Azure.Security.KeyVault.Administration.Models { - /// The SASTokenParameter. + /// An authentication method and location for the operation. internal partial class SASTokenParameter { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . /// Azure Blob storage container Uri. /// is null. @@ -26,11 +59,18 @@ public SASTokenParameter(string storageResourceUri) /// Azure Blob storage container Uri. /// The SAS token pointing to an Azure Blob storage container. /// Indicates which authentication method should be used. If set to true, Managed HSM will use the configured user-assigned managed identity to authenticate with Azure Storage. Otherwise, a SAS token has to be specified. - internal SASTokenParameter(string storageResourceUri, string token, bool? useManagedIdentity) + /// Keeps track of any properties unknown to the library. + internal SASTokenParameter(string storageResourceUri, string token, bool? useManagedIdentity, IDictionary serializedAdditionalRawData) { StorageResourceUri = storageResourceUri; Token = token; UseManagedIdentity = useManagedIdentity; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SASTokenParameter() + { } /// Azure Blob storage container Uri. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreDetailsInternal.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreDetailsInternal.Serialization.cs index 2e2854411b24..f3952a2f3f80 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreDetailsInternal.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreDetailsInternal.Serialization.cs @@ -6,29 +6,132 @@ #nullable disable using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; +using Azure.Core; namespace Azure.Security.KeyVault.Administration.Models { - internal partial class SelectiveKeyRestoreDetailsInternal + internal partial class SelectiveKeyRestoreDetailsInternal : IUtf8JsonSerializable, IJsonModel { - internal static SelectiveKeyRestoreDetailsInternal DeserializeSelectiveKeyRestoreDetailsInternal(JsonElement element) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SelectiveKeyRestoreDetailsInternal)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Status)) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.Value.ToString()); + } + if (Optional.IsDefined(StatusDetails)) + { + writer.WritePropertyName("statusDetails"u8); + writer.WriteStringValue(StatusDetails); + } + if (Optional.IsDefined(Error)) + { + if (Error != null) + { + writer.WritePropertyName("error"u8); + writer.WriteObjectValue(Error, options); + } + else + { + writer.WriteNull("error"); + } + } + if (Optional.IsDefined(JobId)) + { + writer.WritePropertyName("jobId"u8); + writer.WriteStringValue(JobId); + } + if (Optional.IsDefined(StartTime)) + { + writer.WritePropertyName("startTime"u8); + writer.WriteNumberValue(StartTime.Value, "U"); + } + if (Optional.IsDefined(EndTime)) + { + if (EndTime != null) + { + writer.WritePropertyName("endTime"u8); + writer.WriteNumberValue(EndTime.Value, "U"); + } + else + { + writer.WriteNull("endTime"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + SelectiveKeyRestoreDetailsInternal IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SelectiveKeyRestoreDetailsInternal)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSelectiveKeyRestoreDetailsInternal(document.RootElement, options); + } + + internal static SelectiveKeyRestoreDetailsInternal DeserializeSelectiveKeyRestoreDetailsInternal(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + if (element.ValueKind == JsonValueKind.Null) { return null; } - string status = default; + OperationStatus? status = default; string statusDetails = default; - KeyVaultServiceError error = default; + FullBackupOperationError error = default; string jobId = default; DateTimeOffset? startTime = default; DateTimeOffset? endTime = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("status"u8)) { - status = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new OperationStatus(property.Value.GetString()); continue; } if (property.NameEquals("statusDetails"u8)) @@ -43,7 +146,7 @@ internal static SelectiveKeyRestoreDetailsInternal DeserializeSelectiveKeyRestor error = null; continue; } - error = KeyVaultServiceError.DeserializeKeyVaultServiceError(property.Value); + error = FullBackupOperationError.DeserializeFullBackupOperationError(property.Value, options); continue; } if (property.NameEquals("jobId"u8)) @@ -70,16 +173,53 @@ internal static SelectiveKeyRestoreDetailsInternal DeserializeSelectiveKeyRestor endTime = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); continue; } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } } + serializedAdditionalRawData = rawDataDictionary; return new SelectiveKeyRestoreDetailsInternal( status, statusDetails, error, jobId, startTime, - endTime); + endTime, + serializedAdditionalRawData); } + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(SelectiveKeyRestoreDetailsInternal)} does not support writing '{options.Format}' format."); + } + } + + SelectiveKeyRestoreDetailsInternal IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeSelectiveKeyRestoreDetailsInternal(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SelectiveKeyRestoreDetailsInternal)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + /// Deserializes the model from a raw response. /// The response to deserialize the model from. internal static SelectiveKeyRestoreDetailsInternal FromResponse(Response response) @@ -87,5 +227,13 @@ internal static SelectiveKeyRestoreDetailsInternal FromResponse(Response respons using var document = JsonDocument.Parse(response.Content); return DeserializeSelectiveKeyRestoreDetailsInternal(document.RootElement); } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreDetailsInternal.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreDetailsInternal.cs index 02070cc29745..79550c4721fd 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreDetailsInternal.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreDetailsInternal.cs @@ -6,12 +6,45 @@ #nullable disable using System; +using System.Collections.Generic; namespace Azure.Security.KeyVault.Administration.Models { /// Selective Key Restore operation. internal partial class SelectiveKeyRestoreDetailsInternal { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . internal SelectiveKeyRestoreDetailsInternal() { @@ -24,7 +57,8 @@ internal SelectiveKeyRestoreDetailsInternal() /// Identifier for the selective key restore operation. /// The start time of the restore operation. /// The end time of the restore operation. - internal SelectiveKeyRestoreDetailsInternal(string status, string statusDetails, KeyVaultServiceError error, string jobId, DateTimeOffset? startTime, DateTimeOffset? endTime) + /// Keeps track of any properties unknown to the library. + internal SelectiveKeyRestoreDetailsInternal(OperationStatus? status, string statusDetails, FullBackupOperationError error, string jobId, DateTimeOffset? startTime, DateTimeOffset? endTime, IDictionary serializedAdditionalRawData) { Status = status; StatusDetails = statusDetails; @@ -32,14 +66,15 @@ internal SelectiveKeyRestoreDetailsInternal(string status, string statusDetails, JobId = jobId; StartTime = startTime; EndTime = endTime; + _serializedAdditionalRawData = serializedAdditionalRawData; } /// Status of the restore operation. - public string Status { get; } + public OperationStatus? Status { get; } /// The status details of restore operation. public string StatusDetails { get; } /// Error encountered, if any, during the selective key restore operation. - public KeyVaultServiceError Error { get; } + public FullBackupOperationError Error { get; } /// Identifier for the selective key restore operation. public string JobId { get; } /// The start time of the restore operation. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreOperationParameters.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreOperationParameters.Serialization.cs index 8aabf0abe13b..cc20ff9c2761 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreOperationParameters.Serialization.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreOperationParameters.Serialization.cs @@ -5,28 +5,145 @@ #nullable disable +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Security.KeyVault.Administration.Models { - internal partial class SelectiveKeyRestoreOperationParameters : IUtf8JsonSerializable + internal partial class SelectiveKeyRestoreOperationParameters : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SelectiveKeyRestoreOperationParameters)} does not support writing '{format}' format."); + } + writer.WritePropertyName("sasTokenParameters"u8); - writer.WriteObjectValue(SasTokenParameters); + writer.WriteObjectValue(SasTokenParameters, options); writer.WritePropertyName("folder"u8); writer.WriteStringValue(Folder); - writer.WriteEndObject(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + SelectiveKeyRestoreOperationParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SelectiveKeyRestoreOperationParameters)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSelectiveKeyRestoreOperationParameters(document.RootElement, options); + } + + internal static SelectiveKeyRestoreOperationParameters DeserializeSelectiveKeyRestoreOperationParameters(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + SASTokenParameter sasTokenParameters = default; + string folder = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("sasTokenParameters"u8)) + { + sasTokenParameters = SASTokenParameter.DeserializeSASTokenParameter(property.Value, options); + continue; + } + if (property.NameEquals("folder"u8)) + { + folder = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SelectiveKeyRestoreOperationParameters(sasTokenParameters, folder, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(SelectiveKeyRestoreOperationParameters)} does not support writing '{options.Format}' format."); + } + } + + SelectiveKeyRestoreOperationParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeSelectiveKeyRestoreOperationParameters(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SelectiveKeyRestoreOperationParameters)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static SelectiveKeyRestoreOperationParameters FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeSelectiveKeyRestoreOperationParameters(document.RootElement); } /// Convert into a . internal virtual RequestContent ToRequestContent() { var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); return content; } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreOperationParameters.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreOperationParameters.cs index a933200c680b..02a20a2fb946 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreOperationParameters.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/SelectiveKeyRestoreOperationParameters.cs @@ -6,14 +6,47 @@ #nullable disable using System; +using System.Collections.Generic; namespace Azure.Security.KeyVault.Administration.Models { - /// The SelectiveKeyRestoreOperationParameters. + /// The authentication method and location for the selective key restore operation. internal partial class SelectiveKeyRestoreOperationParameters { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . - /// + /// A user-provided SAS token to an Azure blob storage container. /// The Folder name of the blob where the previous successful full backup was stored. /// or is null. public SelectiveKeyRestoreOperationParameters(SASTokenParameter sasTokenParameters, string folder) @@ -25,7 +58,23 @@ public SelectiveKeyRestoreOperationParameters(SASTokenParameter sasTokenParamete Folder = folder; } - /// Gets the sas token parameters. + /// Initializes a new instance of . + /// A user-provided SAS token to an Azure blob storage container. + /// The Folder name of the blob where the previous successful full backup was stored. + /// Keeps track of any properties unknown to the library. + internal SelectiveKeyRestoreOperationParameters(SASTokenParameter sasTokenParameters, string folder, IDictionary serializedAdditionalRawData) + { + SasTokenParameters = sasTokenParameters; + Folder = folder; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SelectiveKeyRestoreOperationParameters() + { + } + + /// A user-provided SAS token to an Azure blob storage container. public SASTokenParameter SasTokenParameters { get; } /// The Folder name of the blob where the previous successful full backup was stored. public string Folder { get; } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/UpdateSettingRequest.Serialization.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/UpdateSettingRequest.Serialization.cs deleted file mode 100644 index 129def546b1d..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/UpdateSettingRequest.Serialization.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Text.Json; -using Azure.Core; - -namespace Azure.Security.KeyVault.Administration.Models -{ - internal partial class UpdateSettingRequest : IUtf8JsonSerializable - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) - { - writer.WriteStartObject(); - 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/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/UpdateSettingRequest.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/UpdateSettingRequest.cs deleted file mode 100644 index b55fad5e8382..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/Models/UpdateSettingRequest.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.Security.KeyVault.Administration.Models -{ - /// The update settings request object. - internal partial class UpdateSettingRequest - { - /// Initializes a new instance of . - /// The value of the pool setting. - /// is null. - public UpdateSettingRequest(string value) - { - Argument.AssertNotNull(value, nameof(value)); - - Value = value; - } - - /// The value of the pool setting. - public string Value { get; } - } -} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/RoleAssignmentsRestClient.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/RoleAssignmentsRestClient.cs index 8cdf96815723..3906a980b62d 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/RoleAssignmentsRestClient.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/RoleAssignmentsRestClient.cs @@ -6,487 +6,620 @@ #nullable disable using System; -using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Autorest.CSharp.Core; using Azure.Core; using Azure.Core.Pipeline; using Azure.Security.KeyVault.Administration.Models; namespace Azure.Security.KeyVault.Administration { - internal partial class RoleAssignmentsRestClient + // Data plane generated client. + /// The RoleAssignmentsRest service client. + public partial class RoleAssignmentsRestClient { + private static readonly string[] AuthorizationScopes = new string[] { "https://vault.azure.net/.default" }; + private readonly TokenCredential _tokenCredential; private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; private readonly string _apiVersion; /// The ClientDiagnostics is used to provide tracing support for the client library. internal ClientDiagnostics ClientDiagnostics { get; } + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of RoleAssignmentsRestClient for mocking. + protected RoleAssignmentsRestClient() + { + } + /// Initializes a new instance of RoleAssignmentsRestClient. - /// 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 RoleAssignmentsRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string apiVersion = "7.5") + /// The to use. + /// A credential used to authenticate to an Azure Service. + /// or is null. + public RoleAssignmentsRestClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new AzureSecurityKeyVaultAdministrationClientOptions()) { - ClientDiagnostics = clientDiagnostics ?? throw new ArgumentNullException(nameof(clientDiagnostics)); - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _apiVersion = apiVersion ?? throw new ArgumentNullException(nameof(apiVersion)); } - internal HttpMessage CreateDeleteRequest(string vaultBaseUrl, string scope, string roleAssignmentName) + /// Initializes a new instance of RoleAssignmentsRestClient. + /// The to use. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public RoleAssignmentsRestClient(Uri endpoint, TokenCredential credential, AzureSecurityKeyVaultAdministrationClientOptions options) { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments/", false); - uri.AppendPath(roleAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new AzureSecurityKeyVaultAdministrationClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; } /// Deletes a role assignment. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role assignment to delete. /// The name of the role assignment to delete. /// The cancellation token to use. - /// , or is null. - public async Task DeleteAsync(string vaultBaseUrl, string scope, string roleAssignmentName, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> DeleteAsync(string scope, string roleAssignmentName, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } - if (roleAssignmentName == null) - { - throw new ArgumentNullException(nameof(roleAssignmentName)); - } + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleAssignmentName, nameof(roleAssignmentName)); - using var message = CreateDeleteRequest(vaultBaseUrl, scope, roleAssignmentName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 404: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await DeleteAsync(scope, roleAssignmentName, context).ConfigureAwait(false); + return Response.FromValue(Models.KeyVaultRoleAssignment.FromResponse(response), response); } /// Deletes a role assignment. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role assignment to delete. /// The name of the role assignment to delete. /// The cancellation token to use. - /// , or is null. - public Response Delete(string vaultBaseUrl, string scope, string roleAssignmentName, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response Delete(string scope, string roleAssignmentName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleAssignmentName, nameof(roleAssignmentName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Delete(scope, roleAssignmentName, context); + return Response.FromValue(Models.KeyVaultRoleAssignment.FromResponse(response), response); + } + + /// + /// [Protocol Method] Deletes a role assignment. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role assignment to delete. + /// The name of the role assignment to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeleteAsync(string scope, string roleAssignmentName, RequestContext context) { - if (vaultBaseUrl == null) + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleAssignmentName, nameof(roleAssignmentName)); + + using var scope0 = ClientDiagnostics.CreateScope("RoleAssignmentsRestClient.Delete"); + scope0.Start(); + try { - throw new ArgumentNullException(nameof(vaultBaseUrl)); + using HttpMessage message = CreateDeleteRequest(scope, roleAssignmentName, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } - if (scope == null) + catch (Exception e) { - throw new ArgumentNullException(nameof(scope)); + scope0.Failed(e); + throw; } - if (roleAssignmentName == null) + } + + /// + /// [Protocol Method] Deletes a role assignment. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role assignment to delete. + /// The name of the role assignment to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response Delete(string scope, string roleAssignmentName, RequestContext context) + { + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleAssignmentName, nameof(roleAssignmentName)); + + using var scope0 = ClientDiagnostics.CreateScope("RoleAssignmentsRestClient.Delete"); + scope0.Start(); + try { - throw new ArgumentNullException(nameof(roleAssignmentName)); + using HttpMessage message = CreateDeleteRequest(scope, roleAssignmentName, context); + return _pipeline.ProcessMessage(message, context); } - - using var message = CreateDeleteRequest(vaultBaseUrl, scope, roleAssignmentName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) + catch (Exception e) { - case 200: - case 404: - return message.Response; - default: - throw new RequestFailedException(message.Response); + scope0.Failed(e); + throw; } } - internal HttpMessage CreateCreateRequest(string vaultBaseUrl, string scope, string roleAssignmentName, RoleAssignmentCreateParameters parameters) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments/", false); - uri.AppendPath(roleAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(parameters); - request.Content = content; - return message; - } - /// Creates a role assignment. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role assignment to create. /// The name of the role assignment to create. It can be any valid GUID. /// Parameters for the role assignment. /// The cancellation token to use. - /// , , or is null. - public async Task> CreateAsync(string vaultBaseUrl, string scope, string roleAssignmentName, RoleAssignmentCreateParameters parameters, CancellationToken cancellationToken = default) + /// , or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> CreateAsync(string scope, string roleAssignmentName, RoleAssignmentCreateParameters parameters, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } - if (roleAssignmentName == null) - { - throw new ArgumentNullException(nameof(roleAssignmentName)); - } - if (parameters == null) - { - throw new ArgumentNullException(nameof(parameters)); - } + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleAssignmentName, nameof(roleAssignmentName)); + Argument.AssertNotNull(parameters, nameof(parameters)); - using var message = CreateCreateRequest(vaultBaseUrl, scope, roleAssignmentName, parameters); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 201: - { - KeyVaultRoleAssignment value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = KeyVaultRoleAssignment.DeserializeKeyVaultRoleAssignment(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + using RequestContent content = parameters.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateAsync(scope, roleAssignmentName, content, context).ConfigureAwait(false); + return Response.FromValue(Models.KeyVaultRoleAssignment.FromResponse(response), response); } /// Creates a role assignment. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role assignment to create. /// The name of the role assignment to create. It can be any valid GUID. /// Parameters for the role assignment. /// The cancellation token to use. - /// , , or is null. - public Response Create(string vaultBaseUrl, string scope, string roleAssignmentName, RoleAssignmentCreateParameters parameters, CancellationToken cancellationToken = default) + /// , or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response Create(string scope, string roleAssignmentName, RoleAssignmentCreateParameters parameters, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleAssignmentName, nameof(roleAssignmentName)); + Argument.AssertNotNull(parameters, nameof(parameters)); + + using RequestContent content = parameters.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Create(scope, roleAssignmentName, content, context); + return Response.FromValue(Models.KeyVaultRoleAssignment.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates a role assignment. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role assignment to create. + /// The name of the role assignment to create. It can be any valid GUID. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task CreateAsync(string scope, string roleAssignmentName, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleAssignmentName, nameof(roleAssignmentName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope0 = ClientDiagnostics.CreateScope("RoleAssignmentsRestClient.Create"); + scope0.Start(); + try { - throw new ArgumentNullException(nameof(scope)); + using HttpMessage message = CreateCreateRequest(scope, roleAssignmentName, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } - if (roleAssignmentName == null) + catch (Exception e) { - throw new ArgumentNullException(nameof(roleAssignmentName)); + scope0.Failed(e); + throw; } - if (parameters == null) + } + + /// + /// [Protocol Method] Creates a role assignment. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role assignment to create. + /// The name of the role assignment to create. It can be any valid GUID. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response Create(string scope, string roleAssignmentName, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleAssignmentName, nameof(roleAssignmentName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope0 = ClientDiagnostics.CreateScope("RoleAssignmentsRestClient.Create"); + scope0.Start(); + try { - throw new ArgumentNullException(nameof(parameters)); + using HttpMessage message = CreateCreateRequest(scope, roleAssignmentName, content, context); + return _pipeline.ProcessMessage(message, context); } - - using var message = CreateCreateRequest(vaultBaseUrl, scope, roleAssignmentName, parameters); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) + catch (Exception e) { - case 201: - { - KeyVaultRoleAssignment value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = KeyVaultRoleAssignment.DeserializeKeyVaultRoleAssignment(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); + scope0.Failed(e); + throw; } } - internal HttpMessage CreateGetRequest(string vaultBaseUrl, string scope, string roleAssignmentName) + /// Get the specified role assignment. + /// The scope of the role assignment. + /// The name of the role assignment to get. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> GetRoleAssignmentsRestClientAsync(string scope, string roleAssignmentName, CancellationToken cancellationToken = default) { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments/", false); - uri.AppendPath(roleAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleAssignmentName, nameof(roleAssignmentName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetRoleAssignmentsRestClientAsync(scope, roleAssignmentName, context).ConfigureAwait(false); + return Response.FromValue(Models.KeyVaultRoleAssignment.FromResponse(response), response); } /// Get the specified role assignment. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role assignment. /// The name of the role assignment to get. /// The cancellation token to use. - /// , or is null. - public async Task> GetAsync(string vaultBaseUrl, string scope, string roleAssignmentName, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response GetRoleAssignmentsRestClient(string scope, string roleAssignmentName, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } - if (roleAssignmentName == null) - { - throw new ArgumentNullException(nameof(roleAssignmentName)); - } + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleAssignmentName, nameof(roleAssignmentName)); - using var message = CreateGetRequest(vaultBaseUrl, scope, roleAssignmentName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - KeyVaultRoleAssignment value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = KeyVaultRoleAssignment.DeserializeKeyVaultRoleAssignment(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetRoleAssignmentsRestClient(scope, roleAssignmentName, context); + return Response.FromValue(Models.KeyVaultRoleAssignment.FromResponse(response), response); } - /// Get the specified role assignment. - /// The vault name, for example https://myvault.vault.azure.net. + /// + /// [Protocol Method] Get the specified role assignment. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// /// The scope of the role assignment. /// The name of the role assignment to get. - /// The cancellation token to use. - /// , or is null. - public Response Get(string vaultBaseUrl, string scope, string roleAssignmentName, CancellationToken cancellationToken = default) + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetRoleAssignmentsRestClientAsync(string scope, string roleAssignmentName, RequestContext context) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } - if (roleAssignmentName == null) + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleAssignmentName, nameof(roleAssignmentName)); + + using var scope0 = ClientDiagnostics.CreateScope("RoleAssignmentsRestClient.GetRoleAssignmentsRestClient"); + scope0.Start(); + try { - throw new ArgumentNullException(nameof(roleAssignmentName)); + using HttpMessage message = CreateGetRoleAssignmentsRestClientRequest(scope, roleAssignmentName, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } - - using var message = CreateGetRequest(vaultBaseUrl, scope, roleAssignmentName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) + catch (Exception e) { - case 200: - { - KeyVaultRoleAssignment value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = KeyVaultRoleAssignment.DeserializeKeyVaultRoleAssignment(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); + scope0.Failed(e); + throw; } } - internal HttpMessage CreateListForScopeRequest(string vaultBaseUrl, string scope, string filter) + /// + /// [Protocol Method] Get the specified role assignment. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role assignment. + /// The name of the role assignment to get. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetRoleAssignmentsRestClient(string scope, string roleAssignmentName, RequestContext context) { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments", false); - if (filter != null) + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleAssignmentName, nameof(roleAssignmentName)); + + using var scope0 = ClientDiagnostics.CreateScope("RoleAssignmentsRestClient.GetRoleAssignmentsRestClient"); + scope0.Start(); + try { - uri.AppendQuery("$filter", filter, true); + using HttpMessage message = CreateGetRoleAssignmentsRestClientRequest(scope, roleAssignmentName, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope0.Failed(e); + throw; } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; } /// Gets role assignments for a scope. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role assignments. /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. /// The cancellation token to use. - /// or is null. - public async Task> ListForScopeAsync(string vaultBaseUrl, string scope, string filter = null, CancellationToken cancellationToken = default) + /// is null. + /// + public virtual AsyncPageable GetForScopesAsync(string scope, string filter = null, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } + Argument.AssertNotNull(scope, nameof(scope)); - using var message = CreateListForScopeRequest(vaultBaseUrl, scope, filter); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - RoleAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetForScopesRequest(scope, filter, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetForScopesNextPageRequest(nextLink, scope, filter, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => Models.KeyVaultRoleAssignment.DeserializeKeyVaultRoleAssignment(e), ClientDiagnostics, _pipeline, "RoleAssignmentsRestClient.GetForScopes", "value", "nextLink", context); } /// Gets role assignments for a scope. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role assignments. /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. /// The cancellation token to use. - /// or is null. - public Response ListForScope(string vaultBaseUrl, string scope, string filter = null, CancellationToken cancellationToken = default) + /// is null. + /// + public virtual Pageable GetForScopes(string scope, string filter = null, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } + Argument.AssertNotNull(scope, nameof(scope)); - using var message = CreateListForScopeRequest(vaultBaseUrl, scope, filter); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - RoleAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetForScopesRequest(scope, filter, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetForScopesNextPageRequest(nextLink, scope, filter, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => Models.KeyVaultRoleAssignment.DeserializeKeyVaultRoleAssignment(e), ClientDiagnostics, _pipeline, "RoleAssignmentsRestClient.GetForScopes", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Gets role assignments for a scope. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role assignments. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetForScopesAsync(string scope, string filter, RequestContext context) + { + Argument.AssertNotNull(scope, nameof(scope)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetForScopesRequest(scope, filter, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetForScopesNextPageRequest(nextLink, scope, filter, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "RoleAssignmentsRestClient.GetForScopes", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Gets role assignments for a scope. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role assignments. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetForScopes(string scope, string filter, RequestContext context) + { + Argument.AssertNotNull(scope, nameof(scope)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetForScopesRequest(scope, filter, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetForScopesNextPageRequest(nextLink, scope, filter, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "RoleAssignmentsRestClient.GetForScopes", "value", "nextLink", context); + } + + internal HttpMessage CreateDeleteRequest(string scope, string roleAssignmentName, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/", false); + uri.AppendPath(scope, false); + uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments/", false); + uri.AppendPath(roleAssignmentName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateRequest(string scope, string roleAssignmentName, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier201); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/", false); + uri.AppendPath(scope, false); + uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments/", false); + uri.AppendPath(roleAssignmentName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; } - internal HttpMessage CreateListForScopeNextPageRequest(string nextLink, string vaultBaseUrl, string scope, string filter) + internal HttpMessage CreateGetRoleAssignmentsRestClientRequest(string scope, string roleAssignmentName, RequestContext context) { - var message = _pipeline.CreateMessage(); + var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendRawNextLink(nextLink, false); + uri.Reset(_endpoint); + uri.AppendPath("/", false); + uri.AppendPath(scope, false); + uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments/", false); + uri.AppendPath(roleAssignmentName, true); + uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } - /// Gets role assignments for a scope. - /// The URL to the next page of results. - /// The vault name, for example https://myvault.vault.azure.net. - /// The scope of the role assignments. - /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. - /// The cancellation token to use. - /// , or is null. - public async Task> ListForScopeNextPageAsync(string nextLink, string vaultBaseUrl, string scope, string filter = null, CancellationToken cancellationToken = default) + internal HttpMessage CreateGetForScopesRequest(string scope, string filter, RequestContext context) { - if (nextLink == null) - { - throw new ArgumentNullException(nameof(nextLink)); - } - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/", false); + uri.AppendPath(scope, false); + uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (filter != null) { - throw new ArgumentNullException(nameof(scope)); + uri.AppendQuery("$filter", filter, true); } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } - using var message = CreateListForScopeNextPageRequest(nextLink, vaultBaseUrl, scope, filter); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - RoleAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + internal HttpMessage CreateGetForScopesNextPageRequest(string nextLink, string scope, string filter, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; } - /// Gets role assignments for a scope. - /// The URL to the next page of results. - /// The vault name, for example https://myvault.vault.azure.net. - /// The scope of the role assignments. - /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. - /// The cancellation token to use. - /// , or is null. - public Response ListForScopeNextPage(string nextLink, string vaultBaseUrl, string scope, string filter = null, CancellationToken cancellationToken = default) + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) { - if (nextLink == null) + if (!cancellationToken.CanBeCanceled) { - throw new ArgumentNullException(nameof(nextLink)); - } - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); + return DefaultRequestContext; } - using var message = CreateListForScopeNextPageRequest(nextLink, vaultBaseUrl, scope, filter); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - RoleAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + return new RequestContext() { CancellationToken = cancellationToken }; } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + private static ResponseClassifier _responseClassifier201; + private static ResponseClassifier ResponseClassifier201 => _responseClassifier201 ??= new StatusCodeClassifier(stackalloc ushort[] { 201 }); } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/RoleDefinitionsRestClient.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/RoleDefinitionsRestClient.cs index 6221ad1e783c..c6e857a44da2 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/RoleDefinitionsRestClient.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/RoleDefinitionsRestClient.cs @@ -6,487 +6,620 @@ #nullable disable using System; -using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Autorest.CSharp.Core; using Azure.Core; using Azure.Core.Pipeline; using Azure.Security.KeyVault.Administration.Models; namespace Azure.Security.KeyVault.Administration { - internal partial class RoleDefinitionsRestClient + // Data plane generated client. + /// The RoleDefinitionsRest service client. + public partial class RoleDefinitionsRestClient { + private static readonly string[] AuthorizationScopes = new string[] { "https://vault.azure.net/.default" }; + private readonly TokenCredential _tokenCredential; private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; private readonly string _apiVersion; /// The ClientDiagnostics is used to provide tracing support for the client library. internal ClientDiagnostics ClientDiagnostics { get; } + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of RoleDefinitionsRestClient for mocking. + protected RoleDefinitionsRestClient() + { + } + /// Initializes a new instance of RoleDefinitionsRestClient. - /// 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 RoleDefinitionsRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string apiVersion = "7.5") + /// The to use. + /// A credential used to authenticate to an Azure Service. + /// or is null. + public RoleDefinitionsRestClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new AzureSecurityKeyVaultAdministrationClientOptions()) { - ClientDiagnostics = clientDiagnostics ?? throw new ArgumentNullException(nameof(clientDiagnostics)); - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _apiVersion = apiVersion ?? throw new ArgumentNullException(nameof(apiVersion)); } - internal HttpMessage CreateDeleteRequest(string vaultBaseUrl, string scope, string roleDefinitionName) + /// Initializes a new instance of RoleDefinitionsRestClient. + /// The to use. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public RoleDefinitionsRestClient(Uri endpoint, TokenCredential credential, AzureSecurityKeyVaultAdministrationClientOptions options) { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/roleDefinitions/", false); - uri.AppendPath(roleDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new AzureSecurityKeyVaultAdministrationClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; } /// Deletes a custom role definition. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role definition to delete. Managed HSM only supports '/'. /// The name (GUID) of the role definition to delete. /// The cancellation token to use. - /// , or is null. - public async Task DeleteAsync(string vaultBaseUrl, string scope, string roleDefinitionName, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> DeleteAsync(string scope, string roleDefinitionName, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } - if (roleDefinitionName == null) - { - throw new ArgumentNullException(nameof(roleDefinitionName)); - } + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleDefinitionName, nameof(roleDefinitionName)); - using var message = CreateDeleteRequest(vaultBaseUrl, scope, roleDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 404: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await DeleteAsync(scope, roleDefinitionName, context).ConfigureAwait(false); + return Response.FromValue(KeyVaultRoleDefinition.FromResponse(response), response); } /// Deletes a custom role definition. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role definition to delete. Managed HSM only supports '/'. /// The name (GUID) of the role definition to delete. /// The cancellation token to use. - /// , or is null. - public Response Delete(string vaultBaseUrl, string scope, string roleDefinitionName, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response Delete(string scope, string roleDefinitionName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleDefinitionName, nameof(roleDefinitionName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Delete(scope, roleDefinitionName, context); + return Response.FromValue(KeyVaultRoleDefinition.FromResponse(response), response); + } + + /// + /// [Protocol Method] Deletes a custom role definition. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role definition to delete. Managed HSM only supports '/'. + /// The name (GUID) of the role definition to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeleteAsync(string scope, string roleDefinitionName, RequestContext context) { - if (vaultBaseUrl == null) + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleDefinitionName, nameof(roleDefinitionName)); + + using var scope0 = ClientDiagnostics.CreateScope("RoleDefinitionsRestClient.Delete"); + scope0.Start(); + try { - throw new ArgumentNullException(nameof(vaultBaseUrl)); + using HttpMessage message = CreateDeleteRequest(scope, roleDefinitionName, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } - if (scope == null) + catch (Exception e) { - throw new ArgumentNullException(nameof(scope)); + scope0.Failed(e); + throw; } - if (roleDefinitionName == null) + } + + /// + /// [Protocol Method] Deletes a custom role definition. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role definition to delete. Managed HSM only supports '/'. + /// The name (GUID) of the role definition to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response Delete(string scope, string roleDefinitionName, RequestContext context) + { + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleDefinitionName, nameof(roleDefinitionName)); + + using var scope0 = ClientDiagnostics.CreateScope("RoleDefinitionsRestClient.Delete"); + scope0.Start(); + try { - throw new ArgumentNullException(nameof(roleDefinitionName)); + using HttpMessage message = CreateDeleteRequest(scope, roleDefinitionName, context); + return _pipeline.ProcessMessage(message, context); } - - using var message = CreateDeleteRequest(vaultBaseUrl, scope, roleDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) + catch (Exception e) { - case 200: - case 404: - return message.Response; - default: - throw new RequestFailedException(message.Response); + scope0.Failed(e); + throw; } } - internal HttpMessage CreateCreateOrUpdateRequest(string vaultBaseUrl, string scope, string roleDefinitionName, RoleDefinitionCreateParameters parameters) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/roleDefinitions/", false); - uri.AppendPath(roleDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(parameters); - request.Content = content; - return message; - } - /// Creates or updates a custom role definition. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role definition to create or update. Managed HSM only supports '/'. /// The name of the role definition to create or update. It can be any valid GUID. /// Parameters for the role definition. /// The cancellation token to use. - /// , , or is null. - public async Task> CreateOrUpdateAsync(string vaultBaseUrl, string scope, string roleDefinitionName, RoleDefinitionCreateParameters parameters, CancellationToken cancellationToken = default) + /// , or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> CreateOrUpdateAsync(string scope, string roleDefinitionName, RoleDefinitionCreateParameters parameters, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } - if (roleDefinitionName == null) - { - throw new ArgumentNullException(nameof(roleDefinitionName)); - } - if (parameters == null) - { - throw new ArgumentNullException(nameof(parameters)); - } + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleDefinitionName, nameof(roleDefinitionName)); + Argument.AssertNotNull(parameters, nameof(parameters)); - using var message = CreateCreateOrUpdateRequest(vaultBaseUrl, scope, roleDefinitionName, parameters); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 201: - { - KeyVaultRoleDefinition value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = KeyVaultRoleDefinition.DeserializeKeyVaultRoleDefinition(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + using RequestContent content = parameters.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateOrUpdateAsync(scope, roleDefinitionName, content, context).ConfigureAwait(false); + return Response.FromValue(KeyVaultRoleDefinition.FromResponse(response), response); } /// Creates or updates a custom role definition. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role definition to create or update. Managed HSM only supports '/'. /// The name of the role definition to create or update. It can be any valid GUID. /// Parameters for the role definition. /// The cancellation token to use. - /// , , or is null. - public Response CreateOrUpdate(string vaultBaseUrl, string scope, string roleDefinitionName, RoleDefinitionCreateParameters parameters, CancellationToken cancellationToken = default) + /// , or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response CreateOrUpdate(string scope, string roleDefinitionName, RoleDefinitionCreateParameters parameters, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleDefinitionName, nameof(roleDefinitionName)); + Argument.AssertNotNull(parameters, nameof(parameters)); + + using RequestContent content = parameters.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateOrUpdate(scope, roleDefinitionName, content, context); + return Response.FromValue(KeyVaultRoleDefinition.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates or updates a custom role definition. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role definition to create or update. Managed HSM only supports '/'. + /// The name of the role definition to create or update. It can be any valid GUID. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task CreateOrUpdateAsync(string scope, string roleDefinitionName, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleDefinitionName, nameof(roleDefinitionName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope0 = ClientDiagnostics.CreateScope("RoleDefinitionsRestClient.CreateOrUpdate"); + scope0.Start(); + try { - throw new ArgumentNullException(nameof(scope)); + using HttpMessage message = CreateCreateOrUpdateRequest(scope, roleDefinitionName, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } - if (roleDefinitionName == null) + catch (Exception e) { - throw new ArgumentNullException(nameof(roleDefinitionName)); + scope0.Failed(e); + throw; } - if (parameters == null) + } + + /// + /// [Protocol Method] Creates or updates a custom role definition. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role definition to create or update. Managed HSM only supports '/'. + /// The name of the role definition to create or update. It can be any valid GUID. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response CreateOrUpdate(string scope, string roleDefinitionName, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleDefinitionName, nameof(roleDefinitionName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope0 = ClientDiagnostics.CreateScope("RoleDefinitionsRestClient.CreateOrUpdate"); + scope0.Start(); + try { - throw new ArgumentNullException(nameof(parameters)); + using HttpMessage message = CreateCreateOrUpdateRequest(scope, roleDefinitionName, content, context); + return _pipeline.ProcessMessage(message, context); } - - using var message = CreateCreateOrUpdateRequest(vaultBaseUrl, scope, roleDefinitionName, parameters); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) + catch (Exception e) { - case 201: - { - KeyVaultRoleDefinition value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = KeyVaultRoleDefinition.DeserializeKeyVaultRoleDefinition(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); + scope0.Failed(e); + throw; } } - internal HttpMessage CreateGetRequest(string vaultBaseUrl, string scope, string roleDefinitionName) + /// Get the specified role definition. + /// The scope of the role definition to get. Managed HSM only supports '/'. + /// The name of the role definition to get. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> GetRoleDefinitionsRestClientAsync(string scope, string roleDefinitionName, CancellationToken cancellationToken = default) { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/roleDefinitions/", false); - uri.AppendPath(roleDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleDefinitionName, nameof(roleDefinitionName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetRoleDefinitionsRestClientAsync(scope, roleDefinitionName, context).ConfigureAwait(false); + return Response.FromValue(KeyVaultRoleDefinition.FromResponse(response), response); } /// Get the specified role definition. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role definition to get. Managed HSM only supports '/'. /// The name of the role definition to get. /// The cancellation token to use. - /// , or is null. - public async Task> GetAsync(string vaultBaseUrl, string scope, string roleDefinitionName, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response GetRoleDefinitionsRestClient(string scope, string roleDefinitionName, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } - if (roleDefinitionName == null) - { - throw new ArgumentNullException(nameof(roleDefinitionName)); - } + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleDefinitionName, nameof(roleDefinitionName)); - using var message = CreateGetRequest(vaultBaseUrl, scope, roleDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - KeyVaultRoleDefinition value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = KeyVaultRoleDefinition.DeserializeKeyVaultRoleDefinition(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetRoleDefinitionsRestClient(scope, roleDefinitionName, context); + return Response.FromValue(KeyVaultRoleDefinition.FromResponse(response), response); } - /// Get the specified role definition. - /// The vault name, for example https://myvault.vault.azure.net. + /// + /// [Protocol Method] Get the specified role definition. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// /// The scope of the role definition to get. Managed HSM only supports '/'. /// The name of the role definition to get. - /// The cancellation token to use. - /// , or is null. - public Response Get(string vaultBaseUrl, string scope, string roleDefinitionName, CancellationToken cancellationToken = default) + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetRoleDefinitionsRestClientAsync(string scope, string roleDefinitionName, RequestContext context) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } - if (roleDefinitionName == null) + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleDefinitionName, nameof(roleDefinitionName)); + + using var scope0 = ClientDiagnostics.CreateScope("RoleDefinitionsRestClient.GetRoleDefinitionsRestClient"); + scope0.Start(); + try { - throw new ArgumentNullException(nameof(roleDefinitionName)); + using HttpMessage message = CreateGetRoleDefinitionsRestClientRequest(scope, roleDefinitionName, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } - - using var message = CreateGetRequest(vaultBaseUrl, scope, roleDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) + catch (Exception e) { - case 200: - { - KeyVaultRoleDefinition value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = KeyVaultRoleDefinition.DeserializeKeyVaultRoleDefinition(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); + scope0.Failed(e); + throw; } } - internal HttpMessage CreateListRequest(string vaultBaseUrl, string scope, string filter) + /// + /// [Protocol Method] Get the specified role definition. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role definition to get. Managed HSM only supports '/'. + /// The name of the role definition to get. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetRoleDefinitionsRestClient(string scope, string roleDefinitionName, RequestContext context) { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/roleDefinitions", false); - if (filter != null) + Argument.AssertNotNull(scope, nameof(scope)); + Argument.AssertNotNullOrEmpty(roleDefinitionName, nameof(roleDefinitionName)); + + using var scope0 = ClientDiagnostics.CreateScope("RoleDefinitionsRestClient.GetRoleDefinitionsRestClient"); + scope0.Start(); + try { - uri.AppendQuery("$filter", filter, true); + using HttpMessage message = CreateGetRoleDefinitionsRestClientRequest(scope, roleDefinitionName, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope0.Failed(e); + throw; } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; } /// Get all role definitions that are applicable at scope and above. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role definition. /// The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as well. /// The cancellation token to use. - /// or is null. - public async Task> ListAsync(string vaultBaseUrl, string scope, string filter = null, CancellationToken cancellationToken = default) + /// is null. + /// + public virtual AsyncPageable GetRoleDefinitionsRestClientsAsync(string scope, string filter = null, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } + Argument.AssertNotNull(scope, nameof(scope)); - using var message = CreateListRequest(vaultBaseUrl, scope, filter); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - RoleDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = RoleDefinitionListResult.DeserializeRoleDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetRoleDefinitionsRestClientsRequest(scope, filter, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetRoleDefinitionsRestClientsNextPageRequest(nextLink, scope, filter, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => KeyVaultRoleDefinition.DeserializeKeyVaultRoleDefinition(e), ClientDiagnostics, _pipeline, "RoleDefinitionsRestClient.GetRoleDefinitionsRestClients", "value", "nextLink", context); } /// Get all role definitions that are applicable at scope and above. - /// The vault name, for example https://myvault.vault.azure.net. /// The scope of the role definition. /// The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as well. /// The cancellation token to use. - /// or is null. - public Response List(string vaultBaseUrl, string scope, string filter = null, CancellationToken cancellationToken = default) + /// is null. + /// + public virtual Pageable GetRoleDefinitionsRestClients(string scope, string filter = null, CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } + Argument.AssertNotNull(scope, nameof(scope)); - using var message = CreateListRequest(vaultBaseUrl, scope, filter); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - RoleDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = RoleDefinitionListResult.DeserializeRoleDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetRoleDefinitionsRestClientsRequest(scope, filter, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetRoleDefinitionsRestClientsNextPageRequest(nextLink, scope, filter, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => KeyVaultRoleDefinition.DeserializeKeyVaultRoleDefinition(e), ClientDiagnostics, _pipeline, "RoleDefinitionsRestClient.GetRoleDefinitionsRestClients", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Get all role definitions that are applicable at scope and above. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role definition. + /// The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as well. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetRoleDefinitionsRestClientsAsync(string scope, string filter, RequestContext context) + { + Argument.AssertNotNull(scope, nameof(scope)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetRoleDefinitionsRestClientsRequest(scope, filter, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetRoleDefinitionsRestClientsNextPageRequest(nextLink, scope, filter, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "RoleDefinitionsRestClient.GetRoleDefinitionsRestClients", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Get all role definitions that are applicable at scope and above. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The scope of the role definition. + /// The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as well. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetRoleDefinitionsRestClients(string scope, string filter, RequestContext context) + { + Argument.AssertNotNull(scope, nameof(scope)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetRoleDefinitionsRestClientsRequest(scope, filter, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetRoleDefinitionsRestClientsNextPageRequest(nextLink, scope, filter, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "RoleDefinitionsRestClient.GetRoleDefinitionsRestClients", "value", "nextLink", context); + } + + internal HttpMessage CreateDeleteRequest(string scope, string roleDefinitionName, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/", false); + uri.AppendPath(scope, false); + uri.AppendPath("/providers/Microsoft.Authorization/roleDefinitions/", false); + uri.AppendPath(roleDefinitionName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateOrUpdateRequest(string scope, string roleDefinitionName, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier201); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/", false); + uri.AppendPath(scope, false); + uri.AppendPath("/providers/Microsoft.Authorization/roleDefinitions/", false); + uri.AppendPath(roleDefinitionName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; } - internal HttpMessage CreateListNextPageRequest(string nextLink, string vaultBaseUrl, string scope, string filter) + internal HttpMessage CreateGetRoleDefinitionsRestClientRequest(string scope, string roleDefinitionName, RequestContext context) { - var message = _pipeline.CreateMessage(); + var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendRawNextLink(nextLink, false); + uri.Reset(_endpoint); + uri.AppendPath("/", false); + uri.AppendPath(scope, false); + uri.AppendPath("/providers/Microsoft.Authorization/roleDefinitions/", false); + uri.AppendPath(roleDefinitionName, true); + uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; } - /// Get all role definitions that are applicable at scope and above. - /// The URL to the next page of results. - /// The vault name, for example https://myvault.vault.azure.net. - /// The scope of the role definition. - /// The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as well. - /// The cancellation token to use. - /// , or is null. - public async Task> ListNextPageAsync(string nextLink, string vaultBaseUrl, string scope, string filter = null, CancellationToken cancellationToken = default) + internal HttpMessage CreateGetRoleDefinitionsRestClientsRequest(string scope, string filter, RequestContext context) { - if (nextLink == null) - { - throw new ArgumentNullException(nameof(nextLink)); - } - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/", false); + uri.AppendPath(scope, false); + uri.AppendPath("/providers/Microsoft.Authorization/roleDefinitions", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (filter != null) { - throw new ArgumentNullException(nameof(scope)); + uri.AppendQuery("$filter", filter, true); } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } - using var message = CreateListNextPageRequest(nextLink, vaultBaseUrl, scope, filter); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - RoleDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = RoleDefinitionListResult.DeserializeRoleDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + internal HttpMessage CreateGetRoleDefinitionsRestClientsNextPageRequest(string nextLink, string scope, string filter, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; } - /// Get all role definitions that are applicable at scope and above. - /// The URL to the next page of results. - /// The vault name, for example https://myvault.vault.azure.net. - /// The scope of the role definition. - /// The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as well. - /// The cancellation token to use. - /// , or is null. - public Response ListNextPage(string nextLink, string vaultBaseUrl, string scope, string filter = null, CancellationToken cancellationToken = default) + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) { - if (nextLink == null) + if (!cancellationToken.CanBeCanceled) { - throw new ArgumentNullException(nameof(nextLink)); - } - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); + return DefaultRequestContext; } - using var message = CreateListNextPageRequest(nextLink, vaultBaseUrl, scope, filter); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - RoleDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = RoleDefinitionListResult.DeserializeRoleDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + return new RequestContext() { CancellationToken = cancellationToken }; } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + private static ResponseClassifier _responseClassifier201; + private static ResponseClassifier ResponseClassifier201 => _responseClassifier201 ??= new StatusCodeClassifier(stackalloc ushort[] { 201 }); } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/SecurityKeyVaultAdministrationClientBuilderExtensions.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/SecurityKeyVaultAdministrationClientBuilderExtensions.cs new file mode 100644 index 000000000000..02d7c8554f3c --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/SecurityKeyVaultAdministrationClientBuilderExtensions.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core.Extensions; +using Azure.Security.KeyVault.Administration; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add , , to client builder. + public static partial class SecurityKeyVaultAdministrationClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// The to use. + public static IAzureClientBuilder AddRoleAssignmentsRestClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new RoleAssignmentsRestClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The to use. + public static IAzureClientBuilder AddRoleDefinitionsRestClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new RoleDefinitionsRestClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The to use. + public static IAzureClientBuilder AddSettingsRestClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new SettingsRestClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddRoleAssignmentsRestClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddRoleDefinitionsRestClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddSettingsRestClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/SettingsRestClient.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/SettingsRestClient.cs index 7a898bfb4b4b..b848e9a9e6b2 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/SettingsRestClient.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/Generated/SettingsRestClient.cs @@ -6,7 +6,6 @@ #nullable disable using System; -using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure.Core; @@ -15,271 +14,389 @@ namespace Azure.Security.KeyVault.Administration { - internal partial class SettingsRestClient + // Data plane generated client. + /// The SettingsRest service client. + public partial class SettingsRestClient { + private static readonly string[] AuthorizationScopes = new string[] { "https://vault.azure.net/.default" }; + private readonly TokenCredential _tokenCredential; private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; private readonly string _apiVersion; /// The ClientDiagnostics is used to provide tracing support for the client library. internal ClientDiagnostics ClientDiagnostics { get; } + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of SettingsRestClient for mocking. + protected SettingsRestClient() + { + } + /// Initializes a new instance of SettingsRestClient. - /// 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 SettingsRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string apiVersion = "7.5") + /// The to use. + /// A credential used to authenticate to an Azure Service. + /// or is null. + public SettingsRestClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new AzureSecurityKeyVaultAdministrationClientOptions()) { - ClientDiagnostics = clientDiagnostics ?? throw new ArgumentNullException(nameof(clientDiagnostics)); - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _apiVersion = apiVersion ?? throw new ArgumentNullException(nameof(apiVersion)); } - internal HttpMessage CreateUpdateSettingRequest(string vaultBaseUrl, string settingName, string value) + /// Initializes a new instance of SettingsRestClient. + /// The to use. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public SettingsRestClient(Uri endpoint, TokenCredential credential, AzureSecurityKeyVaultAdministrationClientOptions options) { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Patch; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/settings/", false); - uri.AppendPath(settingName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var model = new UpdateSettingRequest(value); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(model); - request.Content = content; - return message; + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new AzureSecurityKeyVaultAdministrationClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; } - /// Updates key vault account setting, stores it, then returns the setting name and value to the client. - /// The vault name, for example https://myvault.vault.azure.net. + /// + /// [Protocol Method] Updates key vault account setting, stores it, then returns the setting name and value to the client. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// /// The name of the account setting. Must be a valid settings option. - /// The value of the pool setting. - /// The cancellation token to use. - /// , or is null. - /// Description of the pool setting to be updated. - public async Task> UpdateSettingAsync(string vaultBaseUrl, string settingName, string value, CancellationToken cancellationToken = default) + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task UpdateSettingAsync(string settingName, RequestContent content, RequestContext context = null) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (settingName == null) - { - throw new ArgumentNullException(nameof(settingName)); - } - if (value == null) + Argument.AssertNotNullOrEmpty(settingName, nameof(settingName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("SettingsRestClient.UpdateSetting"); + scope.Start(); + try { - throw new ArgumentNullException(nameof(value)); + using HttpMessage message = CreateUpdateSettingRequest(settingName, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } - - using var message = CreateUpdateSettingRequest(vaultBaseUrl, settingName, value); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) + catch (Exception e) { - case 200: - { - KeyVaultSetting value0 = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value0 = KeyVaultSetting.DeserializeKeyVaultSetting(document.RootElement); - return Response.FromValue(value0, message.Response); - } - default: - throw new RequestFailedException(message.Response); + scope.Failed(e); + throw; } } - /// Updates key vault account setting, stores it, then returns the setting name and value to the client. - /// The vault name, for example https://myvault.vault.azure.net. + /// + /// [Protocol Method] Updates key vault account setting, stores it, then returns the setting name and value to the client. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// /// The name of the account setting. Must be a valid settings option. - /// The value of the pool setting. - /// The cancellation token to use. - /// , or is null. - /// Description of the pool setting to be updated. - public Response UpdateSetting(string vaultBaseUrl, string settingName, string value, CancellationToken cancellationToken = default) + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response UpdateSetting(string settingName, RequestContent content, RequestContext context = null) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } - if (settingName == null) - { - throw new ArgumentNullException(nameof(settingName)); - } - if (value == null) + Argument.AssertNotNullOrEmpty(settingName, nameof(settingName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("SettingsRestClient.UpdateSetting"); + scope.Start(); + try { - throw new ArgumentNullException(nameof(value)); + using HttpMessage message = CreateUpdateSettingRequest(settingName, content, context); + return _pipeline.ProcessMessage(message, context); } - - using var message = CreateUpdateSettingRequest(vaultBaseUrl, settingName, value); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) + catch (Exception e) { - case 200: - { - KeyVaultSetting value0 = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value0 = KeyVaultSetting.DeserializeKeyVaultSetting(document.RootElement); - return Response.FromValue(value0, message.Response); - } - default: - throw new RequestFailedException(message.Response); + scope.Failed(e); + throw; } } - internal HttpMessage CreateGetSettingRequest(string vaultBaseUrl, string settingName) + /// Get specified account setting object. + /// The name of the account setting. Must be a valid settings option. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Retrieves the setting object of a specified setting name. + /// + public virtual async Task> GetSettingAsync(string settingName, CancellationToken cancellationToken = default) { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/settings/", false); - uri.AppendPath(settingName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; + Argument.AssertNotNullOrEmpty(settingName, nameof(settingName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetSettingAsync(settingName, context).ConfigureAwait(false); + return Response.FromValue(Models.KeyVaultSetting.FromResponse(response), response); } /// Get specified account setting object. - /// The vault name, for example https://myvault.vault.azure.net. /// The name of the account setting. Must be a valid settings option. /// The cancellation token to use. - /// or is null. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Retrieves the setting object of a specified setting name. - public async Task> GetSettingAsync(string vaultBaseUrl, string settingName, CancellationToken cancellationToken = default) + /// + public virtual Response GetSetting(string settingName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(settingName, nameof(settingName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetSetting(settingName, context); + return Response.FromValue(Models.KeyVaultSetting.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get specified account setting object. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The name of the account setting. Must be a valid settings option. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetSettingAsync(string settingName, RequestContext context) { - if (vaultBaseUrl == null) + Argument.AssertNotNullOrEmpty(settingName, nameof(settingName)); + + using var scope = ClientDiagnostics.CreateScope("SettingsRestClient.GetSetting"); + scope.Start(); + try { - throw new ArgumentNullException(nameof(vaultBaseUrl)); + using HttpMessage message = CreateGetSettingRequest(settingName, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } - if (settingName == null) + catch (Exception e) { - throw new ArgumentNullException(nameof(settingName)); + scope.Failed(e); + throw; } + } - using var message = CreateGetSettingRequest(vaultBaseUrl, settingName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) + /// + /// [Protocol Method] Get specified account setting object. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The name of the account setting. Must be a valid settings option. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetSetting(string settingName, RequestContext context) + { + Argument.AssertNotNullOrEmpty(settingName, nameof(settingName)); + + using var scope = ClientDiagnostics.CreateScope("SettingsRestClient.GetSetting"); + scope.Start(); + try + { + using HttpMessage message = CreateGetSettingRequest(settingName, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) { - case 200: - { - KeyVaultSetting value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = KeyVaultSetting.DeserializeKeyVaultSetting(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); + scope.Failed(e); + throw; } } - /// Get specified account setting object. - /// The vault name, for example https://myvault.vault.azure.net. - /// The name of the account setting. Must be a valid settings option. + /// List account settings. /// The cancellation token to use. - /// or is null. - /// Retrieves the setting object of a specified setting name. - public Response GetSetting(string vaultBaseUrl, string settingName, CancellationToken cancellationToken = default) + /// Retrieves a list of all the available account settings that can be configured. + /// + public virtual async Task> GetSettingsAsync(CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetSettingsAsync(context).ConfigureAwait(false); + return Response.FromValue(Models.GetSettingsResult.FromResponse(response), response); + } + + /// List account settings. + /// The cancellation token to use. + /// Retrieves a list of all the available account settings that can be configured. + /// + public virtual Response GetSettings(CancellationToken cancellationToken = default) + { + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetSettings(context); + return Response.FromValue(Models.GetSettingsResult.FromResponse(response), response); + } + + /// + /// [Protocol Method] List account settings. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetSettingsAsync(RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("SettingsRestClient.GetSettings"); + scope.Start(); + try { - throw new ArgumentNullException(nameof(vaultBaseUrl)); + using HttpMessage message = CreateGetSettingsRequest(context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } - if (settingName == null) + catch (Exception e) { - throw new ArgumentNullException(nameof(settingName)); + scope.Failed(e); + throw; } + } - using var message = CreateGetSettingRequest(vaultBaseUrl, settingName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) + /// + /// [Protocol Method] List account settings. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetSettings(RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("SettingsRestClient.GetSettings"); + scope.Start(); + try + { + using HttpMessage message = CreateGetSettingsRequest(context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) { - case 200: - { - KeyVaultSetting value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = KeyVaultSetting.DeserializeKeyVaultSetting(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); + scope.Failed(e); + throw; } } - internal HttpMessage CreateGetSettingsRequest(string vaultBaseUrl) + internal HttpMessage CreateUpdateSettingRequest(string settingName, RequestContent content, RequestContext context) { - var message = _pipeline.CreateMessage(); + var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; - request.Method = RequestMethod.Get; + request.Method = RequestMethod.Patch; var uri = new RawRequestUriBuilder(); - uri.AppendRaw(vaultBaseUrl, false); - uri.AppendPath("/settings", false); + uri.Reset(_endpoint); + uri.AppendPath("/settings/", false); + uri.AppendPath(settingName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; return message; } - /// List account settings. - /// The vault name, for example https://myvault.vault.azure.net. - /// The cancellation token to use. - /// is null. - /// Retrieves a list of all the available account settings that can be configured. - public async Task> GetSettingsAsync(string vaultBaseUrl, CancellationToken cancellationToken = default) + internal HttpMessage CreateGetSettingRequest(string settingName, RequestContext context) { - if (vaultBaseUrl == null) - { - throw new ArgumentNullException(nameof(vaultBaseUrl)); - } + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/settings/", false); + uri.AppendPath(settingName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } - using var message = CreateGetSettingsRequest(vaultBaseUrl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - GetSettingsResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = GetSettingsResult.DeserializeGetSettingsResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + internal HttpMessage CreateGetSettingsRequest(RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/settings", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; } - /// List account settings. - /// The vault name, for example https://myvault.vault.azure.net. - /// The cancellation token to use. - /// is null. - /// Retrieves a list of all the available account settings that can be configured. - public Response GetSettings(string vaultBaseUrl, CancellationToken cancellationToken = default) + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) { - if (vaultBaseUrl == null) + if (!cancellationToken.CanBeCanceled) { - throw new ArgumentNullException(nameof(vaultBaseUrl)); + return DefaultRequestContext; } - using var message = CreateGetSettingsRequest(vaultBaseUrl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - GetSettingsResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = GetSettingsResult.DeserializeGetSettingsResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } + return new RequestContext() { CancellationToken = cancellationToken }; } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/autorest.md b/sdk/keyvault/Azure.Security.KeyVault.Administration/src/autorest.md deleted file mode 100644 index 4135789b16a2..000000000000 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/src/autorest.md +++ /dev/null @@ -1,90 +0,0 @@ -# Azure.Security.KeyVault.Administration - -## AutoRest Configuration - -> See https://aka.ms/autorest - -Run `dotnet build /t:GenerateCode` in src directory to re-generate. - -``` yaml -title: Azure.Security.KeyVault.Administration -input-file: -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/7452e1cc7db72fbc6cd9539b390d8b8e5c2a1864/specification/keyvault/data-plane/Microsoft.KeyVault/stable/7.5/rbac.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/7452e1cc7db72fbc6cd9539b390d8b8e5c2a1864/specification/keyvault/data-plane/Microsoft.KeyVault/stable/7.5/backuprestore.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/7452e1cc7db72fbc6cd9539b390d8b8e5c2a1864/specification/keyvault/data-plane/Microsoft.KeyVault/stable/7.5/settings.json -namespace: Azure.Security.KeyVault.Administration -generation1-convenience-client: true -include-csproj: disable -``` - -## Swagger customizations - -These changes should eventually be included in the swagger or at least centralized in Azure/azure-rest-api-specs. - -### Ignore 404s for DELETE operations - -Treat HTTP 404 responses for DELETE operations for RBAC as non-errors. - -``` yaml -directive: -- where-operation: RoleAssignments_Delete - transform: > - $.responses["404"] = { - "description": "The resource to delete does not exist.", - "x-ms-error-response": false - }; - -- where-operation: RoleDefinitions_Delete - transform: > - $.responses["404"] = { - "description": "The resource to delete does not exist.", - "x-ms-error-response": false - }; -``` - -### Return void for DELETE operations - -Do not parse response bodies unnecessarily. - -``` yaml -directive: -- where-operation: RoleAssignments_Delete - transform: > - delete $.responses["200"].schema; - -- where-operation: RoleDefinitions_Delete - transform: > - delete $.responses["200"].schema; -``` - -#### Specify client name for settings operations - -``` yaml -directive: -- rename-operation: - from: UpdateSetting - to: Settings_UpdateSetting -- rename-operation: - from: GetSetting - to: Settings_GetSetting -- rename-operation: - from: GetSettings - to: Settings_GetSettings -``` - -## C# customizations - -``` yaml -directive: -# [CodeGenMember("Type")] yields errors, so we have to rename via autorest transform. -- where: $.definitions.Setting.properties.type - from: swagger-document - transform: > - $["x-ms-client-name"] = "SettingType"; - -# [CodeGenSuppress("Value")] yields errors, so we have to rename via autorest transforms. -- where: $.definitions.Setting.properties.value - from: swagger-document - transform: > - $["x-ms-client-name"] = "content"; -``` diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/tests/Generated/Samples/Samples_BackupRestoreRestClient.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/tests/Generated/Samples/Samples_BackupRestoreRestClient.cs new file mode 100644 index 000000000000..0609b2e21074 --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/tests/Generated/Samples/Samples_BackupRestoreRestClient.cs @@ -0,0 +1,514 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using Azure.Security.KeyVault.Administration.Models; +using NUnit.Framework; + +namespace Azure.Security.KeyVault.Administration.Samples +{ + public partial class Samples_BackupRestoreRestClient + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_FullBackupStatus_GetTheStatusOfAFullBackupOperation() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + Response response = client.FullBackupStatus("45aacd568ab049a2803861e8dd3ae21f", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_FullBackupStatus_GetTheStatusOfAFullBackupOperation_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + Response response = await client.FullBackupStatusAsync("45aacd568ab049a2803861e8dd3ae21f", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_FullBackupStatus_GetTheStatusOfAFullBackupOperation_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + Response response = client.FullBackupStatus("45aacd568ab049a2803861e8dd3ae21f"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_FullBackupStatus_GetTheStatusOfAFullBackupOperation_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + Response response = await client.FullBackupStatusAsync("45aacd568ab049a2803861e8dd3ae21f"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_RestoreStatus_GetTheStatusOfRestoreOperation() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + Response response = client.RestoreStatus("45aacd568ab049a2803861e8dd3ae21f", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_RestoreStatus_GetTheStatusOfRestoreOperation_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + Response response = await client.RestoreStatusAsync("45aacd568ab049a2803861e8dd3ae21f", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_RestoreStatus_GetTheStatusOfRestoreOperation_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + Response response = client.RestoreStatus("45aacd568ab049a2803861e8dd3ae21f"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_RestoreStatus_GetTheStatusOfRestoreOperation_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + Response response = await client.RestoreStatusAsync("45aacd568ab049a2803861e8dd3ae21f"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_FullBackup_CreateAFullBackup() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }); + Operation operation = client.FullBackup(WaitUntil.Completed, content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_FullBackup_CreateAFullBackup_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }); + Operation operation = await client.FullBackupAsync(WaitUntil.Completed, content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_FullBackup_CreateAFullBackup_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + SASTokenParameter azureStorageBlobContainerUri = new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") + { + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }; + Operation operation = client.FullBackup(WaitUntil.Completed, azureStorageBlobContainerUri); + FullBackupDetailsInternal responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_FullBackup_CreateAFullBackup_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + SASTokenParameter azureStorageBlobContainerUri = new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") + { + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }; + Operation operation = await client.FullBackupAsync(WaitUntil.Completed, azureStorageBlobContainerUri); + FullBackupDetailsInternal responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_PreFullBackup_CheckWhetherTheCustomerCanPerformAFullBackupOperation() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }); + Operation operation = client.PreFullBackup(WaitUntil.Completed, content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_PreFullBackup_CheckWhetherTheCustomerCanPerformAFullBackupOperation_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }); + Operation operation = await client.PreFullBackupAsync(WaitUntil.Completed, content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_PreFullBackup_CheckWhetherTheCustomerCanPerformAFullBackupOperation_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + PreBackupOperationParameters preBackupOperationParameters = new PreBackupOperationParameters + { + StorageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }; + Operation operation = client.PreFullBackup(WaitUntil.Completed, preBackupOperationParameters); + FullBackupDetailsInternal responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_PreFullBackup_CheckWhetherTheCustomerCanPerformAFullBackupOperation_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + PreBackupOperationParameters preBackupOperationParameters = new PreBackupOperationParameters + { + StorageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }; + Operation operation = await client.PreFullBackupAsync(WaitUntil.Completed, preBackupOperationParameters); + FullBackupDetailsInternal responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_PreFullRestoreOperation_CheckWhetherTheCustomerCanPerformAFullRestoreOperation() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + sasTokenParameters = new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + folderToRestore = "mhsm-mypool-20200303062926785", + }); + Operation operation = client.PreFullRestoreOperation(WaitUntil.Completed, content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_PreFullRestoreOperation_CheckWhetherTheCustomerCanPerformAFullRestoreOperation_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + sasTokenParameters = new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + folderToRestore = "mhsm-mypool-20200303062926785", + }); + Operation operation = await client.PreFullRestoreOperationAsync(WaitUntil.Completed, content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_PreFullRestoreOperation_CheckWhetherTheCustomerCanPerformAFullRestoreOperation_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + PreRestoreOperationParameters preRestoreOperationParameters = new PreRestoreOperationParameters + { + SasTokenParameters = new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") + { + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + FolderToRestore = "mhsm-mypool-20200303062926785", + }; + Operation operation = client.PreFullRestoreOperation(WaitUntil.Completed, preRestoreOperationParameters); + RestoreDetailsInternal responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_PreFullRestoreOperation_CheckWhetherTheCustomerCanPerformAFullRestoreOperation_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + PreRestoreOperationParameters preRestoreOperationParameters = new PreRestoreOperationParameters + { + SasTokenParameters = new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") + { + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + FolderToRestore = "mhsm-mypool-20200303062926785", + }; + Operation operation = await client.PreFullRestoreOperationAsync(WaitUntil.Completed, preRestoreOperationParameters); + RestoreDetailsInternal responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_FullRestoreOperation_RestoreAllKeyMaterialsFromAPreviouslyStoredAzureBlobStorageBackup() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + sasTokenParameters = new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + folderToRestore = "mhsm-mypool-20200303062926785", + }); + Operation operation = client.FullRestoreOperation(WaitUntil.Completed, content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_FullRestoreOperation_RestoreAllKeyMaterialsFromAPreviouslyStoredAzureBlobStorageBackup_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + sasTokenParameters = new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + folderToRestore = "mhsm-mypool-20200303062926785", + }); + Operation operation = await client.FullRestoreOperationAsync(WaitUntil.Completed, content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_FullRestoreOperation_RestoreAllKeyMaterialsFromAPreviouslyStoredAzureBlobStorageBackup_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + RestoreOperationParameters restoreBlobDetails = new RestoreOperationParameters(new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") + { + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, "mhsm-mypool-20200303062926785"); + Operation operation = client.FullRestoreOperation(WaitUntil.Completed, restoreBlobDetails); + RestoreDetailsInternal responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_FullRestoreOperation_RestoreAllKeyMaterialsFromAPreviouslyStoredAzureBlobStorageBackup_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + RestoreOperationParameters restoreBlobDetails = new RestoreOperationParameters(new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") + { + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, "mhsm-mypool-20200303062926785"); + Operation operation = await client.FullRestoreOperationAsync(WaitUntil.Completed, restoreBlobDetails); + RestoreDetailsInternal responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_SelectiveKeyRestoreOperation_RestoresAllKeyVersionsOfAGivenKey() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + sasTokenParameters = new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + folder = "mhsm-mypool-20200303062926785", + }); + Operation operation = client.SelectiveKeyRestoreOperation(WaitUntil.Completed, "hsm-mail-key", content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_SelectiveKeyRestoreOperation_RestoresAllKeyVersionsOfAGivenKey_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + sasTokenParameters = new + { + storageResourceUri = "https://myaccount.blob.core.windows.net/sascontainer/sasContainer", + token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, + folder = "mhsm-mypool-20200303062926785", + }); + Operation operation = await client.SelectiveKeyRestoreOperationAsync(WaitUntil.Completed, "hsm-mail-key", content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_BackupRestoreRestClient_SelectiveKeyRestoreOperation_RestoresAllKeyVersionsOfAGivenKey_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + SelectiveKeyRestoreOperationParameters restoreBlobDetails = new SelectiveKeyRestoreOperationParameters(new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") + { + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, "mhsm-mypool-20200303062926785"); + Operation operation = client.SelectiveKeyRestoreOperation(WaitUntil.Completed, "hsm-mail-key", restoreBlobDetails); + SelectiveKeyRestoreDetailsInternal responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_BackupRestoreRestClient_SelectiveKeyRestoreOperation_RestoresAllKeyVersionsOfAGivenKey_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + BackupRestoreRestClient client = new BackupRestoreRestClient(endpoint, credential); + + SelectiveKeyRestoreOperationParameters restoreBlobDetails = new SelectiveKeyRestoreOperationParameters(new SASTokenParameter("https://myaccount.blob.core.windows.net/sascontainer/sasContainer") + { + Token = "se=2018-02-01T00%3A00Z&spr=https&sv=2017-04-17&sr=b&sig=REDACTED", + }, "mhsm-mypool-20200303062926785"); + Operation operation = await client.SelectiveKeyRestoreOperationAsync(WaitUntil.Completed, "hsm-mail-key", restoreBlobDetails); + SelectiveKeyRestoreDetailsInternal responseData = operation.Value; + } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/tests/Generated/Samples/Samples_RoleAssignmentsRestClient.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/tests/Generated/Samples/Samples_RoleAssignmentsRestClient.cs new file mode 100644 index 000000000000..d5d75860ad4c --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/tests/Generated/Samples/Samples_RoleAssignmentsRestClient.cs @@ -0,0 +1,244 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using Azure.Security.KeyVault.Administration.Models; +using NUnit.Framework; + +namespace Azure.Security.KeyVault.Administration.Samples +{ + public partial class Samples_RoleAssignmentsRestClient + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleAssignmentsRestClient_Delete_DeleteARoleAssignment() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + Response response = client.Delete("keys", "roleAssignmentName", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleAssignmentsRestClient_Delete_DeleteARoleAssignment_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + Response response = await client.DeleteAsync("keys", "roleAssignmentName", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleAssignmentsRestClient_Delete_DeleteARoleAssignment_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + Response response = client.Delete("keys", "roleAssignmentName"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleAssignmentsRestClient_Delete_DeleteARoleAssignment_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + Response response = await client.DeleteAsync("keys", "roleAssignmentName"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleAssignmentsRestClient_Create_CreateARoleAssignment() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + properties = new + { + roleDefinitionId = "/keys/providers/Microsoft.Authorization/roleDefinitions/roleDefinitionId", + principalId = "principalId", + }, + }); + Response response = client.Create("keys", "roleAssignmentName", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleAssignmentsRestClient_Create_CreateARoleAssignment_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + properties = new + { + roleDefinitionId = "/keys/providers/Microsoft.Authorization/roleDefinitions/roleDefinitionId", + principalId = "principalId", + }, + }); + Response response = await client.CreateAsync("keys", "roleAssignmentName", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleAssignmentsRestClient_Create_CreateARoleAssignment_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + RoleAssignmentCreateParameters parameters = new RoleAssignmentCreateParameters(new KeyVaultRoleAssignmentPropertiesInternal("/keys/providers/Microsoft.Authorization/roleDefinitions/roleDefinitionId", "principalId")); + Response response = client.Create("keys", "roleAssignmentName", parameters); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleAssignmentsRestClient_Create_CreateARoleAssignment_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + RoleAssignmentCreateParameters parameters = new RoleAssignmentCreateParameters(new KeyVaultRoleAssignmentPropertiesInternal("/keys/providers/Microsoft.Authorization/roleDefinitions/roleDefinitionId", "principalId")); + Response response = await client.CreateAsync("keys", "roleAssignmentName", parameters); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleAssignmentsRestClient_GetRoleAssignmentsRestClient_GetTheSpecifiedRoleAssignment() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + Response response = client.GetRoleAssignmentsRestClient("keys", "roleAssignmentName", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleAssignmentsRestClient_GetRoleAssignmentsRestClient_GetTheSpecifiedRoleAssignment_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + Response response = await client.GetRoleAssignmentsRestClientAsync("keys", "roleAssignmentName", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleAssignmentsRestClient_GetRoleAssignmentsRestClient_GetTheSpecifiedRoleAssignment_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + Response response = client.GetRoleAssignmentsRestClient("keys", "roleAssignmentName"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleAssignmentsRestClient_GetRoleAssignmentsRestClient_GetTheSpecifiedRoleAssignment_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + Response response = await client.GetRoleAssignmentsRestClientAsync("keys", "roleAssignmentName"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleAssignmentsRestClient_GetForScopes_GetRoleAssignmentsForAScope() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + foreach (BinaryData item in client.GetForScopes("keys", null, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleAssignmentsRestClient_GetForScopes_GetRoleAssignmentsForAScope_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + await foreach (BinaryData item in client.GetForScopesAsync("keys", null, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleAssignmentsRestClient_GetForScopes_GetRoleAssignmentsForAScope_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + foreach (Models.KeyVaultRoleAssignment item in client.GetForScopes("keys")) + { + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleAssignmentsRestClient_GetForScopes_GetRoleAssignmentsForAScope_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleAssignmentsRestClient client = new RoleAssignmentsRestClient(endpoint, credential); + + await foreach (Models.KeyVaultRoleAssignment item in client.GetForScopesAsync("keys")) + { + } + } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/tests/Generated/Samples/Samples_RoleDefinitionsRestClient.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/tests/Generated/Samples/Samples_RoleDefinitionsRestClient.cs new file mode 100644 index 000000000000..c8b98d2be1ec --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/tests/Generated/Samples/Samples_RoleDefinitionsRestClient.cs @@ -0,0 +1,284 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using Azure.Security.KeyVault.Administration.Models; +using NUnit.Framework; + +namespace Azure.Security.KeyVault.Administration.Samples +{ + public partial class Samples_RoleDefinitionsRestClient + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleDefinitionsRestClient_Delete_DeleteACustomRoleDefinition() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + Response response = client.Delete("/", "00000000-0000-0000-0000-000000000000", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleDefinitionsRestClient_Delete_DeleteACustomRoleDefinition_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + Response response = await client.DeleteAsync("/", "00000000-0000-0000-0000-000000000000", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleDefinitionsRestClient_Delete_DeleteACustomRoleDefinition_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + Response response = client.Delete("/", "00000000-0000-0000-0000-000000000000"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleDefinitionsRestClient_Delete_DeleteACustomRoleDefinition_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + Response response = await client.DeleteAsync("/", "00000000-0000-0000-0000-000000000000"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleDefinitionsRestClient_CreateOrUpdate_CreateOrUpdateACustomRoleDefinition() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + properties = new + { + roleName = "My custom role", + type = "CustomRole", + description = "Role description", + permissions = new object[] + { +new +{ +dataActions = new object[] +{ +"Microsoft.KeyVault/managedHsm/keys/sign/action" +}, +} + }, + }, + }); + Response response = client.CreateOrUpdate("keys", "00000000-0000-0000-0000-000000000000", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleDefinitionsRestClient_CreateOrUpdate_CreateOrUpdateACustomRoleDefinition_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + properties = new + { + roleName = "My custom role", + type = "CustomRole", + description = "Role description", + permissions = new object[] + { +new +{ +dataActions = new object[] +{ +"Microsoft.KeyVault/managedHsm/keys/sign/action" +}, +} + }, + }, + }); + Response response = await client.CreateOrUpdateAsync("keys", "00000000-0000-0000-0000-000000000000", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleDefinitionsRestClient_CreateOrUpdate_CreateOrUpdateACustomRoleDefinition_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + RoleDefinitionCreateParameters parameters = new RoleDefinitionCreateParameters(new RoleDefinitionProperties + { + RoleName = "My custom role", + Description = "Role description", + RoleType = Models.KeyVaultRoleType.CustomRole, + Permissions = {new Models.KeyVaultPermission +{ +DataActions = {Models.KeyVaultDataAction.SignHsmKey}, +}}, + }); + Response response = client.CreateOrUpdate("keys", "00000000-0000-0000-0000-000000000000", parameters); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleDefinitionsRestClient_CreateOrUpdate_CreateOrUpdateACustomRoleDefinition_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + RoleDefinitionCreateParameters parameters = new RoleDefinitionCreateParameters(new RoleDefinitionProperties + { + RoleName = "My custom role", + Description = "Role description", + RoleType = Models.KeyVaultRoleType.CustomRole, + Permissions = {new Models.KeyVaultPermission +{ +DataActions = {Models.KeyVaultDataAction.SignHsmKey}, +}}, + }); + Response response = await client.CreateOrUpdateAsync("keys", "00000000-0000-0000-0000-000000000000", parameters); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleDefinitionsRestClient_GetRoleDefinitionsRestClient_GetTheSpecifiedRoleDefinition() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + Response response = client.GetRoleDefinitionsRestClient("/", "00000000-0000-0000-0000-000000000000", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleDefinitionsRestClient_GetRoleDefinitionsRestClient_GetTheSpecifiedRoleDefinition_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + Response response = await client.GetRoleDefinitionsRestClientAsync("/", "00000000-0000-0000-0000-000000000000", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleDefinitionsRestClient_GetRoleDefinitionsRestClient_GetTheSpecifiedRoleDefinition_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + Response response = client.GetRoleDefinitionsRestClient("/", "00000000-0000-0000-0000-000000000000"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleDefinitionsRestClient_GetRoleDefinitionsRestClient_GetTheSpecifiedRoleDefinition_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + Response response = await client.GetRoleDefinitionsRestClientAsync("/", "00000000-0000-0000-0000-000000000000"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleDefinitionsRestClient_GetRoleDefinitionsRestClients_GetAllRoleDefinitionsThatAreApplicableAtScopeAndAbove() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + foreach (BinaryData item in client.GetRoleDefinitionsRestClients("keys", null, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleDefinitionsRestClient_GetRoleDefinitionsRestClients_GetAllRoleDefinitionsThatAreApplicableAtScopeAndAbove_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + await foreach (BinaryData item in client.GetRoleDefinitionsRestClientsAsync("keys", null, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RoleDefinitionsRestClient_GetRoleDefinitionsRestClients_GetAllRoleDefinitionsThatAreApplicableAtScopeAndAbove_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + foreach (KeyVaultRoleDefinition item in client.GetRoleDefinitionsRestClients("keys")) + { + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RoleDefinitionsRestClient_GetRoleDefinitionsRestClients_GetAllRoleDefinitionsThatAreApplicableAtScopeAndAbove_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + RoleDefinitionsRestClient client = new RoleDefinitionsRestClient(endpoint, credential); + + await foreach (KeyVaultRoleDefinition item in client.GetRoleDefinitionsRestClientsAsync("keys")) + { + } + } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/tests/Generated/Samples/Samples_SettingsRestClient.cs b/sdk/keyvault/Azure.Security.KeyVault.Administration/tests/Generated/Samples/Samples_SettingsRestClient.cs new file mode 100644 index 000000000000..9e94da6ae03c --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/tests/Generated/Samples/Samples_SettingsRestClient.cs @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using Azure.Security.KeyVault.Administration.Models; +using NUnit.Framework; + +namespace Azure.Security.KeyVault.Administration.Samples +{ + public partial class Samples_SettingsRestClient + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SettingsRestClient_UpdateSetting_UpdateKeyVaultAccountSetting() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + value = "true", + }); + Response response = client.UpdateSetting("AllowKeyManagementOperationsThroughARM", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SettingsRestClient_UpdateSetting_UpdateKeyVaultAccountSetting_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + using RequestContent content = RequestContent.Create(new + { + value = "true", + }); + Response response = await client.UpdateSettingAsync("AllowKeyManagementOperationsThroughARM", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SettingsRestClient_GetSetting_ShortVersion() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + Response response = client.GetSetting("", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SettingsRestClient_GetSetting_ShortVersion_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + Response response = await client.GetSettingAsync("", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SettingsRestClient_GetSetting_ShortVersion_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + Response response = client.GetSetting(""); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SettingsRestClient_GetSetting_ShortVersion_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + Response response = await client.GetSettingAsync(""); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SettingsRestClient_GetSetting_AllParameters() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + Response response = client.GetSetting("", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("type").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SettingsRestClient_GetSetting_AllParameters_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + Response response = await client.GetSettingAsync("", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("type").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SettingsRestClient_GetSetting_AllParameters_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + Response response = client.GetSetting(""); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SettingsRestClient_GetSetting_AllParameters_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + Response response = await client.GetSettingAsync(""); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SettingsRestClient_GetSettings_ListAccountSettings() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + Response response = client.GetSettings(null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SettingsRestClient_GetSettings_ListAccountSettings_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + Response response = await client.GetSettingsAsync(null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SettingsRestClient_GetSettings_ListAccountSettings_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + Response response = client.GetSettings(); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SettingsRestClient_GetSettings_ListAccountSettings_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SettingsRestClient client = new SettingsRestClient(endpoint, credential); + + Response response = await client.GetSettingsAsync(); + } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/tsp-location.yaml b/sdk/keyvault/Azure.Security.KeyVault.Administration/tsp-location.yaml new file mode 100644 index 000000000000..9f70c6450aa8 --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/tsp-location.yaml @@ -0,0 +1,8 @@ +directory: specification/keyvault/Security.KeyVault.Administration +commit: eaed7871620fc00e56bb422d7f6a2789e44c0ea9 +repo: Azure/azure-rest-api-specs +additionalDirectories: +- specification/keyvault/Security.KeyVault.BackupRestore +- specification/keyvault/Security.KeyVault.Common +- specification/keyvault/Security.KeyVault.RBAC +- specification/keyvault/Security.KeyVault.Settings