public async Task UploadCertificateToBatchAccountAsync(
            Guid subscriptionId,
            Config.BatchAccount batchAccount,
            X509Certificate2 certificate,
            string password)
        {
            var accessToken = await GetAccessToken();

            var token       = new TokenCredentials(accessToken);
            var batchClient = new BatchManagementClient(token, _httpClientFactory.CreateClient(), false)
            {
                SubscriptionId = subscriptionId.ToString()
            };

            // Check if the cert has already been uploaded.
            var existingCerts = await batchClient.Certificate.ListByBatchAccountAsync(batchAccount.ResourceGroupName, batchAccount.Name);

            if (existingCerts != null &&
                existingCerts.Any(c =>
                                  c.Thumbprint.Equals(certificate.Thumbprint, StringComparison.InvariantCultureIgnoreCase)))
            {
                return;
            }

            var parameters = new CertificateCreateOrUpdateParameters(
                Convert.ToBase64String(certificate.Export(X509ContentType.Pkcs12, password)),
                thumbprint: certificate.Thumbprint,
                thumbprintAlgorithm: "SHA1",
                password: password);

            await batchClient.Certificate.CreateAsync(
                batchAccount.ResourceGroupName,
                batchAccount.Name,
                $"SHA1-{certificate.Thumbprint}",
                parameters);
        }
        public async Task BatchCertificateEndToEndAsync()
        {
            using (MockContext context = StartMockContextAndInitializeClients(this.GetType().FullName))
            {
                string resourceGroupName = TestUtilities.GenerateName();
                string batchAccountName  = TestUtilities.GenerateName();
                string batchCertName     = "SHA1-cff2ab63c8c955aaf71989efa641b906558d9fb7";

                ResourceGroup group = new ResourceGroup(this.Location);
                await this.ResourceManagementClient.ResourceGroups.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, group);

                // Create an account
                BatchAccountCreateParameters createParams = new BatchAccountCreateParameters(this.Location);
                await this.BatchManagementClient.BatchAccount.CreateAsync(resourceGroupName, batchAccountName, createParams);

                try
                {
                    // Create a certificate
                    CertificateCreateOrUpdateParameters param = new CertificateCreateOrUpdateParameters("MIIGMQIBAzCCBe0GCSqGSIb3DQEHAaCCBd4EggXaMIIF1jCCA8AGCSqGSIb3DQEHAaCCA7EEggOtMIIDqTCCA6UGCyqGSIb3DQEMCgECoIICtjCCArIwHAYKKoZIhvc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BrAFQAbQBwADoANABjAGUANgAwADQAZABhAC0AMAA2ADgAMQAtADQANAAxADUALQBhADIAYwBhAC0ANQA3ADcAMwAwADgAZQA2AGQAOQBhAGMwggIOBgkqhkiG9w0BBwGgggH/BIIB+zCCAfcwggHzBgsqhkiG9w0BDAoBA6CCAcswggHHBgoqhkiG9w0BCRYBoIIBtwSCAbMwggGvMIIBXaADAgECAhAdka3aTQsIsUphgIXGUmeRMAkGBSsOAwIdBQAwFjEUMBIGA1UEAxMLUm9vdCBBZ2VuY3kwHhcNMTYwMTAxMDcwMDAwWhcNMTgwMTAxMDcwMDAwWjASMRAwDgYDVQQDEwdub2Rlc2RrMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5fhcxbJHxxBEIDzVOMc56s04U6k4GPY7yMR1m+rBGVRiAyV4RjY6U936dqXHCVD36ps2Q0Z+OeEgyCInkIyVeB1EwXcToOcyeS2YcUb0vRWZDouC3tuFdHwiK1Ed5iW/LksmXDotyV7kpqzaPhOFiMtBuMEwNJcPge9k17hRgRQIDAQABo0swSTBHBgNVHQEEQDA+gBAS5AktBh0dTwCNYSHcFmRjoRgwFjEUMBIGA1UEAxMLUm9vdCBBZ2VuY3mCEAY3bACqAGSKEc+41KpcNfQwCQYFKw4DAh0FAANBAHl2M97QbpzdnwO5HoRBsiEExOcLTNg+GKCr7HUsbzfvrUivw+JLL7qjHAIc5phnK+F5bQ8HKe0L9YXBSKl+fvwxFTATBgkqhkiG9w0BCRUxBgQEAQAAADA7MB8wBwYFKw4DAhoEFGVtyGMqiBd32fGpzlGZQoRM6UQwBBTI0YHFFqTS4Go8CoLgswn29EiuUQICB9A=");
                    param.Format              = CertificateFormat.Pfx;
                    param.Password            = "******";
                    param.Thumbprint          = "cff2ab63c8c955aaf71989efa641b906558d9fb7";
                    param.ThumbprintAlgorithm = "sha1";

                    var certResponse = await this.BatchManagementClient.Certificate.CreateAsync(resourceGroupName, batchAccountName, batchCertName, param);

                    Assert.Equal("CFF2AB63C8C955AAF71989EFA641B906558D9FB7", certResponse.Thumbprint);
                    var referenceId =
                        $"/subscriptions/{this.BatchManagementClient.SubscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{batchAccountName}/certificates/{batchCertName.ToUpperInvariant()}";
                    Assert.Equal(referenceId, certResponse.Id);
                    Assert.Equal(CertificateProvisioningState.Succeeded, certResponse.ProvisioningState);
                    Assert.Equal("SHA1", certResponse.ThumbprintAlgorithm);
                    Assert.Equal(CertificateFormat.Pfx, certResponse.Format);

                    // List the certificates
                    var certs = await this.BatchManagementClient.Certificate.ListByBatchAccountAsync(resourceGroupName, batchAccountName);

                    Assert.Single(certs);

                    // Get the cert
                    var cert = await this.BatchManagementClient.Certificate.GetAsync(resourceGroupName, batchAccountName, batchCertName);

                    Assert.Equal("CFF2AB63C8C955AAF71989EFA641B906558D9FB7", cert.Thumbprint);
                    Assert.Equal(referenceId, cert.Id);
                    Assert.Equal(CertificateProvisioningState.Succeeded, cert.ProvisioningState);
                    Assert.Equal("SHA1", cert.ThumbprintAlgorithm);
                    Assert.Equal(CertificateFormat.Pfx, cert.Format);
                    Assert.Null(cert.DeleteCertificateError);

                    // Update the cert
                    param          = new CertificateCreateOrUpdateParameters("MIIGMQIBAzCCBe0GCSqGSIb3DQEHAaCCBd4EggXaMIIF1jCCA8AGCSqGSIb3DQEHAaCCA7EEggOtMIIDqTCCA6UGCyqGSIb3DQEMCgECoIICtjCCArIwHAYKKoZIhvcNAQwBAzAOBAhyd3xCtln3iQICB9AEggKQhe5P10V9iV1BsDlwWT561Yu2hVq3JT8ae/ebx1ZR/gMApVereDKkS9Zg4vFyssusHebbK5pDpU8vfAqle0TM4m7wGsRj453ZorSPUfMpHvQnAOn+2pEpWdMThU7xvZ6DVpwhDOQk9166z+KnKdHGuJKh4haMT7Rw/6xZ1rsBt2423cwTrQVMQyACrEkianpuujubKltN99qRoFAxhQcnYE2KlYKw7lRcExq6mDSYAyk5xJZ1ZFdLj6MAryZ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BBZ2VuY3kwHhcNMTYwMTAxMDcwMDAwWhcNMTgwMTAxMDcwMDAwWjASMRAwDgYDVQQDEwdub2Rlc2RrMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5fhcxbJHxxBEIDzVOMc56s04U6k4GPY7yMR1m+rBGVRiAyV4RjY6U936dqXHCVD36ps2Q0Z+OeEgyCInkIyVeB1EwXcToOcyeS2YcUb0vRWZDouC3tuFdHwiK1Ed5iW/LksmXDotyV7kpqzaPhOFiMtBuMEwNJcPge9k17hRgRQIDAQABo0swSTBHBgNVHQEEQDA+gBAS5AktBh0dTwCNYSHcFmRjoRgwFjEUMBIGA1UEAxMLUm9vdCBBZ2VuY3mCEAY3bACqAGSKEc+41KpcNfQwCQYFKw4DAh0FAANBAHl2M97QbpzdnwO5HoRBsiEExOcLTNg+GKCr7HUsbzfvrUivw+JLL7qjHAIc5phnK+F5bQ8HKe0L9YXBSKl+fvwxFTATBgkqhkiG9w0BCRUxBgQEAQAAADA7MB8wBwYFKw4DAhoEFGVtyGMqiBd32fGpzlGZQoRM6UQwBBTI0YHFFqTS4Go8CoLgswn29EiuUQICB9A=");
                    param.Password = "******";
                    certResponse   = await this.BatchManagementClient.Certificate.UpdateAsync(resourceGroupName, batchAccountName, batchCertName, param);

                    Assert.Equal(referenceId, certResponse.Id);

                    // Cancel the deletetion
                    await this.BatchManagementClient.Certificate.CancelDeletionAsync(resourceGroupName, batchAccountName, batchCertName);

                    // Delete the certificate
                    try
                    {
                        await this.BatchManagementClient.Certificate.DeleteAsync(resourceGroupName, batchAccountName, batchCertName);
                    }
                    catch (CloudException ex)
                    {
                        if (ex.Response.StatusCode != HttpStatusCode.NotFound)
                        {
                            throw;
                        }
                    }

                    // Verify certificate was deleted. A GET operation will return a 404 error and result in an exception
                    try
                    {
                        await this.BatchManagementClient.Certificate.GetAsync(resourceGroupName, batchAccountName, batchCertName);
                    }
                    catch (CloudException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }
                }
                finally
                {
                    // Clean up
                    await this.BatchManagementClient.BatchAccount.DeleteAsync(resourceGroupName, batchAccountName);

                    await this.ResourceManagementClient.ResourceGroups.DeleteWithHttpMessagesAsync(resourceGroupName);
                }
            }
        }
