Node.js/Electron - Can I reset the system idle time? - node.js

It's quite easy to get the system idle time in Electron with powerMonitor.getSystemIdleTime() However, I wonder if there is any easy way to reset this? I tried both the powerSaveBlocker.start('prevent-app-suspension') and the powerSaveBlocker.start('prevent-display-sleep') but they don't really reset the idle time.
When I use the Caffeine on the Mac OSX I noticed it works perfectly. It keeps reseting the system idle time.
Checked into the Caffeine source code. It's written in C#, not sure how can we make it in Node.js/Electron.
internal static class NativeMethods {
[DllImport("kernel32.dll")]
public static extern uint SetThreadExecutionState(uint esFlags);
public const uint ES_CONTINUOUS = 0x80000000;
public const uint ES_SYSTEM_REQUIRED = 0x00000001;
public const uint ES_DISPLAY_REQUIRED = 0x00000002;
}
Any good ideas?

Related

How to obtain iOS device CPU architecture in Xamarin?

In my Xamarin iOS application, I can obtain many device characteristics such as model, system name, etc. from UIKit.UIDevice.CurrentDevice instance. However, I don't see any method to obtain CPU architecture (x86, arm, etc.) on the class.
How can I get the iOS device CPU architecture in runtime shows a way to get this information using Objective C. I am wondering if there a way to get the CPU information in C# using any of the predefined Xamarin classes.
Create a new file with this class on your iOS project:
public static class DeviceInfo
{
public const string HardwareSysCtlName = "hw.machine";
public static string HardwareArch { get; private set; }
[DllImport(ObjCRuntime.Constants.SystemLibrary)]
static internal extern int sysctlbyname([MarshalAs(UnmanagedType.LPStr)] string property, IntPtr output, IntPtr oldLen, IntPtr newp, uint newlen);
static DeviceInfo()
{
var pLen = Marshal.AllocHGlobal(sizeof(int));
sysctlbyname(HardwareSysCtlName, IntPtr.Zero, pLen, IntPtr.Zero, 0);
var length = Marshal.ReadInt32(pLen);
var pStr = Marshal.AllocHGlobal(length);
sysctlbyname(HardwareSysCtlName, pStr, pLen, IntPtr.Zero, 0);
HardwareArch = Marshal.PtrToStringAnsi(pStr);
}
}
Today, I found that this code works not only for Windows(UWP), but also for iOS With Xamarin:
System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString();
With iOS Simulator, RuntimeInformation has more information, like OSArchitecture, but with real iOS device, only ProcessArchitecture was available.
I used all available recent softwares: Xcode 12.4, Visual Studio for Mac 8.9 (1651), etc.

Intptr Handle are not Garbage Collected

Native Window Handles are not garbage collected. So after searching on internet I came to know about SafeProcessHandle below on MSDN article. Tried to implement it but i am receiving 'System.Runtime.InteropServices.SEHException'
https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace TestHandle
{
class Program
{
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
static void Main(string[] args)
{
while (true)
{
IntPtr hWnd = GetForegroundWindow();
int processID = 0;
int threadID = GetWindowThreadProcessId(hWnd, out processID);
using (Process p = Process.GetProcessById(processID))
{
StringBuilder text = new StringBuilder(256);
GetWindowText(hWnd, text, 256);
Console.WriteLine(text.ToString());
}
Console.WriteLine(hWnd);
Thread.Sleep(100);
}
char tmp = 'q';
while (Console.Read() != tmp) ;
}
}
}
In order to obtain currently opened window, I am trying to implement it through Timer and also tried through while loop but it increases memory footprint and if i am designing a long running Console Application which works till PC is running then things are getting worse. Can someone help me on this?
GetForegroundWindow returns a window handle that you do not need to tidy up. The code shown in the question do not leak and has no need for safe handles. You use safe handles when you have a requirement to tidy up unmanaged resources. That is not the case here.
If indeed you do have a problem with a leak, it is not related to the code shown which does not need to be modified.
Update
Regarding your update it is pointless to obtain the process ID and a .net Process object. You don't use them. You can request the window text with the window handle, as indeed you do.
Nothing here suggests a leak of any unmanaged resource and nothing here requires safe handles. If process memory use grows then that would be the normal behaviour for a GC based process. Each time round the loop a new StringBuilder object is created.
The code can be much simpler:
StringBuilder text = new StringBuilder(256);
while (true)
{
IntPtr hWnd = GetForegroundWindow();
GetWindowText(hWnd, text, 256);
Console.WriteLine(text.ToString());
Console.WriteLine(hWnd);
Thread.Sleep(100);
}
Note that I am re-using a single StringBuilder object which will at least prevent steady increase of managed memory use.
You should also check return values of API calls for errors but I don't want to go into the detail of how to do that here.

How do I set the wake up time to system before shutdown the PC?

