Apply the New Vista APIs to Sidebar Gadgets, Part 1

eveloping Windows Vista Sidebar gadgets generally involves a lot of JavaScript programming. To make it possible for Sidebar gadgets to access the various systems’ information, Microsoft has provided a set of APIs that Sidebar gadget developers can use within their Sidebar gadgets, which are callable from JavaScript. This series explores the various gadget objects and how they can be used enhance the functionality of your gadget. They’re grouped based on their functionalities:

  • Contacts
  • Debugging and diagnostics
  • Sidebar gadgets UI
  • Machine information
  • Emails
  • Network
  • Sounds
  • Time and time zones

Part 1 covers the first four functionalities, and Part 2 will cover the last four.

Contacts
To access the contacts information stored in Windows Contacts (Start?>Programs?>Windows Contacts), you can use the following objects:

  • System.ContactManager
  • System.Contact

The System.ContactManager Object
This object exposes a collection of System.Contact objects through its Contacts collection. The following code gets all the contacts (located in C:UsersContacts) and passes it to the contacts variable:

//---get all contacts---var contacts = System.ContactManager.Contacts;

To access each contact individually, you can use its item property (zero-based):

//---get a particular contact (first contact)---var contact = System.ContactManager.Contacts.item(0);

The count property provides the number of contacts retrieved:

//---get a particular contact (first contact)---var count = System.ContactManager.Contacts.count;

The System.Contact Object
This object contains all the details of a contact. The following code shows how to retrieve all the contacts on the local computer and then prints out the details of each individual contact:

 //---get all contacts---   var contacts = System.ContactManager.Contacts;   var result = document.getElementById("result");   result.innerHTML = "";   //---print the details for each contact---   for (i=0; i
"; result.innerHTML += contacts.item(i).city + "
"; result.innerHTML += contacts.item(i).country + "
"; result.innerHTML += contacts.item(i).defaultEmail + "
"; result.innerHTML += contacts.item(i).filePath + "
"; result.innerHTML += contacts.item(i).homePhone + "
"; result.innerHTML += contacts.item(i).mobilePhone + "
"; result.innerHTML += contacts.item(i).POBox + "
"; result.innerHTML += contacts.item(i).postalCode + "
"; result.innerHTML += contacts.item(i).state + "
"; result.innerHTML += contacts.item(i).street + "
"; result.innerHTML += contacts.item(i).workPhone + "
"; }

Debugging and Diagnostics
Microsoft provides the following objects to help developers better debug their Sidebar gadgets:

  • System.Debug
  • System.Diagnostics.EventLog

System.Debug
The System.Debug object provides a means to display debugging information from within your gadget. It has only one method?outputString()?that writes a message to the output window of a debugger.

The following code writes the current time to the debugger window:

   ("Current Date and Time is " + Date());

The user won?t be able to see the debugging string; you have to use a script debugger to see the message. You can use Visual Studio 2005 for this purpose. To attach a debugger to your Sidebar, first invoke the Windows Task Manager by pressing Ctrl+Alt+Delete. Select the Processes tab, and then right-click the sidebar.exe process and select Debug.

A dialog appears, warning you about the potential loss of data. Click Yes to proceed. The Visual Studio Just-In-Time Debugger dialog appears, which enables you to select a debugger for debugging. If you have Visual Studio 2005 installed, it appears in the list of possible debuggers. Select it and click Yes.

The output generated by the outputString() method will appear in the Output window of Visual Studio 2005 (see Figure 1).

The System.Diagnostics.EventLog Object
The System.Diagnostics.EventLog object enables you to write entries in the Event Viewer event log. It has only one method?writeEntry(), which writes an entry into Event Viewer. It has the following signature:

System.Diagnostics.EventLog.writeEntry(strEventLogEntry [, intEventType])
Figure 1. The Output Window: This output is generated by the outputString() method.

The strEventLogEntry parameter takes in a string containing the information to write to the event log. The intEventType parameter specifies the type of event being logged. It can be one of the following values:

  • 0: Success
  • 1: Error
  • 2: Warning
  • 3: Information (default)

The following code example writes four entries in the event log:

 System.Diagnostics.EventLog.writeEntry("Success message", 0); System.Diagnostics.EventLog.writeEntry("Error message", 1); System.Diagnostics.EventLog.writeEntry("Warning message", 2); System.Diagnostics.EventLog.writeEntry("Information message", 3);

To view the entries written to the event log, select Start?>Settings?>Control Panel?>Administrative Tools?>Event Viewer. Choose the Application log to see the newly written entries.

System Information
You can also use Sidebar gadgets to access basic system information?system root, user name, Windows directory, and so on?using the System.Environment object. This object enables you to obtain values of environment variables. It contains one property, machineName, which returns the name of the machine on the current workgroup or network.

The following code shows how to display the name of the machine hosting the Sidebar gadget:

   var result = document.getElementById("result");   result.innerHTML = System.Environment.machineName + "