Example #3
0
 /// <summary>
 /// Creates or updates the certificate being used for authentication with the
 /// backend.
 /// <see href="https://azure.microsoft.com/en-us/documentation/articles/api-management-howto-mutual-certificates/" />
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='serviceName'>
 /// The name of the API Management service.
 /// </param>
 /// <param name='certificateId'>
 /// Identifier of the certificate entity. Must be unique in the current API
 /// Management service instance.
 /// </param>
 /// <param name='parameters'>
 /// Create or Update parameters.
 /// </param>
 /// <param name='ifMatch'>
 /// ETag of the Entity. Not required when creating an entity, but required when
 /// updating an entity.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <CertificateContract> CreateOrUpdateAsync(this ICertificateOperations operations, string resourceGroupName, string serviceName, string certificateId, CertificateCreateOrUpdateParameters parameters, string ifMatch = default(string), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serviceName, certificateId, parameters, ifMatch, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
        /// <summary>
        /// Creates new or update existing certificate.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group.
        /// </param>
        /// <param name='serviceName'>
        /// Required. The name of the Api Management service.
        /// </param>
        /// <param name='certificateId'>
        /// Required. Identifier of the subscription.
        /// </param>
        /// <param name='parameters'>
        /// Required. Create parameters.
        /// </param>
        /// <param name='etag'>
        /// Optional. ETag.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async Task <AzureOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string serviceName, string certificateId, CertificateCreateOrUpdateParameters parameters, string etag, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (serviceName == null)
            {
                throw new ArgumentNullException("serviceName");
            }
            if (certificateId == null)
            {
                throw new ArgumentNullException("certificateId");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("serviceName", serviceName);
                tracingParameters.Add("certificateId", certificateId);
                tracingParameters.Add("parameters", parameters);
                tracingParameters.Add("etag", etag);
                TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + "Microsoft.ApiManagement";
            url = url + "/service/";
            url = url + Uri.EscapeDataString(serviceName);
            url = url + "/certificates/";
            url = url + Uri.EscapeDataString(certificateId);
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2016-07-07");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Put;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string requestContent = null;
                JToken requestDoc     = null;

                JObject certificateCreateOrUpdateParametersValue = new JObject();
                requestDoc = certificateCreateOrUpdateParametersValue;

                if (parameters.Data != null)
                {
                    certificateCreateOrUpdateParametersValue["data"] = parameters.Data;
                }

                if (parameters.Password != null)
                {
                    certificateCreateOrUpdateParametersValue["password"] = parameters.Password;
                }

                requestContent      = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    AzureOperationResponse result = null;
                    // Deserialize Response
                    result            = new AzureOperationResponse();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
 /// <summary>
 /// Create a certificate.  (see
 /// http://aka.ms/azureautomationsdk/certificateoperations for more
 /// information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Automation.ICertificateOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group
 /// </param>
 /// <param name='automationAccount'>
 /// Required. The automation account name.
 /// </param>
 /// <param name='parameters'>
 /// Required. The parameters supplied to the create or update
 /// certificate operation.
 /// </param>
 /// <returns>
 /// The response model for the create or update certificate operation.
 /// </returns>
 public static Task <CertificateCreateOrUpdateResponse> CreateOrUpdateAsync(this ICertificateOperations operations, string resourceGroupName, string automationAccount, CertificateCreateOrUpdateParameters parameters)
 {
     return(operations.CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None));
 }
