Пример #1
0
        /// <summary>
        /// Initializes a new instance of the AzureAccount class.
        /// </summary>
        /// <param name="subscriptionId">Subscription ID of the Azure account.</param>
        /// <param name="cert">X509 certificate used for authentication.</param>
        public AzureAccount(string subscriptionId, X509Certificate2 cert)
        {
            this.credentials = new CertificateCloudCredentials(subscriptionId, cert);

            this.computeManager = CloudContext.Clients.CreateComputeManagementClient(this.credentials);
            this.storageManager = CloudContext.Clients.CreateStorageManagementClient(this.credentials);
        }
Пример #2
0
        /// <author>Bart</author>
        /// <summary>
        /// Deze methode wordt gebruikt om nieuwe CloudServices aan te maken in Azure. Location of Affinitygroup mag null zijn.
        /// </summary>
        /// <param name="cloudServiceName">Is de naam die de CloudService gaat hebben.</param>
        /// <param name="location">Is de geografische lokatie die de CloudService zal hebben.</param>
        /// <param name="affinityGroupName">Is de groep waar deze CloudService bij hoort.</param>
        /// <returns>Een true of false respectiefelijk aan of de actie geslaagt is of niet.</returns>
        public Boolean CreateCloudService(string cloudServiceName, string location, string affinityGroupName = null)
        {
            ComputeManagementClient client = new ComputeManagementClient(cloudCredentials);
            HostedServiceCreateParameters hostedServiceCreateParams = new HostedServiceCreateParameters();

            if (location != null)
            {
                hostedServiceCreateParams = new HostedServiceCreateParameters
                {
                    ServiceName = cloudServiceName,
                    Location = location,
                    Label = EncodeToBase64(cloudServiceName),
                };
            }
            else if (affinityGroupName != null)
            {
                hostedServiceCreateParams = new HostedServiceCreateParameters
                {
                    ServiceName = cloudServiceName,
                    AffinityGroup = affinityGroupName,
                    Label = EncodeToBase64(cloudServiceName),
                };
            }
            try
            {
                client.HostedServices.Create(hostedServiceCreateParams);
                return true;
            }
            catch (CloudException)
            {
                return false;
            }
        }
Пример #3
0
        public static void CreateAzureVirtualMachine(ComputeManagementClient computeClient, string serviceName, string deploymentName, string storageAccountName, string blobUrl)
        {
            VirtualMachineOSImageListResponse imagesList = computeClient.VirtualMachineOSImages.List();

            VirtualMachineOSImageListResponse.VirtualMachineOSImage imageToGet =
                imagesList.Images.FirstOrDefault(i => string.Equals(i.OperatingSystemType, "Windows", StringComparison.OrdinalIgnoreCase));

            VirtualMachineOSImageGetResponse gottenImage = computeClient.VirtualMachineOSImages.Get(imageToGet.Name);

            VirtualMachineCreateDeploymentParameters parameters = CreateVMParameters(gottenImage, deploymentName, storageAccountName, "SampleLabel", blobUrl);

            parameters.Roles[0].ConfigurationSets.Add(new ConfigurationSet
            {
                AdminUserName = "******",
                AdminPassword = "******",
                ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration,
                ComputerName = serviceName,
                HostName = string.Format("{0}.cloudapp.net", serviceName),
                EnableAutomaticUpdates = false,
                TimeZone = "Pacific Standard Time"
            });

            OperationStatusResponse opResp =
                computeClient.VirtualMachines.CreateDeployment(serviceName, parameters);

            Assert.Equal(opResp.Status, OperationStatus.Succeeded);
        }
