private void AddCertificates(ServiceCertificateListResponse uploadedCertificates, PublishContext context)
 {
     string name = context.ServiceName;
     CloudServiceProject cloudServiceProject = context.ServiceProject;
     if (cloudServiceProject.Components.CloudConfig.Role != null)
     {
         foreach (ConfigCertificate certElement in cloudServiceProject.Components.CloudConfig.Role.
             SelectMany(r => r.Certificates ?? new ConfigCertificate[0]).Distinct())
         {
             if (uploadedCertificates == null || (uploadedCertificates.Certificates.Count(c => c.Thumbprint.Equals(
                 certElement.thumbprint, StringComparison.OrdinalIgnoreCase)) < 1))
             {
                 X509Certificate2 cert = GeneralUtilities.GetCertificateFromStore(certElement.thumbprint);
                 UploadCertificate(cert, certElement, name);
             }
         }
     }
 }
        private void CreateDeployment(PublishContext context)
        {
            var deploymentParams = new DeploymentCreateParameters
            {
                PackageUri      = UploadPackage(context),
                Configuration   = General.GetConfiguration(context.ConfigPath),
                Label           = context.ServiceName,
                Name            = context.DeploymentName,
                StartDeployment = true
            };

            WriteVerboseWithTimestamp(Resources.PublishStartingMessage);

            ServiceCertificateListResponse uploadedCertificates = ComputeClient.ServiceCertificates.List(context.ServiceName);

            AddCertificates(uploadedCertificates, context);

            ComputeClient.Deployments.Create(context.ServiceName, GetSlot(context.ServiceSettings.Slot),
                                             deploymentParams);
        }
        /// <summary>
        /// The List Service Certificates operation lists all of the service
        /// certificates associated with the specified hosted service.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx
        /// for more information)
        /// </summary>
        /// <param name='serviceName'>
        /// Required. The DNS prefix name of your hosted service.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Service Certificates operation response.
        /// </returns>
        public async Task <ServiceCertificateListResponse> ListAsync(string serviceName, CancellationToken cancellationToken)
        {
            // Validate
            if (serviceName == null)
            {
                throw new ArgumentNullException("serviceName");
            }
            // TODO: Validate serviceName is a valid DNS name.

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

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

            // Construct URL
            string url     = "/" + (this.Client.Credentials.SubscriptionId == null ? "" : Uri.EscapeDataString(this.Client.Credentials.SubscriptionId)) + "/services/hostedservices/" + Uri.EscapeDataString(serviceName) + "/certificates";
            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.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("x-ms-version", "2014-10-01");

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

                // 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, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ServiceCertificateListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new ServiceCertificateListResponse();
                        XDocument responseDoc = XDocument.Parse(responseContent);

                        XElement certificatesSequenceElement = responseDoc.Element(XName.Get("Certificates", "http://schemas.microsoft.com/windowsazure"));
                        if (certificatesSequenceElement != null)
                        {
                            foreach (XElement certificatesElement in certificatesSequenceElement.Elements(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure")))
                            {
                                ServiceCertificateListResponse.Certificate certificateInstance = new ServiceCertificateListResponse.Certificate();
                                result.Certificates.Add(certificateInstance);

                                XElement certificateUrlElement = certificatesElement.Element(XName.Get("CertificateUrl", "http://schemas.microsoft.com/windowsazure"));
                                if (certificateUrlElement != null)
                                {
                                    Uri certificateUrlInstance = TypeConversion.TryParseUri(certificateUrlElement.Value);
                                    certificateInstance.CertificateUri = certificateUrlInstance;
                                }

                                XElement thumbprintElement = certificatesElement.Element(XName.Get("Thumbprint", "http://schemas.microsoft.com/windowsazure"));
                                if (thumbprintElement != null)
                                {
                                    string thumbprintInstance = thumbprintElement.Value;
                                    certificateInstance.Thumbprint = thumbprintInstance;
                                }

                                XElement thumbprintAlgorithmElement = certificatesElement.Element(XName.Get("ThumbprintAlgorithm", "http://schemas.microsoft.com/windowsazure"));
                                if (thumbprintAlgorithmElement != null)
                                {
                                    string thumbprintAlgorithmInstance = thumbprintAlgorithmElement.Value;
                                    certificateInstance.ThumbprintAlgorithm = thumbprintAlgorithmInstance;
                                }

                                XElement dataElement = certificatesElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure"));
                                if (dataElement != null)
                                {
                                    byte[] dataInstance = Convert.FromBase64String(dataElement.Value);
                                    certificateInstance.Data = dataInstance;
                                }
                            }
                        }
                    }
                    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();
                }
            }
        }
 private void AddCertificates(ServiceCertificateListResponse uploadedCertificates, PublishContext context)
 {
     string name = context.ServiceName;
     CloudServiceProject cloudServiceProject = new CloudServiceProject(context.RootPath, null);
     if (cloudServiceProject.Components.CloudConfig.Role != null)
     {
         foreach (ConfigCertificate certElement in cloudServiceProject.Components.CloudConfig.Role.
             SelectMany(r => r.Certificates ?? new ConfigCertificate[0]).Distinct())
         {
             if (uploadedCertificates == null || (uploadedCertificates.Certificates.Count(c => c.Thumbprint.Equals(
                 certElement.thumbprint, StringComparison.OrdinalIgnoreCase)) < 1))
             {
                 X509Certificate2 cert = General.GetCertificateFromStore(certElement.thumbprint);
                 UploadCertificate(cert, certElement, name);
             }
         }
     }
 }