简体   繁体   中英

WQL request working in console application but not in Windows service

I'm currently working on a 'monitoring' solution. The idea is to set eyes on a remote ressource and alert user when avaiable disk space goes below a defined threshold.

The app is a Windows service. A timer is launched and make a WQL request every x seconds. The request contains metrics which I then use further in my code (eg total disk size, space avaiable).

I've been testing the whole thing in a console application and it works just fine. But when I implement it in my Win service the WQL request goes wild and return a null element.

How come ? Am I missing something ?

Here is my code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace DatafactMonitoring
{
    public partial class DatafactMonitoring : ServiceBase
    {
        public DatafactMonitoring()
        {
            InitializeComponent();
            //Creating the event log entry
            eventLog1 = new System.Diagnostics.EventLog();
            if (!System.Diagnostics.EventLog.SourceExists("ServiceMonitoringDatafact"))
            {
                System.Diagnostics.EventLog.CreateEventSource("ServiceMonitoringDatafact", "Événements Monitoring Datafact");
            }
            eventLog1.Source = "ServiceMonitoringDatafact";
            eventLog1.Log = "Événements Monitoring Datafact";
        }

    //Parameters
    protected static int threshold = 10;
    //Declarations
    private static int indexLog = 0;
    protected static float diskUsage;

    protected override void OnStart(string[] args)
    {
        eventLog1.WriteEntry("Starting the Datafact monitoring service...");
        // Timer that triggers OnTimer function every 60 seconds
        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 10000; // 10 seconds, to be changed
        timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
        timer.Start();
    }

    public ManagementObject GetMetrics()
    {
        ConnectionOptions options = new ConnectionOptions();
        ManagementScope scope = new ManagementScope("\\\\ad", options);
        scope.Connect();
        SelectQuery query1 = new SelectQuery("Select Name, Size, FreeSpace from Win32_LogicalDisk Where DeviceID = 'P:'");
        eventLog1.WriteEntry("Requete...");
        ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(scope, query1);
        ManagementObjectCollection queryCollection1 = searcher1.Get();
        ManagementObject mo = queryCollection1.OfType<ManagementObject>().First();
        return mo;
    }

    public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
    {
        ManagementObject datafactMetrics = GetMetrics();

        //Metrics parsing
        string diskName = datafactMetrics["Name"].ToString();
        eventLog1.WriteEntry(diskName);
        float diskSize = float.Parse(datafactMetrics["Size"].ToString());
        float freeSpace = float.Parse(datafactMetrics["FreeSpace"].ToString());
        diskUsage = (freeSpace / diskSize) * 100;

        indexLog += 1;

        eventLog1.WriteEntry("Log n°" + indexLog + " - Monitoring Datafact server - Space avaiable : " + freeSpace + "Go", EventLogEntryType.Information);

        if (diskUsage >= threshold)
        {
            try
            {
                //TODO: Change url to SMS sender
                System.Diagnostics.Process.Start("http://www.google.com");
                eventLog1.WriteEntry("Space avaiable below " + threshold + "% (Disk usage : " + diskUsage + "%) - Mail & SMS sent to the team", EventLogEntryType.Warning);
            }

            catch (Exception ex)
            {
                eventLog1.WriteEntry("Error : " + ex.ToString(), EventLogEntryType.Error);
            }
        }
        else
        {
            eventLog1.WriteEntry("Disk usage : " + diskUsage + "%", EventLogEntryType.Information);
        }
    }

    protected override void OnStop()
    {
        eventLog1.WriteEntry("Datafact monitoring service stopped.");
    }
}
}

Unable to find a proper solution with WMI. Workaround found using GetDiskFreeSpace from Win32API.

//Starting with the function's import...
[DllImport("kernel32")]
public static extern int GetDiskFreeSpace(
    string lpRootPathName,
    out int lpSectorsPerCluster,
    out int lpBytesPerSector,
    out int lpNumberOfFreeClusters,
    out int lpTotalNumberOfClusters
);
.
.
.

//... which I then use in my OnTimer function
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
{
    string lpRootPathName = @"\\ServerName\SharedFolder";
    int lpSectorsPerCluster;
    int lpBytesPerSector;
    int lpNumberOfFreeClusters;
    int lpTotalNumberOfClusters;

    int bRC = GetDiskFreeSpace(
        lpRootPathName,
        out lpSectorsPerCluster,
        out lpBytesPerSector,
        out lpNumberOfFreeClusters,
        out lpTotalNumberOfClusters
    );

    .
    .
    .

    eventLog1.WriteEntry("Root : "+ lpRootPathName + "Sectors : "+ lpSectorsPerCluster +"Bytes : "+ lpBytesPerSector +"FreeClusters : "+ lpNumberOfFreeClusters + "TotalClusters : "+ lpTotalNumberOfClusters);

If the LogicalDrive P is a Network Drive you can´t access to it from a windows service, at least not by default settings, because it has minimum privileges:

msdn local service account

If you can´t control privileges of the network drive, you will have to configure the Windows Service to run as a specific user:

impersonating codeproject example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM