示例#1
0
        public static async Task <DeploymentExtended> CreateTemplateDeploymentAsync(
            Microsoft.Rest.TokenCredentials credential,
            string groupName,
            string deploymentName,
            string subscriptionId,
            object template,
            object parameters)
        {
            var resourceManagementClient = new ResourceManagementClient(credential)
            {
                SubscriptionId = subscriptionId
            };

            var deployment = new Microsoft.Azure.Management.ResourceManager.Models.Deployment();

            deployment.Properties = new DeploymentProperties
            {
                Mode       = Microsoft.Azure.Management.ResourceManager.Models.DeploymentMode.Incremental,
                Template   = template,
                Parameters = parameters
            };

            return(await resourceManagementClient.Deployments.CreateOrUpdateAsync(
                       groupName,
                       deploymentName,
                       deployment
                       ));
        }
示例#2
0
    public async Task <IActionResult> List()
    {
        var auth = new Microsoft.Rest.TokenCredentials(User.Claims.First(x => x.Type == "access_token").Value);
        var api  = new Auth0SwaggerSampleAPI(new Uri("http://localhost:5000"), auth);

        return(View(await api.ValuesGetAsync()));
    }
示例#3
0
        public AzureBaseManager(IAzureCloudAuthenticationInfo authInfo)
        {
            this.AuthInfo = authInfo;
            switch (this.AuthInfo.AuthenticationMode)
            {
            case CloudAuthenticationMode.AccessToken:
                Microsoft.Rest.TokenCredentials tokenCredentials =
                    new Microsoft.Rest.TokenCredentials(this.AuthInfo.AzureAccessToken);
                this.ServiceCredentials = tokenCredentials;
                break;

            case CloudAuthenticationMode.Certificate:
                X509Certificate2 cert = new X509Certificate2(this.AuthInfo.CertificateBytes, this.AuthInfo.PfxCertificatePassword,
                                                             X509KeyStorageFlags.MachineKeySet |
                                                             X509KeyStorageFlags.PersistKeySet |
                                                             X509KeyStorageFlags.Exportable);
                Microsoft.Rest.CertificateCredentials certificateCredentials =
                    new Microsoft.Rest.CertificateCredentials(cert);
                this.ServiceCredentials = certificateCredentials;
                break;

            case CloudAuthenticationMode.PublishingProfile:
                byte[]           managementCertificateBytes = Convert.FromBase64String(this.AuthInfo.ManagementCertificate);
                X509Certificate2 publishingCert             = new X509Certificate2(managementCertificateBytes, string.Empty,
                                                                                   X509KeyStorageFlags.MachineKeySet |
                                                                                   X509KeyStorageFlags.PersistKeySet |
                                                                                   X509KeyStorageFlags.Exportable);
                Microsoft.Rest.CertificateCredentials publishingCredentials = new CertificateCredentials(publishingCert);
                this.ServiceCredentials = publishingCredentials;
                break;
            }
        }
示例#4
-1
        private void create_adls_client()
        {

            var authenticationContext = new AuthenticationContext($"https://login.windows.net/{tenant_id}");
            var credential = new ClientCredential(clientId: client_id, clientSecret: client_key);
            var result = authenticationContext.AcquireToken(resource: "https://management.core.windows.net/", clientCredential: credential);

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            string token = result.AccessToken;
            var _credentials = new TokenCredentials(token);
            inner_client = new DataLakeStoreFileSystemManagementClient(_credentials);
            inner_client.SubscriptionId = subscription_id;
        }
