protected override void ProcessRecord()
        {
            Uri    uri;
            string diskLabel;

            try
            {
                base.ProcessRecord();
                this.ValidateParameters();
                if (string.IsNullOrEmpty(this.Label))
                {
                    this.Label = this.Name;
                }
                this.Label = ServiceManagementHelper.EncodeToBase64String(this.Label);
                PersistentVM persistentVM = new PersistentVM();
                persistentVM.AvailabilitySetName  = this.AvailabilitySetName;
                persistentVM.ConfigurationSets    = new Collection <ConfigurationSet>();
                persistentVM.DataVirtualHardDisks = new Collection <DataVirtualHardDisk>();
                persistentVM.RoleName             = this.Name;
                persistentVM.RoleSize             = this.InstanceSize;
                persistentVM.RoleType             = "PersistentVMRole";
                persistentVM.Label = this.Label;
                PersistentVM      persistentVM1     = persistentVM;
                PersistentVM      persistentVM2     = persistentVM1;
                OSVirtualHardDisk oSVirtualHardDisk = new OSVirtualHardDisk();
                oSVirtualHardDisk.DiskName        = this.DiskName;
                oSVirtualHardDisk.SourceImageName = this.ImageName;
                OSVirtualHardDisk oSVirtualHardDisk1 = oSVirtualHardDisk;
                if (string.IsNullOrEmpty(this.MediaLocation))
                {
                    uri = null;
                }
                else
                {
                    uri = new Uri(this.MediaLocation);
                }
                oSVirtualHardDisk1.MediaLink  = uri;
                oSVirtualHardDisk.HostCaching = this.HostCaching;
                OSVirtualHardDisk oSVirtualHardDisk2 = oSVirtualHardDisk;
                if (string.IsNullOrEmpty(this.DiskLabel))
                {
                    diskLabel = null;
                }
                else
                {
                    diskLabel = this.DiskLabel;
                }
                oSVirtualHardDisk2.DiskLabel    = diskLabel;
                persistentVM2.OSVirtualHardDisk = oSVirtualHardDisk;
                CmdletExtensions.WriteVerboseOutputForObject(this, persistentVM1);
                base.WriteObject(persistentVM1, true);
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                base.WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
            }
        }
Example #2
0
        private static OSVirtualHardDisk SetOsVirtualHardDisk(string virtualMachineName, string storageAccountName,
                                                              string imageName)
        {
            var vhd = new OSVirtualHardDisk
            {
                SourceImageName = imageName,
                HostCaching     = VirtualHardDiskHostCaching.ReadWrite,
                MediaLink       = new Uri(string.Format(CultureInfo.InvariantCulture,
                                                        "https://{0}.blob.core.windows.net/vhds/{1}.vhd", storageAccountName, virtualMachineName),
                                          UriKind.Absolute)
            };

            return(vhd);
        }
Example #3
0
        internal void ExecuteCommand()
        {
            var role = VM.GetInstance();

            if (role.OSVirtualHardDisk == null)
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new InvalidOperationException(Resources.OSDiskNotDefinedForVM),
                        string.Empty,
                        ErrorCategory.InvalidData,
                        null));
            }

            OSVirtualHardDisk disk = role.OSVirtualHardDisk;

            disk.HostCaching = HostCaching;
            WriteObject(VM, true);
        }
Example #4
0
        internal void ExecuteCommand()
        {
            var role = VM.GetInstance();

            if (role.OSVirtualHardDisk == null)
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new InvalidOperationException("An OSDisk has not been defined for this VM. Use New-OSDisk to assign a new OS disk."),
                        string.Empty,
                        ErrorCategory.InvalidData,
                        null));
            }

            OSVirtualHardDisk disk = role.OSVirtualHardDisk;

            disk.HostCaching = HostCaching;
            WriteObject(VM, true);
        }
        /// <summary>
        ///     Create virtual machine
        /// </summary>
        /// <param name="hostedServiceName"></param>
        /// <param name="osVirtualHardDisk"></param>
        /// <param name="configurationSets"></param>
        /// <param name="dataVirtualHardDisks"></param>
        /// <param name="virtualMachineName"></param>
        /// <param name="deploymentName"></param>
        /// <returns></returns>
        public string CreateVirtualMachine(
            string hostedServiceName,
            OSVirtualHardDisk osVirtualHardDisk,
            IList <ConfigurationSet> configurationSets,
            IList <DataVirtualHardDisk> dataVirtualHardDisks = null,
            string virtualMachineName = "",
            string deploymentName     = "")
        {
            if (string.IsNullOrEmpty(deploymentName))
            {
                deploymentName = Dependencies.TestResourcesCollector.GetUniqueDeploymentName();
            }

            if (string.IsNullOrEmpty(virtualMachineName))
            {
                virtualMachineName = Dependencies.TestResourcesCollector.GetUniqueVirtualMachineName();
            }

            var csm = new AzureCloudServiceManager();

            csm.CreateOrUpdateDeployment(hostedServiceName, new DeploymentCreateParameters {
                Name = deploymentName
            });

            var vmDeployment = csm.CreateOrUpdateDeployment(hostedServiceName, new DeploymentCreateParameters {
                Name  = deploymentName,
                Label = Base64EncodingHelper.EncodeToBase64String(AzureServiceConstants.DefaultLabel)
            });

            var vmRole = new Role
            {
                RoleName             = virtualMachineName,
                RoleType             = "PersistentVMRole",
                OSVirtualHardDisk    = osVirtualHardDisk,
                ConfigurationSets    = configurationSets,
                DataVirtualHardDisks = dataVirtualHardDisks
            };

            vmDeployment.Roles.Add(vmRole);

            return(CreateVirtualMachine(hostedServiceName, vmDeployment, virtualMachineName));
        }
 protected override void ProcessRecord()
 {
     try
     {
         base.ProcessRecord();
         PersistentVM instance = base.VM.GetInstance();
         if (instance.OSVirtualHardDisk == null)
         {
             base.ThrowTerminatingError(new ErrorRecord(new InvalidOperationException("An OSDisk has not been defined for this VM. Use New-OSDisk to assign a new OS disk."), string.Empty, ErrorCategory.InvalidData, null));
         }
         OSVirtualHardDisk oSVirtualHardDisk = instance.OSVirtualHardDisk;
         oSVirtualHardDisk.HostCaching = this.HostCaching;
         base.WriteObject(base.VM, true);
     }
     catch (Exception exception1)
     {
         Exception exception = exception1;
         base.WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
     }
 }