Пример #4
0
 /// <summary>
 /// Returns a list of Deployment objects for a given subscription
 /// </summary>
 /// <param name="serviceName">The name of the cloud service</param>
 /// <param name="slot">The slot being either Production or Staging</param>
 /// <returns></returns>
 protected DeploymentGetResponse GetAzureDeyployment(string serviceName, DeploymentSlot slot)
 {
     ComputeManagementClient client = new ComputeManagementClient(MyCloudCredentials);
     try
     {
         try
         {
             return client.Deployments.GetBySlot(serviceName, slot);
         }
         catch (CloudException ex)
         {
             if (ex.ErrorCode == "ResourceNotFound")
             {
                 Logger.Warn(ex, String.Format("Resource not found during retrieval of Deployment object for service: {0}, {1}", serviceName, ex.ErrorCode));
                 return null;
             }
             else
             {
                 Logger.Warn(ex, String.Format("Exception during retrieval of Deployment objects for the service: {0}, Errorcode: {1}", serviceName, ex.ErrorCode));
                 return null;
             }
         }
     }
     catch (Exception e)
     {
         Logger.Warn(e, String.Format("Exception during retrieval of Deployment objects for the service: {0}", serviceName));
         return null;
     }
 }
 public TestClientProvider(ManagementClient mgmtClient, ComputeManagementClient computeClient,
     StorageManagementClient storageClient, NetworkManagementClient networkClient)
 {
     this.managementClient = mgmtClient;
     this.computeManagementClient = computeClient;
     this.storageManagementClient = storageClient;
     this.networkManagementClient = networkClient;
 }
Пример #6
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                throw new ArgumentNullException("publish settings informations");
            }
            SubscriptionCloudCredentials cred = GetCredentials(args[0]);

            //WATM
            TrafficManagerManagementClient watmClient = new TrafficManagerManagementClient(cred);
            string atmDns = "adxsdk12345.trafficmanager.net";
            DnsPrefixAvailabilityCheckResponse watmResp = 
                watmClient.Profiles.CheckDnsPrefixAvailability("adxsdk12345.trafficmanager.net");
            Console.WriteLine("Invoke WATM->CheckDnsPrefixAvailability(\'{0}\'). Result: {1}", atmDns, watmResp.Result);

            //Compute
            ComputeManagementClient computeClient = new ComputeManagementClient(cred);
            string hostServiceName = "adxsdk12345";
            HostedServiceCheckNameAvailabilityResponse computeResp = 
                computeClient.HostedServices.CheckNameAvailability(hostServiceName);
            Console.WriteLine("Invoke Compute->CheckNameAvailability(\'{0}\'). Result: {1}", 
                hostServiceName, computeResp.IsAvailable);

            //Websites
            WebSiteManagementClient websiteClient = new WebSiteManagementClient(cred);
            string webSiteName = "adxsdk12345";
            WebSiteIsHostnameAvailableResponse webSiteResp = websiteClient.WebSites.IsHostnameAvailable(webSiteName);
            Console.WriteLine("Invoke WebSite->IsHostnameAvailable(\'{0}\'). Result: {1}", 
                webSiteName, webSiteResp.IsAvailable);

            //Scheduler
            SchedulerManagementClient schedulerClient = new SchedulerManagementClient(cred);
            string schedulerCloudServiceName = "foobarrr";
            string expectedSchedulerException = string.Format(
                "ResourceNotFound: The cloud service with name {0} was not found.", schedulerCloudServiceName);
            bool exceptionFromSchedulerServiceOccurred = false;
            try
            {
                schedulerClient.JobCollections.CheckNameAvailability(schedulerCloudServiceName, "doesnotmatter");
            }
            catch (Exception ex)
            {
                if (ex.Message == expectedSchedulerException)
                {
                    exceptionFromSchedulerServiceOccurred = true;
                    Console.WriteLine("Invoke Scheduler->CheckNameAvailability(\'{0}\'). Get back correct exception", 
                        schedulerCloudServiceName, expectedSchedulerException);
                }
            }
            if (!exceptionFromSchedulerServiceOccurred)
            {
                throw new Exception("we didn't get expected exception message from scheduler service");
            }

            Console.WriteLine("Smoke test is good");
        }
