/
ManagementQuery.cs
3248 lines (2958 loc) · 143 KB
/
ManagementQuery.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.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;
namespace System.Management
{
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Provides an abstract base class for all management query objects.</para>
/// </summary>
/// <remarks>
/// <para> This class is abstract; only
/// derivatives of it are actually used in the API.</para>
/// </remarks>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
[TypeConverter(typeof(ManagementQueryConverter))]
public abstract class ManagementQuery : ICloneable
{
internal const string DEFAULTQUERYLANGUAGE = "WQL";
internal const string TokenSelect = "select "; // Keep trailing space char.
//Used when any public property on this object is changed, to signal
//to the containing object that it needs to be refreshed.
internal event IdentifierChangedEventHandler IdentifierChanged;
//Fires IdentifierChanged event
internal void FireIdentifierChanged()
{
IdentifierChanged?.Invoke(this, null);
}
private string queryLanguage;
private string queryString;
internal void SetQueryString(string qString)
{
queryString = qString;
}
//default constructor
internal ManagementQuery() : this(DEFAULTQUERYLANGUAGE, null) { }
//parameterized constructors
internal ManagementQuery(string query) : this(DEFAULTQUERYLANGUAGE, query) { }
internal ManagementQuery(string language, string query)
{
QueryLanguage = language;
QueryString = query;
}
/// <summary>
/// Parses the query string and sets the property values accordingly.
/// </summary>
/// <param name="query">The query string to be parsed.</param>
protected internal virtual void ParseQuery(string query) { }
//
//properties
//
/// <summary>
/// <para>Gets or sets the query in text format.</para>
/// </summary>
/// <value>
/// <para> If the query object is
/// constructed with no parameters, the property is null until specifically set. If the
/// object was constructed with a specified query, the property returns the specified
/// query string.</para>
/// </value>
public virtual string QueryString
{
get { return queryString ?? string.Empty; }
set
{
if (queryString != value)
{
ParseQuery(value); // this may throw
queryString = value;
FireIdentifierChanged();
}
}
}
/// <summary>
/// <para> Gets or sets the query language used in the query
/// string, defining the format of the query string.</para>
/// </summary>
/// <value>
/// <para>Can be set to any supported query
/// language. "WQL" is the only value supported intrinsically by WMI.</para>
/// </value>
public virtual string QueryLanguage
{
get { return queryLanguage ?? string.Empty; }
set
{
if (queryLanguage != value)
{
queryLanguage = value;
FireIdentifierChanged();
}
}
}
//ICloneable
/// <summary>
/// <para>Returns a copy of the object.</para>
/// </summary>
/// <returns>
/// The cloned object.
/// </returns>
public abstract object Clone();
internal static void ParseToken(ref string q, string token, string op, ref bool bTokenFound, ref string tokenValue)
{
if (bTokenFound)
throw new ArgumentException(SR.InvalidQueryDuplicatedToken); // Invalid query - duplicate token
bTokenFound = true;
q = q.Remove(0, token.Length).TrimStart(null);
// Next character should be the operator if any
if (op != null)
{
if (!q.StartsWith(op, StringComparison.Ordinal))
throw new ArgumentException(SR.InvalidQuery); // Invalid query
// Strip off the op and any leading WS
q = q.Remove(0, op.Length).TrimStart(null);
}
if (0 == q.Length)
throw new ArgumentException(SR.InvalidQueryNullToken); // Invalid query - token has no value
// Next token should be the token value - look for terminating WS
// or end of string
int i;
if (-1 == (i = q.IndexOf(' ')))
i = q.Length; // No WS => consume entire string
tokenValue = q.Substring(0, i);
q = q.Remove(0, tokenValue.Length).TrimStart(null);
}
internal static void ParseToken(ref string q, string token, ref bool bTokenFound)
{
if (bTokenFound)
throw new ArgumentException(SR.InvalidQueryDuplicatedToken); // Invalid query - duplicate token
bTokenFound = true;
q = q.Remove(0, token.Length).TrimStart(null);
}
}//ManagementQuery
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Represents a management query that returns instances or classes.</para>
/// </summary>
/// <remarks>
/// <para>This class or its derivatives are used to specify a
/// query in the <see cref='System.Management.ManagementObjectSearcher'/>. Use
/// a more specific query class whenever possible.</para>
/// </remarks>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This sample demonstrates creating a query.
///
/// class Sample_ObjectQuery
/// {
/// public static int Main(string[] args)
/// {
/// ObjectQuery objectQuery = new ObjectQuery("select * from Win32_Share");
/// ManagementObjectSearcher searcher =
/// new ManagementObjectSearcher(objectQuery);
/// foreach (ManagementObject share in searcher.Get())
/// {
/// Console.WriteLine("Share = " + share["Name"]);
/// }
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This sample demonstrates creating a query.
///
/// Class Sample_ObjectQuery
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim objectQuery As New ObjectQuery("select * from Win32_Share")
/// Dim searcher As New ManagementObjectSearcher(objectQuery)
/// Dim share As ManagementObject
/// For Each share In searcher.Get()
/// Console.WriteLine("Share = " & share("Name"))
/// Next share
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
public class ObjectQuery : ManagementQuery
{
/// <overload>
/// <para>Initializes a new instance of the <see cref='System.Management.ObjectQuery'/>
/// class.</para>
/// </overload>
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ObjectQuery'/>
/// class with no initialized values. This
/// is the default constructor.</para>
/// </summary>
public ObjectQuery() : base() { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ObjectQuery'/>
/// class
/// for a specific query string.</para>
/// </summary>
/// <param name='query'>The string representation of the query.</param>
public ObjectQuery(string query) : base(query) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ObjectQuery'/>
/// class for a specific
/// query string and language.</para>
/// </summary>
/// <param name='language'>The query language in which this query is specified.</param>
/// <param name=' query'>The string representation of the query.</param>
public ObjectQuery(string language, string query) : base(language, query) { }
//ICloneable
/// <summary>
/// <para>Returns a copy of the object.</para>
/// </summary>
/// <returns>
/// The cloned object.
/// </returns>
public override object Clone()
{
return new ObjectQuery(QueryLanguage, QueryString);
}
}//ObjectQuery
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Represents a WMI event query.</para>
/// </summary>
/// <remarks>
/// <para> Objects of this class or its derivatives are used in
/// <see cref='System.Management.ManagementEventWatcher'/> to subscribe to
/// WMI events. Use more specific derivatives of this class whenever possible.</para>
/// </remarks>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This sample demonstrates how to subscribe to an event
/// // using the EventQuery object.
///
/// class Sample_EventQuery
/// {
/// public static int Main(string[] args)
/// {
/// //For this example, we make sure we have an arbitrary class on root\default
/// ManagementClass newClass = new ManagementClass(
/// "root\\default",
/// String.Empty,
/// null);
/// newClass["__Class"] = "TestWql";
/// newClass.Put();
///
/// //Create a query object for watching for class deletion events
/// EventQuery eventQuery = new EventQuery("select * from __classdeletionevent");
///
/// //Initialize an event watcher object with this query
/// ManagementEventWatcher watcher = new ManagementEventWatcher(
/// new ManagementScope("root/default"),
/// eventQuery);
///
/// //Set up a handler for incoming events
/// MyHandler handler = new MyHandler();
/// watcher.EventArrived += new EventArrivedEventHandler(handler.Arrived);
///
/// //Start watching for events
/// watcher.Start();
///
/// //For this example, we delete the class to trigger an event
/// newClass.Delete();
///
/// //Nothing better to do - we loop to wait for an event to arrive.
/// while (!handler.IsArrived) {
/// System.Threading.Thread.Sleep(1000);
/// }
///
/// //In this example we only want to wait for one event, so we can stop watching
/// watcher.Stop();
///
/// //Get some values from the event.
/// //Note: this can also be done in the event handler.
/// ManagementBaseObject eventArg =
/// (ManagementBaseObject)(handler.ReturnedArgs.NewEvent["TargetClass"]);
/// Console.WriteLine("Class Deleted = " + eventArg["__CLASS"]);
///
/// return 0;
/// }
///
/// public class MyHandler
/// {
/// private bool isArrived = false;
/// private EventArrivedEventArgs args;
///
/// //Handles the event when it arrives
/// public void Arrived(object sender, EventArrivedEventArgs e) {
/// args = e;
/// isArrived = true;
/// }
///
/// //Public property to get at the event information stored in the handler
/// public EventArrivedEventArgs ReturnedArgs {
/// get {
/// return args;
/// }
/// }
///
/// //Used to determine whether the event has arrived or not.
/// public bool IsArrived {
/// get {
/// return isArrived;
/// }
/// }
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This sample demonstrates how to subscribe an event
/// ' using the EventQuery object.
///
/// Class Sample_EventQuery
/// Public Shared Sub Main()
///
/// 'For this example, we make sure we have an arbitrary class on root\default
/// Dim newClass As New ManagementClass( _
/// "root\default", _
/// String.Empty, Nothing)
/// newClass("__Class") = "TestWql"
/// newClass.Put()
///
/// 'Create a query object for watching for class deletion events
/// Dim eventQuery As New EventQuery("select * from __classdeletionevent")
///
/// 'Initialize an event watcher object with this query
/// Dim watcher As New ManagementEventWatcher( _
/// New ManagementScope("root/default"), _
/// eventQuery)
///
/// 'Set up a handler for incoming events
/// Dim handler As New MyHandler()
/// AddHandler watcher.EventArrived, AddressOf handler.Arrived
///
/// 'Start watching for events
/// watcher.Start()
///
/// 'For this example, we delete the class to trigger an event
/// newClass.Delete()
///
/// 'Nothing better to do - we loop to wait for an event to arrive.
/// While Not handler.IsArrived
/// Console.Write("0")
/// System.Threading.Thread.Sleep(1000)
/// End While
///
/// 'In this example we only want to wait for one event, so we can stop watching
/// watcher.Stop()
///
/// 'Get some values from the event
/// 'Note: this can also be done in the event handler.
/// Dim eventArg As ManagementBaseObject = CType( _
/// handler.ReturnedArgs.NewEvent("TargetClass"), _
/// ManagementBaseObject)
/// Console.WriteLine(("Class Deleted = " + eventArg("__CLASS")))
///
/// End Sub
///
/// Public Class MyHandler
/// Private _isArrived As Boolean = False
/// Private args As EventArrivedEventArgs
///
/// 'Handles the event when it arrives
/// Public Sub Arrived(sender As Object, e As EventArrivedEventArgs)
/// args = e
/// _isArrived = True
/// End Sub
///
/// 'Public property to get at the event information stored in the handler
/// Public ReadOnly Property ReturnedArgs() As EventArrivedEventArgs
/// Get
/// Return args
/// End Get
/// End Property
///
/// 'Used to determine whether the event has arrived or not.
/// Public ReadOnly Property IsArrived() As Boolean
/// Get
/// Return _isArrived
/// End Get
/// End Property
/// End Class
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
public class EventQuery : ManagementQuery
{
/// <overload>
/// <para>Initializes a new instance of the <see cref='System.Management.EventQuery'/>
/// class.</para>
/// </overload>
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.EventQuery'/>
/// class. This is the
/// default constructor.</para>
/// </summary>
public EventQuery() : base() { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.EventQuery'/>
/// class for the specified query.</para>
/// </summary>
/// <param name='query'>A textual representation of the event query.</param>
public EventQuery(string query) : base(query) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.EventQuery'/>
/// class for the specified
/// language and query.</para>
/// </summary>
/// <param name='language'>The language in which the query string is specified. </param>
/// <param name=' query'>The string representation of the query.</param>
public EventQuery(string language, string query) : base(language, query) { }
//ICloneable
/// <summary>
/// <para>Returns a copy of the object.</para>
/// </summary>
/// <returns>
/// The cloned object.
/// </returns>
public override object Clone()
{
return new EventQuery(QueryLanguage, QueryString);
}
}//EventQuery
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Represents a WMI data query in WQL format.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This sample demonstrates how to use a WqlObjectQuery class to
/// // perform an object query.
///
/// class Sample_WqlObjectQuery
/// {
/// public static int Main(string[] args) {
/// WqlObjectQuery objectQuery = new WqlObjectQuery("select * from Win32_Share");
/// ManagementObjectSearcher searcher =
/// new ManagementObjectSearcher(objectQuery);
///
/// foreach (ManagementObject share in searcher.Get()) {
/// Console.WriteLine("Share = " + share["Name"]);
/// }
///
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This sample demonstrate how to use a WqlObjectQuery class to
/// ' perform an object query.
///
/// Class Sample_WqlObjectQuery
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim objectQuery As New WqlObjectQuery("select * from Win32_Share")
/// Dim searcher As New ManagementObjectSearcher(objectQuery)
///
/// Dim share As ManagementObject
/// For Each share In searcher.Get()
/// Console.WriteLine("Share = " & share("Name"))
/// Next share
///
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
public class WqlObjectQuery : ObjectQuery
{
//constructors
//Here we don't take a language argument but hard-code it to WQL in the base class
/// <overload>
/// <para>Initializes a new instance of the <see cref='System.Management.WqlObjectQuery'/> class.</para>
/// </overload>
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.WqlObjectQuery'/> class. This is the
/// default constructor.</para>
/// </summary>
public WqlObjectQuery() : base(null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.WqlObjectQuery'/> class initialized to the
/// specified query.</para>
/// </summary>
/// <param name='query'><para> The representation of the data query.</para></param>
public WqlObjectQuery(string query) : base(query) { }
//QueryLanguage property is read-only in this class (does this work ??)
/// <summary>
/// <para>Gets or sets the language of the query.</para>
/// </summary>
/// <value>
/// <para> The value of this
/// property is always "WQL".</para>
/// </value>
public override string QueryLanguage
{
get
{ return base.QueryLanguage; }
}
//ICloneable
/// <summary>
/// <para>Creates a copy of the object.</para>
/// </summary>
/// <returns>
/// The copied object.
/// </returns>
public override object Clone()
{
return new WqlObjectQuery(QueryString);
}
}//WqlObjectQuery
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Represents a WQL SELECT data query.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This sample demonstrates how to perform a WQL select query.
///
/// class Sample_SelectQuery
/// {
/// public static int Main(string[] args) {
/// SelectQuery selectQuery = new SelectQuery("win32_logicaldisk");
/// ManagementObjectSearcher searcher =
/// new ManagementObjectSearcher(selectQuery);
///
/// foreach (ManagementObject disk in searcher.Get()) {
/// Console.WriteLine(disk.ToString());
/// }
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This sample demonstrates how to perform a WQL select query.
///
/// Class Sample_SelectQuery
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim selectQuery As New SelectQuery("win32_logicaldisk")
/// Dim searcher As New ManagementObjectSearcher(selectQuery)
///
/// Dim disk As ManagementObject
/// For Each disk In searcher.Get()
/// Console.WriteLine(disk.ToString())
/// Next disk
///
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
public class SelectQuery : WqlObjectQuery
{
private bool isSchemaQuery;
private string className;
private string condition;
private StringCollection selectedProperties;
//default constructor
/// <overload>
/// <para>Initializes a new instance of the <see cref='System.Management.SelectQuery'/>
/// class.</para>
/// </overload>
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.SelectQuery'/>
/// class. This is the
/// default constructor.</para>
/// </summary>
public SelectQuery() : this(null) { }
//parameterized constructors
//ISSUE : We have 2 possible constructors that take a single string :
// one that takes the full query string and the other that takes the class name.
// We resolve this by trying to parse the string, if it succeeds we assume it's the query, if
// not we assume it's the class name.
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.SelectQuery'/> class for the specified
/// query or the specified class name.</para>
/// </summary>
/// <param name='queryOrClassName'>The entire query or the class name to use in the query. The parser in this class attempts to parse the string as a valid WQL SELECT query. If the parser is unsuccessful, it assumes the string is a class name.</param>
/// <example>
/// <code lang='C#'>SelectQuery s = new SelectQuery("SELECT * FROM Win32_Service WHERE State='Stopped');
///
/// or
///
/// //This is equivalent to "SELECT * FROM Win32_Service"
/// SelectQuery s = new SelectQuery("Win32_Service");
/// </code>
/// <code lang='VB'>Dim s As New SelectQuery("SELECT * FROM Win32_Service WHERE State='Stopped')
///
/// or
///
/// //This is equivalent to "SELECT * FROM Win32_Service"
/// Dim s As New SelectQuery("Win32_Service")
/// </code>
/// </example>
public SelectQuery(string queryOrClassName)
{
selectedProperties = new StringCollection();
if (null != queryOrClassName)
{
// Minimally determine if the string is a query or class name.
//
if (queryOrClassName.TrimStart().StartsWith(TokenSelect, StringComparison.OrdinalIgnoreCase))
{
// Looks to be a query - do further checking.
//
QueryString = queryOrClassName; // Parse/validate; may throw.
}
else
{
// Do some basic sanity checking on whether it's a class name
//
ManagementPath p = new ManagementPath(queryOrClassName);
if (p.IsClass && (p.NamespacePath.Length == 0))
ClassName = queryOrClassName;
else
throw new ArgumentException(SR.InvalidQuery, nameof(queryOrClassName));
}
}
}
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.SelectQuery'/>
/// class with the specified
/// class name and condition.</para>
/// </summary>
/// <param name='className'>The name of the class to select in the query.</param>
/// <param name=' condition'>The condition to be applied in the query.</param>
/// <example>
/// <code lang='C#'>SelectQuery s = new SelectQuery("Win32_Process", "HandleID=1234");
/// </code>
/// <code lang='VB'>Dim s As New SelectQuery("Win32_Process", "HandleID=1234")
/// </code>
/// </example>
public SelectQuery(string className, string condition) : this(className, condition, null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.SelectQuery'/>
/// class with the specified
/// class name and condition, selecting only the specified properties.</para>
/// </summary>
/// <param name='className'>The name of the class from which to select.</param>
/// <param name='condition'>The condition to be applied to instances of the selected class.</param>
/// <param name='selectedProperties'>An array of property names to be returned in the query results.</param>
/// <example>
/// <code lang='C#'>String[] properties = {"VariableName", "VariableValue"};
///
/// SelectQuery s = new SelectQuery("Win32_Environment",
/// "User='<system>'",
/// properties);
/// </code>
/// <code lang='VB'>Dim properties As String[] = {"VariableName", "VariableValue"}
///
/// Dim s As New SelectQuery("Win32_Environment", _
/// "User=""<system>""", _
/// properties)
/// </code>
/// </example>
public SelectQuery(string className, string condition, string[] selectedProperties) : base()
{
this.isSchemaQuery = false;
this.className = className;
this.condition = condition;
this.selectedProperties = new StringCollection();
if (null != selectedProperties)
this.selectedProperties.AddRange(selectedProperties);
BuildQuery();
}
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.SelectQuery'/>
/// class for a schema query, optionally specifying a condition. For schema queries,
/// only the <paramref name="condition"/> parameter is valid.</para>
/// </summary>
/// <param name='isSchemaQuery'><see langword='true'/>to indicate that this is a schema query; otherwise, <see langword='false'/>. A <see langword='false'/> value is invalid in this constructor.</param>
/// <param name='condition'>The condition to be applied to form the result set of classes.</param>
/// <example>
/// <code lang='C#'>SelectQuery s = new SelectQuery(true, "__CLASS = 'Win32_Service'");
/// </code>
/// <code lang='VB'>Dim s As New SelectQuery(true, "__CLASS = ""Win32_Service""")
/// </code>
/// </example>
public SelectQuery(bool isSchemaQuery, string condition) : base()
{
if (isSchemaQuery == false)
throw new ArgumentException(SR.InvalidQuery, nameof(isSchemaQuery));
this.isSchemaQuery = true;
this.className = null;
this.condition = condition;
this.selectedProperties = null;
BuildQuery();
}
/// <summary>
/// <para>Gets or sets the query in the <see cref='System.Management.SelectQuery'/>, in string form.</para>
/// </summary>
/// <value>
/// <para>A string representing the query.</para>
/// </value>
/// <remarks>
/// <para> Setting this
/// property value overrides any previous value stored in the object. In addition, setting this
/// property causes the other members of the object to be updated when the string
/// is reparsed.</para>
/// </remarks>
/// <example>
/// <code lang='C#'>SelectQuery s = new SelectQuery();
/// s.QueryString = "SELECT * FROM Win32_LogicalDisk";
/// </code>
/// <code lang='VB'>Dim s As New SelectQuery()
/// s.QueryString = "SELECT * FROM Win32_LogicalDisk"
/// </code>
/// </example>
public override string QueryString
{
get
{
// We need to force a rebuild as we may not have detected
// a change to selected properties
BuildQuery();
return base.QueryString;
}
set
{
base.QueryString = value;
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether this query is a schema query or an instances query.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if this query
/// should be evaluated over the schema; <see langword='false'/> if the query should
/// be evaluated over instances.</para>
/// </value>
/// <remarks>
/// <para>Setting this property value overrides any
/// previous value stored in the object. The query string is
/// rebuilt to reflect the new query type.</para>
/// </remarks>
public bool IsSchemaQuery
{
get
{ return isSchemaQuery; }
set
{ isSchemaQuery = value; BuildQuery(); FireIdentifierChanged(); }
}
/// <summary>
/// <para>Gets or sets the class name to be selected from in the query.</para>
/// </summary>
/// <value>
/// <para>A string representing the name of the
/// class.</para>
/// </value>
/// <remarks>
/// <para> Setting this property value
/// overrides any previous value stored in the object. The query string is
/// rebuilt to reflect the new class name.</para>
/// </remarks>
/// <example>
/// <code lang='C#'>SelectQuery s = new SelectQuery("SELECT * FROM Win32_LogicalDisk");
/// Console.WriteLine(s.QueryString); //output is : SELECT * FROM Win32_LogicalDisk
///
/// s.ClassName = "Win32_Process";
/// Console.WriteLine(s.QueryString); //output is : SELECT * FROM Win32_Process
/// </code>
/// <code lang='VB'>Dim s As New SelectQuery("SELECT * FROM Win32_LogicalDisk")
/// Console.WriteLine(s.QueryString) 'output is : SELECT * FROM Win32_LogicalDisk
///
/// s.ClassName = "Win32_Process"
/// Console.WriteLine(s.QueryString) 'output is : SELECT * FROM Win32_Process
/// </code>
/// </example>
public string ClassName
{
get { return className ?? string.Empty; }
set { className = value; BuildQuery(); FireIdentifierChanged(); }
}
/// <summary>
/// <para>Gets or sets the condition to be applied in the SELECT
/// query.</para>
/// </summary>
/// <value>
/// A string containing the condition to
/// be applied in the SELECT query.
/// </value>
/// <remarks>
/// <para> Setting this property value overrides any previous value
/// stored in the object. The query string is rebuilt to reflect the new
/// condition.</para>
/// </remarks>
public string Condition
{
get { return condition ?? string.Empty; }
set { condition = value; BuildQuery(); FireIdentifierChanged(); }
}
/// <summary>
/// <para> Gets or sets an array of property names to be
/// selected in the query.</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Collections.Specialized.StringCollection'/> containing the names of the
/// properties to be selected in the query.</para>
/// </value>
/// <remarks>
/// <para> Setting this property value overrides any previous value stored
/// in the object. The query string is rebuilt to reflect the new
/// properties.</para>
/// </remarks>
public StringCollection SelectedProperties
{
get { return selectedProperties; }
set
{
if (null != value)
{
// A tad painful since StringCollection doesn't support ICloneable
StringCollection src = (StringCollection)value;
StringCollection dst = new StringCollection();
foreach (string s in src)
dst.Add(s);
selectedProperties = dst;
}
else
selectedProperties = new StringCollection();
BuildQuery();
FireIdentifierChanged();
}
}
/// <summary>
/// Builds the query string according to the current property values.
/// </summary>
protected internal void BuildQuery()
{
string s;
if (isSchemaQuery == false) //this is an instances query
{
//If the class name is not set we can't build a query
//Shouldn't throw here because the user may be in the process of filling in the properties...
if (className == null)
SetQueryString(string.Empty);
if ((className == null) || (className.Length == 0))
return;
//Select clause
s = TokenSelect;
//If properties are specified list them
if ((null != selectedProperties) && (0 < selectedProperties.Count))
{
int count = selectedProperties.Count;
for (int i = 0; i < count; i++)
s = s + selectedProperties[i] + ((i == (count - 1)) ? " " : ",");
}
else
s += "* ";
//From clause
s = s + "from " + className;
}
else //this is a schema query, ignore className or selectedProperties.
{
//Select clause
s = "select * from meta_class";
}
//Where clause
if ((Condition != null) && (Condition.Length != 0))
s = s + " where " + condition;
//Set the queryString member to the built query (NB: note we set
//by accessing the internal helper function rather than the property,
//since we do not want to force a parse of a query we just built).
SetQueryString(s);
}
/// <summary>
/// Parses the query string and sets the property values accordingly.
/// </summary>
/// <param name="query">The query string to be parsed.</param>
protected internal override void ParseQuery(string query)
{
//Clear out previous property values
className = null;
condition = null;
selectedProperties?.Clear();
//Trim whitespaces
string q = query.Trim();
bool bFound = false; string tempProp; int i;
if (isSchemaQuery == false) //instances query
{
//Find "select" clause and get the property list if exists
string keyword = TokenSelect;
if ((q.Length >= keyword.Length) && (string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase) == 0)) //select clause found
{
ParseToken(ref q, keyword, ref bFound);
if (q[0] != '*') //we have properties
{
if (null != selectedProperties)
selectedProperties.Clear();
else
selectedProperties = new StringCollection();
//get the property list
while (true)
{
if ((i = q.IndexOf(',')) > 0)
{
tempProp = q.Substring(0, i);
q = q.Remove(0, i + 1).TrimStart(null);
tempProp = tempProp.Trim();
if (tempProp.Length > 0)
selectedProperties.Add(tempProp);
}
else
{ //last property in the list
if ((i = q.IndexOf(' ')) > 0)