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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Runspaces.Internal;
using System.Threading;

using Dbg = System.Management.Automation.Diagnostics;

#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings

namespace System.Management.Automation
{
    internal class RemotePipeline : Pipeline
    {
        #region Private Members

        private PowerShell _powershell;
        private readonly bool _addToHistory;
        private bool _isNested;
        private bool _isSteppable;
        private readonly Runspace _runspace;
        private readonly object _syncRoot = new object();
        private bool _disposed = false;
        private string _historyString;
        private PipelineStateInfo _pipelineStateInfo = new PipelineStateInfo(PipelineState.NotStarted);
        private readonly CommandCollection _commands = new CommandCollection();
        private readonly string _computerName;
        private readonly Guid _runspaceId;
        private readonly ConnectCommandInfo _connectCmdInfo = null;

        /// <summary>
        /// This is queue of all the state change event which have occurred for
        /// this pipeline. RaisePipelineStateEvents raises event for each
        /// item in this queue. We don't raise the event with in SetPipelineState
        /// because often SetPipelineState is called with in a lock.
        /// Raising event in lock introduces chances of deadlock in GUI applications.
        /// </summary>
        private Queue<ExecutionEventQueueItem> _executionEventQueue = new Queue<ExecutionEventQueueItem>();

        private sealed class ExecutionEventQueueItem
        {
            public ExecutionEventQueueItem(PipelineStateInfo pipelineStateInfo, RunspaceAvailability currentAvailability, RunspaceAvailability newAvailability)
            {
                this.PipelineStateInfo = pipelineStateInfo;
                this.CurrentRunspaceAvailability = currentAvailability;
                this.NewRunspaceAvailability = newAvailability;
            }

            public PipelineStateInfo PipelineStateInfo;
            public RunspaceAvailability CurrentRunspaceAvailability;
            public RunspaceAvailability NewRunspaceAvailability;
        }

        private readonly bool _performNestedCheck = true;

        #endregion Private Members

        #region Constructors

        /// <summary>
        /// Private constructor that does most of the work constructing a remote pipeline object.
        /// </summary>
        /// <param name="runspace">RemoteRunspace object.</param>
        /// <param name="addToHistory">AddToHistory.</param>
        /// <param name="isNested">IsNested.</param>
        private RemotePipeline(RemoteRunspace runspace, bool addToHistory, bool isNested)
            : base(runspace)
        {
            _addToHistory = addToHistory;
            _isNested = isNested;
            _isSteppable = false;
            _runspace = runspace;
            _computerName = ((RemoteRunspace)_runspace).ConnectionInfo.ComputerName;
            _runspaceId = _runspace.InstanceId;

            // Initialize streams
            _inputCollection = new PSDataCollection<object>();
            _inputCollection.ReleaseOnEnumeration = true;

            _inputStream = new PSDataCollectionStream<object>(Guid.Empty, _inputCollection);
            _outputCollection = new PSDataCollection<PSObject>();
            _outputStream = new PSDataCollectionStream<PSObject>(Guid.Empty, _outputCollection);
            _errorCollection = new PSDataCollection<ErrorRecord>();
            _errorStream = new PSDataCollectionStream<ErrorRecord>(Guid.Empty, _errorCollection);

            // Create object stream for method executor objects.
            MethodExecutorStream = new ObjectStream();
            IsMethodExecutorStreamEnabled = false;

            SetCommandCollection(_commands);

            // Create event which will be signalled when pipeline execution
            // is completed/failed/stopped.
            // Note:Runspace.Close waits for all the running pipeline
            // to finish.  This Event must be created before pipeline is
            // added to list of running pipelines. This avoids the race condition
            // where Close is called after pipeline is added to list of
            // running pipeline but before event is created.
            PipelineFinishedEvent = new ManualResetEvent(false);
        }

