Click here to Skip to main content
14,134,442 members
Click here to Skip to main content
Add your own
alternative version

Stats

15.1K views
586 downloads
25 bookmarked
Posted 6 Jan 2016
Licenced CPOL

SessionTime - Log Windows Session Events and Display Session Durations and Locked Periods

, 26 Dec 2017
Rate this:
Please Sign up or sign in to vote.
This application consists of Windows service that logs Windows session events and WPF application that parses resulting log to display session durations and locked/unlocked periods within sessions per user.

Introduction

This article describes possible approach to logging session events on Windows operating system. It also parses event data to display session durations and locked/unlocked periods. Following session events are logged: logon, logoff, lock, unlock.

Source code might be useful to developers who need working source code to help them with their own Windows session logging solution. Windows service and app might be useful if you, say, want to monitor how much time you spend on the computer or at which time you logged in and started working.

Application consists of three parts:

  • SessionTimeMonitor - Windows service that logs events
  • SessionTimeViewer - Windows application that displays parsed session durations and locked/unlocked periods within sessions
  • SessionTimeSetup - installer/uninstaller for Windows service and application

SessionTimeMonitor

Main part is a Windows service called SessionTimeMonitor - it handles the OnSessionChange event which is triggered each time when a session change occurs. When event is triggered, record is added by the service to the XML file on the disk. Record contains information about the event, such as datetime, type of event, etc.

SessionTimeViewer

SessionTimeViewer application opens and parses XML file that contains data records written by the SessionTimeMonitor. It displays list of sessions with their start and end datetime along with the locked/unlocked periods within a single session. SessionTimeViewer is implemented as a WPF application.

Background

I needed this application to determine how much time I spend on the computer and I wanted to have a customizable application. Alternative approach was to write an application that parses Windows event logs but I concluded that parsing Windows event logs and pairing logon/logoff and lock/unlock events was quite cumbersome.

Using the Code

Development Tools

Windows service and WPF application were developed using .NET Framework 4.0 and Visual Studio 2010.

How It Works

Following illustration shows how this approach works:

SessionTimeMonitor (Windows service)

-> writes to - >

XML data file

-> is read and parsed by - >

SessionTimeViewer (Windows application)

Handling the OnSessionChange Event

Main part of the solution is a Windows service that logs session events to the XML data file, this is done through overriding the OnSessionChange event. For this to work, System.ServiceProcess.ServiceBase.CanHandleSessionChangeEvent property has to be set:

CanHandleSessionChangeEvent = true;

in service class:

public SessionTimeMonitor()
{
    try
    {
        InitializeComponent();
        SessionManager.Initialize(dataFilePath, logFilePath);
        CanPauseAndContinue = false;
        CanHandleSessionChangeEvent = true;
        ServiceName = "SessionTimeMonitor";
    }
    catch (Exception ex)
    {
        Utility.Log(logFilePath, ex.ToString());
    }
}

Following method override does the logging:

protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
    try
    {
        if (changeDescription.Reason == SessionChangeReason.SessionLogon
            || changeDescription.Reason == SessionChangeReason.SessionLogoff
            || changeDescription.Reason == SessionChangeReason.SessionLock
            || changeDescription.Reason == SessionChangeReason.SessionUnlock
            )
        {
            SessionManager.LogSessionData(
                currentServiceRunGuid, 
                changeDescription.SessionId, 
                SessionTrackingEvents.OnSessionChange,
                changeDescription.Reason.ToString());
        }
    }
    catch (Exception ex)
    {
        Utility.Log(logFilePath, ex.ToString());
    }
}

Log is kept in form of XML file stored on disk.

XML Data Record