Пример #7
0
        public VMManagementController(VMManagementControllerParameters parameters)
        {
            _parameters = parameters;

            // To authenticate against the Microsoft Azure service management API we require management certificate
            // load this from a publish settings file and later use it with the Service Management Libraries
            var credentials = GetSubscriptionCloudCredentials(parameters.PublishSettingsFilePath);

            _storageManagementClient = CloudContext.Clients.CreateStorageManagementClient(credentials);
            _computeManagementClient = CloudContext.Clients.CreateComputeManagementClient(credentials);
        }
        public void SubscriptionChanged()
        {
            if (_computeManagementClient != null)
                _computeManagementClient.Dispose();

            _computeManagementClient = new ComputeManagementClient(
                new CertificateCloudCredentials(Host.SelectedSubscription.SubscriptionId,
                    new X509Certificate2(
                        Convert.FromBase64String(
                            Host.SelectedSubscription.ManagementCertificate))));
        }
        private VirtualMachineService()
        {
            _serviceName = System.Configuration.ConfigurationManager.AppSettings["serviceName"];
            _deploymentName = System.Configuration.ConfigurationManager.AppSettings["deploymentName"];
            _virtualMachineName = System.Configuration.ConfigurationManager.AppSettings["virtualMachineName"];

            var subscriptionId = System.Configuration.ConfigurationManager.AppSettings["subscriptionId"];
            var certificate = System.Configuration.ConfigurationManager.AppSettings["base64EncodedCertificate"];

            _client = new ComputeManagementClient(GetCredentials(subscriptionId, certificate));
        }
Пример #10
0
        internal ManagementController(ManagementControllerParamters parameters)
        {
            _parameters = parameters;

            var credential = CertificateAuthenticationHelper.GetCredentials(
                parameters.SubscriptionId,
                parameters.Base64EncodedCertificate);

            _storageManagementClient = CloudContext.Clients.CreateStorageManagementClient(credential);
            _computeManagementClient = CloudContext.Clients.CreateComputeManagementClient(credential);
        }
        public EarzyProvisioningCore()
        {
            //Get credentials from subscription ID & Certificate
            var credential = CertificateAuthenticationHelper.GetCredentials(
                ConfigurationManager.AppSettings["SubscriptionId"],
                ConfigurationManager.AppSettings["Certificate"]);

            //Initialize clients
            _storageManagementClient = CloudContext.Clients.CreateStorageManagementClient(credential);
            _computeManagementClient = CloudContext.Clients.CreateComputeManagementClient(credential);
            _webSitesManagementClient = CloudContext.Clients.CreateWebSiteManagementClient(credential);
        }
        /// <summary>
        /// Provisions all the services in the <see cref="IEnumerable{T}"/> of <see cref="AzureCloudService"/>.
        /// </summary>
        /// <param name="services">The list of <see cref="AzureCloudService"/> to provision.</param>
        /// <param name="client">The <see cref="ComputeManagementClient"/> that is performing the operation.</param>
        /// <returns>The async <see cref="Task"/> wrapper.</returns>
        public static async Task ProvisionAllAsync(this IEnumerable<AzureCloudService> services, ComputeManagementClient client)
        {
            Contract.Requires(services != null);
            Contract.Requires(client != null);

            var tasks = services.Select(
                async s =>
                {
                    await client.CreateServiceIfNotExistsAsync(s);
                });

            await Task.WhenAll(tasks);
        }
Пример #13
0
        public IEnumerable<string> GetVirtualMachineImagesList()
        {
            using (var computeClient = new ComputeManagementClient(_credentials))
            {
                var operatingSystemImageListResult =
                    computeClient.VirtualMachineOSImages.ListAsync().Result;



                return from image in operatingSystemImageListResult
                       select image.Name;
            }
        }
Пример #14
0
        /// <author>Bart</author>
        /// <summary>
        /// Deze methode kijkt of er al een deployment bestaat in de Cloudservice.
        /// </summary>
        /// <param name="serviveName">Is de naam van de CloudService waar het om gaat.</param>
        /// <returns>Een true of false respectiefelijk aan of er wel of geen deployment bestaat.</returns>
        public Boolean CheckDeployment(string serviceName)
        {
            ComputeManagementClient client = new ComputeManagementClient(cloudCredentials);

            try
            {
                client.Deployments.GetByName(serviceName, "VMs");
                return true;
            }
            catch (CloudException)
            {
                return false;
            }
        }
