Vista Sidebar Gadgets: A Developer SearchBox

Create Sidebar Gadgets for Windows Vista — and End Up with a Convenient Tool for Finding Software Development Answers onthe Web

Steve C Orr

October 30, 2009

14 Min Read
ITPro Today logo

ControlFreak

LANGUAGES:HTML | JavaScript

 

Vista Sidebar Gadgets:
A Developer SearchBox

Create Sidebar Gadgets for Windows Vista and End Up with a Convenient Tool for Finding Software Development Answers onthe Web

 

By Steve C. Orr

 

This article will introduce you to the Windows VistaSidebar and show you how to create your own Sidebar gadgets. We ll discuss thecomponents that make up a Sidebar gadget, discuss capabilities and securitylimitations, and explain packaging and deployment. This will all be done bywalking through the creation of a useful Developer SearchBox gadget that letsyou search the Web (or specific software development Web sites) for the contentof your choosing. You ll be able to use this gadget from the convenience ofyour own Vista desktop to ease future development tasks.

 

What Is the Windows Vista Sidebar?

The Windows Vista Sidebar can host a variety of fun anduseful little gadgets, right on your desktop. This configurable area cancontain clocks, calendars, resource meters, RSS feeds, stock quotes, weather andtraffic reports, and virtually anything else you can think of. Windows Vistacomes with more than a dozen such gadgets built-in, and hundreds more areavailable for download on the Internet and most of them are free.

 

After downloading a gadget file, simply double click it toinstall it. Once installed, it will then be visible in your list of availablegadgets. To view the list of available gadgets and pick which ones you want toappear in your Sidebar, simply click the plus sign at the top of your Sidebar(as shown in Figure 1) and choose the gadgets you find to be most useful orinteresting. If you choose more gadgets than can fit on your screen at onetime, they will span across multiple columns. Only one column of gadgets canappear on screen at a time, although you can scroll through each column byclicking the arrow buttons at the top of the Sidebar next to the plus sign, asshown in Figure 1. To remove a gadget from your Sidebar, hover the mouse overit and click the X that appears next to it.

 


Figure 1: The Windows Vista Sidebarcan be configured via the buttons at the top of the Sidebar to add gadgets andscroll through multiple columns of gadgets.

 

Some people may liken the Sidebar to the old ActiveDesktop feature that was available in the Windows 98 days. While there aresome similarities, I d have to say that the Vista Sidebar is far more stable andfar less intrusive. You should have a decent amount of RAM in your system ifyou plan to use many gadgets; I d suggest 2 gigabytes. Of course, if you reusing Visual Studio on Windows Vista then you ve probably already found youneed that much RAM to run at a good speed anyway gadgets or not.

 

Once added to your Sidebar, the Developer SearchBox gadgetis never more than a click away. (Simply click on the Windows Sidebar icon inthe notification section on the right side of your Taskbar.)

 

Start by entering a search phrase into the textbox shownat the top of Figure 2. From the dropdown list below that you can choose tosearch the entire Web for the phrase you ve entered, or you can choose tosearch a specific Web site. This list is pre-populated with 30 of the bestsoftware development sites available on the Web, including MSDN and http://www.aspnetPRO.com.

 

You can also choose which search engine to use, such asGoogle or Microsoft. Once you ve made your selections, simply hit the Enter keyor click the Search button and a browser window will open displaying theresults of your search.

 


Figure 2: The Developer SearchBoxgadget allows you to search a specific site or the entire Web for softwaredevelopment answers.

 

Like many Sidebar gadgets, the Developer SearchBox canhave its options configured by clicking on the little magnifying glass iconthat appears on the right when the mouse is hovering over the gadget (ashighlighted in Figure 2). In the case of the Developer SearchBox, this allowsyou to choose a color scheme that aesthetically matches your personal taste.

 

While Sidebar gadgets are primarily HTML and JavaScriptbased, they do not run with the same security restrictions as Web sites. Infact, gadgets have many additional capabilities, including access to many localsystem resources. While Sidebar gadgets are installed on the local machine shard drive (similar to a Windows application), they do not run with the samesecurity restrictions as a Windows application, either. Instead, Sidebargadgets have somewhat unique capabilities and restrictions.

 

