示例#1
0
        public void ContinuousSendSignals()
        {
            IInputEndpoint input          = new InputEndpoint();
            Int32          receivedSignal = 0;

            input.Receive += (sender, signal) =>
            {
                receivedSignal = signal;
            };
            IOutputEndpoint output = new OutputEndpoint(input);

            output.Produce(1);
            Assert.AreEqual(receivedSignal, 1);

            output.Produce(0);
            Assert.AreEqual(receivedSignal, 0);

            output.Produce(0);
            Assert.AreEqual(receivedSignal, 0);

            output.Produce(1);
            Assert.AreEqual(receivedSignal, 1);

            output.Produce(0);
            Assert.AreEqual(receivedSignal, 0);
        }
示例#2
0
        public void SendSignal()
        {
            IInputEndpoint input       = new InputEndpoint();
            Int32          inputSignal = 0;

            input.Receive += (sender, signal) => { inputSignal = signal; };
            IOutputEndpoint  output1       = new OutputEndpoint();
            IOutputEndpoint  output2       = new OutputEndpoint();
            INeutralEndpoint netrual       = new NeutralEndpoint();
            Int32            netrualSignal = 0;

            netrual.Receive += (sender, signal) => { netrualSignal = signal; };

            Nexus nexus = new Nexus(6, input, output1, output2, netrual);

            output1.Produce(1);
            Assert.AreEqual(inputSignal, 1);
            Assert.AreEqual(netrualSignal, 1);
            output2.Produce(0);
            Assert.AreEqual(inputSignal, 1);
            Assert.AreEqual(netrualSignal, 1);
            output1.Produce(0);
            Assert.AreEqual(inputSignal, 0);
            Assert.AreEqual(netrualSignal, 0);
            netrual.Produce(1);
            Assert.AreEqual(inputSignal, 1);
            Assert.AreEqual(netrualSignal, 0);
        }
示例#3
0
        public void inputConnectToTheSameNeutralMoreThanOneTime()
        {
            IInputEndpoint input     = new InputEndpoint();
            Int32          callTimes = 0;

            input.Receive += (sender, signal) =>
            {
                callTimes++;
            };
            INeutralEndpoint neutral = new NeutralEndpoint();

            input.ConnectTo(neutral);
            Assert.AreEqual(callTimes, 1);

            input.ConnectTo(neutral);
            Assert.AreEqual(callTimes, 1);

            neutral.ConnectTo(input);
            Assert.AreEqual(callTimes, 1);

            neutral.ConnectTo(input);
            Assert.AreEqual(callTimes, 1);

            input.ConnectTo(neutral);
            Assert.AreEqual(callTimes, 1);

            neutral.ConnectTo(input);
            Assert.AreEqual(callTimes, 1);
        }
示例#4
0
        public void ChangeEndpointMidwayWithPrechargedSignal()
        {
            IInputEndpoint input1          = new InputEndpoint();
            Int32          receivedSignal1 = 0;

            input1.Receive += (sender, signal) =>
            {
                receivedSignal1 = signal;
            };
            IInputEndpoint input2          = new InputEndpoint();
            Int32          receivedSignal2 = 0;

            input2.Receive += (sender, signal) =>
            {
                receivedSignal2 = signal;
            };
            IOutputEndpoint output = new OutputEndpoint(input1);

            output.Produce(1);
            Assert.AreEqual(receivedSignal1, 1);
            Assert.AreEqual(receivedSignal2, 0);

            output.ConnectTo(input2);
            Assert.AreEqual(receivedSignal1, 0);
            Assert.AreEqual(receivedSignal2, 1);
        }
示例#5
0
        public void inputConnectToTheSameOutputMoreThanOneTime()
        {
            IInputEndpoint input     = new InputEndpoint();
            Int32          callTimes = 0;

            input.Receive += (sender, signal) =>
            {
                callTimes++;
            };
            IOutputEndpoint output = new OutputEndpoint();

            input.ConnectTo(output);
            Assert.AreEqual(callTimes, 1);

            input.ConnectTo(output);
            Assert.AreEqual(callTimes, 1);

            output.ConnectTo(input);
            Assert.AreEqual(callTimes, 1);

            output.ConnectTo(input);
            Assert.AreEqual(callTimes, 1);

            input.ConnectTo(output);
            Assert.AreEqual(callTimes, 1);

            output.ConnectTo(input);
            Assert.AreEqual(callTimes, 1);
        }
示例#6
0
        public void Oscillate20HzOnTime()
        {
            IInputEndpoint input = new InputEndpoint();

            input.ConnectTo(_oscillator10Hz.Output);
            input.Receive += (sd, sgn) =>
            {
                Thread.Sleep(1);
                if ((Int32)_count >= 5)
                {
                    _startPower.Off();
                }
                else
                {
                    _count = (Int32)_count + 1;
                }
            };

            ThreadHelper.ExecuteThenSleepShortly(() => _startPower.On(), 300);
            Assert.AreEqual(_count, 5);

            _count = 0;
            ThreadHelper.ExecuteThenSleepShortly(() => _startPower.On(), 250);
            Assert.AreEqual(_count, 5);

            _count = 0;
            ThreadHelper.ExecuteThenSleepShortly(() => _startPower.On(), 100);
            Assert.IsTrue((Int32)_count < 5);
        }
示例#7
0
        public void OscillateFloppyExactly()
        {
            IInputEndpoint input   = new InputEndpoint();
            IList <Int32>  results = new List <Int32>();

            input.ConnectTo(_oscillator10Hz.Output);

            input.Receive += (sd, sgn) =>
            {
                Thread.Sleep(1);
                if ((Int32)_count >= 5)
                {
                    _startPower.Off();
                }
                else
                {
                    _count = (Int32)_count + 1;
                    results.Add(sgn);
                }
            };

            ThreadHelper.ExecuteThenSleepShortly(() => _startPower.On(), 500);

            Assert.AreEqual(results.Count, 5);
            Assert.AreEqual(results[0], 0);
            Assert.AreEqual(results[1], 1);
            Assert.AreEqual(results[2], 0);
            Assert.AreEqual(results[3], 1);
            Assert.AreEqual(results[4], 0);
        }