Пример #15
0
        public VMManagement(string subscriptionId, byte[] managementCertificate,
			string certificateKey, string blobStorageName, string blobStorageKey, ILogger logger)
        {
            _managementCertificate = new X509Certificate2(managementCertificate, certificateKey, X509KeyStorageFlags.MachineKeySet);

            _subscriptionId = subscriptionId;

            CertificateCloudCredentials cloudCredentials = new CertificateCloudCredentials(_subscriptionId, _managementCertificate);

            _datacenter = new ManagementClient(cloudCredentials);// CloudContext.Clients.CreateManagementClient(cloudCredentials);

            //var roleSizes = _datacenter.RoleSizes.List();
            _compute = new ComputeManagementClient(cloudCredentials);// CloudContext.Clients.CreateComputeManagementClient(cloudCredentials);
            _storage = new StorageManagementClient(cloudCredentials);// CloudContext.Clients.CreateStorageManagementClient(cloudCredentials);
        }
Пример #16
0
        public static void CreateHostedService(string location, ComputeManagementClient computeClient, string serviceName,
            out bool hostedServiceCreated)
        {
            AzureOperationResponse hostedServiceCreate = computeClient.HostedServices.Create(
            new HostedServiceCreateParameters
            {
                Location = location,
                Label = serviceName,
                ServiceName = serviceName
            });

            Assert.True(hostedServiceCreate.StatusCode == HttpStatusCode.Created);

            hostedServiceCreated = true;
        }
Пример #17
0
 public static void createCloudServiceByAffinityGroup(string cloudServiceName, string affinityGroupName)
 {
     ComputeManagementClient client = new ComputeManagementClient(getCredentials());
     HostedServiceCreateParameters hostedServiceCreateParams = new HostedServiceCreateParameters
     {
         ServiceName = cloudServiceName,
         AffinityGroup = affinityGroupName,
         Label = EncodeToBase64(cloudServiceName),
     };
     try
     {
         client.HostedServices.Create(hostedServiceCreateParams);
     }
     catch (CloudException e)
     {
         throw e;
     }
 }
Пример #18
0
        /// <summary>
        /// Performs the execution of the activity.
        /// </summary>
        /// <param name="context">The execution context under which the activity executes.</param>
        protected override void Execute(CodeActivityContext context)
        {
            var azureSubscription = new AzureSubscription(SettingsPath, SubscriptionId);

            var credentials = new CertificateCloudCredentials(
                SubscriptionId,
                new X509Certificate2(Convert.FromBase64String(azureSubscription.ManagementCertificate)));

            var tasks = VirtualMachines.Get(context).Select(
                async vm =>
                {
                    using (var client = new ComputeManagementClient(credentials))
                    {
                        switch (vm.Size)
                        {
                            case VirtualMachineSize.Stop:
                                await client.DeallocateVmAsync(vm.Name);
                                break;

                            case VirtualMachineSize.Small:
                            case VirtualMachineSize.ExtraSmall:
                            case VirtualMachineSize.Large:
                            case VirtualMachineSize.Medium:
                            case VirtualMachineSize.ExtraLarge:
                            case VirtualMachineSize.A5:
                            case VirtualMachineSize.A6:
                            case VirtualMachineSize.A7:
                            case VirtualMachineSize.A8:
                            case VirtualMachineSize.A9:
                                await client.ResizeVmAsync(vm.Name, vm.Size.GetEnumDescription());
                                break;

                            default:
                                throw new ArgumentOutOfRangeException(
                                    nameof(context),
                                    @"Unknown VM Size, this shouldn't happen, but the enumeration value isn't implemented in the acitivity switch");
                        }
                    }
                });

            Task.WhenAll(tasks);
        }
        /// <summary>
        /// Downloads an RDP file for each of the Elastic (Web and Worker based) Roles in a given subscription
        /// </summary>
        /// <returns>List of RdpFileObject containing the RDP file name and a byte[] with the RDP file</returns>
        public List<RdpFileObject> GetAllElasticRoleRdpFiles()
        {
            ComputeManagementClient client = new ComputeManagementClient(MyCloudCredentials);
            try
            {
                var rdpFiles = new List<RdpFileObject>();
                RdpFileObject rdpFile = null;

                var hostedServices = client.HostedServices.List();
                if (hostedServices.Count() > 0)
                {
                    foreach (var service in hostedServices)
                    {
                        var deployment = GetAzureDeyployment(service.ServiceName, DeploymentSlot.Production);
                        if (deployment != null)
                        {
                            var instances = client.Deployments.GetBySlot(service.ServiceName, DeploymentSlot.Production).RoleInstances;
                            if (instances != null)
                            {
                                if (instances.Count > 0)
                                {
                                    foreach (RoleInstance instance in instances)
                                    {
                                        var rdpFileName = String.Format("rdp--{0}--{1}--{2}.rdp", service.ServiceName, deployment.Name, instance.InstanceName);
                                        rdpFile = new RdpFileObject(rdpFileName, client.VirtualMachines.GetRemoteDesktopFile(service.ServiceName, deployment.Name, instance.InstanceName));
                                        rdpFiles.Add(rdpFile);
                                    }
                                }
                            }
                        }
                    }
                    return rdpFiles;
                }
            }
            catch (CloudException ce)
            {
                Logger.Warn(ce, String.Format("Exception durign retrieval of Web Role RDP files - exception: {0}", ce));
            }
            return null;
        }
