Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Security.Cryptography.X509Certificates;
- using System.Text;
- using System.Threading.Tasks;
- using Microsoft.WindowsAzure;
- using Microsoft.WindowsAzure.Management.Compute;
- using Microsoft.WindowsAzure.Management.Compute.Models;
- namespace PMGAzure4
- {
- class Program
- {
- public static string subscriptionId = "zzz";
- public static string base64EncodedCert = "yyy";
- static void Main(string[] args)
- {
- string vmName = "PMGATL0319-2";
- string location = "East US";
- string storageAccountName = "storageATL";
- string imageFamiliyName = "Windows Server 2012 Datacenter";
- string userName = "adminadmin";
- string password = "someKind$$$";
- SubscriptionCloudCredentials subCloudCred = getCredentials(subscriptionId, base64EncodedCert);
- ComputeManagementClient client = new ComputeManagementClient(subCloudCred);
- //You need a hosted service VM.
- try
- {
- createCloudServiceByLocation(vmName, location, subCloudCred);
- }
- catch (CloudException ce)
- {
- Console.WriteLine(ce.Message);
- }
- if (client.HostedServices.Get(vmName) == null)
- {
- createCloudServiceByLocation(vmName, location, subCloudCred);
- }
- var OSVHD = client.VirtualMachineImages.CreateOSVHD(vmName, vmName, storageAccountName, imageFamiliyName);
- var VMROle = client.VirtualMachines.CreateVMRole(vmName, vmName, VirtualMachineRoleSize.Small, userName, password, OSVHD);
- List<Role> roleList = new List<Role>{
- VMROle
- };
- client.VirtualMachines.CreateVMDeployment(vmName, vmName, roleList);
- Console.WriteLine("Create VM success");
- Console.ReadLine();
- }
- public static void createCloudServiceByLocation(string cloudServiceName, string location, SubscriptionCloudCredentials subCloudCred)
- {
- ComputeManagementClient client = new ComputeManagementClient(subCloudCred);
- HostedServiceCreateParameters hostedServiceCreateParams = new HostedServiceCreateParameters
- {
- ServiceName = cloudServiceName,
- Location = location,
- Label = EncodeToBase64(cloudServiceName),
- };
- try
- {
- client.HostedServices.Create(hostedServiceCreateParams);
- }
- catch (CloudException e)
- {
- throw e;
- }
- }
- public static void createCloudServiceByAffinityGroup(string cloudServiceName, string affinityGroupName, SubscriptionCloudCredentials subCloudCred)
- {
- ComputeManagementClient client = new ComputeManagementClient(subCloudCred);
- HostedServiceCreateParameters hostedServiceCreateParams = new HostedServiceCreateParameters
- {
- ServiceName = cloudServiceName,
- AffinityGroup = affinityGroupName,
- Label = EncodeToBase64(cloudServiceName),
- };
- try
- {
- client.HostedServices.Create(hostedServiceCreateParams);
- }
- catch (CloudException e)
- {
- throw e;
- }
- }
- public static string EncodeToBase64(string toEncode)
- {
- byte[] toEncodeAsBytes
- = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
- string returnValue
- = System.Convert.ToBase64String(toEncodeAsBytes);
- return returnValue;
- }
- public static SubscriptionCloudCredentials getCredentials(string subscriptionId, string base64EncodedCertificate)
- {
- return new CertificateCloudCredentials(subscriptionId, new X509Certificate2(Convert.FromBase64String(base64EncodedCertificate)));
- }
- /// <summary>
- /// Instantiate a new VM Role
- /// </summary>
- ///
- }
- public static class MyVirtualMachineExtension
- {
- public static Role CreateVMRole(this IVirtualMachineOperations client, string cloudServiceName, string roleName, string roleSize, string userName, string password, OSVirtualHardDisk osVHD)
- {
- Role vmRole = new Role
- {
- RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(),
- RoleName = roleName,
- Label = roleName,
- RoleSize = roleSize,
- ConfigurationSets = new List<ConfigurationSet>(),
- OSVirtualHardDisk = osVHD
- };
- ConfigurationSet configSet = new ConfigurationSet
- {
- ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration,
- EnableAutomaticUpdates = true,
- ResetPasswordOnFirstLogon = false,
- ComputerName = roleName,
- AdminUserName = userName,
- AdminPassword = password,
- InputEndpoints = new BindingList<InputEndpoint>
- {
- new InputEndpoint { LocalPort = 3389, Name = "RDP", Protocol = "tcp" },
- new InputEndpoint { LocalPort = 80, Port = 80, Name = "web", Protocol = "tcp" }
- }
- };
- vmRole.ConfigurationSets.Add(configSet);
- return vmRole;
- }
- public static OSVirtualHardDisk CreateOSVHD(this IVirtualMachineImageOperations operation, string cloudserviceName, string vmName, string storageAccount, string imageFamiliyName)
- {
- try
- {
- var osVHD = new OSVirtualHardDisk
- {
- MediaLink = GetVhdUri(string.Format("{0}.blob.core.windows.net/vhds", storageAccount), cloudserviceName, vmName),
- SourceImageName = GetSourceImageNameByFamliyName(operation, imageFamiliyName)
- };
- return osVHD;
- }
- catch (CloudException e)
- {
- throw e;
- }
- }
- private static string GetSourceImageNameByFamliyName(this IVirtualMachineImageOperations operation, string imageFamliyName)
- {
- var disk = operation.List().Where(o => o.ImageFamily == imageFamliyName).FirstOrDefault();
- if (disk != null)
- {
- return disk.Name;
- }
- else
- {
- throw new CloudException(string.Format("Can't find {0} OS image in current subscription"));
- }
- }
- private static Uri GetVhdUri(string blobcontainerAddress, string cloudServiceName, string vmName, bool cacheDisk = false, bool https = false)
- {
- var now = DateTime.UtcNow;
- string dateString = now.Year + "-" + now.Month + "-" + now.Day;
- var address = string.Format("http{0}://{1}/{2}-{3}-{4}-{5}-650.vhd", https ? "s" : string.Empty, blobcontainerAddress, cloudServiceName, vmName, cacheDisk ? "-CacheDisk" : string.Empty, dateString);
- return new Uri(address);
- }
- public static void CreateVMDeployment(this IVirtualMachineOperations operations, string cloudServiceName, string deploymentName, List<Role> roleList, DeploymentSlot slot = DeploymentSlot.Production)
- {
- try
- {
- VirtualMachineCreateDeploymentParameters createDeploymentParams = new VirtualMachineCreateDeploymentParameters
- {
- Name = deploymentName,
- Label = cloudServiceName,
- Roles = roleList,
- DeploymentSlot = slot
- };
- operations.CreateDeployment(cloudServiceName, createDeploymentParams);
- }
- catch (CloudException ce)
- {
- WebException we = (WebException)ce.InnerException;
- Console.WriteLine(ce.Response.ToString());
- // var err = new StreamReader(ce.Response.GetResponseStream()).ReadToEnd();
- // Console.WriteLine(err);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment