public async Task BackupAndRestoreAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");
            string backupPath  = Path.GetTempFileName();

            // Instantiate a secret client that will be used to call the service. Notice that the client is using default Azure
            // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
            // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
            var client = new SecretClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // Let's create a secret holding bank account credentials valid for 1 year. if the secret
            // already exists in the key vault, then a new version of the secret is created.
            string secretName = $"StorageAccountPasswor{Guid.NewGuid()}";

            var secret = new Secret(secretName, "f4G34fMh8v")
            {
                Properties =
                {
                    Expires = DateTimeOffset.Now.AddYears(1)
                }
            };

            Secret storedSecret = await client.SetSecretAsync(secret);

            // Backups are good to have if in case secrets get accidentally deleted by you.
            // For long term storage, it is ideal to write the backup to a file.
            using (FileStream sourceStream = File.Open(backupPath, FileMode.OpenOrCreate))
            {
                byte[] byteSecret = await client.BackupSecretAsync(secretName);

                sourceStream.Seek(0, SeekOrigin.End);
                await sourceStream.WriteAsync(byteSecret, 0, byteSecret.Length);
            }

            // The storage account secret is no longer in use, so you delete it.
            await client.DeleteSecretAsync(secretName);

            // To ensure secret is deleted on server side.
            Assert.IsTrue(await WaitForDeletedSecretAsync(client, secretName));

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted secret needs to be purged.
            await client.PurgeDeletedSecretAsync(secretName);

            // After sometime, the secret is required again. We can use the backup value to restore it in the key vault.
            SecretProperties restoreSecret = null;

            using (FileStream sourceStream = File.Open(backupPath, FileMode.Open))
            {
                byte[] result = new byte[sourceStream.Length];
                await sourceStream.ReadAsync(result, 0, (int)sourceStream.Length);

                restoreSecret = await client.RestoreSecretAsync(result);
            }

            AssertSecretsEqual(storedSecret.Properties, restoreSecret);
        }
        public async Task BackupAndRestoreAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            var client = new SecretClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            string secretName = $"StorageAccountPassword{Guid.NewGuid()}";

            var secret = new KeyVaultSecret(secretName, "f4G34fMh8v");

            secret.Properties.ExpiresOn = DateTimeOffset.Now.AddYears(1);

            KeyVaultSecret storedSecret = await client.SetSecretAsync(secret);

            string backupPath = Path.GetTempFileName();

            using (FileStream sourceStream = File.Open(backupPath, FileMode.OpenOrCreate))
            {
                byte[] byteSecret = await client.BackupSecretAsync(secretName);

                sourceStream.Seek(0, SeekOrigin.End);
                await sourceStream.WriteAsync(byteSecret, 0, byteSecret.Length);
            }

            // The storage account secret is no longer in use so you delete it.
            DeleteSecretOperation operation = await client.StartDeleteSecretAsync(secretName);

            // Before it can be purged, you need to wait until the secret is fully deleted.
            await operation.WaitForCompletionAsync();

            // If the Key Vault is soft delete-enabled and you want to permanently delete the secret before its `ScheduledPurgeDate`,
            // the deleted secret needs to be purged.
            await client.PurgeDeletedSecretAsync(secretName);

            SecretProperties restoreSecret = null;

            using (FileStream sourceStream = File.Open(backupPath, FileMode.Open))
            {
                byte[] result = new byte[sourceStream.Length];
                await sourceStream.ReadAsync(result, 0, (int)sourceStream.Length);

                restoreSecret = await client.RestoreSecretBackupAsync(result);
            }

            AssertSecretsEqual(storedSecret.Properties, restoreSecret);

            // Delete and purge the restored secret.
            operation = await client.StartDeleteSecretAsync(restoreSecret.Name);

            // You only need to wait for completion if you want to purge or recover the secret.
            await operation.WaitForCompletionAsync();

            await client.PurgeDeletedSecretAsync(restoreSecret.Name);
        }
        /// <summary>
        /// Demonstrates how to back up and restore a secret.
        /// </summary>
        /// <returns>Task representing this functionality.</returns>
        public static async Task DemonstrateBackupAndRestoreAsync()
        {
            // instantiate the samples object
            var sample = new KeyVaultEntityRecoverySamples();

            var rgName = sample.context.ResourceGroupName;

            // derive a unique vault name for this sample
            var vaultName  = sample.context.VaultName + "backuprestore";
            var secretName = "backupsample";

            // retrieve the vault (or create, if it doesn't exist)
            var vault = await sample.CreateOrRetrieveVaultAsync(rgName, vaultName, enableSoftDelete : false, enablePurgeProtection : false);

            var vaultUri = vault.Properties.VaultUri;

            SecretClient secretClient = sample.GetDataClient(new Uri(vaultUri));

            Console.WriteLine("Operating with vault name '{0}' in resource group '{1}' and location '{2}'", vaultName, rgName, vault.Location);

            try
            {
                // set a secret
                Console.Write("Setting a new value for secret '{0}'...", secretName);
                await secretClient.SetSecretAsync(secretName, Guid.NewGuid().ToString());

                Console.WriteLine("done.");

                // confirm existence
                Console.Write("Verifying secret creation...");
                await secretClient.GetSecretAsync(secretName);

                Console.WriteLine("done.");

                // backup secret
                Console.Write("Backing up secret...");
                Response <byte[]> backupResponse = await secretClient.BackupSecretAsync(secretName);

                Console.WriteLine("done.");

                // delete secret
                Console.Write("Deleting secret...");
                DeleteSecretOperation deleteSecretOperation = await secretClient.StartDeleteSecretAsync(secretName);

                // When deleting a secret asynchronously before you purge it, you can await the WaitForCompletionAsync method on the operation
                await deleteSecretOperation.WaitForCompletionAsync();

                Console.WriteLine("done.");

                // restore secret
                Console.Write("Restoring secret from backup...");
                await secretClient.RestoreSecretBackupAsync(backupResponse.Value);

                Console.WriteLine("done.");

                // confirm existence
                Console.Write("Verifying secret restoration...");
                await secretClient.GetSecretAsync(secretName);

                Console.WriteLine("done.");
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine("Unexpected Key Vault  exception encountered: {0}", ex.Message);

                throw;
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception encountered: {0}", e.Message);

                throw;
            }
        }