示例#8
0
        public void ChargeTheNeutralThenConnectInputOrNuetral()
        {
            IInputEndpoint input          = new InputEndpoint();
            Int32          receivedSignal = 0;

            input.Receive += (sender, signal) =>
            {
                receivedSignal = signal;
            };
            INeutralEndpoint neutral = new NeutralEndpoint();
            Int32            neutralReceivedSignal = 0;

            neutral.Receive += (sender, signal) =>
            {
                neutralReceivedSignal = signal;
            };
            INeutralEndpoint neutralOut = new NeutralEndpoint();

            neutralOut.Produce(1);
            Assert.AreEqual(receivedSignal, 0);
            Assert.AreEqual(neutralReceivedSignal, 0);

            neutralOut.ConnectTo(input);
            Assert.AreEqual(receivedSignal, 1);
            Assert.AreEqual(neutralReceivedSignal, 0);

            neutralOut.ConnectTo(neutral);
            Assert.AreEqual(receivedSignal, 0);
            Assert.AreEqual(neutralReceivedSignal, 1);
        }
        protected override void ProcessRecord()
        {
            Func <InputEndpoint, bool> func = null;

            try
            {
                base.ProcessRecord();
                Collection <InputEndpoint> inputEndpoints  = this.GetInputEndpoints();
                Collection <InputEndpoint> inputEndpoints1 = inputEndpoints;
                if (func == null)
                {
                    func = (InputEndpoint ep) => string.Compare(ep.Name, this.Name, true) == 0;
                }
                InputEndpoint inputEndpoint = inputEndpoints1.Where <InputEndpoint>(func).SingleOrDefault <InputEndpoint>();
                if (inputEndpoint == null)
                {
                    object[] name = new object[1];
                    name[0] = this.Name;
                    base.ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "An endpoint named '{0}' cannot be found in the configuration of this VM.", name)), string.Empty, ErrorCategory.InvalidData, null));
                }
                inputEndpoints.Remove(inputEndpoint);
                base.WriteObject(base.VM, true);
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                base.WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
            }
        }
示例#10
0
        public void CreateNew()
        {
            IInputEndpoint  input  = new InputEndpoint();
            IOutputEndpoint output = new OutputEndpoint();
            Wire            wire   = new Wire(input, output);

            Assert.IsNotNull(wire);
        }
示例#11
0
        public void ConnectSamePoint()
        {
            IInputEndpoint input1 = new InputEndpoint();
            IInputEndpoint input2 = new InputEndpoint();
            Wire           wire   = new Wire(input1, input2);

            wire.Connect(input1, input1);
        }
示例#12
0
        public void AddWinRmEndpoint()
        {
            var winRmEndpoint = new InputEndpoint {
                LocalPort = WinRMPortNumber, Protocol = TcpProtocol, Name = WinRMConstants.EndpointName
            };

            NetworkConfigurationSet.InputEndpoints.Add(winRmEndpoint);
        }
示例#13
0
        public void CreateNewInputPointWithConnectPoint()
        {
            IInputEndpoint input1 = new InputEndpoint();
            IInputEndpoint input2 = new InputEndpoint(input1);

            Assert.IsNotNull(input1.ConnectedPoint);
            Assert.IsNotNull(input2.ConnectedPoint);
            Assert.AreSame(input1.ConnectedPoint, input2);
            Assert.AreSame(input2.ConnectedPoint, input1);
        }
示例#14
0
        public void CreateNewEndpoint()
        {
            IInputEndpoint   input   = new InputEndpoint();
            IOutputEndpoint  output  = new OutputEndpoint();
            INeutralEndpoint neutral = new NeutralEndpoint();

            Assert.IsNotNull(input);
            Assert.IsNotNull(output);
            Assert.IsNotNull(neutral);
        }
示例#15
0
        public void DisconnectEndpoint()
        {
            IInputEndpoint input1 = new InputEndpoint();
            IInputEndpoint input2 = new InputEndpoint(input1);

            input1.DisconnectEndpoint();

            Assert.IsNull(input1.ConnectedPoint);
            Assert.IsNull(input2.ConnectedPoint);
        }
示例#16
0
        public void CreateNewWithInsufficientConnectionPoints()
        {
            IInputEndpoint   input   = new InputEndpoint();
            IOutputEndpoint  output  = new OutputEndpoint();
            INeutralEndpoint netrual = new NeutralEndpoint();

            Nexus nexus = new Nexus(6, input, output, netrual);

            Assert.IsNotNull(nexus);
        }
示例#17
0
        public void ChangeConnection()
        {
            IInputEndpoint input1 = new InputEndpoint();
            IInputEndpoint input2 = new InputEndpoint(input1);
            IInputEndpoint input3 = new InputEndpoint(input2);

            Assert.IsNull(input1.ConnectedPoint);
            Assert.IsNotNull(input2.ConnectedPoint);
            Assert.IsNotNull(input3.ConnectedPoint);
            Assert.AreSame(input2.ConnectedPoint, input3);
            Assert.AreSame(input3.ConnectedPoint, input2);
        }
示例#18
0
        public void CreateNew()
        {
            IInputEndpoint   input1   = new InputEndpoint();
            IInputEndpoint   input2   = new InputEndpoint();
            IOutputEndpoint  output1  = new OutputEndpoint();
            IOutputEndpoint  output2  = new OutputEndpoint();
            INeutralEndpoint netrual1 = new NeutralEndpoint();
            INeutralEndpoint netrual2 = new NeutralEndpoint();

            Nexus nexus = new Nexus(6, input1, input2, output1, output2, netrual1, netrual2);

            Assert.IsNotNull(nexus);
        }
示例#19
0
        public void InputEndpointTransimit()
        {
            IInputEndpoint input1         = new InputEndpoint();
            Int32          receivedSignal = 0;

            input1.Receive += (sender, signal) =>
            {
                receivedSignal = signal;
            };
            input1.Transmit(1);

            Assert.AreEqual(receivedSignal, 1);
        }
示例#20
0
        public void CreateNewWithExcessiveConnectionPoints()
        {
            IInputEndpoint   input1   = new InputEndpoint();
            IInputEndpoint   input2   = new InputEndpoint();
            IOutputEndpoint  output1  = new OutputEndpoint();
            IOutputEndpoint  output2  = new OutputEndpoint();
            INeutralEndpoint netrual1 = new NeutralEndpoint();
            INeutralEndpoint netrual2 = new NeutralEndpoint();

            Nexus nexus = new Nexus(3, input1, input2, output1, output2, netrual1, netrual2);

            Assert.IsNotNull(nexus);
        }
示例#21
0
        public void Reconnect()
        {
            IInputEndpoint input1 = new InputEndpoint();
            IInputEndpoint input2 = new InputEndpoint(input1);

            input1.DisconnectEndpoint();
            input1.ConnectTo(input2);

            Assert.IsNotNull(input1.ConnectedPoint);
            Assert.IsNotNull(input2.ConnectedPoint);
            Assert.AreSame(input1.ConnectedPoint, input2);
            Assert.AreSame(input2.ConnectedPoint, input1);
        }