Пример #20
0
        private async static Task<OperationResponse> RemoveCloudService(SubscriptionCloudCredentials credentials,
            string serviceName)
        {
            OperationResponse response;

            Console.WriteLine("Removing Cloud Service '{0}'.", serviceName);

            using (var client = new ComputeManagementClient(credentials))
            {
                response = await client.HostedServices.DeleteAllAsync(serviceName);
            }

            return response;
        }
Пример #21
0
        public StoreClient(
            AzureSubscription subscription,
            ComputeManagementClient compute,
            StoreManagementClient store,
            MarketplaceClient marketplace,
            ManagementClient management)
        {
            this.subscriptionId = subscription.Id.ToString();

            computeClient = compute;
            storeClient = store;
            MarketplaceClient = marketplace;
            managementClient = management;
        }
Пример #22
0
        private async static Task<OperationResponse> DeployCloudService(SubscriptionCloudCredentials credentials, string storageAccountName,
            string serviceName)
        {
            Console.WriteLine("Deploying to Cloud Service {0}", serviceName);

            OperationResponse response = null;
            string storageAccountKey = null;

            using (var client = new StorageManagementClient(credentials))
            {
                var keys = await client.StorageAccounts.GetKeysAsync(storageAccountName);
                storageAccountKey = keys.PrimaryKey;
            }

            string storageConnectionString =
                string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", storageAccountName,
                    storageAccountKey);

            CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString);
            CloudBlobClient blobClient = account.CreateCloudBlobClient();
            CloudBlobContainer deploymentContainer = blobClient.GetContainerReference("maml-deployment");
            await deploymentContainer.CreateIfNotExistsAsync();


            CloudBlockBlob deploymentBlob = deploymentContainer.GetBlockBlobReference("AzureCloudService1.cspkg");
            await deploymentBlob.UploadFromFileAsync(@"C:\Projects\Demos\AzureAutomationDemos\AzureAutomation\AzureCloudService1\bin\Release\app.publish\AzureCloudService1.cspkg", FileMode.Open);

            using (var client = new ComputeManagementClient(credentials))
            {
                response = await client.Deployments.CreateAsync(serviceName,
                    DeploymentSlot.Production,
                    new DeploymentCreateParameters
                    {
                        Label = serviceName,
                        Name = serviceName + "Prod",
                        PackageUri = deploymentBlob.Uri,
                        Configuration = File.ReadAllText(@"C:\Projects\Demos\AzureAutomationDemos\AzureAutomation\AzureCloudService1\bin\Release\app.publish\ServiceConfiguration.Cloud.cscfg"),
                        StartDeployment = true
                    });
            }

            return response;
        }
