Beispiel #1
0
        private static void Main(string[] args)
        {
            _subscriptionId    = args[0];
            _thumbprint        = args[1];
            _alertEmailAddress = args[2];
            _cloudServiceName  = args[3];
            _deploymentName    = args[4];

            SubscriptionCloudCredentials credentials = new CertificateCloudCredentials(_subscriptionId,
                                                                                       GetStoreCertificate(_thumbprint));

            var metricsClient = new MetricsClient(credentials);

            var resourceId = ResourceIdBuilder.BuildCloudServiceResourceId(_cloudServiceName, _deploymentName);

            Console.WriteLine("Resource Id: {0}", resourceId);

            GetMetricDefinitions(metricsClient, resourceId);

            var alertsClient = new AlertsClient(credentials);

            DisplayAzureAlertRules(alertsClient);

            var response = CreateAzureAlert(resourceId, alertsClient);

            Console.WriteLine("Create alert rule response: " + response.Result.StatusCode);
            Console.ReadLine();
        }
 public AzureScheduler(X509Certificate2 subscriptionCertificate, string subscriptionId,
                       string cloudServiceName, string jobCollectionName)
 {
     cloudCredentials       = new CertificateCloudCredentials(subscriptionId, subscriptionCertificate);
     this.cloudServiceName  = cloudServiceName;
     this.jobCollectionName = jobCollectionName;
 }
        /// <summary>
        /// Processes the Push-CloudServices commandlet synchronously.
        /// </summary>
        protected override void ProcessRecord()
        {
            var azureSubscription = new AzureSubscription(SettingsPath, SubscriptionId);
            var azureCert         = new X509Certificate2(Convert.FromBase64String(azureSubscription.ManagementCertificate));
            var credentials       = new CertificateCloudCredentials(SubscriptionId, azureCert);

            FlexStreams.UseThreadQueue(ThreadAdapter);

            using (EventStream.Subscribe(e => WriteObject(e.Message)))
                using (var computeClient = new ComputeManagementClient(credentials))
                    using (var storageClient = new StorageManagementClient(credentials))
                    {
                        var targetSlot = VipSwap ? DeploymentSlot.Staging : DeploymentSlot.Production;

                        var storageAccount = storageClient.CreateContainerIfNotExistsAsync(
                            StorageAccountName,
                            StorageContainer,
                            BlobContainerPublicAccessType.Off, SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.List).Result;

                        var blobClient = storageAccount.CreateCloudBlobClient();
                        var container  = blobClient.GetContainerReference(StorageContainer);

                        ProcessAsyncWork(ServiceNames.Select((t, i) => DeployCloudServiceAsync(computeClient, container, t, PackagePaths[i], ConfigurationPaths[i], DiagnosticsConfigurationPaths?[i], targetSlot))
                                         .ToArray());
                    }

            WriteObject("Push-CloudServices completed!");
            base.ProcessRecord();
        }
Beispiel #4
0
        public string SetVm(Subscription Subscription, string VmName, bool SetToRunning)
        {
            CertificateCloudCredentials creds = this.GetCredentials(Subscription);

            using (ComputeManagementClient vmClient = new ComputeManagementClient(creds)) {
                // No idea why it wants the same name again and again or when this name would not be the same

                DeploymentGetResponse response = vmClient.Deployments.GetByName(VmName, VmName);

                if (response.Status != DeploymentStatus.Running && SetToRunning)
                {
                    // Start it
                    vmClient.VirtualMachines.Start(VmName, VmName, VmName);
                }

                if (response.Status == DeploymentStatus.Running && !SetToRunning)
                {
                    // Stop it
                    vmClient.VirtualMachines.Shutdown(
                        VmName, VmName, VmName,
                        new VirtualMachineShutdownParameters {
                        PostShutdownAction = PostShutdownAction.StoppedDeallocated
                    }
                        );
                }

                // What is it now?
                response = vmClient.Deployments.GetByName(VmName, VmName);
                return(response.Status.ToString());
            }
        }
Beispiel #5
0
        public List <AzureInfo> GetServers(Subscription Subscription)
        {
            List <AzureInfo> results = new List <AzureInfo>();

            CertificateCloudCredentials creds = this.GetCredentials(Subscription);

            using (ComputeManagementClient vmClient = new ComputeManagementClient(creds)) {
                List <HostedServiceListResponse.HostedService> vms = vmClient.HostedServices.List().ToList();
                results.AddRange(
                    from vm in vms
                    let vmDetails = vmClient.Deployments.GetByName(vm.ServiceName, vm.ServiceName)
                                    let vmController = vmClient.VirtualMachines.Get(vm.ServiceName, vm.ServiceName, vm.ServiceName)
                                                       select new AzureInfo {
                    SubscriptionId = Subscription.SubscriptionId,
                    Name           = vm.ServiceName,
                    Status         = vmDetails.Status.ToString(),
                    Location       = vm.Properties.Location,
                    Size           = vmController.RoleSize,
                    Online         = vmDetails.Status == DeploymentStatus.Running
                }
                    );
            }

            return(results);
        }
Beispiel #6
0
        public BatchManagementClient GetBatchManagementClient(RecordedDelegatingHandler handler)
        {
            var certCreds = new CertificateCloudCredentials(Guid.NewGuid().ToString(), new System.Security.Cryptography.X509Certificates.X509Certificate2());

            handler.IsPassThrough = false;
            return(new BatchManagementClient(certCreds).WithHandler(handler));
        }
Beispiel #7
0
        private static HttpStatusCode UploadNewManagementCert(string subscriptionId, X509Certificate2 existingCertificate, string newCertificateCerFilePath)
        {
            var statusCode     = HttpStatusCode.Unused;
            var newCertificate = new X509Certificate2(newCertificateCerFilePath);

            var creds  = new CertificateCloudCredentials(subscriptionId, existingCertificate);
            var client = new ManagementClient(creds);

            var parm = new ManagementCertificateCreateParameters()
            {
                Data       = newCertificate.RawData,
                PublicKey  = newCertificate.GetPublicKey(),
                Thumbprint = newCertificate.Thumbprint
            };

            //Hyak throws an exception for a Created result, which is actually  the success code
            try
            {
                var response = client.ManagementCertificates.Create(parm);
            }
            catch (CloudException ex)
            {
                statusCode = ex.Response.StatusCode;
            }

            return(statusCode);
        }
Beispiel #8
0
        /// <summary>
        /// Get the test environment from a connection string specifying a certificate
        /// </summary>
        /// <param name="testConnectionString">The connetcion string to parse</param>
        /// <returns>The test environment from parsing the connection string.</returns>
        protected virtual TestEnvironment GetCertificateTestEnvironmentFromConnectionString(string testConnectionString)
        {
            IDictionary <string, string> connections = ParseConnectionString(testConnectionString);
            string certificateReference = connections[ManagementCertificateKey];
            string subscriptionId       = connections[SubscriptionIdKey];

            Assert.IsNotNull(certificateReference);
            X509Certificate2 managementCertificate;

            if (IsCertificateReference(certificateReference))
            {
                managementCertificate = GetCertificateFromReference(certificateReference);
            }
            else
            {
                managementCertificate = GetCertificateFromBase64String(certificateReference);
            }

            CertificateCloudCredentials credentials        = new CertificateCloudCredentials(subscriptionId, managementCertificate);
            TestEnvironment             currentEnvironment = new TestEnvironment {
                Credentials = credentials
            };

            if (connections.ContainsKey(BaseUriKey))
            {
                currentEnvironment.BaseUri = new Uri(connections[BaseUriKey]);
            }

            return(currentEnvironment);
        }
