Ping remote host in Javascript using WMI
I’ve been working on a simple Windows Sidebar Gadget that will determine if a remote host is online or not. For the connectivity test I chose ping, since it’s lightweight and unlikely to disturb any services on a device.
Ping using WMI
function Ping(host) { var wmi = GetObject("Winmgmts:"); var eStatus = new Enumerator(wmi.ExecQuery( "Select StatusCode from Win32_PingStatus Where Address='" + host + "'")); return eStatus.item().StatusCode == 0; }
The function Ping will return true if the host is online, false otherwise. Optionally, a Timeout parameter may be specified in the WMI query.
Faster Windows Gadget development & testing
Testing and debugging of Windows Sidebar Gadgets may be painful if you wish to test or debug a gadget that has a configuration. Removing and re-creating a gadget by dragging it out of the Gadget window will delete any saved configuration. I’ve found that I would like to restart the sidebar and refresh all the gadgets at once. Restarting the Sidebar process is also the only way to flush the image cache. If you’re having caching problems, restarting the Sidebar will reload the data from disk.
To restart the sidebar with just a click – create the following batch file:
taskkill /F /IM sidebar.exe && "c:\Program Files\Windows Sidebar\sidebar.exe"
Save the file as restart_sidebar.bat. Elevation is not required to restart the sidebar.
C#: Don’t display the startup form.
Something that often seems to be a problem with beginning C# developers is the display of the initial form. Normally one would always want the startup form to be displayed as soon as possible–but sometimes the application lives in the tray, or should not initially display a window.
One may first think that an event in System.Windows.Forms.Form can be handled, and the form may be directed to Hide. Unfortunately, this won’t work as expected, the Form will always get the SW_SHOW message when Application.Run() is executed.
When creating a new project, Visual Studio will generate a Program.cs which looks similar to the following:
namespace CamOn { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
When Application.Run is invoked with a Form parameter, it will create and show the window. The easiest way to override this behavior is to simply not call Application.Run with the form:
namespace CamOn { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); new Form1(); Application.Run(); } } }
Form1 will still be created and pump messages – but it won’t initially be shown.
Reading Motion-JPEG camera streams
I’ve recently come across a Hawking HNC230G network camera, which shares internals with the Edimax IC-1500Wg. These cameras pump out a Motion-JPEG stream which is unlike many other “Motion-JPEG” IP cameras.
Many of these devices will create video with a constantly updating jpeg file, served via HTTP. This is generally a better solution than what exists in my camera. Reading these streams is simple in many languages. The HNC230G took a little more probing and experimentation before I could read data without artifacts.
Camera Services
HTTP Administration website – Port 80
Motion-JPEG stream – Port 4321
There does not appear to be any images on the HTTP administration website. All video data passes through the service on 4321. Video data is not encrypted or secured in any way – there is no authentication.
Finished Protocol
After a socket is connected to the service on 4321, it should send the single command which is supported: 0110\n. Sending 0110 followed by a linebreak will signal the device to send a JFIF frame.
The camera will send 4 bytes of data before the JFIF header, these bytes can be interpreted as follows:
- Byte 1: High 8 bits of the frame size
- Byte 2: Low 8 bits of the frame size
- Byte 3: Active users on the camera
- Byte 4: Unknown reserved byte
The size of the frame is calculated only after the 4-byte header. The process can be repeated once the frame has been received by the client. The image data received will contain a JFIF (JPEG File Interchange Format) frame.
I’ve been able to achieve approximately 10fps at 640×480 with this method.
Limitations
The key limitations with this method relate to the firmware design for this camera.
- Image size can only be set through the HTTP web service.
- LED state can only be queried or set through the HTTP web service.
- The device will sometimes disconnect the client or return invalid data. This is solved by reconnecting the client.
- As the number of users increase, the possible frames-per-second decreases. Frame rates are 25-50% less when adding a second user.
Sample C# Code
public byte[] GetFrame() { if (!conn.Connected) { Connect(); if (!conn.Connected) { throw new Exception("Cannot fetch frame from camera. Not Connected."); } } StreamWriter sw = new StreamWriter(conn.GetStream()); // request a frame sw.WriteLine("0110"); sw.Flush(); // get the high 8bits of the size int size = conn.GetStream().ReadByte() << 8; // get the low 8bits of the size size += conn.GetStream().ReadByte(); // active users int j1 = conn.GetStream().ReadByte(); ActiveUsers = j1; // unknown byte int j2 = conn.GetStream().ReadByte(); if (size == 0) { return null; } return new BinaryReader(conn.GetStream()).ReadBytes(size); }
Get to your Windows desktop faster – secure automatic logon.
The common advice for automatically locking the computer after logging in is to create a batch file and add it to the startup folder. Unfortunately the experience isn’t very elegant, or secure. The desktop and shell will appear while applications are loading, long before the computer will lock itself. The possibility exists for someone to tamper with the computer while it is in this intermediate loading state.
A solution to this problem is to lock the computer sooner in the logon process. There are several good places within the logon process to put a task, but the one that may execute the soonest is certainly Userinit. Userinit is the first program which is executed after logon.
From MSDN: http://msdn.microsoft.com/en-us/library/aa378750(VS.85).aspx
Userinit.exe is an application that is executed when the user has logged on. It runs in the newly logged-on user’s context and on the application desktop. Its purpose is to set up the user’s environment, including restoring network uses, establishing profile settings such as fonts and screen colors, and running logon scripts. After completing those tasks, Userinit.exe executes the user shell programs. The shell programs inherit the environment that Userinit.exe sets up. The specific shell programs that Userinit.exe executes are stored in the Shell key value under the Winlogon registry key.
Add the lock command to Userinit
Create a batch file that will lock the computer:
rundll32.exe user32.dll,LockWorkStation
Name the file lock.bat and place it in the System Root. (c:\windows\system32).
Open regedit and navigate to:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon
The registry value Userinit should contain the path to Userinit.exe
C:\Windows\system32\userinit.exe
Change the value to contain the lock batch file before the Userinit.exe, with a comma between.
C:\Windows\System32\lock.bat, C:\Windows\system32\userinit.exe
Log off to see the result. Note that using a batch file does not discriminate between automatic logon, and user-initiated logon. One could write a program that would only call LockWorkStation if the computer was up for less than 10 minutes.
To enable automatic logon
If automatic logon isn’t already enabled, execute control userpasswords2 at the Run prompt, and uncheck Users must enter a username and password to use this computer.

