Exemplo n.º 1
0
 static void Power(PowerState state)
 {
     using (Form foo = new Form()) {
         SendMessage(foo.Handle, WM_SYSCOMMAND,
             (IntPtr)SC_MONITORPOWER, (IntPtr)state);
     }
 }
Exemplo n.º 2
0
        internal static void SuspendComputer(PowerState state, bool force)
        {
            string action;
            switch (state)
            {
                case PowerState.Suspend:
                    action = "sleep";
                    break;
                case PowerState.Hibernate:
                    action = "hybernate";
                    break;
                default:
                    throw new RoomieRuntimeException("Unknown power state \"" + state + "\"");
            }

            try
            {
                bool ret = System.Windows.Forms.Application.SetSuspendState(state, force, false);

                if (!ret)
                    throw new RoomieRuntimeException("Could not " + action + " computer.");
            }
            catch (Exception exception)
            {
                throw new RoomieRuntimeException("Could not " + action + " computer. " + exception.Message, exception);
            }
        }
Exemplo n.º 3
0
 public PowerUp(string name)
 {
     mSpriteName = name;
     if (name.Equals("powerUpTest"))
     {
         mPower = PowerState.Chaos;
     }
 }
Exemplo n.º 4
0
        public void Draw(GameTime gameTime, SpriteBatch sptiteBatch)
        {
            if (time > 0.0f) time = Math.Max(0.0f, time - (float)gameTime.ElapsedGameTime.TotalSeconds);

            if (time == 0.0f) { State = PowerState.Ground; sprite.PlayAnimation(ground); }

            sprite.Draw(gameTime, sptiteBatch, position, SpriteEffects.None);
        }
Exemplo n.º 5
0
 private string SetAppliancePower(PowerState powerState, IAppliance appliance)
 {
     if(powerState == PowerState.Off)
     {
         return appliance.TurnOff();
     }
     else
     {
         return appliance.TurnOn();
     }
 }
Exemplo n.º 6
0
 private string GetPowerStateName(PowerState powerState)
 {
     switch (powerState)
     {
         case PowerState.Off: return "Off";
         case PowerState.LowPower: return "Low Power";
         case PowerState.MediumPower: return "Medium Power";
         case PowerState.HighPower: return "High Power";
         default:return "Unknown Power";
     }
 }
Exemplo n.º 7
0
 private PowerState TogglePowerState(PowerState powerState)
 {
     if ((int)powerState < (int)PowerState.HighPower)
     {
         int intState = (int)powerState;
         powerState = (PowerState)intState + 1;
     }
     else
     {
         powerState = PowerState.Off;
     }
     return powerState;
 }
Exemplo n.º 8
0
        internal PowerInformation(byte[] data)
        {
            if (data == null)
                return;

            if (data.Length != 8)
                return;

            _recVersion = data[0];
            _powerState = (PowerState)data[1];
            _batteryVoltage = BitConverter.ToUInt16(new byte[] { data[3], data[2] }, 0);
            _numberOfRecharges = BitConverter.ToUInt16(new byte[] { data[5], data[4] }, 0);
            _timeSinceLastRecharge = BitConverter.ToUInt16(new byte[] { data[7], data[6] }, 0);
        }
Exemplo n.º 9
0
        public void PowerOff()
        {
            List<Pixel> pixels;

            pixels = LayoutBuilder.CreateLayout().Matrix.GetChangedPixels();
            pixels.AddRange(LayoutBuilder.CreateLayout().Minutes.GetChangedPixels());
            pixels.AddRange(LayoutBuilder.CreateAmbilight().LeftAmbilight.GetChangedPixels());
            pixels.AddRange(LayoutBuilder.CreateAmbilight().RightAmbilight.GetChangedPixels());

            foreach(Pixel p in pixels)
            {
                p.PixelColor = System.Drawing.Color.Empty;
            }

            m_RenderEngine.Render(pixels);
            m_PowerState = PowerState.Off;
        }
Exemplo n.º 10
0
        private void UpdatePowerState()
        {
            PowerState newState = GetPowerState();

            if(newState != m_CurrentState)
            {

                if(newState == PowerState.On)
                {
                    m_Notifier.PowerOn();
                }
                else
                {
                    m_Notifier.PowerOff();
                }
                m_CurrentState = newState;
            }
        }
Exemplo n.º 11
0
        public void Activate()
        {
            IsActive = true;

            State = PowerState.Active;

            if (destPositon == Level.InvalidPositionVector)
            {
                Point blockIndex = new Point((blockNumber - 1) % 3, (blockNumber - 1) / 3);
                destPositon = puzzlePosition + new Vector2(blockIndex.X * Tile.Width, blockIndex.Y * Tile.Height);

                direction = new Vector2(destPositon.X != position.X ? destPositon.X < position.X ? -1 : 1 : 0,
                    destPositon.Y != position.Y ? destPositon.Y < position.Y ? -1 : 1 : 0);

                if (direction.X != 0) { blockIndex = new Point(direction.X < 0 ? 0 : 2, blockIndex.Y); }
                else { blockIndex = new Point(blockIndex.X, direction.Y < 0 ? 0 : 2); }

                maxSlidePosition = puzzlePosition + new Vector2(blockIndex.X * Tile.Width, blockIndex.Y * Tile.Height);
            }
        }
        private void OnReceive(IAsyncResult ar)
        {
            try {
                UdpClient udp = (UdpClient)ar.AsyncState;
                IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
                byte[] data = udp.EndReceive(ar, ref endpoint);

                if (data[0] == 0) {
                    int n_dev = 20;
                    bool[] enabled = new bool[n_dev];
                    PowerState[] powerState = new PowerState[n_dev];
                    for (int i = 0; i < n_dev; i++) {
                        enabled[i] = (data[i+1] & 0x80) != 0;
                        powerState[i] = (PowerState)(data[i+1] & 0x7f);
                    }

                    OnStatusReceived(new MicroPowerStatusEventArgs(enabled, powerState));
                }

                udp.BeginReceive(OnReceive, udp);
            }
            catch (ObjectDisposedException) {
            }
        }
Exemplo n.º 13
0
 public void Flower()
 {
     PowerState.Flower();
 }
Exemplo n.º 14
0
 public void SetPowerState(PowerState state)
 {
     Wordclock.RenderEngine.SetPowerState(state);
 }