Пример #23
0
        private async static Task<string> CreateCloudService(SubscriptionCloudCredentials credentials)
        {
            Console.WriteLine("Creating new Cloud Service . . .");

            OperationResponse response;

            string name = string.Format("{0}{1}", ResourceName, new Random().Next(1, 200));

            using (var client = new ComputeManagementClient(credentials))
            {
                response = await client.HostedServices.CreateAsync(new HostedServiceCreateParameters
                {
                    ServiceName = name,
                    Location = LocationNames.EastUS,
                    Label = string.Format("{0} Demo Service", ResourceName)
                });
            }

            return name;
        }
        private string GetOsImageUri(string imageName)
        {
            ComputeManagementClient computeClient = new ComputeManagementClient(this.Client.Credentials, this.Client.BaseUri);
            VirtualMachineOSImageGetResponse imageGetResponse = null;
            ErrorRecord er = null;

            try
            {
                imageGetResponse = computeClient.VirtualMachineOSImages.Get(imageName);
            }
            catch (Hyak.Common.CloudException cloudEx)
            {
                // If the image was created in azure with Vm capture, GetOsImageUri won't find that. Don't terminate in this case
                if (cloudEx.Error.Code != "ResourceNotFound")
                {
                    er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                                        cloudEx.Message,
                                        String.Empty,
                                        Client.TemplateImages,
                                        ErrorCategory.InvalidArgument
                                        );

                    ThrowTerminatingError(er);
                }
            }
            catch (Exception ex)
            {
                er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                                        ex.Message,
                                        String.Empty,
                                        Client.TemplateImages,
                                        ErrorCategory.InvalidArgument
                                        );

                ThrowTerminatingError(er);
            }

            if (imageGetResponse != null)
            {
                ValidateImageOsType(imageGetResponse.OperatingSystemType);
                ValidateImageMediaLink(imageGetResponse.MediaLinkUri);

                return imageGetResponse.MediaLinkUri.AbsoluteUri;
            }
            else
            {
                return null;
            }
        }
        private string GetVmImageUri(string imageName)
        {
            ComputeManagementClient computeClient = new ComputeManagementClient(this.Client.Credentials, this.Client.BaseUri);
            VirtualMachineVMImageListResponse vmList = null;
            ErrorRecord er = null;
            string imageUri = null;

            try
            {
                vmList = computeClient.VirtualMachineVMImages.List();
            }
            catch (Exception ex)
            {
                er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                                ex.Message,
                                String.Empty,
                                Client.TemplateImages,
                                ErrorCategory.InvalidArgument
                                );

                ThrowTerminatingError(er);
            }

            foreach (VirtualMachineVMImageListResponse.VirtualMachineVMImage image in vmList.VMImages)
            {
                if (string.Compare(image.Name, imageName, true) == 0)
                {
                    if (image.OSDiskConfiguration != null)
                    {
                        ValidateImageOsType(image.OSDiskConfiguration.OperatingSystem);
                        ValidateImageMediaLink(image.OSDiskConfiguration.MediaLink);

                        imageUri = image.OSDiskConfiguration.MediaLink.AbsoluteUri;
                        break;
                    }
                    else
                    {
                        er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                                string.Format(Commands_RemoteApp.NoOsDiskFoundErrorFormat, imageName),
                                String.Empty,
                                Client.TemplateImages,
                                ErrorCategory.InvalidArgument
                                );

                        ThrowTerminatingError(er);
                    }
                }
            }

            if (imageUri == null)
            {
                er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                                    string.Format(Commands_RemoteApp.NoVmImageFoundErrorFormat, imageName),
                                    String.Empty,
                                    Client.TemplateImages,
                                    ErrorCategory.InvalidArgument
                                    );

                ThrowTerminatingError(er);
            }

            return imageUri;
        }