Example #7
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="vm"></param>
 /// <param name="expOS"></param>
 /// <param name="expHC"></param>
 /// <returns></returns>
 internal static bool AzureOsDisk(PersistentVM vm, string expOS, HostCaching expHC)
 {
     try
     {
         OSVirtualHardDisk osdisk = vmPowershellCmdlets.GetAzureOSDisk(vm);
         Console.WriteLine("OS Disk: Name - {0}, Label - {1}, HostCaching - {2}, OS - {3}", osdisk.DiskName, osdisk.DiskLabel, osdisk.HostCaching, osdisk.OS);
         Assert.IsTrue(osdisk.Equals(vm.OSVirtualHardDisk), "OS disk returned is not the same!");
         Assert.AreEqual(expOS, osdisk.OS);
         Assert.AreEqual(expHC.ToString(), osdisk.HostCaching);
         return(true);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
         if (e is AssertFailedException)
         {
             return(false);
         }
         else
         {
             throw;
         }
     }
 }
Example #8
0
		public void NewAzureVMProcess()
		{
			NewQuickVM.NewQuickVM variable = null;
			string serviceName;
			string instanceSize;
			Uri uri;
			string name;
			string str;
			Action<string> action = null;
			SubscriptionData currentSubscription = CmdletSubscriptionExtensions.GetCurrentSubscription(this);
			CloudStorageAccount currentStorageAccount = null;
			try
			{
				currentStorageAccount = currentSubscription.GetCurrentStorageAccount(base.Channel);
			}
			catch (EndpointNotFoundException endpointNotFoundException)
			{
				throw new ArgumentException("CurrentStorageAccount is not accessible. Ensure the current storage account is accessible and in the same location or affinity group as your cloud service.");
			}
			if (currentStorageAccount != null)
			{
				NewQuickVM.NewQuickVM variable1 = variable;
				PersistentVMRole persistentVMRole = new PersistentVMRole();
				persistentVMRole.AvailabilitySetName = this.AvailabilitySetName;
				persistentVMRole.ConfigurationSets = new Collection<ConfigurationSet>();
				persistentVMRole.DataVirtualHardDisks = new Collection<DataVirtualHardDisk>();
				PersistentVMRole persistentVMRole1 = persistentVMRole;
				if (string.IsNullOrEmpty(this.Name))
				{
					serviceName = this.ServiceName;
				}
				else
				{
					serviceName = this.Name;
				}
				persistentVMRole1.RoleName = serviceName;
				PersistentVMRole persistentVMRole2 = persistentVMRole;
				if (string.IsNullOrEmpty(this.InstanceSize))
				{
					instanceSize = null;
				}
				else
				{
					instanceSize = this.InstanceSize;
				}
				persistentVMRole2.RoleSize = instanceSize;
				persistentVMRole.RoleType = "PersistentVMRole";
				persistentVMRole.Label = ServiceManagementHelper.EncodeToBase64String(this.ServiceName);
				variable1.vm = persistentVMRole;
				PersistentVMRole persistentVMRole3 = uri1;
				OSVirtualHardDisk oSVirtualHardDisk = new OSVirtualHardDisk();
				oSVirtualHardDisk.DiskName = null;
				oSVirtualHardDisk.SourceImageName = this.ImageName;
				OSVirtualHardDisk oSVirtualHardDisk1 = oSVirtualHardDisk;
				if (string.IsNullOrEmpty(this.MediaLocation))
				{
					uri = null;
				}
				else
				{
					uri = new Uri(this.MediaLocation);
				}
				oSVirtualHardDisk1.MediaLink = uri;
				oSVirtualHardDisk.HostCaching = this.HostCaching;
				persistentVMRole3.OSVirtualHardDisk = oSVirtualHardDisk;
				if (oSVirtualHardDisk1.MediaLink == null && string.IsNullOrEmpty(oSVirtualHardDisk1.DiskName))
				{
					DateTime now = DateTime.Now;
					object[] roleName = new object[6];
					roleName[0] = this.ServiceName;
					roleName[1] = uri1.RoleName;
					roleName[2] = now.Year;
					roleName[3] = now.Month;
					roleName[4] = now.Day;
					roleName[5] = now.Millisecond;
					string str1 = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", roleName);
					string absoluteUri = currentStorageAccount.BlobEndpoint.AbsoluteUri;
					if (!absoluteUri.EndsWith("/"))
					{
						absoluteUri = string.Concat(absoluteUri, "/");
					}
					oSVirtualHardDisk1.MediaLink = new Uri(string.Concat(absoluteUri, "vhds/", str1));
				}
				NetworkConfigurationSet networkConfigurationSet = new NetworkConfigurationSet();
				networkConfigurationSet.InputEndpoints = new Collection<InputEndpoint>();
				if (this.SubnetNames != null)
				{
					networkConfigurationSet.SubnetNames = new SubnetNamesCollection();
					string[] subnetNames = this.SubnetNames;
					for (int i = 0; i < (int)subnetNames.Length; i++)
					{
						string str2 = subnetNames[i];
						networkConfigurationSet.SubnetNames.Add(str2);
					}
				}
				if (!base.ParameterSetName.Equals("Windows", StringComparison.OrdinalIgnoreCase))
				{
					LinuxProvisioningConfigurationSet linuxProvisioningConfigurationSet = new LinuxProvisioningConfigurationSet();
					LinuxProvisioningConfigurationSet linuxProvisioningConfigurationSet1 = linuxProvisioningConfigurationSet;
					if (string.IsNullOrEmpty(this.Name))
					{
						name = this.ServiceName;
					}
					else
					{
						name = this.Name;
					}
					linuxProvisioningConfigurationSet1.HostName = name;
					linuxProvisioningConfigurationSet.UserName = this.LinuxUser;
					linuxProvisioningConfigurationSet.UserPassword = this.Password;
					linuxProvisioningConfigurationSet.DisableSshPasswordAuthentication = new bool?(false);
					if (this.SSHKeyPairs != null && this.SSHKeyPairs.Count > 0 || this.SSHPublicKeys != null && this.SSHPublicKeys.Count > 0)
					{
						linuxProvisioningConfigurationSet.SSH = new LinuxProvisioningConfigurationSet.SSHSettings();
						linuxProvisioningConfigurationSet.SSH.PublicKeys = this.SSHPublicKeys;
						linuxProvisioningConfigurationSet.SSH.KeyPairs = this.SSHKeyPairs;
					}
					InputEndpoint inputEndpoint = new InputEndpoint();
					inputEndpoint.LocalPort = 22;
					inputEndpoint.Protocol = "tcp";
					inputEndpoint.Name = "SSH";
					networkConfigurationSet.InputEndpoints.Add(inputEndpoint);
					uri1.ConfigurationSets.Add(linuxProvisioningConfigurationSet);
					uri1.ConfigurationSets.Add(networkConfigurationSet);
				}
				else
				{
					WindowsProvisioningConfigurationSet windowsProvisioningConfigurationSet = new WindowsProvisioningConfigurationSet();
					windowsProvisioningConfigurationSet.AdminPassword = this.Password;
					WindowsProvisioningConfigurationSet windowsProvisioningConfigurationSet1 = windowsProvisioningConfigurationSet;
					if (string.IsNullOrEmpty(this.Name))
					{
						str = this.ServiceName;
					}
					else
					{
						str = this.Name;
					}
					windowsProvisioningConfigurationSet1.ComputerName = str;
					windowsProvisioningConfigurationSet.EnableAutomaticUpdates = new bool?(true);
					windowsProvisioningConfigurationSet.ResetPasswordOnFirstLogon = false;
					windowsProvisioningConfigurationSet.StoredCertificateSettings = this.Certificates;
					InputEndpoint inputEndpoint1 = new InputEndpoint();
					inputEndpoint1.LocalPort = 0xd3d;
					inputEndpoint1.Protocol = "tcp";
					inputEndpoint1.Name = "RemoteDesktop";
					networkConfigurationSet.InputEndpoints.Add(inputEndpoint1);
					uri1.ConfigurationSets.Add(windowsProvisioningConfigurationSet);
					uri1.ConfigurationSets.Add(networkConfigurationSet);
				}
				new List<string>();
				Operation operation = null;
				bool flag = this.DoesCloudServiceExist(this.ServiceName);
				using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
				{
					try
					{
						DateTime dateTime = DateTime.Now;
						DateTime universalTime = dateTime.ToUniversalTime();
						string str3 = string.Format("Implicitly created hosted service{0}", universalTime.ToString("yyyy-MM-dd HH:mm"));
						if (!string.IsNullOrEmpty(this.Location) || !string.IsNullOrEmpty(this.AffinityGroup) || !string.IsNullOrEmpty(this.VNetName) && !flag)
						{
							CreateHostedServiceInput createHostedServiceInput = new CreateHostedServiceInput();
							createHostedServiceInput.AffinityGroup = this.AffinityGroup;
							createHostedServiceInput.Location = this.Location;
							createHostedServiceInput.ServiceName = this.ServiceName;
							createHostedServiceInput.Description = str3;
							createHostedServiceInput.Label = ServiceManagementHelper.EncodeToBase64String(this.ServiceName);
							CmdletExtensions.WriteVerboseOutputForObject(this, createHostedServiceInput);
							base.RetryCall((string s) => base.Channel.CreateHostedService(s, createHostedServiceInput));
							Operation operation1 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create Cloud Service"));
							ManagementOperationContext managementOperationContext = new ManagementOperationContext();
							managementOperationContext.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create Cloud Service"));
							managementOperationContext.set_OperationId(operation1.OperationTrackingId);
							managementOperationContext.set_OperationStatus(operation1.Status);
							ManagementOperationContext managementOperationContext1 = managementOperationContext;
							base.WriteObject(managementOperationContext1, true);
						}
					}
					catch (CommunicationException communicationException1)
					{
						CommunicationException communicationException = communicationException1;
						this.WriteErrorDetails(communicationException);
						return;
					}
				}
				if (operation == null || string.Compare(operation.Status, "Failed", StringComparison.OrdinalIgnoreCase) != 0)
				{
					if (base.CurrentDeployment != null)
					{
						if (this.VNetName != null || this.DnsSettings != null)
						{
							base.WriteWarning("VNetName or DnsSettings can only be specified on new deployments.");
						}
					}
					else
					{
						using (OperationContextScope operationContextScope1 = new OperationContextScope((IContextChannel)base.Channel))
						{
							try
							{
								Deployment deployment = new Deployment();
								deployment.DeploymentSlot = "Production";
								deployment.Name = this.ServiceName;
								deployment.Label = this.ServiceName;
								List<Role> roles = new List<Role>();
								roles.Add(uri1);
								deployment.RoleList = new RoleList(roles);
								deployment.VirtualNetworkName = this.VNetName;
								Deployment dnsSetting = deployment;
								if (this.DnsSettings != null)
								{
									dnsSetting.Dns = new DnsSettings();
									dnsSetting.Dns.DnsServers = new DnsServerList();
									DnsServer[] dnsSettings = this.DnsSettings;
									for (int j = 0; j < (int)dnsSettings.Length; j++)
									{
										DnsServer dnsServer = dnsSettings[j];
										dnsSetting.Dns.DnsServers.Add(dnsServer);
									}
								}
								CmdletExtensions.WriteVerboseOutputForObject(this, dnsSetting);
								base.RetryCall((string s) => base.Channel.CreateDeployment(s, this.ServiceName, dnsSetting));
								Operation operation2 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create Deployment with VM ", uri1.RoleName));
								ManagementOperationContext managementOperationContext2 = new ManagementOperationContext();
								managementOperationContext2.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create Deployment with VM ", uri1.RoleName));
								managementOperationContext2.set_OperationId(operation2.OperationTrackingId);
								managementOperationContext2.set_OperationStatus(operation2.Status);
								ManagementOperationContext managementOperationContext3 = managementOperationContext2;
								base.WriteObject(managementOperationContext3, true);
							}
							catch (CommunicationException communicationException3)
							{
								CommunicationException communicationException2 = communicationException3;
								if (communicationException2 as EndpointNotFoundException == null)
								{
									this.WriteErrorDetails(communicationException2);
									return;
								}
								else
								{
									throw new Exception("Cloud Service does not exist. Specify -Location or -Affinity group to create one.");
								}
							}
							this.CreatedDeployment = true;
						}
					}
					if (operation == null || string.Compare(operation.Status, "Failed", StringComparison.OrdinalIgnoreCase) != 0)
					{
						if (!this.CreatedDeployment)
						{
							using (OperationContextScope operationContextScope2 = new OperationContextScope((IContextChannel)base.Channel))
							{
								try
								{
									CmdletExtensions.WriteVerboseOutputForObject(this, uri1);
									NewQuickVM newQuickVM = this;
									if (action == null)
									{
										action = (string s) => base.Channel.AddRole(s, this.ServiceName, this.ServiceName, uri1);
									}
									((CmdletBase<IServiceManagement>)newQuickVM).RetryCall(action);
									Operation operation3 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create VM ", uri1.RoleName));
									ManagementOperationContext managementOperationContext4 = new ManagementOperationContext();
									managementOperationContext4.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create VM ", uri1.RoleName));
									managementOperationContext4.set_OperationId(operation3.OperationTrackingId);
									managementOperationContext4.set_OperationStatus(operation3.Status);
									ManagementOperationContext managementOperationContext5 = managementOperationContext4;
									base.WriteObject(managementOperationContext5, true);
								}
								catch (CommunicationException communicationException5)
								{
									CommunicationException communicationException4 = communicationException5;
									this.WriteErrorDetails(communicationException4);
									return;
								}
							}
						}
						return;
					}
					else
					{
						return;
					}
				}
				return;
			}
			else
			{
				throw new ArgumentException("CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it.");
			}
		}
