/// <summary>
        /// Get the vault extended info.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group containing the job
        /// collection.
        /// </param>
        /// <param name='resourceName'>
        /// Required. The name of the resource.
        /// </param>
        /// <param name='parameters'>
        /// Required. Upload Vault Certificate input parameters.
        /// </param>
        /// <param name='certFriendlyName'>
        /// Required. Certificate friendly name
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Optional. Request header parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the upload certificate response
        /// </returns>
        public async Task <UploadCertificateResponse> UploadCertificateAsync(string resourceGroupName, string resourceName, CertificateArgs parameters, string certFriendlyName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceName == null)
            {
                throw new ArgumentNullException("resourceName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Properties == null)
            {
                throw new ArgumentNullException("parameters.Properties");
            }
            if (certFriendlyName == null)
            {
                throw new ArgumentNullException("certFriendlyName");
            }

            // 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("resourceName", resourceName);
                tracingParameters.Add("parameters", parameters);
                tracingParameters.Add("certFriendlyName", certFriendlyName);
                tracingParameters.Add("customRequestHeaders", customRequestHeaders);
                TracingAdapter.Enter(invocationId, this, "UploadCertificateAsync", 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 + Uri.EscapeDataString(this.Client.ResourceNamespace);
            url = url + "/";
            url = url + "SiteRecoveryVault";
            url = url + "/";
            url = url + Uri.EscapeDataString(resourceName);
            url = url + "/certificates/";
            url = url + Uri.EscapeDataString(certFriendlyName);
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2015-03-15");
            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.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);

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

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

                JObject parametersValue = new JObject();
                requestDoc = parametersValue;

                if (parameters.Properties != null)
                {
                    if (parameters.Properties is ILazyCollection == false || ((ILazyCollection)parameters.Properties).IsInitialized)
                    {
                        JObject propertiesDictionary = new JObject();
                        foreach (KeyValuePair <string, string> pair in parameters.Properties)
                        {
                            string propertiesKey   = pair.Key;
                            string propertiesValue = pair.Value;
                            propertiesDictionary[propertiesKey] = propertiesValue;
                        }
                        parametersValue["properties"] = propertiesDictionary;
                    }
                }

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

                // 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.OK)
                    {
                        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
                    UploadCertificateResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new UploadCertificateResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken propertiesValue2 = responseDoc["properties"];
                            if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
                            {
                                CertificateProperties propertiesInstance = new CertificateProperties();
                                result.Properties = propertiesInstance;

                                JToken friendlyNameValue = propertiesValue2["friendlyName"];
                                if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
                                {
                                    string friendlyNameInstance = ((string)friendlyNameValue);
                                    propertiesInstance.FriendlyName = friendlyNameInstance;
                                }

                                JToken globalAcsHostNameValue = propertiesValue2["globalAcsHostName"];
                                if (globalAcsHostNameValue != null && globalAcsHostNameValue.Type != JTokenType.Null)
                                {
                                    string globalAcsHostNameInstance = ((string)globalAcsHostNameValue);
                                    propertiesInstance.GlobalAcsHostName = globalAcsHostNameInstance;
                                }

                                JToken globalAcsNamespaceValue = propertiesValue2["globalAcsNamespace"];
                                if (globalAcsNamespaceValue != null && globalAcsNamespaceValue.Type != JTokenType.Null)
                                {
                                    string globalAcsNamespaceInstance = ((string)globalAcsNamespaceValue);
                                    propertiesInstance.GlobalAcsNamespace = globalAcsNamespaceInstance;
                                }

                                JToken globalAcsRPRealmValue = propertiesValue2["globalAcsRPRealm"];
                                if (globalAcsRPRealmValue != null && globalAcsRPRealmValue.Type != JTokenType.Null)
                                {
                                    string globalAcsRPRealmInstance = ((string)globalAcsRPRealmValue);
                                    propertiesInstance.GlobalAcsRPRealm = globalAcsRPRealmInstance;
                                }

                                JToken resourceIdValue = propertiesValue2["resourceId"];
                                if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null)
                                {
                                    long resourceIdInstance = ((long)resourceIdValue);
                                    propertiesInstance.ResourceId = resourceIdInstance;
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Beispiel #2
0
        public void HelloWorldSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            // Instantiate a certificate 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 CertificateClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // Let's create a self signed certifiate using the default policy. If the certificiate
            // already exists in the Key Vault, then a new version of the key is created.
            string certName = $"defaultCert-{Guid.NewGuid()}";

            CertificateOperation certOp = client.StartCreateCertificate(certName);

            // Next let's wait on the certificate operation to complete. Note that certificate creation can last an indeterministic
            // amount of time, so applications should only wait on the operation to complete in the case the issuance time is well
            // known and within the scope of the application lifetime. In this case we are creating a self-signed certificate which
            // should be issued in a relatively short amount of time.
            while (!certOp.HasCompleted)
            {
                certOp.UpdateStatus();

                Thread.Sleep(certOp.PollingInterval);
            }

            // Let's get the created certificate along with it's policy from the Key Vault.
            CertificateWithPolicy certificate = client.GetCertificateWithPolicy(certName);

            Debug.WriteLine($"Certificate was returned with name {certificate.Name} which expires {certificate.Properties.Expires}");

            // We find that the certificate has been compromised and we want to disable it so applications will no longer be able
            // to access the compromised version of the certificate.
            CertificateProperties certificateProperties = certificate.Properties;

            certificateProperties.Enabled = false;

            Certificate updatedCert = client.UpdateCertificateProperties(certificateProperties);

            Debug.WriteLine($"Certificate enabled set to '{updatedCert.Properties.Enabled}'");

            // We need to create a new version of the certificate that applications can use to replace the compromised certificate.
            // Creating a certificate with the same name and policy as the compromised certificate will create another version of the
            // certificate with similar properties to the original certificate
            CertificateOperation newCertOp = client.StartCreateCertificate(certificate.Name, certificate.Policy);

            while (!newCertOp.HasCompleted)
            {
                newCertOp.UpdateStatus();

                Thread.Sleep(newCertOp.PollingInterval);
            }

            // The certificate is no longer needed, need to delete it from the Key Vault.
            client.DeleteCertificate(certName);

            // To ensure certificate is deleted on server side.
            Assert.IsTrue(WaitForDeletedCertificate(client, certName));

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted certificate needs to be purged.
            client.PurgeDeletedCertificate(certName);
        }