Beispiel #9
0
        public static SubscriptionCloudCredentials GetCredentialsByPublishSettingFile(string fileName)
        {
            var doc = new XmlDocument( );

            doc.Load(fileName);
            var certNode = doc.SelectSingleNode("/PublishData/PublishProfile/@ManagementCertificate");

            // Some publishsettings files (with multiple subscriptions?) have the management publisherCertificate under the Subscription
            if (certNode == null)
            {
                certNode =
                    doc.SelectSingleNode(
                        "/PublishData/PublishProfile/Subscription/@ManagementCertificate");
            }

            X509Certificate2 ManagementCertificate = new X509Certificate2(Convert.FromBase64String(certNode.Value));
            var subNode =
                doc.SelectSingleNode("/PublishData/PublishProfile/Subscription/@Id");
            string SubscriptionId = subNode.Value;

            // Obtain management via .publishsettings file from https://manage.windowsazure.com/publishsettings/index?schemaversion=2.0
            CertificateCloudCredentials creds = new CertificateCloudCredentials(SubscriptionId, ManagementCertificate);

            return(creds);
        }
        public AzureWebsitesUsageClient(AzureManagementRestClient client, CertificateCloudCredentials credentials)
        {
            var azureWebsiteApiClient = new AzureWebsiteApiClient(client);

            _azureWebsitesInfoClient    = new AzureWebsitesInfoApiClient(azureWebsiteApiClient);
            _azureWebsitesMetricsClient = new AzureWebsitesMetricsApiClient(azureWebsiteApiClient);
            _metricsApiClient           = new AzureMetricsApiClient(credentials);
        }
Beispiel #11
0
        public AzureManagementService(string subscriptionId, string base64Certificate)
        {
            cloudCredentials = new CertificateCloudCredentials(
                subscriptionId,
                new X509Certificate2(Convert.FromBase64String(base64Certificate)));

            storageClient = CloudContext.Clients.CreateStorageManagementClient(cloudCredentials);
            computeClient = CloudContext.Clients.CreateComputeManagementClient(cloudCredentials);
        }
        public static void CreateVMSteps(string message, TextWriter log)
        {
            RootCreateVMObject r = JsonConvert.DeserializeObject <RootCreateVMObject>(message);

            log.WriteLine("Received message to deploy {0}", r.createvm.Service.ServiceName);

            // get the subscription details from configuration
            Subscription sub = Subscriptions.Instance.Get(r.createvm.SubscriptionName);

            if (sub == null)
            {
                string msg = string.Format("Subscription name {0} not found in configuration file.", r.createvm.SubscriptionName);
                Common.LogExit(msg, r.createvm.Service.ServiceName, log);
                return;
            }

            // create credentials object based on management certificate
            CertificateCloudCredentials creds = new CertificateCloudCredentials(sub.SubscriptionId, sub.MgtCertificate);

            // see if the cloud service already exists
            bool nameIsAvailable = Common.CheckServiceNameAvailability(r.createvm.Service.ServiceName, creds);

            // if not and create if not exists, create it.
            if (nameIsAvailable && r.createvm.Service.CreateServiceIfNotExist)
            {
                log.WriteLine("Creating hosted service: {0}", r.createvm.Service.ServiceName);
                HttpStatusCode code = Common.CreateService(creds, r, sub, log);
                log.WriteLine("Code returned from CreateService: {0}", code.ToString());
            }

            bool   deploymentExists = DeploymentExists(creds, r, sub, log);
            string requestId        = null;

            if (deploymentExists)
            {
                requestId = CreateVM(creds, r, sub, log);
            }
            else
            {
                requestId = CreateDeployment(creds, r, sub, log);
            }

            if (string.IsNullOrEmpty(requestId))
            {
                string msg        = string.Format("Creation of VM on service {0} did not succeed.", r.createvm.Service.ServiceName);
                string consoleMsg = string.Format("Creation of VM on service {0} failed.  Check the log for details.", r.createvm.Service.ServiceName);
                Common.LogExit(msg, consoleMsg, r.createvm.Service.ServiceName, log);
                return;
            }
            else
            {
                string msg        = string.Format("Creation of VM on service {0} succeeded with request ID: {1}.", r.createvm.Service.ServiceName, requestId);
                string consoleMsg = string.Format("Creation of VM on service {0} succeeded.  Check the log for details.", r.createvm.Service.ServiceName);
                Common.LogSuccess(msg, consoleMsg, r.createvm.Service.ServiceName, log);
                return;
            }
        }
Beispiel #13
0
        public ScalingAgent(string subscriptionID, string subscriptionManagementCertificateThumbprint, StoreLocation storeLocation)
        {
            X509Certificate2             managementCert = subscriptionManagementCertificateThumbprint.FindX509CertificateByThumbprint(storeLocation);
            SubscriptionCloudCredentials creds          = new CertificateCloudCredentials(subscriptionID, managementCert);

            this.computeManagementClient      = CloudContext.Clients.CreateComputeManagementClient(creds);
            this.storageManagementClient      = CloudContext.Clients.CreateStorageManagementClient(creds);
            this.cloudServiceManagementClient = CloudContext.Clients.CreateCloudServiceManagementClient(creds);
            this.managementClient             = CloudContext.Clients.CreateManagementClient(creds);
        }
Beispiel #14
0
        public override void ExecuteCommand()
        {
            var cred  = new CertificateCloudCredentials(SubscriptionId, ManagementCertificate);
            var csman = CloudContext.Clients.CreateCloudServiceManagementClient(cred);
            var svcs  = csman.CloudServices.ListAsync(CancellationToken.None).Result;

            foreach (var svc in svcs)
            {
                Log.Info("* {0} ({1}): {2}", svc.Name, svc.GeoRegion, svc.Description);
            }
        }
        public ScheduledAutoTestApi(string subscriptionId, X509Certificate2 managementCertificate, IQueue queue, string jobCollectionName, string storageAccountName, string sasToken, int minutesToKeepInCache)
        {
            var credentials = new CertificateCloudCredentials(subscriptionId, managementCertificate);

            _schedulerClient      = new SchedulerClient(CloudService, jobCollectionName, credentials);
            _queue                = queue;
            _storageAccountName   = storageAccountName;
            _sasToken             = sasToken;
            _minutesToKeepInCache = minutesToKeepInCache;
            _needRefresh          = false;
        }
        public static ExpressRouteManagementClient GetProviderExpressRouteManagementClient()
        {
            string managementCertificate = "";
            string baseUri;
            string subscriptionId;

            if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                baseUri               = HttpMockServer.Variables["TEST_PROVIDER_BASE_URI"];
                subscriptionId        = HttpMockServer.Variables["TEST_PROVIDER_SUBSCRIPTION_ID"];
                managementCertificate = HttpMockServer.Variables["TEST_PROVIDER_MANAGEMENT_CERTIFICATE"];
            }
            else
            {
                string publishSettingsFile = Environment.GetEnvironmentVariable("TEST_PUBLISHSETTINGS_FILE_P");
                if (string.IsNullOrEmpty(publishSettingsFile))
                {
                    // Take default path
                    publishSettingsFile = @"C:\Powershell\PublishSettings\defaultProvider.publishsettings";
                }
                PublishData publishData = XmlSerializationHelpers.DeserializeXmlFile <PublishData>(publishSettingsFile);
                managementCertificate = Enumerable.First <PublishDataPublishProfile>((IEnumerable <PublishDataPublishProfile>)publishData.Items).ManagementCertificate;
                if (string.IsNullOrEmpty(managementCertificate))
                {
                    managementCertificate = Enumerable.First <PublishDataPublishProfileSubscription>((IEnumerable <PublishDataPublishProfileSubscription>)Enumerable.First <PublishDataPublishProfile>((IEnumerable <PublishDataPublishProfile>)publishData.Items).Subscription).ManagementCertificate;
                }
                if (string.IsNullOrEmpty(managementCertificate))
                {
                    throw new ArgumentException(string.Format("{0} is not a valid publish settings file, you must provide a valid publish settings file in the environment variable {1}", (object)publishSettingsFile, (object)"TEST_PROVIDER_PUBLISHSETTINGS_FILE"));
                }


                subscriptionId = Enumerable.First <PublishDataPublishProfileSubscription>((IEnumerable <PublishDataPublishProfileSubscription>)Enumerable.First <PublishDataPublishProfile>((IEnumerable <PublishDataPublishProfile>)publishData.Items).Subscription).Id;

                baseUri = Enumerable.First <PublishDataPublishProfileSubscription>(
                    (IEnumerable <PublishDataPublishProfileSubscription>)
                    Enumerable.First <PublishDataPublishProfile>(
                        (IEnumerable <PublishDataPublishProfile>)publishData.Items).Subscription)
                          .ServiceManagementUrl ?? publishData.Items[0].Url;

                HttpMockServer.Variables["TEST_PROVIDER_MANAGEMENT_CERTIFICATE"] = managementCertificate;
                HttpMockServer.Variables["TEST_PROVIDER_SUBSCRIPTION_ID"]        = subscriptionId;
                HttpMockServer.Variables["TEST_PROVIDER_BASE_URI"] = baseUri;
            }

            var credentials = new CertificateCloudCredentials(subscriptionId, new X509Certificate2(Convert.FromBase64String(managementCertificate), string.Empty));
            var client      = new ExpressRouteManagementClient(credentials, new Uri(baseUri));

            client.AddHandlerToPipeline(HttpMockServer.CreateInstance());
            return(client);
        }
        public void ManagementClientReturnsLocationList()
        {
            // Import certificate
            CertificateEnrollmentManager.ImportPfxDataAsync(_certificateString, _certificatePassword, ExportOption.NotExportable,
                                                                KeyProtectionLevel.NoConsent, InstallOptions.None,
                                                                "test").AsTask().Wait();

            var credentials = new CertificateCloudCredentials(_subscription);
            var client = new ManagementClient(credentials);
            var result = client.Locations.List();

            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.IsTrue(result.Locations.Count > 0);
        }
        public void ManagementClientReturnsLocationList()
        {
            // Import certificate
            CertificateEnrollmentManager.ImportPfxDataAsync(_certificateString, _certificatePassword, ExportOption.NotExportable,
                                                            KeyProtectionLevel.NoConsent, InstallOptions.None,
                                                            "test").AsTask().Wait();

            var credentials = new CertificateCloudCredentials(_subscription);
            var client      = new ManagementClient(credentials);
            var result      = client.Locations.List();

            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.IsTrue(result.Locations.Count > 0);
        }
        public override void ExecuteCommand()
        {
            var cred   = new CertificateCloudCredentials(SubscriptionId, ManagementCertificate);
            var csman  = CloudContext.Clients.CreateCloudServiceManagementClient(cred);
            var result = csman.CloudServices.CreateAsync(
                Arguments[0], new CloudServiceCreateParameters()
            {
                Label       = Label,
                GeoRegion   = Region,
                Email       = Email,
                Description = Description
            }, CancellationToken.None).Result;

            Log.Info("Created Cloud Service {0}", Arguments[0]);
        }
