/// <summary>	Get a mocked API Client, using the call and response collection in <see cref="requestsAndResponses"/>. </summary>
        /// <returns>	The API client. </returns>
        protected ComputeApiClient GetApiClient()
        {
            var httpClient = CreateFakeHttpClient();
            var client     = new ComputeApiClient(httpClient);

            return(client);
        }
		public async Task GetAllSystemImagesAU1()
		{
			IReadOnlyList<DeployedImageWithSoftwareLabelsType> images;
			using (ComputeApiClient apiClient = new ComputeApiClient("AU"))
			{
				await apiClient.LoginAsync(
					accountCredentials: GetIntegrationTestCredentials()
				);

				images = await apiClient.GetImages("AU1");
			}

			foreach (var image in images)
			{
				TestContext.WriteLine(
					"Image '{0}' (Id = '{1}') - '{2}' ({3})",
					image.name,
					image.id,
					image
						.machineSpecification
						.operatingSystem
						.displayName,
					image
						.machineSpecification
						.operatingSystem
						.type
				);
			}
		}
Ejemplo n.º 3
0
        public async Task GetAvailableDatacenters()
        {
            ICredentials credentials = GetIntegrationTestCredentials();

            using (ComputeApiClient computeApiClient = new ComputeApiClient("au"))
            {
                IAccount account = await
                                   computeApiClient
                                   .LoginAsync(credentials);

                Assert.IsNotNull(account);

                Guid organizationId = account.OrganizationId;
                Assert.AreNotEqual(Guid.Empty, organizationId);

                IReadOnlyList <IDatacenterDetail> dataCenters =
                    await computeApiClient
                    .GetAvailableDataCentersAsync();

                Assert.AreNotEqual(0, dataCenters.Count);
                foreach (IDatacenterDetail dataCenter in dataCenters)
                {
                    TestContext.WriteLine("{0}:{1} ({2})", dataCenter.LocationCode, dataCenter.DisplayName, dataCenter.Country);
                }
            }
        }
Ejemplo n.º 4
0
        public async Task GetAllSystemImagesAU1()
        {
            IReadOnlyList <DeployedImageWithSoftwareLabelsType> images;

            using (ComputeApiClient apiClient = new ComputeApiClient("AU"))
            {
                await apiClient.LoginAsync(
                    accountCredentials : GetIntegrationTestCredentials()
                    );

                images = await apiClient.GetImagesAsync("AU1");
            }

            foreach (var image in images)
            {
                TestContext.WriteLine(
                    "Image '{0}' (Id = '{1}') - '{2}' ({3})",
                    image.name,
                    image.id,
                    image
                    .machineSpecification
                    .operatingSystem
                    .displayName,
                    image
                    .machineSpecification
                    .operatingSystem
                    .type
                    );
            }
        }
		public async Task GetAllSystemImagesAllLocations()
		{
			using (ComputeApiClient apiClient = new ComputeApiClient("AU"))
			{
				await apiClient.LoginAsync(
					accountCredentials: GetIntegrationTestCredentials()
				);

				foreach (DatacenterWithMaintenanceStatusType datacenter in await apiClient.GetDataCentersWithMaintenanceStatuses())
				{
					TestContext.WriteLine("DataCenter '{0}' ({1}):", datacenter.location, datacenter.displayName);

					foreach (var image in await apiClient.GetImages(null,null,datacenter.location,null,null))
					{
						TestContext.WriteLine(
							"\tImage '{0}' (Id = '{1}') - '{2}' ({3})",
							image.name,
							image.id,
							image.operatingSystem[0].type,
                            image.operatingSystem[0].displayName
                            
															
						);
					}
				}
			}
		}
Ejemplo n.º 6
0
        /// <summary>
        /// Get the Citrix machine model for the given server ID
        /// </summary>
        /// <param name="connectionSettings"></param>
        /// <param name="machineId"></param>
        /// <returns></returns>
        public IManagedMachine GetMachineDetails(ConnectionSettings connectionSettings, string machineId)
        {
            ComputeApiClient client = connectionSettings.GetComputeClient();
            ServerType       server = client.ServerManagement.Server.GetServer(Guid.Parse(machineId)).Result;

            return(server.ToManagedMachine());
        }
		public async Task GetAvailableNetworkDomains()
		{
			ICredentials credentials = GetIntegrationTestCredentials();

			using (var computeApiClient = new ComputeApiClient("apinashpcs01.opsourcecloud.net"))
			{
				IAccount account = await
					computeApiClient
						.LoginAsync(credentials);
				Assert.IsNotNull(account);

				Guid organizationId = account.OrganizationId;
				Assert.AreNotEqual(Guid.Empty, organizationId);

				var networkDomains = (await computeApiClient.GetNetworkDomains()).ToList();

				Assert.AreNotEqual(0, networkDomains.Count);

				TestContext.WriteLine("Domains List \n");

				foreach (NetworkDomain domain in networkDomains)
				{
					TestContext.WriteLine("Name & Type : {0} - {1}", domain.name, domain.type);
					TestContext.WriteLine("Description: {0}", domain.description);
				}
			}
		}
Ejemplo n.º 8
0
        public async Task GetAllSystemImagesAllLocations()
        {
            using (ComputeApiClient apiClient = new ComputeApiClient("AU"))
            {
                await apiClient.LoginAsync(
                    accountCredentials : GetIntegrationTestCredentials()
                    );

                foreach (DatacenterSummary datacenter in await apiClient.GetAvailableDataCentersAsync())
                {
                    TestContext.WriteLine("DataCenter '{0}' ({1}):", datacenter.LocationCode, datacenter.DisplayName);

                    foreach (var image in await apiClient.GetImagesAsync(datacenter.LocationCode))
                    {
                        TestContext.WriteLine(
                            "\tImage '{0}' (Id = '{1}') - '{2}' ({3})",
                            image.name,
                            image.id,
                            image
                            .machineSpecification
                            .operatingSystem
                            .displayName,
                            image
                            .machineSpecification
                            .operatingSystem
                            .type
                            );
                    }
                }
            }
        }
        /// <summary>
        /// Try to login into the account using the credentials.
        ///     If succeed, it will return the account details.
        /// </summary>
        /// <returns>
        /// The CaaS connection
        /// </returns>
        private async Task <ComputeServiceConnection> LoginTask()
        {
            ComputeApiClient apiClient = ComputeApiClient.GetComputeApiClient(Vendor, Region, ApiCredentials.GetNetworkCredential());

            var newCloudComputeConnection = new ComputeServiceConnection(apiClient);

            WriteDebug("Trying to login into the CaaS");

            await newCloudComputeConnection.ApiClient.Login();

            return(newCloudComputeConnection);
        }