I am new in C#, I am developing the project at C#.net windows application in that I need to read the next schedule time from my schedule file, if there is no schedule for next one hour, my system need not to wake on until next schedule time reach which is defined in schedule file. My system needs to shutdown, and before shutdown it need to set the timer for system wake. How to set the system on time before shutdown my pc.I did this same in Linux system through python script by writing the system on time at /sys/class/rtc/rtc0/wakealaramlocation. I just write the next system on time at this location and shutdown the system, the system can be automatically on by reach the time which is given in wakealaram file. I need to do the same in Windows system by using C#.
Have a look at below.
#region Clock Reset
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
public short Year;
public short Month;
public short DayOfWeek;
public short Day;
public short Hour;
public short Minute;
public short Second;
public short Milliseconds;
}
[DllImport("kernel32.dll")]
public extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);
private void ResetSystemTime(DateTime tdt)
{
try
{
SYSTEMTIME time = new SYSTEMTIME();
time.Day = (short)tdt.Day;
time.Month = (short)tdt.Month;
time.Year = (short)tdt.Year;
time.Hour = (short)tdt.Hour;
time.Minute = (short)tdt.Minute;
time.Second = (short)tdt.Second;
SetSystemTime(ref time);
}
catch (Exception ex)
{
MessageBox.Show("System time reset Exception: " + ex.Message);
}
}
#endregion

BeforeFeature/AfterFeature does not work using SpecFlow and Coded UI

I am not able to define a [BeforeFeature]/[AfterFeature] hook for my feature file. The application under test is WPF standalone desktop applications.
If I use [BeforeScenario]/[AfterScenario] everything works fine, the application starts without any problem, the designed steps are performed correctly and the app is closed.
Once I use the same steps with [BeforeFeature]/[AfterFeature] tags the application starts and the test fails with:
The following error occurred when this process was started: Object reference not set to an instance of an object.
Here is an example:
[Binding]
public class Setup
{
[BeforeScenario("setup_scenario")]
public static void BeforeAppScenario()
{
UILoader.General.StartApplication();
}
[AfterScenario("setup_scenario")]
public static void AfterAppScenario()
{
UILoader.General.CloseApplication();
}
[BeforeFeature("setup_feature")]
public static void BeforeAppFeature()
{
UILoader.General.StartApplication();
}
[AfterFeature("setup_feature")]
public static void AfterAppFeature()
{
UILoader.General.CloseApplication();
}
}
StartApplication/CloseApplication were recorded and auto-generated with Coded UI Test Builder:
public void StartApplication()
{
// Launch '%ProgramFiles%\...
ApplicationUnderTest Application = ApplicationUnderTest.Launch(this.StartApplicationParams.ExePath, this.StartApplicationParams.AlternateExePath);
}
public class StartApplicationParams
{
public string ExePath = "C:\\Program Files..."
public string AlternateExePath = "%ProgramFiles%\\..."
}
Noteworthy: I'm quite new with SpecFlow.
I can't figure it out why my test fails with [BeforeFeature] and works fine with [BeforeScenario].
It would be great if somebody could help me with this issue. Thanks!
I ran into a similar problem recently. Not sure if this can still help you, but it may be of use for people who stumble upon this question.
For BeforeFeature\AfterFeature to work, the feature itself needs to be tagged, tagging just specific scenarios will not work.
Your feature files should start like this:
#setup_feature
Feature: Name Of Your Feature
#setup_scenario
Scenario: ...

MonoTouch, NSLog, and TestFlightSdk

I am trying to integrate the TestFlightSdk into an app I've made using MonoTouch.
I am trying to implement logging in my app in such a way that it is picked up by the TestFlightSdk. It supposedly picks up NSLogged text automatically, but I can't seem to find the right combination of code to add to my own app, written in C#/MonoTouch, that does the same.
What I've tried:
Console.WriteLine("...");
Debug.WriteLine("..."); (but I think this just calls Console.WriteLine)
Implementing support for NSlog, but this crashed my app so apparently I did something wrong (I'll ask a new question if this is the way to go forward.)
Is there anything built into MonoTouch that will write log messages through NSLog, so that I can use it with TestFlightSdk? Or do I have to roll my own wrapper for NSLog?
In order to implement NSLog myself, I added this:
public static class Logger
{
[DllImport("/System/Library/Frameworks/Foundation.framework/Foundation")]
private extern static void NSLog(string format, string arg1);
public static void Log(string message)
{
NSLog("%s", message);
}
}
(I got pieces of the code above from this other SO question: How to I bind to the iOS Foundations function NSLog.)
But this crashes my app with a SIGSEGV fault.
using System;
using System.Runtime.InteropServices;
using Foundation;
public class Logger
{
[DllImport(ObjCRuntime.Constants.FoundationLibrary)]
private extern static void NSLog(IntPtr message);
public static void Log(string msg, params object[] args)
{
using (var nss = new NSString (string.Format (msg, args))) {
NSLog(nss.Handle);
}
}
}
Anuj pointed the way, and this is what I ended up with:
[DllImport(MonoTouch.Constants.FoundationLibrary)]
private extern static void NSLog(IntPtr format, IntPtr arg1);
and calling it:
using (var format = new NSString("%#"))
using (var arg1 = new NSString(message))
NSLog(format.Handle, arg1.Handle);
When I tried just the single parameter, if I had percentage characters in the string, it was interpreted as an attempt to format the string, but since there was no arguments, it crashed.
Console.WriteLine() works as expected (it redirects to NSLog) on current xamarin.ios versions. Even on release builds (used by hockeyapp, etc). No need to use DllImport anymore.

Resources