Exemplo n.º 15
0
 /// <summary>
 /// Part of interface IAPCPowerable. Sets the griddle's state according to the given power state.
 /// </summary>
 /// <param name="state">The power state to set the griddle's state with.</param>
 public void StateUpdate(PowerState state)
 {
     CurrentState.PowerStateUpdate(state);
 }
        private void GetData()
        {
            try
            {
                var epd     = ApplicationContext.EndPointListTree.Find(r => r.EndpointId == _endpointId);
                var comType = epd.ComputerType;

                EndpointId          = epd.EndpointId;
                ID                  = epd.GUIID;
                OSName              = epd.OSName;
                UserName            = epd.UserName;
                SystemManufacturer  = epd.SystemManufacturer;
                SystemName          = epd.SystemName;
                SystemType          = epd.SystemType;
                SystemModel         = epd.SystemModel;
                LastSync            = epd.LastSync;
                PowerState          = Functions.UppercaseFirst(epd.PowerState);
                Processor           = epd.Processor;
                TotalPhysicalMemory = (int)Math.Round(epd.TotalPhysicalMemory ?? 0);
                ComputerType        = string.IsNullOrWhiteSpace(ID) ? "" : Functions.UppercaseFirst(comType);
                Domain              = epd.Domain;
                IPv4                = epd.IPv4;
                IPv6                = epd.IPv6;
                MACAddress          = epd.MACAddress;
                HDDCapacity         = epd.HDDCapacity.Replace(";", " GB;");
                FolderId            = epd.FolderId;
                ProductVersion      = epd.ProductVersion;
                FontColor           = "#FFF";
                if (PowerState.ToLower() == "offline")
                {
                    FontColor = "#808e8f98";
                }
                else if (PowerState.ToLower() == "online")
                {
                    FontColor = "#FFF";
                }
                //ImageHeader = string.IsNullOrEmpty(ID)
                //    ? "../../Images/logo_noagent.png"
                //    : string.IsNullOrWhiteSpace(ComputerType)? "../../Images/Notebook.png" : string.Format("../../Images/{0}.png", ComputerType);

                Color       = epd.Color;
                ImageHeader = "../" + EndPoint.GetImages(ComputerType, Color);
                var headerViewModel = _view.EndpointViewHeaderElement.DataContext as EndpointViewHeaderViewModel;
                if (headerViewModel != null)
                {
                    headerViewModel.SystemName            = SystemName;
                    headerViewModel.ImageHeader           = ImageHeader;
                    headerViewModel.ActivedButtonIndex    = 1;
                    headerViewModel.ColorCodeMessageColor = Color;
                    headerViewModel.FontColor             = FontColor;
                    //Reset color message
                    headerViewModel.ColorCodeMessage  = "";
                    headerViewModel.TextStatusVisible = true;

                    if (string.IsNullOrEmpty(ID))
                    {
                        headerViewModel.ColorCodeMessage = "POC Agent not installed";
                    }
                    else if (!string.IsNullOrEmpty(epd.LastSyncDayText))
                    {
                        headerViewModel.ColorCodeMessage =
                            string.Concat(epd.AgentText, "\n", epd.LastSyncDayText).Trim();
                    }
                    else if (string.IsNullOrEmpty(epd.LastSyncDayText) &&
                             (Color == CommonConstants.GREEN_OFFLINE_COLOR ||
                              Color == CommonConstants.GREEN_ONLINE_COLOR) &&
                             !string.IsNullOrEmpty(ID)
                             )
                    {
                        headerViewModel.TextStatusVisible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);

                PageNavigatorHelper._MainWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
                {
                    var messageDialog =
                        PageNavigatorHelper._MainWindow.MessageDialogContentControl.Content as MessageDialog;
                    messageDialog.TxtMessageText.Text =
                        "Cannot get endpoint due to exception occured, please see the log file under the Logs for more information";
                    messageDialog.Visibility = Visibility.Visible;
                }));
            }
        }
Exemplo n.º 17
0
		static Color GetPowerColor(PowerState state)
		{
			if (state == PowerState.Critical) return Color.Red;
			if (state == PowerState.Low) return Color.Orange;
			return Color.LimeGreen;
		}
Exemplo n.º 18
0
 public void Reboot()
 {
     PowerState.RebootDevice(false);
 }
Exemplo n.º 19
0
 private static void SetSuspendState(PowerState state, object sender)
 {
     if (PowerActionConfirmed((ContentControl) sender))
         System.Windows.Forms.Application.SetSuspendState(state,
                                                          SettingsManager.Instance.ForcePowerActions,
                                                          false);
 }
Exemplo n.º 20
0
 public static void SetPowerState(PowerState newState, bool force = false, bool disableWakeupEvents = false)
 {
     Application.SetSuspendState(newState, force, disableWakeupEvents);
 }
Exemplo n.º 21
0
 protected void Died()
 {
     State = PowerState.Die; sprite.PlayAnimation(dieAnimation);
 }
Exemplo n.º 22
0
 /// <include file='doc\Application.uex' path='docs/doc[@for="Application.SetSuspendState"]/*' />
 /// <devdoc>
 ///     Sets the suspend/hibernate state of the machine.
 ///     Returns true if the call succeeded, else false.
 /// </devdoc>
 public static bool SetSuspendState(PowerState state, bool force, bool disableWakeEvent) {
     IntSecurity.AffectMachineState.Demand();
     return UnsafeNativeMethods.SetSuspendState(state == PowerState.Hibernate, force, disableWakeEvent);
 }
Exemplo n.º 23
0
 private static bool SetSuspendState(PowerState state, bool forceShutDown)
 {
   return (Application.SetSuspendState(state, forceShutDown, false));
 }
Exemplo n.º 24
0
        public void Collision(Rectangle bounds)
        {
            State = PowerState.Die; IsActive = false;

            if (direction.X != 0) { position.X = bounds.Left - direction.X * Tile.Width; }
            else { position.Y = bounds.Top - direction.Y * Tile.Height; }
        }
Exemplo n.º 25
0
        private static void SleepMode()
        {
            var ps = new PowerState();

            ps.SetSuspendState(false, false, false);
        }
Exemplo n.º 26
0
        public void Update(GameTime gameTime)
        {
            if (State == PowerState.Active)
            {
                Move(direction, maxSlidePosition);

                if (position == maxSlidePosition) State = PowerState.Die;
            }
            else if (State == PowerState.Pick)
            {
                Vector2 oppDirection = direction * -1;

                Move(oppDirection, oriPosition);

                if (position == oriPosition) State = PowerState.Ground;
            }
        }
        public void CanCreate()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var GroupName       = TestUtilities.GenerateName("rgfluentchash-");
                var computeManager  = TestHelper.CreateComputeManager();
                var resourceManager = TestHelper.CreateResourceManager();

                try
                {
                    // Create
                    var vm = computeManager.VirtualMachines
                             .Define(VMName)
                             .WithRegion(Location)
                             .WithNewResourceGroup(GroupName)
                             .WithNewPrimaryNetwork("10.0.0.0/28")
                             .WithPrimaryPrivateIPAddressDynamic()
                             .WithoutPrimaryPublicIPAddress()
                             .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012Datacenter)
                             .WithAdminUsername("Foo12")
                             .WithAdminPassword("BaR@12!Foo")
                             .WithUnmanagedDisks()
                             .WithOSDiskCaching(CachingTypes.ReadWrite)
                             .WithSize(VirtualMachineSizeTypes.StandardD3)
                             .WithOSDiskName("javatest")
                             .Create();

                    var foundedVM = computeManager.VirtualMachines.ListByResourceGroup(GroupName)
                                    .FirstOrDefault(v => v.Name.Equals(VMName, StringComparison.OrdinalIgnoreCase));

                    Assert.NotNull(foundedVM);
                    Assert.Equal(Location, foundedVM.RegionName);
                    // Get
                    foundedVM = computeManager.VirtualMachines.GetByResourceGroup(GroupName, VMName);
                    Assert.NotNull(foundedVM);
                    Assert.Equal(Location, foundedVM.RegionName);

                    // Fetch instance view
                    PowerState powerState = foundedVM.PowerState;
                    Assert.True(powerState == PowerState.Running);
                    VirtualMachineInstanceView instanceView = foundedVM.InstanceView;
                    Assert.NotNull(instanceView);
                    Assert.NotEmpty(instanceView.Statuses);

                    // Capture the VM [Requires VM to be Poweroff and generalized]
                    foundedVM.PowerOff();
                    foundedVM.Generalize();
                    var jsonResult = foundedVM.Capture("captured-vhds", "cpt", true);
                    Assert.NotNull(jsonResult);

                    // Delete VM
                    computeManager.VirtualMachines.DeleteById(foundedVM.Id);
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(GroupName);
                    }
                    catch { }
                }
            }
        }
