/
WMIGenerator.cs
7710 lines (6477 loc) · 360 KB
/
WMIGenerator.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 Microsoft.CSharp;
using Microsoft.VisualBasic;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.Versioning;
namespace System.Management
{
/// <summary>
/// <para>Defines the languages supported by the code generator.</para>
/// </summary>
public enum CodeLanguage
{
/// <summary>
/// A value for generating C# code.
/// </summary>
CSharp,
/// <summary>
/// <para>A value for generating JScript code.</para>
/// </summary>
JScript,
/// <summary>
/// <para>A value for generating Visual Basic code.</para>
/// </summary>
VB,
/// <summary>
/// <para>A value for generating Visual J# code.</para>
/// </summary>
VJSharp,
/// <summary>
/// <para>A value for generating Managed C++ code.</para>
/// </summary>
Mcpp
};
/// <summary>
/// Used to generate a strongly-typed code class for a given WMI class.
/// </summary>
internal sealed class ManagementClassGenerator
{
private readonly string VSVERSION = "8.0.0.0";
private string OriginalServer = string.Empty;
private string OriginalNamespace = string.Empty;
private string OriginalClassName = string.Empty;
private readonly string OriginalPath = string.Empty;
private bool bSingletonClass;
private bool bUnsignedSupported = true;
private string NETNamespace = string.Empty;
private string arrConvFuncName = string.Empty;
private string enumType = string.Empty;
private const int DMTF_DATETIME_STR_LENGTH = 25;
private bool bDateConversionFunctionsAdded;
private bool bTimeSpanConversionFunctionsAdded;
private ManagementClass classobj;
private CodeDomProvider cp;
private TextWriter tw;
private readonly string genFileName = string.Empty;
private CodeTypeDeclaration cc;
private CodeTypeDeclaration ccc;
private CodeTypeDeclaration ecc;
private CodeTypeDeclaration EnumObj;
private CodeNamespace cn;
private CodeMemberProperty cmp;
private CodeConstructor cctor;
private CodeMemberField cf;
private CodeObjectCreateExpression coce;
private CodeParameterDeclarationExpression cpde;
private CodeIndexerExpression cie;
private CodeMemberField cmf;
private CodeMemberMethod cmm;
private CodePropertyReferenceExpression cpre;
private CodeMethodInvokeExpression cmie;
private CodeExpressionStatement cmis;
private CodeConditionStatement cis;
private CodeBinaryOperatorExpression cboe;
private CodeIterationStatement cfls;
private CodeAttributeArgument caa;
private CodeAttributeDeclaration cad;
private readonly ArrayList arrKeyType = new ArrayList(5);
private readonly ArrayList arrKeys = new ArrayList(5);
private readonly ArrayList BitMap = new ArrayList(5);
private ArrayList BitValues = new ArrayList(5);
private readonly ArrayList ValueMap = new ArrayList(5);
private ArrayList Values = new ArrayList(5);
private SortedList PublicProperties = new SortedList(StringComparer.OrdinalIgnoreCase);
private SortedList PublicMethods = new SortedList(StringComparer.OrdinalIgnoreCase);
private SortedList PublicNamesUsed = new SortedList(StringComparer.OrdinalIgnoreCase);
private SortedList PrivateNamesUsed = new SortedList(StringComparer.OrdinalIgnoreCase);
private bool bHasEmbeddedProperties;
/// <summary>
/// <para>Creates an empty generator object. This is the default constructor.</para>
/// </summary>
public ManagementClassGenerator()
{
}
/// <summary>
/// <para>Creates a generator object and initializes it
/// with the specified <see cref="System.Management.ManagementClass"/>.</para>
/// </summary>
/// <param name='cls'><see cref="System.Management.ManagementClass"/> object for which the code is to be generated.</param>
public ManagementClassGenerator(ManagementClass cls)
{
this.classobj = cls;
}
/// <summary>
/// <para>
/// Returns a <see cref="System.CodeDom.CodeTypeDeclaration"/> for
/// this class.</para>
/// </summary>
/// <param name='includeSystemProperties'>Indicates if a class for handling system properties should be included.</param>
/// <param name='systemPropertyClass'>Indicates if the generated code is for a class that handles system properties.</param>
/// <returns>
/// <para>Returns the <see cref="System.CodeDom.CodeTypeDeclaration"/> for the WMI class.</para>
/// </returns>
/// <remarks>
/// <para>If includeSystemProperties is <see langword="true"/>,
/// the ManagementSystemProperties class is included in the generated class definition.
/// This parameter is ignored if systemPropertyClass is <see langword="true"/>.</para>
/// </remarks>
public CodeTypeDeclaration GenerateCode(bool includeSystemProperties, bool systemPropertyClass)
{
CodeTypeDeclaration retType;
if (systemPropertyClass)
{
//Initialize the public attributes . private variables
InitilializePublicPrivateMembers();
retType = GenerateSystemPropertiesClass();
}
else
{
CheckIfClassIsProperlyInitialized();
InitializeCodeGeneration();
retType = GetCodeTypeDeclarationForClass(includeSystemProperties);
}
return retType;
}
/// <summary>
/// Generates a strongly-typed code class for the specified language provider (C#, Visual Basic or JScript)
/// and writes it to the specified file.
/// </summary>
/// <param name="lang">The language to generate in.</param>
/// <param name="filePath">The path to the file where the generated code should be stored.</param>
/// <param name="netNamespace">The .NET namespace into which the class is generated.</param>
public bool GenerateCode(CodeLanguage lang, string filePath, string netNamespace)
{
// check for proper arguments
if (filePath == null)
{
throw new ArgumentOutOfRangeException(SR.NullFilePathException);
}
if (filePath.Length == 0)
{
throw new ArgumentOutOfRangeException(SR.EmptyFilePathException);
}
NETNamespace = netNamespace;
CheckIfClassIsProperlyInitialized();
// Initialize Code Generator
InitializeCodeGeneration();
//Now create the filestream (output file)
tw = new StreamWriter(new FileStream(filePath, FileMode.Create), System.Text.Encoding.UTF8);
return GenerateAndWriteCode(lang);
}
/// <summary>
/// Checks if mandatory properties are properly initialized.
/// </summary>
private void CheckIfClassIsProperlyInitialized()
{
if (classobj == null)
{
if (OriginalNamespace == null || (OriginalNamespace != null && OriginalNamespace.Length == 0))
{
throw new ArgumentOutOfRangeException(SR.NamespaceNotInitializedException);
}
if (OriginalClassName == null || (OriginalClassName != null && OriginalClassName.Length == 0))
{
throw new ArgumentOutOfRangeException(SR.ClassNameNotInitializedException);
}
}
}
private void InitializeCodeGeneration()
{
//First try to get the class object for the given WMI Class.
//If we cannot get it then there is no point in continuing
//as we won't have any information for the code generation.
InitializeClassObject();
//Initialize the public attributes . private variables
InitilializePublicPrivateMembers();
//First form the namespace for the generated class.
//The namespace will look like System.Wmi.Root.Cimv2.Win32
//for the path \\root\cimv2:Win32_Service and the class name will be
//Service.
ProcessNamespaceAndClassName();
//First we will sort out the different naming collision that might occur
//in the generated code.
ProcessNamingCollisions();
}
/// <summary>
/// This function will generate the code. This is the function which
/// should be called for generating the code.
/// </summary>
/// <param name="bIncludeSystemClassinClassDef">
/// Flag to indicate if system properties are to be included or not
/// </param>
private CodeTypeDeclaration GetCodeTypeDeclarationForClass(bool bIncludeSystemClassinClassDef)
{
//Create type defination for the class
cc = new CodeTypeDeclaration(PrivateNamesUsed["GeneratedClassName"].ToString());
// Adding Component as base class so as to enable drag and drop
cc.BaseTypes.Add(new CodeTypeReference(PrivateNamesUsed["ComponentClass"].ToString()));
AddClassComments(cc);
//Generate the code for defaultNamespace
//public string defNamespace {
// get {
// return (<defNamespace>);
// }
//}
GeneratePublicReadOnlyProperty(PublicNamesUsed["NamespaceProperty"].ToString(), "System.String",
OriginalNamespace, false, true, SR.CommentOriginNamespace);
/*
Generate the following code for className
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ManagementClassName {
get {
string strRet = CreatedClassName;
if (((PrivateLateBoundObject != null)
&& (PrivateLateBoundObject.Path != null))) {
strRet = ((string)(PrivateLateBoundObject["__CLASS"]));
if (((strRet == null)
|| (strRet.Length == 0))) {
strRet = CreatedClassName;
}
}
return strRet;
}
}
*/
// Add a private member variable to hold the namespace of the created class
// Generate a private member variable for storing the generated class Name
GeneratePrivateMember(PrivateNamesUsed["CreationWmiNamespace"].ToString(), "System.String",
new CodePrimitiveExpression(OriginalNamespace), true, SR.CommentCreatedWmiNamespace);
GenerateClassNameProperty();
// Generate a private member variable for storing the generated class Name
GeneratePrivateMember(PrivateNamesUsed["CreationClassName"].ToString(), "System.String",
new CodePrimitiveExpression(OriginalClassName), true, SR.CommentCreatedClass);
//public SystemPropertiesClass _SystemProps{
// get {
// return (privSysProps);
// }
//}
GeneratePublicReadOnlyProperty(PublicNamesUsed["SystemPropertiesProperty"].ToString(), PublicNamesUsed["SystemPropertiesClass"].ToString(),
PrivateNamesUsed["SystemPropertiesObject"].ToString(), true, true,
SR.CommentSystemObject);
//public wmiObjectClass _Object{
// get {
// return (privWmiObject);
// }
//}
GeneratePublicReadOnlyProperty(PublicNamesUsed["LateBoundObjectProperty"].ToString(), PublicNamesUsed["BaseObjClass"].ToString(),
PrivateNamesUsed["CurrentObject"].ToString(), true, false,
SR.CommentLateBoundProperty);
//public ManagementScope Scope {
// get {
// return privScope;
// }
// set {
// privScope = value;
// }
//}
GenerateScopeProperty();
//public bool AutoCommit {
// get {
// return AutoCommitProp;
// }
// set {
// AutoCommitProp; = value;
// }
//}
GeneratePublicProperty(PublicNamesUsed["AutoCommitProperty"].ToString(), "System.Boolean",
new CodeSnippetExpression(PrivateNamesUsed["AutoCommitProperty"].ToString()), false,
SR.CommentAutoCommitProperty, false);
//public ManagementPath Path {
// get {
// return privWmiObject.Path;
// }
// set {
// if (String.Compare(value.ClassName,className,true,CultureInfo.InvariantCulture) != 0)
// throw new ArgumentException("Class name doesn\'t match.");
// privWmiObject.Path = value;
// }
//}
GeneratePathProperty();
// Adding a private member for storing the ManagementScope to be used by various static methods
GeneratePrivateMember(PrivateNamesUsed["statMgmtScope"].ToString(), PublicNamesUsed["ScopeClass"].ToString(),
new CodePrimitiveExpression(null), true, SR.CommentStaticManagementScope);
// Generate a property "StaticScope" to set and get the static ManagementScope for the class
GeneratePublicProperty(PrivateNamesUsed["staticScope"].ToString(), PublicNamesUsed["ScopeClass"].ToString(),
new CodeVariableReferenceExpression(PrivateNamesUsed["statMgmtScope"].ToString()), true, SR.CommentStaticScopeProperty, true);
// Generate a function to check if a given class can be represented
// by the generated class
GenerateIfClassvalidFunction();
//Now generate properties of the WMI Class
GenerateProperties();
// Add Function to Initialize Member variables
GenerateMethodToInitializeVariables();
//Now Generate static ConstructPath()
GenerateConstructPath();
//Now create the default constructor
GenerateDefaultConstructor();
GenerateInitializeObject();
if (bSingletonClass)
{
//Now Generate a constructor which accepts only the scope
GenerateConstructorWithScope();
//Now Generate a constructor which accepts only the get options
GenerateConstructorWithOptions();
//Now generate a constructor which accepts both scope and options
GenerateConstructorWithScopeOptions();
}
else
{
//Now create the constructor which accepts the key values
GenerateConstructorWithKeys();
//Also generate a constructor which accepts a scope and keys
GenerateConstructorWithScopeKeys();
//Now generate constructor with Path & Options
GenerateConstructorWithPathOptions();
//Now Generate a constructor with scope & path
GenerateConstructorWithScopePath();
//Now Generate the GetInstances()
GenerateGetInstancesWithNoParameters();
//Now Generate the GetInstances(condition)
GenerateGetInstancesWithCondition();
//Now Generate the GetInstances(propertylist)
GenerateGetInstancesWithProperties();
//Now Generate the GetInstances(condition,propertylist)
GenerateGetInstancesWithWhereProperties();
//Now Generate the GetInstances(scope)
GenerateGetInstancesWithScope();
//Now Generate the GetInstances(scope,condition)
GenerateGetInstancesWithScopeCondition();
//Now Generate the GetInstances(scope,propertylist)
GenerateGetInstancesWithScopeProperties();
//Now Generate the GetInstances(scope,condition,propertylist)
GenerateGetInstancesWithScopeWhereProperties();
//Generate the Collection Class
GenerateCollectionClass();
}
//Now create constructor with path object
GenerateConstructorWithPath();
//Now Generate the constructor with path,scope,options
GenerateConstructorWithScopePathOptions();
//Now generate Constructor with latebound Object
GenarateConstructorWithLateBound();
//Now generate Constructor with latebound Object
// and the object is an embedded object
GenarateConstructorWithLateBoundForEmbedded();
// Generate static CreateInstance() to create instance of the class
GenerateCreateInstance();
// Generate static DeleteInstance() to delete instance
GenerateDeleteInstance();
//Now Enumerate all the methods
GenerateMethods();
//Now declare the private sealed class variables
//private Wmi_SystemProps SystemProps
GeneratePrivateMember(PrivateNamesUsed["SystemPropertiesObject"].ToString(), PublicNamesUsed["SystemPropertiesClass"].ToString(), null);
//private WmiObject privObject
GeneratePrivateMember(PrivateNamesUsed["LateBoundObject"].ToString(), PublicNamesUsed["LateBoundClass"].ToString(), SR.CommentLateBoundObject);
//private Internal AutoCommitProperty
GeneratePrivateMember(PrivateNamesUsed["AutoCommitProperty"].ToString(), "System.Boolean", new CodePrimitiveExpression(true), false, SR.CommentPrivateAutoCommit);
//private WmiObject Embedded object
GeneratePrivateMember(PrivateNamesUsed["EmbeddedObject"].ToString(), PublicNamesUsed["BaseObjClass"].ToString(), SR.CommentEmbeddedObject);
//private WmiObject for current object used
GeneratePrivateMember(PrivateNamesUsed["CurrentObject"].ToString(), PublicNamesUsed["BaseObjClass"].ToString(), SR.CommentCurrentObject);
//private WmiObject for current object used
GeneratePrivateMember(PrivateNamesUsed["IsEmbedded"].ToString(), "System.Boolean", new CodePrimitiveExpression(false), false, SR.CommentFlagForEmbedded);
//Now generate the Type Converter class also
cc.Members.Add(GenerateTypeConverterClass());
if (bIncludeSystemClassinClassDef)
{
cc.Members.Add(GenerateSystemPropertiesClass());
}
if (bHasEmbeddedProperties)
{
AddCommentsForEmbeddedProperties();
}
// Added at the end so that this comment is the last comment just before declaring the class
cc.Comments.Add(new CodeCommentStatement(SR.CommentClassBegin +
OriginalClassName));
return cc;
}
private bool GenerateAndWriteCode(CodeLanguage lang)
{
if (InitializeCodeGenerator(lang) == false)
{
return false;
}
//Now Initialize the code class for generation
InitializeCodeTypeDeclaration(lang);
// Call this function to create CodeTypeDeclaration for the WMI class
GetCodeTypeDeclarationForClass(true);
// Trying to resolve the classname with a identifier
cc.Name = cp.CreateValidIdentifier(cc.Name);
//As we have finished the class definition, generate the class code NOW!!!!!
cn.Types.Add(cc);
try
{
cp.GenerateCodeFromNamespace(cn, tw, new CodeGeneratorOptions());
}
finally
{
tw.Close();
}
return true;
}
/// <summary>
/// Function for initializing the class object that will be used to get all the
/// method and properties of the WMI Class for generating the code.
/// </summary>
private void InitializeClassObject()
{
//First try to connect to WMI and get the class object.
// If it fails then no point in continuing
// If object is not initialized by the constructor
if (classobj == null)
{
ManagementPath thePath;
if (OriginalPath.Length != 0)
{
thePath = new ManagementPath(OriginalPath);
}
else
{
thePath = new ManagementPath();
if (OriginalServer.Length != 0)
thePath.Server = OriginalServer;
thePath.ClassName = OriginalClassName;
thePath.NamespacePath = OriginalNamespace;
/*
throw new Exception("OriginalServer is " + OriginalServer +
" OriginalNamespace is " + OriginalNamespace +
" OriginalClassName is " + OriginalClassName +
" results in " + thePath.Path);
*/
}
classobj = new ManagementClass(thePath);
}
else
{
// Get the common properties
ManagementPath thePath = classobj.Path;
OriginalServer = thePath.Server;
OriginalClassName = thePath.ClassName;
OriginalNamespace = thePath.NamespacePath;
char[] arrString = OriginalNamespace.ToCharArray();
// Remove the server from the namespace
if (arrString.Length >= 2 && arrString[0] == '\\' && arrString[1] == '\\')
{
bool bStart = false;
int Len = OriginalNamespace.Length;
OriginalNamespace = string.Empty;
for (int i = 2; i < Len; i++)
{
if (bStart)
{
OriginalNamespace += arrString[i];
}
else
if (arrString[i] == '\\')
{
bStart = true;
}
}
}
}
try
{
classobj.Get();
}
catch (ManagementException)
{
throw;
}
//By default all classes are non-singleton(???)
bSingletonClass = false;
foreach (QualifierData q in classobj.Qualifiers)
{
if (string.Equals(q.Name, "singleton", StringComparison.OrdinalIgnoreCase))
{
//This is a singleton class
bSingletonClass = true;
break;
}
}
}
/// <summary>
/// This functrion initializes the public attributes and private variables
/// list that will be used in the generated code.
/// </summary>
private void InitilializePublicPrivateMembers()
{
//Initialize the public members
PublicNamesUsed.Add("SystemPropertiesProperty", "SystemProperties");
PublicNamesUsed.Add("LateBoundObjectProperty", "LateBoundObject");
PublicNamesUsed.Add("NamespaceProperty", "OriginatingNamespace");
PublicNamesUsed.Add("ClassNameProperty", "ManagementClassName");
PublicNamesUsed.Add("ScopeProperty", "Scope");
PublicNamesUsed.Add("PathProperty", "Path");
PublicNamesUsed.Add("SystemPropertiesClass", "ManagementSystemProperties");
PublicNamesUsed.Add("LateBoundClass", "System.Management.ManagementObject");
PublicNamesUsed.Add("PathClass", "System.Management.ManagementPath");
PublicNamesUsed.Add("ScopeClass", "System.Management.ManagementScope");
PublicNamesUsed.Add("QueryOptionsClass", "System.Management.EnumerationOptions");
PublicNamesUsed.Add("GetOptionsClass", "System.Management.ObjectGetOptions");
PublicNamesUsed.Add("ArgumentExceptionClass", "System.ArgumentException");
PublicNamesUsed.Add("QueryClass", "SelectQuery");
PublicNamesUsed.Add("ObjectSearcherClass", "System.Management.ManagementObjectSearcher");
PublicNamesUsed.Add("FilterFunction", "GetInstances");
PublicNamesUsed.Add("ConstructPathFunction", "ConstructPath");
PublicNamesUsed.Add("TypeConverter", "TypeConverter");
PublicNamesUsed.Add("AutoCommitProperty", "AutoCommit");
PublicNamesUsed.Add("CommitMethod", "CommitObject");
PublicNamesUsed.Add("ManagementClass", "System.Management.ManagementClass");
PublicNamesUsed.Add("NotSupportedExceptClass", "System.NotSupportedException");
PublicNamesUsed.Add("BaseObjClass", "System.Management.ManagementBaseObject");
PublicNamesUsed.Add("OptionsProp", "Options");
PublicNamesUsed.Add("ClassPathProperty", "ClassPath");
PublicNamesUsed.Add("CreateInst", "CreateInstance");
PublicNamesUsed.Add("DeleteInst", "Delete");
// Adding this so that the namespace resolving routine does not name
// any properties with the name "System"
PublicNamesUsed.Add("SystemNameSpace", "System");
PublicNamesUsed.Add("ArgumentOutOfRangeException", "System.ArgumentOutOfRangeException");
PublicNamesUsed.Add("System", "System");
PublicNamesUsed.Add("Other", "Other");
PublicNamesUsed.Add("Unknown", "Unknown");
PublicNamesUsed.Add("PutOptions", "System.Management.PutOptions");
PublicNamesUsed.Add("Type", "System.Type");
PublicNamesUsed.Add("Boolean", "System.Boolean");
PublicNamesUsed.Add("ValueType", "System.ValueType");
PublicNamesUsed.Add("Events1", "Events");
PublicNamesUsed.Add("Component1", "Component");
//Initialize the Private Members
PrivateNamesUsed.Add("SystemPropertiesObject", "PrivateSystemProperties");
PrivateNamesUsed.Add("LateBoundObject", "PrivateLateBoundObject");
PrivateNamesUsed.Add("AutoCommitProperty", "AutoCommitProp");
PrivateNamesUsed.Add("Privileges", "EnablePrivileges");
PrivateNamesUsed.Add("ComponentClass", "System.ComponentModel.Component");
PrivateNamesUsed.Add("ScopeParam", "mgmtScope");
PrivateNamesUsed.Add("NullRefExcep", "System.NullReferenceException");
PrivateNamesUsed.Add("ConverterClass", "WMIValueTypeConverter");
PrivateNamesUsed.Add("EnumParam", "enumOptions");
PrivateNamesUsed.Add("CreationClassName", "CreatedClassName");
PrivateNamesUsed.Add("CreationWmiNamespace", "CreatedWmiNamespace");
PrivateNamesUsed.Add("ClassNameCheckFunc", "CheckIfProperClass");
PrivateNamesUsed.Add("EmbeddedObject", "embeddedObj");
PrivateNamesUsed.Add("CurrentObject", "curObj");
PrivateNamesUsed.Add("IsEmbedded", "isEmbedded");
PrivateNamesUsed.Add("ToDateTimeMethod", "ToDateTime");
PrivateNamesUsed.Add("ToDMTFDateTimeMethod", "ToDmtfDateTime");
PrivateNamesUsed.Add("ToDMTFTimeIntervalMethod", "ToDmtfTimeInterval");
PrivateNamesUsed.Add("ToTimeSpanMethod", "ToTimeSpan");
PrivateNamesUsed.Add("SetMgmtScope", "SetStaticManagementScope");
PrivateNamesUsed.Add("statMgmtScope", "statMgmtScope");
PrivateNamesUsed.Add("staticScope", "StaticScope");
PrivateNamesUsed.Add("initVariable", "Initialize");
PrivateNamesUsed.Add("putOptions", "putOptions");
PrivateNamesUsed.Add("InitialObjectFunc", "InitializeObject");
}
/// <summary>
/// This function will solve the naming collisions that might occur
/// due to the collision between the local objects of the generated
/// class and the properties/methods of the original WMI Class.
/// </summary>
private void ProcessNamingCollisions()
{
if (classobj.Properties != null)
{
foreach (PropertyData prop in classobj.Properties)
{
PublicProperties.Add(prop.Name, prop.Name);
}
}
if (classobj.Methods != null)
{
foreach (MethodData meth in classobj.Methods)
{
PublicMethods.Add(meth.Name, meth.Name);
}
}
int nIndex;
//Process the collisions here
//We will check each public names with the property names here.
foreach (string s in PublicNamesUsed.Values)
{
nIndex = IsContainedIn(s, ref PublicProperties);
if (nIndex != -1)
{
//We had found a collision with a public property
//So we will resolve the collision by changing the property name
//and continue
PublicProperties.SetByIndex(nIndex, ResolveCollision(s, false));
continue;
}
nIndex = IsContainedIn(s, ref PublicMethods);
if (nIndex != -1)
{
//We had found a collision with a public method
//So we will resolve the collision by changing the method name
//and continue
PublicMethods.SetByIndex(nIndex, ResolveCollision(s, false));
continue;
}
}
//Now we will check for collision against private variables
foreach (string s in PublicProperties.Values)
{
nIndex = IsContainedIn(s, ref PrivateNamesUsed);
if (nIndex != -1)
{
//We had found a collision with a public property
//So we will resolve the collision by changing the private name
//and continue
PrivateNamesUsed.SetByIndex(nIndex, ResolveCollision(s, false));
}
}
foreach (string s in PublicMethods.Values)
{
nIndex = IsContainedIn(s, ref PrivateNamesUsed);
if (nIndex != -1)
{
//We had found a collision with a public method
//So we will resolve the collision by changing the private name
//and continue
PrivateNamesUsed.SetByIndex(nIndex, ResolveCollision(s, false));
}
}
//Now we will check for collision against Methods and Public Properties
foreach (string s in PublicProperties.Values)
{
nIndex = IsContainedIn(s, ref PublicMethods);
if (nIndex != -1)
{
//We had found a collision with a public property
//So we will resolve the collision by changing the Public Property name
//and continue
PublicMethods.SetByIndex(nIndex, ResolveCollision(s, false));
}
}
//Now we will create the CollectionClass and Enumerator Class names as they are dependent on the
//generated class name and the generated class name might have changed due to collision
string strTemp = PrivateNamesUsed["GeneratedClassName"].ToString() + "Collection";
PrivateNamesUsed.Add("CollectionClass", ResolveCollision(strTemp, true));
strTemp = PrivateNamesUsed["GeneratedClassName"].ToString() + "Enumerator";
PrivateNamesUsed.Add("EnumeratorClass", ResolveCollision(strTemp, true));
}
/// <summary>
/// This function is used to resolve (actually generate a new name) collision
/// between the generated class properties/variables with WMI methods/properties.
/// This function safely assumes that there will be atleast one string left
/// in the series prop0, prop1 ...prop(maxInt) . Otherwise this function will
/// enter an infinite loop. May be we can avoid this through something, which
/// i will think about it later
/// </summary>
/// <param name="inString"> </param>
/// <param name="bCheckthisFirst"></param>
private string ResolveCollision(string inString, bool bCheckthisFirst)
{
string strTemp = inString;
bool bCollision = true;
int k = -1;
string strToAdd = "";
if (bCheckthisFirst == false)
{
k++;
strTemp = strTemp + strToAdd + k.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int)));
}
while (bCollision)
{
if (IsContainedIn(strTemp, ref PublicProperties) == -1)
{
if (IsContainedIn(strTemp, ref PublicMethods) == -1)
{
if (IsContainedIn(strTemp, ref PublicNamesUsed) == -1)
{
if (IsContainedIn(strTemp, ref PrivateNamesUsed) == -1)
{
//So this is not colliding with anything.
bCollision = false;
break;
}
}
}
}
try
{
k++;
}
catch (OverflowException)
{
strToAdd += "_";
k = 0;
}
strTemp = inString + strToAdd + k.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int)));
}
if (strTemp.Length > 0)
{
string strFirstChar = strTemp.Substring(0, 1).ToUpperInvariant();
strTemp = strFirstChar + strTemp.Substring(1);
}
return strTemp;
}
/// <summary>
/// This function processes the WMI namespace and WMI classname and converts them to
/// the namespace used to generate the class and the classname.
/// </summary>
private void ProcessNamespaceAndClassName()
{
string strClass = string.Empty;
string strNs = string.Empty;
// if Namespace is not alread set then construct the namespace
if (NETNamespace.Length == 0)
{
strNs = OriginalNamespace;
strNs = strNs.Replace('\\', '.');
strNs = strNs.ToUpperInvariant();
}
else
{
strNs = NETNamespace;
}
if (OriginalClassName.IndexOf('_') > 0)
{
strClass = OriginalClassName.Substring(0, OriginalClassName.IndexOf('_'));
// if Namespace is not alread set then construct the namespace
if (NETNamespace.Length == 0)
{
strNs += ".";
strNs += strClass;
}
//Now trim the class name without the first '_'
strClass = OriginalClassName.Substring(OriginalClassName.IndexOf('_') + 1);
}
else
{
strClass = OriginalClassName;
}
// Check if the name of the class starts with a charachter. If not add "C" to the beginning of the name
if (char.IsLetter(strClass[0]) == false)
{
strClass = "C" + strClass;
}
strClass = ResolveCollision(strClass, true);
// Try to get a type from any of the namespace which are used in the generated code and see if
// it collides with any of the standard classes.
if (Type.GetType("System." + strClass) != null ||
Type.GetType("System.ComponentModel." + strClass) != null ||
Type.GetType("System.Management." + strClass) != null ||
Type.GetType("System.Collections." + strClass) != null ||
Type.GetType("System.Globalization." + strClass) != null)
{
PublicNamesUsed.Add(strClass, strClass);
strClass = ResolveCollision(strClass, true);
}
PrivateNamesUsed.Add("GeneratedClassName", strClass);
PrivateNamesUsed.Add("GeneratedNamespace", strNs);
}
private void InitializeCodeTypeDeclaration(CodeLanguage lang)
{
//Now add the import statements
cn = new CodeNamespace(PrivateNamesUsed["GeneratedNamespace"].ToString());
cn.Imports.Add(new CodeNamespaceImport("System"));
cn.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
cn.Imports.Add(new CodeNamespaceImport("System.Management"));
cn.Imports.Add(new CodeNamespaceImport("System.Collections"));
cn.Imports.Add(new CodeNamespaceImport("System.Globalization"));
if (lang == CodeLanguage.VB)
{
cn.Imports.Add(new CodeNamespaceImport("Microsoft.VisualBasic"));
}
}
/// <summary>
/// This function generates the code for the read only property.
/// The generated code will be of the form
/// public <propType> <propName>{
/// get {
/// return (<propValue>);
/// }
/// }
/// </summary>
/// <param name="propName"> </param>
/// <param name="propType"> </param>
/// <param name="propValue"> </param>
/// <param name="isLiteral"></param>
/// <param name="isBrowsable"></param>
/// <param name="Comment"></param>
private void GeneratePublicReadOnlyProperty(string propName, string propType, object propValue, bool isLiteral, bool isBrowsable, string Comment)
{
cmp = new CodeMemberProperty();
cmp.Name = propName;
cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final;
cmp.Type = new CodeTypeReference(propType);
caa = new CodeAttributeArgument();
caa.Value = new CodePrimitiveExpression(isBrowsable);
cad = new CodeAttributeDeclaration();
cad.Name = "Browsable";
cad.Arguments.Add(caa);
cmp.CustomAttributes = new CodeAttributeDeclarationCollection();
cmp.CustomAttributes.Add(cad);
caa = new CodeAttributeArgument();
caa.Value = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DesignerSerializationVisibility"), "Hidden");
cad = new CodeAttributeDeclaration();
cad.Name = "DesignerSerializationVisibility";
cad.Arguments.Add(caa);
cmp.CustomAttributes.Add(cad);
if (isLiteral)
{
cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression(propValue.ToString())));
}
else
{
cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(propValue)));
}
cc.Members.Add(cmp);
if (Comment != null && Comment.Length != 0)
{
cmp.Comments.Add(new CodeCommentStatement(Comment));
}
}
private void GeneratePublicProperty(string propName, string propType, CodeExpression Value, bool isBrowsable, string Comment, bool isStatic)
{
cmp = new CodeMemberProperty();
cmp.Name = propName;
cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final;
cmp.Type = new CodeTypeReference(propType);
if (isStatic)
{
cmp.Attributes |= MemberAttributes.Static;
}
caa = new CodeAttributeArgument();
caa.Value = new CodePrimitiveExpression(isBrowsable);
cad = new CodeAttributeDeclaration();
cad.Name = "Browsable";
cad.Arguments.Add(caa);
cmp.CustomAttributes = new CodeAttributeDeclarationCollection();
cmp.CustomAttributes.Add(cad);
// If the property is not Path then add an attribb DesignerSerializationVisibility
// to indicate that the property is to be hidden for designer serilization.
if (IsDesignerSerializationVisibilityToBeSet(propName))
{
caa = new CodeAttributeArgument();
caa.Value = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DesignerSerializationVisibility"), "Hidden");
cad = new CodeAttributeDeclaration();
cad.Name = "DesignerSerializationVisibility";
cad.Arguments.Add(caa);
cmp.CustomAttributes.Add(cad);
}
cmp.GetStatements.Add(new CodeMethodReturnStatement(Value));
cmp.SetStatements.Add(new CodeAssignStatement(Value,