Exemple #1
0
        public async Task <HttpResponseMessage> Execute(ExecuteVM executeVm)
        {
            var credential = CertificateAuthenticationHelper.GetCredential(AMUWHelper.GetAppSetting("Azure-SubscriptionId"), AMUWHelper.GetAppSetting("Azure-Credential"));
            var requestId  = string.Empty;

            if (executeVm.Action == "start")
            {
                var execute = await CloudContext.Clients.CreateComputeManagementClient(credential).VirtualMachines.StartAsync(executeVm.ServiceName, executeVm.DeploymentName, executeVm.RoleName);

                requestId = execute.RequestId;
            }
            else
            {
                var execute = await CloudContext.Clients.CreateComputeManagementClient(credential).VirtualMachines.ShutdownAsync(
                    executeVm.ServiceName,
                    executeVm.DeploymentName,
                    executeVm.RoleName, new VirtualMachineShutdownParameters()
                {
                    PostShutdownAction = PostShutdownAction.StoppedDeallocated
                });

                requestId = execute.RequestId;
            }
            return(Request.CreateResponse <string>(HttpStatusCode.OK, requestId));
        }
Exemple #2
0
        private SubscriptionCloudCredentials GetSubscriptionCloudCredentials(string publishSettingsFilePath)
        {
            PublishSettingsSubscriptionItem publishSettingCreds = null;

            using (var fs = File.OpenRead(publishSettingsFilePath))
            {
                var document      = XDocument.Load(fs);
                var subscriptions =
                    from e in document.Descendants("Subscription")
                    select e;

                if (subscriptions.Count() >= 1)
                {
                    // use first subscription in the publish settings file
                    var subscription = subscriptions.First();

                    publishSettingCreds = new PublishSettingsSubscriptionItem
                    {
                        SubscriptionName      = subscription.Attribute("Name").Value,
                        SubscriptionId        = subscription.Attribute("Id").Value,
                        ManagementCertificate = subscription.Attribute("ManagementCertificate").Value
                    };
                }
                else
                {
                    Console.WriteLine("Invalid publishsettings file: Subscription not found.");
                }
            }

            return(CertificateAuthenticationHelper.GetCredentials(publishSettingCreds.SubscriptionId, publishSettingCreds.ManagementCertificate));
        }
 public void GetCredentialsTestNulls()
 {
     Assert.Throws(typeof(ArgumentNullException), new TestDelegate(delegate
     {
         CertificateAuthenticationHelper.GetCredentials("", "");
     }));
 }
Exemple #4
0
        public async Task <ActionResult> Detail(ExecuteVM executeVm)
        {
            var credential   = CertificateAuthenticationHelper.GetCredential(AMUWHelper.GetAppSetting("Azure-SubscriptionId"), AMUWHelper.GetAppSetting("Azure-Credential"));
            var cloudService = await CloudContext.Clients.CreateComputeManagementClient(credential).HostedServices.GetDetailedAsync(executeVm.ServiceName);

            var deployment = cloudService.Deployments.FirstOrDefault();
            var vmDetail   = deployment.RoleInstances.FirstOrDefault(x => x.RoleName == executeVm.RoleName);
            var viewModel  = new VirtualMachineDetailViewModel();

            viewModel.DeploymentId = cloudService.Deployments.FirstOrDefault().PrivateId;
            viewModel.VirtualIP    = deployment.VirtualIPAddresses.Count > 0 ? deployment.VirtualIPAddresses.FirstOrDefault().Address : "";
            viewModel.InternalIP   = vmDetail.IPAddress;
            viewModel.RoleName     = executeVm.RoleName;
            viewModel.Size         = vmDetail.InstanceSize;
            viewModel.Status       = vmDetail.PowerState.ToString();
            var userVmList = _vmUserService.GetByVMName(executeVm.RoleName);

            viewModel.UserList = new List <string>();
            foreach (var item in userVmList)
            {
                var emailAddress = UserManager.FindById(item.User.UserId).Email;
                viewModel.UserList.Add(item.User.Username + "(" + emailAddress + ")");
            }
            viewModel.UserRole = AMUW.Helpers.AMUWHelper.GetRole();
            return(View(viewModel));
        }
        public void GetCredentialsWithCrapData()
        {
            var badFormatSubscriptionID  = "oasidnfaodifna;odifna;odifand;ofiandfosainfoaiurgeoivfnaorivnar";
            var badFormatBaseEncodedCert = "or2ifnwosnfvslfnbsougoaingfa;oineo;gtinearoigfnarg;oiarhg;oeairhga;oiregnalkna";

            Assert.Throws(typeof(FormatException), new TestDelegate(delegate
            {
                CertificateAuthenticationHelper.GetCredentials(badFormatSubscriptionID, badFormatBaseEncodedCert);
            }));
        }
        private static StorageManagementClient EstablishClient(DeveloperParameters devOptions)
        {
            // set up the credentials for azure
            var creds =
                CertificateAuthenticationHelper.GetCredentials(devOptions.AzureManagementSubscriptionId,
                                                               devOptions.AzureAuthenticationKey);
            // set up the storage management client
            var client = new StorageManagementClient(creds);

            return(client);
        }