Пример #26
0
        /// <summary>
        /// Rollback all imported cloud services.
        /// </summary>
        /// <param name="cloudServices">Cloud services to be deleted.</param>
        private void RollBackServices(List<string> cloudServices)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
            Logger.Info(methodName, ProgressResources.ExecutionStarted, ResourceType.CloudService.ToString());
            Logger.Info(methodName, ProgressResources.RollbackCloudServices, ResourceType.CloudService.ToString());
            dcMigrationManager.ReportProgress(ProgressResources.RollbackCloudServices);
            Stopwatch swTotalServices = new Stopwatch();
            swTotalServices.Start();
            //string origServiceName = null;
            if (cloudServices.Count > 0)
            {
                using (var client = new ComputeManagementClient(importParameters.DestinationSubscriptionSettings.Credentials))
                {
                    Parallel.ForEach(cloudServices, cloudService =>
                        {
                            try
                            {
                                Stopwatch swService = new Stopwatch();
                                swService.Start();
                                string origServiceName = resourceImporter.GetSourceResourceName(ResourceType.CloudService, cloudService);
                                Retry.RetryOperation(() => client.HostedServices.DeleteAll(cloudService),
                                    (BaseParameters)importParameters, ResourceType.CloudService, cloudService, ignoreResourceNotFoundEx:true);

                                CloudService service = subscription.DataCenters.FirstOrDefault().CloudServices.
                                    Where(ser => (ser.CloudServiceDetails.ServiceName == origServiceName)).FirstOrDefault();
                                if (service.DeploymentDetails != null)
                                {
                                    string deploymentName = resourceImporter.GetDestinationResourceName(
                                        ResourceType.Deployment, service.DeploymentDetails.Name, ResourceType.CloudService,
                                        resourceImporter.GetDestinationResourceName(ResourceType.CloudService, service.CloudServiceDetails.ServiceName)
                                        );
                                    resourceImporter.UpdateMedatadaFile(ResourceType.Deployment, deploymentName, false,
                                          resourceImporter.GetDestinationResourceName(ResourceType.CloudService, service.CloudServiceDetails.ServiceName)
                                        );
                                    Logger.Info(methodName, string.Format(ProgressResources.RollbackDeployment, service.DeploymentDetails.Name,
                                        service.DeploymentDetails.Name), ResourceType.Deployment.ToString(), service.DeploymentDetails.Name);

                                    foreach (VirtualMachine vm in service.DeploymentDetails.VirtualMachines)
                                    {
                                        string virtualmachineName = resourceImporter.GetDestinationResourceName(
                                        ResourceType.VirtualMachine, vm.VirtualMachineDetails.RoleName, ResourceType.CloudService,
                                        resourceImporter.GetDestinationResourceName(ResourceType.CloudService, service.CloudServiceDetails.ServiceName)
                                        );

                                        resourceImporter.UpdateMedatadaFile(ResourceType.VirtualMachine, virtualmachineName, false,
                                              resourceImporter.GetDestinationResourceName(ResourceType.CloudService, service.CloudServiceDetails.ServiceName)
                                            );
                                        Logger.Info(methodName, string.Format(ProgressResources.RollbackVirtualMachine, vm.VirtualMachineDetails.RoleName),
                                            ResourceType.VirtualMachine.ToString(), vm.VirtualMachineDetails.RoleName);
                                    }
                                }
                                resourceImporter.UpdateMedatadaFile(ResourceType.CloudService, cloudService, false);
                                swService.Stop();
                                Logger.Info(methodName, string.Format(ProgressResources.RollbackCloudService, cloudService,swService.Elapsed.Days, swService.Elapsed.Hours,
                                    swService.Elapsed.Minutes, swService.Elapsed.Seconds), ResourceType.CloudService.ToString(), cloudService);
                            }
                            catch (AggregateException exAgg)
                            {
                                foreach (var ex in exAgg.InnerExceptions)
                                {
                                    Logger.Error(methodName, exAgg, ResourceType.CloudService.ToString(), cloudService);
                                }
                                throw;
                            }
                        });
                    Logger.Info(methodName, ProgressResources.RollbackCloudServicesWaiting, ResourceType.CloudService.ToString());
                    dcMigrationManager.ReportProgress(ProgressResources.RollbackCloudServicesWaiting);
                    Task.Delay(Constants.DelayTimeInMilliseconds_Rollback).Wait();
                }
            }
            swTotalServices.Stop();
            Logger.Info(methodName, string.Format(ProgressResources.ExecutionCompletedWithTime,swTotalServices.Elapsed.Days, swTotalServices.Elapsed.Hours, swTotalServices.Elapsed.Minutes,
                swTotalServices.Elapsed.Seconds), ResourceType.CloudService.ToString());
        }