示例#22
0
        public void AbleToOscillate()
        {
            IInputEndpoint input = new InputEndpoint();

            input.ConnectTo(_oscillator10Hz.Output);
            input.Receive += (sd, sgn) =>
            {
                Thread.Sleep(1);
                _count = (Int32)_count + 1;
            };

            ThreadHelper.ExecuteThenSleepShortly(() => _startPower.On(), 500);
            _startPower.Off();
            Assert.IsTrue((Int32)_count > 0);
        }
示例#23
0
        public void DisconnectInputWithConnectionNoCharge()
        {
            IInputEndpoint input     = new InputEndpoint();
            Int32          callTimes = 0;

            input.Receive += (sender, signal) =>
            {
                callTimes++;
            };
            IOutputEndpoint output = new OutputEndpoint(input);

            input.DisconnectEndpoint();

            Assert.AreEqual(callTimes, 1);
        }
示例#24
0
        public void NeutralEndpointProduceToInput()
        {
            IInputEndpoint input          = new InputEndpoint();
            Int32          receivedSignal = 0;

            input.Receive += (sender, signal) =>
            {
                receivedSignal = signal;
            };
            INeutralEndpoint neutral = new NeutralEndpoint(input);

            neutral.Produce(1);

            Assert.AreEqual(receivedSignal, 1);
        }
示例#25
0
        public void DisconnectInputWithoutConnection()
        {
            IInputEndpoint input     = new InputEndpoint();
            Int32          callTimes = 0;

            input.Receive += (sender, signal) =>
            {
                callTimes++;
            };

            input.DisconnectEndpoint();
            Assert.AreEqual(callTimes, 0);
            input.DisconnectEndpoint();
            Assert.AreEqual(callTimes, 0);
        }
        public void AddRdpEndpoint()
        {
            var endPoint = GetRdpEndpoint(NetworkConfigurationSet);

            if (endPoint != null)
            {
                endPoint.Port = null; // null out to avoid conflicts
            }
            else
            {
                var rdpEndpoint = new InputEndpoint {
                    LocalPort = RDPPortNumber, Protocol = TcpProtocol, Name = RdpEndpointName
                };
                NetworkConfigurationSet.InputEndpoints.Add(rdpEndpoint);
            }
        }
        public void AddSshEndpoint()
        {
            var endpoint = GetSSHEndpoint(NetworkConfigurationSet);

            if (endpoint != null)
            {
                endpoint.Port = null;  // null out to avoid conflicts
            }
            else
            {
                var sshEndpoint = new InputEndpoint {
                    LocalPort = SSHPortNumber, Protocol = TcpProtocol, Name = SSHEndpointName
                };
                NetworkConfigurationSet.InputEndpoints.Add(sshEndpoint);
            }
        }
示例#28
0
        public void DisconnectEndpointWithPrechargedSignal()
        {
            IInputEndpoint input          = new InputEndpoint();
            Int32          receivedSignal = 0;

            input.Receive += (sender, signal) =>
            {
                receivedSignal = signal;
            };
            IOutputEndpoint output = new OutputEndpoint(input);

            output.Produce(1);
            Assert.AreEqual(receivedSignal, 1);

            output.DisconnectEndpoint();
            Assert.AreEqual(receivedSignal, 0);
        }
示例#29
0
        public void DisconnectInputWithConnectionPrecharged()
        {
            IInputEndpoint input     = new InputEndpoint();
            Int32          callTimes = 0;

            input.Receive += (sender, signal) =>
            {
                callTimes++;
            };
            IOutputEndpoint output = new OutputEndpoint();

            output.Produce(1);
            output.ConnectTo(input);

            input.DisconnectEndpoint();

            Assert.AreEqual(callTimes, 2);
        }