";

The system.Environment object has only one method?getEnvironmentVariable(), which retrieves the value for an environment variable. Some examples of environment variables are: HOMEPATH, PATH, USERNAME, WINDIR, etc.

You use the getEnvironmentVariable() method to retrieve the value of environment variables, as the following code sample shows:

  var result = document.getElementById("result");result.innerHTML = System.Environment.machineName + "
";result.innerHTML += System.Environment.getEnvironmentVariable("WINDIR") + "
";result.innerHTML += System.Environment.getEnvironmentVariable("USERPROFILE");

Sidebar Gadgets UI
To manipulate the various UI features (flyout, options page, docking and undocking, and so forth) of your Sidebar gadget, use the following objects:

  • System.Gadget
  • System.Gadget.Settings.ClosingEvent
  • System.Gadget.Flyout
  • System.Gadget.Settings

System.Gadget
The System.Gadget object contains various events, methods, and properties that allow you to control the behavior of your Sidebar gadgets.

The code in Listing 1 shows a simple gadget that utilizes all the events and properties of the System.Gadget object. It also has an options page named Settings.html. First, when the gadget is loaded, you print out the various properties of the gadget and set the location of the options page (through the settingsUI property). Next, you assign the event handlers for the onUndock, onDock, onSettingsClosed, and onShowSettings events. Finally, you define the event handlers for these events. And in each of these event handlers, you print a message when each event is fired.

Listing 2 defines the Settings.html page. When the options page is closed, the SettingsClosing() function (as set in the onSetttingsClosing event) will be called to determine the button that was clicked (OK or Cancel).

When the gadget is first loaded (on the left in Figure 2), it displays information about itself, such as name, opacity, path, platform version, and version. When it is undocked (on the right in Figure 2), it displays its docking status.

Figure 2. System.Gadget: The gadget in docked and undocked state.

The System.Gadget.onSettingsClosing event is used in the options page, while the System.Gadget.onSettingsClosed event is used in the main gadget page. By servicing these two events, you can know whether the user has clicked the OK or Cancel button.

When the user clicks the OK or Cancel button on the options page, the SettingsClosing() function is called. You know which button has been clicked though the event parameter. If the user has clicked the OK button, the event.CloseAction property returns 0 (you can also check using the event.Action.commit constant). For example, if the user clicked the Cancel button, you may want to check that certain required fields are entered before the options page can be closed. Likewise, if the OK button is clicked, you may want to validate the input fields before closing the options page.

When the options page is closed, the SettingsClosed() function (in APIs-Gadgets.html) is called, and likewise you can check whether the user has clicked the OK or Cancel button.

The close() method enables you to programmatically close the gadget and remove it from the Sidebar pane. The following example shows that a gadget will be closed five seconds after it has been loaded:

function load()      {           setTimeout(close, 5000);      }      function close()      {         System.Gadget.close();      }

If your gadget’s UI is constantly updated, you might want to use beginTransition() and endTransition() methods to temporarily suspend all visual updates until all the changes are made:

        System.Gadget.beginTransition();        //...        //---perform all your UI updates here---                          //...        System.Gadget.endTransition(           System.Gadget.TransitionType.none, 2);

The first argument of the endTransition() method can be one of the following:

  • System.Gadget.TransitionType.morph
  • System.Gadget.TransitionType.none

The second parameter is the amount of time in seconds to perform the transition.

System.Gadget.Settings.ClosingEvent
The System.Gadget.Settings.ClosingEvent object provides the status of the options page and gives you the capability to prevent an options page from closing. In the previous section, you saw that the System.Gadget.onSettingsClosing event is fired on the options page when the options page is closing, while the System.Gadget.onSettingsClosed event is fired on the main gadget page when the options page has closed. The event handlers for these two events have an event parameter of type System.Gadget.Settings.ClosingEvent. Using this parameter, you can know whether the user has clicked OK or Cancel:

      //---in the gadget's main page---      //---when the settings page has closed---      function SettingsClosed(event)      {         if (event.closeAction == event.Action.commit) {            DisplayValue("User clicked OK");                }         else {            DisplayValue("User clicked Cancel");                 }      }

The Action property has two enumerations: commit and cancel.

To make sure that the options page does not close until some criteria are satisfied, you can use the System.Gadget.Settings.ClosingEvent.cancel property in the System.Gadget.onSettingsClosing event handler (in the options page), like this:

      //---in the options page---      function SettingsClosing(event)      {         if ((some_condition) && (!event.cancellable)) {            //---prevent the options page from closing---            event.cancel=true;         }      }

The cancel property gives you the capability to cancel the closing of the options page (that is, to prevent the options page from closing). This capability is useful if some criteria are not met, such as users not supplying the expected inputs. In that case, they won’t be able to close the options page until they have given the required input.