Example #6
0
 /// <summary>
 /// Creates or updates the certificate being used for authentication with the
 /// backend.
 /// <see href="https://azure.microsoft.com/en-us/documentation/articles/api-management-howto-mutual-certificates/" />
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='serviceName'>
 /// The name of the API Management service.
 /// </param>
 /// <param name='certificateId'>
 /// Identifier of the certificate entity. Must be unique in the current API
 /// Management service instance.
 /// </param>
 /// <param name='parameters'>
 /// Create or Update parameters.
 /// </param>
 /// <param name='ifMatch'>
 /// ETag of the Entity. Not required when creating an entity, but required when
 /// updating an entity.
 /// </param>
 public static CertificateContract CreateOrUpdate(this ICertificateOperations operations, string resourceGroupName, string serviceName, string certificateId, CertificateCreateOrUpdateParameters parameters, string ifMatch = default(string))
 {
     return(operations.CreateOrUpdateAsync(resourceGroupName, serviceName, certificateId, parameters, ifMatch).GetAwaiter().GetResult());
 }
 /// <summary>
 /// Updates the properties of an existing certificate.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group that contains the Batch account.
 /// </param>
 /// <param name='accountName'>
 /// The name of the Batch account.
 /// </param>
 /// <param name='certificateName'>
 /// The identifier for the certificate. This must be made up of algorithm and
 /// thumbprint separated by a dash, and must match the certificate data in the
 /// request. For example SHA1-a3d1c5.
 /// </param>
 /// <param name='parameters'>
 /// Certificate entity to update.
 /// </param>
 /// <param name='ifMatch'>
 /// The entity state (ETag) version of the certificate to update. This value
 /// can be omitted or set to "*" to apply the operation unconditionally.
 /// </param>
 public static Certificate Update(this ICertificateOperations operations, string resourceGroupName, string accountName, string certificateName, CertificateCreateOrUpdateParameters parameters, string ifMatch = default(string))
 {
     return(operations.UpdateAsync(resourceGroupName, accountName, certificateName, parameters, ifMatch).GetAwaiter().GetResult());
 }
 /// <summary>
 /// Create a certificate.  (see
 /// http://aka.ms/azureautomationsdk/certificateoperations for more
 /// information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Automation.ICertificateOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group
 /// </param>
 /// <param name='automationAccount'>
 /// Required. The automation account name.
 /// </param>
 /// <param name='parameters'>
 /// Required. The parameters supplied to the create or update
 /// certificate operation.
 /// </param>
 /// <returns>
 /// The response model for the create or update certificate operation.
 /// </returns>
 public static CertificateCreateOrUpdateResponse CreateOrUpdate(this ICertificateOperations operations, string resourceGroupName, string automationAccount, CertificateCreateOrUpdateParameters parameters)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((ICertificateOperations)s).CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
 /// <summary>
 /// Create a certificate.
 /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" />
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Name of an Azure Resource group.
 /// </param>
 /// <param name='automationAccountName'>
 /// The name of the automation account.
 /// </param>
 /// <param name='certificateName'>
 /// The parameters supplied to the create or update certificate operation.
 /// </param>
 /// <param name='parameters'>
 /// The parameters supplied to the create or update certificate operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <Certificate> CreateOrUpdateAsync(this ICertificateOperations operations, string resourceGroupName, string automationAccountName, string certificateName, CertificateCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, automationAccountName, certificateName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Create a certificate.
 /// <see href="http://aka.ms/azureautomationsdk/certificateoperations" />
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Name of an Azure Resource group.
 /// </param>
 /// <param name='automationAccountName'>
 /// The name of the automation account.
 /// </param>
 /// <param name='certificateName'>
 /// The parameters supplied to the create or update certificate operation.
 /// </param>
 /// <param name='parameters'>
 /// The parameters supplied to the create or update certificate operation.
 /// </param>
 public static Certificate CreateOrUpdate(this ICertificateOperations operations, string resourceGroupName, string automationAccountName, string certificateName, CertificateCreateOrUpdateParameters parameters)
 {
     return(operations.CreateOrUpdateAsync(resourceGroupName, automationAccountName, certificateName, parameters).GetAwaiter().GetResult());
 }
