Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

Building a Windows Vista Email Gadget using the .NET Framework

 



The E-mail Alert Gadget is a simple yet indispensible Gadget for the Windows Sidebar platform. It provides users with a dynamic unread e-mail counter in the Windows Sidebar. By leveraging the convenience and functionality of Windows Sidebar and the power of .NET Framework applications, E-mail Alert is able to provide users with quick access to a useful piece of information: the number of unread e-mails in the user's inbox.
SharpLogic Software

Difficulty: Easy
Time Required: 1-3 hours
Cost: Free
Software: Tested on Windows Vista Beta 2 (Build 5384), Visual Basic or Visual C# Express Editions, Visual Web Developer Express for JavaScript editing.
Hardware: None
Download: Download

 

  

Windows Sidebar

Windows Sidebar is an application host of sorts that enables you to host customizable mini-applications or “Gadgets” to boost your personal productivity. Windows Sidebar is supported on both Windows XP* and Windows Vista. Figure 1 shows a Sidebar with three Gadgets: a clock, a stock ticker, and a CPU and memory gauge.

* Sidebar is not supported in Windows XP (thank you to alert C4F reader Tom Sage for pointing this out) 

Figure 1: Windows Sidebar.

Windows Sidebar Gadgets

Windows Sidebar Gadgets consist of, at the least, an HTML file containing the Gadget, an XML file describing the Gadget, and an icon for the Gadget. More functionality can be added through JavaScript and additional HTML. Moreover, the Windows Sidebar API provides additional namespaces and functionality programmable through either VBScript or JavaScript for more dynamic Gadget functionality. In fact, using only JavaScript a Gadget can access the hard drive, check power and network status, read and write environment variables, and even communicate with Windows SideShow information appliances, and more.

E-mail Alert Gadget

The E-mail Alert is a Gadget for Windows Sidebar that provides Microsoft Office Outlook and MSN Messenger users an at-a-glance count of the unread e-mails in their Outlook or Hotmail inbox. E-mail Alert also provides links that enable users to quickly access the inbox or compose a new message with the default e-mail application.

Like other Gadgets, E-mail Alert has been built with HTML and JavaScript. E-mail Alert can either be docked in the Sidebar or float on the Windows desktop. Unlike other Gadgets, the E-mail Alert Gadget shows how you can interoperate with a .NET external application so that you can harness the power of .NET applications in your Gadget.

Figure 2: E-mail Alert Gadget.

Connecting a Gadget to a .NET application

Although it is generally recommended that Gadgets perform all of their logic in JavaScript whenever possible, there are occasionally times when it is beneficial to leverage external applications and scripts. In this sample we have opted to use the more complex external application model in order to illustrate a simple solution to connect a Gadget to a .NET application. In the case of the E-mail Alert Gadget, the GetUnreadEmailCount application retrieves the user's current unread e-mail count. The application can then return output to the Gadget, which displays it to the user in the Sidebar.

Figure 3: Gadget execution.

E-mail Alert Gadget Files

The simplest Gadget consists of a single XML file describing the Gadget, an HTML file containing the entire Gadget, and a single PNG icon image for the Gadget. In order to incorporate more advanced functionality and design, a Gadget can also incorporate JavaScript, CSS, JScript, VBScript, or external executables.

 

Gadget.xml

Gadget.xml is the Gadget manifest, an XML file defining the Gadget's properties, including name, author, and description:

<name>E-mail Alert</name> 

<author>Microsoft Corporation</author> 

<copyright>Microsoft 1985-2006</copyright> 

<description>Keep up with new e-mail as you receive it.</description> 

The information in the manifest is displayed to users when they are browsing available Gadgets through Windows Sidebar. The manifest also informs the Sidebar about which HTML file in the Gadget package contains the body of the Gadget, and contains information about icons to use for the Gadget.

Email.html

Email.html is the main body of the E-mail Alert Gadget. Essentially, a Gadget is a collection of HTML and JavaScript that is displayed in the Windows Sidebar. Email.html contains a link to a CSS file that provides style information for the Gadget. It also includes a link to Email.js, a JavaScript file that is responsible for the functionality of the Gadget.

Email.js

Email.js is a JavaScript file that contains the main functionality of the E-mail Alert Gadget. When the Gadget first loads, Email.js constructs a WScript Shell object. The WScript Shell object enables access to system information, environment variables, and the Windows Registry. Email.js uses this object to search the registry to determine the user's e-mail client in the SetMailClientPath method:

 
/// <summary>
/// Determine the name and path of the user's e-mail client.
/// </summary>