Beispiel #20
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);
        }
Beispiel #21
0
        public static void StartRolesSteps(string message, TextWriter log)
        {
            RootStartVMsObject r = JsonConvert.DeserializeObject <RootStartVMsObject>(message);

            log.WriteLine("Received message to start VM(s) on service {0}", r.startvms.Service.ServiceName);

            // get the subscription details from configuration
            Subscription sub = Subscriptions.Instance.Get(r.startvms.SubscriptionName);

            if (sub == null)
            {
                string msg = string.Format("Subscription name {0} not found in configuration file.",
                                           r.startvms.SubscriptionName);
                Common.LogExit(msg, r.startvms.Service.ServiceName, log);
                return;
            }

            // create credentials object based on management certificate
            CertificateCloudCredentials creds = new CertificateCloudCredentials(sub.SubscriptionId, sub.MgtCertificate);

            // see if the cloud service exists
            bool nameIsAvailable = Common.CheckServiceNameAvailability(r.startvms.Service.ServiceName, creds);

            // if so, nothing to do.
            if (nameIsAvailable)
            {
                log.WriteLine("Hosted service {0} does not exist.  Nothing to do.", r.startvms.Service.ServiceName);
                return;
            }

            string requestId = StartVMs(creds, r, sub, log);

            if (string.IsNullOrEmpty(requestId))
            {
                string msg        = string.Format("Start of VMs on service {0} did not succeed.", r.startvms.Service.ServiceName);
                string consoleMsg = string.Format("Start of VMs on service {0} failed.  Check the log for details.", r.startvms.Service.ServiceName);
                Common.LogExit(msg, consoleMsg, r.startvms.Service.ServiceName, log);
                return;
            }
            else
            {
                string msg        = string.Format("Start of VMs on service {0} succeeded with request ID: {1}.", r.startvms.Service.ServiceName, requestId);
                string consoleMsg = string.Format("Start of VMs on service {0} succeeded.  Check the log for details.", r.startvms.Service.ServiceName);
                Common.LogSuccess(msg, consoleMsg, r.startvms.Service.ServiceName, log);
                return;
            }
        }
Beispiel #22
0
        private async Task <Dictionary <string, string> > ListStorageAccounts()
        {
            Dictionary <string, string> accountDictionary = new Dictionary <string, string>();

            CertificateCloudCredentials creds    = new CertificateCloudCredentials(_id, _certificate);
            StorageManagementClient     client   = new StorageManagementClient(creds);
            StorageAccountListResponse  accounts = await client.StorageAccounts.ListAsync();

            foreach (var account in accounts)
            {
                StorageAccountGetKeysResponse keys = await client.StorageAccounts.GetKeysAsync(account.Name);

                accountDictionary.Add(account.Name, keys.PrimaryKey);
            }

            return(accountDictionary);
        }
        static void Main(string[] args)
        {
            var credential = new CertificateCloudCredentials(SubscriptionId, cert);

            _WebSiteClient = new WebSiteManagementClient(credential);
            var web = _WebSiteClient.WebSites.Get(webspace, websitename, null).WebSite;

            web.HostNames.Add("www.example.com");
            var updates = new WebSiteUpdateParameters {
                HostNames  = web.HostNames,
                ServerFarm = web.ServerFarm,
                State      = web.State
            };

            _WebSiteClient.WebSites.Update(webspaces, websitename, updates);
            System.Console.WriteLine("Press ENTER to continue");
            System.Console.ReadLine();
        }
 public static void QueryRegisteredSchedulerProperties(CertificateCloudCredentials credentials)
 {
     try
     {
         var schedulerServiceClient = new SchedulerManagementClient(credentials);
         var result3 = schedulerServiceClient.GetResourceProviderProperties();
         foreach (var prop in result3.Properties)
         {
             Console.WriteLine("QueryRegisteredSchedulerProperties :\n" + prop.Key + ": " + prop.Value);
         }
         Console.ReadLine();
     }
     catch (Exception e)
     {
         Console.WriteLine("QueryRegisteredSchedulerProperties Exception :\n" + e.Message);
         throw;
     }
 }
Beispiel #25
0
 private static string DeleteService(CertificateCloudCredentials creds, RootDeleteServiceObject r, Subscription sub, TextWriter log)
 {
     try
     {
         using (var client = new ComputeManagementClient(creds))
         {
             OperationResponse resp = client.HostedServices.Delete(
                 r.deleteservice.Service.ServiceName);
             return(resp.RequestId);
         }
     }
     catch (Exception ex)
     {
         // get a 404 if the cloud service doesn't exist
         string msg = string.Format("Exception deleting service: {0}", ex.Message);
         Common.LogExit(msg, r.deleteservice.Service.ServiceName, log);
         return(null);
     }
 }
        /// <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);
        }
Beispiel #27
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);
        }
Beispiel #28
0
        private static void Main(String[] args)
        {
            var subscription = " "; //oc
            var credentials  = new CertificateCloudCredentials(subscription, GetCertificate());


            using (var computeManagementClient = new ComputeManagementClient(credentials, new Uri("https://management.core.windows.net")))
            {
                //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://management.core.windows.net/" + subscription + "/services/hostedservices");
                //request.ClientCertificates.Add(GetCertificate());
                //request.Headers.Add("x-ms-version", "2015-04-01");
                //request.ContentType = "application/xml";
                //var response = request.GetResponse();
                //var responseStream = response.GetResponseStream();


                var services = computeManagementClient.HostedServices.List();
                foreach (var item in services)
                {
                    var serviceDetail = computeManagementClient.HostedServices.GetDetailed(item.ServiceName);

                    var deployments = new List <HostedServiceGetDetailedResponse.Deployment>();
                    foreach (var deployment in serviceDetail.Deployments)
                    {
                        var tempDeployment = new HostedServiceGetDetailedResponse.Deployment
                        {
                            DeploymentSlot = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), deployment.DeploymentSlot.ToString()), RoleInstances = new List <RoleInstance>()
                        };
                        foreach (var roleInstance in deployment.RoleInstances)
                        {
                        }
                        tempDeployment.Roles = new List <Role>();
                        foreach (var role in deployment.Roles)
                        {
                        }
                        tempDeployment.Status = (DeploymentStatus)Enum.Parse(typeof(DeploymentStatus), deployment.Status.ToString());
                        deployments.Add(tempDeployment);
                    }
                }
            }
        }
        public static void RegisterScheduleResourceProvider(CertificateCloudCredentials credentials)
        {
            var schedulerServiceClient = new SchedulerManagementClient(credentials);

            try
            {
                var result2 = schedulerServiceClient.RegisterResourceProvider();

                Console.WriteLine("RegisterScheduleResourceProvider :\n" + result2.RequestId);
                Console.WriteLine("RegisterScheduleResourceProvider :\n" + result2.StatusCode);
                Console.ReadLine();
            }
            catch (CloudException exc)
            {
                if (exc.Response.StatusCode != HttpStatusCode.Conflict)
                {
                    Console.WriteLine("RegisterScheduleResourceProvider Exception :\n" + exc.Message);
                    throw;
                }
            }
        }
Beispiel #30
0
        public SubscriptionCloudCredentials GetManagementCredentials()
        {
            var subscription = ActiveSubscription;

            var settings = new Dictionary <string, object>
            {
                { "SubscriptionId", subscription.SubscriptionId },
                { "ManagementCertificate", subscription.ManagementCertificate.Thumbprint ?? subscription.ManagementCertificate.Base64Data }
            };

            var credentials = CertificateCloudCredentials.Create(settings);

            if (credentials == null)
            {
                var message = String.Format("The Subscription for '{0}' did not have valid subscription details configured.", subscription.Name);
                _logger.ErrorFormat(message);
                throw new CredentialException(message);
            }

            return(credentials);
        }
Beispiel #31
0
        private static X509Certificate2 GetExistingManagementCertificate(string subscriptionId)
        {
            var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            certStore.Open(OpenFlags.ReadOnly);
            var azureCerts = certStore.Certificates.Find(X509FindType.FindByIssuerName, "Windows Azure Tools", false);

            foreach (var cert in azureCerts)
            {
                var creds  = new CertificateCloudCredentials(subscriptionId, cert);
                var client = new ManagementClient(creds);
                try
                {
                    var v = client.Locations.List();
                    return(cert);
                }
                catch (CloudException)
                { }
            }

            return(null);
        }
        public static CertificateCloudCredentials GetCredentialsByPublishSettingFile(string fileName)
        {
            var doc = new XmlDocument( );
            doc.Load( fileName );
            var certNode = doc.SelectSingleNode( "/PublishData/PublishProfile/@ManagementCertificate" );
            // Some publishsettings files (with multiple subscriptions?) have the management publisherCertificate under the Subscription
            if( certNode == null )
            {
                certNode =
                doc.SelectSingleNode(
                    "/PublishData/PublishProfile/Subscription/@ManagementCertificate" );
            }

            X509Certificate2 ManagementCertificate = new X509Certificate2( Convert.FromBase64String( certNode.Value ) );
            var subNode =
                doc.SelectSingleNode( "/PublishData/PublishProfile/Subscription/@Id" );
            string SubscriptionId = subNode.Value;

            // Obtain management via .publishsettings file from https://manage.windowsazure.com/publishsettings/index?schemaversion=2.0
            CertificateCloudCredentials creds = new CertificateCloudCredentials( SubscriptionId, ManagementCertificate );
            return creds;
        }
Beispiel #33
0
        public override void ExecuteCommand()
        {
            var cred   = new CertificateCloudCredentials(SubscriptionId, ManagementCertificate);
            var schman = CloudContext.Clients.CreateSchedulerManagementClient(cred);

            var createParams = new JobCollectionCreateParameters()
            {
                Label             = Label,
                IntrinsicSettings = new JobCollectionIntrinsicSettings()
                {
                    Plan  = Plan,
                    Quota = new JobCollectionQuota()
                    {
                        MaxJobCount      = MaxJobCount,
                        MaxJobOccurrence = MaxJobOccurrence,
                        MaxRecurrence    = MaxRecurrenceFrequency.HasValue ? new JobCollectionMaxRecurrence()
                        {
                            Frequency = MaxRecurrenceFrequency.Value,
                            Interval  = MaxRecurrenceInterval.Value
                        } : null
                    }
                }
            };

            if (WhatIf)
            {
                Log.Info("Would create job collection {0} in {1} with the following params:", Arguments[0], CloudService);
                Log.Info(JsonConvert.SerializeObject(createParams, new StringEnumConverter()));
            }
            else
            {
                Log.Info("Creating job collection {0} in {1}...", Arguments[0], CloudService);
                schman.JobCollections.CreateAsync(
                    CloudService,
                    Arguments[0],
                    createParams,
                    CancellationToken.None).Wait();
            }
        }
        // Entrypoint and main method
        static void Main(string[] args)
        {
            // The azure subscription id
            SubscriptionId = "{subscriptionId}";

            // Management Certificate thumbprint
            CertificateThumbprint = "{thumbprint}";

            // Creates credentials / Management operations require the X509Certificate2 type
            CertificateCloudCredentials credential = new CertificateCloudCredentials(SubscriptionId, GetStoreCertificate(CertificateThumbprint));

            using (var computeClient = new ComputeManagementClient(credential))
            {
                //Gets a list of Cloud Services inside the Subscription
                var myCloudServices = computeClient.HostedServices.List();

                // Loops the the HostedServices object
                foreach (HostedServiceListResponse.HostedService cs in myCloudServices)
                {
                    // Prints every Cloud Service found
                    Console.WriteLine(cs.ServiceName);
                }

                // Gets a specific Cloud Service
                var result = computeClient.HostedServices.GetDetailed("{cloud-service-name}");
                var productionDeployment = result.Deployments.Where(d => d.DeploymentSlot == DeploymentSlot.Production).FirstOrDefault();

                // Prints a specific Cloud Service Details
                Console.WriteLine("Service Name: " + result.ServiceName);
                Console.WriteLine("Status: " + productionDeployment.Status);
                Console.WriteLine("Public IP address: " + productionDeployment.VirtualIPAddresses[0].Address);
                Console.WriteLine("Deployment name: " + productionDeployment.Name);
                Console.WriteLine("Deployment label: " + productionDeployment.Label);
                Console.WriteLine("Deployment ID: " + productionDeployment.PrivateId);
            }
            Console.WriteLine("press any key to exit...");
            Console.ReadKey();
        }
Beispiel #35
0
        /// <summary>
        /// Validates and converts input parameters into <see cref="ExportParameters"/> class.
        /// </summary>
        /// <param name="parameters">Collection of input parameters stored in key value pairs 
        /// <example> Operation "Export" SourceSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" SourceDCName "East Asia" 
        /// ExportMetadataFolderPath "D:\\DataCenterMigration" SourcePublishSettingsFilePath  "D:\\PublishSettings.PublishSettings"
        /// QuietMode "True" </example> </param>
        /// <returns>Parameters required for export functionality</returns>
        internal static ExportParameters ValidateAndConvertExportParameters(IDictionary<string, string> parameters)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            Logger.Info(methodName, ProgressResources.ExecutionStarted);
            Logger.Info(methodName, ProgressResources.ParameterValidationStarted);

            #region Check for missing required parameters
            // PublishSettingsFilePath / CertificateThumbprint
            if (!parameters.Keys.Contains(Constants.Parameters.SourcePublishSettingsFilePath) && !parameters.Keys.Contains(
                Constants.Parameters.SourceCertificateThumbprint))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Source,
                    Constants.AppConfigArguments));
            }

            // ExportMetadataFolderPath
            if (!parameters.Keys.Contains(Constants.Parameters.ExportMetadataFolderPath))
            {
                throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                    Constants.Parameters.ExportMetadataFolderPath, Constants.AppConfigArguments));
            }
            // SourceSubscriptionID
            if (!parameters.Keys.Contains(Constants.Parameters.SourceSubscriptionID))
            {
                throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                Constants.Parameters.SourceSubscriptionID, Constants.AppConfigArguments));
            }

            // SourceDCName
            if (!parameters.Keys.Contains(Constants.Parameters.SourceDCName))
            {
                throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                    Constants.Parameters.SourceDCName, Constants.AppConfigArguments));
            }

            #endregion

            #region Check for null or empty values

            // PublishSettingsFilePath
            if ((parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath) && string.IsNullOrEmpty(parameters[Constants.Parameters.SourcePublishSettingsFilePath]))
                   || (parameters.ContainsKey(Constants.Parameters.SourceCertificateThumbprint) && string.IsNullOrEmpty(parameters[Constants.Parameters.SourceCertificateThumbprint])))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Source, Constants.AppConfigArguments));
            }

            // ExportMetadataFolderPath
            if (string.IsNullOrEmpty(parameters[Constants.Parameters.ExportMetadataFolderPath]))
            {
                throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.ExportMetadataFolderPath));
            }
            //// SourceSubscriptionID
            if (string.IsNullOrEmpty(parameters[Constants.Parameters.SourceSubscriptionID]))
            {
                throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.SourceSubscriptionID));
            }

            //// SourceDCName
            if (string.IsNullOrEmpty(parameters[Constants.Parameters.SourceDCName]))
            {
                throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.SourceDCName));
            }

            #endregion

            #region Validate parameter's value

            // Validate PublishSettingsFilePath 
            if (parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath) && !File.Exists(parameters[Constants.Parameters.SourcePublishSettingsFilePath]))
            {
                throw new ValidationException(string.Format(StringResources.InvalidParameterValue, Constants.Parameters.SourcePublishSettingsFilePath),
                    new FileNotFoundException(StringResources.PublishSettingsFilePathParamException));
            }

            // Validate ExportMetadataFolderPath
            string folderPath = parameters[Constants.Parameters.ExportMetadataFolderPath];

            if (!Directory.Exists(parameters[Constants.Parameters.ExportMetadataFolderPath]))
            {
                throw new ValidationException(string.Format(StringResources.InvalidParameterValue, Constants.Parameters.ExportMetadataFolderPath),
                    new DirectoryNotFoundException(StringResources.ExportMetadataFolderPathParamException));
            }

            int retryCount;
            Double minBackOff;
            Double maxBackOff;
            Double deltaBackOff;
            bool generateMapperXmlValue;

            if (!parameters.Keys.Contains(Constants.Parameters.RetryCount))
            {
                retryCount = Int32.Parse(Constants.RetryCountDefault);
            }
            else
            {
                Int32.TryParse(parameters[Constants.Parameters.RetryCount], out retryCount);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.MinBackoff))
            {
                minBackOff = Double.Parse(Constants.MinBackoffDefault);
            }
            else
            {
                Double.TryParse(parameters[Constants.Parameters.MinBackoff], out minBackOff);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.MaxBackoff))
            {
                maxBackOff = Double.Parse(Constants.MaxBackoffDefault);
            }
            else
            {
                Double.TryParse(parameters[Constants.Parameters.MaxBackoff], out maxBackOff);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.DeltaBackoff))
            {
                deltaBackOff = Double.Parse(Constants.DeltaBackoffDefault);
            }
            else
            {
                Double.TryParse(parameters[Constants.Parameters.DeltaBackoff], out deltaBackOff);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.GenerateMapperXml))
            {
                generateMapperXmlValue = false;
            }
            else
            {
                bool.TryParse(parameters[Constants.Parameters.GenerateMapperXml], out generateMapperXmlValue);
            }

            // Validate SourceSubscriptionID
            PublishSettings publishSettingsFile = null;
            PublishSetting subscription = null;
            if (parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath))
            {
                try
                {
                    var fileContents = File.ReadAllText(parameters[Constants.Parameters.SourcePublishSettingsFilePath]);
                    publishSettingsFile = new PublishSettings(fileContents);
                }
                catch (Exception xmlEx)
                {
                    throw new ValidationException(string.Format(StringResources.XMLParsingException + " =>" + xmlEx.Message,
                        parameters[Constants.Parameters.SourcePublishSettingsFilePath]));
                }

                // Check whether subscriptionId exists in publish settings file
                subscription = publishSettingsFile.Subscriptions.FirstOrDefault(a =>
                    string.Compare(a.Id, parameters[Constants.Parameters.SourceSubscriptionID], StringComparison.InvariantCultureIgnoreCase) == 0);
                if (subscription == null)
                {
                    throw new ValidationException(string.Format(StringResources.SubscriptionIdParamException,
                        parameters[Constants.Parameters.SourceSubscriptionID], parameters[Constants.Parameters.SourcePublishSettingsFilePath]));
                }
            }
            else
            {
                string thumbprint = parameters[Constants.Parameters.SourceCertificateThumbprint];
                X509Certificate2 certificate = GetStoreCertificate(thumbprint);
                if (!certificate.HasPrivateKey)
                {
                    throw new ValidationException(string.Format(
                        StringResources.MissingPrivateKeyInCertificate, StringResources.Source, thumbprint));
                }
                var sourceCredentials = new CertificateCloudCredentials(parameters[Constants.Parameters.SourceSubscriptionID],
                      certificate);
                string sourceSubscriptionName = null;
                using (var client = new ManagementClient(sourceCredentials))
                {
                    BaseParameters baseParams = new BaseParameters()
                    {
                        RetryCount = retryCount,
                        MinBackOff = TimeSpan.FromSeconds(minBackOff),
                        MaxBackOff = TimeSpan.FromSeconds(maxBackOff),
                        DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff)
                    };
                    SubscriptionGetResponse subscriptionResponse = Retry.RetryOperation(() => client.Subscriptions.Get(),
                       baseParams, ResourceType.None);
                    sourceSubscriptionName = subscriptionResponse.SubscriptionName;
                }
                subscription = new PublishSetting()
                {
                    Id = parameters[Constants.Parameters.SourceSubscriptionID],
                    Name = sourceSubscriptionName,
                    ServiceUrl = new Uri(Constants.ServiceManagementUrlValue),
                    Credentials = sourceCredentials
                };
            }

            List<string> locations = ExportDataCenterLocations(subscription.Credentials, retryCount, minBackOff, maxBackOff, deltaBackOff);
            //// Check whether SourceDc name exists in subscription
            bool sourceLocationNamePresent = locations.Any((l => string.Compare(l, parameters[Constants.Parameters.SourceDCName],
                StringComparison.CurrentCultureIgnoreCase) == 0));

            if (!sourceLocationNamePresent)
            {
                throw new ValidationException(string.Format(StringResources.DCParamException, parameters[Constants.Parameters.SourceDCName]));
            }

            Logger.Info(methodName, ProgressResources.ParametersValidationCompleted);

            #endregion

            // Stores validated parameters in class.
            ExportParameters exportParams = new ExportParameters()
            {
                SourceDCName = parameters[Constants.Parameters.SourceDCName],
                ExportMetadataFolderPath = Path.Combine(parameters[Constants.Parameters.ExportMetadataFolderPath],
                    string.Format(Constants.MetadataFileName, parameters[Constants.Parameters.SourceDCName],
                    DateTime.Now.ToString(Constants.ExportMetadataFileNameFormat))),
                SourceSubscriptionSettings = subscription,
                RetryCount = retryCount,
                MinBackOff = TimeSpan.FromSeconds(minBackOff),
                MaxBackOff = TimeSpan.FromSeconds(maxBackOff),
                DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff),
                GenerateMapperXml = generateMapperXmlValue,
                DestinationPrefixName = parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName) ?
                                        parameters[Constants.Parameters.DestinationPrefixName].ToLower() : Constants.DestinationPrefixValue,
                MigrateDeallocatedVms = parameters[Constants.Parameters.MigrateDeallocatedVms]
            };
            return exportParams;
        }
Beispiel #36
0
        /// <summary>
        /// Validates and converts input parameters into <see cref="ImportParameters"/> class.
        /// </summary>
        /// <param name="parameters">Collection of input parameters stored in key value pairs 
        /// <example> Operation "Import" SourceSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" 
        /// DestinationSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" DestinationDCName "West US" 
        /// SourcePublishSettingsFilePath "D:\\PublishSettings.PublishSettings" 
        /// DestinationPublishSettingsFilePath "D:\\PublishSettings.PublishSettings" 
        /// ImportMetadataFilePath "D:\\DataCenterMigration\mydata.json" DestinationPrefixName "dc" QuietMode "True" 
        /// RollBackOnFailure "True" ResumeImport "True" </example> </param>
        /// <param name="validateForImport">True if the function will be called for import functionality. 
        /// False if it is called for Migrate functionality</param>
        /// <returns>Parameters required for import functionality</returns>
        internal static ImportParameters ValidateAndConvertImportParameters(IDictionary<string, string> parameters,
            bool validateForImport)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
            Logger.Info(methodName, ProgressResources.ExecutionStarted);
            Logger.Info(methodName, ProgressResources.ParameterValidationStarted);

            #region Check for missing required parameters
            // SourcePublishSettingsFilePath/ CertificateThumbprint            
            if (!parameters.Keys.Contains(Constants.Parameters.SourcePublishSettingsFilePath) && !parameters.Keys.Contains(Constants.Parameters.SourceCertificateThumbprint))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Source, Constants.AppConfigArguments));
            }

            // DestinationPublishSettingsFilePath
            if (!parameters.Keys.Contains(Constants.Parameters.DestinationPublishSettingsFilePath) && !parameters.Keys.Contains(Constants.Parameters.DestinationCertificateThumbprint))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Destination, Constants.AppConfigArguments));
            }

            // SourceSubscriptionID
            if (!parameters.Keys.Contains(Constants.Parameters.SourceSubscriptionID))
            {
                throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                    Constants.Parameters.SourceSubscriptionID, Constants.AppConfigArguments));
            }

            // DestinationSubscriptionID
            if (!parameters.Keys.Contains(Constants.Parameters.DestinationSubscriptionID))
            {
                throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                    Constants.Parameters.DestinationSubscriptionID, Constants.AppConfigArguments));
            }

            // DestinationDCName
            if (!parameters.Keys.Contains(Constants.Parameters.DestinationDCName))
            {
                throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                    Constants.Parameters.DestinationDCName, Constants.AppConfigArguments));
            }

            ////DestinationPrefixName & MapperXmlFilePath.
            if (!validateForImport)
            {
                if (!parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName))
                {
                    throw new ValidationException(string.Format(StringResources.MissingRequiredParameter,
                        Constants.Parameters.DestinationPrefixName, Constants.AppConfigArguments));
                }
            }
            else
            {
                if (!parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName) &&
                    !parameters.Keys.Contains(Constants.Parameters.MapperXmlFilePath))
                {
                    throw new ValidationException(string.Format(StringResources.MissingMapperAndPrefix,
                       StringResources.Destination, Constants.AppConfigArguments));
                }
            }

            #endregion

            #region Check for null or empty values
            ////SourcePublishSettingsFilePath            
            if ((parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath) && string.IsNullOrEmpty(parameters[Constants.Parameters.SourcePublishSettingsFilePath]))
                  || (parameters.ContainsKey(Constants.Parameters.SourceCertificateThumbprint) && string.IsNullOrEmpty(parameters[Constants.Parameters.SourceCertificateThumbprint])))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Source, Constants.AppConfigArguments));
            }

            // DestinationPublishSettingsFilePath
            if ((parameters.ContainsKey(Constants.Parameters.DestinationPublishSettingsFilePath) && string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationPublishSettingsFilePath]))
                  || (parameters.ContainsKey(Constants.Parameters.DestinationCertificateThumbprint) && string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationCertificateThumbprint])))
            {
                throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Destination, Constants.AppConfigArguments));
            }

            // ImportMetadataFilePath
            if (validateForImport && (string.IsNullOrEmpty(parameters[Constants.Parameters.ImportMetadataFilePath])))
            {
                throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter,
                    Constants.Parameters.ImportMetadataFilePath));
            }
            //// DestinationSubscriptionID
            if (string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationSubscriptionID]))
            {
                throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter,
                    Constants.Parameters.DestinationSubscriptionID));
            }

            //// DestinationDCName
            if (string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationDCName]))
            {
                throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.DestinationDCName));
            }

            ////DestinationPrefixName & MapperXmlFilePath.
            if (!validateForImport)
            {
                if (string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationPrefixName]))
                {
                    throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.DestinationPrefixName));
                }
            }
            else
            {
                if ((parameters.ContainsKey(Constants.Parameters.DestinationPrefixName) &&
                    string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationPrefixName])) ||
                    (parameters.ContainsKey(Constants.Parameters.MapperXmlFilePath)
                    && string.IsNullOrEmpty(parameters[Constants.Parameters.MapperXmlFilePath])))
                {
                    throw new ValidationException(string.Format(StringResources.MissingMapperAndPrefix,
                       StringResources.Destination, Constants.AppConfigArguments));
                }
            }

            #endregion

            #region Validate parameter's value.

            // Validate SourcePublishSettingsFilePath 
            if ((parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath) && !File.Exists(parameters[Constants.Parameters.SourcePublishSettingsFilePath])))
            {
                throw new ValidationException(string.Format(StringResources.InvalidParameterValue,
                    Constants.Parameters.SourcePublishSettingsFilePath),
                    new FileNotFoundException(StringResources.PublishSettingsFilePathParamException));
            }

            // Validate DestinationPublishSettingsFilePath 
            if ((parameters.ContainsKey(Constants.Parameters.DestinationPublishSettingsFilePath) && !File.Exists(parameters[Constants.Parameters.DestinationPublishSettingsFilePath])))
            {
                throw new ValidationException(string.Format(StringResources.InvalidParameterValue,
                    Constants.Parameters.DestinationPublishSettingsFilePath),
                    new FileNotFoundException(StringResources.PublishSettingsFilePathParamException));
            }

            string importMapperXmlFilePath = string.Empty;
            string destinationPrefix = string.Empty;
            //// Validate MapperXmlFilePath if provided
            if (validateForImport && parameters.ContainsKey(Constants.Parameters.MapperXmlFilePath))
            {
                importMapperXmlFilePath = parameters[Constants.Parameters.MapperXmlFilePath];

                if (!File.Exists(importMapperXmlFilePath))
                {
                    throw new ValidationException(string.Format(StringResources.InvalidParameterValue,
                        Constants.Parameters.MapperXmlFilePath),
                        new FileNotFoundException(StringResources.MapperFilePathParamException));
                }
                if (!Path.GetExtension(importMapperXmlFilePath).Equals(Constants.MapperFileExtension, StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new ValidationException(string.Format(StringResources.InvalidExtensionMapperFile,
                        Constants.Parameters.MapperXmlFilePath),
                        new FileNotFoundException(StringResources.MapperFilePathParamException));
                }
            }
            destinationPrefix = parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName) ?
                                    parameters[Constants.Parameters.DestinationPrefixName].ToLower() :
                                    Constants.DestinationPrefixValue;

            // Validate ImportMetadataFilePath
            if (validateForImport)
            {
                if (!string.IsNullOrEmpty(parameters[Constants.Parameters.ImportMetadataFilePath]))
                {
                    string filePath = parameters[Constants.Parameters.ImportMetadataFilePath];

                    if (!File.Exists(filePath))
                    {
                        throw new ValidationException(string.Format(StringResources.InvalidParameterValue,
                            Constants.Parameters.ImportMetadataFilePath),
                            new FileNotFoundException(StringResources.ImportMetadataFilePathParamException));
                    }
                    if (!Path.GetExtension(filePath).Equals(Constants.MetadataFileExtension, StringComparison.InvariantCultureIgnoreCase))
                    {
                        throw new ValidationException(string.Format(StringResources.InvalidExtensionMetadataFile,
                            Constants.Parameters.ImportMetadataFilePath),
                            new FileNotFoundException(StringResources.ImportMetadataFilePathParamException));
                    }
                }
            }

            bool rollBackBoolValue;
            bool resumeImportBoolValue;
            int retryCount;
            Double minBackOff;
            Double maxBackOff;
            Double deltaBackOff;

            if (!parameters.Keys.Contains(Constants.Parameters.RollBackOnFailure))
            {
                rollBackBoolValue = false;
            }
            else
            {
                bool.TryParse(parameters[Constants.Parameters.RollBackOnFailure], out rollBackBoolValue);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.ResumeImport))
            {
                resumeImportBoolValue = false;
            }
            else
            {
                bool.TryParse(parameters[Constants.Parameters.ResumeImport], out resumeImportBoolValue);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.RetryCount))
            {
                retryCount = Int32.Parse(Constants.RetryCountDefault);
            }
            else
            {
                Int32.TryParse(parameters[Constants.Parameters.RetryCount], out retryCount);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.MinBackoff))
            {
                minBackOff = Double.Parse(Constants.MinBackoffDefault);
            }
            else
            {
                Double.TryParse(parameters[Constants.Parameters.MinBackoff], out minBackOff);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.MaxBackoff))
            {
                maxBackOff = Double.Parse(Constants.MaxBackoffDefault);
            }
            else
            {
                Double.TryParse(parameters[Constants.Parameters.MaxBackoff], out maxBackOff);
            }

            if (!parameters.Keys.Contains(Constants.Parameters.DeltaBackoff))
            {
                deltaBackOff = Double.Parse(Constants.DeltaBackoffDefault);
            }
            else
            {
                Double.TryParse(parameters[Constants.Parameters.DeltaBackoff], out deltaBackOff);
            }
            // Validate SourcePublishSettings File
            PublishSettings sourcePublishSettingsFile = null;
            PublishSetting sourceSubscription = null;

            if (parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath))
            {
                try
                {
                    var fileContents = File.ReadAllText(parameters[Constants.Parameters.SourcePublishSettingsFilePath]);
                    sourcePublishSettingsFile = new PublishSettings(fileContents);
                }
                catch (Exception xmlEx)
                {
                    throw new ValidationException(string.Format(StringResources.XMLParsingException + " =>" + xmlEx.Message,
                        parameters[Constants.Parameters.SourcePublishSettingsFilePath]));
                }

                // Check whether sourceSubscriptionId exists in publish settings file
                sourceSubscription = sourcePublishSettingsFile.Subscriptions.FirstOrDefault(a =>
                    string.Compare(a.Id, parameters[Constants.Parameters.SourceSubscriptionID], StringComparison.InvariantCultureIgnoreCase) == 0);
                if (sourceSubscription == null)
                {
                    throw new ValidationException(string.Format(StringResources.SubscriptionIdParamException, parameters[Constants.Parameters.SourceSubscriptionID], parameters[Constants.Parameters.SourcePublishSettingsFilePath]));
                }
            }
            else
            {
                string thumbprint = parameters[Constants.Parameters.SourceCertificateThumbprint];
                X509Certificate2 certificate = GetStoreCertificate(thumbprint);
                if (!certificate.HasPrivateKey)
                {
                    throw new ValidationException(string.Format(
                        StringResources.MissingPrivateKeyInCertificate, StringResources.Source, thumbprint));
                }
                var sourceCredentials = new CertificateCloudCredentials(parameters[Constants.Parameters.SourceSubscriptionID],
                      certificate);
                string sourceSubscriptionName = null;
                using (var client = new ManagementClient(sourceCredentials))
                {
                    BaseParameters baseParams = new BaseParameters()
                    {
                        RetryCount = retryCount,
                        MinBackOff = TimeSpan.FromSeconds(minBackOff),
                        MaxBackOff = TimeSpan.FromSeconds(maxBackOff),
                        DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff)
                    };
                    SubscriptionGetResponse subscriptionResponse = Retry.RetryOperation(() => client.Subscriptions.Get(), baseParams, ResourceType.None);
                    sourceSubscriptionName = subscriptionResponse.SubscriptionName;
                }
                sourceSubscription = new PublishSetting()
                {
                    Id = parameters[Constants.Parameters.SourceSubscriptionID],
                    Name = sourceSubscriptionName,
                    ServiceUrl = new Uri(Constants.ServiceManagementUrlValue),
                    Credentials = sourceCredentials
                };
            }

            // Validate DestinationPublishSettings File            
            PublishSettings destPublishSettingsFile = null;
            PublishSetting destSubscription = null;

            if (parameters.ContainsKey(Constants.Parameters.DestinationPublishSettingsFilePath))
            {
                try
                {
                    var fileContents = File.ReadAllText(parameters[Constants.Parameters.DestinationPublishSettingsFilePath]);
                    destPublishSettingsFile = new PublishSettings(fileContents);
                }
                catch (Exception xmlEx)
                {
                    throw new ValidationException(string.Format(StringResources.XMLParsingException + " =>" + xmlEx.Message,
                        parameters[Constants.Parameters.DestinationPublishSettingsFilePath]));
                }
                // Check whether destSubscriptionId exists in publish settings file
                destSubscription = destPublishSettingsFile.Subscriptions.FirstOrDefault(a =>
                    string.Compare(a.Id, parameters[Constants.Parameters.DestinationSubscriptionID], StringComparison.InvariantCultureIgnoreCase) == 0);
                if (destSubscription == null)
                {
                    throw new ValidationException(string.Format(StringResources.SubscriptionIdParamException, parameters[Constants.Parameters.DestinationSubscriptionID], parameters[Constants.Parameters.DestinationPublishSettingsFilePath]));
                }
            }
            else
            {
                string thumbprint = parameters[Constants.Parameters.DestinationCertificateThumbprint];
                X509Certificate2 certificate = GetStoreCertificate(thumbprint);
                if (!certificate.HasPrivateKey)
                {
                    throw new ValidationException(string.Format(
                        StringResources.MissingPrivateKeyInCertificate, StringResources.Destination, thumbprint));
                }
                var destCredentials = new CertificateCloudCredentials(parameters[Constants.Parameters.DestinationSubscriptionID],
                       certificate);
                string destSubscriptionName = null;
                using (var client = new ManagementClient(destCredentials))
                {
                    BaseParameters baseParams = new BaseParameters()
                    {
                        RetryCount = retryCount,
                        MinBackOff = TimeSpan.FromSeconds(minBackOff),
                        MaxBackOff = TimeSpan.FromSeconds(maxBackOff),
                        DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff)
                    };
                    SubscriptionGetResponse subscriptionResponse = Retry.RetryOperation(() => client.Subscriptions.Get(),
                      baseParams, ResourceType.None);
                    destSubscriptionName = subscriptionResponse.SubscriptionName;
                }
                destSubscription = new PublishSetting()
                {
                    Id = parameters[Constants.Parameters.DestinationSubscriptionID],
                    Name = destSubscriptionName,
                    ServiceUrl = new Uri(Constants.ServiceManagementUrlValue),
                    Credentials = destCredentials
                };
            }

            // Check whether DestinationDCName exists in subscription
            List<string> locations = ExportDataCenterLocations(destSubscription.Credentials, retryCount, minBackOff, maxBackOff, deltaBackOff);

            bool destinationLocationNamePresent = locations.Any((l => string.Compare(l,
                 parameters[Constants.Parameters.DestinationDCName],
                 StringComparison.CurrentCultureIgnoreCase) == 0));

            if (!destinationLocationNamePresent)
            {
                throw new ValidationException(string.Format(StringResources.DCParamException,
                    parameters[Constants.Parameters.DestinationDCName]));
            }

            // Valiadte DestinationPrefixName
            if (parameters.ContainsKey(Constants.Parameters.DestinationPrefixName) &&
                (parameters[Constants.Parameters.DestinationPrefixName].Length < 1 || parameters[Constants.Parameters.DestinationPrefixName].Length > 5))
            {
                throw new ValidationException(string.Format(StringResources.InvalidDestinationPrefixName,
                    parameters[Constants.Parameters.DestinationPrefixName]));
            }
            #endregion

            // Stores validated parameters in class.
            ImportParameters importParams = new ImportParameters()
            {
                DestinationDCName = parameters[Constants.Parameters.DestinationDCName],
                ImportMetadataFilePath = (!validateForImport) ? null : parameters[Constants.Parameters.ImportMetadataFilePath],
                MapperXmlFilePath = importMapperXmlFilePath,
                DestinationPrefixName = destinationPrefix,
                DestinationSubscriptionSettings = destSubscription,
                RollBackOnFailure = rollBackBoolValue,
                ResumeImport = resumeImportBoolValue,
                RetryCount = retryCount,
                MinBackOff = TimeSpan.FromSeconds(minBackOff),
                MaxBackOff = TimeSpan.FromSeconds(maxBackOff),
                DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff),
                SourceSubscriptionSettings = sourceSubscription
            };

            Logger.Info(methodName, ProgressResources.ParametersValidationCompleted);
            return importParams;
        }
        private XElement GetConfigXml()
        {
            XElement configXml = null;

            if(!RoleEnvironment.IsAvailable/*as local web project*/ || RoleEnvironment.IsEmulated /*as azure emulator project*/)
            {
                try
                {
                    var localConfigFile =
                        new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.EnumerateFiles(
                            "*Local.cscfg", SearchOption.AllDirectories).FirstOrDefault();
                    if (localConfigFile == null)
                    {
                        return null;
                    }

                    XmlDocument doc = new XmlDocument();
                    doc.Load(localConfigFile.FullName);
                    configXml = XElement.Parse(doc.InnerXml);
                }
                catch(Exception) // happens in some projects when using Full Emulator
                {
                    throw; // intended - just marking - will catch it above
                }
            }
            else
            {
                var managementCertificate = new X509Certificate2(Convert.FromBase64String(_managementCertContents));
                var credentials = new CertificateCloudCredentials(_subscriptionId, managementCertificate);

                var computeManagementClient = new ComputeManagementClient(credentials);
                var response = computeManagementClient.HostedServices.GetDetailed(_cloudServiceName);
                HostedServiceGetDetailedResponse.Deployment deployment = null;

                var isProduction = Convert.ToBoolean(CloudConfigurationManager.GetSetting("IsProduction"));
                if(isProduction)
                {
                    deployment = response.Deployments.FirstOrDefault(d => d.DeploymentSlot == DeploymentSlot.Production);
                }
                else
                {
                    deployment = response.Deployments.FirstOrDefault(d => d.DeploymentSlot == DeploymentSlot.Staging);
                }

                if(deployment != null)
                {
                    var config = deployment.Configuration;
                    configXml = XElement.Parse(config);
                }
            }
            return configXml;
        }
 public BatchManagementClient GetBatchManagementClient(RecordedDelegatingHandler handler)
 {
     var certCreds = new CertificateCloudCredentials(Guid.NewGuid().ToString(), new System.Security.Cryptography.X509Certificates.X509Certificate2());
     handler.IsPassThrough = false;
     return new BatchManagementClient(certCreds).WithHandler(handler);
 }
        /// <summary>
        /// Get the test environment from a connection string specifying a certificate
        /// </summary>
        /// <param name="testConnectionString">The connetcion string to parse</param>
        /// <returns>The test environment from parsing the connection string.</returns>
        protected virtual TestEnvironment GetCertificateTestEnvironmentFromConnectionString(string testConnectionString)
        {
            IDictionary<string, string> connections = ParseConnectionString(testConnectionString);
            string certificateReference = connections[ManagementCertificateKey];
            string subscriptionId = connections[SubscriptionIdKey];
            Assert.IsNotNull(certificateReference);
            X509Certificate2 managementCertificate;
            if (IsCertificateReference(certificateReference))
            {
                managementCertificate = GetCertificateFromReference(certificateReference);
            }
            else
            {
                managementCertificate = GetCertificateFromBase64String(certificateReference);
            }

            CertificateCloudCredentials credentials = new CertificateCloudCredentials(subscriptionId, managementCertificate);
            TestEnvironment currentEnvironment = new TestEnvironment { Credentials = credentials };
            if (connections.ContainsKey(BaseUriKey))
            {
                currentEnvironment.BaseUri = new Uri(connections[BaseUriKey]);
            }

            return currentEnvironment;
        }
        public static ExpressRouteManagementClient GetSecondCustomerExpressRouteManagementClient()
        {
            string managementCertificate = "";
            string baseUri;
            string subscriptionId;
            if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                baseUri = HttpMockServer.Variables["TEST_CUSTOMER2_BASE_URI"];
                subscriptionId = HttpMockServer.Variables["TEST_CUSTOMER2_SUBSCRIPTION_ID"];
                managementCertificate = HttpMockServer.Variables["TEST_CUSTOMER2_MANAGEMENT_CERTIFICATE"];
            }
            else
            {
                string publishSettingsFile = Environment.GetEnvironmentVariable("TEST_CUSTOMER2_PUBLISHSETTINGS_FILE");
                PublishData publishData = XmlSerializationHelpers.DeserializeXmlFile<PublishData>(publishSettingsFile);
                managementCertificate = Enumerable.First<PublishDataPublishProfile>((IEnumerable<PublishDataPublishProfile>) publishData.Items).ManagementCertificate;
                if (string.IsNullOrEmpty(managementCertificate))
                    managementCertificate = Enumerable.First<PublishDataPublishProfileSubscription>((IEnumerable<PublishDataPublishProfileSubscription>) Enumerable.First<PublishDataPublishProfile>((IEnumerable<PublishDataPublishProfile>) publishData.Items).Subscription).ManagementCertificate;
                if (string.IsNullOrEmpty(managementCertificate))
                    throw new ArgumentException(string.Format("{0} is not a valid publish settings file, you must provide a valid publish settings file in the environment variable {1}", (object) publishSettingsFile, (object) "TEST_PUBLISHSETTINGS_FILE"));
                
                
                subscriptionId = Enumerable.First<PublishDataPublishProfileSubscription>((IEnumerable<PublishDataPublishProfileSubscription>) Enumerable.First<PublishDataPublishProfile>((IEnumerable<PublishDataPublishProfile>) publishData.Items).Subscription).Id;
                
                baseUri =  Enumerable.First<PublishDataPublishProfileSubscription>(
                        (IEnumerable<PublishDataPublishProfileSubscription>)
                        Enumerable.First<PublishDataPublishProfile>(
                            (IEnumerable<PublishDataPublishProfile>) publishData.Items).Subscription)
                              .ServiceManagementUrl ?? publishData.Items[0].Url;

                HttpMockServer.Variables["TEST_CUSTOMER2_MANAGEMENT_CERTIFICATE"] = managementCertificate;
                HttpMockServer.Variables["TEST_CUSTOMER2_SUBSCRIPTION_ID"] = subscriptionId;
                HttpMockServer.Variables["TEST_CUSTOMER2_BASE_URI"] = baseUri;
            }

            var credentials = new CertificateCloudCredentials(subscriptionId, new X509Certificate2(Convert.FromBase64String(managementCertificate), string.Empty));
            var client = new ExpressRouteManagementClient(credentials, new Uri(baseUri));
            client.AddHandlerToPipeline(HttpMockServer.CreateInstance());
            return client;
        }