Ejemplo n.º 10
0
        public static ComputeApiClient GetComputeClient(this ConnectionSettings connectionSettings)
        {
            // The Provisioning SDK currently only supports a single "default" connection
            // credential, consisting of a username and password pair (although these can also
            // be treated as API/secret keys).
            UserCredential defaultCredential = connectionSettings.Credentials["Default"];

            // We support multiple service addresses, but REST APIs endpoints are typically just a
            // single address, so let's assume that pattern here.
            string endpoint = connectionSettings.ServiceAddresses[0];

            // Create a client.
            return(ComputeApiClient.GetComputeApiClient(new System.Uri(endpoint), new NetworkCredential(defaultCredential.UserName, defaultCredential.Password)));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Gets all direct children of a given path.
        /// </summary>
        /// <param name="connectionSettings">The settings needed to contact and authenticate with the hosting
        /// infrastructure. This demo code doesn't consult the connection settings, because the inventory being
        /// returned is just hard-coded dummy data. A "real" implementation would use these settings to make the
        /// API calls needed to discover the inventory.</param>
        /// <param name="path">The path whose direct children are required.</param>
        /// <returns>
        /// The return value is a flat list of items, whose tree structure is implied by the path of each item. The
        /// plugin can choose to return all recursive children here, or just the direct children of the given path.
        /// This dummy implementation assumes a simple, flat tree, where all networks/storage/templates are direct
        /// children of the root. Therefore, it only returns any data when "/" is passed in as the query path.
        /// If you use Powershell to do a "dir" within the XDHyp:\Connections\ tree, you'll be able to see
        /// these items.
        /// </returns>
        public IList <IInventoryItem> GetContents(ConnectionSettings connectionSettings, string path)
        {
            List <IInventoryItem> inventoryItems = new List <IInventoryItem>();

            if (path == RootFolderPath)
            {
                ComputeApiClient client = connectionSettings.GetComputeClient();
                IEnumerable <NetworkDomainType> networkDomains = client.Networking.NetworkDomain.GetNetworkDomains().Result;
                AddNetworks(path, inventoryItems, networkDomains);
                //AddStoragePools(path, inventoryItems, storage);
                var images = client.ServerManagementLegacy.ServerImage.GetImages(null, null, null, null, null).Result;
                AddTemplates(path, inventoryItems, images);
            }
            return(inventoryItems);
        }
	    public async Task TestListMultiGeoDataCentersWithKey()
	    {
            ICredentials credentials = GetIntegrationTestCredentials();
            using (ComputeApiClient computeApiClient = new ComputeApiClient("au"))
            {
                IAccount account = await
                    computeApiClient
                        .LoginAsync(credentials);
                Assert.IsNotNull(account);

                Guid organizationId = account.OrganizationId;
                Assert.AreNotEqual(Guid.Empty, organizationId);

                await computeApiClient.GetListOfMultiGeographyRegions();
            }
        }
		public async Task LoginWithValidCredentials()
		{
			ICredentials credentials = GetIntegrationTestCredentials();
			using (ComputeApiClient computeApiClient = new ComputeApiClient("au"))
			{
				IAccount account = await
					computeApiClient
						.LoginAsync(credentials);
				Assert.IsNotNull(account);
				Assert.IsNotNull(computeApiClient.Account);

				TestContext.WriteLine("Account organisation Id: '{0}", account.OrganizationId);
				TestContext.WriteLine("Account full name: '{0}'", account.FullName);
				TestContext.WriteLine("Account email address: '{0}'", account.EmailAddress);
			}
		}
        /// <summary>
        /// Checks for the existence of the default VLAN (in app.config)
        /// and returns the ID of that VLAN
        /// </summary>
        /// <param name="connectionSettings"></param>
        /// <returns></returns>
        private Guid?GetVlanId(ConnectionSettings connectionSettings)
        {
            ComputeApiClient client = connectionSettings.GetComputeClient();
            var vlans = client.Networking.Vlan.GetVlans(new VlanListOptions()
            {
                Name = _defaultVlan
            }).Result;

            if (vlans == null || !vlans.Any())
            {
                throw new Exception("Must have default VLAN provisioned first");
            }
            else
            {
                return(Guid.Parse(vlans.First().id));
            }
        }
        /// <summary>
        /// Checks for the existence of the default Network Domain
        /// and returns the ID of that network domain
        /// </summary>
        /// <param name="connectionSettings"></param>
        /// <returns></returns>
        private Guid?GetNetworkDomainId(ConnectionSettings connectionSettings)
        {
            ComputeApiClient client = connectionSettings.GetComputeClient();
            var domains             = client.Networking.NetworkDomain.GetNetworkDomains(new NetworkDomainListOptions()
            {
                Name = _defaultNetworkDomain
            }).Result;

            if (domains == null || !domains.Any())
            {
                throw new Exception("Must have default network domain provisioned first");
            }
            else
            {
                return(Guid.Parse(domains.First().id));
            }
        }
Ejemplo n.º 16
0
        public async Task LoginWithValidCredentials()
        {
            ICredentials credentials = GetIntegrationTestCredentials();

            using (ComputeApiClient computeApiClient = new ComputeApiClient("au"))
            {
                IAccount account = await
                                   computeApiClient
                                   .LoginAsync(credentials);

                Assert.IsNotNull(account);
                Assert.IsNotNull(computeApiClient.Account);

                TestContext.WriteLine("Account organisation Id: '{0}", account.OrganizationId);
                TestContext.WriteLine("Account full name: '{0}'", account.FullName);
                TestContext.WriteLine("Account email address: '{0}'", account.EmailAddress);
            }
        }
        public async Task ProvisionNetworkDomainTest()
        {
            requestsAndResponses.Add(ApiUris.MyAccount, RequestFileResponseType.AsGoodResponse("GetMyAccountDetails.xml"));
            requestsAndResponses.Add(ApiUris.CreateNetworkDomain(this.accountId), RequestFileResponseType.AsGoodResponse("CreateNetworkDomainResponse.xml"));

            ComputeApiClient client = GetApiClient();
            await client.LoginAsync(new NetworkCredential(string.Empty, string.Empty));

            ResponseType domainResponse = await client.DeployNetworkDomain(new DeployNetworkDomainType()
            {
                datacenterId = "DC1",
                description  = "my description",
                name         = "domain1",
                type         = "ESSENTIALS"
            });

            Assert.IsNotNull(domainResponse);
            Assert.AreEqual("IN_PROGRESS", domainResponse.responseCode);
        }
        /// <summary>
        /// Map the list of servers in the network to the
        /// </summary>
        /// <param name="connectionSettings"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public IList <IManagedMachine> GetMachineStates(ConnectionSettings connectionSettings, IList <string> filter)
        {
            // Step 1: Get the ID of the default Network Domain
            _networkDomainId = GetNetworkDomainId(connectionSettings);
            _vlanId          = GetVlanId(connectionSettings);

            IEnumerable <IManagedMachine> results;
            ComputeApiClient         client  = connectionSettings.GetComputeClient();
            IEnumerable <ServerType> servers = client.ServerManagement.Server.GetServers(new ServerListOptions()
            {
                Name            = filter[0],
                NetworkDomainId = _networkDomainId,
                VlanId          = _vlanId
            }).Result;

            results =
                servers.Select(
                    s => s.ToManagedMachine());

            return(results.ToList());
        }
		public async Task LoginWithInvalidCredentials()
		{
			ICredentials credentials = new NetworkCredential(
				userName: "******",
				password: "******"
			);
			using (ComputeApiClient computeApiClient = new ComputeApiClient("au"))
			{
				try
				{
					await computeApiClient.LoginAsync(credentials);
					
					Assert.Fail("LoginAsync with invalid credentials failed to raise a ComputeApiException.");
				}
				catch (ComputeApiException eInvalidCredentials)
				{
					if (eInvalidCredentials.Error != ComputeApiError.InvalidCredentials)
						throw;
				}
			}
		}
		public async Task GetAvailableDatacenters()
		{
			ICredentials credentials = GetIntegrationTestCredentials();
			using (ComputeApiClient computeApiClient = new ComputeApiClient("au"))
			{
				IAccount account = await
					computeApiClient
						.LoginAsync(credentials);
				Assert.IsNotNull(account);

				Guid organizationId = account.OrganizationId;
				Assert.AreNotEqual(Guid.Empty, organizationId);

			    IEnumerable<DatacenterWithMaintenanceStatusType> dataCenters =
			        await computeApiClient
			            .GetDataCentersWithMaintenanceStatuses();

				Assert.AreNotEqual(0, dataCenters.Count());
                foreach (DatacenterWithMaintenanceStatusType dataCenter in dataCenters)
					TestContext.WriteLine("{0}:{1} ({2})", dataCenter.location, dataCenter.displayName, dataCenter.country);
			}
		}
Ejemplo n.º 21
0
        /// <summary>
        ///     Try to login into the account using the credentials.
        ///     If succeed, it will return the account details.
        /// </summary>
        /// <returns>
        ///     The CaaS connection
        /// </returns>
        private async Task <ComputeServiceConnection> LoginTask()
        {
            var messageHandler = GetMessageHandler(ApiCredentials.GetNetworkCredential());
            var baseUri        = KnownApiUri.Instance.GetBaseUri(Vendor, Region);
            var httpClient     = new HttpClientAdapter(
                new HttpClient(messageHandler, disposeHandler: true)
            {
                BaseAddress = baseUri,
                Timeout     = TimeSpan.FromMinutes(5),
            });


            // we will not try to login again, assuming the clientId remains the same accross the regions
            var apiClient = new ComputeApiClient(httpClient);

            var newCloudComputeConnection = new ComputeServiceConnection(apiClient, messageHandler);

            WriteDebug("Trying to login into the CaaS");

            await apiClient.LoginAsync();

            return(newCloudComputeConnection);
        }
Ejemplo n.º 22
0
        public async Task LoginWithInvalidCredentials()
        {
            ICredentials credentials = new NetworkCredential(
                userName: "******",
                password: "******"
                );

            using (ComputeApiClient computeApiClient = new ComputeApiClient("au"))
            {
                try
                {
                    await computeApiClient.LoginAsync(credentials);

                    Assert.Fail("LoginAsync with invalid credentials failed to raise a ComputeApiException.");
                }
                catch (ComputeApiException eInvalidCredentials)
                {
                    if (eInvalidCredentials.Error != ComputeApiError.InvalidCredentials)
                    {
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Try to login into the account using the credentials.
        ///     If succeed, it will return the account details.
        /// </summary>
        /// <returns>
        /// The CaaS connection
        /// </returns>
        private async Task <ComputeServiceConnection> LoginTask()
        {
            var ftpHost = string.Empty;
            ComputeApiClient apiClient = null;

            if (ParameterSetName == "KnownApiUri")
            {
                apiClient = ComputeApiClient.GetComputeApiClient(Vendor, Region, ApiCredentials.GetNetworkCredential());
                ftpHost   = ComputeApiClient.GetFtpHost(Vendor, Region);
            }

            if (ParameterSetName == "ApiDomainName")
            {
                var baseUri = new Uri(ApiDomainName);
                WriteWarning("This parameter is obselete and will not work for MCP2.0 commands, use Vendor and Region");
                apiClient = ComputeApiClient.GetComputeApiClient(baseUri, ApiCredentials.GetNetworkCredential());
                ftpHost   = ApiDomainName;
            }

            var newCloudComputeConnection = new ComputeServiceConnection(apiClient);

            WriteDebug("Trying to login into the CaaS");
            newCloudComputeConnection.Account = await newCloudComputeConnection.ApiClient.Login();

            // Right now we dont need to do a connect, as ftp is used in only a few commands
            newCloudComputeConnection.FtpClient = new FtpClient
            {
                Host                     = ftpHost,
                EncryptionMode           = FtpEncryptionMode.Explicit,
                DataConnectionEncryption = true,
                Credentials              = ApiCredentials.GetNetworkCredential()
                                           .GetCredential(new Uri(string.Format("ftp://{0}", ftpHost)), "Basic")
            };

            return(newCloudComputeConnection);
        }
Ejemplo n.º 24
0
        /// <summary>
        ///     Try to login into the account using the credentials.
        ///     If succeed, it will return the account details.
        /// </summary>
        /// <returns>
        ///     The CaaS connection
        /// </returns>
        private async Task <ComputeServiceConnection> LoginTask()
        {
            string            ftpHost   = string.Empty;
            IComputeApiClient apiClient = null;
            var messageHandler          = GetMessageHandler(ApiCredentials.GetNetworkCredential());

            _logger = new HttpTraceLogger(this);
            messageHandler.LogEventHandler += _logger.LogRequestHandler;

            if (ParameterSetName == "KnownApiUri")
            {
                var baseUri = KnownApiUri.Instance.GetBaseUri(Vendor, Region);
                apiClient = GetComputeApiClient(baseUri, messageHandler);
                ftpHost   = ComputeApiClient.GetFtpHost(Vendor, Region);
            }

            if (ParameterSetName == "ApiDomainName")
            {
                Uri baseUri;
                // Support ApiDomainName containing https://
                if (Uri.TryCreate(ApiDomainName, UriKind.Absolute, out baseUri))
                {
                    ftpHost = baseUri.Host;
                }
                else
                {
                    // Support ApiDomainName as in just the domainName
                    baseUri = new Uri(string.Format("https://{0}/", ApiDomainName));
                    ftpHost = ApiDomainName;
                }

                // Handle explicit FTP host name
                if (!string.IsNullOrWhiteSpace(FtpDomainName))
                {
                    ftpHost = FtpDomainName;
                    Uri ftpUri;
                    if (Uri.TryCreate(FtpDomainName, UriKind.Absolute, out ftpUri))
                    {
                        ftpHost = ftpUri.Host;
                    }
                }

                apiClient = GetComputeApiClient(baseUri, messageHandler);
            }
            if (ParameterSetName == "HttpClient")
            {
                apiClient = new ComputeApiClient(new HttpClientAdapter(HttpClient));
            }

            var newCloudComputeConnection = new ComputeServiceConnection(apiClient, messageHandler);

            WriteDebug("Trying to login into the CaaS");
            newCloudComputeConnection.User = await apiClient.LoginAsync();

            // await newCloudComputeConnection.ApiClient.LoginAsync();

            if (!string.IsNullOrWhiteSpace(ftpHost))
            {
                // Right now we dont need to do a connect, as ftp is used in only a few commands
                newCloudComputeConnection.FtpClient = new FtpClient
                {
                    Host                     = ftpHost,
                    EncryptionMode           = FtpEncryptionMode.Explicit,
                    DataConnectionEncryption = true,
                    Credentials              = ApiCredentials.GetNetworkCredential()
                                               .GetCredential(new Uri(string.Format("ftp://{0}", ftpHost)), "Basic")
                };
            }
            messageHandler.LogEventHandler -= _logger.LogRequestHandler;
            return(newCloudComputeConnection);
        }
		public async Task CreateNetworkDomain()
		{
			ICredentials credentials = GetIntegrationTestCredentials();

			using (var computeApiClient = new ComputeApiClient("apinashpcs01.opsourcecloud.net"))
			{
				IAccount account = await computeApiClient.LoginAsync(credentials);
				Assert.IsNotNull(account);

				Guid organizationId = account.OrganizationId;
				Assert.AreNotEqual(Guid.Empty, organizationId);

				var newDomain = new DeployNetworkDomain { location = "NASH_PCS01_N2_VMWARE_1", name = "Test Network Domain", description = "This is test Network Domain created using Network 2.0 API", type = "ESSENTIALS" };

				var result = await computeApiClient.DeployNetworkDomain(newDomain);

				Assert.AreEqual("OK", result.responseCode);
				Assert.IsTrue(result.info.Length > 0);
				Assert.IsNotNull(result.info[0].ToString());
			}
		}