In addition to the capabilities of Internet Explorer andJavaScript, Sidebar gadgets have a special object model all their own. Thisscripting object model includes access to local machine information, such asCPU details, environment variables, recycle bin properties, time-zoneinformation, wireless status, and laptop battery status. It also includesaccess to local data stores, such as messages, contacts, and access to thelocal hard drive. Additionally, sounds can be played, such as system sounds andother custom sound files. Functions also exist for setting background images,rotating images, blurring, shadows, and other special effects. There are alsoquite a few functions that are helpful for debugging, such as write-only accessto the event log and console output. Finally, there is the ability to launchURLs, open local files, and launch local executables. (The full Windows Sidebarobject model documentation reference is located at http://msdn2.microsoft.com/en-us/library/aa965853.aspx.)

 

Aside from this rather liberal list of capabilities,Sidebar gadgets are not permitted access to many other significant functions except one: The ability to use locally installed ActiveX controls, which allowsaccess to media player and Microsoft Office components, and access to Webservices (via the XmlHttp ActiveX object), just to name a few. In fact,multiple Web services may even be called across multiple domains, thus openingmany creative mash-up possibilities.

 

In case those aren t enough, you could always instantiateyour own custom ActiveX controls if you can figure out a way to deploy them. Gadgetswon t be any help in downloading, deploying, or registering ActiveX controls asthey don t have permission for such functions. On the bright side, if you canmitigate that matter, you can easily use your favorite .NET language to developsuch ActiveX controls without issue by exposing a COM wrapper around yourcustom .NET component. Using such a .NET-based ActiveX control within astandard Web application would likely raise concerns about browser support and.NET Framework deployment, but there is no need to worry about those issues asSidebar components are targeted to Windows Vista and above, which has modernversions of Internet Explorer and the .NET Framework installed by default.

 

Microsoft recommends Sidebar gadgets be no wider than 130pixels (so each fits nicely within the Vista Sidebar), although thisrestriction is not currently enforced. If you need extra space, flyout areascan be used and Sidebar gadgets can be dragged onto the main desktop wheresize is really no longer an issue. However, don t even think about trying toopen new windows; I m happy to say that focus-stealing popup annoyances such asthe JavaScript alert function are squelched.

 

What exactly makes up a Sidebar gadget? A minimal sidebargadget requires at least two files. The Sidebar Gadget manifest file must benamed gadget.xml. This XML file contains information about the gadget, such asits name, version number, description, etc.

 

The other required file is an HTML file that acts as themain user interface for the gadget. The name of this file is configurable, andmust be specified inside the gadget.xml file.

 

Other common, optional files may include an icon file, CSSfiles, JavaScript files, VBScript files, media files, and other helper HTMLfiles.

 

The Developer SearchBox manifest file (gadget.xml) islisted in Figure 3. The contents should be mostly self explanatory, and mostitems are not very critical. Be sure to fill in the name element with thegadget title that you d like to appear to your users when they re choosingwhich gadgets they want in their Sidebar using the standard dialog box (shownin Figure 4). Also, be sure to fill in the src element with the name of themain HTML file that will act as the user interface for your gadget.

 

   Search Box    whatever    1.0.0.0                    ©2007    DeveloperSearch Box                                          src="SearchBox.html" />            Full                        Figure 3: EverySidebar gadget requires a manifest file named gadget.xml, as shown here for theDeveloper SearchBox gadget.  
Figure 4: The manifest file(gadget.xml) is used to specify many of the details that show up in thestandard Windows Vista gadget selection dialog box shown here.   The main HTML file for the Developer SearchBox gadget isnamed SearchBox.html. This standard HTML file contains a textbox, two dropdownlists, and a button, as shown in Figure 5. It also contains a JavaScript filereference, which holds the business logic, and a CSS file reference to prettythings up.              rel="stylesheet" type="text/css" />        language="javascript">                        Search For:            
                               size="16" style="color: Blue;"            onkeyup="KeyCheck(event.keyCode);" />                            Search Site:
                      onkeyup="KeyCheck(event.keyCode);">                TheWeb                Adobe.com                ASP.NETAJAX                AspAlliance                aspnetPRO.com      ...                                        Search Engine:
                           onkeyup="KeyCheck(event.keyCode);">                Microsoft                Google                                                        name="btnSearch" id="btnSearch"                onclick="DoSearch();" value="Search!"                disabled="disabled" class="searchbutton"            />             Figure 5: TheDeveloper SearchBox gadget s user interface is defined by this fairly simpleand standard HTML file.   When the user clicks on the Search button to execute theirsearch, the custom DoSearch JavaScript function listed in Figure 6 is invoked,as specified by the button s onclick event.  function DoSearch(){ var URL = "";  var SiteName =ddlSite.options[ddlSite.selectedIndex].text;  SiteName =SiteName.toLowerCase(); var Eng =ddlEngine.options[ddlEngine.selectedIndex].text;  if (Eng =="Microsoft")  {      //Do Microsoft Search     URL = "http://search.msn.com/results.aspx?q=";  }  else {      //Do Google Search     URL ="http://www.google.com/search?hl=en&q=";  }  URL = URL +escape(q.value);    if (SiteName != "theweb")  {       //Search a specificweb site     URL = URL + " site:";      URL = URL +GetSiteURL(SiteName);  }  System.Shell.execute(URL); //execute the search}Figure 6: ThisDoSearch JavaScript function contains the Developer SearchBox s primarybusiness logic. It concatenates a custom URL based on the user s input, whichexecutes a search on either Google s or Microsoft s search engine.   The DoSearch function contains the Developer SearchBox smain business logic. It collects the user s input and uses it to construct aURL that s compatible with either Microsoft s or Google s search engine. Thefinal line launches that URL using the special gadget object model sSystem.Shell.execute method.  Displaying, Configuring, and Storing Custom User Settings Gadgets that have configurable options can allow users tochange those options by clicking on the little magnifying glass that appears onthe right side of the gadget when the mouse hovers overhead, as shown in Figure7.  
Figure 7: The Developer SearchBoxgadget allows users to adjust its color scheme by clicking on the standardmagnifying glass icon located on the right side of the gadget when the mousehovers overhead.   If you d like to provide a user interface that allows theuser to change custom options for your Sidebar gadget, the HTML file thatcontains this user interface should be specified using a line of JavaScriptsuch as this:  System.Gadget.settingsUI = "settings.html";   You should also specify the JavaScript function you wantto be called when the user has completed their adjustments (so you can applytheir changes immediately). That is done with a line of JavaScript such asthis:  System.Gadget.onSettingsClosed = settingsClosed;   It only takes a single line of code to load or save asingle custom setting. To load and save custom settings, respectively, useJavaScript lines such as these:  var Color =System.Gadget.Settings.read("CustomColor1"); System.Gadget.Settings.write("CustomColor1", Color);   Normally you d want to read in any custom settings fromthe onload event of your HTML files. For example, you d probably want to dothis both for the onload event of the main gadget HTML file and also the customsettings HTML file, so they can each display the user s custom settingsappropriately. If the read method returns an empty string then the customsetting hasn t been specified by the user yet (as is essentially null), so youshould probably use a default value of some kind under this condition.   A custom settings HTML file should generally contain codesuch as this to ensure an OK button appears on the form and that the user scustom selections are saved when it is clicked:  //Wire up the eventSystem.Gadget.onSettingsClosing = settingsClosing; function settingsClosing(event) { if (event.closeAction ==event.Action.commit)  {    var clr =ddlColor.options[ddlColor.selectedIndex].text;    System.Gadget.Settings.write("CustomColor", clr);  } }   The first line ensures an OK button will appear and thatthe settingsClosing function is called in response to its click event. ThesettingsClosing event (not to be confused with the settingsClosed event in themain HTML file) then stores the user s customizations only if the OK button wasclicked and not if the Cancel button was clicked. Once all this finishesexecuting, the settingsClosed function in the main HTML file is called (if it sbeen wired up as previously instructed) so that the user s customizations canbe immediately applied from there.   Multiple occurrences of a gadget can be placed in a user sSidebar. For example, a frequent traveler might choose to place several clocksin their Sidebar, each configured to a different time zone. Custom settings areautomatically associated with each specific occurrence of a gadget, so you don tneed to worry about naming conflicts with other gadget occurrences when savingsettings. Whenever Windows restarts, each gadget occurrence automatically loadsits stored settings just as they were before Windows was shut down. However, ifa user deletes a gadget occurrence from their sidebar, its settings will belost. A user may add a new occurrence of the gadget back to their Sidebar, butit will start with default settings. This could be confusing and frustrating tonovice users, especially if they spent a lot of time configuring customsettings that now might seem to have vanished. For this reason I suggestkeeping custom settings few and simple and easy for users to reset.  Packaging/Deploying a Gadget Packaging a gadget to prepare it for deployment couldhardly be any easier. Simply zip up the manifest file (gadget.xml) along withall HTML files and any other support files the gadget may need. Then change thefile s extension from zip to gadget . That s it. Optional steps areavailable, such as signing the gadget file, but this is not required. When auser downloads the gadget file and double clicks it, it will be immediatelyinstalled and available for placement into their Sidebar. Conversely, if youdownload a gadget file, you can change its file extension from gadget to zip and then unzip it like any other compressed file to examine its contents. Incase you re curious, downloaded Sidebar gadgets are installed in the followingfolder by default:   %userprofile%AppDataLocalMicrosoftWindowsSidebarGadgets   It can be convenient to develop sidebar gadgets directlyin this folder, so you don t have to reinstall between each edit.   The gadgets that come with Windows Vista are stored here:   %programfiles%Windows SidebarGadgets   Examining their source code can be a great way to learnadvanced gadget creation tricks.  Conclusion Windows Vista Sidebar gadgets can be fun to play with andproductive to use. They re also rather fun to develop as they essentially are anentirely new kind of software application, yet they re based on familiartechnologies that are easy to grasp for any experienced Web developer.   I encourage you to play with the gadgets that come withWindows Vista and explore the many novel gadgets available on the Web. I alsoencourage you to dissect them to help you learn techniques for your own gadgetdevelopment. And don t forget to download the Developer SearchBox gadget thataccompanies this article so you can dissect it and use it to quickly findanswers to your future development questions.   The full source codefor the Developer SearchBox gadget is available for download.  Steve C. Orr is an ASPInsider, MCSD, Certified ScrumMaster,Microsoft MVP in ASP.NET, and author of the book BeginningASP.NET 2.0 AJAXby Wrox. He s been developing software solutions for leading companies in the Seattlearea for more than a decade. When he s not busy designing software systems orwriting about them, he can often be found loitering at local user groups andhabitually lurking in the ASP.NET newsgroup. Find out more about him at http://SteveOrr.net or e-mail him at mailto:[email protected].      

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like