The cancellable property (read-only) returns a value indicating if the user can successfully close the options page.

System.Gadget.Flyout
The System.Gadget.Flyout object enables you to implement a flyout for your Sidebar gadget. The gadget in Listing 3 contains a button that shows a flyout page when it is clicked. You first set the name of the flyout file using the file property. To make the flyout appear, set the show property to true. Then, set the onHide and onShow events to the two event handlers, FlyoutHidden and FlyoutOnShow. When the flyout is shown, you will display a string indicating that the flyout is shown. When the flyout closes, you will display the name entered in the flyout. Figure 3 shows the flyout.

Figure 3. Flyout: Displaying the flyout of the gadget.

The flyout page (see Listing 4) provides a textbox for entering a name. Clicking the Done button closes the flyout page by setting the show property to false.

When the user clicks the Done button the flyout closes and the name entered in the flyout is displayed in the gadget, which is achieved using the System.Gadget.Flyout.document.getElementById() method.

System.Gadget.Settings
The System.Gadget.Settings object enables you to save setting values specific to each Sidebar gadget. The following code example shows how you can save and read values using each of the four methods:

System.Gadget.Settings.write ("age", 30);System.Gadget.Settings.write ("PI_1", 3.142857142857142857142);System.Gadget.Settings.writeString ("PI_2",    "3.142857142857142857142");System.Gadget.Settings.write ("firstname", "John");System.Gadget.Settings.writeString ("lastname", "Smith");var result = document.getElementById("result");result.innerHTML = System.Gadget.Settings.readString("age") + "
";result.innerHTML += System.Gadget.Settings.read("PI_1") + "
";result.innerHTML += System.Gadget.Settings.readString("PI_1") + "
";result.innerHTML += System.Gadget.Settings.read("PI_2") + "
";result.innerHTML += System.Gadget.Settings.readString("PI_2") + "
";result.innerHTML += System.Gadget.Settings.read("firstname") + "
";result.innerHTML += System.Gadget.Settings.readString("lastname") + "
";

The outputs from the code are as follows:

303.14285714285714 (PI_1)3.14285714285714 (PI_1)3.142857142857143 (PI_2)3.142857142857142857142 (PI_2)JohnSmith

What is interesting is that when you try to save the value of PI using the write() method, it will attempt to guess the data type of the data to be saved and some rounding or truncation may occur inadvertently (depending on the precision of the number to be saved). In this case, the value of PI_1 will be truncated when it is saved, and that can be seen when you read the value of PI_1 using the read() and readString() methods. For PI_2, it is saved using the writeString() method, which writes the value as a string without trying to convert it to a numeric type. Notice that when you use the read() method to try to read the value of PI_2, there is a loss of precision because read() tries to guess the datatype it is reading. If you use the readString() method, the value of PI_2 will be retrieved correctly.

In general, use the writeString() and readString() methods when manipulating numeric values.

Machine Information
You can obtain detailed information about the processors and power status on your system with the following objects:

  • System.Machine
  • System.Machine.CPU
  • System.Machine.PowerStatus

System.Machine.CPU and System.Machine
The System.Machine.CPU object contains information about the CPU of the computer running the gadget. The System.Machine object exposes a collection of System.Machine.CPU objects through its System.Machine.CPUs collection.

The following code example displays the detailed information of the current machine hosting the gadget and then displays the name and usage percentage for each CPU (in a multicore processor).

         var result = document.getElementById("result");         result.innerHTML = "Available Memory: " +            System.Machine.availableMemory + "MB
"; result.innerHTML += "Total Memory: " + System.Machine.totalMemory + "MB
"; result.innerHTML += "Processor Architecture: " + System.Machine.processorArchitecture + "
"; //---get all CPUs--- var cpus = System.Machine.CPUs; //---display name and usage of each CPU--- for (i=0; i
"; result.innerHTML += cpus.item(i).usagePercentage + "
"; } cpus = null; result = null;

Figure 4 shows the result when the gadget is run on my computer.

Figure 4. Running the Gadget: Displaying the detailed information of a system.

System.Machine.PowerStatus
The System.Machine.PowerStatus object returns detailed information about the power status of the computer hosting the gadget.

The System.Machine.PowerStatus object has one event, powerLineStatusChanged, which specifies a function that is called whenever the system is switched from adapter power to battery power, or vice versa.

The gadget in Listing 5 shows the detailed power status of your computer. When the page is loaded, you first print out the power status of your computer. You then set the powerLineStatusChanged event to the PowerLineStatusChanged event handler so that this event handler will be called whenever there is a change in power status (such as when you switch from battery power to adapter power, and vice versa).

The PowerLineStatusChanged() function is fired whenever there is a change in power status (such as the notebook computer is connected to a power source).

This article has examined the first four objects exposed by Windows Sidebar. Stay tuned for Part 2, which will discuss the email, network, sound, and time and time zone objects.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may