function SetMailClientPath()
{
    // The name of the mail client should be the default
    // value for the mail count registry key. Retrieve it
    // using the WScript shell.

    try
    {
        _MailClientName = _WshShell.RegRead("HKCU" +
          _MailCountRegistryPath);
    }
    catch (e)
    {
        // There is no mail client setting for this user,
        // fall back to the system default in HKLM.
        _MailClientName = _WshShell.RegRead("HKLM" +
          _MailCountRegistryPath);
    }
    // Retrieve the path to the mail client using the
    // WScript shell.
    try
    {
        _MailClientPath = _WshShell.RegRead("HKCU" +
          _MailCountRegistryPath + _MailClientName +
          "\\shell\\open\\command\\");
    }
    catch (e)
    {
        // There is no mail client path setting for this
        // user, fall back to the system default in HKLM.
        _MailClientPath = _WshShell.RegRead("HKLM" +
          _MailCountRegistryPath + _MailClientName +
          "\\shell\\open\\command\\");
    } 
}
 

After determining the name and path of the user's e-mail client, Email.js enables a timer with an interval of 30 seconds. When the timer fires, Email.js executes the GetUnreadEmailCount .NET application, passing the user's e-mail client preference as a command-line argument. Finally, Email.js reads the number of unread e-mails from the standard output stream of the GetUnreadEmailCount application and updates the E-mail Alert Gadget's display:

 
/// <summary>
/// Retrieve the unread mail count from the GetUnreadMailCount application.
/// </summary>
function RefreshEmail()
{
    try
    {
        // Stop the timer while we're retrieving data.
        ClearRefreshIntervals();
    
        // Run the GetUnreadMailCount application using the
        // WScript shell.
        exec = _WshShell.Exec("\"" +
            window.external.System.Shell.GadgetPath +
            "\\" + _MailCountApplicationName + "\" \"" +
            _MailClientName + "\"");
            
        // Grab the unread count from the standard output
        // stream of GetUnreadMailCount.
        _UnreadEmailCount = exec.StdOut.ReadAll();
      
        // Update the Gadget UI.
        UpdateView();
        
        // Restart the timer.
        SetRefreshIntervals();     
    }
    catch (e)
    {
        // An error occurred, display it and restart the
        // timer.
        DisplayErrorMessage(_errEmailErrorText);
        SetRefreshIntervals();
    }

}

GetUnreadEmailCount

The GetUnreadEmailCount .NET application is a simple application that accepts an e-mail client name as a command-line argument and determines the number of unread e-mails for that e-mail client. Currently, GetUnreadEmailCount supports Microsoft Office Outlook and Windows Live Messenger (MSN Messenger). When GetUnreadEmailCount does not recognize the requested e-mail client, it defaults to the unread e-mail count provided by the HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\UnreadMail registry key.

Integration with Microsoft Office Outlook is achieved through the Microsoft Outlook 11.0 Object Library (the Outlook 11 Primary Interop Assembly), accessible through the Microsoft.Office.Interop.Outlook namespace. GetUnreadEmailCount includes a shared function (static method) that retrieves the number of unread e-mails in the user's Microsoft Office Outlook by using the Messaging API (MAPI) support built into the Microsoft Outlook 11.0 library:

Visual Basic

''' <summary>
''' Gets the number of unread messages in the user's Microsoft Office Outlook
''' inbox.
''' </summary>
''' <returns>
''' Returns the number of unread messages in the user's
''' inbox.
''' </returns>
''' <remarks></remarks>
Private Shared Function GetOutlookUnreadCount() As Integer
     ' Create a new reference to Office Outlook using
     ' Messaging API (MAPI).
     Dim outlookApplication As New Application()
     Dim outlookMapi As _NameSpace = _
          outlookApplication.GetNamespace("MAPI")

     ' Logon to the user's Office Outlook inbox using MAPI
     ' and default settings.

     outlookMapi.Logon(Nothing, Nothing, True, False)

     ' Get and return the unread e-mail count from the
     ' user's Office Outlook inbox.

     Return _
          outlookMapi.GetDefaultFolder( _
          OlDefaultFolders.olFolderInbox).UnReadItemCount
End Function

C#

/// <summary>
/// Gets the number of unread messages in the user's Microsoft Office Outlook
/// inbox.
/// </summary>
/// <returns>
/// Returns the number of unread messages in the user's inbox.
/// </returns>
private static int GetOutlookUnreadCount()
{
     // Create a new reference to Office Outlook using
     // Messaging API (MAPI).
     Application outlookApplication = new Application();
     _NameSpace outlookMapi = outlookApplication
          .GetNamespace("MAPI");

     // Logon to the user's Office Outlook inbox using MAPI    // and default settings.
     outlookMapi.Logon(null, null, true, false);

     // Get and return the unread e-mail count from the   // user's Office Outlook inbox.
     Return outlookMapi.GetDefaultFolder(
          OlDefaultFolders.olFolderInbox).UnReadItemCount;
}

For Windows Live Messenger, as well as for unrecognized e-mail clients, GetUnreadEmailCount falls back to the UnreadMail key in the registry. It accesses this using the Microsoft.Win32 namespace:

Visual Basic

''' <summary>
''' Gets the number of unread messages listed in the user's registry.
''' </summary>
''' <returns>
''' Returns the number of unread messages listed in the user's registry.
''' </returns>
''' <remarks></remarks>
Private Shared Function GetRegistryUnreadCount() As Integer
     ' Open the UnreadMail key in the registry that
     ' contains unread e-mail counts.
     Using unreadMailKey As RegistryKey = _
          Registry.CurrentUser.OpenSubKey( _
          "SOFTWARE\Microsoft\Windows\" & _
          "CurrentVersion\UnreadMail")
          Dim unreadEmailCount As Integer = 0
 
          ' The UnreadMail key in the registry contains
          ' subkeys for each e-mail account. We'll iterate
          ' through them and sum the unread e-mail counts.
          For Each account As String In _
              unreadMailKey.GetSubKeyNames()
              unreadEmailCount +=Int32.Parse( _
                   unreadMailKey.OpenSubKey(account) _
                   .GetValue("MessageCount").ToString())
          Next
 
          Return unreadEmailCount
     End Using