        /// <summary>
        /// Constructs a remote pipeline for the specified runspace and
        /// specified command.
        /// </summary>
        /// <param name="runspace">Runspace in which to create the pipeline.</param>
        /// <param name="command">Command as a string, to be used in pipeline creation.</param>
        /// <param name="addToHistory">Whether to add the command to the runspaces history.</param>
        /// <param name="isNested">Whether this pipeline is nested.</param>
        internal RemotePipeline(RemoteRunspace runspace, string command, bool addToHistory, bool isNested)
            : this(runspace, addToHistory, isNested)
        {
            if (command != null)
            {
                _commands.Add(new Command(command, true));
            }

            // initialize the underlying powershell object
            _powershell = new PowerShell(_inputStream, _outputStream, _errorStream,
                ((RemoteRunspace)_runspace).RunspacePool);

            _powershell.SetIsNested(isNested);

            _powershell.InvocationStateChanged += HandleInvocationStateChanged;
        }

        /// <summary>
        /// Constructs a remote pipeline object associated with a remote running
        /// command but in a disconnected state.
        /// </summary>
        /// <param name="runspace">Remote runspace associated with running command.</param>
        internal RemotePipeline(RemoteRunspace runspace)
            : this(runspace, false, false)
        {
            if (runspace.RemoteCommand == null)
            {
                throw new InvalidOperationException(PipelineStrings.InvalidRemoteCommand);
            }

            _connectCmdInfo = runspace.RemoteCommand;
            _commands.Add(_connectCmdInfo.Command);

            // Beginning state will be disconnected.
            SetPipelineState(PipelineState.Disconnected, null);

            // Create the underlying powershell object.
            _powershell = new PowerShell(_connectCmdInfo, _inputStream, _outputStream, _errorStream,
                ((RemoteRunspace)_runspace).RunspacePool);

            _powershell.InvocationStateChanged += HandleInvocationStateChanged;
        }

        /// <summary>
        /// Creates a cloned pipeline from the specified one.
        /// </summary>
        /// <param name="pipeline">Pipeline to clone from.</param>
        /// <remarks>This constructor is private because this will
        /// only be called from the copy method</remarks>
        private RemotePipeline(RemotePipeline pipeline)
            : this(
                (RemoteRunspace)pipeline.Runspace,
                command: null,
                addToHistory: false,
                pipeline.IsNested)
        {
            _isSteppable = pipeline._isSteppable;

            // NTRAID#Windows Out Of Band Releases-915851-2005/09/13
            // the above comment copied from RemotePipelineBase which
            // originally copied it from PipelineBase
            if (pipeline == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(pipeline));
            }

            if (pipeline._disposed)
            {
                throw PSTraceSource.NewObjectDisposedException("pipeline");
            }

            _addToHistory = pipeline._addToHistory;
            _historyString = pipeline._historyString;
            foreach (Command command in pipeline.Commands)
            {
                Command clone = command.Clone();

                // Attach the cloned Command to this pipeline.
                Commands.Add(clone);
            }
        }

        /// <summary>
        /// Override for creating a copy of pipeline.
        /// </summary>
        /// <returns>
        /// Pipeline object which is copy of this pipeline
        /// </returns>
        public override Pipeline Copy()
        {
            if (_disposed)
            {
                throw PSTraceSource.NewObjectDisposedException("pipeline");
            }

            return (Pipeline)new RemotePipeline(this);
        }

        #endregion Constructors

        #region Properties

        /// <summary>
        /// Access the runspace this pipeline is created on.
        /// </summary>
        public override Runspace Runspace
        {
            get
            {
#pragma warning disable 56503
                // NTRAID#Windows Out Of Band Releases-915851-2005/09/13
                if (_disposed)
                {
                    throw PSTraceSource.NewObjectDisposedException("pipeline");
                }
#pragma warning restore 56503

                return _runspace;
            }
        }

        /// <summary>
        /// This internal method doesn't do the _disposed check.
        /// </summary>
        /// <returns></returns>
        internal Runspace GetRunspace()
        {
            return _runspace;
        }

        /// <summary>
        /// Is this pipeline nested.
        /// </summary>
        public override bool IsNested
        {
            get
            {
                return _isNested;
            }
        }

        /// <summary>
        /// Internal method to set the value of IsNested. This is called
        /// by serializer.
        /// </summary>
        internal void SetIsNested(bool isNested)
        {
            _isNested = isNested;
            _powershell.SetIsNested(isNested);
        }

