public void SetRoleInstanceCountProcess()
        {
            OperationStatusResponse operation;
            var currentDeployment = this.GetCurrentDeployment(out operation);
            if (currentDeployment == null)
            {
                return;
            }

            XNamespace ns = "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration";
            var configuration = XDocument.Parse(currentDeployment.Configuration);
            var role = configuration.Root.Elements(ns + "Role").SingleOrDefault(p => string.Compare(p.Attribute("name").Value, this.RoleName, true) == 0);

            if (role != null)
            {
                role.Element(ns + "Instances").SetAttributeValue("count", this.Count);
            }

            var updatedConfigurationParameter = new DeploymentChangeConfigurationParameters
            {
                Configuration = configuration.ToString()
            };
            DeploymentSlot slot;
            if (!Enum.TryParse(this.Slot, out slot))
            {
                throw new ArgumentOutOfRangeException("Slot");
            }
            ExecuteClientActionNewSM(configuration, 
                CommandRuntime.ToString(), 
                () => this.ComputeClient.Deployments.ChangeConfigurationBySlot(this.ServiceName, slot, updatedConfigurationParameter));
        }
 /// <summary>
 /// The Begin Changing Deployment Configuration By Name operation
 /// initiates a change to the deployment configuration. This operation
 /// is an asynchronous operation. To determine whether the Management
 /// service has finished processing the request, call Get Operation
 /// Status. For more information on asynchronous operations, see
 /// Tracking Asynchronous Service Management Requests at
 /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx.
 /// (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.Compute.IDeploymentOperations.
 /// </param>
 /// <param name='serviceName'>
 /// Required. The cloud service to change deployment configuration for.
 /// </param>
 /// <param name='deploymentName'>
 /// Required. The deployment to change configuration for.
 /// </param>
 /// <param name='parameters'>
 /// Required. Parameters supplied to the Begin Changing Configuration
 /// Deployment By Name operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static OperationResponse BeginChangingConfigurationByName(this IDeploymentOperations operations, string serviceName, string deploymentName, DeploymentChangeConfigurationParameters parameters)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IDeploymentOperations)s).BeginChangingConfigurationByNameAsync(serviceName, deploymentName, parameters);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
 /// <summary>
 /// The Change Deployment Configuration operation initiates a change to
 /// the deployment configuration.  The Change Deployment Configuration
 /// operation is an asynchronous operation. To determine whether the
 /// Management service has finished processing the request, call Get
 /// Operation Status.  For more information on asynchronous
 /// operations, see Tracking Asynchronous Service Management Requests.
 /// (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.Compute.IDeploymentOperations.
 /// </param>
 /// <param name='serviceName'>
 /// The cloud service to change deployment configuration for.
 /// </param>
 /// <param name='deploymentName'>
 /// The deployment to change configuration for.
 /// </param>
 /// <param name='parameters'>
 /// Parameters supplied to the Change Configuration Deployment
 /// operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static OperationResponse BeginChangingConfigurationByName(this IDeploymentOperations operations, string serviceName, string deploymentName, DeploymentChangeConfigurationParameters parameters)
 {
     try
     {
         return operations.BeginChangingConfigurationByNameAsync(serviceName, deploymentName, parameters).Result;
     }
     catch (AggregateException ex)
     {
         if (ex.InnerExceptions.Count > 1)
         {
             throw;
         }
         else
         {
             throw ex.InnerException;
         }
     }
 }
        public void ExecuteCommand()
        {
            string configString = string.Empty;
            if (!string.IsNullOrEmpty(Configuration))
            {
                configString = GeneralUtilities.GetConfiguration(Configuration);
            }

            ExtensionConfiguration extConfig = null;
            if (ExtensionConfiguration != null)
            {
                string errorConfigInput = null;
                if (!ExtensionManager.Validate(ExtensionConfiguration, out errorConfigInput))
                {
                    throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, errorConfigInput));
                }

                foreach (ExtensionConfigurationInput context in ExtensionConfiguration)
                {
                    if (context != null && context.X509Certificate != null)
                    {
                        ExecuteClientActionNewSM(
                            null,
                            string.Format(Resources.ServiceExtensionUploadingCertificate, CommandRuntime, context.X509Certificate.Thumbprint),
                            () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, CertUtilsNewSM.Create(context.X509Certificate)));
                    }
                }

                var slotType = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true);
                DeploymentGetResponse d = null;
                InvokeInOperationContext(() =>
                {
                    try
                    {
                        d = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, slotType);
                    }
                    catch (CloudException ex)
                    {
                        if (ex.Response.StatusCode != HttpStatusCode.NotFound && IsVerbose() == false)
                        {
                            this.WriteExceptionDetails(ex);
                        }
                    }
                });

                ExtensionManager extensionMgr = new ExtensionManager(this, ServiceName);
                extConfig = extensionMgr.Add(d, ExtensionConfiguration, this.Slot);
            }

            // Upgrade Parameter Set
            if (string.Compare(ParameterSetName, "Upgrade", StringComparison.OrdinalIgnoreCase) == 0)
            {
                bool removePackage = false;
                var storageName = CurrentContext.Subscription.GetProperty(AzureSubscription.Property.StorageAccount);

                Uri packageUrl = null;
                if (Package.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
                    Package.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
                {
                    packageUrl = new Uri(Package);
                }
                else
                {
                    if (string.IsNullOrEmpty(storageName))
                    {
                        throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
                    }

                    var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.UploadingPackage);
                    WriteProgress(progress);
                    removePackage = true;
                    InvokeInOperationContext(() => packageUrl = RetryCall(s => AzureBlob.UploadPackageToBlob(this.StorageClient, storageName, Package, null)));
                }

                DeploymentUpgradeMode upgradeMode;
                if (!Enum.TryParse<DeploymentUpgradeMode>(Mode, out upgradeMode))
                {
                    upgradeMode = DeploymentUpgradeMode.Auto;
                }

                var upgradeDeploymentInput = new DeploymentUpgradeParameters
                {
                    Mode = upgradeMode,
                    Configuration = configString,
                    ExtensionConfiguration = extConfig,
                    PackageUri = packageUrl,
                    Label = Label ?? ServiceName,
                    Force = Force.IsPresent
                };

                if (!string.IsNullOrEmpty(RoleName))
                {
                    upgradeDeploymentInput.RoleToUpgrade = RoleName;
                }

                InvokeInOperationContext(() =>
                {
                    try
                    {
                        ExecuteClientActionNewSM(
                            upgradeDeploymentInput,
                            CommandRuntime.ToString(),
                            () => this.ComputeClient.Deployments.UpgradeBySlot(
                                this.ServiceName,
                                (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true),
                                upgradeDeploymentInput));

                        if (removePackage == true)
                        {
                            this.RetryCall(s =>
                            AzureBlob.DeletePackageFromBlob(
                                    this.StorageClient,
                                    storageName,
                                    packageUrl));
                        }
                    }
                    catch (CloudException ex)
                    {
                        this.WriteExceptionDetails(ex);
                    }
                });
            }
            else if (string.Compare(this.ParameterSetName, "Config", StringComparison.OrdinalIgnoreCase) == 0)
            {
                // Config parameter set
                var changeDeploymentStatusParams = new DeploymentChangeConfigurationParameters
                {
                    Configuration = configString,
                    ExtensionConfiguration = extConfig
                };

                ExecuteClientActionNewSM(
                    changeDeploymentStatusParams,
                    CommandRuntime.ToString(),
                    () => this.ComputeClient.Deployments.ChangeConfigurationBySlot(
                        this.ServiceName,
                        (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true),
                        changeDeploymentStatusParams));
            }
            else
            {
                // Status parameter set
                var updateDeploymentStatusParams = new DeploymentUpdateStatusParameters
                {
                    Status = (UpdatedDeploymentStatus)Enum.Parse(typeof(UpdatedDeploymentStatus), this.NewStatus, true)
                };

                ExecuteClientActionNewSM(
                    null,
                    CommandRuntime.ToString(),
                    () => this.ComputeClient.Deployments.UpdateStatusByDeploymentSlot(
                    this.ServiceName,
                    (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true),
                    updateDeploymentStatusParams));
            }
        }
        protected PSArgument[] CreateDeploymentChangeConfigurationByNameParameters()
        {
            string serviceName = string.Empty;
            string deploymentName = string.Empty;
            DeploymentChangeConfigurationParameters parameters = new DeploymentChangeConfigurationParameters();

            return ConvertFromObjectsToArguments(new string[] { "ServiceName", "DeploymentName", "Parameters" }, new object[] { serviceName, deploymentName, parameters });
        }
 /// <summary>
 /// The Begin Changing Deployment Configuration By Slot operation
 /// initiates a change to the deployment configuration. This operation
 /// is an asynchronous operation. To determine whether the Management
 /// service has finished processing the request, call Get Operation
 /// Status. For more information on asynchronous operations, see
 /// Tracking Asynchronous Service Management Requests at
 /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx.
 /// (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.Compute.IDeploymentOperations.
 /// </param>
 /// <param name='serviceName'>
 /// Required. The cloud service to change deployment configuration for.
 /// </param>
 /// <param name='deploymentSlot'>
 /// Required. The slot to change deployment configuration for.
 /// </param>
 /// <param name='parameters'>
 /// Required. Parameters supplied to the Begin Changing Configuration
 /// Deployment By Slot operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static Task<AzureOperationResponse> BeginChangingConfigurationBySlotAsync(this IDeploymentOperations operations, string serviceName, DeploymentSlot deploymentSlot, DeploymentChangeConfigurationParameters parameters)
 {
     return operations.BeginChangingConfigurationBySlotAsync(serviceName, deploymentSlot, parameters, CancellationToken.None);
 }
 /// <summary>
 /// The Change Deployment Configuration By Name operation initiates a
 /// change to the deployment configuration. This operation is an
 /// asynchronous operation. To determine whether the Management
 /// service has finished processing the request, call Get Operation
 /// Status. For more information on asynchronous operations, see
 /// Tracking Asynchronous Service Management Requests at
 /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx.
 /// (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.Compute.IDeploymentOperations.
 /// </param>
 /// <param name='serviceName'>
 /// Required. The cloud service to change deployment configuration for.
 /// </param>
 /// <param name='deploymentName'>
 /// Required. The deployment to change configuration for.
 /// </param>
 /// <param name='parameters'>
 /// Required. Parameters supplied to the Change ConfigurationDeployment
 /// By Name operation.
 /// </param>
 /// <returns>
 /// The response body contains the status of the specified asynchronous
 /// operation, indicating whether it has succeeded, is inprogress, or
 /// has failed. Note that this status is distinct from the HTTP status
 /// code returned for the Get Operation Status operation itself. If
 /// the asynchronous operation succeeded, the response body includes
 /// the HTTP status code for the successful request. If the
 /// asynchronous operation failed, the response body includes the HTTP
 /// status code for the failed request and error information regarding
 /// the failure.
 /// </returns>
 public static Task<OperationStatusResponse> ChangeConfigurationByNameAsync(this IDeploymentOperations operations, string serviceName, string deploymentName, DeploymentChangeConfigurationParameters parameters)
 {
     return operations.ChangeConfigurationByNameAsync(serviceName, deploymentName, parameters, CancellationToken.None);
 }
        protected void ChangeDeployment(ExtensionConfiguration extConfig)
        {
            DeploymentChangeConfigurationParameters changeConfigInput = new DeploymentChangeConfigurationParameters
            {
                Configuration = Deployment.Configuration,
                ExtensionConfiguration = Deployment.ExtensionConfiguration = extConfig,
                Mode = DeploymentChangeConfigurationMode.Auto,
                TreatWarningsAsError = false
            };

            ExecuteClientActionNewSM(
                null,
                CommandRuntime.ToString(),
                () => this.ComputeClient.Deployments.ChangeConfigurationBySlot(
                    ServiceName,
                    (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), Slot, true),
                    changeConfigInput));
        }
 /// <summary>
 /// The Change Deployment Configuration operation initiates a change to
 /// the deployment configuration.  The Change Deployment Configuration
 /// operation is an asynchronous operation. To determine whether the
 /// Management service has finished processing the request, call Get
 /// Operation Status.  For more information on asynchronous
 /// operations, see Tracking Asynchronous Service Management Requests.
 /// (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.Compute.IDeploymentOperations.
 /// </param>
 /// <param name='serviceName'>
 /// The cloud service to change deployment configuration for.
 /// </param>
 /// <param name='deploymentSlot'>
 /// The slot to change deployment configuration for.
 /// </param>
 /// <param name='parameters'>
 /// Parameters supplied to the Change Configuration Deployment
 /// operation.
 /// </param>
 /// <returns>
 /// The response body contains the status of the specified asynchronous
 /// operation, indicating whether it has succeeded, is inprogress, or
 /// has failed. Note that this status is distinct from the HTTP status
 /// code returned for the Get Operation Status operation itself.  If
 /// the asynchronous operation succeeded, the response body includes
 /// the HTTP status code for the successful request.  If the
 /// asynchronous operation failed, the response body includes the HTTP
 /// status code for the failed request, and also includes error
 /// information regarding the failure.
 /// </returns>
 public static ComputeOperationStatusResponse ChangeConfigurationBySlot(this IDeploymentOperations operations, string serviceName, DeploymentSlot deploymentSlot, DeploymentChangeConfigurationParameters parameters)
 {
     try
     {
         return operations.ChangeConfigurationBySlotAsync(serviceName, deploymentSlot, parameters).Result;
     }
     catch (AggregateException ex)
     {
         if (ex.InnerExceptions.Count > 1)
         {
             throw;
         }
         else
         {
             throw ex.InnerException;
         }
     }
 }
 public async Task<OperationResponse> ChangeDeploymentConfiguration(DeploymentChangeConfigurationParameters changeConfigParameters, DeploymentSlot slot = DeploymentSlot.Production)
 {
     return await _computeClient.Value.Deployments.BeginChangingConfigurationBySlotAsync(this.ServiceName, slot, changeConfigParameters);
 }