/
ManagementPath.cs
1125 lines (990 loc) · 42.2 KB
/
ManagementPath.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.Diagnostics;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Reflection;
using System.ComponentModel.Design.Serialization;
using System.Text;
namespace System.Management
{
/// <summary>
/// <para>Provides a wrapper for parsing and building paths to WMI objects.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This sample displays all properties in a ManagementPath object.
///
/// class Sample_ManagementPath
/// {
/// public static int Main(string[] args) {
/// ManagementPath path = new ManagementPath( "\\\\MyServer\\MyNamespace:Win32_logicaldisk='c:'");
///
/// // Results of full path parsing
/// Console.WriteLine("Path: " + path.Path);
/// Console.WriteLine("RelativePath: " + path.RelativePath);
/// Console.WriteLine("Server: " + path.Server);
/// Console.WriteLine("NamespacePath: " + path.NamespacePath);
/// Console.WriteLine("ClassName: " + path.ClassName);
/// Console.WriteLine("IsClass: " + path.IsClass);
/// Console.WriteLine("IsInstance: " + path.IsInstance);
/// Console.WriteLine("IsSingleton: " + path.IsSingleton);
///
/// // Change a portion of the full path
/// path.Server = "AnotherServer";
/// Console.WriteLine("New Path: " + path.Path);
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// 'This sample displays all properties in a ManagementPath object.
/// Class Sample_ManagementPath Overloads
/// Public Shared Function Main(args() As String) As Integer
/// Dim path As _ New
/// ManagementPath("\\MyServer\MyNamespace:Win32_LogicalDisk='c:'")
///
/// ' Results of full path parsing
/// Console.WriteLine("Path: " & path.Path)
/// Console.WriteLine("RelativePath: " & path.RelativePath)
/// Console.WriteLine("Server: " & path.Server)
/// Console.WriteLine("NamespacePath: " & path.NamespacePath)
/// Console.WriteLine("ClassName: " & path.ClassName)
/// Console.WriteLine("IsClass: " & path.IsClass)
/// Console.WriteLine("IsInstance: " & path.IsInstance)
/// Console.WriteLine("IsSingleton: " & path.IsSingleton)
///
/// ' Change a portion of the full path
/// path.Server= "AnotherServer"
/// Console.WriteLine("New Path: " & path.Path)
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
[TypeConverter(typeof(ManagementPathConverter))]
public class ManagementPath : ICloneable
{
private static ManagementPath defaultPath = new ManagementPath("//./root/cimv2");
//Used to minimize the cases in which new wbemPath (WMI object path parser) objects need to be constructed
//This is done for performance reasons.
private bool isWbemPathShared;
internal event IdentifierChangedEventHandler IdentifierChanged;
//Fires IdentifierChanged event
private void FireIdentifierChanged()
{
IdentifierChanged?.Invoke(this, null);
}
//internal factory
/// <summary>
/// Internal static "factory" method for making a new ManagementPath
/// from the system property of a WMI object
/// </summary>
/// <param name="wbemObject">The WMI object whose __PATH property will
/// be used to supply the returned object</param>
internal static string GetManagementPath(
IWbemClassObjectFreeThreaded wbemObject)
{
string path = null;
int status = (int)ManagementStatus.Failed;
if (null != wbemObject)
{
int dummy1 = 0, dummy2 = 0;
object val = null;
status = wbemObject.Get_("__PATH", 0, ref val, ref dummy1, ref dummy2);
if ((status < 0) || (val == System.DBNull.Value))
{
//try to get the relpath instead
status = wbemObject.Get_("__RELPATH", 0, ref val, ref dummy1, ref dummy2);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
if (System.DBNull.Value == val)
path = null;
else
path = (string)val;
}
return path;
}
//Used internally to check whether a string passed in as a namespace is indeed syntactically correct
//for a namespace (e.g. either has "\" or "/" in it or is the special case of "root")
//This doesn't check for the existence of that namespace, nor does it guarrantee correctness.
internal static bool IsValidNamespaceSyntax(string nsPath)
{
if (nsPath.Length != 0)
{
// Any path separators present?
char[] pathSeparators = { '\\', '/' };
if (nsPath.IndexOfAny(pathSeparators) == -1)
{
// No separators. The only valid path is "root".
if (!string.Equals("root", nsPath, StringComparison.OrdinalIgnoreCase))
return false;
}
}
return true;
}
internal static ManagementPath _Clone(ManagementPath path)
{
return ManagementPath._Clone(path, null);
}
internal static ManagementPath _Clone(ManagementPath path, IdentifierChangedEventHandler handler)
{
ManagementPath pathTmp = new ManagementPath();
// Wire up change handler chain. Use supplied handler, if specified;
// otherwise, default to that of the path argument.
if (handler != null)
pathTmp.IdentifierChanged = handler;
// Assign ManagementPath IWbemPath to this.wmiPath.
// Optimization for performance : As long as the path is only read, we share this interface.
// On the first write, a private copy will be needed;
// isWbemPathShared signals ManagementPath to create such a copy at write-time.
if (path != null && path.wmiPath != null)
{
pathTmp.wmiPath = path.wmiPath;
pathTmp.isWbemPathShared = path.isWbemPathShared = true;
}
return pathTmp;
}
/// <overload>
/// Initializes a new instance
/// of the <see cref='System.Management.ManagementPath'/> class.
/// </overload>
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementPath'/> class that is empty. This is the default constructor.</para>
/// </summary>
public ManagementPath() : this((string)null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementPath'/> class for the given path.</para>
/// </summary>
/// <param name='path'> The object path. </param>
public ManagementPath(string path)
{
if ((null != path) && (0 < path.Length))
wmiPath = CreateWbemPath(path);
}
/// <summary>
/// <para>Returns the full object path as the string representation.</para>
/// </summary>
/// <returns>
/// A string containing the full object
/// path represented by this object. This value is equivalent to the value of the
/// <see cref='System.Management.ManagementPath.Path'/> property.
/// </returns>
public override string ToString()
{
return this.Path;
}
/// <summary>
/// <para>Returns a copy of the <see cref='System.Management.ManagementPath'/>.</para>
/// </summary>
/// <returns>
/// The cloned object.
/// </returns>
public ManagementPath Clone()
{
return new ManagementPath(Path);
}
/// <summary>
/// Standard Clone returns a copy of this ManagementPath as a generic "Object" type
/// </summary>
/// <returns>
/// The cloned object.
/// </returns>
object ICloneable.Clone()
{
return Clone();
}
/// <summary>
/// <para>Gets or sets the default scope path used when no scope is specified.
/// The default scope is /-/ \\.\root\cimv2, and can be changed by setting this property.</para>
/// </summary>
/// <value>
/// <para>By default the scope value is /-/ \\.\root\cimv2, or a different scope path if
/// the default was changed.</para>
/// </value>
public static ManagementPath DefaultPath
{
get { return ManagementPath.defaultPath; }
set { ManagementPath.defaultPath = value; }
}
//private members
private IWbemPath wmiPath;
private IWbemPath CreateWbemPath(string path)
{
IWbemPath wbemPath = (IWbemPath)MTAHelper.CreateInMTA(typeof(WbemDefPath)); //new WbemDefPath();
SetWbemPath(wbemPath, path);
return wbemPath;
}
private void SetWbemPath(string path)
{
// Test/utilize isWbemPathShared *only* on public + internal members!
if (wmiPath == null)
{
wmiPath = CreateWbemPath(path);
}
else
{
SetWbemPath(wmiPath, path);
}
}
private static void SetWbemPath(IWbemPath wbemPath, string path)
{
if (null != wbemPath)
{
uint flags = (uint)tag_WBEM_PATH_CREATE_FLAG.WBEMPATH_CREATE_ACCEPT_ALL;
//For now we have to special-case the "root" namespace -
// this is because in the case of "root", the path parser cannot tell whether
// this is a namespace name or a class name
if (string.Equals(path, "root", StringComparison.OrdinalIgnoreCase))
flags |= (uint)tag_WBEM_PATH_CREATE_FLAG.WBEMPATH_TREAT_SINGLE_IDENT_AS_NS;
int status = wbemPath.SetText_(flags, path);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
}
private string GetWbemPath()
{
return GetWbemPath(this.wmiPath);
}
private static string GetWbemPath(IWbemPath wbemPath)
{
string pathStr = string.Empty;
if (null != wbemPath)
{
// Requesting the path from a parser which has
// been only given a relative path results in an incorrect
// value being returned (e.g. \\.\win32_logicaldisk). To work
// around this we check if there are any namespaces,
// and if not ask for the relative path instead.
int flags = (int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_TOO;
uint nCount = 0;
int status = (int)ManagementStatus.NoError;
status = wbemPath.GetNamespaceCount_(out nCount);
if (status >= 0)
{
if (0 == nCount)
flags = (int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_RELATIVE_ONLY;
// Get the space we need to reserve
uint bufLen = 0;
status = wbemPath.GetText_(flags, ref bufLen, null);
if (status >= 0 && 0 < bufLen)
{
char[] pathChars = new char[(int)bufLen];
status = wbemPath.GetText_(flags, ref bufLen, pathChars);
pathStr = new string(pathChars, 0, Array.IndexOf(pathChars, '\0'));
}
}
if (status < 0)
{
if (status == (int)tag_WBEMSTATUS.WBEM_E_INVALID_PARAMETER)
{
// Interpret as unspecified - return ""
}
else if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
return pathStr;
}
private void ClearKeys(bool setAsSingleton)
{
// Test/utilize isWbemPathShared *only* on public + internal members!
int status = (int)ManagementStatus.NoError;
try
{
if (null != wmiPath)
{
IWbemPathKeyList keyList = null;
status = wmiPath.GetKeyList_(out keyList);
if (null != keyList)
{
status = keyList.RemoveAllKeys_(0);
if ((status & 0x80000000) == 0)
{
sbyte bSingleton = (setAsSingleton) ? (sbyte)(-1) : (sbyte)0;
status = keyList.MakeSingleton_(bSingleton);
FireIdentifierChanged();
}
}
}
}
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());
}
}
internal bool IsEmpty
{
get
{
return (Path.Length == 0);
}
}
//
// Methods
//
/// <summary>
/// <para> Sets the path as a new class path. This means that the path must have
/// a class name but not key values.</para>
/// </summary>
public void SetAsClass()
{
if (IsClass || IsInstance)
{
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
if (isWbemPathShared)
{
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
ClearKeys(false);
}
else
throw new ManagementException(ManagementStatus.InvalidOperation, null, null);
}
/// <summary>
/// <para> Sets the path as a new singleton object path. This means that it is a path to an instance but
/// there are no key values.</para>
/// </summary>
public void SetAsSingleton()
{
if (IsClass || IsInstance)
{
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
if (isWbemPathShared)
{
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
ClearKeys(true);
}
else
throw new ManagementException(ManagementStatus.InvalidOperation, null, null);
}
//
// Properties
//
/// <summary>
/// <para> Gets or sets the string representation of the full path in the object.</para>
/// </summary>
/// <value>
/// <para>A string containing the full path
/// represented in this object.</para>
/// </value>
[RefreshProperties(RefreshProperties.All)]
public string Path
{
get
{
return this.GetWbemPath();
}
set
{
try
{
// Before overwriting, check it's OK
// Note, we've never done such validation, should we?
//
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
if (isWbemPathShared)
{
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
this.SetWbemPath(value);
}
catch
{
throw new ArgumentOutOfRangeException(nameof(value));
}
FireIdentifierChanged();
}
}
/// <summary>
/// <para> Gets or sets the relative path: class name and keys only.</para>
/// </summary>
/// <value>
/// A string containing the relative
/// path (not including the server and namespace portions) represented in this
/// object.
/// </value>
[RefreshProperties(RefreshProperties.All)]
public string RelativePath
{
get
{
string pathStr = string.Empty;
if (null != wmiPath)
{
// Get the space we need to reserve
uint bufLen = 0;
int status = wmiPath.GetText_(
(int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_RELATIVE_ONLY,
ref bufLen,
null);
if (status >= 0 && 0 < bufLen)
{
char[] pathChars = new char[(int)bufLen];
status = wmiPath.GetText_(
(int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_RELATIVE_ONLY,
ref bufLen,
pathChars);
pathStr = new string(pathChars, 0, Array.IndexOf(pathChars, '\0'));
}
if (status < 0)
{
if (status == (int)tag_WBEMSTATUS.WBEM_E_INVALID_PARAMETER)
{
// Interpret as unspecified - return ""
}
else if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
return pathStr;
}
set
{
try
{
// No need for isWbemPathShared here since internal SetRelativePath
// always creates a new copy.
SetRelativePath(value);
}
catch (COMException)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
FireIdentifierChanged();
}
}
internal void SetRelativePath(string relPath)
{
// No need for isWbemPathShared here since internal SetRelativePath
// always creates a new copy.
ManagementPath newPath = new ManagementPath(relPath);
newPath.NamespacePath = this.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY);
newPath.Server = this.Server;
wmiPath = newPath.wmiPath;
}
//Used to update the relative path when the user changes any key properties
internal void UpdateRelativePath(string relPath)
{
if (relPath == null)
return;
//Get the server & namespace part from the existing path, and concatenate the given relPath.
//NOTE : we need to do this because IWbemPath doesn't have a function to set the relative path alone...
string newPath = string.Empty;
string nsPath = this.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY);
if (nsPath.Length > 0)
newPath = string.Concat(nsPath, ":", relPath);
else
newPath = relPath;
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
if (isWbemPathShared)
{
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
this.SetWbemPath(newPath);
}
/// <summary>
/// <para>Gets or sets the server part of the path.</para>
/// </summary>
/// <value>
/// A string containing the server name
/// from the path represented in this object.
/// </value>
[RefreshProperties(RefreshProperties.All)]
public string Server
{
get
{
string pathStr = string.Empty;
if (null != wmiPath)
{
uint uLen = 0;
int status = wmiPath.GetServer_(ref uLen, null);
if (status >= 0 && 0 < uLen)
{
char[] pathChars = new char[(int)uLen];
status = wmiPath.GetServer_(ref uLen, pathChars);
pathStr = new string(pathChars, 0, Array.IndexOf(pathChars, '\0'));
}
if (status < 0)
{
if (status == (int)tag_WBEMSTATUS.WBEM_E_NOT_AVAILABLE)
{
// Interpret as unspecified - return ""
}
else if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
return pathStr;
}
set
{
string oldValue = Server;
// Only set if changed
if (!string.Equals(oldValue, value, StringComparison.OrdinalIgnoreCase))
{
if (null == wmiPath)
wmiPath = (IWbemPath)MTAHelper.CreateInMTA(typeof(WbemDefPath)); //new WbemDefPath ();
else if (isWbemPathShared)
{
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
int status = wmiPath.SetServer_(value);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
FireIdentifierChanged();
}
}
}
internal string SetNamespacePath(string nsPath, out bool bChange)
{
int status = (int)ManagementStatus.NoError;
string nsOrg = null;
string nsNew = null;
IWbemPath wmiPathTmp = null;
bChange = false;
Debug.Assert(nsPath != null);
//Do some validation on the path to make sure it is a valid namespace path (at least syntactically)
if (!IsValidNamespaceSyntax(nsPath))
ManagementException.ThrowWithExtendedInfo((ManagementStatus)tag_WBEMSTATUS.WBEM_E_INVALID_NAMESPACE);
wmiPathTmp = CreateWbemPath(nsPath);
if (wmiPath == null)
{
wmiPath = this.CreateWbemPath("");
}
else if (isWbemPathShared)
{
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
nsOrg = GetNamespacePath(wmiPath,
(int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_NAMESPACE_ONLY);
nsNew = GetNamespacePath(wmiPathTmp,
(int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_NAMESPACE_ONLY);
if (!string.Equals(nsOrg, nsNew, StringComparison.OrdinalIgnoreCase))
{
wmiPath.RemoveAllNamespaces_(); // Out with the old... Ignore status code.
// Add the new ones in
bChange = true; // Now dirty from above.
uint nCount = 0;
status = wmiPathTmp.GetNamespaceCount_(out nCount);
if (status >= 0)
{
for (uint i = 0; i < nCount; i++)
{
uint uLen = 0;
status = wmiPathTmp.GetNamespaceAt_(i, ref uLen, null);
if (status >= 0)
{
char[] space = new char[(int)uLen];
status = wmiPathTmp.GetNamespaceAt_(i, ref uLen, space);
if (status >= 0)
{
status = wmiPath.SetNamespaceAt_(i, space);
if (status < 0)
break;
}
else
break;
}
else
break;
}
}
}
else {; } // Continue on. Could have different server name, same ns specified.
//
// Update Server property if specified in the namespace.
// eg: "\\MyServer\root\cimv2".
//
if (status >= 0 && nsPath.Length > 1 &&
(nsPath[0] == '\\' && nsPath[1] == '\\' ||
nsPath[0] == '/' && nsPath[1] == '/'))
{
uint uLen = 0;
status = wmiPathTmp.GetServer_(ref uLen, null);
if (status >= 0 && uLen > 0)
{
char[] newServerChars = new char[(int)uLen];
status = wmiPathTmp.GetServer_(ref uLen, newServerChars);
string serverNew = new string(newServerChars, 0, Array.IndexOf(newServerChars, '\0'));
if (status >= 0)
{
// Compare server name on this object, if specified, to the caller's.
// Update this object if different or unspecified.
uLen = 0;
status = wmiPath.GetServer_(ref uLen, null); // NB: Cannot use property get since it may throw.
if (status >= 0)
{
char[] orgServerChars = new char[(int)uLen];
status = wmiPath.GetServer_(ref uLen, orgServerChars);
string serverOrg = new string(orgServerChars, 0, Array.IndexOf(orgServerChars, '\0'));
if (status >= 0 && !string.Equals(serverOrg, serverNew, StringComparison.OrdinalIgnoreCase))
status = wmiPath.SetServer_(serverNew);
}
else if (status == (int)tag_WBEMSTATUS.WBEM_E_NOT_AVAILABLE)
{
status = wmiPath.SetServer_(serverNew);
if (status >= 0)
bChange = true;
}
}
}
else if (status == (int)tag_WBEMSTATUS.WBEM_E_NOT_AVAILABLE) // No caller-supplied server name;
status = (int)ManagementStatus.NoError; // Ignore error.
}
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return nsNew;
}
internal string GetNamespacePath(int flags)
{
return GetNamespacePath(wmiPath, flags);
}
internal static string GetNamespacePath(IWbemPath wbemPath, int flags)
{
string pathStr = string.Empty;
if (null != wbemPath)
{
// Requesting the namespace path from a parser which has
// been only given a relative path results in an incorrect
// value being returned (e.g. \\.\). To work
// around this, check if there are any namespaces,
// and if not just return "".
uint nCount = 0;
int status = (int)ManagementStatus.NoError;
status = wbemPath.GetNamespaceCount_(out nCount);
if (status >= 0 && nCount > 0)
{
// Get the space we need to reserve
uint bufLen = 0;
status = wbemPath.GetText_(flags, ref bufLen, null);
if (status >= 0 && bufLen > 0)
{
char[] pathChars = new char[(int)bufLen];
status = wbemPath.GetText_(flags, ref bufLen, pathChars);
pathStr = new string(pathChars, 0, Array.IndexOf(pathChars, '\0'));
}
}
if (status < 0)
{
if (status == (int)tag_WBEMSTATUS.WBEM_E_INVALID_PARAMETER)
{
// Interpret as unspecified - return ""
}
else if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
return pathStr;
}
/// <summary>
/// <para>Gets or sets the namespace part of the path. Note that this does not include
/// the server name, which can be retrieved separately.</para>
/// </summary>
/// <value>
/// A string containing the namespace
/// portion of the path represented in this object.
/// </value>
[RefreshProperties(RefreshProperties.All)]
public string NamespacePath
{
get
{
return GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_NAMESPACE_ONLY);
}
set
{
bool bChange = false;
try
{
// isWbemPathShared handled in internal SetNamespacePath.
SetNamespacePath(value, out bChange);
}
catch (COMException)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (bChange)
FireIdentifierChanged();
}
}
/// <summary>
/// Gets or sets the class portion of the path.
/// </summary>
/// <value>
/// A string containing the name of the
/// class.
/// </value>
[RefreshProperties(RefreshProperties.All)]
public string ClassName
{
get
{
return internalClassName;
}
set
{
string oldValue = ClassName;
// Only set if changed
if (!string.Equals(oldValue, value, StringComparison.OrdinalIgnoreCase))
{
// isWbemPathShared handled in internal className property accessor.
internalClassName = value;
FireIdentifierChanged();
}
}
}
internal string internalClassName
{
get
{
string pathStr = string.Empty;
int status = (int)ManagementStatus.NoError;
if (null != wmiPath)
{
uint bufLen = 0;
status = wmiPath.GetClassName_(ref bufLen, null);
if (status >= 0 && 0 < bufLen)
{
char[] pathChars = new char[(int)bufLen];
status = wmiPath.GetClassName_(ref bufLen, pathChars);
pathStr = new string(pathChars, 0, Array.IndexOf(pathChars, '\0'));
if (status < 0)
pathStr = string.Empty;
}
}
return pathStr;
}
set
{
int status = (int)ManagementStatus.NoError;
if (wmiPath == null)
{
wmiPath = (IWbemPath)MTAHelper.CreateInMTA(typeof(WbemDefPath)); //new WbemDefPath();
}
else if (isWbemPathShared)
{
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
try
{
status = wmiPath.SetClassName_(value);
}
catch (COMException)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether this is a class path.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if this is a class path; otherwise,
/// <see langword='false'/>.</para>
/// </value>
public bool IsClass
{
get
{
if (null == wmiPath)
return false;
ulong uInfo = 0;
int status = wmiPath.GetInfo_(0, out uInfo);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return (0 != (uInfo & (ulong)tag_WBEM_PATH_STATUS_FLAG.WBEMPATH_INFO_IS_CLASS_REF));
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether this is an instance path.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if this is an instance path; otherwise,
/// <see langword='false'/>.</para>
/// </value>