        /// <summary>
        /// Internal method to set the value of IsSteppable. This is called
        /// during DoConcurrentCheck.
        /// </summary>
        internal void SetIsSteppable(bool isSteppable)
        {
            _isSteppable = isSteppable;
        }

        /// <summary>
        /// Info about current state of the pipeline.
        /// </summary>
        /// <remarks>
        /// This value indicates the state of the pipeline after the change.
        /// </remarks>
        public override PipelineStateInfo PipelineStateInfo
        {
            get
            {
                lock (_syncRoot)
                {
                    // Note:We do not return internal state.
                    return _pipelineStateInfo.Clone();
                }
            }
        }

        /// <summary>
        /// Access the input writer for this pipeline.
        /// </summary>
        public override PipelineWriter Input
        {
            get
            {
                return _inputStream.ObjectWriter;
            }
        }

        /// <summary>
        /// Access the output reader for this pipeline.
        /// </summary>
        public override PipelineReader<PSObject> Output
        {
            get
            {
                return _outputStream.GetPSObjectReaderForPipeline(_computerName, _runspaceId);
            }
        }

        /// <summary>
        /// Access the error output reader for this pipeline.
        /// </summary>
        /// <remarks>
        /// This is the non-terminating error stream from the command.
        /// In this release, the objects read from this PipelineReader
        /// are PSObjects wrapping ErrorRecords.
        /// </remarks>
        public override PipelineReader<object> Error
        {
            get
            {
                return _errorStream.GetObjectReaderForPipeline(_computerName, _runspaceId);
            }
        }

        /// <summary>
        /// String which is added in the history.
        /// </summary>
        /// <remarks>This needs to be internal so that it can be replaced
        /// by invoke-cmd to place correct string in history.</remarks>
        internal string HistoryString
        {
            get
            {
                return _historyString;
            }

            set
            {
                _historyString = value;
            }
        }

        /// <summary>
        /// Whether the pipeline needs to be added to history of the runspace.
        /// </summary>
        public bool AddToHistory
        {
            get
            {
                return _addToHistory;
            }
        }

        #endregion Properties

        #region streams

        // Stream and Collection go together...a stream wraps
        // a corresponding collection to support
        // streaming behavior of the pipeline.
        private readonly PSDataCollection<PSObject> _outputCollection;
        private readonly PSDataCollectionStream<PSObject> _outputStream;
        private readonly PSDataCollection<ErrorRecord> _errorCollection;
        private readonly PSDataCollectionStream<ErrorRecord> _errorStream;
        private readonly PSDataCollection<object> _inputCollection;
        private readonly PSDataCollectionStream<object> _inputStream;

        /// <summary>
        /// Stream for providing input to PipelineProcessor. Host will write on
        /// ObjectWriter of this stream. PipelineProcessor will read from
        /// ObjectReader of this stream.
        /// </summary>
        protected PSDataCollectionStream<object> InputStream
        {
            get
            {
                return _inputStream;
            }
        }

        #endregion streams

        #region Invoke

        /// <summary>
        /// Invoke the pipeline asynchronously.
        /// </summary>
        /// <remarks>
        /// Results are returned through the <see cref="Pipeline.Output"/> reader.
        /// </remarks>
        public override void InvokeAsync()
        {
            InitPowerShell(false);
            CoreInvokeAsync();
        }

        /// <summary>
        /// Invokes a remote command and immediately disconnects if
        /// transport layer supports it.
        /// </summary>
        internal override void InvokeAsyncAndDisconnect()
        {
            // Initialize PowerShell invocation with "InvokeAndDisconnect" setting.
            InitPowerShell(false, true);
            CoreInvokeAsync();
        }

