forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCimSessionProxy.cs
More file actions
2316 lines (2105 loc) · 84.4 KB
/
Copy pathCimSessionProxy.cs
File metadata and controls
2316 lines (2105 loc) · 84.4 KB
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
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.Management.Infrastructure.Generic;
using Microsoft.Management.Infrastructure.Options;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
#region Context base class
/// <summary>
/// context base class for cross operations
/// for example, some cmdlets need to query instance first and then
/// remove instance, those scenarios need context object transferred
/// from one operation to another.
/// </summary>
internal abstract class XOperationContextBase
{
/// <summary>
/// <para>namespace</para>
/// </summary>
internal string Namespace
{
get
{
return this.nameSpace;
}
}
protected string nameSpace;
/// <summary>
/// <para>
/// Session proxy
/// </para>
/// </summary>
internal CimSessionProxy Proxy
{
get
{
return this.proxy;
}
}
protected CimSessionProxy proxy;
}
/// <summary>
/// class provides all information regarding the
/// current invocation to .net api
/// </summary>
internal class InvocationContext
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="proxy"></param>
internal InvocationContext(CimSessionProxy proxy)
{
if (proxy != null)
{
this.ComputerName = proxy.CimSession.ComputerName;
this.TargetCimInstance = proxy.TargetCimInstance;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="proxy"></param>
internal InvocationContext(string computerName, CimInstance targetCimInstance)
{
this.ComputerName = computerName;
this.TargetCimInstance = targetCimInstance;
}
/// <summary>
/// <para>
/// ComputerName of the session
/// </para>
/// <remarks>
/// return value could be null
/// </remarks>
/// </summary>
internal virtual string ComputerName
{
get;
private set;
}
/// <summary>
/// <para>
/// CimInstance on which the current operation against.
/// </para>
/// <remarks>
/// return value could be null
/// </remarks>
/// </summary>
internal virtual CimInstance TargetCimInstance
{
get;
private set;
}
}
#endregion
#region Preprocessing of result object interface
/// <summary>
/// Defines a method to preprocessing an result object before sending to
/// output pipeline.
/// </summary>
[ComVisible(false)]
internal interface IObjectPreProcess
{
/// <summary>
/// Performs pre processing of given result object.
/// </summary>
/// <param name="resultObject"></param>
/// <returns>Pre-processed object</returns>
object Process(object resultObject);
}
#endregion
#region Eventargs class
/// <summary>
/// <para>
/// CmdletActionEventArgs holds a CimBaseAction object
/// </para>
/// </summary>
internal sealed class CmdletActionEventArgs : EventArgs
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="action">CimBaseAction object bound to the event</param>
public CmdletActionEventArgs(CimBaseAction action)
{
this.Action = action;
}
public readonly CimBaseAction Action;
}
/// <summary>
/// OperationEventArgs holds a cancellation object, and an operation.
/// </summary>
internal sealed class OperationEventArgs : EventArgs
{
/// <summary>
/// constructor
/// </summary>
/// <param name="operationCancellation">Object used to cancel the operation</param>
/// <param name="operation">Async observable operation</param>
public OperationEventArgs(IDisposable operationCancellation,
IObservable<object> operation,
bool theSuccess)
{
this.operationCancellation = operationCancellation;
this.operation = operation;
this.success = theSuccess;
}
public readonly IDisposable operationCancellation;
public readonly IObservable<object> operation;
public readonly bool success;
}
#endregion
/// <summary>
/// <para>
/// Wrapper of <see cref="CimSession"/> object.
/// A CimSessionProxy object can only execute one operation at specific moment.
/// </para>
/// </summary>
internal class CimSessionProxy : IDisposable
{
#region static members
/// <summary>
/// <para>
/// global operation counter
/// </para>
/// </summary>
private static long gOperationCounter = 0;
/// <summary>
/// temporary CimSession cache lock
/// </summary>
private static readonly object temporarySessionCacheLock = new object();
/// <summary>
/// <para>temporary CimSession cache</para>
/// <para>Temporary CimSession means the session is created by cimcmdlets,
/// which is not created by <see cref="New-CimSession"/> cmdlet.
/// Due to some cmdlet, such as <see cref="Remove-CimInstance"/>
/// might need to split the operation into multiple stages, i.e., query
/// CimInstance firstly, then remove the CimInstance resulted from query,
/// such that the temporary CimSession need to be shared between
/// multiple <see cref="CimSessionProxy"/> objects, introducing a
/// temporary session cache is necessary to control the lifetime of the
/// temporary CimSession objects.</para>
/// <para>
/// Once the reference count of the CimSession is decreased to 0,
/// then call Dispose on it.
/// </para>
/// </summary>
private static Dictionary<CimSession, uint> temporarySessionCache = new Dictionary<CimSession, uint>();
/// <summary>
/// <para>
/// Add <see cref="CimSession"/> to temporary cache.
/// If CimSession already present in cache, then increase the refcount by 1,
/// otherwise insert it into the cache.
/// </para>
/// </summary>
/// <param name="session">CimSession to be added</param>
internal static void AddCimSessionToTemporaryCache(CimSession session)
{
if (null != session)
{
lock (temporarySessionCacheLock)
{
if (temporarySessionCache.ContainsKey(session))
{
temporarySessionCache[session]++;
DebugHelper.WriteLogEx(@"Increase cimsession ref count {0}", 1, temporarySessionCache[session]);
}
else
{
temporarySessionCache.Add(session, 1);
DebugHelper.WriteLogEx(@"Add cimsession to cache. Ref count {0}", 1, temporarySessionCache[session]);
}
}
}
}
/// <summary>
/// <para>Wrapper function to remove CimSession from cache</para>
/// </summary>
/// <param name="session"></param>
/// <param name="dispose">Whether need to dispose the <see cref="CimSession"/> object</param>
private static void RemoveCimSessionFromTemporaryCache(CimSession session,
bool dispose)
{
if (null != session)
{
bool removed = false;
lock (temporarySessionCacheLock)
{
if (temporarySessionCache.ContainsKey(session))
{
temporarySessionCache[session]--;
DebugHelper.WriteLogEx(@"Decrease cimsession ref count {0}", 1, temporarySessionCache[session]);
if (temporarySessionCache[session] == 0)
{
removed = true;
temporarySessionCache.Remove(session);
}
}
}
// there is a race condition that if
// one thread is waiting to add CimSession to cache,
// while current thread is removing the CimSession,
// then invalid CimSession may be added to cache.
// Ignored this scenario in CimCmdlet implementation,
// since the code inside cimcmdlet will not hit this
// scenario anyway.
if (removed && dispose)
{
DebugHelper.WriteLogEx(@"Dispose cimsession ", 1);
session.Dispose();
}
}
}
/// <summary>
/// <para>
/// Remove <see cref="CimSession"/> from temporary cache.
/// If CimSession already present in cache, then decrease the refcount by 1,
/// otherwise ignore.
/// If refcount became 0, call dispose on the <see cref="CimSession"/> object.
/// </para>
/// </summary>
/// <param name="session">CimSession to be added</param>
internal static void RemoveCimSessionFromTemporaryCache(CimSession session)
{
RemoveCimSessionFromTemporaryCache(session, true);
}
#endregion
#region Event definitions
/// <summary>
/// Define delegate that handles new cmdlet action come from
/// the operations related to the current CimSession object.
/// </summary>
/// <param name="cimSession">cimSession object, which raised the event</param>
/// <param name="actionArgs">Event args</param>
public delegate void NewCmdletActionHandler(
object cimSession,
CmdletActionEventArgs actionArgs);
/// <summary>
/// Define an Event based on the NewActionHandler
/// </summary>
public event NewCmdletActionHandler OnNewCmdletAction;
/// <summary>
/// Define delegate that handles operation creation and complete
/// issued by the current CimSession object.
/// </summary>
/// <param name="cimSession">cimSession object, which raised the event</param>
/// <param name="actionArgs">Event args</param>
public delegate void OperationEventHandler(
object cimSession,
OperationEventArgs actionArgs);
/// <summary>
/// Event triggered when a new operation is started
/// </summary>
public event OperationEventHandler OnOperationCreated;
/// <summary>
/// Event triggered when a new operation is completed,
/// either success or failed.
/// </summary>
public event OperationEventHandler OnOperationDeleted;
#endregion
#region constructors
/// <summary>
/// Then create wrapper object by given CimSessionProxy object.
/// </summary>
/// <param name="computerName"></param>
public CimSessionProxy(CimSessionProxy proxy)
{
DebugHelper.WriteLogEx("protocol = {0}", 1, proxy.Protocol);
CreateSetSession(null, proxy.CimSession, null, proxy.OperationOptions, proxy.IsTemporaryCimSession);
this.protocol = proxy.Protocol;
this.OperationTimeout = proxy.OperationTimeout;
this.isDefaultSession = proxy.isDefaultSession;
}
/// <summary>
/// Create <see cref="CimSession"/> by given computer name.
/// Then create wrapper object.
/// </summary>
/// <param name="computerName"></param>
public CimSessionProxy(string computerName)
{
CreateSetSession(computerName, null, null, null, false);
this.isDefaultSession = (computerName == ConstValue.NullComputerName);
}
/// <summary>
/// Create <see cref="CimSession"/> by given computer name
/// and session options.
/// Then create wrapper object.
/// </summary>
/// <param name="computerName"></param>
/// <param name="sessionOptions"></param>
public CimSessionProxy(string computerName, CimSessionOptions sessionOptions)
{
CreateSetSession(computerName, null, sessionOptions, null, false);
this.isDefaultSession = (computerName == ConstValue.NullComputerName);
}
/// <summary>
/// Create <see cref="CimSession"/> by given computer name
/// and cimInstance. Then create wrapper object.
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
public CimSessionProxy(string computerName, CimInstance cimInstance)
{
DebugHelper.WriteLogEx("ComputerName {0}; cimInstance.CimSessionInstanceID = {1}; cimInstance.CimSessionComputerName = {2}.",
0,
computerName,
cimInstance.GetCimSessionInstanceId(),
cimInstance.GetCimSessionComputerName());
if (computerName != ConstValue.NullComputerName)
{
CreateSetSession(computerName, null, null, null, false);
return;
}
Debug.Assert(cimInstance != null, "Caller should verify cimInstance != null");
// computerName is null, fallback to create session from cimInstance
CimSessionState state = CimSessionBase.GetCimSessionState();
if (state != null)
{
CimSession session = state.QuerySession(cimInstance.GetCimSessionInstanceId());
if (session != null)
{
DebugHelper.WriteLogEx("Found the session from cache with InstanceID={0}.", 0, cimInstance.GetCimSessionInstanceId());
CreateSetSession(null, session, null, null, false);
return;
}
}
String cimsessionComputerName = cimInstance.GetCimSessionComputerName();
CreateSetSession(cimsessionComputerName, null, null, null, false);
this.isDefaultSession = (cimsessionComputerName == ConstValue.NullComputerName);
DebugHelper.WriteLogEx("Create a temp session with computerName = {0}.", 0, cimsessionComputerName);
}
/// <summary>
/// Create <see cref="CimSession"/> by given computer name,
/// session options
/// </summary>
/// <param name="computerName"></param>
/// <param name="sessionOptions"></param>
/// <param name="operOptions">Used when create async operation</param>
public CimSessionProxy(string computerName, CimSessionOptions sessionOptions, CimOperationOptions operOptions)
{
CreateSetSession(computerName, null, sessionOptions, operOptions, false);
this.isDefaultSession = (computerName == ConstValue.NullComputerName);
}
/// <summary>
/// Create <see cref="CimSession"/> by given computer name.
/// Then create wrapper object.
/// </summary>
/// <param name="computerName"></param>
/// <param name="operOptions">Used when create async operation</param>
public CimSessionProxy(string computerName, CimOperationOptions operOptions)
{
CreateSetSession(computerName, null, null, operOptions, false);
this.isDefaultSession = (computerName == ConstValue.NullComputerName);
}
/// <summary>
/// Create wrapper object by given session object
/// </summary>
/// <param name="session"></param>
public CimSessionProxy(CimSession session)
{
CreateSetSession(null, session, null, null, false);
}
/// <summary>
/// Create wrapper object by given session object
/// </summary>
/// <param name="session"></param>
/// <param name="operOptions">Used when create async operation</param>
public CimSessionProxy(CimSession session, CimOperationOptions operOptions)
{
CreateSetSession(null, session, null, operOptions, false);
}
/// <summary>
/// Initialize CimSessionProxy object
/// </summary>
/// <param name="computerName"></param>
/// <param name="session"></param>
/// <param name="sessionOptions"></param>
/// <param name="options"></param>
private void CreateSetSession(
string computerName,
CimSession cimSession,
CimSessionOptions sessionOptions,
CimOperationOptions operOptions,
bool temporaryCimSession)
{
DebugHelper.WriteLogEx("computername {0}; cimsession {1}; sessionOptions {2}; operationOptions {3}.", 0, computerName, cimSession, sessionOptions, operOptions);
lock (this.stateLock)
{
this.CancelOperation = null;
this.operation = null;
}
InitOption(operOptions);
this.protocol = ProtocolType.Wsman;
this.isTemporaryCimSession = temporaryCimSession;
if (cimSession != null)
{
this.session = cimSession;
CimSessionState state = CimSessionBase.GetCimSessionState();
if (state != null)
{
CimSessionWrapper wrapper = state.QuerySession(cimSession);
if (wrapper != null)
{
this.protocol = wrapper.GetProtocolType();
}
}
}
else
{
if (sessionOptions != null)
{
if (sessionOptions is DComSessionOptions)
{
string defaultComputerName = ConstValue.IsDefaultComputerName(computerName) ? ConstValue.NullComputerName : computerName;
this.session = CimSession.Create(defaultComputerName, sessionOptions);
this.protocol = ProtocolType.Dcom;
}
else
{
this.session = CimSession.Create(computerName, sessionOptions);
}
}
else
{
this.session = CreateCimSessionByComputerName(computerName);
}
this.isTemporaryCimSession = true;
}
if (this.isTemporaryCimSession)
{
AddCimSessionToTemporaryCache(this.session);
}
this.invocationContextObject = new InvocationContext(this);
DebugHelper.WriteLog("Protocol {0}, Is temporary session ? {1}", 1, this.protocol, this.isTemporaryCimSession);
}
#endregion
#region set operation options
/// <summary>
/// Set timeout value (seconds) of the operation
/// </summary>
public UInt32 OperationTimeout
{
set
{
DebugHelper.WriteLogEx("OperationTimeout {0},", 0, value);
this.options.Timeout = TimeSpan.FromSeconds((double)value);
}
get
{
return (UInt32)this.options.Timeout.TotalSeconds;
}
}
/// <summary>
/// Set resource URI of the operation
/// </summary>
public Uri ResourceUri
{
set
{
DebugHelper.WriteLogEx("ResourceUri {0},", 0, value);
this.options.ResourceUri= value;
}
get
{
return this.options.ResourceUri;
}
}
/// <summary>
/// Enable/Disable the method result streaming,
/// it is enabled by default.
/// </summary>
public bool EnableMethodResultStreaming
{
get
{
return this.options.EnableMethodResultStreaming;
}
set
{
DebugHelper.WriteLogEx("EnableMethodResultStreaming {0}", 0, value);
this.options.EnableMethodResultStreaming = value;
}
}
/// <summary>
/// Enable/Disable prompt user streaming,
/// it is enabled by default.
/// </summary>
public bool EnablePromptUser
{
set
{
DebugHelper.WriteLogEx("EnablePromptUser {0}", 0, value);
if(value)
{
this.options.PromptUser = this.PromptUser;
}
}
}
/// <summary>
/// Enable the pssemantics
/// </summary>
private void EnablePSSemantics()
{
DebugHelper.WriteLogEx();
// this.options.PromptUserForceFlag...
// this.options.WriteErrorMode
this.options.WriteErrorMode = CimCallbackMode.Inquire;
// !!!NOTES: Does not subscribe to PromptUser for CimCmdlets now
// since cmdlet does not provider an approach
// to let user select how to handle prompt message
// this can be enabled later if needed.
this.options.WriteError = this.WriteError;
this.options.WriteMessage = this.WriteMessage;
this.options.WriteProgress = this.WriteProgress;
}
/// <summary>
/// Set keyonly property.
/// </summary>
public SwitchParameter KeyOnly
{
set { this.options.KeysOnly = value.IsPresent; }
}
/// <summary>
/// Set Shallow flag.
/// </summary>
public SwitchParameter Shallow
{
set
{
if (value.IsPresent)
{
this.options.Flags = CimOperationFlags.PolymorphismShallow;
}
else
{
this.options.Flags = CimOperationFlags.None;
}
}
}
/// <summary>
/// Initialize the operation option
/// </summary>
private void InitOption(CimOperationOptions operOptions)
{
DebugHelper.WriteLogEx();
if (operOptions != null)
{
this.options = new CimOperationOptions(operOptions);
}
else if (this.options == null)
{
this.options = new CimOperationOptions();
}
this.EnableMethodResultStreaming = true;
this.EnablePSSemantics();
}
#endregion
#region misc operations
/// <summary>
/// Caller call Detach to retrieve the session
/// object and control the lifecycle of the CimSession object.
/// </summary>
/// <returns></returns>
public CimSession Detach()
{
DebugHelper.WriteLogEx();
// Remove the CimSession from cache but don't dispose it
RemoveCimSessionFromTemporaryCache(this.session, false);
CimSession sessionToReturn = this.session;
this.session = null;
this.isTemporaryCimSession = false;
return sessionToReturn;
}
/// <summary>
/// Add a new operation to cache.
/// </summary>
/// <param name="operation"></param>
/// <param name="cancelObject"></param>
private void AddOperation(IObservable<object> operation)
{
DebugHelper.WriteLogEx();
lock (this.stateLock)
{
Debug.Assert(this.Completed, "Caller should verify that there is no operation in progress");
this.operation = operation;
}
}
/// <summary>
/// Remove object from cache
/// </summary>
/// <param name="operation"></param>
private void RemoveOperation(IObservable<object> operation)
{
DebugHelper.WriteLogEx();
lock (this.stateLock)
{
Debug.Assert(this.operation == operation, "Caller should verify that the operation to remove is the operation in progress");
this.DisposeCancelOperation();
if (this.operation != null)
{
this.operation = null;
}
if (this.session != null && this.ContextObject == null)
{
DebugHelper.WriteLog("Dispose this proxy object @ RemoveOperation");
this.Dispose();
}
}
}
/// <summary>
/// <para>
/// Trigger an event that new action available
/// </para>
/// </summary>
/// <param name="action"></param>
protected void FireNewActionEvent(CimBaseAction action)
{
DebugHelper.WriteLogEx();
CmdletActionEventArgs actionArgs = new CmdletActionEventArgs(action);
if (!PreNewActionEvent(actionArgs))
{
return;
}
NewCmdletActionHandler temp = this.OnNewCmdletAction;
if (temp != null)
{
temp(this.session, actionArgs);
}
else
{
DebugHelper.WriteLog("Ignore action since OnNewCmdletAction is null.", 5);
}
this.PostNewActionEvent(actionArgs);
}
/// <summary>
/// <para>
/// Trigger an event that new operation is created
/// </para>
/// </summary>
/// <param name="cancelOperation"></param>
/// <param name="operation"></param>
private void FireOperationCreatedEvent(
IDisposable cancelOperation,
IObservable<object> operation)
{
DebugHelper.WriteLogEx();
OperationEventArgs args = new OperationEventArgs(
cancelOperation, operation, false);
OperationEventHandler temp = this.OnOperationCreated;
if (temp != null)
{
temp(this.session, args);
}
this.PostOperationCreateEvent(args);
}
/// <summary>
/// <para>
/// Trigger an event that an operation is deleted
/// </para>
/// </summary>
/// <param name="operation"></param>
private void FireOperationDeletedEvent(
IObservable<object> operation,
bool success)
{
DebugHelper.WriteLogEx();
this.WriteOperationCompleteMessage(this.operationName);
OperationEventArgs args = new OperationEventArgs(
null, operation, success);
PreOperationDeleteEvent(args);
OperationEventHandler temp = this.OnOperationDeleted;
if (temp != null)
{
temp(this.session, args);
}
this.PostOperationDeleteEvent(args);
this.RemoveOperation(operation);
this.operationName = null;
}
#endregion
#region PSExtension callback functions
/// <summary>
/// <para>
/// WriteMessage callback
/// </para>
/// </summary>
/// <param name="channel"></param>
/// <param name="message"></param>
internal void WriteMessage(UInt32 channel, string message)
{
DebugHelper.WriteLogEx("Channel = {0} message = {1}", 0, channel, message);
try
{
CimWriteMessage action = new CimWriteMessage(channel, message);
this.FireNewActionEvent(action);
}
catch (Exception ex)
{
DebugHelper.WriteLogEx("{0}", 0, ex);
}
}
/// <summary>
/// <para>
/// Write operation start verbose message
/// </para>
/// </summary>
/// <param name="operation"></param>
/// <param name="parameters"></param>
internal void WriteOperationStartMessage(string operation, Hashtable parameterList)
{
DebugHelper.WriteLogEx();
StringBuilder parameters = new StringBuilder();
if (parameterList != null)
{
foreach (string key in parameterList.Keys)
{
if (parameters.Length > 0)
{
parameters.Append(",");
}
parameters.Append(string.Format(CultureInfo.CurrentUICulture, @"'{0}' = {1}", key, parameterList[key]));
}
}
string operationStartMessage = string.Format(CultureInfo.CurrentUICulture,
Strings.CimOperationStart,
operation,
(parameters.Length == 0) ? "null" : parameters.ToString());
WriteMessage((UInt32)CimWriteMessageChannel.Verbose, operationStartMessage);
}
/// <summary>
/// <para>
/// Write operation complete verbose message
/// </para>
/// </summary>
/// <param name="operation"></param>
internal void WriteOperationCompleteMessage(string operation)
{
DebugHelper.WriteLogEx();
string operationCompleteMessage = string.Format(CultureInfo.CurrentUICulture,
Strings.CimOperationCompleted,
operation);
WriteMessage((UInt32)CimWriteMessageChannel.Verbose, operationCompleteMessage);
}
/// <summary>
/// <para>
/// WriteProgress callback
/// </para>
/// </summary>
/// <param name="activity"></param>
/// <param name="currentOperation"></param>
/// <param name="statusDescription"></param>
/// <param name="percentageCompleted"></param>
/// <param name="secondsRemaining"></param>
public void WriteProgress(string activity,
string currentOperation,
string statusDescription,
UInt32 percentageCompleted,
UInt32 secondsRemaining)
{
DebugHelper.WriteLogEx("activity:{0}; currentOperation:{1}; percentageCompleted:{2}; secondsRemaining:{3}",
0, activity, currentOperation, percentageCompleted, secondsRemaining);
try
{
CimWriteProgress action = new CimWriteProgress(
activity,
(int)this.operationID,
currentOperation,
statusDescription,
percentageCompleted,
secondsRemaining);
this.FireNewActionEvent(action);
}
catch (Exception ex)
{
DebugHelper.WriteLogEx("{0}", 0, ex);
}
}
/// <summary>
/// <para>
/// WriteError callback
/// </para>
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public CimResponseType WriteError(CimInstance instance)
{
DebugHelper.WriteLogEx("Error:{0}", 0, instance);
try
{
CimWriteError action = new CimWriteError(instance, this.invocationContextObject);
this.FireNewActionEvent(action);
return action.GetResponse();
}
catch (Exception ex)
{
DebugHelper.WriteLogEx("{0}", 0, ex);
return CimResponseType.NoToAll;
}
}
/// <summary>
/// PromptUser callback
/// </summary>
/// <param name="message"></param>
/// <param name="prompt"></param>
/// <returns></returns>
public CimResponseType PromptUser(string message, CimPromptType prompt)
{
DebugHelper.WriteLogEx("message:{0} prompt:{1}", 0, message, prompt);
try
{
CimPromptUser action = new CimPromptUser(message, prompt);
this.FireNewActionEvent(action);
return action.GetResponse();
}
catch (Exception ex)
{
DebugHelper.WriteLogEx("{0}", 0, ex);
return CimResponseType.NoToAll;
}
}
#endregion
#region Async result handler
/// <summary>
/// <para>
/// Handle async event triggered by <see cref="CimResultObserver<T>"/>
/// </para>
/// </summary>
/// <param name="observer">object triggered the event</param>
/// <param name="resultArgs">async result event argument</param>
internal void ResultEventHandler(
object observer,
AsyncResultEventArgsBase resultArgs)
{
DebugHelper.WriteLogEx();
switch (resultArgs.resultType)
{
case AsyncResultType.Completion:
{
DebugHelper.WriteLog("ResultEventHandler::Completion", 4);
AsyncResultCompleteEventArgs args = resultArgs as AsyncResultCompleteEventArgs;
this.FireOperationDeletedEvent(args.observable, true);
}
break;
case AsyncResultType.Exception:
{
AsyncResultErrorEventArgs args = resultArgs as AsyncResultErrorEventArgs;
DebugHelper.WriteLog("ResultEventHandler::Exception {0}", 4, args.error);
using (CimWriteError action = new CimWriteError(args.error, this.invocationContextObject, args.context))
{
this.FireNewActionEvent(action);
}
this.FireOperationDeletedEvent(args.observable, false);
}
break;
case AsyncResultType.Result:
{
AsyncResultObjectEventArgs args = resultArgs as AsyncResultObjectEventArgs;