/
ManagementObject.cs
2843 lines (2495 loc) · 120 KB
/
ManagementObject.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
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace System.Management
{
/// <summary>
/// Delegate definition for the IdentifierChanged event.
/// This event is used to signal the ManagementObject that an identifying property
/// has been changed. Identifying properties are the ones that identify the object,
/// namely the scope, path and options.
/// </summary>
internal delegate void IdentifierChangedEventHandler(object sender,
IdentifierChangedEventArgs e);
/// <summary>
/// Delegate definition for InternalObjectPut event. This is used so that
/// the WmiEventSink can signal to this object that the async Put call has
/// completed.
/// </summary>
internal delegate void InternalObjectPutEventHandler(object sender,
InternalObjectPutEventArgs e);
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Represents a data management object.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This example demonstrates reading a property of a ManagementObject.
/// class Sample_ManagementObject
/// {
/// public static int Main(string[] args) {
/// ManagementObject disk = new ManagementObject(
/// "win32_logicaldisk.deviceid=\"c:\"");
/// disk.Get();
/// Console.WriteLine("Logical Disk Size = " + disk["Size"] + " bytes");
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This example demonstrates reading a property of a ManagementObject.
/// Class Sample_ManagementObject
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim disk As New ManagementObject("win32_logicaldisk.deviceid=""c:""")
/// disk.Get()
/// Console.WriteLine(("Logical Disk Size = " & disk("Size").ToString() _
/// & " bytes"))
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
public class ManagementObject : ManagementBaseObject, ICloneable
{
// constants
internal const string ID = "ID";
internal const string RETURNVALUE = "RETURNVALUE";
//Fields
private IWbemClassObjectFreeThreaded wmiClass;
internal ManagementScope scope;
internal ManagementPath path;
internal ObjectGetOptions options;
//Used to represent whether this managementObject is currently bound to a wbemObject
//or not - whenever an "identifying" property is changed (Path, Scope...) the object
//is "detached" (isBound becomes false) so that we refresh the wbemObject next time
//it's used, in conformance with the new property values.
//
// ***
// * Changed isBound flag to wbemObject==null check.
// * private bool isBound;
// ***
//This is used to identify a state in which a Put() operation was performed, but the
//object was not retrieved again, so the WMI object that's available at this point
//cannot be used for certain operations, namely CreateInstance, GetSubclasses, Derive,
//Clone & ClassPath.
//When these operations are invoked, if we are in this state we need to implicitly
//get the object...
private bool putButNotGot;
//Event fired when any "identifying" property changes.
internal event IdentifierChangedEventHandler IdentifierChanged;
protected override void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public new void Dispose()
{
if (wmiClass != null)
{
wmiClass.Dispose();
wmiClass = null;
}
base.Dispose();
GC.SuppressFinalize(this);
}
//Fires IdentifierChanged event
internal void FireIdentifierChanged()
{
IdentifierChanged?.Invoke(this, null);
}
internal bool PutButNotGot
{
get
{ return putButNotGot; }
set
{ putButNotGot = value; }
}
//Called when IdentifierChanged() event fires
private void HandleIdentifierChange(object sender,
IdentifierChangedEventArgs e)
{
// Detach the object from the WMI object underneath
//
// ***
// * Changed isBound flag to wbemObject==null check.
// * isBound = false;
// ***
wbemObject = null;
}
internal bool IsBound
{
get
{ return _wbemObject != null; }
}
//internal constructor
internal static ManagementObject GetManagementObject(
IWbemClassObjectFreeThreaded wbemObject,
ManagementObject mgObj)
{
ManagementObject newObject = new ManagementObject();
newObject.wbemObject = wbemObject;
if (null != mgObj)
{
newObject.scope = ManagementScope._Clone(mgObj.scope);
if (null != mgObj.path)
newObject.path = ManagementPath._Clone(mgObj.path);
if (null != mgObj.options)
newObject.options = ObjectGetOptions._Clone(mgObj.options);
// We set isBound last since assigning to Scope, Path
// or Options can trigger isBound to be set false.
//
// ***
// * Changed isBound flag to wbemObject==null check.
// * newObject.isBound = mgObj.isBound;
// ***
}
return newObject;
}
internal static ManagementObject GetManagementObject(
IWbemClassObjectFreeThreaded wbemObject,
ManagementScope scope)
{
ManagementObject newObject = new ManagementObject();
newObject.wbemObject = wbemObject;
newObject.path = new ManagementPath(ManagementPath.GetManagementPath(wbemObject));
newObject.path.IdentifierChanged += new IdentifierChangedEventHandler(newObject.HandleIdentifierChange);
newObject.scope = ManagementScope._Clone(scope, new IdentifierChangedEventHandler(newObject.HandleIdentifierChange));
// Since we have an object, we should mark it as bound. Note
// that we do this AFTER setting Scope and Path, since those
// have side-effects of setting isBound=false.
//
// ***
// * Changed isBound flag to wbemObject==null check.
// * newObject.isBound = true;
// ***
return newObject;
}
//default constructor
/// <overload>
/// Initializes a new instance of the <see cref='System.Management.ManagementObject'/> class.
/// </overload>
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObject'/> class. This is the
/// default constructor.</para>
/// </summary>
/// <example>
/// <code lang='C#'>ManagementObject o = new ManagementObject();
///
/// //Now set the path on this object to bind it to a 'real' manageable entity
/// o.Path = new ManagementPath("Win32_LogicalDisk='c:'");
///
/// //Now it can be used
/// Console.WriteLine(o["FreeSpace"]);
/// </code>
/// <code lang='VB'>Dim o As New ManagementObject()
/// Dim mp As New ManagementPath("Win32_LogicalDisk='c:'")
///
/// 'Now set the path on this object to bind it to a 'real' manageable entity
/// o.Path = mp
///
/// 'Now it can be used
/// Console.WriteLine(o("FreeSpace"))
/// </code>
/// </example>
public ManagementObject() : this((ManagementScope)null, null, null) { }
//parameterized constructors
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObject'/> class for the specified WMI
/// object path. The path is provided as a <see cref='System.Management.ManagementPath'/>.</para>
/// </summary>
/// <param name='path'>A <see cref='System.Management.ManagementPath'/> that contains a path to a WMI object.</param>
/// <example>
/// <code lang='C#'>ManagementPath p = new ManagementPath("Win32_Service.Name='Alerter'");
/// ManagementObject o = new ManagementObject(p);
/// </code>
/// <code lang='VB'>Dim p As New ManagementPath("Win32_Service.Name=""Alerter""")
/// Dim o As New ManagementObject(p)
/// </code>
/// </example>
public ManagementObject(ManagementPath path) : this(null, path, null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObject'/> class for the specified WMI object path. The path
/// is provided as a string.</para>
/// </summary>
/// <param name='path'>A WMI path.</param>
/// <remarks>
/// <para>If the specified path is a relative path only (a server
/// or namespace is not specified), the default path is the local machine, and the
/// default namespace is the <see cref='System.Management.ManagementPath.DefaultPath'/>
/// path (by default, root\cimv2). If the user specifies a
/// full path, the default settings are overridden.</para>
/// </remarks>
/// <example>
/// <code lang='C#'>ManagementObject o = new ManagementObject("Win32_Service.Name='Alerter'");
///
/// //or with a full path :
///
/// ManagementObject o = new ManagementObject("\\\\MyServer\\root\\MyApp:MyClass.Key='abc'");
/// </code>
/// <code lang='VB'>Dim o As New ManagementObject("Win32_Service.Name=""Alerter""")
///
/// //or with a full path :
///
/// Dim o As New ManagementObject("\\\\MyServer\\root\\MyApp:MyClass.Key=""abc""");
/// </code>
/// </example>
public ManagementObject(string path) : this(null, new ManagementPath(path), null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObject'/> class bound to the specified
/// WMI path, including the specified additional options.</para>
/// </summary>
/// <param name='path'>A <see cref='System.Management.ManagementPath'/> containing the WMI path.</param>
/// <param name=' options'>An <see cref='System.Management.ObjectGetOptions'/> containing additional options for binding to the WMI object. This parameter could be null if default options are to be used.</param>
/// <example>
/// <code lang='C#'>ManagementPath p = new ManagementPath("Win32_ComputerSystem.Name='MyMachine'");
///
/// //Set options for no context info, but requests amended qualifiers
/// //to be contained in the object
/// ObjectGetOptions opt = new ObjectGetOptions(null, true);
///
/// ManagementObject o = new ManagementObject(p, opt);
///
/// Console.WriteLine(o.GetQualifierValue("Description"));
/// </code>
/// <code lang='VB'>Dim p As New ManagementPath("Win32_ComputerSystem.Name=""MyMachine""")
///
/// 'Set options for no context info, but requests amended qualifiers
/// 'to be contained in the object
/// Dim opt As New ObjectGetOptions(null, true)
///
/// Dim o As New ManagementObject(p, opt)
///
/// Console.WriteLine(o.GetQualifierValue("Description"));
/// </code>
/// </example>
public ManagementObject(ManagementPath path, ObjectGetOptions options) : this(null, path, options) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObject'/> class bound to the specified WMI path, including the
/// specified additional options. In this variant, the path can be specified as a
/// string.</para>
/// </summary>
/// <param name='path'>The WMI path to the object.</param>
/// <param name=' options'>An <see cref='System.Management.ObjectGetOptions'/> representing options to get the specified WMI object.</param>
/// <example>
/// <code lang='C#'>//Set options for no context info,
/// //but requests amended qualifiers to be contained in the object
/// ObjectGetOptions opt = new ObjectGetOptions(null, true);
///
/// ManagementObject o = new ManagementObject("Win32_ComputerSystem.Name='MyMachine'", opt);
///
/// Console.WriteLine(o.GetQualifierValue("Description"));
/// </code>
/// <code lang='VB'>'Set options for no context info,
/// 'but requests amended qualifiers to be contained in the object
/// Dim opt As New ObjectGetOptions(null, true)
///
/// Dim o As New ManagementObject("Win32_ComputerSystem.Name=""MyMachine""", opt);
///
/// Console.WriteLine(o.GetQualifierValue("Description"))
/// </code>
/// </example>
public ManagementObject(string path, ObjectGetOptions options) :
this(new ManagementPath(path), options)
{ }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementObject'/>
/// class bound to the specified WMI path that includes the specified options.</para>
/// </summary>
/// <param name='scope'>A <see cref='System.Management.ManagementScope'/> representing the scope in which the WMI object resides. In this version, scopes can only be WMI namespaces.</param>
/// <param name=' path'>A <see cref='System.Management.ManagementPath'/> representing the WMI path to the manageable object.</param>
/// <param name=' options'>An <see cref='System.Management.ObjectGetOptions'/> specifying additional options for getting the object.</param>
/// <remarks>
/// <para> Because WMI paths can be relative or full, a conflict between the scope and the path
/// specified may arise. However, if a scope is specified and
/// a relative WMI path is specified, then there is no conflict. The
/// following are some possible conflicts: </para>
/// <para> If a scope is not specified and a relative WMI
/// path is specified, then the scope will default to the local machine's <see cref='System.Management.ManagementPath.DefaultPath'/>. </para>
/// <para> If a scope is not specified and a full WMI path is
/// specified, then the scope will be inferred from the scope portion of the full
/// path. For example, the full WMI path: <c>\\MyMachine\root\MyNamespace:MyClass.Name='abc'</c> will
/// represent the WMI object 'MyClass.Name='abc'" in the scope
/// '\\MyMachine\root\MyNamespace'. </para>
/// If a scope is specified and a full WMI path is specified, then the scope
/// will override the scope portion of the full path. For example, if the following
/// scope was specified: \\MyMachine\root\MyScope, and the following full path was
/// specified: \\MyMachine\root\MyNamespace:MyClass.Name='abc', then look for the
/// following <c>object:
/// \\MyMachine\root\MyScope:MyClass.Name=
/// 'abc'</c>
/// (the scope part of the full path is ignored).
/// </remarks>
/// <example>
/// <code lang='C#'>ManagementScope s = new ManagementScope("\\\\MyMachine\\root\\cimv2");
/// ManagementPath p = new ManagementPath("Win32_LogicalDisk.Name='c:'");
/// ManagementObject o = new ManagementObject(s,p);
/// </code>
/// <code lang='VB'>Dim s As New ManagementScope("\\MyMachine\root\cimv2");
/// Dim p As New ManagementPath("Win32_LogicalDisk.Name=""c:""");
/// Dim o As New ManagementObject(s,p);
/// </code>
/// </example>
public ManagementObject(ManagementScope scope, ManagementPath path, ObjectGetOptions options)
: base(null)
{
ManagementObjectCTOR(scope, path, options);
}
private void ManagementObjectCTOR(ManagementScope scope, ManagementPath path, ObjectGetOptions options)
{
// We may use this to set the scope path
string nsPath = string.Empty;
if ((null != path) && !path.IsEmpty)
{
//If this is a ManagementObject then the path has to be an instance,
// and if this is a ManagementClass the path has to be a class.
if (GetType() == typeof(ManagementObject) && path.IsClass)
throw new ArgumentOutOfRangeException(nameof(path));
else if (GetType() == typeof(ManagementClass) && path.IsInstance)
throw new ArgumentOutOfRangeException(nameof(path));
// Save the namespace path portion of the path (if any) in case
// we don't have a scope
nsPath = path.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY);
if ((null != scope) && (scope.Path.NamespacePath.Length > 0))
{
// If the scope has a path too, the namespace portion of
// scope.path takes precedence over what is specified in path
path = new ManagementPath(path.RelativePath);
path.NamespacePath = scope.Path.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY);
}
// If the supplied path is a class or instance use it, otherwise
// leave it empty
if (path.IsClass || path.IsInstance)
this.path = ManagementPath._Clone(path, new IdentifierChangedEventHandler(HandleIdentifierChange));
else
this.path = ManagementPath._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange));
}
if (null != options)
this.options = ObjectGetOptions._Clone(options, new IdentifierChangedEventHandler(HandleIdentifierChange));
if (null != scope)
this.scope = ManagementScope._Clone(scope, new IdentifierChangedEventHandler(HandleIdentifierChange));
else
{
// Use the path if possible, otherwise let it default
if (nsPath.Length > 0)
{
this.scope = new ManagementScope(nsPath);
this.scope.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
}
}
//register for identifier change events
IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
// ***
// * Changed isBound flag to wbemObject==null check.
// * isBound = false;
// ***
putButNotGot = false;
}
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementObject'/> class
/// bound to the specified WMI path, and includes the specified options. The scope and
/// the path are specified as strings.</para>
/// </summary>
/// <param name='scopeString'>The scope for the WMI object.</param>
/// <param name=' pathString'>The WMI object path.</param>
/// <param name=' options'>An <see cref='System.Management.ObjectGetOptions'/> representing additional options for getting the WMI object.</param>
/// <remarks>
/// <para>See the equivalent overload for details.</para>
/// </remarks>
/// <example>
/// <code lang='C#'>GetObjectOptions opt = new GetObjectOptions(null, true);
/// ManagementObject o = new ManagementObject("root\\MyNamespace", "MyClass.Name='abc'", opt);
/// </code>
/// <code lang='VB'>Dim opt As New GetObjectOptions(null, true)
/// Dim o As New ManagementObject("root\MyNamespace", "MyClass.Name=""abc""", opt);
/// </code>
/// </example>
public ManagementObject(string scopeString, string pathString, ObjectGetOptions options)
: this(new ManagementScope(scopeString), new ManagementPath(pathString), options) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObject'/> class that is serializable.</para>
/// </summary>
/// <param name='info'>The <see cref='System.Runtime.Serialization.SerializationInfo'/> to populate with data.</param>
/// <param name='context'>The destination (see <see cref='System.Runtime.Serialization.StreamingContext'/> ) for this serialization.</param>
protected ManagementObject(SerializationInfo info, StreamingContext context) : base(info, context)
{
ManagementObjectCTOR(null, null, null);
}
/// <summary>
/// <para> Gets or sets the scope in which this object resides.</para>
/// </summary>
/// <value>
/// <para> A <see cref='System.Management.ManagementScope'/>.</para>
/// </value>
/// <remarks>
/// <para>
/// Changing
/// this property after the management object has been bound to a WMI object in
/// a particular namespace results in releasing the original WMI object. This causes the management object to
/// be rebound to the new object specified by the new path properties and scope
/// values. </para>
/// <para>The rebinding is performed in a "lazy" manner, that is, only when a requested
/// value requires the management object to be bound to the WMI object. Changes can
/// be made to more than just this property before attempting to rebind (for example, modifying the scope
/// and path properties simultaneously).</para>
/// </remarks>
/// <example>
/// <code lang='C#'>//Create the object with the default namespace (root\cimv2)
/// ManagementObject o = new ManagementObject();
///
/// //Change the scope (=namespace) of this object to the one specified.
/// o.Scope = new ManagementScope("root\\MyAppNamespace");
/// </code>
/// <code lang='VB'>'Create the object with the default namespace (root\cimv2)
/// Dim o As New ManagementObject()
///
/// 'Change the scope (=namespace) of this object to the one specified.
/// o.Scope = New ManagementScope("root\MyAppNamespace")
/// </code>
/// </example>
public ManagementScope Scope
{
get
{
return scope ??= ManagementScope._Clone(null);
}
set
{
if (null != value)
{
if (null != scope)
scope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
scope = ManagementScope._Clone((ManagementScope)value, new IdentifierChangedEventHandler(HandleIdentifierChange));
//the scope property has changed so fire event
FireIdentifierChanged();
}
else
throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// <para> Gets or sets the object's WMI path.</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Management.ManagementPath'/> representing the object's path.</para>
/// </value>
/// <remarks>
/// <para>
/// Changing the property after the management
/// object has been bound to a WMI object in a particular namespace results in releasing
/// the original WMI object. This causes the management object to be rebound to
/// the new object specified by the new path properties and scope values.</para>
/// <para>The rebinding is performed in a "lazy" manner, that is, only when a requested
/// value requires the management object to be bound to the WMI object. Changes can
/// be made to more than just the property before attempting to rebind (for example,
/// modifying the scope and path properties simultaneously).</para>
/// </remarks>
/// <example>
/// <code lang='C#'>ManagementObject o = new ManagementObject();
///
/// //Specify the WMI path to which this object should be bound to
/// o.Path = new ManagementPath("MyClass.Name='MyName'");
/// </code>
/// <code lang='VB'>Dim o As New ManagementObject()
///
/// 'Specify the WMI path to which this object should be bound to
/// o.Path = New ManagementPath("MyClass.Name=""MyName""");
/// </code>
/// </example>
public virtual ManagementPath Path
{
get
{
return path ??= ManagementPath._Clone(null);
}
set
{
ManagementPath newPath = value ?? new ManagementPath();
//If the new path contains a namespace path and the scope is currently defaulted,
//we want to set the scope to the new namespace path provided
string nsPath = newPath.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY);
if ((nsPath.Length > 0) && (scope != null) && (scope.IsDefaulted))
Scope = new ManagementScope(nsPath);
// This must be a class for a ManagementClass object or an instance for a ManagementObject, or empty
if ((GetType() == typeof(ManagementObject) && newPath.IsInstance) ||
(GetType() == typeof(ManagementClass) && newPath.IsClass) ||
newPath.IsEmpty)
{
if (null != path)
path.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
path = ManagementPath._Clone((ManagementPath)value, new IdentifierChangedEventHandler(HandleIdentifierChange));
//the path property has changed so fire event
FireIdentifierChanged();
}
else
throw new ArgumentOutOfRangeException(nameof(value));
}
}
/// <summary>
/// <para>
/// Gets or
/// sets additional information to use when retrieving the object.</para>
/// </summary>
/// <value>
/// <para>An <see cref='System.Management.ObjectGetOptions'/> to use when retrieving the object.</para>
/// </value>
/// <remarks>
/// <para> When the property is
/// changed after the management object has been bound to a WMI object, the management object
/// is disconnected from the original WMI object and later rebound using the new
/// options.</para>
/// </remarks>
/// <example>
/// <code lang='C#'>//Contains default options
/// ManagementObject o = new ManagementObject("MyClass.Name='abc'");
///
/// //Replace default options, in this case requesting retrieval of
/// //amended qualifiers along with the WMI object.
/// o.Options = new ObjectGetOptions(null, true);
/// </code>
/// <code lang='VB'>'Contains default options
/// Dim o As New ManagementObject("MyClass.Name=""abc""")
///
/// 'Replace default options, in this case requesting retrieval of
/// 'amended qualifiers along with the WMI object.
/// o.Options = New ObjectGetOptions(null, true)
/// </code>
/// </example>
public ObjectGetOptions Options
{
get
{
return options ??= ObjectGetOptions._Clone(null);
}
set
{
if (null != value)
{
if (null != options)
options.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
options = ObjectGetOptions._Clone((ObjectGetOptions)value, new IdentifierChangedEventHandler(HandleIdentifierChange));
//the options property has changed so fire event
FireIdentifierChanged();
}
else
throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// <para>Gets or sets the path to the object's class.</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Management.ManagementPath'/> representing the path to the object's
/// class.</para>
/// </value>
/// <remarks>
/// <para>This property is read-only.</para>
/// </remarks>
/// <example>
/// <code lang='C#'>ManagementObject o = new ManagementObject("MyClass.Name='abc'");
///
/// //Get the class definition for the object above.
/// ManagementClass c = new ManagementClass(o.ClassPath);
/// </code>
/// <code lang='VB'>Dim o As New ManagementObject("MyClass.Name=""abc""")
///
/// 'Get the class definition for the object above.
/// Dim c As New ManagementClass(o.ClassPath);
/// </code>
/// </example>
public override ManagementPath ClassPath
{
get
{
object serverName = null;
object scopeName = null;
object className = null;
int propertyType = 0;
int propertyFlavor = 0;
if (PutButNotGot)
{
Get();
PutButNotGot = false;
}
int status = wbemObject.Get_("__SERVER", 0, ref serverName, ref propertyType, ref propertyFlavor);
if (status >= 0)
{
status = wbemObject.Get_("__NAMESPACE", 0, ref scopeName, ref propertyType, ref propertyFlavor);
if (status >= 0)
{
status = wbemObject.Get_("__CLASS", 0, ref className, ref propertyType, ref propertyFlavor);
}
}
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
ManagementPath classPath = new ManagementPath();
// initialize in case of throw
classPath.Server = string.Empty;
classPath.NamespacePath = string.Empty;
classPath.ClassName = string.Empty;
// Some of these may throw if they are NULL
try
{
classPath.Server = (string)(serverName is System.DBNull ? "" : serverName);
classPath.NamespacePath = (string)(scopeName is System.DBNull ? "" : scopeName);
classPath.ClassName = (string)(className is System.DBNull ? "" : className);
}
catch
{
}
return classPath;
}
}
//
//Methods
//
//******************************************************
//Get
//******************************************************
/// <overload>
/// Binds to the management object.
/// </overload>
/// <summary>
/// <para> Binds to the management object.</para>
/// </summary>
/// <remarks>
/// <para> The method is implicitly
/// invoked at the first attempt to get or set information to the WMI object. It
/// can also be explicitly invoked at the user's discretion, to better control the
/// timing and manner of retrieval.</para>
/// </remarks>
/// <example>
/// <code lang='C#'>ManagementObject o = new ManagementObject("MyClass.Name='abc'");
/// string s = o["SomeProperty"]; //this causes an implicit Get().
///
/// //or :
///
/// ManagementObject o= new ManagementObject("MyClass.Name= 'abc'");
/// o.Get(); //explicitly
/// //Now it's faster because the object has already been retrieved.
/// string s = o["SomeProperty"];
/// </code>
/// <code lang='VB'>Dim o As New ManagementObject("MyClass.Name=""abc""")
/// string s = o("SomeProperty") 'this causes an implicit Get().
///
/// 'or :
///
/// Dim o As New ManagementObject("MyClass.Name= ""abc""")
/// o.Get() 'explicitly
/// 'Now it's faster because the object has already been retrieved.
/// string s = o("SomeProperty");
/// </code>
/// </example>
public void Get()
{
IWbemClassObjectFreeThreaded tempObj = null;
Initialize(false); // this may throw
if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
else
{
ObjectGetOptions gOptions = options ?? new ObjectGetOptions();
SecurityHandler securityHandler = null;
int status = (int)ManagementStatus.NoError;
try
{
securityHandler = scope.GetSecurityHandler();
status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).GetObject_(path.RelativePath,
gOptions.Flags,
gOptions.GetContext(),
ref tempObj,
IntPtr.Zero);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
wbemObject = tempObj;
}
finally
{
securityHandler?.Reset();
}
}
}
//******************************************************
//Get
//******************************************************
/// <summary>
/// <para> Binds to the management object asynchronously.</para>
/// </summary>
/// <param name='watcher'>The object to receive the results of the operation as events.</param>
/// <remarks>
/// <para>The method will issue the request to get the object
/// and then will immediately return. The results of the operation will then be
/// delivered through events being fired on the watcher object provided.</para>
/// </remarks>
/// <example>
/// <code lang='C#'>ManagementObject o = new ManagementObject("MyClass.Name='abc'");
///
/// //Set up handlers for asynchronous get
/// MyHandler h = new MyHandler();
/// ManagementOperationObserver ob = new ManagementOperationObserver();
/// ob.Completed += new CompletedEventHandler(h.Done);
///
/// //Get the object asynchronously
/// o.Get(ob);
///
/// //Wait until operation is completed
/// while (!h.Completed)
/// System.Threading.Thread.Sleep (1000);
///
/// //Here we can use the object
/// Console.WriteLine(o["SomeProperty"]);
///
/// public class MyHandler
/// {
/// private bool completed = false;
///
/// public void Done(object sender, CompletedEventArgs e) {
/// Console.WriteLine("async Get completed !");
/// completed = true;
/// }
///
/// public bool Completed {
/// get {
/// return completed;
/// }
/// }
/// }
/// </code>
/// <code lang='VB'>Dim o As New ManagementObject("MyClass.Name=""abc""")
///
/// 'Set up handlers for asynchronous get
/// Dim h As New MyHandler()
/// Dim ob As New ManagementOperationObserver()
/// ob.Completed += New CompletedEventHandler(h.Done)
///
/// 'Get the object asynchronously
/// o.Get(ob)
///
/// 'Wait until operation is completed
/// While Not h.Completed
/// System.Threading.Thread.Sleep(1000)
/// End While
///
/// 'Here we can use the object
/// Console.WriteLine(o("SomeProperty"))
///
/// Public Class MyHandler
/// Private _completed As Boolean = false;
///
/// Public Sub Done(sender As Object, e As EventArrivedEventArgs)
/// Console.WriteLine("async Get completed !")
/// _completed = True
/// End Sub
///
/// Public ReadOnly Property Completed() As Boolean
/// Get
/// Return _completed
/// End Get
/// End Property
/// End Class
/// </code>
/// </example>
public void Get(ManagementOperationObserver watcher)
{
Initialize(false);
if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
else if (null == watcher)
throw new ArgumentNullException(nameof(watcher));
else
{
IWbemServices wbemServices = scope.GetIWbemServices();
ObjectGetOptions o = ObjectGetOptions._Clone(options);
WmiGetEventSink sink = watcher.GetNewGetSink(
scope,
o.Context,
this);
// If someone has registered for progress, make sure we flag it
if (watcher.HaveListenersForProgress)
o.SendStatus = true;
SecurityHandler securityHandler = null;
int status = (int)ManagementStatus.NoError;
securityHandler = scope.GetSecurityHandler();
status = scope.GetSecuredIWbemServicesHandler(wbemServices).GetObjectAsync_(path.RelativePath,
o.Flags,
o.GetContext(),
sink.Stub);
securityHandler?.Reset();
if (status < 0)
{
watcher.RemoveSink(sink);
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
}
//******************************************************
//GetRelated
//****************************************************
/// <overload>
/// <para>Gets a collection of objects related to the object (associators).</para>
/// </overload>
/// <summary>
/// <para>Gets a collection of objects related to the object (associators).</para>
/// </summary>
/// <returns>
/// <para>A <see cref='System.Management.ManagementObjectCollection'/> containing the
/// related objects.</para>
/// </returns>
/// <remarks>
/// <para> The operation is equivalent to an ASSOCIATORS OF query where ResultClass = relatedClass.</para>
/// </remarks>
/// <example>
/// <code lang='C#'>ManagementObject o = new ManagementObject("Win32_Service='Alerter'");
/// foreach (ManagementBaseObject b in o.GetRelated())
/// Console.WriteLine("Object related to Alerter service : ", b.Path);
/// </code>
/// <code lang='VB'>Dim o As New ManagementObject("Win32_Service=""Alerter""")
/// Dim b As ManagementBaseObject
/// For Each b In o.GetRelated()
/// Console.WriteLine("Object related to Alerter service : ", b.Path)
/// Next b
/// </code>
/// </example>
public ManagementObjectCollection GetRelated()
{
return GetRelated((string)null);
}
//******************************************************
//GetRelated
//****************************************************
/// <summary>
/// <para>Gets a collection of objects related to the object (associators).</para>
/// </summary>
/// <param name='relatedClass'>A class of related objects. </param>
/// <returns>
/// A <see cref='System.Management.ManagementObjectCollection'/> containing the related objects.
/// </returns>
/// <example>
/// <code lang='C#'>ManagementObject o = new ManagementObject("Win32_Service='Alerter'");
/// foreach (ManagementBaseObject b in o.GetRelated("Win32_Service")
/// Console.WriteLine("Service related to the Alerter service {0} is {1}", b["Name"], b["State"]);
/// </code>
/// <code lang='VB'>Dim o As New ManagementObject("Win32_Service=""Alerter""");
/// Dim b As ManagementBaseObject
/// For Each b in o.GetRelated("Win32_Service")
/// Console.WriteLine("Service related to the Alerter service {0} is {1}", b("Name"), b("State"))
/// Next b
/// </code>
/// </example>
public ManagementObjectCollection GetRelated(
string relatedClass)
{
return GetRelated(relatedClass, null, null, null, null, null, false, null);
}
//******************************************************
//GetRelated
//****************************************************
/// <summary>
/// <para>Gets a collection of objects related to the object (associators).</para>
/// </summary>
/// <param name='relatedClass'>The class of the related objects. </param>
/// <param name='relationshipClass'>The relationship class of interest. </param>
/// <param name='relationshipQualifier'>The qualifier required to be present on the relationship class. </param>