Skip to content

Commit

Permalink
Added IWMIWatcher interface so WMIWatcher can be injected via DI
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicolas authored and Nicolas committed Dec 2, 2020
1 parent f3289d8 commit e454bea
Show file tree
Hide file tree
Showing 12 changed files with 242 additions and 64 deletions.
16 changes: 16 additions & 0 deletions ORMi.Sample.Worker/ORMi.Sample.Worker.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UserSecretsId>dotnet-ORMi.Sample.Worker-C66EC170-4903-4DCA-B88C-AD394F5DF5F3</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.8" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\ORMi.Sample\ORMi.Sample.csproj" />
<ProjectReference Include="..\ORMi\ORMi.csproj" />
</ItemGroup>
</Project>
28 changes: 28 additions & 0 deletions ORMi.Sample.Worker/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ORMi.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ORMi.Sample.Worker
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
services.AddSingleton<IWMIHelper>(new WMIHelper("root\\cimv2"));
services.AddSingleton<IWMIWatcher, WMIWatcher>();
});
}
}
10 changes: 10 additions & 0 deletions ORMi.Sample.Worker/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"profiles": {
"ORMi.Sample.Worker": {
"commandName": "Project",
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}
36 changes: 36 additions & 0 deletions ORMi.Sample.Worker/Worker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ORMi.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ORMi.Sample.Worker
{
public class Worker : BackgroundService
{
private readonly IWMIHelper _helper;
private readonly IWMIWatcher _watcher;

public Worker(IWMIHelper helper, IWMIWatcher watcher)
{
_helper = helper;
_watcher = watcher;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_watcher.Initialize("root\\CimV2", "SELECT * FROM Win32_ProcessStartTrace");
_watcher.WMIEventArrived += _watcher_WMIEventArrived;
}

private void _watcher_WMIEventArrived(object sender, WMIEventArgs e)
{
dynamic process = e.Object;

Console.WriteLine("New Process: {0} (Pid: {1})", process.ProcessName, process.ProcessID.ToString());
}
}
}
9 changes: 9 additions & 0 deletions ORMi.Sample.Worker/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
9 changes: 9 additions & 0 deletions ORMi.Sample.Worker/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
11 changes: 6 additions & 5 deletions ORMi.Sample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ class Program
{
static void Main(string[] args)
{
IWMIHelper helper = new WMIHelper("root\\CimV2");
//IWMIHelper helper = new WMIHelper("root\\CimV2");

Process p = new Process();
p.Create("C:/Windows/notepad.exe", null, null);
//Process p = new Process();
//p.Create("C:/Windows/notepad.exe", null, null);

//List<NetworkAdapterConfiguration> interfaces = helper.Query<NetworkAdapterConfiguration>().ToList();

Expand Down Expand Up @@ -79,8 +79,8 @@ static void Main(string[] args)
//List<Person> queryPerson = helper.Query<Person>("SELECT * FROM Lnl_Cardholder WHERE LASTNAME = 'Lopez'").ToList();

//WMIWatcher watcher = new WMIWatcher("root\\CimV2", "SELECT * FROM Win32_ProcessStartTrace", typeof(Process));
//WMIWatcher watcher = new WMIWatcher("root\\CimV2", "SELECT * FROM Win32_ProcessStartTrace");
//watcher.WMIEventArrived += Watcher_WMIEventArrived;
WMIWatcher watcher = new WMIWatcher("root\\CimV2", "SELECT * FROM Win32_ProcessStartTrace");
watcher.WMIEventArrived += Watcher_WMIEventArrived;

Console.ReadLine();
}
Expand All @@ -89,6 +89,7 @@ private static void Watcher_WMIEventArrived(object sender, WMIEventArgs e)
{
//Process process = (Process)e.Object;


dynamic process = e.Object;

Console.WriteLine("New Process: {0} (Pid: {1})", process.ProcessName, process.ProcessID.ToString());
Expand Down
16 changes: 11 additions & 5 deletions ORMi.sln
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27703.2000
# Visual Studio Version 16
VisualStudioVersion = 16.0.30709.132
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ORMi", "ORMi\ORMi.csproj", "{458EAFAF-7557-45E7-81C7-73C34834CCF8}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ORMi", "ORMi\ORMi.csproj", "{458EAFAF-7557-45E7-81C7-73C34834CCF8}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{244C8151-A276-408B-BA7F-3A3672649234}"
ProjectSection(SolutionItems) = preProject
README.md = README.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ORMi.Sample", "ORMi.Sample\ORMi.Sample.csproj", "{3F99A314-D156-469A-9651-D365A478FA4B}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ORMi.Sample", "ORMi.Sample\ORMi.Sample.csproj", "{3F99A314-D156-469A-9651-D365A478FA4B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ORMi.Tests", "ORMi.Tests\ORMi.Tests.csproj", "{3637DD0D-E46C-4B0D-8382-40B71A351B24}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ORMi.Tests", "ORMi.Tests\ORMi.Tests.csproj", "{3637DD0D-E46C-4B0D-8382-40B71A351B24}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ORMi.Sample.Worker", "ORMi.Sample.Worker\ORMi.Sample.Worker.csproj", "{4AAE0870-1E3A-4335-9A49-1F7D9900F389}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand All @@ -32,6 +34,10 @@ Global
{3637DD0D-E46C-4B0D-8382-40B71A351B24}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3637DD0D-E46C-4B0D-8382-40B71A351B24}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3637DD0D-E46C-4B0D-8382-40B71A351B24}.Release|Any CPU.Build.0 = Release|Any CPU
{4AAE0870-1E3A-4335-9A49-1F7D9900F389}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4AAE0870-1E3A-4335-9A49-1F7D9900F389}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4AAE0870-1E3A-4335-9A49-1F7D9900F389}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4AAE0870-1E3A-4335-9A49-1F7D9900F389}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
83 changes: 45 additions & 38 deletions ORMi/Helpers/TypeHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,58 +56,65 @@ private static void _SetPropertyValue(ManagementBaseObject mo, PropertyInfo p, o

if (ignoreProp == null)
{
WMIProperty propAtt = p.GetCustomAttribute<WMIProperty>();

string propertyName = String.Empty;

if (propAtt != null)
try
{
propertyName = propAtt.Name;
}
else
{
propertyName = p.Name;
}
WMIProperty propAtt = p.GetCustomAttribute<WMIProperty>();

var a = mo.Properties[propertyName].Value;
string propertyName = String.Empty;

if (a == null)
{
p.SetValue(o, null);
}
else if (p.PropertyType == typeof(DateTime) && a is string s)
{
p.SetValue(o, ManagementDateTimeConverter.ToDateTime((string)a), null);
}
else if (a is ManagementBaseObject b)
{
var classAtt = p.PropertyType.GetCustomAttribute<WMIClass>();
if (propAtt != null)
{
propertyName = propAtt.Name;
}
else
{
propertyName = p.Name;
}

string className = String.Empty;
var a = mo.Properties[propertyName].Value;

if (classAtt != null)
if (a == null)
{
className = classAtt.Name;
p.SetValue(o, null);
}
else
else if (p.PropertyType == typeof(DateTime) && a is string s)
{
className = p.PropertyType.Name;
p.SetValue(o, ManagementDateTimeConverter.ToDateTime((string)a), null);
}
else if (a is ManagementBaseObject b)
{
var classAtt = p.PropertyType.GetCustomAttribute<WMIClass>();

string className = String.Empty;

if (classAtt != null)
{
className = classAtt.Name;
}
else
{
className = p.PropertyType.Name;
}

if (className == b.ClassPath.ClassName)
if (className == b.ClassPath.ClassName)
{
p.SetValue(o, LoadObject(b, p.PropertyType), null);
}
}
else
{
p.SetValue(o, LoadObject(b, p.PropertyType), null);
var propertyType = p.PropertyType;
if (propertyType.IsGenericType &&
propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = propertyType.GetGenericArguments()[0];
}
p.SetValue(o, Convert.ChangeType(a, propertyType), null);
}
}
else
catch (Exception ex)
{
var propertyType = p.PropertyType;
if (propertyType.IsGenericType &&
propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = propertyType.GetGenericArguments()[0];
}
p.SetValue(o, Convert.ChangeType(a, propertyType), null);
throw new Exception($"Property name was not found on WMI object. Check out {o} property names and attributes");
}
}
else
Expand Down
38 changes: 38 additions & 0 deletions ORMi/Interfaces/IWMIWatcher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace ORMi.Interfaces
{
public interface IWMIWatcher
{
event WMIWatcher.WMIEventHandler WMIEventArrived;

/// <summary>
/// Disposes the WMIWatcher object.
/// </summary>
void Dispose();

/// <summary>
/// Initializes the WMIWatcher with the desired parameters.
/// </summary>
/// <param name="scope">Desired Scope</param>
/// <param name="query">Query to be watch</param>
/// <param name="type">Type of result</param>
/// <param name="options">Connection options. If null, default options are used</param>
void Initialize(string scope, string query, Type type = null, ConnectionOptions options = null);

/// <summary>
/// Starts the current WMI Event watcher
/// </summary>
void StartWatcher();

/// <summary>
/// Stops the current WMI Event watcher
/// </summary>
void StopWatcher();
}
}
6 changes: 3 additions & 3 deletions ORMi/ORMi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@
<Product>ORMi</Product>
<Description>A Light-ORM for accesing WMI</Description>
<Copyright>Copyright 2018</Copyright>
<Version>3.0.0.0</Version>
<Version>3.1.0.0</Version>
<Authors>nicoriff</Authors>
<PackageIconUrl>https://www.shareicon.net/data/128x128/2017/02/07/878478_key_512x512.png</PackageIconUrl>
<PackageId>ORMi</PackageId>
<PackageLicenseUrl>https://github.com/nicoriff/ORMi/blob/master/LICENSE</PackageLicenseUrl>
<PackageProjectUrl>https://github.com/nicoriff/ormi</PackageProjectUrl>
<PackageReleaseNotes>A Light-ORM for accesing WMI</PackageReleaseNotes>
<PackageTags>WMI ORM ORMi</PackageTags>
<AssemblyVersion>3.0.0.0</AssemblyVersion>
<FileVersion>3.0.0.0</FileVersion>
<AssemblyVersion>3.1.0.0</AssemblyVersion>
<FileVersion>3.1.0.0</FileVersion>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'net45'">
Expand Down
Loading

0 comments on commit e454bea

Please sign in to comment.