Exemple #7
0
        public async Task <HttpResponseMessage> Get(IEnumerable <ExecuteVM> vms)
        {
            var credential = CertificateAuthenticationHelper.GetCredential(AMUWHelper.GetAppSetting("Azure-SubscriptionId"), AMUWHelper.GetAppSetting("Azure-Credential"));

            if (vms != null)
            {
                foreach (var vm in vms)
                {
                    var vmDetail = await CloudContext.Clients.CreateComputeManagementClient(credential).VirtualMachines.GetAsync(vm.ServiceName, vm.DeploymentName, vm.RoleName);
                }
            }
            return(Request.CreateResponse <string>(HttpStatusCode.OK, ""));
        }
        public override ProvisionAddOnResult Provision(AddonProvisionRequest request)
        {
            var provisionResult = new ProvisionAddOnResult("");

            try
            {
                var devParameters = DeveloperParameters.Parse(request.DeveloperParameters, request.Manifest.GetProperties());

                SubscriptionCloudCredentials creds = CertificateAuthenticationHelper.GetCredentials(devParameters.AzureManagementSubscriptionId, devParameters.AzureAuthenticationKey, devParameters.PFXPassword);

                // ok so if we need a storage account, we need to use the storage management client.
                if (devParameters.NewStorageAccountFlag)
                {
                    var client     = new StorageManagementClient(creds);
                    var parameters = CreateStorageAccountParameters(devParameters);
                    client.StorageAccounts.Create(parameters);
                    do
                    {
                        var verificationResponse = client.StorageAccounts.Get(parameters.Name);

                        if (verificationResponse.StorageAccount.Properties.Status.Equals(StorageAccountStatus.Created))
                        {
                            var azureconnectioninfo = client.StorageAccounts.Get(devParameters.StorageAccountName);
                            var keysForStorageUnit  = client.StorageAccounts.GetKeys(devParameters.StorageAccountName);

                            var connectionInfo = new ConnectionInfo
                            {
                                PrimaryKey         = keysForStorageUnit.PrimaryKey,
                                SecondaryKey       = keysForStorageUnit.SecondaryKey,
                                StorageAccountName = azureconnectioninfo.StorageAccount.Name,
                                Uri = keysForStorageUnit.Uri.ToString()
                            };
                            provisionResult.ConnectionData = connectionInfo.ToString();
                            provisionResult.IsSuccess      = true;
                            break;
                        }
                        Thread.Sleep(TimeSpan.FromSeconds(10d));
                    } while (true);
                }
            }
            catch (Exception e)
            {
                provisionResult.IsSuccess      = false;
                provisionResult.EndUserMessage = e.Message + "\n We're in an error\n";
            }

            return(provisionResult);
        }
        public override OperationResult Deprovision(AddonDeprovisionRequest request)
        {
            var connectionData = request.ConnectionData;
            // changing to overloaded constructor - 5/22/14
            var deprovisionResult  = new ProvisionAddOnResult(connectionData);
            var manifest           = request.Manifest;
            var inputDevParameters = request.DeveloperParameters;
            // parse required options here, use developer options class to do so.
            var manifestProperties = manifest.GetProperties();
            // Developer Options will be instantiated first time here.
            var devParams = DeveloperParameters.Parse(inputDevParameters, manifestProperties);

            // set up the credentials for azure
            var creds = CertificateAuthenticationHelper.GetCredentials(devParams.AzureManagementSubscriptionId,
                                                                       devParams.AzureAuthenticationKey);
            // set up the storage management client
            var client = new StorageManagementClient();

            var mResponse = client.StorageAccounts.Delete(devParams.StorageAccountName);

            if (mResponse.StatusCode.Equals(HttpStatusCode.OK))
            {
                do
                {
                    var verificationResponse =
                        client.StorageAccounts.Get(devParams.StorageAccountName);

                    if (verificationResponse.StorageAccount.Properties.Status.Equals(StorageAccountStatus.Deleting))
                    {
                        deprovisionResult.IsSuccess      = true;
                        deprovisionResult.EndUserMessage =
                            "Deprovision Request Complete, please allow a few minutes for resources to be fully deleted.";
                        break;
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(10d));
                } while (true);
                return(deprovisionResult);
            }
            else
            {
                return(new OperationResult()
                {
                    EndUserMessage = "Azure Query failed. Please check your syntax and credetials.",
                    IsSuccess = false
                });
            }
        }
        public override OperationResult Test(AddonTestRequest request)
        {
            var manifest        = request.Manifest;
            var developerParams = request.DeveloperParameters;
            var testResult      = new OperationResult {
                IsSuccess = false
            };
            var testProgress       = "";
            var manifestProperties = manifest.Properties;

            if (manifestProperties != null)
            {
                var devOptions = DeveloperParameters.Parse(developerParams, manifest.GetProperties());
                var creds      = CertificateAuthenticationHelper.GetCredentials(devOptions.AzureManagementSubscriptionId,
                                                                                devOptions.AzureAuthenticationKey, devOptions.PFXPassword);
                try
                {
                    testProgress += "Establishing connection to Azure...\n";
                    // set up the credentials for azure

                    var client = new StorageManagementClient(creds);

                    //var listOfStorageAccounts = client.StorageAccounts.List();

                    testProgress             += "Successfully passed all testing criteria!";
                    testResult.IsSuccess      = true;
                    testResult.EndUserMessage = testProgress;
                }
                catch (Exception e)
                {
                    // adding a forced failure here.
                    testResult.IsSuccess      = false;
                    testResult.EndUserMessage = testProgress + "\nEXCEPTION: " + e.Message;
                }
            }
            else
            {
                testResult.IsSuccess      = false;
                testResult.EndUserMessage = "Missing required manifest properties (requireDevCredentials)";
            }

            return(testResult);
        }
        public override OperationResult Deprovision(AddonDeprovisionRequest request)
        {
            var connectionData    = request.ConnectionData;
            var deprovisionResult = new ProvisionAddOnResult(connectionData);
            var devOptions        = DeveloperParameters.Parse(request.DeveloperParameters, request.Manifest.GetProperties());
            // set up the credentials for azure
            SubscriptionCloudCredentials creds = CertificateAuthenticationHelper.GetCredentials(devOptions.AzureManagementSubscriptionId, devOptions.AzureAuthenticationKey, devOptions.PFXPassword);
            // set up the storage management client
            var client = new StorageManagementClient(creds);

            // check to see if the storage accounts exists...if they do not exist, throw a no-op here.
            var account = client.StorageAccounts.Get(devOptions.StorageAccountName);

            if (account.StatusCode.Equals(HttpStatusCode.NotFound))
            {
                // no account found. return a no-op as something went wrong, proceed to deletion
                deprovisionResult.IsSuccess      = true;
                deprovisionResult.EndUserMessage = "Storage account not found, may have been deleted via 3rd party.";
                return(deprovisionResult);
            }

            // then if requested, delete the storage account name
            client.StorageAccounts.Delete(devOptions.StorageAccountName);

            do
            {
                var verificationResponse = client.StorageAccounts.Get(devOptions.StorageAccountName);

                if (verificationResponse.StorageAccount.Properties.Status.Equals(StorageAccountStatus.Deleting))
                {
                    deprovisionResult.IsSuccess      = true;
                    deprovisionResult.EndUserMessage = "Deprovision Request Complete, please allow a few minutes for resources to be fully deleted.";
                    break;
                }
                Thread.Sleep(TimeSpan.FromSeconds(10d));
            }while (true);
            return(deprovisionResult);
        }