示例#30
0
        public void ConnectNullPointWithoutException()
        {
            Wire wire1 = new Wire();
            Wire wire2 = new Wire(null, null);

            IInputEndpoint input = new InputEndpoint();
            Wire           wire3 = new Wire(input);
            Wire           wire4 = new Wire(input, null);
            Wire           wire5 = new Wire(null, input);

            Assert.IsNotNull(wire1);
            Assert.IsNotNull(wire2);
            Assert.IsNotNull(wire3);
            Assert.IsNotNull(wire4);
            Assert.IsNotNull(wire5);

            wire1.Connect(input, null);
            wire1.Connect(null, input);
            wire1.Connect(null, null);
        }
        internal void ExecuteCommand()
        {
            ValidateParameters();

            var endpoints = GetInputEndpoints();
            var endpoint = endpoints.SingleOrDefault(p => p.Name == Name);

            if (endpoint != null)
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                            new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "An endpoint named '{0}' has already been defined for this VM. Specify a different endpoint name or use Set-Endpoint to change the configuration settings of the existing endpoint.", this.Name)),
                            string.Empty,
                            ErrorCategory.InvalidData,
                            null));
            }

            endpoint = new InputEndpoint
            {
                Name = Name,
                Port = PublicPort.HasValue ? PublicPort : null,
                LocalPort = LocalPort,
                Protocol = Protocol,
            };

            if (ParameterSetName == LoadBalancedProbeParameterSet)
            {
                endpoint.LoadBalancedEndpointSetName = LBSetName;
                endpoint.LoadBalancerProbe = new LoadBalancerProbe { Protocol = ProbeProtocol };

                endpoint.LoadBalancerProbe.Port = ProbePort;

                if (endpoint.LoadBalancerProbe.Protocol == "http")
                {
                    if (string.IsNullOrEmpty(ProbePath) == false)
                    {
                        endpoint.LoadBalancerProbe.Path = ProbePath;
                    }
                    else
                    {
                        endpoint.LoadBalancerProbe.Path = "/";
                    }
                }

                if (ProbeIntervalInSeconds.HasValue)
                {
                    endpoint.LoadBalancerProbe.IntervalInSeconds = ProbeIntervalInSeconds;
                }

                if (ProbeTimeoutInSeconds.HasValue)
                {
                    endpoint.LoadBalancerProbe.TimeoutInSeconds = ProbeTimeoutInSeconds;
                }
            }
            else if (ParameterSetName == LoadBalancedParameterSet)
            {
                endpoint.LoadBalancedEndpointSetName = LBSetName;
            }

            endpoints.Add(endpoint);

            WriteObject(VM, true);
        }
		protected override void ProcessRecord()
		{
			bool flag;
			bool flag1;
			try
			{
				base.ProcessRecord();
				PersistentVM instance = this.VM.GetInstance();
				SwitchParameter linux = base.Linux;
				if (!linux.IsPresent)
				{
					WindowsProvisioningConfigurationSet windowsProvisioningConfigurationSet = instance.ConfigurationSets.OfType<WindowsProvisioningConfigurationSet>().SingleOrDefault<WindowsProvisioningConfigurationSet>();
					if (windowsProvisioningConfigurationSet == null)
					{
						windowsProvisioningConfigurationSet = new WindowsProvisioningConfigurationSet();
						instance.ConfigurationSets.Add(windowsProvisioningConfigurationSet);
					}
					base.SetProvisioningConfiguration(windowsProvisioningConfigurationSet);
					windowsProvisioningConfigurationSet.ComputerName = instance.RoleName;
					SwitchParameter noRDPEndpoint = base.NoRDPEndpoint;
					if (!noRDPEndpoint.IsPresent)
					{
						NetworkConfigurationSet networkConfigurationSet = instance.ConfigurationSets.OfType<NetworkConfigurationSet>().SingleOrDefault<NetworkConfigurationSet>();
						if (networkConfigurationSet == null)
						{
							networkConfigurationSet = new NetworkConfigurationSet();
							instance.ConfigurationSets.Add(networkConfigurationSet);
						}
						if (networkConfigurationSet.InputEndpoints == null)
						{
							networkConfigurationSet.InputEndpoints = new Collection<InputEndpoint>();
						}
						foreach (InputEndpoint inputEndpoint in networkConfigurationSet.InputEndpoints)
						{
							if (string.Compare(inputEndpoint.Name, "RDP", StringComparison.OrdinalIgnoreCase) != 0 && inputEndpoint.LocalPort != 0xd3d)
							{
								continue;
							}
							flag1 = false;
							int? nullable = null;
							inputEndpoint.Port = nullable;
							break;
						}
						if (flag1)
						{
							InputEndpoint inputEndpoint1 = new InputEndpoint();
							inputEndpoint1.LocalPort = 0xd3d;
							inputEndpoint1.Protocol = "tcp";
							inputEndpoint1.Name = "RDP";
							networkConfigurationSet.InputEndpoints.Add(inputEndpoint1);
						}
					}
				}
				else
				{
					LinuxProvisioningConfigurationSet linuxProvisioningConfigurationSet = instance.ConfigurationSets.OfType<LinuxProvisioningConfigurationSet>().SingleOrDefault<LinuxProvisioningConfigurationSet>();
					if (linuxProvisioningConfigurationSet == null)
					{
						linuxProvisioningConfigurationSet = new LinuxProvisioningConfigurationSet();
						instance.ConfigurationSets.Add(linuxProvisioningConfigurationSet);
					}
					base.SetProvisioningConfiguration(linuxProvisioningConfigurationSet);
					linuxProvisioningConfigurationSet.HostName = instance.RoleName;
					SwitchParameter disableSSH = base.DisableSSH;
					if (disableSSH.IsPresent)
					{
						SwitchParameter noSSHEndpoint = base.NoSSHEndpoint;
						if (!noSSHEndpoint.IsPresent)
						{
							goto Label0;
						}
					}
					NetworkConfigurationSet inputEndpoints = instance.ConfigurationSets.OfType<NetworkConfigurationSet>().SingleOrDefault<NetworkConfigurationSet>();
					if (inputEndpoints == null)
					{
						inputEndpoints = new NetworkConfigurationSet();
						inputEndpoints.InputEndpoints = new Collection<InputEndpoint>();
						instance.ConfigurationSets.Add(inputEndpoints);
					}
					foreach (InputEndpoint inputEndpoint2 in inputEndpoints.InputEndpoints)
					{
						if (string.Compare(inputEndpoint2.Name, "SSH", StringComparison.OrdinalIgnoreCase) != 0 && inputEndpoint2.LocalPort != 22)
						{
							continue;
						}
						flag = false;
						int? nullable1 = null;
						inputEndpoint2.Port = nullable1;
						break;
					}
					if (flag)
					{
						InputEndpoint inputEndpoint3 = new InputEndpoint();
						inputEndpoint3.LocalPort = 22;
						inputEndpoint3.Protocol = "tcp";
						inputEndpoint3.Name = "SSH";
						inputEndpoints.InputEndpoints.Add(inputEndpoint3);
					}
				}
			Label0:
				CmdletExtensions.WriteVerboseOutputForObject(this, this.VM);
				base.WriteObject(this.VM, true);
			}
			catch (Exception exception1)
			{
				Exception exception = exception1;
				base.WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
			}
		}
        internal void ExecuteCommand()
        {
            var role = VM.GetInstance();

            if (Linux.IsPresent)
            {
                var provisioningConfiguration = role.ConfigurationSets
                    .OfType<LinuxProvisioningConfigurationSet>()
                    .SingleOrDefault();

                if (provisioningConfiguration == null)
                {
                    provisioningConfiguration = new LinuxProvisioningConfigurationSet();
                    role.ConfigurationSets.Add(provisioningConfiguration);
                }

                SetProvisioningConfiguration(provisioningConfiguration);
                provisioningConfiguration.HostName = role.RoleName;

                if (DisableSSH.IsPresent == false || NoSSHEndpoint.IsPresent)
                {
                    var netConfig = role.ConfigurationSets
                        .OfType<NetworkConfigurationSet>()
                        .SingleOrDefault();

                    if (netConfig == null)
                    {
                        netConfig = new NetworkConfigurationSet
                        {
                            InputEndpoints =
                                new System.Collections.ObjectModel.Collection<InputEndpoint>()
                        };

                        role.ConfigurationSets.Add(netConfig);
                    }

                    // Add check in case the settings were imported
                    bool addSSH = true;

                    foreach (InputEndpoint ep in netConfig.InputEndpoints)
                    {
                        if (string.Compare(ep.Name, "SSH", StringComparison.OrdinalIgnoreCase) == 0 || ep.LocalPort == 22)
                        {
                            addSSH = false;
                            ep.Port = null; // null out to avoid conflicts
                            break;
                        }
                    }

                    if (addSSH)
                    {
                        InputEndpoint sshEndpoint = new InputEndpoint();
                        sshEndpoint.LocalPort = 22;
                        sshEndpoint.Protocol = "tcp";
                        sshEndpoint.Name = "SSH";
                        netConfig.InputEndpoints.Add(sshEndpoint);
                    }
                }
            }
            else
            {
                var provisioningConfiguration = role.ConfigurationSets
                    .OfType<WindowsProvisioningConfigurationSet>()
                    .SingleOrDefault();
                if (provisioningConfiguration == null)
                {
                    provisioningConfiguration = new WindowsProvisioningConfigurationSet();
                    role.ConfigurationSets.Add(provisioningConfiguration);
                }

                SetProvisioningConfiguration(provisioningConfiguration);
                provisioningConfiguration.ComputerName = role.RoleName;

                if (!NoRDPEndpoint.IsPresent)
                {
                    var netConfig = role.ConfigurationSets
                        .OfType<NetworkConfigurationSet>()
                        .SingleOrDefault();

                    if (netConfig == null)
                    {
                        netConfig = new NetworkConfigurationSet();
                        role.ConfigurationSets.Add(netConfig);
                    }

                    if (netConfig.InputEndpoints == null)
                    {
                        netConfig.InputEndpoints = new System.Collections.ObjectModel.Collection<InputEndpoint>();
                    }

                    bool addRDP = true;

                    foreach (InputEndpoint ep in netConfig.InputEndpoints)
                    {
                        if (string.Compare(ep.Name, "RDP", StringComparison.OrdinalIgnoreCase) == 0 || ep.LocalPort == 3389)
                        {
                            addRDP = false;
                            ep.Port = null; // null out to avoid conflicts
                            break;
                        }
                    }

                    if (addRDP)
                    {
                        InputEndpoint rdpEndpoint = new InputEndpoint { LocalPort = 3389, Protocol = "tcp", Name = "RDP" };
                        netConfig.InputEndpoints.Add(rdpEndpoint);
                    }
                }

                if (!this.DisableWinRMHttps.IsPresent)
                {
                    var netConfig = role.ConfigurationSets
                        .OfType<NetworkConfigurationSet>()
                        .SingleOrDefault();

                    if (netConfig == null)
                    {
                        netConfig = new NetworkConfigurationSet();
                        role.ConfigurationSets.Add(netConfig);
                    }

                    if (netConfig.InputEndpoints == null)
                    {
                        netConfig.InputEndpoints = new System.Collections.ObjectModel.Collection<InputEndpoint>();
                    }

                    var builder = new WinRmConfigurationBuilder();
                    if (this.EnableWinRMHttp.IsPresent)
                    {
                        builder.AddHttpListener();
                    }
                    builder.AddHttpsListener(this.WinRMCertificate);
                    provisioningConfiguration.WinRM = builder.Configuration;

                    var winRmEndpoint = new InputEndpoint {LocalPort = WinRMConstants.HttpsListenerPort, Protocol = "tcp", Name = WinRMConstants.EndpointName};
                    netConfig.InputEndpoints.Add(winRmEndpoint);
                    role.WinRMCertificate = WinRMCertificate;
                }

                role.X509Certificates = new List<X509Certificate2>();
                if (this.X509Certificates != null)
                {
                    role.X509Certificates.AddRange(this.X509Certificates);
                }
                role.NoExportPrivateKey = this.NoExportPrivateKey.IsPresent;
            }

            WriteObject(VM, true);
        }
        private PersistentVMRole CreatePersistenVMRole(CloudStorageAccount currentStorage)
        {
            var vm = new PersistentVMRole
            {
                AvailabilitySetName = AvailabilitySetName,
                ConfigurationSets = new Collection<ConfigurationSet>(),
                DataVirtualHardDisks = new Collection<DataVirtualHardDisk>(),
                RoleName = String.IsNullOrEmpty(Name) ? ServiceName : Name, // default like the portal
                RoleSize = String.IsNullOrEmpty(InstanceSize) ? null : InstanceSize,
                RoleType = "PersistentVMRole",
                Label = ServiceName,
                OSVirtualHardDisk = new OSVirtualHardDisk
                {
                    DiskName = null,
                    SourceImageName = ImageName,
                    MediaLink = string.IsNullOrEmpty(MediaLocation) ? null : new Uri(MediaLocation),
                    HostCaching = HostCaching
                }
            };

            if (vm.OSVirtualHardDisk.MediaLink == null && String.IsNullOrEmpty(vm.OSVirtualHardDisk.DiskName))
            {
                DateTime dtCreated = DateTime.Now;
                string vhdname = String.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", this.ServiceName, vm.RoleName, dtCreated.Year, dtCreated.Month, dtCreated.Day, dtCreated.Millisecond);
                string blobEndpoint = currentStorage.BlobEndpoint.AbsoluteUri;
                if (blobEndpoint.EndsWith("/") == false)
                    blobEndpoint += "/";
                vm.OSVirtualHardDisk.MediaLink = new Uri(blobEndpoint + "vhds/" + vhdname);
            }

            var netConfig = CreateNetworkConfigurationSet();

            if (ParameterSetName.Equals("Windows", StringComparison.OrdinalIgnoreCase))
            {
                var windowsConfig = new WindowsProvisioningConfigurationSet
                {
                    AdminUsername = this.AdminUsername,
                    AdminPassword = Password,
                    ComputerName =
                        string.IsNullOrEmpty(Name) ? ServiceName : Name,
                    EnableAutomaticUpdates = true,
                    ResetPasswordOnFirstLogon = false,
                    StoredCertificateSettings = CertUtils.GetCertificateSettings(this.Certificates, this.X509Certificates),
                    WinRM = GetWinRmConfiguration()
                };

                netConfig.InputEndpoints.Add(new InputEndpoint {LocalPort = 3389, Protocol = "tcp", Name = "RemoteDesktop"});
                if(!this.DisableWinRMHttps.IsPresent)
                {
                    netConfig.InputEndpoints.Add(new InputEndpoint { LocalPort = WinRMConstants.HttpsListenerPort, Protocol = "tcp", Name = WinRMConstants.EndpointName });
                }
                vm.ConfigurationSets.Add(windowsConfig);
                vm.ConfigurationSets.Add(netConfig);
            }
            else
            {
                var linuxConfig = new LinuxProvisioningConfigurationSet
                {
                    HostName = string.IsNullOrEmpty(this.Name) ? this.ServiceName : this.Name,
                    UserName = this.LinuxUser,
                    UserPassword = this.Password,
                    DisableSshPasswordAuthentication = false
                };

                if (this.SSHKeyPairs != null && this.SSHKeyPairs.Count > 0 ||
                    this.SSHPublicKeys != null && this.SSHPublicKeys.Count > 0)
                {
                    linuxConfig.SSH = new LinuxProvisioningConfigurationSet.SSHSettings
                    {
                        PublicKeys = this.SSHPublicKeys,
                        KeyPairs = this.SSHKeyPairs
                    };
                }

                var rdpEndpoint = new InputEndpoint {LocalPort = 22, Protocol = "tcp", Name = "SSH"};
                netConfig.InputEndpoints.Add(rdpEndpoint);
                vm.ConfigurationSets.Add(linuxConfig);
                vm.ConfigurationSets.Add(netConfig);
            }

            return vm;
        }
        private void UpdateEndpointProperties(InputEndpoint endpoint)
        {
            if (this.ParameterSpecified("Protocol"))
            {
                endpoint.Protocol = this.Protocol;
            }

            if (this.ParameterSpecified("LocalPort"))
            {
                if (!this.ParameterSpecified("ProbePort")
                    && endpoint.LoadBalancerProbe != null
                    && endpoint.LocalPort == endpoint.LoadBalancerProbe.Port)
                {
                    endpoint.LoadBalancerProbe.Port = this.LocalPort;
                }

                endpoint.LocalPort = this.LocalPort;
            }

            if (this.ParameterSpecified("PublicPort"))
            {
                endpoint.Port = this.PublicPort;
            }

            if (this.ParameterSpecified("DirectServerReturn"))
            {
                endpoint.EnableDirectServerReturn = this.DirectServerReturn;
            }

            if (this.ParameterSpecified("ACL"))
            {
                endpoint.EndpointAccessControlList = this.ACL;
            }

            if (this.ParameterSetName == SetAzureLoadBalancedEndpoint.HTTPProbeParameterSet
                || this.ParameterSetName == SetAzureLoadBalancedEndpoint.TCPProbeParameterSet)
            {
                if (endpoint.LoadBalancerProbe == null)
                {
                    endpoint.LoadBalancerProbe = new LoadBalancerProbe();
                    if (!this.ParameterSpecified("ProbePort"))
                    {
                        endpoint.LoadBalancerProbe.Port = endpoint.LocalPort;
                    }
                }

                if (this.ParameterSpecified("ProbePort"))
                {
                    endpoint.LoadBalancerProbe.Port = this.ProbePort;
                }

                if (this.ParameterSpecified("ProbeIntervalInSeconds"))
                {
                    endpoint.LoadBalancerProbe.IntervalInSeconds = this.ProbeIntervalInSeconds;
                }

                if (this.ParameterSpecified("ProbeTimeoutInSeconds"))
                {
                    endpoint.LoadBalancerProbe.TimeoutInSeconds = this.ProbeTimeoutInSeconds;
                }

                if (this.ParameterSetName == SetAzureLoadBalancedEndpoint.HTTPProbeParameterSet)
                {
                    endpoint.LoadBalancerProbe.Protocol = "http";
                    endpoint.LoadBalancerProbe.Path = this.ProbePath;
                }

                if (this.ParameterSetName == SetAzureLoadBalancedEndpoint.TCPProbeParameterSet)
                {
                    endpoint.LoadBalancerProbe.Protocol = "tcp";
                    endpoint.LoadBalancerProbe.Path = null;
                }
            }
        }