Example #11
0
 /// <summary>
 /// Creates new or update existing certificate.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.ApiManagement.ICertificatesOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='serviceName'>
 /// Required. The name of the Api Management service.
 /// </param>
 /// <param name='certificateId'>
 /// Required. Identifier of the subscription.
 /// </param>
 /// <param name='parameters'>
 /// Required. Create parameters.
 /// </param>
 /// <param name='etag'>
 /// Optional. ETag.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static Task <AzureOperationResponse> CreateOrUpdateAsync(this ICertificatesOperations operations, string resourceGroupName, string serviceName, string certificateId, CertificateCreateOrUpdateParameters parameters, string etag)
 {
     return(operations.CreateOrUpdateAsync(resourceGroupName, serviceName, certificateId, parameters, etag, CancellationToken.None));
 }
Example #12
0
 /// <summary>
 /// Creates new or update existing certificate.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.ApiManagement.ICertificatesOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='serviceName'>
 /// Required. The name of the Api Management service.
 /// </param>
 /// <param name='certificateId'>
 /// Required. Identifier of the subscription.
 /// </param>
 /// <param name='parameters'>
 /// Required. Create parameters.
 /// </param>
 /// <param name='etag'>
 /// Optional. ETag.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static AzureOperationResponse CreateOrUpdate(this ICertificatesOperations operations, string resourceGroupName, string serviceName, string certificateId, CertificateCreateOrUpdateParameters parameters, string etag)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((ICertificatesOperations)s).CreateOrUpdateAsync(resourceGroupName, serviceName, certificateId, parameters, etag);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
        public async Task CreateListUpdateDelete()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // list certificates: there should be none
                var listResponse = testBase.client.Certificate.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);

                Assert.NotNull(listResponse);
                Assert.Empty(listResponse);

                // create new certificate
                string certificateId = TestUtilities.GenerateName("certificateId");

                try
                {
                    var base64ArrayCertificate = Convert.FromBase64String(testBase.base64EncodedTestCertificateData);
                    var cert = new X509Certificate2(base64ArrayCertificate, testBase.testCertificatePassword);

                    var createResponse = testBase.client.Certificate.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        certificateId,
                        new CertificateCreateOrUpdateParameters
                    {
                        Data     = testBase.base64EncodedTestCertificateData,
                        Password = testBase.testCertificatePassword
                    },
                        null);

                    Assert.NotNull(createResponse);
                    Assert.Equal(certificateId, createResponse.Name);

                    // get the certificate to check is was created
                    var getResponse = await testBase.client.Certificate.GetWithHttpMessagesAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        certificateId);

                    Assert.NotNull(getResponse);
                    Assert.Equal(certificateId, getResponse.Body.Name);
                    Assert.Equal(cert.Subject, getResponse.Body.Subject, StringComparer.OrdinalIgnoreCase);
                    Assert.Equal(cert.Thumbprint, getResponse.Body.Thumbprint, StringComparer.OrdinalIgnoreCase);

                    //create key vault certificate
                    string kvcertificateId    = TestUtilities.GenerateName("kvcertificateId");
                    var    kvCreateParameters = new CertificateCreateOrUpdateParameters
                    {
                        KeyVault = new KeyVaultContractCreateProperties
                        {
                            SecretIdentifier = testBase.testKeyVaultSecretUrl
                        },
                    };

                    var kvCertificateIdResponse = testBase.client.Certificate.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        kvcertificateId,
                        kvCreateParameters,
                        null);

                    Assert.NotNull(createResponse);
                    Assert.Equal(certificateId, createResponse.Name);

                    // get the certificate to check is was created
                    var getKVResponse = await testBase.client.Certificate.GetWithHttpMessagesAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        kvcertificateId);

                    Assert.NotNull(getKVResponse);
                    Assert.Equal(kvcertificateId, getKVResponse.Body.Name);

                    //refresh secret of key vault client
                    var refreshKvCertificateResponse = testBase.client.Certificate.RefreshSecret(
                        testBase.rgName,
                        testBase.serviceName,
                        kvcertificateId);

                    Assert.NotNull(refreshKvCertificateResponse);

                    // list certificates
                    listResponse = testBase.client.Certificate.ListByService(
                        testBase.rgName,
                        testBase.serviceName,
                        null);

                    Assert.NotNull(listResponse);
                    Assert.Equal(2, listResponse.Count());

                    // remove the certificate
                    testBase.client.Certificate.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        certificateId,
                        getResponse.Headers.ETag);

                    testBase.client.Certificate.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        kvcertificateId,
                        "*");

                    // list again to see it was removed
                    listResponse = testBase.client.Certificate.ListByService(
                        testBase.rgName,
                        testBase.serviceName,
                        null);

                    Assert.NotNull(listResponse);
                    Assert.Empty(listResponse);
                }
                finally
                {
                    testBase.client.Certificate.Delete(testBase.rgName, testBase.serviceName, certificateId, "*");
                }
            }
        }