-
Notifications
You must be signed in to change notification settings - Fork 0
/
TrackerTestHub.cs
388 lines (340 loc) · 13.4 KB
/
TrackerTestHub.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
using System;
using System.Management;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using SharpPcap;
using SharpPcap.LibPcap;
using PacketDotNet;
using Microsoft.Win32;
class Program
{
static void Main()
{
//T1 working
// Subscribe to the NetworkAvailabilityChanged event
//NetworkChange.NetworkAvailabilityChanged += NetworkAvailabilityChangedHandler;
////Console.WriteLine("Press Enter to exit.");
////Console.ReadLine();
//DisplayNetworkInterfaceInformation();
////T2
//// Set up a timer to periodically check for changes
Timer timer = new Timer(EventCheckNow, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
Console.WriteLine("Press Enter to exit.");
Console.ReadLine();
// Dispose the timer when done
timer.Dispose();
////T3
//ApplicationUsage();//T3 Working
//NetworkTracker(); //T4 Need to test
////T5
//MonitorSystemResourceUsage();//WOrking
////T6
//MonitorSystemResourceUsageMain();//Working
////T7
//processErrorReading();//Partial Working
////T8
//GetInstalledAllApplications();//WOrking
////T9
//GetInstalledUserApplications();//Working v1
////T10
////GetInstalledUserApplicationsMain();
////T11
//ReadEventLog("Application"); //Working
//T12
//ReadChromeEvent(); //Working
}
static void ReadEventLog(string eventLogName)
{
try
{
// Open the specified event log
EventLog eventLog = new EventLog(eventLogName);
// Display information about the event log
Console.WriteLine($"Reading from event log: {eventLog.LogDisplayName}");
Console.WriteLine($"Total number of entries: {eventLog.Entries.Count}");
// Iterate over the entries in the event log and display them
foreach (EventLogEntry entry in eventLog.Entries)
{
Console.WriteLine($"Entry Type: {entry.EntryType}");
Console.WriteLine($"Event ID: {entry.InstanceId}");
Console.WriteLine($"Message: {entry.Message}");
Console.WriteLine($"Time Generated: {entry.TimeGenerated}");
Console.WriteLine();
}
// Close the event log
eventLog.Close();
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static void GetInstalledUserApplications()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Product WHERE InstallLocation IS NOT NULL");
ManagementObjectCollection products = searcher.Get();
foreach (ManagementObject product in products)
{
string name = product["Name"] as string;
string version = product["Version"] as string;
string vendor = product["Vendor"] as string;
string installLocation = product["InstallLocation"] as string;
Console.WriteLine($"Name: {name}, Version: {version}, Vendor: {vendor}, InstallLocation: {installLocation}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static void GetInstalledAllApplications()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Product");
ManagementObjectCollection products = searcher.Get();
foreach (ManagementObject product in products)
{
string name = product["Name"] as string;
string version = product["Version"] as string;
string vendor = product["Vendor"] as string;
Console.WriteLine($"Name: {name}, Version: {version}, Vendor: {vendor}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static void processErrorReading()
{
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "C:\\Program Files\\Adobe\\Adobe Photoshop 2023\\Photoshop.exe", // Assuming chrome.exe is in the system's PATH
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data != null)
{
Console.WriteLine($"Error output: {e.Data}");
}
};
process.Start();
// Begin asynchronous reading of error output
process.BeginErrorReadLine();
// Other code or tasks can run concurrently here...
// Wait for the process to exit and clean up
process.WaitForExit();
process.Close();
}
static void MonitorSystemResourceUsage()
{
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
PerformanceCounter diskCounter = new PerformanceCounter("LogicalDisk", "% Free Space", "C:");
while (true)
{
// Retrieve and display CPU usage
float cpuUsage = cpuCounter.NextValue();
Console.WriteLine($"CPU Usage: {cpuUsage}%");
// Retrieve and display available RAM
float availableRAM = ramCounter.NextValue();
Console.WriteLine($"Available RAM: {availableRAM} MB");
// Retrieve and display % free space on C: drive
float freeDiskSpace = diskCounter.NextValue();
Console.WriteLine($"Free Disk Space (C:): {freeDiskSpace}%");
Console.WriteLine("------------------------------");
// Sleep for a short interval before checking again
System.Threading.Thread.Sleep(1000); // Adjust as needed
}
}
static void MonitorSystemResourceUsageMain()
{
PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
while (true)
{
// Retrieve and display available RAM
float availableRAM = ramCounter.NextValue();
Console.WriteLine($"Available RAM: {availableRAM} MB");
// Display detailed process memory usage
DisplayProcessMemoryUsage();
Console.WriteLine("------------------------------");
// Sleep for a short interval before checking again
System.Threading.Thread.Sleep(1000); // Adjust as needed
}
}
static void DisplayProcessMemoryUsage()
{
Console.WriteLine("Process Memory Usage:");
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
try
{
Console.WriteLine($"{process.ProcessName}: {process.WorkingSet64 / (1024 * 1024)} MB");
}
catch (Exception ex)
{
// Handle exceptions (e.g., access denied to some processes)
Console.WriteLine($"{process.ProcessName}: Error - {ex.Message}");
}
}
}
static void NetworkTracker()
{
// List available network devices
var devices = CaptureDeviceList.Instance;
if (devices.Count < 1)
{
Console.WriteLine("No network devices found.");
return;
}
Console.WriteLine("Available network devices:");
for (int i = 0; i < devices.Count; i++)
{
Console.WriteLine($"{i + 1}. {devices[i].Description}");
}
Console.Write("Select a device (enter the number): ");
int selectedDeviceIndex;
if (int.TryParse(Console.ReadLine(), out selectedDeviceIndex) && selectedDeviceIndex >= 1 && selectedDeviceIndex <= devices.Count)
{
// Open the selected device for capturing
ICaptureDevice device = devices[selectedDeviceIndex - 1];
device.OnPacketArrival += Device_OnPacketArrival;
device.Open(DeviceMode.Promiscuous, 1000); // Open in promiscuous mode with a 1-second timeout
device.StartCapture();
Console.WriteLine($"Capturing network traffic on {device.Description}. Press Enter to stop.");
Console.ReadLine();
// Stop capturing and close the device when done
device.StopCapture();
device.Close();
}
else
{
Console.WriteLine("Invalid selection.");
}
}
private static void Device_OnPacketArrival(object sender, CaptureEventArgs e)
{
// Process captured packet
var packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
Console.WriteLine($"Captured packet: {packet}");
}
static void ApplicationUsage()
{
foreach (var process in Process.GetProcesses())
{
Console.WriteLine($"Process Name: {process.ProcessName}, ID: {process.Id}");
// Log or store process information
}
}
static void EventCheckNow(object state)
{
//ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Process");
//foreach (ManagementObject process in searcher.Get())
//{
// Console.WriteLine($"Process Name: {process["Name"]}");
// Console.WriteLine($"Process ID: {process["ProcessId"]}");
//}
EventQuery query = new EventQuery();
query.QueryString = "SELECT * FROM" +
" __InstanceCreationEvent WITHIN 1 " +
"WHERE TargetInstance isa \"Win32_Process\"";
// Initialize an event watcher and subscribe to events
// that match this query
ManagementEventWatcher watcher =
new ManagementEventWatcher(query);
// times out watcher.WaitForNextEvent in 5 seconds
watcher.Options.Timeout = new TimeSpan(0, 0, 5);
// Block until the next event occurs
// Note: this can be done in a loop if waiting for
// more than one occurrence
Console.WriteLine(
"Open an application (notepad.exe) to trigger an event.");
ManagementBaseObject e = watcher.WaitForNextEvent();
//Display information from the event
Console.WriteLine(
"Process {0} has been created, path is: {1}",
((ManagementBaseObject)e
["TargetInstance"])["Name"],
((ManagementBaseObject)e
["TargetInstance"])["ExecutablePath"]);
//Cancel the subscription
watcher.Stop();
}
static void DisplayNetworkInterfaceInformation()
{
Console.WriteLine("Current Network Interfaces:");
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
Console.WriteLine($"Interface: {nic.Description}");
Console.WriteLine($" Status: {nic.OperationalStatus}");
Console.WriteLine($" Speed: {nic.Speed} bps");
Console.WriteLine($" Bytes Sent: {nic.GetIPv4Statistics().BytesSent}");
Console.WriteLine($" Bytes Received: {nic.GetIPv4Statistics().BytesReceived}");
Console.WriteLine("----------------------------");
}
}
static void CheckForNetworkChanges(object state)
{
Console.WriteLine("Checking for network changes...");
// Display updated network interface information
DisplayNetworkInterfaceInformation();
}
static void NetworkAvailabilityChangedHandler(object sender, NetworkAvailabilityEventArgs e)
{
if (e.IsAvailable)
{
Console.WriteLine("Network connection is available.");
}
else
{
Console.WriteLine("Network connection is unavailable.");
}
}
static void ReadChromeEvent()
{
string chromeSource = "Chrome_Process";
ReadApplicationEvents(chromeSource);
}
static void ReadApplicationEvents(string applicationName)
{
try
{
// Open the "Application" event log
EventLog eventLog = new EventLog("Application");
// Display information about the event log
Console.WriteLine($"Reading events from the 'Application' log...");
// Iterate over the entries in the event log and filter by application name
foreach (EventLogEntry entry in eventLog.Entries)
{
if (entry.Source.Equals(applicationName, StringComparison.OrdinalIgnoreCase))
{
// Display information about the event
Console.WriteLine($"Event Type: {entry.EntryType}");
Console.WriteLine($"Event ID: {entry.InstanceId}");
Console.WriteLine($"Source: {entry.Source}");
Console.WriteLine($"Message: {entry.Message}");
Console.WriteLine($"Time Generated: {entry.TimeGenerated}");
Console.WriteLine();
}
}
// Close the event log
//eventLog.Close();
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}