示例#36
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.");
			}
		}
示例#37
0
		protected override void ProcessRecord()
		{
			int? publicPort;
			Func<InputEndpoint, bool> func = null;
			try
			{
				base.ProcessRecord();
				this.ValidateParameters();
				Collection<InputEndpoint> inputEndpoints = this.GetInputEndpoints();
				Collection<InputEndpoint> inputEndpoints1 = inputEndpoints;
				if (func == null)
				{
					func = (InputEndpoint p) => p.Name == this.Name;
				}
				InputEndpoint lBSetName = inputEndpoints1.Where<InputEndpoint>(func).SingleOrDefault<InputEndpoint>();
				if (lBSetName != null)
				{
					object[] name = new object[1];
					name[0] = this.Name;
					base.ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "An endpoint named '{0}' has already been defined for this VM. Specify a different endpoint name or use Set-Endpoint to change the configuration settings of the existing endpoint.", name)), string.Empty, ErrorCategory.InvalidData, null));
				}
				InputEndpoint inputEndpoint = new InputEndpoint();
				inputEndpoint.Name = this.Name;
				InputEndpoint inputEndpoint1 = inputEndpoint;
				int? nullable = this.PublicPort;
				if (nullable.HasValue)
				{
					publicPort = this.PublicPort;
				}
				else
				{
					int? nullable1 = null;
					publicPort = nullable1;
				}
				inputEndpoint1.Port = publicPort;
				inputEndpoint.LocalPort = this.LocalPort;
				inputEndpoint.Protocol = this.Protocol;
				lBSetName = inputEndpoint;
				if (!string.IsNullOrEmpty(this.LBSetName))
				{
					lBSetName.LoadBalancedEndpointSetName = this.LBSetName;
					lBSetName.LoadBalancerProbe = new LoadBalancerProbe();
					lBSetName.LoadBalancerProbe.Protocol = this.ProbeProtocol;
					if (lBSetName.LoadBalancerProbe.Protocol == "http")
					{
						if (string.IsNullOrEmpty(this.ProbePath))
						{
							lBSetName.LoadBalancerProbe.Path = "/";
						}
						else
						{
							lBSetName.LoadBalancerProbe.Path = this.ProbePath;
						}
					}
					lBSetName.LoadBalancerProbe.Port = this.ProbePort;
				}
				inputEndpoints.Add(lBSetName);
				base.WriteObject(base.VM, true);
			}
			catch (Exception exception1)
			{
				Exception exception = exception1;
				base.WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
			}
		}
        internal void ExecuteCommand()
        {
            var role = VM.GetInstance();

            if (Linux.IsPresent)
            {
                var provisioningConfiguration = role.ConfigurationSets
                    .OfType<LinuxProvisioningConfigurationSet>()
                    .SingleOrDefault();

                if (provisioningConfiguration == null)
                {
                    provisioningConfiguration = new LinuxProvisioningConfigurationSet();
                    role.ConfigurationSets.Add(provisioningConfiguration);
                }

                SetProvisioningConfiguration(provisioningConfiguration);
                provisioningConfiguration.HostName = role.RoleName;

                if (DisableSSH.IsPresent == false || NoSSHEndpoint.IsPresent)
                {
                    var netConfig = role.ConfigurationSets
                        .OfType<NetworkConfigurationSet>()
                        .SingleOrDefault();

                    if (netConfig == null)
                    {
                        netConfig = new NetworkConfigurationSet
                        {
                            InputEndpoints =
                                new System.Collections.ObjectModel.Collection<InputEndpoint>()
                        };

                        role.ConfigurationSets.Add(netConfig);
                    }

                    // Add check in case the settings were imported
                    bool addSSH = true;

                    foreach (InputEndpoint ep in netConfig.InputEndpoints)
                    {
                        if (string.Compare(ep.Name, "SSH", StringComparison.OrdinalIgnoreCase) == 0 || ep.LocalPort == 22)
                        {
                            addSSH = false;
                            ep.Port = null; // null out to avoid conflicts
                            break;
                        }
                    }

                    if (addSSH)
                    {
                        InputEndpoint sshEndpoint = new InputEndpoint();
                        sshEndpoint.LocalPort = 22;
                        sshEndpoint.Protocol = "tcp";
                        sshEndpoint.Name = "SSH";
                        netConfig.InputEndpoints.Add(sshEndpoint);
                    }
                }
            }
            else
            {
                var provisioningConfiguration = role.ConfigurationSets
                    .OfType<WindowsProvisioningConfigurationSet>()
                    .SingleOrDefault();
                if (provisioningConfiguration == null)
                {
                    provisioningConfiguration = new WindowsProvisioningConfigurationSet();
                    role.ConfigurationSets.Add(provisioningConfiguration);
                }

                SetProvisioningConfiguration(provisioningConfiguration);
                provisioningConfiguration.ComputerName = role.RoleName;

                if (!NoRDPEndpoint.IsPresent)
                {
                    var netConfig = role.ConfigurationSets
                        .OfType<NetworkConfigurationSet>()
                        .SingleOrDefault();

                    if (netConfig == null)
                    {
                        netConfig = new NetworkConfigurationSet();
                        role.ConfigurationSets.Add(netConfig);
                    }

                    if (netConfig.InputEndpoints == null)
                    {
                        netConfig.InputEndpoints = new System.Collections.ObjectModel.Collection<InputEndpoint>();
                    }

                    bool addRDP = true;

                    foreach (InputEndpoint ep in netConfig.InputEndpoints)
                    {
                        if (string.Compare(ep.Name, "RDP", StringComparison.OrdinalIgnoreCase) == 0 || ep.LocalPort == 3389)
                        {
                            addRDP = false;
                            ep.Port = null; // null out to avoid conflicts
                            break;
                        }
                    }

                    if (addRDP)
                    {
                        InputEndpoint rdpEndpoint = new InputEndpoint { LocalPort = 3389, Protocol = "tcp", Name = "RDP" };
                        netConfig.InputEndpoints.Add(rdpEndpoint);
                    }
                }
            }

            WriteObject(VM, true);
        }
示例#39
0
        public void NewAzureVMProcess()
        {
            SubscriptionData currentSubscription = this.GetCurrentSubscription();
            CloudStorageAccount currentStorage = null;
            try
            {
                currentStorage = currentSubscription.GetCurrentStorageAccount(Channel);
            }
            catch (EndpointNotFoundException) // couldn't access
            {
                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 (currentStorage == null) // not set
            {
                throw new ArgumentException("CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it.");
            }

            var vm = new PersistentVMRole
            {
                AvailabilitySetName = AvailabilitySetName,
                ConfigurationSets = new Collection<ConfigurationSet>(),
                DataVirtualHardDisks = new Collection<DataVirtualHardDisk>(),
                RoleName = String.IsNullOrEmpty(Name) ? ServiceName : Name, // default like the portal
                RoleSize = String.IsNullOrEmpty(InstanceSize) ? null : InstanceSize,
                RoleType = "PersistentVMRole",
                Label = ServiceManagementHelper.EncodeToBase64String(ServiceName)
            };

            vm.OSVirtualHardDisk = new OSVirtualHardDisk()
            {
                DiskName = null,
                SourceImageName = ImageName,
                MediaLink = string.IsNullOrEmpty(MediaLocation) ? null : new Uri(MediaLocation),
                HostCaching = HostCaching
            };

            if (vm.OSVirtualHardDisk.MediaLink == null && String.IsNullOrEmpty(vm.OSVirtualHardDisk.DiskName))
            {
                DateTime dtCreated = DateTime.Now;
                string vhdname = String.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", this.ServiceName, vm.RoleName, dtCreated.Year, dtCreated.Month, dtCreated.Day, dtCreated.Millisecond);
                string blobEndpoint = currentStorage.BlobEndpoint.AbsoluteUri;
                if (blobEndpoint.EndsWith("/") == false)
                    blobEndpoint += "/";
                vm.OSVirtualHardDisk.MediaLink = new Uri(blobEndpoint + "vhds/" + vhdname);
            }

            NetworkConfigurationSet netConfig = new NetworkConfigurationSet();
            netConfig.InputEndpoints = new Collection<InputEndpoint>();
            if (SubnetNames != null)
            {
                netConfig.SubnetNames = new SubnetNamesCollection();
                foreach (string subnet in SubnetNames)
                {
                    netConfig.SubnetNames.Add(subnet);
                }
            }

            if (ParameterSetName.Equals("Windows", StringComparison.OrdinalIgnoreCase))
            {
                WindowsProvisioningConfigurationSet windowsConfig = new WindowsProvisioningConfigurationSet
                {
                    AdminPassword = Password,
                    ComputerName = string.IsNullOrEmpty(Name) ? ServiceName : Name,
                    EnableAutomaticUpdates = true,
                    ResetPasswordOnFirstLogon = false,
                    StoredCertificateSettings = Certificates
                };

                InputEndpoint rdpEndpoint = new InputEndpoint { LocalPort = 3389, Protocol = "tcp", Name = "RemoteDesktop" };

                netConfig.InputEndpoints.Add(rdpEndpoint);
                vm.ConfigurationSets.Add(windowsConfig);
                vm.ConfigurationSets.Add(netConfig);
            }
            else
            {
                LinuxProvisioningConfigurationSet linuxConfig = new LinuxProvisioningConfigurationSet();
                linuxConfig.HostName = string.IsNullOrEmpty(this.Name) ? this.ServiceName : this.Name;
                linuxConfig.UserName = this.LinuxUser;
                linuxConfig.UserPassword = this.Password;
                linuxConfig.DisableSshPasswordAuthentication = false;

                if (this.SSHKeyPairs != null && this.SSHKeyPairs.Count > 0 || this.SSHPublicKeys != null && this.SSHPublicKeys.Count > 0)
                {
                    linuxConfig.SSH = new LinuxProvisioningConfigurationSet.SSHSettings();
                    linuxConfig.SSH.PublicKeys = this.SSHPublicKeys;
                    linuxConfig.SSH.KeyPairs = this.SSHKeyPairs;
                }

                InputEndpoint rdpEndpoint = new InputEndpoint();
                rdpEndpoint.LocalPort = 22;
                rdpEndpoint.Protocol = "tcp";
                rdpEndpoint.Name = "SSH";
                netConfig.InputEndpoints.Add(rdpEndpoint);
                vm.ConfigurationSets.Add(linuxConfig);
                vm.ConfigurationSets.Add(netConfig);
            }

            string CreateCloudServiceOperationID = String.Empty;
            string CreateDeploymentOperationID = String.Empty;
            List<String> CreateVMOperationIDs = new List<String>();
            Operation lastOperation = null;

            bool ServiceExists = DoesCloudServiceExist(this.ServiceName);

            if (string.IsNullOrEmpty(this.Location) == false || string.IsNullOrEmpty(AffinityGroup) == false || (!String.IsNullOrEmpty(VNetName) && ServiceExists == false))
            {
                using (new OperationContextScope((IContextChannel)Channel))
                {
                    try
                    {
                        //Implicitly created hosted service2012-05-07 23:12

                        // Create the Cloud Service when
                        // Location or Affinity Group is Specified
                        // or VNET is specified and the service doesn't exist
                        var chsi = new CreateHostedServiceInput
                        {
                            AffinityGroup = this.AffinityGroup,
                            Location = this.Location,
                            ServiceName = this.ServiceName,
                            Description = String.Format("Implicitly created hosted service{0}", DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                            Label = ServiceManagementHelper.EncodeToBase64String(this.ServiceName)
                        };

                        ExecuteClientAction(chsi, CommandRuntime + " - Create Cloud Service", s => this.Channel.CreateHostedService(s, chsi), WaitForOperation);
                    }

                    catch (CommunicationException ex)
                    {
                        this.WriteErrorDetails(ex);
                        return;
                    }
                }
            }
            if (lastOperation != null && string.Compare(lastOperation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0)
                return;

            // If the current deployment doesn't exist set it create it
            if (CurrentDeployment == null)
            {
                using (new OperationContextScope((IContextChannel)Channel))
                {
                    try
                    {
                        var deployment = new Deployment
                        {
                            DeploymentSlot = "Production",
                            Name = this.ServiceName,
                            Label = this.ServiceName,
                            RoleList = new RoleList(new List<Role> { vm }),
                            VirtualNetworkName = this.VNetName

                        };

                        if (this.DnsSettings != null)
                        {
                            deployment.Dns = new DnsSettings();
                            deployment.Dns.DnsServers = new DnsServerList();
                            foreach (DnsServer dns in this.DnsSettings)
                                deployment.Dns.DnsServers.Add(dns);
                        }

                        ExecuteClientAction(deployment, CommandRuntime + " - Create Deployment with VM " + vm.RoleName, s => this.Channel.CreateDeployment(s, this.ServiceName, deployment), WaitForOperation);
                    }

                    catch (CommunicationException ex)
                    {
                        if (ex is EndpointNotFoundException)
                        {
                            throw new Exception("Cloud Service does not exist. Specify -Location or -Affinity group to create one.");
                        }
                        else
                        {
                            this.WriteErrorDetails(ex);
                        }
                        return;
                    }

                    _createdDeployment = true;
                }
            }
            else
            {
                if (VNetName != null || DnsSettings != null)
                {
                    WriteWarning("VNetName or DnsSettings can only be specified on new deployments.");
                }
            }

            if (lastOperation != null && string.Compare(lastOperation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0)
                return;

            // Only create the VM when a new VM was added and it was not created during the deployment phase.
            if ((_createdDeployment == false))
            {
                using (new OperationContextScope((IContextChannel)Channel))
                {
                    try
                    {
                        ExecuteClientAction(vm, CommandRuntime + " - Create VM " + vm.RoleName, s => this.Channel.AddRole(s, this.ServiceName, this.ServiceName, vm), WaitForOperation);
                    }
                    catch (CommunicationException ex)
                    {
                        this.WriteErrorDetails(ex);
                        return;
                    }
                }
            }
        }
        internal void ExecuteCommand()
        {
            this.ValidateParameters();

            var endpoints = GetInputEndpoints();
            var endpoint = endpoints.SingleOrDefault(p => p.Name.Equals(this.Name, StringComparison.InvariantCultureIgnoreCase));

            if (endpoint != null)
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                            new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resources.EndpointAlreadyDefinedForVM, this.Name)),
                            string.Empty,
                            ErrorCategory.InvalidData,
                            null));
            }

            endpoint = new InputEndpoint
            {
                Name = this.Name,
                Port = this.ParameterSpecified("PublicPort") ? this.PublicPort : null,
                LocalPort = this.LocalPort,
                Protocol = this.Protocol,
                EndpointAccessControlList = this.ACL,
                EnableDirectServerReturn = this.DirectServerReturn,
                LoadBalancerName = this.InternalLoadBalancerName,
                IdleTimeoutInMinutes = this.ParameterSpecified("IdleTimeoutInMinutes") ? this.IdleTimeoutInMinutes : null,
                LoadBalancerDistribution = this.ParameterSpecified("LoadBalancerDistribution") ? this.LoadBalancerDistribution : null,
                VirtualIPName = this.ParameterSpecified("VirtualIPName") ? this.VirtualIPName : null, 
            };

            if (this.ParameterSetName == AddAzureEndpoint.LBNoProbeParameterSet
                || this.ParameterSetName == AddAzureEndpoint.LBDefaultProbeParameterSet
                || this.ParameterSetName == AddAzureEndpoint.LBCustomProbeParameterSet)
            {
                endpoint.LoadBalancedEndpointSetName = this.LBSetName;

                if (this.ParameterSetName == AddAzureEndpoint.LBDefaultProbeParameterSet)
                {
                    endpoint.LoadBalancerProbe = new LoadBalancerProbe()
                    {
                        Protocol = "TCP",
                        Port = endpoint.LocalPort
                    };
                }
                else if (this.ParameterSetName == AddAzureEndpoint.LBCustomProbeParameterSet)
                {
                    endpoint.LoadBalancerProbe = new LoadBalancerProbe 
                    { 
                        Protocol = this.ProbeProtocol,
                        Port = this.ProbePort
                    };

                    if (endpoint.LoadBalancerProbe.Protocol.Equals("http", StringComparison.OrdinalIgnoreCase))
                    {
                        endpoint.LoadBalancerProbe.Path = this.ParameterSpecified("ProbePath") ? this.ProbePath : "/";
                    }

                    if (this.ParameterSpecified("ProbeIntervalInSeconds"))
                    {
                        endpoint.LoadBalancerProbe.IntervalInSeconds = this.ProbeIntervalInSeconds;
                    }

                    if (this.ParameterSpecified("ProbeTimeoutInSeconds"))
                    {
                        endpoint.LoadBalancerProbe.TimeoutInSeconds = this.ProbeTimeoutInSeconds;
                    }
                }
            }

            endpoints.Add(endpoint);

            this.WriteObject(VM, true);
        }