Welcome!

Microsoft Cloud Authors: Janakiram MSV, Yeshim Deniz, David H Deans, Andreas Grabner, Stackify Blog

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

Catching SENS Events in .NET

Keep tabs on Windows with System Notification Events

Microsoft Windows provides a process called the System Event Notification Service. This service raises events relative to interactive logon, network, and power changes. Using this service an application can be notified when network connectivity changes, when available power decreases, or when a person logs on, locks his or screen, or his or her screensaver starts. This service notifies COM+ of these events, which appropriates them to any subscribing application.

In this article, we will focus on the logon events. However, the principles discussed in this article extend to catching and processing network and power events.

Uses of SENS Logon Events
When working in an environment without a Windows Domain to track users or a consistent IM service, it would be good to know when co-workers are at their desks. An application could track when someone has logged into his or her computer, when the screensaver turns on, or when the screen is purposefully locked.

This is ambient information about people's presence at work and the likelihood of their presence at their desks. Managers especially like this information so that they can drop in and chat with workers unannounced. This logon information could be presented in many interesting ways, such as a media player visualization where pictures of each person logged in could fly around, with those who have locked their screens being represented by small pictures. Knowing user logon status could also help reclaim lost computing cycles. Most desktop computers utilize very little of their possible computing power. Open the Task Manager and watch the CPU usage: most of the time, it will barely peak above 4% usage. This computing power could be used to solve many interesting problems.

For example, our media players could run in-depth statistics on the songs we listen to, such as finding patterns within the actual audio of our favorite songs, so that it can suggest other songs that have similar audio qualities. The computer would need to spend a lot of time analyzing each song, producing a local database of songs, and indexing between songs. Desktop search engines need to view and index all of the files you have on your computer. An interesting help would be to index all Web pages visited, particularly sites that get a lot of interactive time from the user, and are relevant to keywords in personal documents and emails.

Then, when performing an online search, results from relevant, frequently visited sites could be favored over the typical search results. In fact, the application may be able to suggest search terms that would help search for more accurate and relevant results when looking for new information. This kind of intensive processing could be done on a low-priority thread: eating up processor time when it is not needed by other applications. However when a lot of disk access is involved, it can degrade the performance of other higher-priority applications.

SENS Events
Let's start a new console application to illustrate catching SENS events through COM. Create a new Visual Studio solution called DotNetSENS with a C# Console Application in that solution. Then add a COM reference to "SENS Events Type Library." Visual Studio.Net will create a small DLL that interfaces between the .NET Framework and the SENS Events COM DLL. By using the code in Listing 1 we should be able to catch the screen lock and unlock events (if you cannot lock your screen, you can catch the screen saver start and stop events).

The first time we try and run this new application it crashes. Unfortunately, we cannot actually create an instance of the SENSClass class: it is a COM process that is running, and it provides its events through the COM+ Event System.

After a lot of searching on the topic, I stumbled on an article that helps to explain how to connect to the COM+ Event Sys-tem using managed code (www.codeproject.com/csharp/subscriptionviewer.asp). That article helped me learn how to register for SENS events. Most of the rest of this article describes how to register for SENS events directly; once you understand the code, it becomes a pattern for how to register for any events that are provided through the COM+ Event System.

Registering With the COM+ Event System
Ideally, we want a DLL that we can import into any project that we are working on and start getting SENS events. To do this, add a new "C# Class Library" project to the DotNetSENS project, and name it ManagedSENS. Remove Class1 and add a new class called EventSystemRegistrar. This class will contain all of the code necessary to connect to the Event System. Now add a reference to "EventSystem 1.0 Type Library" so that we can have the classes necessary to register with and use the COM + Event System.

Just importing the EventSystem classes is not enough to gain access to the Event System; we need a few classes we can instantiate and call methods on. These classes are provided in Listing 2. Even though they do not have any methods on them, through the magic of COM Interop these classes will expose the methods of the classes specified by the GUID attribute. (COM is dependent on Globally Unique Identifiers (GUID) to uniquely identify all of the classes, interfaces, methods, etc. that can be specified in COM. GUIDs in COM serve the purpose of the GAC in the .NET Framework: they make sure that two classes with the same name do not conflict with each other, and a library that wants to call methods on certain classes does not get the wrong classes.)

The COM+ Event System is a set of COM libraries that make it seamless for any class to register for events raised in any running process. Thus the system can send events to the places we want it to, and it requires several pieces of information to register for them:

  • Description: A friendly description of the class subscribing
  • Name: Usually the name of the class: just to be friendly
  • Identifier: A way of uniquely identifying this subscription (because the Description may not be unique)
  • Object on which to call methods
  • Type of interface on which to call methods - this is for the COM system so that it can register the object with the appropriate event-raising process
To conform to the needs of the Event System, we will create a SubscribeToEvents routine, which is shown in Listing 3. Each of the parameters matches what the Event System requires. Also, if you look inside this method, you can see the magic of the COM Interop: the EventSubscription object has no methods, yet it can be cast to an IEventSubscription interface, which has methods that can be called.

Registering for SENS through the Event System
Now that we have a class to register with the Event System, we need a class to receive the events. The problem is that SENS will only call certain kinds of methods. To support this, we need to add the "SENS Events Type Library" to the class library project, as we did with the console application. The reason this library must be added is so that we have all the appropriate GUIDs, interfaces, and methods available for the Event System to call.

More Stories By Richard Arthur

Richard Arthur is currently an instructor of C# at Northface University (www.northface.edu) in Salt Lake City, Utah. He has gained extensive experience doing Automation of MS Office products through VBA and COM at previous jobs.
In his spare time he learns about the inner workings of many current and future .NET Technologies, including Windows Forms, ASP.NET, Generics, P/Invoke, and COM Interoperability.
If anyone has any questions regarding this article, please contact Richard at [email protected]

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...