-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathApplicationBase.cs
More file actions
634 lines (608 loc) · 20.4 KB
/
Copy pathApplicationBase.cs
File metadata and controls
634 lines (608 loc) · 20.4 KB
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
using BytecodeApi.Extensions;
using BytecodeApi.IO;
using BytecodeApi.IO.Wmi;
using BytecodeApi.Mathematics;
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
namespace BytecodeApi
{
/// <summary>
/// Provides <see langword="static" /> methods that extend the <see cref="Application" /> and the <see cref="System.Windows.Forms.Application" /> class.
/// </summary>
public static class ApplicationBase
{
private static Version _Version;
private static bool? _DebugMode;
/// <summary>
/// Gets the path for the executable file that started the application, not including the executable name.
/// </summary>
public static string Path => System.Windows.Forms.Application.StartupPath;
/// <summary>
/// Gets the path for the executable file that started the application, including the executable name.
/// </summary>
public static string FileName => System.Windows.Forms.Application.ExecutablePath;
/// <summary>
/// Gets the <see cref="System.Version" /> of the entry assembly.
/// </summary>
public static Version Version
{
get
{
if (_Version == null) _Version = Assembly.GetEntryAssembly().GetName().Version;
return _Version;
}
}
/// <summary>
/// Gets a <see cref="bool" /> value indicating whether <see cref="Debugger.IsAttached" /> was <see langword="true" /> the first time this property is retrieved, or if this executable is located in a directory named like "\bin\Debug", "\bin\x86\Debug", or "\bin\x64\Debug".
/// </summary>
public static bool DebugMode
{
get
{
if (_DebugMode == null) _DebugMode = Debugger.IsAttached || new[] { @"\bin\Debug", @"\bin\x86\Debug", @"\bin\x64\Debug" }.Any(path => Path.Contains(path + @"\", SpecialStringComparisons.IgnoreCase) || Path.EndsWith(path, SpecialStringComparisons.IgnoreCase));
return _DebugMode.Value;
}
}
/// <summary>
/// Invokes an empty <see cref="Action" /> on the <see cref="Dispatcher" /> of <see cref="Application.Current" /> while <paramref name="condition" /> evaluates to <see langword="true" />, thereby refreshing the UI. This is the WPF equivalent to <see cref="System.Windows.Forms.Application.DoEvents" />.
/// </summary>
/// <param name="condition">The <see cref="Func{TResult}" /> to be evaluated.</param>
public static void DoEventsWhile(Func<bool> condition)
{
DoEventsWhile(condition, TimeSpan.FromMilliseconds(1));
}
/// <summary>
/// Invokes an empty <see cref="Action" /> on the <see cref="Dispatcher" /> of <see cref="Application.Current" /> while <paramref name="condition" /> evaluates to <see langword="true" />, thereby refreshing the UI. This is the WPF equivalent to <see cref="System.Windows.Forms.Application.DoEvents" />. The specified delay is waited between each call to <paramref name="condition" />.
/// </summary>
/// <param name="condition">The <see cref="Func{TResult}" /> to be evaluated.</param>
/// <param name="delay">A <see cref="TimeSpan" /> that specifies the delay between each call to <paramref name="condition" />. The default value is 1 milliseconds.</param>
public static void DoEventsWhile(Func<bool> condition, TimeSpan delay)
{
Check.ArgumentNull(condition, nameof(condition));
Check.ArgumentOutOfRangeEx.GreaterEqual0(delay, nameof(delay));
do
{
Thread.Sleep(delay);
Application.Current.Dispatcher.Invoke(delegate { }, DispatcherPriority.Background);
}
while (condition());
}
/// <summary>
/// Restarts the current <see cref="System.Diagnostics.Process" /> with elevated privileges. Returns <see langword="null" />, if the process is already elevated; <see langword="false" />, if elevation failed; <see langword="true" /> if the restart was successful.
/// </summary>
/// <param name="commandLine">A <see cref="string" /> specifying the commandline for the new <see cref="System.Diagnostics.Process" />.</param>
/// <param name="shutdownCallback">A callback that is invoked after the new <see cref="System.Diagnostics.Process" /> was successfully started with elevated privileges. Depending on application type, this is typically <see cref="Environment.Exit(int)" /> or <see cref="Application.Shutdown()" />.</param>
/// <returns>
/// <see langword="null" />, if the process is already elevated;
/// <see langword="false" />, if elevation failed;
/// <see langword="true" />, if the restart was successful.
/// </returns>
public static bool? RestartElevated(string commandLine, Action shutdownCallback)
{
if (Process.IsElevated)
{
return null;
}
else
{
try
{
System.Diagnostics.Process.Start(new ProcessStartInfo(FileName, commandLine) { Verb = "runas" });
shutdownCallback?.Invoke();
return true;
}
catch
{
return false;
}
}
}
/// <summary>
/// Provides information about the current process.
/// </summary>
public static class Process
{
private static int? _Id;
private static int? _SessionId;
private static ProcessIntegrityLevel? _IntegrityLevel;
private static bool? _IsElevated;
private static ElevationType? _ElevationType;
private static Version _FrameworkVersion;
/// <summary>
/// Gets the ProcessID of the current <see cref="System.Diagnostics.Process" />.
/// </summary>
public static int Id
{
get
{
if (_Id == null)
{
using (System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess())
{
_Id = process.Id;
}
}
return _Id.Value;
}
}
/// <summary>
/// Gets the SessionID of the current <see cref="System.Diagnostics.Process" />.
/// </summary>
public static int SessionId
{
get
{
if (_SessionId == null)
{
using (System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess())
{
_SessionId = process.SessionId;
}
}
return _SessionId.Value;
}
}
/// <summary>
/// Gets the mandatory integrity level for the current <see cref="System.Diagnostics.Process" />.
/// </summary>
public static ProcessIntegrityLevel IntegrityLevel
{
get
{
if (_IntegrityLevel == null)
{
using (System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess())
{
_IntegrityLevel = process.GetIntegrityLevel();
}
}
return _IntegrityLevel ?? throw Throw.Win32();
}
}
/// <summary>
/// Gets a <see cref="bool" /> value indicating whether the current <see cref="System.Diagnostics.Process" /> is elevated or not.
/// </summary>
public static bool IsElevated
{
get
{
if (_IsElevated == null)
{
using (WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent())
{
_IsElevated = new WindowsPrincipal(windowsIdentity).IsInRole(WindowsBuiltInRole.Administrator);
}
}
return _IsElevated.Value;
}
}
/// <summary>
/// Gets the <see cref="ElevationType" /> for the current <see cref="System.Diagnostics.Process" />.
/// </summary>
public static ElevationType ElevationType
{
get
{
if (_ElevationType == null)
{
IntPtr token;
using (System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess())
{
token = process.OpenToken(8);
}
if (token != IntPtr.Zero)
{
try
{
IntPtr elevationTypePtr = Marshal.AllocHGlobal(4);
try
{
if (Native.GetTokenInformation(token, 18, elevationTypePtr, 4, out int returnLength) && returnLength == 4)
{
_ElevationType = (ElevationType)Marshal.ReadInt32(elevationTypePtr);
}
}
finally
{
Marshal.FreeHGlobal(elevationTypePtr);
}
}
finally
{
Native.CloseHandle(token);
}
}
}
return _ElevationType ?? throw Throw.Win32();
}
}
/// <summary>
/// Gets the amount of private memory, in bytes, allocated for the current <see cref="System.Diagnostics.Process" />.
/// </summary>
public static long Memory
{
get
{
using (System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess())
{
return process.PrivateMemorySize64;
}
}
}
/// <summary>
/// Gets the <see cref="System.Version" /> of the .NET Framework that the current <see cref="System.Diagnostics.Process" /> is running with.
/// </summary>
public static Version FrameworkVersion
{
get
{
if (_FrameworkVersion == null) _FrameworkVersion = new Version(typeof(object).Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version);
return _FrameworkVersion;
}
}
}
/// <summary>
/// Provides information about the current logon session and related information.
/// </summary>
public static class Session
{
private static string _CurrentUser;
private static string _DomainName;
private static string _Workgroup;
private static bool? _IsWorkstationLocked;
private static bool? _IsRdp;
/// <summary>
/// Gets the name of the current <see cref="WindowsIdentity" />, including the domain or workstation name.
/// </summary>
public static string CurrentUser
{
get
{
if (_CurrentUser == null) _CurrentUser = WindowsIdentity.GetCurrent().Name;
return _CurrentUser;
}
}
/// <summary>
/// Gets the name of the current <see cref="WindowsIdentity" />, not including the domain or workstation name.
/// </summary>
public static string CurrentUserShort => CurrentUser.SubstringFrom(@"\", true);
/// <summary>
/// Gets the domain in which the local computer is registered, or <see langword="null" />, if the user is not member of a domain.
/// </summary>
public static string DomainName
{
get
{
if (_DomainName == null) _DomainName = IPGlobalProperties.GetIPGlobalProperties().DomainName.ToNullIfEmpty();
return _DomainName;
}
}
/// <summary>
/// Gets the workgroup in which the local computer is registered, or <see langword="null" />, if the user is not member of a workgroup.
/// </summary>
public static string Workgroup
{
get
{
if (_Workgroup == null)
{
_Workgroup = new WmiNamespace("CIMV2", false, false)
.GetClass("Win32_ComputerSystem", false)
.GetObjects("Workgroup")
.First()
.Properties["Workgroup"]
.GetValue<string>()
?.Trim()
.ToNullIfEmpty();
}
return _Workgroup;
}
}
/// <summary>
/// Gets a <see cref="bool" /> value indicating whether the workstation is locked. The application is required to have a message loop, such as in a WPF or WinForms project.
/// </summary>
public static bool IsWorkstationLocked
{
get
{
if (_IsWorkstationLocked == null)
{
_IsWorkstationLocked = false; //IMPORTANT: Bug: Wrongfully returns false, if workstation was locked when application started.
SystemEvents.SessionSwitch += delegate (object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock) _IsWorkstationLocked = true;
else if (e.Reason == SessionSwitchReason.SessionUnlock) _IsWorkstationLocked = false;
};
}
return _IsWorkstationLocked.Value;
}
}
/// <summary>
/// Gets the screen DPI. A value of 96.0 corresponds to 100% font scaling.
/// </summary>
public static SizeF DesktopDpi
{
get
{
IntPtr desktop = IntPtr.Zero;
try
{
desktop = Native.GetDC(IntPtr.Zero);
using (Graphics graphics = Graphics.FromHdc(desktop))
{
return new SizeF(graphics.DpiX, graphics.DpiY);
}
}
finally
{
if (desktop != IntPtr.Zero) Native.ReleaseDC(IntPtr.Zero, desktop);
}
}
}
/// <summary>
/// Gets a <see cref="bool" /> value indicating whether the current session is an RDP session.
/// </summary>
public static bool IsRdp
{
get
{
if (_IsRdp == null) _IsRdp = Environment.GetEnvironmentVariable("SESSIONNAME").StartsWith("RDP-", StringComparison.OrdinalIgnoreCase);
return _IsRdp.Value;
}
}
}
/// <summary>
/// Provides information about the installed operating system.
/// </summary>
public static class OperatingSystem
{
//FEATURE: Major & Minor version
private static string _Name;
private static DateTime? _InstallDate;
private static string[] _InstalledAntiVirusSoftware;
private static int? _FrameworkVersionNumber;
/// <summary>
/// Gets the name of the operating system.
/// <para>Examples: "Windows 7 Professional", "Windows 10 Pro"</para>
/// </summary>
public static string Name
{
get
{
if (_Name == null)
{
_Name = new WmiNamespace("CIMV2", false, false)
.GetClass("Win32_OperatingSystem", false)
.GetObjects("Caption")
.First()
.Properties["Caption"]
.GetValue<string>()
.SubstringFrom("Microsoft ")
.Trim();
}
return _Name;
}
}
/// <summary>
/// Gets the installation date of the operating system, or <see langword="null" />, if it could not be determined.
/// </summary>
public static DateTime? InstallDate
{
get
{
if (_InstallDate == null)
{
using (RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
using (RegistryKey key = baseKey.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion"))
{
int installDate = key.GetInt32Value("InstallDate", 0);
_InstallDate = installDate == 0 ? (DateTime?)null : DateTimeEx.ConvertUnixTimeStamp((uint)installDate);
}
}
return _InstallDate;
}
}
/// <summary>
/// Gets an array containing a list of installed antivirus software.
/// </summary>
public static string[] InstalledAntiVirusSoftware
{
get
{
if (_InstalledAntiVirusSoftware == null)
{
_InstalledAntiVirusSoftware = new WmiNamespace("SecurityCenter2", false, false)
.GetClass("AntiVirusProduct", false)
.GetObjects("displayName")
.Select(obj => obj.Properties["displayName"].GetValue<string>())
.Where(item => !item.IsNullOrEmpty())
.ToArray();
}
return _InstalledAntiVirusSoftware;
}
}
/// <summary>
/// Gets the default browser of the current user, or <see langword="null" />, if it could not be determined.
/// </summary>
public static KnownBrowser? DefaultBrowser
{
get
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice"))
{
if (key?.GetStringValue("Progid") is string program)
{
if (program.Equals("IE.HTTP", StringComparison.OrdinalIgnoreCase)) return KnownBrowser.InternetExplorer;
else if (program == "AppXq0fevzme2pys62n3e0fbqa7peapykr8v") return KnownBrowser.Edge;
else if (program.Equals("ChromeHTML", StringComparison.OrdinalIgnoreCase)) return KnownBrowser.Chrome;
else if (program.StartsWith("FirefoxURL", StringComparison.OrdinalIgnoreCase)) return KnownBrowser.Firefox;
else if (program.StartsWith("Opera", StringComparison.OrdinalIgnoreCase) || program.StartsWith("OperaStable", StringComparison.OrdinalIgnoreCase)) return KnownBrowser.Opera;
else if (program.StartsWith("Safari", StringComparison.OrdinalIgnoreCase) || program.StartsWith("SafariHTML", StringComparison.OrdinalIgnoreCase)) return KnownBrowser.Safari;
}
}
using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command"))
{
string browser = key
?.GetStringValue(null)
.Replace("\"", null)
.SubstringUntil(".exe", false, false, true)
.SubstringFrom(@"\", true)
.Trim()
.ToLower();
if (browser != null)
{
switch (browser)
{
case "iexplore": return KnownBrowser.InternetExplorer;
case "chrome": return KnownBrowser.Chrome;
case "firefox": return KnownBrowser.Firefox;
case "launcher": return KnownBrowser.Opera;
default: return null;
}
}
}
return null;
}
}
/// <summary>
/// Gets the currently installed version of the .NET Framework and returns the version number. Works for .NET 4.5+.
/// <para>Examples: 528049, 528040, 461814</para>
/// </summary>
public static int? FrameworkVersionNumber
{
get
{
if (_FrameworkVersionNumber == null)
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"))
{
_FrameworkVersionNumber = key.GetInt32Value("Release");
}
}
return _FrameworkVersionNumber;
}
}
/// <summary>
/// Gets the currently installed version of the .NET Framework, deduced from the <see cref="FrameworkVersionNumber" /> property and <see langword="null" />, if the version name could not be determined. Works for .NET 4.5+.
/// <para>Examples: 4.5, 4.6, 4.7, 4.7.1, 4.7.2, 4.8</para>
/// </summary>
public static string FrameworkVersionName
{
get
{
// Version numbers: https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies
//TODO: Find algorithm, where code changes are not needed, when new version is released
switch (FrameworkVersionNumber)
{
case 378389:
return "4.5";
case 378675:
case 378758:
return "4.5.1";
case 379893:
return "4.5.2";
case 393295:
case 393297:
return "4.6";
case 394254:
case 394271:
return "4.6.1";
case 394802:
case 394806:
return "4.6.2";
case 460798:
case 460805:
return "4.7";
case 461308:
case 461310:
return "4.7.1";
case 461808:
case 461814:
return "4.7.2";
case 528040:
case 528049:
case 528372:
case 528449:
return "4.8";
default:
return null;
}
}
}
}
/// <summary>
/// Provides information about installed hardware.
/// </summary>
public static class Hardware
{
private static string _Processor;
private static long? _Memory;
private static string _VideoController;
/// <summary>
/// Gets the name of the processor. If multiple processors are installed, the name of the first processor is returned.
/// </summary>
public static string Processor
{
get
{
if (_Processor == null)
{
_Processor = new WmiNamespace("CIMV2", false, false)
.GetClass("Win32_Processor", false)
.GetObjects("Name")
.First()
.Properties["Name"]
.GetValue<string>()
.Trim();
}
return _Processor;
}
}
/// <summary>
/// Gets the total amount of installed physical memory, or <see langword="null" />, if it could not be determined.
/// </summary>
public static long? Memory
{
get
{
if (_Memory == null)
{
Native.MemoryStatusEx memoryStatus = new Native.MemoryStatusEx();
_Memory = Native.GlobalMemoryStatusEx(memoryStatus) ? (long)memoryStatus.TotalPhys : (long?)null;
}
return _Memory;
}
}
/// <summary>
/// Gets the name of the video controller. If multiple video controllers are installed, the name of the first video controller is returned.
/// </summary>
public static string VideoController
{
get
{
if (_VideoController == null)
{
_VideoController = new WmiNamespace("CIMV2", false, false)
.GetClass("Win32_VideoController", false)
.GetObjects("Name")
.First()
.Properties["Name"]
.GetValue<string>()
.Trim();
}
return _VideoController;
}
}
}
}
}