Example #9
0
		protected override void ProcessRecord()
		{
			Uri uri;
			string diskLabel;
			try
			{
				base.ProcessRecord();
				this.ValidateParameters();
				if (string.IsNullOrEmpty(this.Label))
				{
					this.Label = this.Name;
				}
				this.Label = ServiceManagementHelper.EncodeToBase64String(this.Label);
				PersistentVM persistentVM = new PersistentVM();
				persistentVM.AvailabilitySetName = this.AvailabilitySetName;
				persistentVM.ConfigurationSets = new Collection<ConfigurationSet>();
				persistentVM.DataVirtualHardDisks = new Collection<DataVirtualHardDisk>();
				persistentVM.RoleName = this.Name;
				persistentVM.RoleSize = this.InstanceSize;
				persistentVM.RoleType = "PersistentVMRole";
				persistentVM.Label = this.Label;
				PersistentVM persistentVM1 = persistentVM;
				PersistentVM persistentVM2 = persistentVM1;
				OSVirtualHardDisk oSVirtualHardDisk = new OSVirtualHardDisk();
				oSVirtualHardDisk.DiskName = this.DiskName;
				oSVirtualHardDisk.SourceImageName = this.ImageName;
				OSVirtualHardDisk oSVirtualHardDisk1 = oSVirtualHardDisk;
				if (string.IsNullOrEmpty(this.MediaLocation))
				{
					uri = null;
				}
				else
				{
					uri = new Uri(this.MediaLocation);
				}
				oSVirtualHardDisk1.MediaLink = uri;
				oSVirtualHardDisk.HostCaching = this.HostCaching;
				OSVirtualHardDisk oSVirtualHardDisk2 = oSVirtualHardDisk;
				if (string.IsNullOrEmpty(this.DiskLabel))
				{
					diskLabel = null;
				}
				else
				{
					diskLabel = this.DiskLabel;
				}
				oSVirtualHardDisk2.DiskLabel = diskLabel;
				persistentVM2.OSVirtualHardDisk = oSVirtualHardDisk;
				CmdletExtensions.WriteVerboseOutputForObject(this, persistentVM1);
				base.WriteObject(persistentVM1, true);
			}
			catch (Exception exception1)
			{
				Exception exception = exception1;
				base.WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
			}
		}
        private static string CreateDeployment(SubscriptionCloudCredentials creds, RootCreateVMObject root, Subscription sub, TextWriter log)
        {
            InputEndpoint rdEndpoint = new InputEndpoint();

            rdEndpoint.EnableDirectServerReturn = false;
            rdEndpoint.EndpointAcl = null;
            rdEndpoint.LocalPort   = 3389;
            rdEndpoint.Port        = 3389;
            rdEndpoint.Name        = "RD";
            rdEndpoint.Protocol    = "TCP";

            List <Role> roles = new List <Role>();

            foreach (JSONVM vm in root.createvm.VM)
            {
                ConfigurationSet set = new ConfigurationSet();
                set.AdminPassword             = vm.ConfigurationSet.AdminPassword;
                set.AdminUserName             = vm.ConfigurationSet.AdminUserName;
                set.ComputerName              = vm.ConfigurationSet.ComputerName; // Host Name in portal
                set.ConfigurationSetType      = ConfigurationSetTypes.WindowsProvisioningConfiguration;
                set.ResetPasswordOnFirstLogon = false;

                OSVirtualHardDisk disk = new OSVirtualHardDisk();
                disk.HostCaching     = VirtualHardDiskHostCaching.ReadWrite;
                disk.Label           = "osdisk";
                disk.SourceImageName = vm.OSVirtualHardDisk.SourceImageName;
                string mediaLink = string.Format("https://{0}.blob.core.windows.net/{1}/{2}-{3}-osdisk.vhd",
                                                 vm.OSVirtualHardDisk.StorageAccount,
                                                 vm.OSVirtualHardDisk.Container,
                                                 root.createvm.Service.ServiceName,
                                                 vm.ConfigurationSet.ComputerName);
                disk.MediaLink = new Uri(mediaLink);

                Role r = new Role();
                r.ConfigurationSets.Add(set);
                r.Label               = vm.Name + "-label";
                r.OSVirtualHardDisk   = disk;
                r.RoleName            = vm.Name;                  // VM Name in portal
                r.RoleSize            = vm.Size;                  // permitted values = enum VirtualMachineRoleSize
                r.RoleType            = VirtualMachineRoleType.PersistentVMRole.ToString();
                r.OSVersion           = "Windows Server 2012 R2"; // appears to be simply a string, no function
                r.ProvisionGuestAgent = true;

                roles.Add(r);
            }

            try
            {
                using (var client = new ComputeManagementClient(creds))
                {
                    OperationStatusResponse resp = client.VirtualMachines.CreateDeployment(root.createvm.Service.ServiceName,
                                                                                           new VirtualMachineCreateDeploymentParameters
                    {
                        DeploymentSlot = DeploymentSlot.Production,
                        Label          = root.createvm.Service.ServiceName + "-label",
                        Name           = root.createvm.Service.DeploymentName,   // this goes into the name of the status file for the VHD, it's also used for future operations on this VM
                        Roles          = roles
                    });
                    return(resp.RequestId);
                }
            }
            catch (Exception ex)
            {
                // get a 404 if the cloud service doesn't exist
                string msg = string.Format("Exception creating VM: {0}", ex.Message);
                Common.LogExit(msg, root.createvm.Service.ServiceName, log);
                return(null);
            }
        }
        private static string CreateVM(SubscriptionCloudCredentials creds, RootCreateVMObject root, Subscription sub, TextWriter log)
        {
            InputEndpoint rdEndpoint = new InputEndpoint();

            rdEndpoint.EnableDirectServerReturn = false;
            rdEndpoint.EndpointAcl = null;
            rdEndpoint.LocalPort   = 3389;
            rdEndpoint.Port        = 3389;
            rdEndpoint.Name        = "RD";
            rdEndpoint.Protocol    = "TCP";

            ConfigurationSet set = new ConfigurationSet();

            set.AdminPassword             = root.createvm.VM[0].ConfigurationSet.AdminPassword;
            set.AdminUserName             = root.createvm.VM[0].ConfigurationSet.AdminUserName;
            set.ComputerName              = root.createvm.VM[0].ConfigurationSet.ComputerName; // Host Name in portal
            set.ConfigurationSetType      = ConfigurationSetTypes.WindowsProvisioningConfiguration;
            set.ResetPasswordOnFirstLogon = false;

            List <ConfigurationSet> sets = new List <ConfigurationSet>();

            sets.Add(set);

            OSVirtualHardDisk disk = new OSVirtualHardDisk();

            disk.HostCaching     = VirtualHardDiskHostCaching.ReadWrite;
            disk.Label           = "osdisk";
            disk.SourceImageName = root.createvm.VM[0].OSVirtualHardDisk.SourceImageName;
            string mediaLink = string.Format("https://{0}.blob.core.windows.net/{1}/{2}-{3}-osdisk.vhd",
                                             root.createvm.VM[0].OSVirtualHardDisk.StorageAccount,
                                             root.createvm.VM[0].OSVirtualHardDisk.Container,
                                             root.createvm.Service.ServiceName,
                                             root.createvm.VM[0].ConfigurationSet.ComputerName);

            disk.MediaLink = new Uri(mediaLink);

            try
            {
                using (var client = new ComputeManagementClient(creds))
                {
                    OperationStatusResponse resp = client.VirtualMachines.Create(
                        root.createvm.Service.ServiceName,
                        root.createvm.Service.DeploymentName,
                        new VirtualMachineCreateParameters
                    {
                        ConfigurationSets   = sets,
                        OSVirtualHardDisk   = disk,
                        RoleName            = root.createvm.VM[0].Name, // this goes into the name of the status file for the VHD, it's also used for future operations on this VM
                        RoleSize            = root.createvm.VM[0].Size,
                        ProvisionGuestAgent = true
                    });
                    return(resp.RequestId);
                }
            }
            catch (Exception ex)
            {
                // get a 404 if the cloud service doesn't exist
                string msg = string.Format("Exception creating VM: {0}", ex.Message);
                Common.LogExit(msg, root.createvm.Service.ServiceName, log);
                return(null);
            }
        }