End Function

C#

/// <summary>
/// Gets the number of unread messages listed in the user's registry.
/// </summary>
/// <returns>
/// Returns the number of unread messages listed in the user's registry.
/// </returns>
private static int GetRegistryUnreadCount()
{ 
     // Open the UnreadMail key in the registry that
     // contains unread e-mail counts.
     using (RegistryKey unreadMailKey = Registry
          .CurrentUser.OpenSubKey(
          @"SOFTWARE\Microsoft\Windows\" +
          @"CurrentVersion\UnreadMail"))
     {
          int unreadEmailCount = 0;
 
          // The UnreadMail key in the registry contains
          // subkeys for each e-mail account. We'll iterate
          // through them and sum the unread e-mail counts.
          foreach (string account in
              unreadMailKey.GetSubKeyNames())
          {
              unreadEmailCount += Int32.Parse(
                   unreadMailKey.OpenSubKey(account)
                   .GetValue("MessageCount").ToString());
          }

          return unreadEmailCount;
     }
}

Once the number of unread e-mails has been determined, GetUnreadEmailCount writes its results to the standard output stream. Email.js reads this stream and displays the number of unread e-mails in the Email Alert Gadget.

Packaging & Deployment

To Package a Gadget for deployment first, place any culture specific files, such as Gadget.xml, into culture-specific folders. For the E-mail Alert Gadget, we can place Email.html, Gadget.xml, and other culture-specific files in the en-US folder. Non-culture-specific files remain outside of this folder.

To create a Gadget package, we first compress all the files and folders comprising the Gadget into a ZIP file, in this case Email Alert.zip. Next, we replace the .zip file extension with the .gadget file extension, yielding Email Alert.gadget. We can then deploy the Gadget file to a website or to the Microsoft Gadgets Gallery at microsoftgadgets.com.

Windows Vista users can add the E-mail Alert Gadget to the Windows Sidebar simply by downloading and opening it. Since the entire Gadget is self-contained in the Email Alert.gadget file, the E-mail Alert Gadget functions out-of-the-box with no configuration required.

Figure 4: Installing the E-mail Alert Gadget.

Conclusion

The E-mail Alert Gadget demonstrates how you can extend Windows Sidebar Gadgets by interoperating with a .NET application, in this case to display an unread e-mail counter. This enables .NET developers to bridge the gap between JavaScript Gadgets and existing .NET applications.

Further Reading

Rohan Singh

Rohan Singh, a software design engineer at SharpLogic Software, has been doing software Web development work for the past six years. Though now primarily a .NET developer, he has experience with web design, network administration, and server deployment. His current technological interests include Ajax, Windows Communication Foundation, and neural networks. While not at his keyboard, Rohan is an avid rock climber and snowboarder.

Tags:

Follow the Discussion

  • GuruparanGuruparan

    Great example...i will start to work on these types of gadgets (using .net!)

  • angryangry

    why ,why, on the earth,on 2007 you MSers,all keeping me angry ,all your pics dont appear on the browser.

  • CKCK

    Nice looking gadget with a little problem. I m using avast antivirus and everytime the gadget checks my inbox i get a splash screen from avast.Would be nice if u created a gadget that wouldn't actually load outlook but would check your mail directly, like a mail notifier with maybe an option for autodeleting spam from the server.

  • JeroenJeroen

    Thanks for this great article and example!

    This article helped me to start writing a gadget which 'll communicate with SharePoint Webservices.

    Cheers,

    Jeroen

  • ParrisParris

    The BBC programme CLICK demonstrated a piece of additional software that was running as a gadget on WinXP. I suspect there is some confusion here as to whether this material will work or not, but I notice you have scored out the offending line. The BBC hyperlink takes you to the Official Microsoft site, despite the article being about using WinXP rather than updating to Vista. No gadgets for WinXP users, unless they obtain them from a 3rd party then. Dumb * BBC!

  • Jawad HaiderJawad Haider

    Hello

    I wanna know the way to read vista window mail (that was outlook express in XP) through VB6

    Thanks

  • Clint RutkasClint I'm a "developer"

    Why do you want to use VB6?

  • kyoto.123@hotmail.comkyoto.​123@hotmail.​com

    I tried it out,it works with outlook but not with live mail,can you help me?

Remove this comment

Remove this thread

close

Comments Closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.