Exemple #12
0
        public async Task <HttpResponseMessage> Get(int?id)
        {
            List <VirtualMachineViewModel> vms = new List <VirtualMachineViewModel>();
            var credential = CertificateAuthenticationHelper.GetCredential(AMUWHelper.GetAppSetting("Azure-SubscriptionId"), AMUWHelper.GetAppSetting("Azure-Credential"));

            var cloudServiceList = new List <string>();

            if (id != null)
            {
                var vmUser = _vmUserService.GetAll(id.Value);
                foreach (var item in vmUser)
                {
                    var cloudService = await CloudContext.Clients.CreateComputeManagementClient(credential).HostedServices.GetAsync(item.ServiceName);

                    var detailService = await CloudContext.Clients.CreateComputeManagementClient(credential).HostedServices.GetDetailedAsync(cloudService.ServiceName);

                    var deplyoments      = detailService.Deployments;
                    var resourceLocation = cloudService.Properties.ExtendedProperties.FirstOrDefault(x => x.Key == "ResourceLocation").Value;
                    foreach (var deployment in deplyoments)
                    {
                        var roleInstances = deployment.RoleInstances;
                        foreach (var roleInstance in roleInstances)
                        {
                            vms.Add(new VirtualMachineViewModel
                            {
                                ServiceName    = cloudService.ServiceName,
                                DeploymentName = deployment.Name,
                                Name           = roleInstance.RoleName,
                                Status         = roleInstance.PowerState.ToString(),
                                DnsName        = deployment.Uri.ToString(),
                                Location       = cloudService.Properties.Location != null ? resourceLocation : cloudService.Properties.AffinityGroup + " (" + resourceLocation + ")"
                            });
                        }
                    }
                }
            }
            else
            {
                var cloudServices = await CloudContext.Clients.CreateComputeManagementClient(credential).HostedServices.ListAsync();

                foreach (var cloudService in cloudServices)
                {
                    var detailService = await CloudContext.Clients.CreateComputeManagementClient(credential).HostedServices.GetDetailedAsync(cloudService.ServiceName);

                    var deplyoments      = detailService.Deployments;
                    var resourceLocation = cloudService.Properties.ExtendedProperties.FirstOrDefault(x => x.Key == "ResourceLocation").Value;
                    foreach (var deployment in deplyoments)
                    {
                        var roleInstances = deployment.RoleInstances;
                        foreach (var roleInstance in roleInstances)
                        {
                            var userVmList = _vmUserService.GetByVMName(roleInstance.RoleName);
                            var userList   = new List <string>();
                            foreach (var item in userVmList)
                            {
                                var emailAddress = _helper.GetEmail(item.User.UserId);
                                userList.Add(item.User.Username + "(" + emailAddress + ")");
                            }
                            vms.Add(new VirtualMachineViewModel
                            {
                                ServiceName    = cloudService.ServiceName,
                                DeploymentName = deployment.Name,
                                Name           = roleInstance.RoleName,
                                Status         = roleInstance.PowerState.ToString(),
                                DnsName        = deployment.Uri.ToString(),
                                Location       = cloudService.Properties.Location != null ? resourceLocation : cloudService.Properties.AffinityGroup + " (" + resourceLocation + ")",
                                UserList       = userList.Count > 0 ? string.Join("<br/>", userList) : string.Empty
                            });
                        }
                    }
                }
            }
            return(Request.CreateResponse <List <VirtualMachineViewModel> >(HttpStatusCode.OK, vms));
        }
        public void GetLegitCredentials()
        {
            var credential = CertificateAuthenticationHelper.GetCredentials(AzureSubscriptionId, AzureAccessToken);

            Assert.That(credential, Is.TypeOf <CertificateCloudCredentials>());
        }