示例#5
-1
        /// <summary>
        /// Gets the embed url for the report to render
        /// </summary>
        /// <returns></returns>
        protected override string GetEmbedUrl()
        {
            if (string.IsNullOrWhiteSpace(this.ReportId))
            {
                return null;
            }

            var accessToken = base.GetAccessToken();
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                return null;
            }

            var credentials = new TokenCredentials(accessToken);
            using (var client = new PowerBIClient(new Uri(this.BaseUri), credentials))
            {
                var report = client.Reports.GetReports(this.CollectionName, this.WorkspaceId).Value.FirstOrDefault(r => r.Id == this.ReportId);
                return report?.EmbedUrl;
            }
        }
        static async Task MainAsync()
        {
            // Get the credentials
            TokenCloudCredentials cloudCreds = GetCredsFromServicePrincipal();

            var tokenCreds = new TokenCredentials(cloudCreds.Token);

            var loggingHandler = new LoggingHandler(new HttpClientHandler());

            // Create our own HttpClient so we can do logging
            var httpClient = new HttpClient(loggingHandler);

            // Use the creds to create the clients we need
            _resourceGroupClient = new ResourceManagementClient(cloudCreds, httpClient);
            _websiteClient = new WebSiteManagementClient(tokenCreds, loggingHandler);
            _websiteClient.SubscriptionId = cloudCreds.SubscriptionId;

            await ListResourceGroupsAndSites();

            // Note: site names are globally unique, so you may need to change it to avoid conflicts
            await CreateSite("MyResourceGroup", "MyAppServicePlan", "SampleSiteFromAPI", "West US");
        }
        public object PostManage(string api_version, [FromBody]JObject data)
        {
            HttpRequestAuth reqauth = new HttpRequestAuth(Request);
            if (!reqauth.IsHeaderVerfied() )
            {
                return new
                {
                    stat = Constants.ApiStatFailure,
                    code = Constants.ApiErrorCodeInvalidParameter,
                    message = "Invalid Parameters. Wrong headers"
                };
            }
            if (!reqauth.IsTokenAuthenticated())
            {
                return new
                {
                    stat = Constants.ApiStatFailure,
                    code = Constants.ApiErrorCodeUnauthorized,
                    message = "No Token"
                };
            }

            var entities = data["entities"];
            VirtualMachineManager vmm;
            try
            {
                var credentials = new TokenCredentials(reqauth.GetTokenCache());
                vmm = new VirtualMachineManager(credentials, reqauth.GetSubID());
            }
            catch (CloudException ce)
            {
                return new
                {
                    stat = Constants.ApiStatFailure,
                    code =Constants.ApiErrorCodeUnauthorized,
                    message = ce.Message
                };
            }
            catch (Exception e)
            {
                return new
                {
                    stat = Constants.ApiStatFailure,
                    code = Constants.ApiErrorCodeUnknownExecutionError,
                    message = e.Message
                };
            }

            List<Dictionary<string,string>> result_entities = new List<Dictionary<string,string>>();

            foreach (var entity in entities)
            {
                string action = entity["action"].ToString();
                string name = entity["name"].ToString();
                string resourcegroup = entity["resourcegroup"].ToString();
                string status = string.Empty;
                string message = string.Empty;

                try
                {
                    switch(action){
                        case "start":
                            vmm.StartVirtualMachine(resourcegroup,name);
                            break;
                        case "stop":
                            vmm.StopVirtualMachine(resourcegroup,name);
                            break;
                        case "restart":
                            vmm.RestartVirtualMachine(resourcegroup,name);
                            break;
                        default:
                            status = Constants.ApiStatFailure;
                            message = "Invalid action param! Need to be either start, stop, or restart";
                            break;
                    }
                    status = Constants.ApiStatOK;
                    message = "OK";

                }
                catch (Exception e)
                {
                    status = Constants.ApiStatFailure;
                    message = e.Message;
                }
                Dictionary<string, string> result_entity = new Dictionary<string, string>();
                result_entity.Add("name", name);
                result_entity.Add("resourcegroup", resourcegroup);
                result_entity.Add("action", action);
                result_entity.Add("status", status);
                result_entity.Add("message", message);
                result_entities.Add(result_entity);
            }

            return new
            {
                stat = Constants.ApiStatOK,
                result = result_entities
            };
        }
 public VirtualMachineManager( TokenCredentials cred, string subid )
 {
     this._client = new ComputeManagementClient(cred)
                         { SubscriptionId = subid };
 }
        static void Main(string[] args)
        {
            string token = GetAuthorizationHeader();
            TokenCredentials credential = new TokenCredentials(token);
            ResourceManagementClient resourcesClient = new ResourceManagementClient(credential) { SubscriptionId = subscriptionId };
            StorageManagementClient storageMgmtClient = new StorageManagementClient(credential) { SubscriptionId = subscriptionId };

            try
            {
                //Register the Storage Resource Provider with the Subscription
                RegisterStorageResourceProvider(resourcesClient);

                //Create a new resource group
                CreateResourceGroup(rgName, resourcesClient);

                //Create a new account in a specific resource group with the specified account name
                CreateStorageAccount(rgName, accountName, storageMgmtClient);

                //Get all the account properties for a given resource group and account name
                StorageAccount storAcct = storageMgmtClient.StorageAccounts.GetProperties(rgName, accountName);

                //Get a list of storage accounts within a specific resource group
                IEnumerable<StorageAccount> storAccts = storageMgmtClient.StorageAccounts.ListByResourceGroup(rgName);

                //Get all the storage accounts for a given subscription
                IEnumerable<StorageAccount> storAcctsSub = storageMgmtClient.StorageAccounts.List();

                //Get the storage account keys for a given account and resource group
                IList<StorageAccountKey> acctKeys = storageMgmtClient.StorageAccounts.ListKeys(rgName, accountName).Keys;

                //Regenerate the account key for a given account in a specific resource group
                IList<StorageAccountKey> regenAcctKeys = storageMgmtClient.StorageAccounts.RegenerateKey(rgName, accountName, "key1").Keys;

                //Update the storage account for a given account name and resource group
                UpdateStorageAccountSku(rgName, accountName, SkuName.StandardLRS, storageMgmtClient);

                //Check if the account name is available
                bool? nameAvailable = storageMgmtClient.StorageAccounts.CheckNameAvailability(accountName).NameAvailable;

                //Delete a storage account with the given account name and a resource group
                DeleteStorageAccount(rgName, accountName, storageMgmtClient);

                Console.ReadLine();
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
示例#10
-1
        protected IPowerBIClient CreatePowerBIClient(PowerBIToken token)
        {
            var jwt = token.Generate(accessKey);
            var credentials = new TokenCredentials(jwt, "AppToken");
            var client = new PowerBIClient(credentials)
            {
                BaseUri = new Uri(apiUrl)
            };

            return client;
        }
示例#11
-1
 private SubscriptionClient GetSubscriptionClient(HttpRequestMessage request)
 {
     var creds = new TokenCredentials(request.Headers.GetValues("managementToken").First());
     var subscriptionClient = new SubscriptionClient(creds);
     subscriptionClient.SubscriptionId = Guid.Empty.ToString(); //must be set or validation error.
     return subscriptionClient;
 }
示例#12
-1
        /// <summary>
        /// Create Virtual Network Interface Card, NIC
        /// </summary>
        /// <param name="credentials">Credentials to authorize application</param>
        /// <param name="subscriptionId">SubscriptionID that identifies subscription to create resoruce in</param>
        /// <param name="resourceGroup">Name of resource group</param>
        /// <param name="location">Location for resource</param>
        /// <param name="nicName">Internal name for NIC</param>
        /// <param name="nicIPConfigName">Internal name for NIC Configuration. Sample only provides one configuration, but could be extended to provide more</param>
        /// <param name="pip">Public IP Address to be assigned to NIC</param>
        /// <param name="subnet">Subnet to use for current configuration</param>
        /// <returns>Awaitable task</returns>
        private static Task<NetworkInterface> CreateNetworkInterfaceAsync(TokenCredentials credentials, string subscriptionId, string resourceGroup, string location, string nicName, string nicIPConfigName, PublicIPAddress pip, Subnet subnet)
        {
            Console.WriteLine("Creating Network Interface");
            var networkClient = new NetworkManagementClient(credentials) { SubscriptionId = subscriptionId };
            var createNicTask = networkClient.NetworkInterfaces.CreateOrUpdateAsync(resourceGroup, nicName,
                new NetworkInterface()
                {
                    Location = location,
                    IpConfigurations = new[] {
                        new NetworkInterfaceIPConfiguration
                        {
                            Name = nicIPConfigName,
                            PrivateIPAllocationMethod = "Dynamic",
                            PublicIPAddress = pip,
                            Subnet = subnet
                        }
                    }
                });

            return createNicTask;
        }
示例#13
-1
 private IPowerBIClient CreatePowerBIClient(HttpClientHandler handler)
 {
     var credentials = new TokenCredentials(AccessKey);
     return new PowerBIClient(credentials, handler);
 }
示例#14
-1
 /// <summary>
 /// Creates (or updates existing) resource group
 /// </summary>
 /// <param name="credentials">Credentials to authorize application</param>
 /// <param name="subscriptionId">SubscriptionID that identifies subscription to create resoruce group in</param>
 /// <param name="resourceGroup">Name of resource group</param>
 /// <param name="location">Location for resource group</param>
 /// <returns>Awaitable task</returns>
 private static async Task<ResourceGroup> CreateResourceGroupAsync(TokenCredentials credentials, string subscriptionId, string resourceGroup, string location)
 {
     Console.WriteLine($"Creating Resource Group {resourceGroup}");
     var resourceClient = new ResourceManagementClient(credentials) { SubscriptionId = subscriptionId };
     return await resourceClient.ResourceGroups.CreateOrUpdateAsync(resourceGroup,
         new ResourceGroup
         {
             Location = location
         });
 }
示例#15
-1
        /// <summary>
        /// Creates new Virtual Machine using ARM APIs, one by one, building a complete Virtual Machine from the bottom up including:
        /// Resource Group, Storage Account, Public IP Address, Virtual Network, Network Interface Card and the Virtual Machine itself.
        /// 
        /// Sample showcases (among others):
        /// * Authentication against Azure AD
        /// * ARM API calls using REST
        /// * Arm API calls using Azure SDK for .NET
        /// * How parts of the deployment can be optimized using parallel tasks
        /// </summary>
        /// <returns></returns>
        async static Task ManualArmApiDeployment()
        {


#error Replace the values for storageAccountName and pipDnsName to a globally unique value and then remove or comment this row!!!
            // Globally unique values used in DNS names
            const string storageAccountName = "armstorage";                     // Globally unique name used for the created storage account, pick a name no one else could have chosen
            const string pipDnsName = "armdns";                                 // Globally unique name that will be used as part of the DNS name for your public IP and Virtual Machine

            // Parameters used in creation of Virtual Machine
            const string resourceGroup = "manualrg";                            // Name of resource group to deploy to
            const string location = "North Europe";                             // Location of deployed resources
            const string pipAddressName = "pip001";                             // Internal name for Public IP Address
            const string vNetName = "vnet001";                                  // Internal name for Virtual Network
            const string vNetAddressPrefix = "10.0.0.0/16";                     // Virtual network IP Address Range
            const string vNetSubnetName = "subnet001";                          // Internal name for Subnet
            const string vNetSubnetPrefix = "10.0.0.0/24";                      // Subnet IP Address Range
            const string nicName = "nic001";                                    // Internal name for Network Interface Card, NIC
            const string nicIPConfig = "nicipconfig001";                        // Internal name for NIC Configuration
            const string vmName = "windowsvm001";                               // Internal (in the Virtual Network) name for Virtual Machine
            const string vmSize = "Standard_D2";                                // Virtual Machine Size, notice that different location provides availability of different VM Sizes
            const string vmAdminUsername = "******";                        // Username of created user
            const string vmAdminPassword = "******";                         // Password of created user
            const string vmImagePublisher = "MicrosoftWindowsServer";           // Publisher of used source virtual harddrive image
            const string vmImageOffer = "WindowsServer";                        // Identifies offer from selected Publisher
            const string vmImageSku = "2012-R2-Datacenter";                     // Identifies SKU of selected offer
            const string vmImageVersion = "latest";                             // Version of selected Image SKU
            const string vmOSDiskName = "osdisk";                               // Internal name for VM Operating System Disk

            // Authenticate against Azure AD using client id and client secret
            var token = GetAccessToken(TenantId, ClientId, ClientSecret).AccessToken;
            var credentials = new TokenCredentials(token);

            // List subscriptions and save first subscription id (might be incorrect if you have several subscriptions)
            var subscriptionId = (await GetSubscriptionsAsync(token)).FirstOrDefault();
            if (subscriptionId == null) throw new Exception("No subscription found");

            // Create Resource Group
            //   Await the creation of the storage group since everything else in this deployment
            //   depend on the existense of the resource group.
            await CreateResourceGroupAsync(
                credentials, 
                subscriptionId, 
                resourceGroup, 
                location);

            // Create Storage Account Async
            var createStorageAccountTask = CreateStorageAccountAsync(
                credentials, 
                subscriptionId, 
                resourceGroup, 
                location, 
                storageAccountName);

            // Create Public IP Address Async
            var createPipTask = CreatePublicIPAddressAsync(credentials, 
                subscriptionId, 
                resourceGroup, 
                location, 
                pipAddressName, 
                pipDnsName);

            // Create Virtual Network Async
            var subnets = new[] { new Subnet(vNetSubnetPrefix, vNetSubnetName) };
            var createVNetTask = CreateVirtualNetworkAsync(
                credentials, 
                subscriptionId, 
                resourceGroup, 
                location, 
                vNetName, 
                vNetAddressPrefix, 
                subnets);

            // Wait for Public IP Address and Virtual Network to be created before continuing
            // creation of Virtual Network Interface, since it has a dependency to those.
            Console.WriteLine("Waiting for Public IP Address and Virtual Network to be created");
            Task.WaitAll(
                createPipTask,
                createVNetTask);
            Console.WriteLine("Proceeding");

            var pip = createPipTask.Result;
            var vNet = createVNetTask.Result;
            var subnet = vNet.Subnets.First();

            // Create Network Interface
            var createNicTask = CreateNetworkInterfaceAsync(
                credentials, 
                subscriptionId,
                resourceGroup, 
                location, 
                nicName, 
                nicIPConfig, 

                pip, 
                subnet);

            // Wait for Storage Account and Virtual Network Interface to be created before continuing
            // creation of Virtual Machine, since it has a dependency to those.
            Console.WriteLine("Waiting for Storage Account and Network Interface to be created");
            Task.WaitAll(
                createStorageAccountTask,
                createNicTask);
            Console.WriteLine("Proceeding");

            var storageAccount = createStorageAccountTask.Result;
            var nic = createNicTask.Result;

            // Create Virtual Machine
            //   This is last task to complete so await the creation of the Virtual Machine
            var vm = await CreateVirtualMachineAsync(
                credentials, 
                subscriptionId, 
                resourceGroup, 
                location, 
                storageAccountName, 
                vmName, 
                vmSize, 
                vmAdminUsername, 
                vmAdminPassword, 
                vmImagePublisher, 
                vmImageOffer, 
                vmImageSku, 
                vmImageVersion, 
                vmOSDiskName, 
                nic.Id);

            Console.WriteLine("Success!!!");
            Console.WriteLine($"VM ProvisioningState: {vm.ProvisioningState}");

        }
示例#16
-1
        async static Task TemplatedArmDeployment()
        {
            Console.Write("Template URI   :");
            var templateUri = Console.ReadLine();
            Console.Write("Parameters URI :");
            var parametersUri = Console.ReadLine();

            const string resourceGroup = "templatedrg";                         // Name of resource group to deploy to
            const string location = "North Europe";                             // Location of deployed resources

            // Authenticate against Azure AD using client id and client secret
            var token = GetAccessToken(TenantId, ClientId, ClientSecret).AccessToken;
            var credentials = new TokenCredentials(token);

            // List subscriptions and save first subscription id (might be incorrect if you have several subscriptions)
            var subscriptionId = (await GetSubscriptionsAsync(token)).FirstOrDefault();
            if (subscriptionId == null) throw new Exception("No subscription found");

            // Create Resource Group
            //   Await the creation of the storage group since everything else in this deployment
            //   depend on the existence of the resource group.
            await CreateResourceGroupAsync(
                credentials,
                subscriptionId,
                resourceGroup,
                location);

            await CreateTemplatedDeployment(credentials, subscriptionId, resourceGroup, templateUri, parametersUri);
        }
示例#17
-1
        private static async Task<DeploymentExtended> CreateTemplatedDeployment(TokenCredentials credentials, string subscriptionId, string resourceGroup, string templateUri, string parametersUri)
        {
            var resourceClient = new ResourceManagementClient(credentials) { SubscriptionId = subscriptionId };

            return await resourceClient.Deployments.BeginCreateOrUpdateAsync(resourceGroup, "mytemplateddeployment", new Deployment(
                new DeploymentProperties()
                {
                    Mode = DeploymentMode.Incremental,
                    TemplateLink = new TemplateLink(templateUri),
                    ParametersLink = new ParametersLink(parametersUri)
                }));

        }
示例#18
-1
        private static async Task MainAsync()
        {
            // Obtain an access token using the "common" AAD resource. This allows the application
            // to query AAD for information that lies outside the application's tenant (such as for
            // querying subscription information in your Azure account).
            AuthenticationContext authContext = new AuthenticationContext(AuthorityUri);
            AuthenticationResult authResult = authContext.AcquireToken(ResourceUri,
                                                                       ClientId,
                                                                       new Uri(RedirectUri),
                                                                       PromptBehavior.Auto);

            // The first credential object is used when querying for subscriptions, and is therefore
            // not associated with a specific subscription.
            ServiceClientCredentials subscriptionCreds = new TokenCredentials(authResult.AccessToken);

            string subscriptionId = String.Empty;
            using (SubscriptionClient subClient = new SubscriptionClient(subscriptionCreds))
            {
                // Ask the user to select a subscription. We'll use the selected subscription's
                // ID when constructing another credential object used in initializing the management
                // clients for the remainder of the sample.
                subscriptionId = await SelectSubscriptionAsync(subClient);
            }

            // These credentials are associated with a subscription, and can therefore be used when
            // creating Resource and Batch management clients for use in manipulating entities within
            // the subscription (e.g. resource groups and Batch accounts).
            ServiceClientCredentials creds = new TokenCredentials(authResult.AccessToken);

            // With the ResourceManagementClient, we create a resource group in which to create the Batch account.
            using (ResourceManagementClient resourceManagementClient = new ResourceManagementClient(creds))
            {
                resourceManagementClient.SubscriptionId = subscriptionId;

                // Register with the Batch resource provider; this only needs to be performed once per subscription.
                resourceManagementClient.Providers.Register(BatchNameSpace);
                
                string location = await PromptUserForLocationAsync(resourceManagementClient);
                
                await CreateResourceGroupAsync(resourceManagementClient, location);

                await PerformBatchAccountOperationsAsync(authResult.AccessToken, subscriptionId, location);

                await DeleteResourceGroupAsync(resourceManagementClient);
            }
        }
示例#19
-1
        /// <summary>
        /// 
        /// </summary>
        /// <param name="credentials">Credentials to authorize application</param>
        /// <param name="subscriptionId">SubscriptionID that identifies subscription to create resoruce in</param>
        /// <param name="resourceGroup">Name of resource group</param>
        /// <param name="location">Location for resource</param>
        /// <param name="storageAccountName">Name of Storage Account used to store Virtual HDD on</param>
        /// <param name="vmName">Name of Virtual Machine</param>
        /// <param name="vmSize">VM Size as allowed for the current location</param>
        /// <param name="vmAdminUsername">Admin username</param>
        /// <param name="vmAdminPassword">Admin password</param>
        /// <param name="vmImagePublisher">Publisher of VM Image</param>
        /// <param name="vmImageOffer">Offer from Publisher</param>
        /// <param name="vmImageSku">SKU of Offer</param>
        /// <param name="vmImageVersion">Version of SKU</param>
        /// <param name="vmOSDiskName">Internal name for operating system disk</param>
        /// <param name="nicId">NIC Identifer, used to attach NIC to VM</param>
        /// <returns>Awaitable task</returns>
        private static async Task<VirtualMachine> CreateVirtualMachineAsync(TokenCredentials credentials, string subscriptionId, string resourceGroup, string location, string storageAccountName, string vmName, string vmSize, string vmAdminUsername, string vmAdminPassword, string vmImagePublisher, string vmImageOffer, string vmImageSku, string vmImageVersion, string vmOSDiskName, string nicId)
        {
            Console.WriteLine("Creating Virtual Machine (this may take a while)");
            var computeClient = new ComputeManagementClient(credentials) { SubscriptionId = subscriptionId };
            var vm = await computeClient.VirtualMachines.CreateOrUpdateAsync(resourceGroup, vmName,
                new VirtualMachine
                {
                    Location = location,
                    HardwareProfile = new HardwareProfile(vmSize),
                    OsProfile = new OSProfile(vmName, vmAdminUsername, vmAdminPassword),
                    StorageProfile = new StorageProfile(
                        new ImageReference
                        {
                            Publisher = vmImagePublisher,
                            Offer = vmImageOffer,
                            Sku = vmImageSku,
                            Version = vmImageVersion
                        },
                        new OSDisk
                        {
                            Name = vmOSDiskName,
                            Vhd = new VirtualHardDisk($"http://{storageAccountName}.blob.core.windows.net/vhds/{vmOSDiskName}.vhd"),
                            Caching = "ReadWrite",
                            CreateOption = "FromImage"
                        }),
                    NetworkProfile = new NetworkProfile(
                        new[] { new NetworkInterfaceReference { Id = nicId } }),
                    DiagnosticsProfile = new DiagnosticsProfile(
                        new BootDiagnostics
                        {
                            Enabled = true,
                            StorageUri = $"http://{storageAccountName}.blob.core.windows.net"
                        })
                });

            return vm;
        }
示例#20
-1
        /// <summary>
        /// Create Public IP Address (with DNS name)
        /// </summary>
        /// <param name="credentials">Credentials to authorize application</param>
        /// <param name="subscriptionId">SubscriptionID that identifies subscription to create resoruce in</param>
        /// <param name="resourceGroup">Name of resource group</param>
        /// <param name="location">Location for resource</param>
        /// <param name="pipAddressName">Internal name used to identify Public IP Address within your subscription</param>
        /// <param name="pipDnsName">Globally unique name. Will be part of Fully Qualified Domain Name, FQDN, used to access resources in Azure</param>
        /// <returns>Awaitable task</returns>
        private static Task<PublicIPAddress> CreatePublicIPAddressAsync(TokenCredentials credentials, string subscriptionId, string resourceGroup, string location, string pipAddressName, string pipDnsName)
        {
            Console.WriteLine("Creating Public IP");
            var networkClient = new NetworkManagementClient(credentials) { SubscriptionId = subscriptionId };
            var createPipTask = networkClient.PublicIPAddresses.CreateOrUpdateAsync(resourceGroup, pipAddressName,
                new PublicIPAddress
                {
                    Location = location,
                    DnsSettings = new PublicIPAddressDnsSettings { DomainNameLabel = pipDnsName },
                    PublicIPAllocationMethod = "Dynamic" // This sample doesn't support Static IP Addresses but could be extended to do so
                });

            return createPipTask;
        }
示例#21
-1
        /// <summary>
        /// Create Virtual Network
        /// </summary>
        /// <param name="credentials">Credentials to authorize application</param>
        /// <param name="subscriptionId">SubscriptionID that identifies subscription to create resoruce in</param>
        /// <param name="resourceGroup">Name of resource group</param>
        /// <param name="location">Location for resource</param>
        /// <param name="vNetName">Internal name used to identify Virtual Network within your subscription</param>
        /// <param name="vNetAddressPrefix">IP Address range for Virtual Network</param>
        /// <param name="subnets">List of Subnets to be provisioned inside the Virtual Network</param>
        /// <returns>Awaitable task</returns>
        private static Task<VirtualNetwork> CreateVirtualNetworkAsync(TokenCredentials credentials, string subscriptionId, string resourceGroup, string location, string vNetName, string vNetAddressPrefix, Subnet[] subnets)
        {
            Console.WriteLine("Creating Virtual Network");
            var networkClient = new NetworkManagementClient(credentials) { SubscriptionId = subscriptionId };
            var createVNetTask = networkClient.VirtualNetworks.CreateOrUpdateAsync(resourceGroup, vNetName,
                new VirtualNetwork
                {
                    Location = location,
                    AddressSpace = new AddressSpace(new[] { vNetAddressPrefix }),
                    Subnets = subnets
                });

            return createVNetTask;
        }
示例#22
-1
 /// <summary>
 /// Creates storage account
 /// </summary>
 /// <param name="credentials">Credentials to authorize application</param>
 /// <param name="subscriptionId">SubscriptionID that identifies subscription to create resoruce in</param>
 /// <param name="resourceGroup">Name of resource group</param>
 /// <param name="location">Location for resource</param>
 /// <param name="storageAccountName">Globally unique name. Will be part of Fully Qualified Domain Name, FQDN, for Storage Account, i.e. storageAccountnName.blob.core.windows.net, etc.</param>
 /// <param name="accountType">Type of storage account to create</param>
 /// <returns>Awaitable task</returns>
 private static async Task<StorageAccount> CreateStorageAccountAsync(TokenCredentials credentials, string subscriptionId, string resourceGroup, string location, string storageAccountName, AccountType accountType = AccountType.StandardLRS)
 {
     Console.WriteLine("Creating Storage Account");
     var storageClient = new StorageManagementClient(credentials) { SubscriptionId = subscriptionId };
     return await storageClient.StorageAccounts.CreateAsync(resourceGroup, storageAccountName,
         new StorageAccountCreateParameters
         {
             Location = location,
             AccountType = accountType,
         });
 }
示例#23
-1
        private static IPowerBIClient CreatePowerBiClient(PowerBIToken token)
        {
            var jwt = token.Generate(ConfigHelper.PowerbiSigningKey);
            var credentials = new TokenCredentials(jwt, "AppToken");

            var client = new PowerBIClient(credentials)
            {
                BaseUri = new Uri(ConfigHelper.PowerbiApiUrl)
            };

            return client;
        }
示例#24
-2
        static async Task MainAsync()
        {
            // Set Environment - Choose between Azure public cloud, china cloud and US govt. cloud
            _environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];

            // Get the credentials
            TokenCloudCredentials cloudCreds = GetCredsFromServicePrincipal();
            
            var tokenCreds = new TokenCredentials(cloudCreds.Token);

            var loggingHandler = new LoggingHandler(new HttpClientHandler());

            // Create our own HttpClient so we can do logging
            var httpClient = new HttpClient(loggingHandler);

            // Use the creds to create the clients we need
            _resourceGroupClient = new ResourceManagementClient(cloudCreds, _environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), httpClient);
            _websiteClient = new WebSiteManagementClient(_environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), tokenCreds, loggingHandler);
            _websiteClient.SubscriptionId = cloudCreds.SubscriptionId;

            await ListResourceGroupsAndSites();

            // Note: site names are globally unique, so you may need to change it to avoid conflicts
            await CreateSite("MyResourceGroup", "MyAppServicePlan", "SampleSiteFromAPI", "West US");

            // Upload certificate to resource group
            await UpdateLoadCertificate("MyResourceGroup", "CertificateName", "West US", "PathToPfxFile", "CertificatePassword");
        }
示例#25
-2
        public void Run()
        {
            // Try to obtain the authorization token
            var clientCredential = new ClientCredential(clientId, clientSecret);
            var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));
            var result = context.AcquireTokenAsync("https://management.azure.com/", clientCredential).Result;

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain authorization token");
            }

            // Read the token and create the appropriate credentials object
            string token = result.AccessToken;
            var credentials = new TokenCredentials(token);

            // Read the template and parameter file contents
            JObject templateFileContents = GetJsonFileContents(pathToTemplateFile);
            JObject parameterFileContents = GetJsonFileContents(pathToParameterFile);

            // Create the resource manager client
            var resourceManagementClient = new ResourceManagementClient(credentials);
            resourceManagementClient.SubscriptionId = subscriptionId;

            // Create or check that resource group exists
            EnsureResourceGroupExists(resourceManagementClient, resourceGroupName, resourceGroupLocation);

            // Start a deployment
            DeployTemplate(resourceManagementClient, resourceGroupName, deploymentName, templateFileContents, parameterFileContents);
        }
        public static WebSiteManagementClient GetWebSiteManagementClient(IAuthSettings model)
        {
            var settings = ActiveDirectoryServiceSettings.Azure;
            var authContext = new AuthenticationContext(settings.AuthenticationEndpoint + model.Tenant);

            var token = authContext.AcquireToken(settings.TokenAudience.ToString(), new ClientCredential(model.ClientId.ToString(), model.ClientSecret));
            var creds = new TokenCredentials(token.AccessToken);

            var websiteClient = new WebSiteManagementClient(creds);
            websiteClient.SubscriptionId = model.SubscriptionId.ToString();
            return websiteClient;
        }
        public object GetListAll(string api_version)
        {
            HttpRequestAuth reqauth = new HttpRequestAuth(Request);
            if (!reqauth.IsHeaderVerfied() )
            {
                return new
                {
                    stat = Constants.ApiStatFailure,
                    code = Constants.ApiErrorCodeInvalidParameter,
                    message = "Invalid Parameters. Wrong headers"
                };
            }
            if (!reqauth.IsTokenAuthenticated())
            {
                return new
                {
                    stat = Constants.ApiStatFailure,
                    code = Constants.ApiErrorCodeUnauthorized,
                    message = "No Token"
                };
            }

            try
            {
                var credentials = new TokenCredentials(reqauth.GetTokenCache());
                var vmm = new VirtualMachineManager(credentials, reqauth.GetSubID());
                List<VirtualMachineObject> vmos = vmm.GetAllVirtualMachines();
                return new
                {
                    stat = Constants.ApiStatOK,
                    result = vmos
                };
            }
            catch (CloudException ce)
            {
                return new
                {
                    stat = Constants.ApiStatFailure,
                    code =Constants.ApiErrorCodeUnauthorized,
                    message = ce.Message
                };
            }
            catch (Exception e)
            {
                return new
                {
                    stat = Constants.ApiStatFailure,
                    code = Constants.ApiErrorCodeUnknownExecutionError,
                    message = e.Message
                };
            }
        }
