/
ManagementObjectCollection.cs
647 lines (565 loc) · 25.8 KB
/
ManagementObjectCollection.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Runtime.InteropServices;
namespace System.Management
{
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Represents different collections of management objects
/// retrieved through WMI. The objects in this collection are of <see cref='System.Management.ManagementBaseObject'/>-derived types, including <see cref='System.Management.ManagementObject'/> and <see cref='System.Management.ManagementClass'/>
/// .</para>
/// <para> The collection can be the result of a WMI
/// query executed through a <see cref='System.Management.ManagementObjectSearcher'/> object, or an enumeration of
/// management objects of a specified type retrieved through a <see cref='System.Management.ManagementClass'/> representing that type.
/// In addition, this can be a collection of management objects related in a specified
/// way to a specific management object - in this case the collection would
/// be retrieved through a method such as <see cref='System.Management.ManagementObject.GetRelated()'/>.</para>
/// <para>The collection can be walked using the <see cref='System.Management.ManagementObjectCollection.ManagementObjectEnumerator'/> and objects in it can be inspected or
/// manipulated for various management tasks.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This example demonstrates how to enumerate instances of a ManagementClass object.
/// class Sample_ManagementObjectCollection
/// {
/// public static int Main(string[] args) {
/// ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
/// ManagementObjectCollection disks = diskClass.GetInstances();
/// foreach (ManagementObject disk in disks) {
/// Console.WriteLine("Disk = " + disk["deviceid"]);
/// }
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This example demonstrates how to enumerate instances of a ManagementClass object.
/// Class Sample_ManagementObjectCollection
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim diskClass As New ManagementClass("Win32_LogicalDisk")
/// Dim disks As ManagementObjectCollection = diskClass.GetInstances()
/// Dim disk As ManagementObject
/// For Each disk In disks
/// Console.WriteLine("Disk = " & disk("deviceid").ToString())
/// Next disk
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
public class ManagementObjectCollection : ICollection, IEnumerable, IDisposable
{
private static readonly string name = typeof(ManagementObjectCollection).FullName;
//fields
internal ManagementScope scope;
internal EnumerationOptions options;
private readonly IEnumWbemClassObject enumWbem; //holds WMI enumerator for this collection
private bool isDisposed;
//Constructor
internal ManagementObjectCollection(
ManagementScope scope,
EnumerationOptions options,
IEnumWbemClassObject enumWbem)
{
if (null != options)
this.options = (EnumerationOptions)options.Clone();
else
this.options = new EnumerationOptions();
if (null != scope)
this.scope = (ManagementScope)scope.Clone();
else
this.scope = ManagementScope._Clone(null);
this.enumWbem = enumWbem;
}
/// <summary>
/// <para>Disposes of resources the object is holding. This is the destructor for the object.</para>
/// </summary>
~ManagementObjectCollection()
{
Dispose(false);
}
/// <summary>
/// Releases resources associated with this object. After this
/// method has been called, an attempt to use this object will
/// result in an ObjectDisposedException being thrown.
/// </summary>
public void Dispose()
{
if (!isDisposed)
{
Dispose(true);
}
}
private void Dispose(bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
isDisposed = true;
}
Marshal.ReleaseComObject(enumWbem);
}
//
//ICollection properties & methods
//
/// <summary>
/// <para>Represents the number of objects in the collection.</para>
/// </summary>
/// <value>
/// <para>The number of objects in the collection.</para>
/// </value>
/// <remarks>
/// <para>This property is very expensive - it requires that
/// all members of the collection be enumerated.</para>
/// </remarks>
public int Count
{
get
{
if (isDisposed)
throw new ObjectDisposedException(name);
//
// We can not use foreach since it _always_ calls Dispose on the collection
// invalidating the IEnumWbemClassObject pointers.
// We prevent this by doing a manual walk of the collection.
//
int count = 0;
ManagementObjectEnumerator enumCol = this.GetEnumerator();
while (enumCol.MoveNext())
{
count++;
}
return count;
}
}
/// <summary>
/// <para>Represents whether the object is synchronized.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/>, if the object is synchronized;
/// otherwise, <see langword='false'/>.</para>
/// </value>
public bool IsSynchronized
{
get
{
if (isDisposed)
throw new ObjectDisposedException(name);
return false;
}
}
/// <summary>
/// <para>Represents the object to be used for synchronization.</para>
/// </summary>
/// <value>
/// <para> The object to be used for synchronization.</para>
/// </value>
public object SyncRoot
{
get
{
if (isDisposed)
throw new ObjectDisposedException(name);
return this;
}
}
/// <overload>
/// Copies the collection to an array.
/// </overload>
/// <summary>
/// <para> Copies the collection to an array.</para>
/// </summary>
/// <param name='array'>An array to copy to. </param>
/// <param name='index'>The index to start from. </param>
public void CopyTo(Array array, int index)
{
if (isDisposed)
throw new ObjectDisposedException(name);
if (null == array)
throw new ArgumentNullException(nameof(array));
if ((index < array.GetLowerBound(0)) || (index > array.GetUpperBound(0)))
throw new ArgumentOutOfRangeException(nameof(index));
// Since we don't know the size until we've enumerated
// we'll have to dump the objects in a list first then
// try to copy them in.
int capacity = array.Length - index;
int numObjects = 0;
ArrayList arrList = new ArrayList();
ManagementObjectEnumerator en = this.GetEnumerator();
ManagementBaseObject obj;
while (en.MoveNext())
{
obj = en.Current;
arrList.Add(obj);
numObjects++;
if (numObjects > capacity)
throw new ArgumentException(null, nameof(index));
}
// If we get here we are OK. Now copy the list to the array
arrList.CopyTo(array, index);
return;
}
/// <summary>
/// <para>Copies the items in the collection to a <see cref='System.Management.ManagementBaseObject'/>
/// array.</para>
/// </summary>
/// <param name='objectCollection'>The target array.</param>
/// <param name=' index'>The index to start from.</param>
public void CopyTo(ManagementBaseObject[] objectCollection, int index)
{
CopyTo((Array)objectCollection, index);
}
//
//IEnumerable methods
//
//****************************************
//GetEnumerator
//****************************************
/// <summary>
/// <para>Returns the enumerator for the collection. If the collection was retrieved from an operation that
/// specified the EnumerationOptions.Rewindable = false only one iteration through this enumerator is allowed.
/// Note that this applies to using the Count property of the collection as well since an iteration over the collection
/// is required. Due to this, code using the Count property should never specify EnumerationOptions.Rewindable = false.
/// </para>
/// </summary>
/// <returns>
/// An <see cref='System.Collections.IEnumerator'/>that can be used to iterate through the
/// collection.
/// </returns>
public ManagementObjectEnumerator GetEnumerator()
{
if (isDisposed)
throw new ObjectDisposedException(name);
//
// We do not clone the enumerator if its the first enumerator.
// If it is the first enumerator we pass the reference
// to the enumerator implementation rather than a clone. If the enumerator is used
// from within a foreach statement in the client code, the foreach statement will
// dec the ref count on the reference which also happens to be the reference to the
// original enumerator causing subsequent uses of the collection to fail.
// To prevent this we always clone the enumerator (assuming its a rewindable enumerator)
// to avoid invalidating the collection.
//
// If its a forward only enumerator we simply pass back the original enumerator (i.e.
// not cloned) and if it gets disposed we end up throwing the next time its used. Essentially,
// the enumerator becomes the collection.
//
// Unless this is the first enumerator, we have
// to clone. This may throw if we are non-rewindable.
if (this.options.Rewindable)
{
IEnumWbemClassObject enumWbemClone = null;
int status = (int)ManagementStatus.NoError;
try
{
status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Clone_(ref enumWbemClone);
if ((status & 0x80000000) == 0)
{
//since the original enumerator might not be reset, we need
//to reset the new one.
status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbemClone).Reset_();
}
}
catch (COMException e)
{
ManagementException.ThrowWithExtendedInfo(e);
}
if ((status & 0xfffff000) == 0x80041000)
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
}
else if ((status & 0x80000000) != 0)
{
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return new ManagementObjectEnumerator(this, enumWbemClone);
}
else
{
//
// Notice that we use the original enumerator and hence enum position is retained.
// For example, if the client code manually walked half the collection and then
// used a foreach statement, the foreach statement would continue from where the
// manual walk ended.
//
return new ManagementObjectEnumerator(this, enumWbem);
}
}
/// <internalonly/>
/// <summary>
/// <para>Returns an enumerator that can iterate through a collection.</para>
/// </summary>
/// <returns>
/// An <see cref='System.Collections.IEnumerator'/> that can be used to iterate
/// through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
//
// ManagementObjectCollection methods
//
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
/// <summary>
/// <para>Represents the enumerator on the collection.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This example demonstrates how to enumerate all logical disks
/// // using the ManagementObjectEnumerator object.
/// class Sample_ManagementObjectEnumerator
/// {
/// public static int Main(string[] args) {
/// ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
/// ManagementObjectCollection disks = diskClass.GetInstances();
/// ManagementObjectCollection.ManagementObjectEnumerator disksEnumerator =
/// disks.GetEnumerator();
/// while(disksEnumerator.MoveNext()) {
/// ManagementObject disk = (ManagementObject)disksEnumerator.Current;
/// Console.WriteLine("Disk found: " + disk["deviceid"]);
/// }
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
/// ' This sample demonstrates how to enumerate all logical disks
/// ' using ManagementObjectEnumerator object.
/// Class Sample_ManagementObjectEnumerator
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim diskClass As New ManagementClass("Win32_LogicalDisk")
/// Dim disks As ManagementObjectCollection = diskClass.GetInstances()
/// Dim disksEnumerator As _
/// ManagementObjectCollection.ManagementObjectEnumerator = _
/// disks.GetEnumerator()
/// While disksEnumerator.MoveNext()
/// Dim disk As ManagementObject = _
/// CType(disksEnumerator.Current, ManagementObject)
/// Console.WriteLine("Disk found: " & disk("deviceid"))
/// End While
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
public class ManagementObjectEnumerator : IEnumerator, IDisposable
{
private static readonly string name = typeof(ManagementObjectEnumerator).FullName;
private IEnumWbemClassObject enumWbem;
private ManagementObjectCollection collectionObject;
private uint cachedCount; //says how many objects are in the enumeration cache (when using BlockSize option)
private int cacheIndex; //used to walk the enumeration cache
private IWbemClassObjectFreeThreaded[] cachedObjects; //points to objects currently available in enumeration cache
private bool atEndOfCollection;
private bool isDisposed;
//constructor
internal ManagementObjectEnumerator(
ManagementObjectCollection collectionObject,
IEnumWbemClassObject enumWbem)
{
this.enumWbem = enumWbem;
this.collectionObject = collectionObject;
cachedObjects = new IWbemClassObjectFreeThreaded[collectionObject.options.BlockSize];
cachedCount = 0;
cacheIndex = -1; // Reset position
atEndOfCollection = false;
}
/// <summary>
/// <para>Disposes of resources the object is holding. This is the destructor for the object.</para>
/// </summary>
~ManagementObjectEnumerator()
{
Dispose();
}
/// <summary>
/// Releases resources associated with this object. After this
/// method has been called, an attempt to use this object will
/// result in an ObjectDisposedException being thrown.
/// </summary>
public void Dispose()
{
if (!isDisposed)
{
if (null != enumWbem)
{
Marshal.ReleaseComObject(enumWbem);
enumWbem = null;
}
cachedObjects = null;
// DO NOT dispose of collectionObject. It is merely a reference - its lifetime
// exceeds that of this object. If collectionObject.Dispose was to be done here,
// a reference count would be needed.
//
collectionObject = null;
isDisposed = true;
GC.SuppressFinalize(this);
}
}
/// <summary>
/// <para>Gets the current <see cref='System.Management.ManagementBaseObject'/> that this enumerator points
/// to.</para>
/// </summary>
/// <value>
/// <para>The current object in the enumeration.</para>
/// </value>
public ManagementBaseObject Current
{
get
{
if (isDisposed)
throw new ObjectDisposedException(name);
if (cacheIndex < 0)
throw new InvalidOperationException();
return ManagementBaseObject.GetBaseObject(cachedObjects[cacheIndex],
collectionObject.scope);
}
}
/// <internalonly/>
/// <summary>
/// <para>Returns the current object in the enumeration.</para>
/// </summary>
/// <value>
/// <para>The current object in the enumeration.</para>
/// </value>
object IEnumerator.Current
{
get
{
return Current;
}
}
//****************************************
//MoveNext
//****************************************
/// <summary>
/// Indicates whether the enumerator has moved to
/// the next object in the enumeration.
/// </summary>
/// <returns>
/// <para><see langword='true'/>, if the enumerator was
/// successfully advanced to the next element; <see langword='false'/> if the enumerator has
/// passed the end of the collection.</para>
/// </returns>
public bool MoveNext()
{
if (isDisposed)
throw new ObjectDisposedException(name);
//If there are no more objects in the collection return false
if (atEndOfCollection)
return false;
//Look for the next object
cacheIndex++;
if ((cachedCount - cacheIndex) == 0) //cache is empty - need to get more objects
{
//If the timeout is set to infinite, need to use the WMI infinite constant
int timeout = (collectionObject.options.Timeout.Ticks == long.MaxValue) ?
(int)tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE : (int)collectionObject.options.Timeout.TotalMilliseconds;
//Get the next [BLockSize] objects within the specified timeout
SecurityHandler securityHandler = collectionObject.scope.GetSecurityHandler();
//Because Interop doesn't support custom marshalling for arrays, we have to use
//the "DoNotMarshal" objects in the interop and then convert to the "FreeThreaded"
//counterparts afterwards.
IWbemClassObject_DoNotMarshal[] tempArray = new IWbemClassObject_DoNotMarshal[collectionObject.options.BlockSize];
int status = collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Next_(timeout, (uint)collectionObject.options.BlockSize, tempArray, ref cachedCount);
securityHandler.Reset();
if (status >= 0)
{
//Convert results and put them in cache.
for (int i = 0; i < cachedCount; i++)
{
cachedObjects[i] = new IWbemClassObjectFreeThreaded
(
Marshal.GetIUnknownForObject(tempArray[i])
);
}
}
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
else
{
//If there was a timeout and no object can be returned we throw a timeout exception...
if ((status == (int)tag_WBEMSTATUS.WBEM_S_TIMEDOUT) && (cachedCount == 0))
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
//If not timeout and no objects were returned - we're at the end of the collection
if ((status == (int)tag_WBEMSTATUS.WBEM_S_FALSE) && (cachedCount == 0))
{
atEndOfCollection = true;
cacheIndex--; //back to last object
/* This call to Dispose is being removed as per discussion with URT people and the newly supported
* Dispose() call in the foreach implementation itself.
*
* //Release the COM object (so that the user doesn't have to)
Dispose();
*/
return false;
}
}
cacheIndex = 0;
}
return true;
}
//****************************************
//Reset
//****************************************
/// <summary>
/// <para>Resets the enumerator to the beginning of the collection.</para>
/// </summary>
public void Reset()
{
if (isDisposed)
throw new ObjectDisposedException(name);
//If the collection is not rewindable you can't do this
if (!collectionObject.options.Rewindable)
throw new InvalidOperationException();
else
{
//Reset the WMI enumerator
SecurityHandler securityHandler = collectionObject.scope.GetSecurityHandler();
int status = (int)ManagementStatus.NoError;
try
{
status = collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Reset_();
}
catch (COMException e)
{
ManagementException.ThrowWithExtendedInfo(e);
}
finally
{
securityHandler.Reset();
}
if ((status & 0xfffff000) == 0x80041000)
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
}
else if ((status & 0x80000000) != 0)
{
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
//Flush the current enumeration cache
for (int i = (cacheIndex >= 0 ? cacheIndex : 0); i < cachedCount; i++)
Marshal.ReleaseComObject((IWbemClassObject_DoNotMarshal)(Marshal.GetObjectForIUnknown(cachedObjects[i])));
cachedCount = 0;
cacheIndex = -1;
atEndOfCollection = false;
}
}
} //ManagementObjectEnumerator class
} //ManagementObjectCollection class
}