Exemplo n.º 28
0
 /// <summary>        
 /// Sending a 0 to the comport will toggle the DC power supply.
 /// Sending a 1 to the comport will toggle the usb power supply.
 /// Sending a 255 to the comport will give you current status of the device.
 /// The status of the device can be one of the four below:
 ///         0x0 = DC & USB off
 ///         0x1 = DC on
 ///         0x2 = USB on
 ///         0x3 = DC & USB on        
 /// </summary>
 /// <param name="power">This parameter specifies the power state which can be on or off.</param>
 /// <param name="ps">This parameter specifies the power source.</param>
 internal static void Switch(PowerState power, PowerSource ps)
 {
     byte status;
     switch (GetStatus())
     {
         case 0: // Both DC & USB off.
             if (power == PowerState.Off)
             {
                 return;
             }
             else
             {
                 switch ((int)ps)
                 {
                     case 2:
                         status = Send(0);
                         CheckStatus(status, 0);
                         status = Send(1);
                         CheckStatus(status, 1);
                         break;
                     default:
                         byte b = Convert.ToByte((int)ps);
                         status = Send(b);
                         CheckStatus(status, b);
                         break;
                 }
             }
             break;
         case 1: // Only DC is on.
             if (power == PowerState.Off)
             {
                 switch ((int)ps)
                 {
                     case 0:
                         status = Send(0);
                         CheckStatus(status, 0);
                         break;
                     default:
                         break;
                 }
             }
             else
             {
                 switch ((int)ps)
                 {
                     case 0:
                         break;
                     default:
                         status = Send(1);
                         CheckStatus(status, 1);
                         break;
                 }
             }
             break;
         case 2: // Only USB is on.
             if (power == PowerState.Off)
             {
                 switch ((int)ps)
                 {
                     case 1:
                         status = Send(1);
                         CheckStatus(status, 1);
                         break;
                     default:
                         break;
                 }
             }
             else
             {
                 switch ((int)ps)
                 {
                     case 1:
                         break;
                     default:
                         status = Send(0);
                         CheckStatus(status, 0);
                         break;
                 }
             }
             break;
         case 3: // Both DC & USB on.
             if (power == PowerState.Off)
             {
                 switch ((int)ps)
                 {
                     case 2:
                         status = Send(0);
                         CheckStatus(status, 0);
                         status = Send(1);
                         CheckStatus(status, 1);
                         break;
                     default:
                         byte b = Convert.ToByte((int)ps);
                         status = Send(b);
                         CheckStatus(status, b);
                         break;
                 }
             }
             else
             {
                 return;
             }
             break;
     }
 }
Exemplo n.º 29
0
        /// <summary>
        /// Sets power state. If powerState is ON, power on the blade; otherwise, power off the blade.
        /// If bladeId is specified, change power state to that specific blade; otherwise, the change
        /// will be made to all blades.
        /// </summary>
        protected bool SetPowerState(PowerState state, int bladeId = -1, [CallerMemberName]
                                     string testName = null)
        {
            try
            {
                var message = string.Format("Set {1} to power state {0}", state,
                    bladeId > 0 ? string.Format("Blade {0}", bladeId) : "all blades");
                CmTestLog.Info(string.Concat("Trying to ", message), testName);
                ChassisResponse response;
                if (bladeId > 0)
                {
                    response = state == PowerState.ON
                               ? this.Channel.SetPowerOn(bladeId)
                               : this.Channel.SetPowerOff(bladeId);
                }
                else
                {
                    response = state == PowerState.ON
                               ? this.Channel.SetAllPowerOn()
                               : this.Channel.SetAllPowerOff();
                }

                var result = ChassisManagerTestHelper.AreEqual(CompletionCode.Success,
                    response.completionCode, message, testName);

                if (state == PowerState.OFF)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(CmConstants.BladePowerOffSeconds));
                }
                else
                {
                    Thread.Sleep(TimeSpan.FromSeconds(CmConstants.BladePowerOnSeconds));
                }

                return result;
            }
            catch (Exception e)
            {
                CmTestLog.Exception(e, testName);
                return false;
            }
        }
Exemplo n.º 30
0
 //NOT CORRECTLY IMPLEMENTED YET
 public void Star()
 {
     PowerState.Star();
 }
Exemplo n.º 31
0
        /// <summary>
        /// Toggles the backlight.
        /// </summary>
        /// <param name="state">Power state to toggle too</param>
        public void ToggleBacklight(PowerState state)
        {
            switch (state) {
            case PowerState.On:
                {
                    if (!m_BacklightIsOn) {
                        m_PiFaceCAD.BacklightOn ();
                        m_BacklightIsOn = true;
                    }

                    break;
                }
            case PowerState.Off:
                {
                    if (m_BacklightIsOn) {
                        m_PiFaceCAD.BacklightOff ();
                        m_BacklightIsOn = false;
                    }

                    break;
                }
            }
        }
Exemplo n.º 32
0
 public void ChangeToSuperMario()
 {
     PowerState.ChangeToSuperMario();
 }
Exemplo n.º 33
0
 private void ProcessTweetSuspend(PowerState state)
 {
     Save();
     InitSince_ID();
     TweetShuttingDown = true;
     Application.SetSuspendState(state, true, false);
 }