Example #12
0
        public void NewAzureVMProcess()
        {
            NewQuickVM.NewQuickVM variable = null;
            string              serviceName;
            string              instanceSize;
            Uri                 uri;
            string              name;
            string              str;
            Action <string>     action = null;
            SubscriptionData    currentSubscription   = CmdletSubscriptionExtensions.GetCurrentSubscription(this);
            CloudStorageAccount currentStorageAccount = null;

            try
            {
                currentStorageAccount = currentSubscription.GetCurrentStorageAccount(base.Channel);
            }
            catch (EndpointNotFoundException endpointNotFoundException)
            {
                throw new ArgumentException("CurrentStorageAccount is not accessible. Ensure the current storage account is accessible and in the same location or affinity group as your cloud service.");
            }
            if (currentStorageAccount != null)
            {
                NewQuickVM.NewQuickVM variable1        = variable;
                PersistentVMRole      persistentVMRole = new PersistentVMRole();
                persistentVMRole.AvailabilitySetName  = this.AvailabilitySetName;
                persistentVMRole.ConfigurationSets    = new Collection <ConfigurationSet>();
                persistentVMRole.DataVirtualHardDisks = new Collection <DataVirtualHardDisk>();
                PersistentVMRole persistentVMRole1 = persistentVMRole;
                if (string.IsNullOrEmpty(this.Name))
                {
                    serviceName = this.ServiceName;
                }
                else
                {
                    serviceName = this.Name;
                }
                persistentVMRole1.RoleName = serviceName;
                PersistentVMRole persistentVMRole2 = persistentVMRole;
                if (string.IsNullOrEmpty(this.InstanceSize))
                {
                    instanceSize = null;
                }
                else
                {
                    instanceSize = this.InstanceSize;
                }
                persistentVMRole2.RoleSize = instanceSize;
                persistentVMRole.RoleType  = "PersistentVMRole";
                persistentVMRole.Label     = ServiceManagementHelper.EncodeToBase64String(this.ServiceName);
                variable1.vm = persistentVMRole;
                PersistentVMRole  persistentVMRole3 = uri1;
                OSVirtualHardDisk oSVirtualHardDisk = new OSVirtualHardDisk();
                oSVirtualHardDisk.DiskName        = null;
                oSVirtualHardDisk.SourceImageName = this.ImageName;
                OSVirtualHardDisk oSVirtualHardDisk1 = oSVirtualHardDisk;
                if (string.IsNullOrEmpty(this.MediaLocation))
                {
                    uri = null;
                }
                else
                {
                    uri = new Uri(this.MediaLocation);
                }
                oSVirtualHardDisk1.MediaLink        = uri;
                oSVirtualHardDisk.HostCaching       = this.HostCaching;
                persistentVMRole3.OSVirtualHardDisk = oSVirtualHardDisk;
                if (oSVirtualHardDisk1.MediaLink == null && string.IsNullOrEmpty(oSVirtualHardDisk1.DiskName))
                {
                    DateTime now      = DateTime.Now;
                    object[] roleName = new object[6];
                    roleName[0] = this.ServiceName;
                    roleName[1] = uri1.RoleName;
                    roleName[2] = now.Year;
                    roleName[3] = now.Month;
                    roleName[4] = now.Day;
                    roleName[5] = now.Millisecond;
                    string str1        = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", roleName);
                    string absoluteUri = currentStorageAccount.BlobEndpoint.AbsoluteUri;
                    if (!absoluteUri.EndsWith("/"))
                    {
                        absoluteUri = string.Concat(absoluteUri, "/");
                    }
                    oSVirtualHardDisk1.MediaLink = new Uri(string.Concat(absoluteUri, "vhds/", str1));
                }
                NetworkConfigurationSet networkConfigurationSet = new NetworkConfigurationSet();
                networkConfigurationSet.InputEndpoints = new Collection <InputEndpoint>();
                if (this.SubnetNames != null)
                {
                    networkConfigurationSet.SubnetNames = new SubnetNamesCollection();
                    string[] subnetNames = this.SubnetNames;
                    for (int i = 0; i < (int)subnetNames.Length; i++)
                    {
                        string str2 = subnetNames[i];
                        networkConfigurationSet.SubnetNames.Add(str2);
                    }
                }
                if (!base.ParameterSetName.Equals("Windows", StringComparison.OrdinalIgnoreCase))
                {
                    LinuxProvisioningConfigurationSet linuxProvisioningConfigurationSet  = new LinuxProvisioningConfigurationSet();
                    LinuxProvisioningConfigurationSet linuxProvisioningConfigurationSet1 = linuxProvisioningConfigurationSet;
                    if (string.IsNullOrEmpty(this.Name))
                    {
                        name = this.ServiceName;
                    }
                    else
                    {
                        name = this.Name;
                    }
                    linuxProvisioningConfigurationSet1.HostName    = name;
                    linuxProvisioningConfigurationSet.UserName     = this.LinuxUser;
                    linuxProvisioningConfigurationSet.UserPassword = this.Password;
                    linuxProvisioningConfigurationSet.DisableSshPasswordAuthentication = new bool?(false);
                    if (this.SSHKeyPairs != null && this.SSHKeyPairs.Count > 0 || this.SSHPublicKeys != null && this.SSHPublicKeys.Count > 0)
                    {
                        linuxProvisioningConfigurationSet.SSH            = new LinuxProvisioningConfigurationSet.SSHSettings();
                        linuxProvisioningConfigurationSet.SSH.PublicKeys = this.SSHPublicKeys;
                        linuxProvisioningConfigurationSet.SSH.KeyPairs   = this.SSHKeyPairs;
                    }
                    InputEndpoint inputEndpoint = new InputEndpoint();
                    inputEndpoint.LocalPort = 22;
                    inputEndpoint.Protocol  = "tcp";
                    inputEndpoint.Name      = "SSH";
                    networkConfigurationSet.InputEndpoints.Add(inputEndpoint);
                    uri1.ConfigurationSets.Add(linuxProvisioningConfigurationSet);
                    uri1.ConfigurationSets.Add(networkConfigurationSet);
                }
                else
                {
                    WindowsProvisioningConfigurationSet windowsProvisioningConfigurationSet = new WindowsProvisioningConfigurationSet();
                    windowsProvisioningConfigurationSet.AdminPassword = this.Password;
                    WindowsProvisioningConfigurationSet windowsProvisioningConfigurationSet1 = windowsProvisioningConfigurationSet;
                    if (string.IsNullOrEmpty(this.Name))
                    {
                        str = this.ServiceName;
                    }
                    else
                    {
                        str = this.Name;
                    }
                    windowsProvisioningConfigurationSet1.ComputerName             = str;
                    windowsProvisioningConfigurationSet.EnableAutomaticUpdates    = new bool?(true);
                    windowsProvisioningConfigurationSet.ResetPasswordOnFirstLogon = false;
                    windowsProvisioningConfigurationSet.StoredCertificateSettings = this.Certificates;
                    InputEndpoint inputEndpoint1 = new InputEndpoint();
                    inputEndpoint1.LocalPort = 0xd3d;
                    inputEndpoint1.Protocol  = "tcp";
                    inputEndpoint1.Name      = "RemoteDesktop";
                    networkConfigurationSet.InputEndpoints.Add(inputEndpoint1);
                    uri1.ConfigurationSets.Add(windowsProvisioningConfigurationSet);
                    uri1.ConfigurationSets.Add(networkConfigurationSet);
                }
                new List <string>();
                Operation operation = null;
                bool      flag      = this.DoesCloudServiceExist(this.ServiceName);
                using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
                {
                    try
                    {
                        DateTime dateTime      = DateTime.Now;
                        DateTime universalTime = dateTime.ToUniversalTime();
                        string   str3          = string.Format("Implicitly created hosted service{0}", universalTime.ToString("yyyy-MM-dd HH:mm"));
                        if (!string.IsNullOrEmpty(this.Location) || !string.IsNullOrEmpty(this.AffinityGroup) || !string.IsNullOrEmpty(this.VNetName) && !flag)
                        {
                            CreateHostedServiceInput createHostedServiceInput = new CreateHostedServiceInput();
                            createHostedServiceInput.AffinityGroup = this.AffinityGroup;
                            createHostedServiceInput.Location      = this.Location;
                            createHostedServiceInput.ServiceName   = this.ServiceName;
                            createHostedServiceInput.Description   = str3;
                            createHostedServiceInput.Label         = ServiceManagementHelper.EncodeToBase64String(this.ServiceName);
                            CmdletExtensions.WriteVerboseOutputForObject(this, createHostedServiceInput);
                            base.RetryCall((string s) => base.Channel.CreateHostedService(s, createHostedServiceInput));
                            Operation operation1 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create Cloud Service"));
                            ManagementOperationContext managementOperationContext = new ManagementOperationContext();
                            managementOperationContext.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create Cloud Service"));
                            managementOperationContext.set_OperationId(operation1.OperationTrackingId);
                            managementOperationContext.set_OperationStatus(operation1.Status);
                            ManagementOperationContext managementOperationContext1 = managementOperationContext;
                            base.WriteObject(managementOperationContext1, true);
                        }
                    }
                    catch (CommunicationException communicationException1)
                    {
                        CommunicationException communicationException = communicationException1;
                        this.WriteErrorDetails(communicationException);
                        return;
                    }
                }
                if (operation == null || string.Compare(operation.Status, "Failed", StringComparison.OrdinalIgnoreCase) != 0)
                {
                    if (base.CurrentDeployment != null)
                    {
                        if (this.VNetName != null || this.DnsSettings != null)
                        {
                            base.WriteWarning("VNetName or DnsSettings can only be specified on new deployments.");
                        }
                    }
                    else
                    {
                        using (OperationContextScope operationContextScope1 = new OperationContextScope((IContextChannel)base.Channel))
                        {
                            try
                            {
                                Deployment deployment = new Deployment();
                                deployment.DeploymentSlot = "Production";
                                deployment.Name           = this.ServiceName;
                                deployment.Label          = this.ServiceName;
                                List <Role> roles = new List <Role>();
                                roles.Add(uri1);
                                deployment.RoleList           = new RoleList(roles);
                                deployment.VirtualNetworkName = this.VNetName;
                                Deployment dnsSetting = deployment;
                                if (this.DnsSettings != null)
                                {
                                    dnsSetting.Dns            = new DnsSettings();
                                    dnsSetting.Dns.DnsServers = new DnsServerList();
                                    DnsServer[] dnsSettings = this.DnsSettings;
                                    for (int j = 0; j < (int)dnsSettings.Length; j++)
                                    {
                                        DnsServer dnsServer = dnsSettings[j];
                                        dnsSetting.Dns.DnsServers.Add(dnsServer);
                                    }
                                }
                                CmdletExtensions.WriteVerboseOutputForObject(this, dnsSetting);
                                base.RetryCall((string s) => base.Channel.CreateDeployment(s, this.ServiceName, dnsSetting));
                                Operation operation2 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create Deployment with VM ", uri1.RoleName));
                                ManagementOperationContext managementOperationContext2 = new ManagementOperationContext();
                                managementOperationContext2.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create Deployment with VM ", uri1.RoleName));
                                managementOperationContext2.set_OperationId(operation2.OperationTrackingId);
                                managementOperationContext2.set_OperationStatus(operation2.Status);
                                ManagementOperationContext managementOperationContext3 = managementOperationContext2;
                                base.WriteObject(managementOperationContext3, true);
                            }
                            catch (CommunicationException communicationException3)
                            {
                                CommunicationException communicationException2 = communicationException3;
                                if (communicationException2 as EndpointNotFoundException == null)
                                {
                                    this.WriteErrorDetails(communicationException2);
                                    return;
                                }
                                else
                                {
                                    throw new Exception("Cloud Service does not exist. Specify -Location or -Affinity group to create one.");
                                }
                            }
                            this.CreatedDeployment = true;
                        }
                    }
                    if (operation == null || string.Compare(operation.Status, "Failed", StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        if (!this.CreatedDeployment)
                        {
                            using (OperationContextScope operationContextScope2 = new OperationContextScope((IContextChannel)base.Channel))
                            {
                                try
                                {
                                    CmdletExtensions.WriteVerboseOutputForObject(this, uri1);
                                    NewQuickVM newQuickVM = this;
                                    if (action == null)
                                    {
                                        action = (string s) => base.Channel.AddRole(s, this.ServiceName, this.ServiceName, uri1);
                                    }
                                    ((CmdletBase <IServiceManagement>)newQuickVM).RetryCall(action);
                                    Operation operation3 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create VM ", uri1.RoleName));
                                    ManagementOperationContext managementOperationContext4 = new ManagementOperationContext();
                                    managementOperationContext4.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create VM ", uri1.RoleName));
                                    managementOperationContext4.set_OperationId(operation3.OperationTrackingId);
                                    managementOperationContext4.set_OperationStatus(operation3.Status);
                                    ManagementOperationContext managementOperationContext5 = managementOperationContext4;
                                    base.WriteObject(managementOperationContext5, true);
                                }
                                catch (CommunicationException communicationException5)
                                {
                                    CommunicationException communicationException4 = communicationException5;
                                    this.WriteErrorDetails(communicationException4);
                                    return;
                                }
                            }
                        }
                        return;
                    }
                    else
                    {
                        return;
                    }
                }
                return;
            }
            else
            {
                throw new ArgumentException("CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it.");
            }
        }