Microsoft Cloud Authors: Elizabeth White, Yeshim Deniz, Serafima Al, Janakiram MSV, John Katrick

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
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
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.
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...