Exemplo n.º 34
0
 public static bool SetSuspendState(PowerState state,
                                    bool force,
                                    bool disableWakeEvent)
 {
     return(false);
 }
        public static void UpdateRampPositions(float frameTime, PowerState state)
        {
            // Update supplies to move their ramp position towards target, if necessary.
            foreach (var supply in state.Supplies.Values)
            {
                if (supply.Paused)
                {
                    continue;
                }

                if (!supply.Enabled)
                {
                    // If disabled, set ramp to 0.
                    supply.SupplyRampPosition = 0;
                    continue;
                }

                var rampDev = supply.SupplyRampTarget - supply.SupplyRampPosition;
                if (Math.Abs(rampDev) > 0.001f)
                {
                    float newPos;
                    if (rampDev > 0)
                    {
                        // Position below target, go up.
                        newPos = Math.Min(
                            supply.SupplyRampTarget,
                            supply.SupplyRampPosition + supply.SupplyRampRate * frameTime);
                    }
                    else
                    {
                        // Other way around, go down
                        newPos = Math.Max(
                            supply.SupplyRampTarget,
                            supply.SupplyRampPosition - supply.SupplyRampRate * frameTime);
                    }

                    supply.SupplyRampPosition = Math.Clamp(newPos, 0, supply.MaxSupply);
                }
                else
                {
                    supply.SupplyRampPosition = supply.SupplyRampTarget;
                }
            }

            // Batteries too.
            foreach (var battery in state.Batteries.Values)
            {
                if (battery.Paused)
                {
                    continue;
                }

                if (!battery.Enabled)
                {
                    // If disabled, set ramp to 0.
                    battery.SupplyRampPosition = 0;
                    continue;
                }

                var rampDev = battery.SupplyRampTarget - battery.SupplyRampPosition;
                if (Math.Abs(rampDev) > 0.001f)
                {
                    float newPos;
                    if (rampDev > 0)
                    {
                        // Position below target, go up.
                        newPos = Math.Min(
                            battery.SupplyRampTarget,
                            battery.SupplyRampPosition + battery.SupplyRampRate * frameTime);
                    }
                    else
                    {
                        // Other way around, go down
                        newPos = Math.Max(
                            battery.SupplyRampTarget,
                            battery.SupplyRampPosition - battery.SupplyRampRate * frameTime);
                    }

                    battery.SupplyRampPosition = Math.Clamp(newPos, 0, battery.MaxSupply);
                }
                else
                {
                    battery.SupplyRampPosition = battery.SupplyRampTarget;
                }
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// Triggered when a command has been given
        /// </summary>
        /// <param name="Shell">Reference to the shell</param>
        /// <param name="Arguments">Command line arguments</param>
        /// <param name="SuspressError">Set to 'true' if you could do anything with the command</param>
        /// <param name="Time">Current timestamp</param>
        private static void Shell_OnCommandReceived(ShellCore Shell, string[] Arguments, ref bool SuspressError, DateTime Time)
        {
            switch (Arguments[0].ToUpper())
            {
            case "CLS":
                Shell.TelnetServer.ClearScreen();
                SuspressError = true;
                break;

            case "MOTD":
                _SendMotd(Shell.TelnetServer);
                SuspressError = true;
                break;

            case "ECHO":
                Shell.TelnetServer.Print(Shell.LastCommandline.Substring(5));
                SuspressError = true;
                break;

            case "REBOOT":
                Shell.TelnetServer.Print("Rebooting...");
                Thread.Sleep(100);
                Shell.TelnetServer.Close();
                PowerState.RebootDevice(false);
                SuspressError = true;
                break;

            case "QUIT":
                Shell.TelnetServer.Print("Bye!");
                Thread.Sleep(100);
                Shell.TelnetServer.Close();
                SuspressError = true;
                break;

            case "INFO":
                Shell.TelnetServer.Print("Manufacturer: " + SystemInfo.OEMString);
                Shell.TelnetServer.Print("Firmware version: " + SystemInfo.Version.ToString());
                Shell.TelnetServer.Print("Memory available: " + Tools.MetricPrefix(Debug.GC(false), true) + "B");
                if (PowerState.Uptime.Days == 0)
                {
                    Shell.TelnetServer.Print("Uptime: " + PowerState.Uptime.ToString());
                }
                else
                {
                    Shell.TelnetServer.Print("Uptime: " + PowerState.Uptime.Days.ToString() + " days, " + PowerState.Uptime.ToString());
                }
                Shell.TelnetServer.Print("Hardware provider: " + Tools.HardwareProvider);
                Shell.TelnetServer.Print("System clock: " + Tools.MetricPrefix(Cpu.SystemClock) + "hz");
                Shell.TelnetServer.Print("Endianness: " + (SystemInfo.IsBigEndian ? "Big Endian" : "Little Endian"));
                Shell.TelnetServer.Print("Debugger: " + (System.Diagnostics.Debugger.IsAttached ? "attached" : "not attached"));
                SuspressError = true;
                break;

            case "VER":
                System.Reflection.Assembly[] Assemblies = AppDomain.CurrentDomain.GetAssemblies();
                for (int i = 0; i < Assemblies.Length; ++i)
                {
                    Shell.TelnetServer.Print(Assemblies[i].FullName);
                }
                SuspressError = true;
                break;

            case "HELP":
                bool PageFound = false;
                if (Arguments.Length == 1)
                {
                    PageFound = DoHelp(Shell.TelnetServer, "");
                }
                else
                {
                    PageFound = DoHelp(Shell.TelnetServer, Arguments[1].ToUpper());
                }
                if (PageFound)
                {
                    SuspressError = true;
                }
                break;
            }
        }
Exemplo n.º 37
0
 //actions that can be taken
 public void Damage()
 {
     PowerState.Damage();
 }
Exemplo n.º 38
0
        public List <PowerGame> Parse(bool createJsonFile, bool createCleanLog)
        {
            List <PowerGame>         powerGames        = new List <PowerGame>();
            PowerState               currentPowerState = PowerState.Start;
            PowerGame                currentPowerGame  = null;
            PowerType                currentPowerType  = 0;
            Dictionary <string, int> currentNameToIdDict;
            PowerHistoryEntry        currentPowerHistoryEntry = null;
            StringBuilder            cleanLog = new StringBuilder();

            string line;

            while ((line = file.ReadLine()) != null)
            {
                Match matchLogRgx = logRgx.Match(line);
                if (matchLogRgx.Success)
                {
                    string entryType = matchLogRgx.Groups[1].Value;
                    string timestamp = matchLogRgx.Groups[2].Value;
                    string classType = matchLogRgx.Groups[3].Value;
                    string debugType = matchLogRgx.Groups[4].Value;
                    string content   = matchLogRgx.Groups[5].Value;

                    if (!classType.Equals("GameState") || debugType.Equals("DebugPrintOptions"))
                    {
                        continue;
                    }

                    string contentLine = content.Trim();

                    cleanLog.AppendLine($"{("[" + debugType.ToString() + "] ").PadLeft(27)}{content}");

                    PowerType nextPowerType;
                    if (Enum.TryParse <PowerType>(contentLine.Split(' ')[0], out nextPowerType))
                    {
                        currentPowerType = nextPowerType;
                    }
                    ;

                    switch (currentPowerType)
                    {
                    case PowerType.CREATE_GAME:
                        break;
                    }
                }
                else
                {
                    Console.WriteLine("matchLogRgx: '" + line + "'");
                }
            }

            if (createJsonFile)
            {
                string jsonStr = JsonConvert.SerializeObject(powerGames, Formatting.Indented,
                                                             new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.All
                });
                File.WriteAllText(filePath + "powerLog.json", jsonStr);
            }

            if (createCleanLog)
            {
                File.WriteAllText(filePath + "cleanLog.log", cleanLog.ToString());
            }

            //while (powerGame.PowerHistory.Count > 0)
            //{
            //    var powerHistoryEntry = powerGame.PowerHistory.Dequeue();
            //    powerHistoryEntry.Process(powerGame);
            //}
            //File.WriteAllText(filePath + "powerLogProc.json", JsonConvert.SerializeObject(powerGame, Formatting.Indented));

            return(powerGames);
        }
Exemplo n.º 39
0
 public void Mushroom()
 {
     PowerState.Mushroom();
 }
Exemplo n.º 40
0
 public override string Toggle()
 {
     _powerState = TogglePowerState(_powerState);
     return string.Format("PullChain->{0}->{1}", GetPowerStateName(_powerState), SetAppliancePower(_powerState, Appliance));
 }
Exemplo n.º 41
0
 public void ChangeToSmallMario()
 {
     PowerState.ChangeToSmallMario();
 }
Exemplo n.º 42
0
        public void PowerOn()
        {
            m_PowerState = PowerState.On;

            Render(m_LastRenderedPixels);
        }
Exemplo n.º 43
0
 public void ChangeToFireMario()
 {
     PowerState.ChangeToFireMario();
 }
Exemplo n.º 44
0
        private void ProcessRequest()
        {
            const Int32 c_microsecondsPerSecond = 1000000;

            try
            {
                using (m_clientSocket)
                {
                    if (m_clientSocket.Poll(5 * c_microsecondsPerSecond,
                                            SelectMode.SelectRead))
                    {
                        if (m_clientSocket.Available == 0)
                        {
                            return;
                        }

                        int bytesReceived = m_clientSocket.Available;
                        if (bytesReceived > 0)
                        {
                            byte[]   buffer    = new byte[bytesReceived];
                            int      byteCount = m_clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);
                            string   request   = new string(Encoding.UTF8.GetChars(buffer));
                            string   firstLine = request.Substring(0, request.IndexOf('\n'));
                            string[] words     = firstLine.Split(' ');

                            string command  = string.Empty;
                            string response = string.Empty;
                            string header   = string.Empty;

                            Logging.log_entry("ACCESS " + m_clientSocket.RemoteEndPoint.ToString() + " - " + '"' + firstLine.Trim() + '"');

                            //Debug.Print("Memory: " + Microsoft.SPOT.Debug.GC(true).ToString());

                            command = words[1].Substring(1).Trim();
                            if (command[0] == 63)                             // '?'
                            {
                                // pokud nam zustal otaznik na zacatku, tak oriznout o dva
                                command = words[1].Substring(2).Trim();
                            }

                            // bliknuti
                            m_ports[0].Write(true);
                            Thread.Sleep(10);
                            m_ports[0].Write(false);

                            // ocekavane url
                            // GET /?login=admin:admin&led=

                            if (command.Equals("favicon.ico"))
                            {
                                byte[] favicon = FileUtilities.file_get_contents_byte(@"\SD\setup\favicon.ico");
                                header = "HTTP/1.0 200 OK\r\nContent-Type: image/x-icon\r\nContent-Length: " + favicon.Length.ToString() + "\r\nConnection: close\r\n\r\n";
                                m_clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
                                m_clientSocket.Send(favicon, favicon.Length, SocketFlags.None);
                            }
                            else
                            {
                                if (command.Length > 0)
                                {
                                    bool authenticated = false;

                                    try
                                    {
                                        string[] cmds = command.Split('&');
                                        if (cmds.Length > 0)
                                        {
                                            for (int i = 0; i < cmds.Length; i++)
                                            {
                                                // zpracovani jednotlivych prikazu
                                                string[] cmd_parsed = cmds[i].Split('=');
                                                switch (cmd_parsed[0])
                                                {
                                                // login - prihlaseni ke sluzbam
                                                // l=user:password
                                                case "login":
                                                    string[] auth_data = cmd_parsed[1].Split(':');
                                                    authenticated = UserControl.authenticate(auth_data[0], auth_data[1]);
                                                    break;

                                                // ports
                                                case "led":
                                                    if (authenticated)
                                                    {
                                                        if (cmd_parsed[1].Length == 5)
                                                        {
                                                            controlLedStripe(cmd_parsed[1]);
                                                        }
                                                        else
                                                        {
                                                            SendResponse("500 Bad command params", "500 Internal Server Error");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        SendResponse("401 Unauthorized");
                                                    }
                                                    break;

                                                case "restart":
                                                    if (authenticated)
                                                    {
                                                        SendResponse("200 OK");
                                                        m_clientSocket.Close();
                                                        PowerState.RebootDevice(false);
                                                    }
                                                    break;

                                                default:
                                                    SendResponse("500 Unknown command", "500 Internal Server Error");

                                                    break;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            // stranka pokud nebyly predany parametry
                                            SendResponse("200 HELLO * GIVE ME COMMAND :-)", "200 OK");
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        Logging.log_entry(e.ToString());
                                    }
                                }
                                else
                                {
                                    // stranka pokud nebyl zadny request string
                                    SendResponse("200 HELLO * GIVE ME COMMAND :-)", "200 OK");
                                }
                            }

                            m_clientSocket.Close();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logging.log_entry(e.ToString());
            }
        }
Exemplo n.º 45
0
        private void InsertVirtualMachineAvailabilityZoneRegionResults(string region, int availbilityZone, TraceWriter log)
        {
            try
            {
                var virtualMachineQuery = TableQuery.CombineFilters(TableQuery.GenerateFilterConditionForInt(
                                                                        "AvailabilityZone",
                                                                        QueryComparisons.Equal,
                                                                        availbilityZone),
                                                                    TableOperators.And,
                                                                    TableQuery.GenerateFilterCondition("RegionName",
                                                                                                       QueryComparisons.Equal,
                                                                                                       region));

                //TableQuery.GenerateFilterConditionForInt("AvailabilityZone", QueryComparisons.GreaterThanOrEqual, 0);
                var virtualMachinesTableQuery     = new TableQuery <VirtualMachineCrawlerResponse>().Where(virtualMachineQuery);
                var crawledVirtualMachinesResults = StorageAccountProvider.GetEntities(
                    virtualMachinesTableQuery,
                    StorageTableNames.VirtualMachineCrawlerTableName);
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                crawledVirtualMachinesResults = crawledVirtualMachinesResults.Where(x => PowerState.Parse(x.State) == PowerState.Running);
                var virtualMachinesResults = crawledVirtualMachinesResults.ToList();
                var meanTimeQuery          = TableQuery.GenerateFilterConditionForDate("ScheduledExecutionTime",
                                                                                       QueryComparisons.GreaterThanOrEqual,
                                                                                       DateTimeOffset.UtcNow.AddMinutes(-azureClient.AzureSettings.Chaos.MeanTime));

                var recentlyExecutedAvailabilityZoneRegionCombinationQuery = TableQuery.GenerateFilterCondition(
                    "ResourceType",
                    QueryComparisons.Equal,
                    VirtualMachineGroup.VirtualMachineScaleSets.ToString());

                var recentlyExecutedVMScaleSetsQuery = TableQuery.CombineFilters(meanTimeQuery,
                                                                                 TableOperators.And,
                                                                                 recentlyExecutedAvailabilityZoneRegionCombinationQuery);

                var scheduledQuery = new TableQuery <ScheduledRules>().Where(recentlyExecutedVMScaleSetsQuery);
                //Will get the executed query results.
                var executedVMScaleSetsResults = StorageAccountProvider.GetEntities(scheduledQuery,
                                                                                    StorageTableNames.ScheduledRulesTableName);

                List <VirtualMachineCrawlerResponse> executedVMAvailabilityZones = null;

                if (virtualMachinesResults.Count() != 0 && executedVMScaleSetsResults.Count() != 0)
                {
                    foreach (var virtualMachineResult in virtualMachinesResults)
                    {
                        foreach (var executedVMScaleSetsResult in executedVMScaleSetsResults)
                        {
                            if ((executedVMScaleSetsResult.RowKey.ToLowerInvariant().Contains(virtualMachineResult.ResourceName.ToLowerInvariant())) &&
                                (executedVMScaleSetsResult.RowKey.ToLowerInvariant().Contains(virtualMachineResult.ResourceGroupName.ToLowerInvariant())) &&
                                (executedVMScaleSetsResult.RowKey.ToLowerInvariant().Contains(virtualMachineResult.AvailabilityZone.ToString()))
                                //&& (executedVMScaleSetsResult.RowKey.ToLowerInvariant().Contains(executedVMScaleSetsResult..ToLowerInvariant()))
                                )
                            {
                                executedVMAvailabilityZones.Add(virtualMachineResult);
                            }
                        }
                    }
                    if (executedVMAvailabilityZones != null && executedVMAvailabilityZones.Count() != 0)
                    {
                        virtualMachinesResults = virtualMachinesResults.Except(executedVMAvailabilityZones).ToList();
                    }
                }
                if (!virtualMachinesResults.Any())
                {
                    return;
                }
                var batchTasks = new List <Task>();
                var table      = StorageAccountProvider.CreateOrGetTable(StorageTableNames.ScheduledRulesTableName);
                if (table == null)
                {
                    return;
                }

                for (var i = 0; i < virtualMachinesResults.Count; i += TableConstants.TableServiceBatchMaximumOperations)
                {
                    var batchItems = virtualMachinesResults.Skip(i)
                                     .Take(TableConstants.TableServiceBatchMaximumOperations).ToList();
                    var scheduledRulesbatchOperation = VirtualMachineHelper
                                                       .CreateScheduleEntityForAvailabilityZone(
                        batchItems,
                        azureClient.AzureSettings.Chaos.SchedulerFrequency,
                        azureClient.AzureSettings.Chaos.AzureFaultInjectionActions);

                    if (scheduledRulesbatchOperation.Count <= 0)
                    {
                        return;
                    }
                    batchTasks.Add(table.ExecuteBatchAsync(scheduledRulesbatchOperation));
                }

                if (batchTasks.Count > 0)
                {
                    Task.WhenAll(batchTasks);
                }
            }
            catch (Exception ex)
            {
                log.Error("AvailabilityZone RuleEngine: thrown exception", ex);
                log.Error(ex.Source);
                log.Error(ex.Message);
            }
        }
Exemplo n.º 46
0
		public static bool SetSuspendState (PowerState state, bool force, bool disableWakeEvent)
		{
			return false;
		}
Exemplo n.º 47
0
 public static extern int SetSystemPowerState(String stateName, PowerState powerState, DevicePowerFlags flags);
Exemplo n.º 48
0
 public void SmallMario()
 {
     PowerState.SmallMario(this);
 }
Exemplo n.º 49
0
        private static void HibernateMode()
        {
            var ps = new PowerState();

            ps.SetSuspendState(true, true, false);
        }
Exemplo n.º 50
0
 public void SuperMario()
 {
     PowerState.SuperMario(this);
 }
Exemplo n.º 51
0
 public abstract void PowerStateUpdate(PowerState state);
Exemplo n.º 52
0
 public void FireMario()
 {
     PowerState.FireMario(this);
 }
Exemplo n.º 53
0
        public void WaitForReady()
        {
            TimeSpan waitBetweenChecks = TimeSpan.FromSeconds(5);

            OnUpdateStatus("Waiting for device to come to ready...");

            PowerState[] rejectedPowerStates = new PowerState[] { PowerState.Off, PowerState.None };
            OnUpdateStatus($"  Waiting for device to return a responsive power state...");
            int  powerCheckCount = 0;
            bool success         =
                Wait.ForTrue(
                    () =>
            {
                var state = _device.PowerManagement.GetPowerState();
                OnUpdateStatus($"    Device Power State: {state}");
                bool ok = !rejectedPowerStates.Contains(state);
                if (ok)
                {
                    ++powerCheckCount;
                }
                return(ok);
            }
                    , TimeSpan.FromSeconds(240)
                    , waitBetweenChecks);

            if (!success)
            {
                throw new DeviceInvalidOperationException($"Device did not come to an acceptable power state. ({_device.Address})");
            }

            DeviceStatus[] acceptedDeviceStatus = new DeviceStatus[] { DeviceStatus.Running, DeviceStatus.Warning };
            OnUpdateStatus($"  Waiting for device status reflecting readiness...");
            success =
                Wait.ForTrue(
                    () =>
            {
                var state = _device.GetDeviceStatus();
                OnUpdateStatus($"    Device Status: {state}");
                return(acceptedDeviceStatus.Contains(state));
            }
                    , TimeSpan.FromSeconds(240)
                    , waitBetweenChecks);

            if (!success)
            {
                throw new DeviceInvalidOperationException($"Device did not return an acceptable status. ({_device.Address})");
            }

            OnUpdateStatus($"  Waiting for device web services and OXP services to come online...");
            const int     MaxCreateCreateDeviceAttempts = 10;
            int           createDeviceAttempts          = 0;
            const int     ConsecutiveSuccessfulDeviceInfoCallsRequired = 2;
            int           consecutiveSuccessfulDeviceInfoCalls         = 0;
            StringBuilder statusMessages = new StringBuilder();

            do
            {
                JediDevice tempDevice = null;
                try
                {
                    using (tempDevice = (JediDevice)DeviceConstructor.Create(_deviceInfo))
                    {
                        var deviceInfo = tempDevice.GetDeviceInfo();
                        if (++consecutiveSuccessfulDeviceInfoCalls >= ConsecutiveSuccessfulDeviceInfoCallsRequired)
                        {
                            string message = $"Device is ready. (FirmwareRevision {deviceInfo.FirmwareRevision}; FirmwareDateCode: {deviceInfo.FirmwareDateCode})";
                            OnUpdateStatus($"    {message}");
                            break;
                        }
                        else
                        {
                            string message = $"Device is responding. (ModelName {deviceInfo.ModelName}; ModelNumber: {deviceInfo.ModelNumber}; SerialNumber: {deviceInfo.SerialNumber})";
                            OnUpdateStatus($"    {message}");
                            statusMessages.AppendLine(message);
                            waitBetweenChecks = TimeSpan.FromSeconds(3);
                        }
                    }
                }
                catch (InvalidCastException castX)
                {
                    // Might encounter exception: Unable to cast object of type 'HP.DeviceAutomation.Phoenix.PhoenixDevice' to type 'HP.DeviceAutomation.Jedi.JediDevice'.
                    // Device is still initializing operate a different web service which looks like a Phoenix device.
                    OnUpdateStatus($"    Device is still initializing and hosting a rudimentary EWS landing page on a Phoenix-y web server. ({castX.Message})");
                    statusMessages.AppendLine(castX.ToString());
                }
                catch (DeviceCommunicationException comX)
                {
                    // HP.DeviceAutomation.DeviceCommunicationException: OXP UI Configuration service could not be found at 15.86.229.141
                    // HP.DeviceAutomation.DeviceCommunicationException: OXP UI Configuration service at 15.86.229.141 did not respond.
                    OnUpdateStatus($"    Device OXP services not yet ready. ({comX.Message})");
                    statusMessages.AppendLine(comX.ToString());
                }
                catch (Exception x)
                {
                    OnUpdateStatus($"    {x.Message}");
                    statusMessages.AppendLine(x.ToString());
                }

                Thread.Sleep(waitBetweenChecks);
            } while (++createDeviceAttempts <= MaxCreateCreateDeviceAttempts);

            if (createDeviceAttempts >= MaxCreateCreateDeviceAttempts)
            {
                OnUpdateStatus(statusMessages.ToString());
                throw new DeviceInvalidOperationException($"Device web services and/or OXP services did not respond as expected after {MaxCreateCreateDeviceAttempts} attempts.");
            }
        }
Exemplo n.º 54
0
 public void DeadMario()
 {
     PowerState.DeadMario(this);
 }
        public void CannotUpdateProximityPlacementGroupForVirtualMachine()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var GroupName1      = TestUtilities.GenerateName("rgfluentchash-");
                var GroupName2      = TestUtilities.GenerateName("rgfluentchash-");
                var AvailName1      = TestUtilities.GenerateName("availset1");
                var AvailName2      = TestUtilities.GenerateName("availset2");
                var ProxyGroupName1 = TestUtilities.GenerateName("testproxgroup1");
                var ProxyGroupName2 = TestUtilities.GenerateName("testproxgroup1");

                var ProxyGroupType = ProximityPlacementGroupType.Standard;
                var RegionPPG1     = Region.USWestCentral;
                var RegionPPG2     = Region.USSouthCentral;

                var computeManager  = TestHelper.CreateComputeManager();
                var resourceManager = TestHelper.CreateResourceManager();

                try
                {
                    var setCreated1 = computeManager.AvailabilitySets
                                      .Define(AvailName1)
                                      .WithRegion(RegionPPG1)
                                      .WithNewResourceGroup(GroupName1)
                                      .WithNewProximityPlacementGroup(ProxyGroupName1, ProxyGroupType)
                                      .Create();

                    Assert.Equal(AvailName1, setCreated1.Name);
                    Assert.NotNull(setCreated1.ProximityPlacementGroup);
                    Assert.Equal(ProxyGroupType, setCreated1.ProximityPlacementGroup.ProximityPlacementGroupType);
                    Assert.NotNull(setCreated1.ProximityPlacementGroup.AvailabilitySetIds);
                    Assert.False(setCreated1.ProximityPlacementGroup.AvailabilitySetIds.Count == 0);
                    Assert.Equal(setCreated1.Id, setCreated1.ProximityPlacementGroup.AvailabilitySetIds[0], true);
                    Assert.Equal(setCreated1.RegionName, setCreated1.ProximityPlacementGroup.Location);


                    var setCreated2 = computeManager.AvailabilitySets
                                      .Define(AvailName2)
                                      .WithRegion(RegionPPG2)
                                      .WithNewResourceGroup(GroupName2)
                                      .WithNewProximityPlacementGroup(ProxyGroupName2, ProxyGroupType)
                                      .Create();

                    Assert.Equal(AvailName2, setCreated2.Name);
                    Assert.NotNull(setCreated2.ProximityPlacementGroup);
                    Assert.Equal(ProxyGroupType, setCreated2.ProximityPlacementGroup.ProximityPlacementGroupType);
                    Assert.Equal(ProxyGroupType, setCreated2.ProximityPlacementGroup.ProximityPlacementGroupType);
                    Assert.NotNull(setCreated2.ProximityPlacementGroup.AvailabilitySetIds);
                    Assert.False(setCreated2.ProximityPlacementGroup.AvailabilitySetIds.Count == 0);
                    Assert.Equal(setCreated2.Id, setCreated2.ProximityPlacementGroup.AvailabilitySetIds[0], true);
                    Assert.Equal(setCreated2.RegionName, setCreated2.ProximityPlacementGroup.Location);

                    // Create
                    computeManager.VirtualMachines
                    .Define(VMName)
                    .WithRegion(RegionPPG1)
                    .WithExistingResourceGroup(GroupName1)
                    .WithNewPrimaryNetwork("10.0.0.0/28")
                    .WithPrimaryPrivateIPAddressDynamic()
                    .WithoutPrimaryPublicIPAddress()
                    .WithProximityPlacementGroup(setCreated1.ProximityPlacementGroup.Id)
                    .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012Datacenter)
                    .WithAdminUsername("Foo12")
                    .WithAdminPassword("abc!@#F0orL")
                    .WithUnmanagedDisks()
                    .WithSize(VirtualMachineSizeTypes.StandardDS3V2)
                    .WithOSDiskCaching(CachingTypes.ReadWrite)
                    .WithOSDiskName("javatest")
                    .WithLicenseType("Windows_Server")
                    .Create();

                    IVirtualMachine foundVM = null;
                    var             vms     = computeManager.VirtualMachines.ListByResourceGroup(GroupName1);
                    foreach (IVirtualMachine vm1 in vms)
                    {
                        if (vm1.Name.Equals(VMName))
                        {
                            foundVM = vm1;
                            break;
                        }
                    }
                    Assert.NotNull(foundVM);
                    Assert.Equal(RegionPPG1, foundVM.Region);
                    // Get
                    foundVM = computeManager.VirtualMachines.GetByResourceGroup(GroupName1, VMName);
                    Assert.NotNull(foundVM);
                    Assert.Equal(RegionPPG1, foundVM.Region);
                    Assert.Equal("Windows_Server", foundVM.LicenseType);

                    // Fetch instance view
                    PowerState powerState = foundVM.PowerState;
                    Assert.Equal(powerState, PowerState.Running);
                    VirtualMachineInstanceView instanceView = foundVM.InstanceView;
                    Assert.NotNull(instanceView);
                    Assert.True(instanceView.Statuses.Count > 0);

                    Assert.NotNull(foundVM.ProximityPlacementGroup);
                    Assert.Equal(ProxyGroupType, foundVM.ProximityPlacementGroup.ProximityPlacementGroupType);
                    Assert.NotNull(foundVM.ProximityPlacementGroup.AvailabilitySetIds);
                    Assert.True(foundVM.ProximityPlacementGroup.AvailabilitySetIds.Count > 0);
                    Assert.Equal(setCreated1.Id, foundVM.ProximityPlacementGroup.AvailabilitySetIds[0], true);
                    Assert.NotNull(foundVM.ProximityPlacementGroup.VirtualMachineIds);
                    Assert.True(foundVM.ProximityPlacementGroup.VirtualMachineIds.Count > 0);
                    Assert.Equal(foundVM.Id, setCreated1.ProximityPlacementGroup.VirtualMachineIds[0], true);

                    try
                    {
                        //Update Vm to remove it from proximity placement group
                        IVirtualMachine updatedVm = foundVM.Update()
                                                    .WithProximityPlacementGroup(setCreated2.ProximityPlacementGroup.Id)
                                                    .Apply();
                    }
                    catch (Microsoft.Rest.Azure.CloudException clEx)
                    {
                        Assert.Equal("Changing property 'proximityPlacementGroup.id' is not allowed.", clEx.Message, true);
                    }

                    // Delete resources
                    computeManager.VirtualMachines.DeleteById(foundVM.Id);
                    computeManager.AvailabilitySets.DeleteById(setCreated1.Id);
                    computeManager.AvailabilitySets.DeleteById(setCreated2.Id);
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(GroupName1);
                        resourceManager.ResourceGroups.DeleteByName(GroupName2);
                    }
                    catch { }
                }
            }
        }
Exemplo n.º 56
0
 /// <summary>
 /// Set power to an explicit state (on/off).
 /// </summary>
 /// <param name="powerState">On or off.</param>
 /// <param name="duration">How long in seconds you want the power action to take. Range: 0.0 – 3155760000.0 (100 years).</param>
 /// <returns></returns>
 public async Task <ApiResult> SetPower(PowerState powerState, double duration = LifxClient.DEFAULT_DURATION)
 {
     return((await Client.SetPower(this, powerState, duration)).Results.First());
 }
Exemplo n.º 57
0
 public static extern int SetSystemPowerState(String stateName, PowerState powerState, DevicePowerFlags flags);
Exemplo n.º 58
0
 /// <summary>
 /// Set an explicit state. As documented here: https://api.developer.lifx.com/docs/set-state.
 /// </summary>
 /// <param name="powerState">On or off.</param>
 /// <param name="color">The color to set the light to.</param>
 /// <param name="brightness">The brightness level from 0.0 to 1.0. Overrides any brightness set in color (if any).</param>
 /// <param name="duration">How long in seconds you want the power action to take. Range: 0.0 – 3155760000.0 (100 years).</param>
 /// <param name="infrared">The maximum brightness of the infrared channel.</param>
 /// <returns></returns>
 public async Task <ApiResult> SetState(PowerState powerState, LifxColor color, double brightness, double duration = LifxClient.DEFAULT_DURATION, double infrared = LifxClient.DEFAULT_INFRARED)
 {
     return((await Client.SetState(this, powerState, color, brightness, duration, infrared)).Results.First());
 }
Exemplo n.º 59
0
        /// <summary>
        /// Verifies that all BladeStateResponses in the given collection are the same as the expectedState.
        /// If a blade is a server, this method verifies the server has the same state as the expectedState; if a blade
        /// is a jbod, this method ignores the expectedState parameter and verifies the blade returns CommandNotValidForBlade.
        /// If there is only one response in the collection and it is from an empty slot, the method returns false; 
        /// in other cases, empty slots in the collection will just be ignored.
        /// </summary>
        protected bool VerifyBladeState(PowerState expectedState, IEnumerable<BladeStateResponse> bladeStates,
            [CallerMemberName]
            string testName = null)
        {
            GetAllBladesInfoResponse allBlades;
            if (!this.GetAllBladesInfo(out allBlades, testName))
            {
                return false;
            }

            try
            {
                var bladeStateCollection = new List<BladeStateResponse>(bladeStates);
                bool serverResult = true, jbodResult = true;

                foreach (var state in bladeStateCollection)
                {
                    // current blade info
                    var bladeInfo = allBlades.bladeInfoResponseCollection.Single(info => info.bladeNumber == state.bladeNumber);

                    if (string.IsNullOrEmpty(bladeInfo.bladeType))
                    {
                        // for empty slot, if it is the only blade to be vefiried, return false;
                        // or just ignore it, not counting into result.
                        if (bladeStateCollection.Count == 1)
                        {
                            return false;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    // verify server blade
                    if (bladeInfo.bladeType.Equals(CmConstants.ServerBladeType) && state.bladeState != expectedState)
                    {
                        serverResult = false;
                        CmTestLog.Failure(string.Format("Server Blade #{0} state is not as expected (Expected: {1}, Actual: {2})",
                            state.bladeNumber, expectedState, state.bladeState), testName);
                    }
                    // verify jbod blade
                    else if (bladeInfo.bladeType.Equals(CmConstants.JbodBladeType) && state.completionCode != CompletionCode.CommandNotValidForBlade)
                    {
                        jbodResult = false;
                        CmTestLog.Failure(string.Format("JBOD Blade #{0} completion code is not correct (Expected: {1}, Actual: {2})",
                            state.bladeNumber, CompletionCode.CommandNotValidForBlade, state.completionCode), testName);
                    }
                }

                if (serverResult)
                {
                    CmTestLog.Success(string.Format("Verified server blades are {0}", expectedState), testName);
                }
                if (jbodResult)
                {
                    CmTestLog.Success("Verified JBODs return CommandNotValidForBlade", testName);
                }

                return serverResult && jbodResult;
            }
            catch (Exception e)
            {
                CmTestLog.Exception(e, testName);
                return false;
            }
        }
Exemplo n.º 60
0
        /// <summary>
        /// Toggles the display.
        /// </summary>
        /// <param name="state">Power state to toggle too</param>
        public void ToggleDisplay(PowerState state)
        {
            switch (state) {
            case PowerState.On:
                {
                    if (!m_DisplayIsOn) {
                        m_PiFaceCAD.DisplayOn ();
                        m_DisplayIsOn = true;
                    }

                    break;
                }
            case PowerState.Off:
                {
                    if (m_DisplayIsOn) {
                        if (m_BacklightIsOn) {
                            ToggleBacklight (PowerState.Off);
                        }

                        m_PiFaceCAD.DisplayOff ();
                        m_DisplayIsOn = false;
                    }

                    break;
                }
            }
        }