示例#28
-2
        protected override string GetEmbedUrl()
        {
            if(string.IsNullOrWhiteSpace(this.DashboardId) || string.IsNullOrWhiteSpace(this.TileId))
            {
                return null;
            }

            var accessToken = base.GetAccessToken();
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                return null;
            }

            var credentials = new TokenCredentials(accessToken);
            using (var client = new PowerBIClient(new Uri(this.BaseUri), credentials))
            {
                var tile = client.Dashboards.GetTileByDashboardkeyAndTilekey(this.DashboardId, this.TileId);
                return tile.EmbedUrl;
            }
        }
示例#29
-2
        static IPowerBIClient CreateClient(PowerBIToken token, string accessKey, string apiUrl)
        {
            WorkspaceCollectionKeys accessKeys = new WorkspaceCollectionKeys()
            {
                Key1 = accessKey
            };

            // Generate a JWT token used when accessing the REST APIs
            var jwt = token.Generate(accessKeys.Key1);

            // Create a token credentials with "AppToken" type
            var credentials = new TokenCredentials(jwt, "AppToken");

            // Instantiate your Power BI client passing in the required credentials
            var client = new PowerBIClient(credentials);

            // Override the api endpoint base URL.  Default value is https://api.powerbi.com
            client.BaseUri = new Uri(apiUrl);

            return client;
        }