        /// <summary>
        /// Invoke the pipeline, synchronously, returning the results as an
        /// array of objects.
        /// </summary>
        /// <param name="input">an array of input objects to pass to the pipeline.
        /// Array may be empty but may not be null</param>
        /// <returns>An array of zero or more result objects.</returns>
        /// <remarks>Caller of synchronous exectute should not close
        /// input objectWriter. Synchronous invoke will always close the input
        /// objectWriter.
        ///
        /// On Synchronous Invoke if output is throttled and no one is reading from
        /// output pipe, Execution will block after buffer is full.
        /// </remarks>
        public override Collection<PSObject> Invoke(System.Collections.IEnumerable input)
        {
            if (input == null)
            {
                this.InputStream.Close();
            }

            InitPowerShell(true);

            Collection<PSObject> results;

            try
            {
                results = _powershell.Invoke(input);
            }
            catch (InvalidRunspacePoolStateException)
            {
                InvalidRunspaceStateException e =
                    new InvalidRunspaceStateException
                    (
                        StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipeline, _runspace.RunspaceStateInfo.State.ToString()),
                        _runspace.RunspaceStateInfo.State,
                        RunspaceState.Opened
                    );
                throw e;
            }

            return results;
        }

        #endregion Invoke

        #region Connect

        /// <summary>
        /// Connects synchronously to a running command on a remote server.
        /// The pipeline object must be in the disconnected state.
        /// </summary>
        /// <returns>A collection of result objects.</returns>
        public override Collection<PSObject> Connect()
        {
            InitPowerShellForConnect(true);

            Collection<PSObject> results;

            try
            {
                results = _powershell.Connect();
            }
            catch (InvalidRunspacePoolStateException)
            {
                InvalidRunspaceStateException e =
                    new InvalidRunspaceStateException
                    (
                        StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipelineConnect, _runspace.RunspaceStateInfo.State.ToString()),
                        _runspace.RunspaceStateInfo.State,
                        RunspaceState.Opened
                    );

                throw e;
            }

            // PowerShell object will return empty results if it was provided an alternative object to
            // collect output in.  Check to see if the output was collected in a member variable.
            if (results.Count == 0)
            {
                if (_outputCollection != null && _outputCollection.Count > 0)
                {
                    results = new Collection<PSObject>(_outputCollection);
                }
            }

            return results;
        }

        /// <summary>
        /// Connects asynchronously to a running command on a remote server.
        /// </summary>
        public override void ConnectAsync()
        {
            InitPowerShellForConnect(false);

            try
            {
                _powershell.ConnectAsync();
            }
            catch (InvalidRunspacePoolStateException)
            {
                InvalidRunspaceStateException e =
                    new InvalidRunspaceStateException
                    (
                        StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipelineConnect, _runspace.RunspaceStateInfo.State.ToString()),
                        _runspace.RunspaceStateInfo.State,
                        RunspaceState.Opened
                    );
                throw e;
            }
        }

        #endregion

        #region Stop

        /// <summary>
        /// Stop the pipeline synchronously.
        /// </summary>
        public override void Stop()
        {
            bool isAlreadyStopping = false;
            if (CanStopPipeline(out isAlreadyStopping))
            {
                // A pipeline can be stopped before it is started.so protecting against that
                if (_powershell != null)
                {
                    IAsyncResult asyncresult = null;
                    try
                    {
                        asyncresult = _powershell.BeginStop(null, null);
                    }
                    catch (ObjectDisposedException)
                    {
                        throw PSTraceSource.NewObjectDisposedException("Pipeline");
                    }

                    asyncresult.AsyncWaitHandle.WaitOne();
                }
            }

            // Waits until pipeline completes stop as this is a sync call.
            PipelineFinishedEvent.WaitOne();
        }

        /// <summary>
        /// Stop the pipeline asynchronously.
        /// This method calls the BeginStop on the underlying
        /// powershell and so any exception will be
        /// thrown on the same thread.
        /// </summary>
        public override void StopAsync()
        {
            bool isAlreadyStopping;
            if (CanStopPipeline(out isAlreadyStopping))
            {
                try
                {
                    _powershell.BeginStop(null, null);
                }
                catch (ObjectDisposedException)
                {
                    throw PSTraceSource.NewObjectDisposedException("Pipeline");
                }
            }
        }

        /// <summary>
        /// Verifies if the pipeline is in a state where it can be stopped.
        /// </summary>
        private bool CanStopPipeline(out bool isAlreadyStopping)
        {
            bool returnResult = false;
            isAlreadyStopping = false;
            lock (_syncRoot)
            {
                // SetPipelineState does not raise events..
                // so locking is ok here.
                switch (_pipelineStateInfo.State)
                {
                    case PipelineState.NotStarted:
                        SetPipelineState(PipelineState.Stopping, null);
                        SetPipelineState(PipelineState.Stopped, null);
                        returnResult = false;
                        break;

                    // If pipeline execution has failed or completed or
                    // stopped, return silently.
                    case PipelineState.Stopped:
                    case PipelineState.Completed:
                    case PipelineState.Failed:
                        return false;

                    // If pipeline is in Stopping state, ignore the second
                    // stop.
                    case PipelineState.Stopping:
                        isAlreadyStopping = true;
                        return false;

                    case PipelineState.Running:
                    case PipelineState.Disconnected:
                        SetPipelineState(PipelineState.Stopping, null);
                        returnResult = true;
                        break;
                }
            }

            RaisePipelineStateEvents();

            return returnResult;
        }

        #endregion Stop

        #region Events

        /// <summary>
        /// Event raised when Pipeline's state changes.
        /// </summary>
        public override event EventHandler<PipelineStateEventArgs> StateChanged = null;

        #endregion Events

        #region Dispose

        /// <summary>
        /// Disposes the pipeline.
        /// </summary>
        /// <param name="disposing">True, when called on Dispose().</param>
        protected override void Dispose(bool disposing)
        {
            try
            {
                if (_disposed)
                {
                    return;
                }

                lock (_syncRoot)
                {
                    if (_disposed)
                    {
                        return;
                    }

                    _disposed = true;
                }

                if (disposing)
                {
                    // wait for the pipeline to stop..this will block
                    // if the pipeline is already stopping.
                    Stop();
                    // _pipelineFinishedEvent.Close();

                    if (_powershell != null)
                    {
                        _powershell.Dispose();
                        _powershell = null;
                    }

                    _inputCollection.Dispose();
                    _inputStream.Dispose();
                    _outputCollection.Dispose();
                    _outputStream.Dispose();
                    _errorCollection.Dispose();
                    _errorStream.Dispose();
                    MethodExecutorStream.Dispose();
                    PipelineFinishedEvent.Dispose();
                }
            }
            finally
            {
                base.Dispose(disposing);
            }
        }

        #endregion Dispose

        #region Private Methods

        private void CoreInvokeAsync()
        {
            try
            {
                _powershell.BeginInvoke();
            }
            catch (InvalidRunspacePoolStateException)
            {
                InvalidRunspaceStateException e =
                    new InvalidRunspaceStateException
                    (
                        StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipeline, _runspace.RunspaceStateInfo.State.ToString()),
                        _runspace.RunspaceStateInfo.State,
                        RunspaceState.Opened
                    );
                throw e;
            }
        }

        private void HandleInvocationStateChanged(object sender, PSInvocationStateChangedEventArgs e)
        {
            SetPipelineState((PipelineState)e.InvocationStateInfo.State, e.InvocationStateInfo.Reason);

            RaisePipelineStateEvents();
        }

        /// <summary>
        /// Sets the new execution state.
        /// </summary>
        /// <param name="state">The new state.</param>
        /// <param name="reason">
        /// An exception indicating that state change is the result of an error,
        /// otherwise; null.
        /// </param>
        /// <remarks>
        /// Sets the internal execution state information member variable. It
        /// also adds PipelineStateInfo to a queue. RaisePipelineStateEvents
        /// raises event for each item in this queue.
        /// </remarks>
        private void SetPipelineState(PipelineState state, Exception reason)
        {
            PipelineState copyState = state;
            PipelineStateInfo copyStateInfo = null;

            lock (_syncRoot)
            {
                switch (_pipelineStateInfo.State)
                {
                    case PipelineState.Completed:
                    case PipelineState.Failed:
                    case PipelineState.Stopped:
                        return;

                    case PipelineState.Running:
                        {
                            if (state == PipelineState.Running)
                            {
                                return;
                            }
                        }

                        break;
                    case PipelineState.Stopping:
                        {
                            if (state == PipelineState.Running || state == PipelineState.Stopping)
                            {
                                return;
                            }
                            else
                            {
                                copyState = PipelineState.Stopped;
                            }
                        }

                        break;
                }

                _pipelineStateInfo = new PipelineStateInfo(copyState, reason);
                copyStateInfo = _pipelineStateInfo;

                // Add _pipelineStateInfo to _executionEventQueue.
                // RaisePipelineStateEvents will raise event for each item
                // in this queue.
                // Note:We are doing clone here instead of passing the member
                // _pipelineStateInfo because we donot want outside
                // to change pipeline state.
                RunspaceAvailability previousAvailability = _runspace.RunspaceAvailability;

                Guid? cmdInstanceId = (_powershell != null) ? _powershell.InstanceId : (Guid?)null;
                _runspace.UpdateRunspaceAvailability(_pipelineStateInfo.State, false, cmdInstanceId);

                _executionEventQueue.Enqueue(
                    new ExecutionEventQueueItem(
                        _pipelineStateInfo.Clone(),
                        previousAvailability,
                        _runspace.RunspaceAvailability));
            }

            // using the copyStateInfo here as this piece of code is
            // outside of lock and _pipelineStateInfo might get changed
            // by two threads running concurrently..so its value is
            // not guaranteed to be the same for this entire method call.
            // copyStateInfo is a local variable.
            if (copyStateInfo.State == PipelineState.Completed ||
                copyStateInfo.State == PipelineState.Failed ||
                copyStateInfo.State == PipelineState.Stopped)
            {
                Cleanup();
            }
        }

        /// <summary>
        /// Raises events for changes in execution state.
        /// </summary>
        protected void RaisePipelineStateEvents()
        {
            Queue<ExecutionEventQueueItem> tempEventQueue = null;
            EventHandler<PipelineStateEventArgs> stateChanged = null;
            bool runspaceHasAvailabilityChangedSubscribers = false;

            lock (_syncRoot)
            {
                stateChanged = this.StateChanged;
                runspaceHasAvailabilityChangedSubscribers = _runspace.HasAvailabilityChangedSubscribers;

                if (stateChanged != null || runspaceHasAvailabilityChangedSubscribers)
                {
                    tempEventQueue = _executionEventQueue;
                    _executionEventQueue = new Queue<ExecutionEventQueueItem>();
                }
                else
                {
                    // Clear the events if there are no EventHandlers. This
                    // ensures that events do not get called for state
                    // changes prior to their registration.
                    _executionEventQueue.Clear();
                }
            }

            if (tempEventQueue != null)
            {
                while (tempEventQueue.Count > 0)
                {
                    ExecutionEventQueueItem queueItem = tempEventQueue.Dequeue();

                    if (runspaceHasAvailabilityChangedSubscribers && queueItem.NewRunspaceAvailability != queueItem.CurrentRunspaceAvailability)
                    {
                        _runspace.RaiseAvailabilityChangedEvent(queueItem.NewRunspaceAvailability);
                    }

                    // Exception raised in the eventhandler are not error in pipeline.
                    // silently ignore them.
                    if (stateChanged != null)
                    {
                        try
                        {
                            stateChanged(this, new PipelineStateEventArgs(queueItem.PipelineStateInfo));
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Initializes the underlying PowerShell object after verifying
        /// if the pipeline is in a state where it can be invoked.
        /// If invokeAndDisconnect is true then the remote PowerShell
        /// command will be immediately disconnected after it begins
        /// running.
        /// </summary>
        /// <param name="syncCall">True if called from a sync call.</param>
        /// <param name="invokeAndDisconnect">Invoke and Disconnect.</param>
        private void InitPowerShell(bool syncCall, bool invokeAndDisconnect = false)
        {
            if (_commands == null || _commands.Count == 0)
            {
                throw PSTraceSource.NewInvalidOperationException(
                        RunspaceStrings.NoCommandInPipeline);
            }

            if (_pipelineStateInfo.State != PipelineState.NotStarted)
            {
                InvalidPipelineStateException e =
                    new InvalidPipelineStateException
                    (
                        StringUtil.Format(RunspaceStrings.PipelineReInvokeNotAllowed),
                        _pipelineStateInfo.State,
                        PipelineState.NotStarted
                    );
                throw e;
            }

            ((RemoteRunspace)_runspace).DoConcurrentCheckAndAddToRunningPipelines(this, syncCall);

            PSInvocationSettings settings = new PSInvocationSettings();
            settings.AddToHistory = _addToHistory;
            settings.InvokeAndDisconnect = invokeAndDisconnect;

            _powershell.InitForRemotePipeline(_commands, _inputStream, _outputStream, _errorStream, settings, RedirectShellErrorOutputPipe);

            _powershell.RemotePowerShell.HostCallReceived += HandleHostCallReceived;
        }

        /// <summary>
        /// Initializes the underlying PowerShell object after verifying that it is
        /// in a state where it can connect to the remote command.
        /// </summary>
        /// <param name="syncCall"></param>
        private void InitPowerShellForConnect(bool syncCall)
        {
            if (_pipelineStateInfo.State != PipelineState.Disconnected)
            {
                throw new InvalidPipelineStateException(StringUtil.Format(PipelineStrings.PipelineNotDisconnected),
                                                        _pipelineStateInfo.State,
                                                        PipelineState.Disconnected);
            }

            // The connect may be from the same Pipeline that disconnected and in this case
            // the Pipeline state already exists.  Or this could be a new Pipeline object
            // (connect reconstruction case) and new state is created.

            // Check to see if this pipeline already exists in the runspace.
            RemotePipeline currentPipeline = (RemotePipeline)((RemoteRunspace)_runspace).GetCurrentlyRunningPipeline();
            if (!ReferenceEquals(currentPipeline, this))
            {
                ((RemoteRunspace)_runspace).DoConcurrentCheckAndAddToRunningPipelines(this, syncCall);
            }

            // Initialize the PowerShell object if it hasn't been initialized before.
            if ((_powershell.RemotePowerShell) == null || !_powershell.RemotePowerShell.Initialized)
            {
                PSInvocationSettings settings = new PSInvocationSettings();
                settings.AddToHistory = _addToHistory;

                _powershell.InitForRemotePipelineConnect(_inputStream, _outputStream, _errorStream, settings, RedirectShellErrorOutputPipe);

                _powershell.RemotePowerShell.HostCallReceived += HandleHostCallReceived;
            }
        }

        /// <summary>
        /// Handle host call received.
        /// </summary>
        /// <param name="sender">Sender of this event, unused.</param>
        /// <param name="eventArgs">Arguments describing the host call to invoke.</param>
        private void HandleHostCallReceived(object sender, RemoteDataEventArgs<RemoteHostCall> eventArgs)
        {
            ClientMethodExecutor.Dispatch(
                _powershell.RemotePowerShell.DataStructureHandler.TransportManager,
                ((RemoteRunspace)_runspace).RunspacePool.RemoteRunspacePoolInternal.Host,
                _errorStream,
                MethodExecutorStream,
                IsMethodExecutorStreamEnabled,
                ((RemoteRunspace)_runspace).RunspacePool.RemoteRunspacePoolInternal,
                _powershell.InstanceId,
                eventArgs.Data);
        }

        /// <summary>
        /// Does the cleanup necessary on pipeline completion.
        /// </summary>
        private void Cleanup()
        {
            // Close the output stream if it is not closed.
            if (_outputStream.IsOpen)
            {
                try
                {
                    _outputCollection.Complete();
                    _outputStream.Close();
                }
                catch (ObjectDisposedException)
                {
                }
            }

            // Close the error stream if it is not closed.
            if (_errorStream.IsOpen)
            {
                try
                {
                    _errorCollection.Complete();
                    _errorStream.Close();
                }
                catch (ObjectDisposedException)
                {
                }
            }

            // Close the input stream if it is not closed.
            if (_inputStream.IsOpen)
            {
                try
                {
                    _inputCollection.Complete();
                    _inputStream.Close();
                }
                catch (ObjectDisposedException)
                {
                }
            }

            try
            {
                // Runspace object maintains a list of pipelines in execution.
                // Remove this pipeline from the list. This method also calls the
                // pipeline finished event.
                ((RemoteRunspace)_runspace).RemoveFromRunningPipelineList(this);

                PipelineFinishedEvent.Set();
            }
            catch (ObjectDisposedException)
            {
            }
        }

        #endregion Private Methods

        #region Internal Methods/Properties

        /// <summary>
        /// ManualResetEvent which is signaled when pipeline execution is
        /// completed/failed/stopped.
        /// </summary>
        internal ManualResetEvent PipelineFinishedEvent { get; }

        /// <summary>
        /// Is method executor stream enabled.
        /// </summary>
        internal bool IsMethodExecutorStreamEnabled { get; set; }

        /// <summary>
        /// Method executor stream.
        /// </summary>
        internal ObjectStream MethodExecutorStream { get; }

        /// <summary>
        /// Check if anyother pipeline is executing.
        /// In case of nested pipeline, checks that it is called
        /// from currently executing pipeline's thread.
        /// </summary>
        /// <param name="syncCall">True if method is called from Invoke, false
        /// if called from InvokeAsync</param>
        /// <exception cref="InvalidOperationException">
        /// 1) A pipeline is already executing. Pipeline cannot execute
        /// concurrently.
        /// 2) InvokeAsync is called on nested pipeline. Nested pipeline
        /// cannot be executed Asynchronously.
        /// 3) Attempt is made to invoke a nested pipeline directly. Nested
        /// pipeline must be invoked from a running pipeline.
        /// </exception>
        internal void DoConcurrentCheck(bool syncCall)
        {
            RemotePipeline currentPipeline =
                (RemotePipeline)((RemoteRunspace)_runspace).GetCurrentlyRunningPipeline();

            if (!_isNested)
            {
                if (currentPipeline == null &&
                    ((RemoteRunspace)_runspace).RunspaceAvailability != RunspaceAvailability.Busy &&
                    ((RemoteRunspace)_runspace).RunspaceAvailability != RunspaceAvailability.RemoteDebug)
                {
                    // We can add a new pipeline to the runspace only if it is
                    // available (not busy).
                    return;
                }

                if (currentPipeline == null &&
                    ((RemoteRunspace)_runspace).RemoteCommand != null &&
                    _connectCmdInfo != null &&
                    Guid.Equals(((RemoteRunspace)_runspace).RemoteCommand.CommandId, _connectCmdInfo.CommandId))
                {
                    // Connect case.  We can add a pipeline to a busy runspace when
                    // that pipeline represents the same command as is currently
                    // running.
                    return;
                }

                if (currentPipeline != null &&
                         ReferenceEquals(currentPipeline, this))
                {
                    // Reconnect case.  We can add a pipeline to a busy runspace when the
                    // pipeline is the same (reconnecting).
                    return;
                }

                if (!_isSteppable)
                {
                    throw PSTraceSource.NewInvalidOperationException(
                            RunspaceStrings.ConcurrentInvokeNotAllowed);
                }
            }
            else
            {
                if (_performNestedCheck)
                {
                    if (_isSteppable)
                    {
                        return;
                    }

                    if (!syncCall)
                    {
                        throw PSTraceSource.NewInvalidOperationException(
                                RunspaceStrings.NestedPipelineInvokeAsync);
                    }

                    if (currentPipeline == null)
                    {
                        if (!_isSteppable)
                        {
                            throw PSTraceSource.NewInvalidOperationException(
                                    RunspaceStrings.NestedPipelineNoParentPipeline);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// The underlying powershell object on which this remote pipeline
        /// is created.
        /// </summary>
        internal PowerShell PowerShell
        {
            get
            {
                return _powershell;
            }
        }

        /// <summary>
        /// Sets the history string to the specified string.
        /// </summary>
        /// <param name="historyString">New history string to set to.</param>
        internal override void SetHistoryString(string historyString)
        {
            _powershell.HistoryString = historyString;
        }

        #endregion Internal Methods/Properties

        #region Remote data drain/block methods

        /// <summary>
        /// Blocks data arriving from remote session.
        /// </summary>
        internal override void SuspendIncomingData()
        {
            _powershell.SuspendIncomingData();
        }

        /// <summary>
        /// Resumes data arrive from remote session.
        /// </summary>
        internal override void ResumeIncomingData()
        {
            _powershell.ResumeIncomingData();
        }

        /// <summary>
        /// Blocking call that waits until the current remote data
        /// queue is empty.
        /// </summary>
        internal override void DrainIncomingData()
        {
            _powershell.WaitForServicingComplete();
        }

        #endregion
    }
}