Пример #27
0
        public DeploymentGetResponse CreateMultivipDeploymentAndAssertSuccess(NetworkManagementClient networkClient, ComputeManagementClient computeClient, List<string> vipNames, string serviceName, string deploymentName, string storageAccountName, string location)
        {
            Utilities.CreateAzureVirtualMachine(computeClient, serviceName, deploymentName,
                            storageAccountName, "blob.core.windows.net");

            DeploymentGetResponse depRetrieved =
                computeClient.Deployments.GetByName(serviceName: serviceName, deploymentName: deploymentName);

            List<ConfigurationSet> endpointCfgSets = new List<ConfigurationSet>
                        {
                            new ConfigurationSet
                            {
                                ConfigurationSetType = "NetworkConfiguration",
                                InputEndpoints =
                                    new List<InputEndpoint>
                                    {
                                        new InputEndpoint()
                                        {
                                            LocalPort = 3387,
                                            Name = "RDP2",
                                            Port = 52777,
                                            Protocol = InputEndpointTransportProtocol.Tcp,
                                            EnableDirectServerReturn = false
                                        },
                                    }
                            }
                        };

            // Update with single endpoint

            var updateParams = Utilities.GetVMUpdateParameters(depRetrieved.Roles.First(),
                storageAccountName, endpointCfgSets, preserveOriginalConfigSets: false);

            computeClient.VirtualMachines.Update(
            serviceName,
            deploymentName,
            depRetrieved.Roles.First().RoleName,
            updateParams);
            int i = 1;
            foreach (var vip in vipNames)
            {
                i++;
                OperationStatusResponse virtualIPCreate =
                           networkClient.VirtualIPs.Add(serviceName: serviceName,
                               deploymentName: deploymentName, virtualIPName: vip);

                Assert.True(virtualIPCreate.StatusCode == HttpStatusCode.OK);

                depRetrieved = Utilities.AssertLogicalVipWithoutIPPresentOrAbsent(computeClient, serviceName: serviceName,
                    deploymentName: deploymentName, virtualIPName: vip, expectedVipCount: i, present: true);

                endpointCfgSets.First().InputEndpoints.Add(
                    new InputEndpoint()
                    {
                        LocalPort = 3387 + i,
                        Name = "RDPS" + i,
                        Port = 52777 + i,
                        Protocol = InputEndpointTransportProtocol.Tcp,
                        EnableDirectServerReturn = false,
                        VirtualIPName = vip
                    });
            }

            updateParams = Utilities.GetVMUpdateParameters(depRetrieved.Roles.First(),
               storageAccountName, endpointCfgSets, preserveOriginalConfigSets: false);

            computeClient.VirtualMachines.Update(
            serviceName,
            deploymentName,
            depRetrieved.Roles.First().RoleName,
            updateParams);

            depRetrieved =
                computeClient.Deployments.GetByName(serviceName: serviceName, deploymentName: deploymentName);

            Assert.NotNull(depRetrieved);
            Assert.NotNull(depRetrieved.VirtualIPAddresses);
            Assert.True(depRetrieved.VirtualIPAddresses.Count == vipNames.Count + 1);
            foreach (var virtualIpAddress in depRetrieved.VirtualIPAddresses)
            {
                Assert.NotNull(virtualIpAddress.Address);
            }
            return depRetrieved;
        }
Пример #28
0
        public StoreClient(
            WindowsAzureSubscription subscription,
            ComputeManagementClient compute,
            StoreManagementClient store,
            MarketplaceClient marketplace,
            ManagementClient management)
        {
            Validate.ValidateStringIsNullOrEmpty(subscription.SubscriptionId, null, true);
            this.subscriptionId = subscription.SubscriptionId;

            computeClient = compute;
            storeClient = store;
            MarketplaceClient = marketplace;
            managementClient = management;
        }
 public VirtualMachineImageHelper(ComputeManagementClient computeClient)
 {
     this.computeClient = computeClient;
 }
Пример #30
0
        internal CloudServiceClient(
            AzureSubscription subscription,
            ManagementClient managementClient,
            StorageManagementClient storageManagementClient,
            ComputeManagementClient computeManagementClient)
            : this((string)null, null, null, null)
        {
            Subscription = subscription;
            CurrentDirectory = null;
            DebugStream = null;
            VerboseStream = null;
            WarningStream = null;

            CloudBlobUtility = new CloudBlobUtility();
            ManagementClient = managementClient;
            StorageClient = storageManagementClient;
            ComputeClient = computeManagementClient;
        }