Each logged event is represented by SessionTrackingParams XML element. Such element is added to log when the service starts (during the service's OnStart event) for each existing session or when session changes (when OnSessionChange event occurs) only for session that changed. Such events are logged in SessionTimeMonitor service and serialized to the list stored in XML data file.

Example of XML data record could be:

<SessionTracking xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

 xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SessionTrackingParamsList>
    <SessionTrackingParams ServiceRunGuid="88a4a5f5-711a-45d7-90c4-34f23c2fea93" 

     SessionId="9" LogonDT="2016-01-06T10:50:32.8418659+01:00" 

     EventDT="2016-01-06T11:32:39.6701443+01:00" UserAccount="Ivan-PC\Ivan" 

     Event="OnStart" Reason="" />
  </SessionTrackingParamsList>
</SessionTracking>

SessionTrackingParams elements are added by LogSessionData method, signature of this method is:

public static void LogSessionData(Guid currentServiceRunGuid, int sessionId, 
SessionTrackingEvents sessionTrackingEvent, string reason, bool logAllExistingSessions = false)

Explanations of parameters:

  • Guid currentServiceRunGuid - ID of service run, this ID is defined by SessionTimeMonitor, it remains the same from SessionTimeMonitor start (usually at system start up) until its stops (usually at system shutdown)
  • int sessionId - session ID to log, this ID is defined by Windows, it is unique per user logon but only between the same computer- boot/computer-shutdown period, it will start again from 0 after each computer restart, to distinguish between different sessions, currentServiceRunGuid is logged to data file and used by SessionTimeViewer when parsing session durations
  • SessionTrackingEvents sessionTrackingEvent - represents the event because of which the method was called, possible values:
    • OnStart - sent when the SessionTimeMonitor service starts, when the service starts, it will log all the existing user sessions
    • OnSessionChange - sent when the OnSessionChange event occurs
  • string reason - value received from event parameters of a OnSessionChange event, can be:
    • empty string - when sessionTrackingEvent is OnStart
    • SessionLogon - when sessionTrackingEvent is OnSessionChange and session was logged on, example: user logged on
    • SessionLogoff - when sessionTrackingEvent is OnSessionChange and session was logged off, example: user logged off or computer was shut down
    • SessionLock - when sessionTrackingEvent is OnSessionChange and session was locked, example: user has put computer to sleep
    • SessionUnlock- when sessionTrackingEvent is OnSessionChange and session was unlocked, example: user has woken computer from sleep
  • bool logAllExistingSessions = false - optional parameter, when:
    • true - records for all existing sessions are logged, used when sessionTrackingEvent is OnStart
    • false - only record for sessionId is logged

Displaying Session Duration and Locked/Unlocked Periods

Parsing of XML data file is performed by SessionTimeViewer which is a Windows WPF application that shows following types of data:

  • sessions - as periods between logon and logoff event within same service run marked by ServiceRunGuid
  • unlocked periods - as periods within same session between:
    • logon and logoff
    • logon and lock
    • unlock and logoff
    • unlock and lock
  • locked periods - as periods within same session between:
    • lock and unlock
    • lock and logoff

This way, it is possible to see when and how long certain user has been logged on and when locked or unlocked periods happened.

An example screenshot of SessionTimeViewer:

Points of Interest

  • SessionTimeMonitor utilizes the Cassia library which is "a .NET library for accessing the native Windows Terminal Services API (now the Remote Desktop Services API)" (https://code.goog le.com/p/cassia/, 2016-01-06), it uses its GetSessions method to obtain session data
  • SessionTimeViewer displays only session for which the logoff event exists, this means that current session along with its locked/unlocked periods is not displayed until logoff
  • When computer starts up, it is possible that SessionTimeMonitor:
    • starts before user logon - in such case, user logon will be logged through OnSessionChange event
    • starts after the user logon - in such case, all existing sessions are logged through service's OnStart event
  • SessionTimeMonitor and SessionTimeViewer are using config files to set path of XML data file, so those paths are configurable
  • Service and application have been tested on Windows 7 (32 bit), Windows 8.1 (64 bit)
  • Prerequisite on client computer is .NET Framework 4.0

ToDo

Improve Event Data Logging

Currently, logging of events to the XML data file on the disk is performed using deserialization and serialization of data file content into List<SessionEventParams>, theoretically this might cause delay since data file can contain many records that are going to be serialized/deserialized each time a record is added.

Example: Described behavior might slow down logoff: in case of a shutdown, shutdown starts logoff, logoffs are logged by SessionTimeMonitor that utilizes current serialization/deserialization which might be slow in case of very large data file.

History

  • 1.0.0.0 - 2016-06-01 - Initial version from previous article with the same name, I deleted it due to a bug it contained
  • 1.0.0.1 - 2016-06-01 - Bugfix for version 1.0.0.0, previous version wasn't logging logoff event correctly due to last-minute untested change, sorry to all the folks who downloaded version 1.0.0.0 :/

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ivan Golović
Croatia Croatia
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionEasier Log viewing? Pin
John Torjo6-Jan-16 1:03
professionalJohn Torjo6-Jan-16 1:03 
AnswerRe: Easier Log viewing? Pin
Ivan Golović6-Jan-16 1:20
memberIvan Golović6-Jan-16 1:20 
GeneralRe: Easier Log viewing? Pin
John Torjo6-Jan-16 1:29
professionalJohn Torjo6-Jan-16 1:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190518.1 | Last Updated 27 Dec 2017
Article Copyright 2016 by Ivan Golović
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid