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
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
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Remoting;
using System.Management.Automation.Remoting.Internal;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Tracing;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;

using Microsoft.PowerShell.Commands;

using Dbg = System.Management.Automation.Diagnostics;

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

namespace System.Management.Automation
{
    /// <summary>
    /// Enumeration for job status values. Indicates the status
    /// of the result object.
    /// </summary>
    public enum JobState
    {
        /// <summary>
        /// Execution of command in job not started.
        /// </summary>
        NotStarted = 0,

        /// <summary>
        /// Execution of command in progress.
        /// </summary>
        Running = 1,

        /// <summary>
        /// Execution of command completed in all
        /// computernames/runspaces.
        /// </summary>
        Completed = 2,

        /// <summary>
        /// An error was encountered when trying to executed
        /// command in one or more computernames/runspaces.
        /// </summary>
        Failed = 3,

        /// <summary>
        /// Command execution is cancelled (stopped) in one or more
        /// computernames/runspaces.
        /// </summary>
        Stopped = 4,

        /// <summary>
        /// Command execution is blocked (on user input host calls etc)
        /// </summary>
        Blocked = 5,

        /// <summary>
        /// The job has been suspended.
        /// </summary>
        Suspended = 6,

        /// <summary>
        /// The job is a remote job and has been disconnected from the server.
        /// </summary>
        Disconnected = 7,

        /// <summary>
        /// Suspend is in progress.
        /// </summary>
        Suspending = 8,

        /// <summary>
        /// Stop is in progress.
        /// </summary>
        Stopping = 9,

        /// <summary>
        /// Script execution is halted in a debugger stop.
        /// </summary>
        AtBreakpoint = 10
    }

    /// <summary>
    /// Defines exception which is thrown when state of the PSJob is different
    /// from the expected state.
    /// </summary>
    public class InvalidJobStateException : SystemException
    {
        /// <summary>
        /// Creates a new instance of InvalidPSJobStateException class.
        /// </summary>
        public InvalidJobStateException()
            : base
        (
            PSRemotingErrorInvariants.FormatResourceString
            (
                RemotingErrorIdStrings.InvalidJobStateGeneral
            )
        )
        {
        }

        /// <summary>
        /// Creates a new instance of InvalidPSJobStateException class.
        /// </summary>
        /// <param name="message">
        /// The error message that explains the reason for the exception.
        /// </param>
        public InvalidJobStateException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Creates a new instance of InvalidPSJobStateException class.
        /// </summary>
        /// <param name="message">
        /// The error message that explains the reason for the exception.
        /// </param>
        /// <param name="innerException">
        /// The exception that is the cause of the current exception.
        /// </param>
        public InvalidJobStateException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        /// <summary>
        /// Creates a new instance of InvalidJobStateException class.
        /// </summary>
        /// <param name="currentState">
        /// The Job State at the time of the error.
        /// </param>
        /// <param name="actionMessage">
        /// An additional message that gives more information about the error. Used
        /// for context after a generalized error message.
        /// </param>
        public InvalidJobStateException(JobState currentState, string actionMessage)
            : base
        (
            PSRemotingErrorInvariants.FormatResourceString
            (
                RemotingErrorIdStrings.InvalidJobStateSpecific, currentState, actionMessage
            )
        )
        {
            _currState = currentState;
        }

        /// <summary>
        /// Initializes a new instance of the InvalidPSJobStateException and defines value of
        /// CurrentState.
        /// </summary>
        /// <param name="currentState">Current state of powershell.</param>
        internal InvalidJobStateException(JobState currentState)
            : base
        (
            PSRemotingErrorInvariants.FormatResourceString
            (
                RemotingErrorIdStrings.InvalidJobStateGeneral
            )
        )
        {
            _currState = currentState;
        }

        #region ISerializable Members

        // No need to implement GetObjectData
        // if all fields are static or [NonSerialized]

        /// <summary>
        /// Initializes a new instance of the InvalidPSJobStateException
        /// class with serialized data.
        /// </summary>
        /// <param name="info">
        /// The <see cref="SerializationInfo"/> that holds the serialized object
        /// data about the exception being thrown.
        /// </param>
        /// <param name="context">
        /// The <see cref="StreamingContext"/> that contains contextual information
        /// about the source or destination.
        /// </param>
        [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] 
        protected
        InvalidJobStateException(SerializationInfo info, StreamingContext context)
        {
            throw new NotSupportedException();
        }

        #endregion

        /// <summary>
        /// Gets CurrentState of the Job.
        /// </summary>
        public JobState CurrentState
        {
            get
            {
                return _currState;
            }
        }

        /// <summary>
        /// State of job when exception was thrown.
        /// </summary>
        [NonSerialized]
        private readonly JobState _currState = 0;
    }

    /// <summary>
    /// Type which has information about JobState and Exception
    /// ,if any, associated with JobState.
    /// </summary>
    public sealed class JobStateInfo
    {
        #region constructors

        /// <summary>
        /// Constructor for state changes not resulting from an error.
        /// </summary>
        /// <param name="state">Execution state.</param>
        public JobStateInfo(JobState state)
            : this(state, null)
        {
        }

        /// <summary>
        /// Constructor for state changes with an optional error.
        /// </summary>
        /// <param name="state">The new state.</param>
        /// <param name="reason">A non-null exception if the state change was
        /// caused by an error,otherwise; null.
        /// </param>
        public JobStateInfo(JobState state, Exception reason)
        {
            State = state;
            Reason = reason;
        }

        /// <summary>
        /// Copy constructor to support cloning.
        /// </summary>
        /// <param name="jobStateInfo">Source information.</param>
        /// <throws>
        /// ArgumentNullException when <paramref name="jobStateInfo"/> is null.
        /// </throws>
        internal JobStateInfo(JobStateInfo jobStateInfo)
        {
            State = jobStateInfo.State;
            Reason = jobStateInfo.Reason;
        }

        #endregion constructors

        #region public_properties

        /// <summary>
        /// The state of the job.
        /// </summary>
        /// <remarks>
        /// This value indicates the state of the job .
        /// </remarks>
        public JobState State { get; }

        /// <summary>
        /// The reason for the state change, if caused by an error.
        /// </summary>
        /// <remarks>
        /// The value of this property is non-null if the state
        /// changed due to an error. Otherwise, the value of this
        /// property is null.
        /// </remarks>
        public Exception Reason { get; }

        #endregion public_properties

        /// <summary>
        /// Override for ToString()
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return State.ToString();
        }

        /// <summary>
        /// Clones this object.
        /// </summary>
        /// <returns>Cloned object.</returns>
        internal JobStateInfo Clone()
        {
            return new JobStateInfo(this);
        }

        #region private_fields

        #endregion private_fields
    }

    /// <summary>
    /// Event arguments passed to JobStateEvent handlers
    /// <see cref="Job.StateChanged"/> event.
    /// </summary>
    public sealed class JobStateEventArgs : EventArgs
    {
        #region constructors

        /// <summary>
        /// Constructor of JobStateEventArgs.
        /// </summary>
        /// <param name="jobStateInfo">The current state of the job.</param>
        public JobStateEventArgs(JobStateInfo jobStateInfo)
            : this(jobStateInfo, null)
        {
        }

        /// <summary>
        /// Constructor of JobStateEventArgs.
        /// </summary>
        /// <param name="jobStateInfo">The current state of the job.</param>
        /// <param name="previousJobStateInfo">The previous state of the job.</param>
        public JobStateEventArgs(JobStateInfo jobStateInfo, JobStateInfo previousJobStateInfo)
        {
            if (jobStateInfo == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(jobStateInfo));
            }

            JobStateInfo = jobStateInfo;
            PreviousJobStateInfo = previousJobStateInfo;
        }

        #endregion constructors

        #region public_properties

        /// <summary>
        /// Info about the current state of the job.
        /// </summary>
        public JobStateInfo JobStateInfo { get; }

        /// <summary>
        /// Info about the previous state of the job.
        /// </summary>
        public JobStateInfo PreviousJobStateInfo { get; }

        #endregion public_properties
    }

    /// <summary>
    /// Object that must be created by PowerShell to allow reuse of an ID for a job.
    /// Also allows setting of the Instance Id so that jobs may be recreated.
    /// </summary>
    public sealed class JobIdentifier
    {
        internal JobIdentifier(int id, Guid instanceId)
        {
            if (id <= 0)
                PSTraceSource.NewArgumentException(nameof(id), RemotingErrorIdStrings.JobSessionIdLessThanOne, id);
            Id = id;
            InstanceId = instanceId;
        }

        internal int Id { get; }

        internal Guid InstanceId { get; private set; }
    }

    /// <summary>
    /// Interface to expose a job debugger.
    /// </summary>
#nullable enable
    public interface IJobDebugger
    {
        /// <summary>
        /// Job Debugger.
        /// </summary>
        Debugger? Debugger
        {
            get;
        }

        /// <summary>
        /// True if job is running asynchronously.
        /// </summary>
        bool IsAsync
        {
            get;
            set;
        }
    }
#nullable restore

    /// <summary>
    /// Represents a command running in background. A job object can internally
    /// contain many child job objects.
    /// </summary>
    public abstract class Job : IDisposable
    {
        #region Constructor

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected Job()
        {
            Id = System.Threading.Interlocked.Increment(ref s_jobIdSeed);
        }

        /// <summary>
        /// Creates an instance of this class.
        /// </summary>
        /// <param name="command">Command invoked by this job object.</param>
        protected Job(string command)
            : this()
        {
            Command = command;
            _name = AutoGenerateJobName();
        }

        /// <summary>
        /// Creates an instance of this class.
        /// </summary>
        /// <param name="command">Command invoked by this job object.</param>
        /// <param name="name">Friendly name for the job object.</param>
        protected Job(string command, string name)
            : this(command)
        {
            if (!string.IsNullOrEmpty(name))
            {
                _name = name;
            }
        }

        /// <summary>
        /// Creates an instance of this class.
        /// </summary>
        /// <param name="command">Command invoked by this job object.</param>
        /// <param name="name">Friendly name for the job object.</param>
        /// <param name="childJobs">Child jobs of this job object.</param>
        protected Job(string command, string name, IList<Job> childJobs)
            : this(command, name)
        {
            _childJobs = childJobs;
        }

        /// <summary>
        /// Creates an instance of this class.
        /// </summary>
        /// <param name="command">Command invoked by this job object.</param>
        /// <param name="name">Friendly name for the job object.</param>
        /// <param name="token">Id and InstanceId pair to be used for this job object.</param>
        /// <remarks>The JobIdentifier is a token that must be issued by PowerShell to allow
        /// reuse of the Id. This is the only way to set either Id or instance Id.</remarks>
        protected Job(string command, string name, JobIdentifier token)
        {
            if (token == null)
                throw PSTraceSource.NewArgumentNullException(nameof(token), RemotingErrorIdStrings.JobIdentifierNull);
            if (token.Id > s_jobIdSeed)
            {
                throw PSTraceSource.NewArgumentException(nameof(token), RemotingErrorIdStrings.JobIdNotYetAssigned, token.Id);
            }

            Command = command;

            Id = token.Id;
            InstanceId = token.InstanceId;

            if (!string.IsNullOrEmpty(name))
            {
                _name = name;
            }
            else
            {
                _name = AutoGenerateJobName();
            }
        }

        /// <summary>
        /// Creates an instance of this class.
        /// </summary>
        /// <param name="command">Command invoked by this job object.</param>
        /// <param name="name">Friendly name for the job object.</param>
        /// <param name="instanceId">InstanceId to be used for this job object.</param>
        /// <remarks>The InstanceId may need to be set to maintain job identity across
        /// instances of the process.</remarks>
        protected Job(string command, string name, Guid instanceId)
            : this(command, name)
        {
            InstanceId = instanceId;
        }

        internal static string GetCommandTextFromInvocationInfo(InvocationInfo invocationInfo)
        {
            if (invocationInfo == null)
            {
                return null;
            }

            IScriptExtent scriptExtent = invocationInfo.ScriptPosition;
            if ((scriptExtent != null) && (scriptExtent.StartScriptPosition != null) && !string.IsNullOrWhiteSpace(scriptExtent.StartScriptPosition.Line))
            {
                Dbg.Assert(scriptExtent.StartScriptPosition.ColumnNumber > 0, "Column numbers start at 1");
                Dbg.Assert(scriptExtent.StartScriptPosition.ColumnNumber <= scriptExtent.StartScriptPosition.Line.Length, "Column numbers are not greater than the length of a line");
                return scriptExtent.StartScriptPosition.Line.AsSpan(scriptExtent.StartScriptPosition.ColumnNumber - 1).Trim().ToString();
            }

            return invocationInfo.InvocationName;
        }

        #endregion Constructor

        #region Private Members

        private ManualResetEvent _finished = new ManualResetEvent(false);

        private string _name;
        private IList<Job> _childJobs;
        internal readonly object syncObject = new object();   // object used for synchronization
        // ISSUE: Should Result be public property
        private PSDataCollection<PSStreamObject> _results = new PSDataCollection<PSStreamObject>();
        private bool _resultsOwner = true;
        private PSDataCollection<ErrorRecord> _error = new PSDataCollection<ErrorRecord>();
        private bool _errorOwner = true;
        private PSDataCollection<ProgressRecord> _progress = new PSDataCollection<ProgressRecord>();
        private bool _progressOwner = true;
        private PSDataCollection<VerboseRecord> _verbose = new PSDataCollection<VerboseRecord>();
        private bool _verboseOwner = true;
        private PSDataCollection<WarningRecord> _warning = new PSDataCollection<WarningRecord>();
        private bool _warningOwner = true;
        private PSDataCollection<DebugRecord> _debug = new PSDataCollection<DebugRecord>();
        private bool _debugOwner = true;
        private PSDataCollection<InformationRecord> _information = new PSDataCollection<InformationRecord>();
        private bool _informationOwner = true;
        private PSDataCollection<PSObject> _output = new PSDataCollection<PSObject>();
        private bool _outputOwner = true;

        /// <summary>
        /// Static variable which is incremented to generate id.
        /// </summary>
        private static int s_jobIdSeed = 0;

        private string _jobTypeName = string.Empty;

        #endregion Private Members

        #region Job Properties

        /// <summary>
        /// Command Invoked by this Job.
        /// </summary>
        public string Command { get; }

        /// <summary>
        /// Status of the command execution.
        /// </summary>
        public JobStateInfo JobStateInfo { get; private set; } = new JobStateInfo(JobState.NotStarted);

        /// <summary>
        /// Wait Handle which is signaled when job is finished.
        /// This is set when state of the job is set to Completed,
        /// Stopped or Failed.
        /// </summary>
        public WaitHandle Finished
        {
            get
            {
                lock (this.syncObject)
                {
                    if (_finished != null)
                    {
                        return _finished;
                    }
                    else
                    {
                        // Damage control mode:
                        // Somebody is trying to get Finished handle for an already disposed Job instance.
                        // Return an already triggered handle (disposed job is finished by definition).
                        // The newly created handle will not be disposed in a deterministic manner
                        // and in some circumstances can be mistaken for a handle leak.
                        return new ManualResetEvent(true);
                    }
                }
            }
        }

        /// <summary>
        /// Unique identifier for this job.
        /// </summary>
        public Guid InstanceId { get; } = Guid.NewGuid();

        /// <summary>
        /// Short identifier for this result which will be
        /// recycled and used within a process.
        /// </summary>
        public int Id { get; }

        /// <summary>
        /// Name for identifying this job object.
        /// </summary>
        public string Name
        {
            get
            {
                return _name;
            }

            set
            {
                AssertNotDisposed();
                _name = value;
            }
        }

        /// <summary>
        /// List of child jobs contained within this job.
        /// </summary>
        public IList<Job> ChildJobs
        {
            get
            {
                if (_childJobs == null)
                {
                    lock (syncObject)
                    {
                        _childJobs ??= new List<Job>();
                    }
                }

                return _childJobs;
            }
        }

        /// <summary>
        /// Success status of the command execution.
        /// </summary>
        public abstract string StatusMessage { get; }

        /// <summary>
        /// Indicates that more data is available in this
        /// result object for reading.
        /// </summary>
        public abstract bool HasMoreData { get; }

        /// <summary>
        /// Time job was started.
        /// </summary>
        public DateTime? PSBeginTime { get; protected set; } = null;

        /// <summary>
        /// Time job stopped.
        /// </summary>
        public DateTime? PSEndTime { get; protected set; } = null;

        /// <summary>
        /// Job type name.
        /// </summary>
        public string PSJobTypeName
        {
            get
            {
                return _jobTypeName;
            }

            protected internal set
            {
                _jobTypeName = value ?? this.GetType().ToString();
            }
        }

        #region results

        /// <summary>
        /// Result objects from this job. If this object is not a
        /// leaf node (with no children), then this will
        /// aggregate the results from all child jobs.
        /// </summary>
        internal PSDataCollection<PSStreamObject> Results
        {
            get
            {
                return _results;
            }

            set
            {
                if (value == null)
                {
                    throw PSTraceSource.NewArgumentNullException("Results");
                }

                lock (syncObject)
                {
                    AssertChangesAreAccepted();
                    _resultsOwner = false;
                    _results = value;
                }
            }
        }

        /// <summary>
        /// Indicates if a particular Job type uses the
        /// internal results collection.
        /// </summary>
        internal bool UsesResultsCollection { get; set; }

        /// <summary>
        /// Suppresses forwarding of job output into a cmdlet (like Receive-Job).
        /// This flag modifies functionality of <see cref="WriteObject"/> method, so that it doesnt add output-processing to <see cref="Results"/> collection.
        /// </summary>
        internal bool SuppressOutputForwarding { get; set; }

        internal virtual void WriteObject(object outputObject)
        {
            PSObject pso = (outputObject == null) ? null : PSObject.AsPSObject(outputObject);
            this.Output.Add(pso);

            if (!SuppressOutputForwarding)
            {
                this.Results.Add(new PSStreamObject(PSStreamObjectType.Output, pso));
            }
        }

        /// <summary>
        /// Allows propagating of terminating exceptions from remote "throw" statement
        /// (normally / by default all remote errors are transformed into non-terminating errors.
        /// </summary>
        internal bool PropagateThrows { get; set; }

        private void WriteError(Cmdlet cmdlet, ErrorRecord errorRecord)
        {
            if (this.PropagateThrows)
            {
                Exception e = GetExceptionFromErrorRecord(errorRecord);
                if (e != null)
                    throw e;
            }

            errorRecord.PreserveInvocationInfoOnce = true;
            cmdlet.WriteError(errorRecord);
        }

        private static Exception GetExceptionFromErrorRecord(ErrorRecord errorRecord)
        {
            if (errorRecord.Exception is not RuntimeException runtimeException)
                return null;

            if (runtimeException is not RemoteException remoteException)
                return null;

            PSPropertyInfo wasThrownFromThrow =
                remoteException.SerializedRemoteException.Properties["WasThrownFromThrowStatement"];
            if (wasThrownFromThrow == null || !((bool)wasThrownFromThrow.Value))
                return null;

            runtimeException.WasThrownFromThrowStatement = true;
            return runtimeException;
        }

        internal virtual void WriteError(ErrorRecord errorRecord)
        {
            Error.Add(errorRecord);
            if (PropagateThrows)
            {
                Exception exception = GetExceptionFromErrorRecord(errorRecord);
                if (exception != null)
                {
                    Results.Add(new PSStreamObject(PSStreamObjectType.Exception, exception));
                    return;
                }
            }

            Results.Add(new PSStreamObject(PSStreamObjectType.Error, errorRecord));
        }

        internal void WriteError(ErrorRecord errorRecord, out Exception exceptionThrownOnCmdletThread)
        {
            this.Error.Add(errorRecord);
            this.InvokeCmdletMethodAndWaitForResults<object>(
                (Cmdlet cmdlet) =>
                {
                    this.WriteError(cmdlet, errorRecord);
                    return null;
                },
                out exceptionThrownOnCmdletThread);
        }

        internal virtual void WriteWarning(string message)
        {
            this.Warning.Add(new WarningRecord(message));
            this.Results.Add(new PSStreamObject(PSStreamObjectType.Warning, message));
        }

        internal virtual void WriteVerbose(string message)
        {
            this.Verbose.Add(new VerboseRecord(message));
            this.Results.Add(new PSStreamObject(PSStreamObjectType.Verbose, message));
        }

        internal virtual void WriteDebug(string message)
        {
            this.Debug.Add(new DebugRecord(message));
            this.Results.Add(new PSStreamObject(PSStreamObjectType.Debug, message));
        }

        internal virtual void WriteProgress(ProgressRecord progressRecord)
        {
            if ((progressRecord.ParentActivityId == (-1)) && (_parentActivityId != null))
            {
                progressRecord = new ProgressRecord(progressRecord) { ParentActivityId = _parentActivityId.Value };
            }

            Progress.Add(progressRecord);
            Results.Add(new PSStreamObject(PSStreamObjectType.Progress, progressRecord));
        }

        internal virtual void WriteInformation(InformationRecord informationRecord)
        {
            Information.Add(informationRecord);
            Results.Add(new PSStreamObject(PSStreamObjectType.Information, informationRecord));
        }

        private Lazy<int> _parentActivityId;

        internal void SetParentActivityIdGetter(Func<int> parentActivityIdGetter)
        {
            Dbg.Assert(parentActivityIdGetter != null, "Caller should verify parentActivityIdGetter != null");
            _parentActivityId = new Lazy<int>(parentActivityIdGetter);
        }

        internal bool ShouldContinue(string query, string caption)
        {
            Exception exceptionThrownOnCmdletThread;
            return this.ShouldContinue(query, caption, out exceptionThrownOnCmdletThread);
        }

        internal bool ShouldContinue(string query, string caption, out Exception exceptionThrownOnCmdletThread)
        {
            bool methodResult = InvokeCmdletMethodAndWaitForResults(
                cmdlet => cmdlet.ShouldContinue(query, caption),
                out exceptionThrownOnCmdletThread);
            return methodResult;
        }

        internal virtual void NonblockingShouldProcess(
            string verboseDescription,
            string verboseWarning,
            string caption)
        {
            InvokeCmdletMethodAndIgnoreResults(
                (Cmdlet cmdlet) =>
                {
                    ShouldProcessReason throwAwayProcessReason;
                    cmdlet.ShouldProcess(
                        verboseDescription,
                        verboseWarning,
                        caption,
                        out throwAwayProcessReason);
                });
        }

        internal virtual bool ShouldProcess(
            string verboseDescription,
            string verboseWarning,
            string caption,
            out ShouldProcessReason shouldProcessReason,
            out Exception exceptionThrownOnCmdletThread)
        {
            ShouldProcessReason closureSafeShouldProcessReason = ShouldProcessReason.None;

            bool methodResult = InvokeCmdletMethodAndWaitForResults(
                cmdlet => cmdlet.ShouldProcess(
                    verboseDescription,
                    verboseWarning,
                    caption,
                    out closureSafeShouldProcessReason),
                out exceptionThrownOnCmdletThread);

            shouldProcessReason = closureSafeShouldProcessReason;
            return methodResult;
        }

        private void InvokeCmdletMethodAndIgnoreResults(Action<Cmdlet> invokeCmdletMethod)
        {
            object resultsLock = new object();
            CmdletMethodInvoker<object> methodInvoker = new CmdletMethodInvoker<object>
            {
                Action = (Cmdlet cmdlet) => { invokeCmdletMethod(cmdlet); return null; },
                Finished = null,
                SyncObject = resultsLock
            };
            Results.Add(new PSStreamObject(PSStreamObjectType.BlockingError, methodInvoker));
        }

        private T InvokeCmdletMethodAndWaitForResults<T>(Func<Cmdlet, T> invokeCmdletMethodAndReturnResult, out Exception exceptionThrownOnCmdletThread)
        {
            Dbg.Assert(invokeCmdletMethodAndReturnResult != null, "Caller should verify invokeCmdletMethodAndReturnResult != null");

            T methodResult = default(T);
            Exception closureSafeExceptionThrownOnCmdletThread = null;
            object resultsLock = new object();
            using (var gotResultEvent = new ManualResetEventSlim(false))
            {
                EventHandler<JobStateEventArgs> stateChangedEventHandler =
                    (object sender, JobStateEventArgs eventArgs) =>
                    {
                        if (IsFinishedState(eventArgs.JobStateInfo.State) || eventArgs.JobStateInfo.State == JobState.Stopping)
                        {
                            lock (resultsLock)
                            {
                                closureSafeExceptionThrownOnCmdletThread = new OperationCanceledException();
                            }

                            gotResultEvent.Set();
                        }
                    };
                this.StateChanged += stateChangedEventHandler;
                Interlocked.MemoryBarrier();
                try
                {
                    stateChangedEventHandler(null, new JobStateEventArgs(this.JobStateInfo));

                    if (!gotResultEvent.IsSet)
                    {
                        this.SetJobState(JobState.Blocked);

                        // addition to results column happens here
                        CmdletMethodInvoker<T> methodInvoker = new CmdletMethodInvoker<T>
                        {
                            Action = invokeCmdletMethodAndReturnResult,
                            Finished = gotResultEvent,
                            SyncObject = resultsLock
                        };
                        PSStreamObjectType objectType = PSStreamObjectType.ShouldMethod;

                        if (typeof(T) == typeof(object))
                            objectType = PSStreamObjectType.BlockingError;

                        Results.Add(new PSStreamObject(objectType, methodInvoker));

                        gotResultEvent.Wait();
                        this.SetJobState(JobState.Running);

                        lock (resultsLock)
                        {
                            if (closureSafeExceptionThrownOnCmdletThread == null) // stateChangedEventHandler didn't set the results?  = ok to clobber results?
                            {
                                closureSafeExceptionThrownOnCmdletThread = methodInvoker.ExceptionThrownOnCmdletThread;
                                methodResult = methodInvoker.MethodResult;
                            }
                        }
                    }
                }
                finally
                {
                    this.StateChanged -= stateChangedEventHandler;
                }
            }

            lock (resultsLock)
            {
                exceptionThrownOnCmdletThread = closureSafeExceptionThrownOnCmdletThread;
                return methodResult;
            }
        }

        internal virtual void ForwardAvailableResultsToCmdlet(Cmdlet cmdlet)
        {
            foreach (PSStreamObject obj in Results.ReadAll())
            {
                obj.WriteStreamObject(cmdlet);
            }
        }

        internal virtual void ForwardAllResultsToCmdlet(Cmdlet cmdlet)
        {
            foreach (PSStreamObject obj in this.Results)
            {
                obj.WriteStreamObject(cmdlet);
            }
        }

        /// <summary>
        /// This method is introduce for delaying the loading of streams
        /// for a particular job.
        /// </summary>
        protected virtual void DoLoadJobStreams()
        {
        }

        /// <summary>
        /// Unloads job streams information. Enables jobs to
        /// clear stream information from memory.
        /// </summary>
        protected virtual void DoUnloadJobStreams()
        {
        }

        /// <summary>
        /// Load the required job streams.
        /// </summary>
        public void LoadJobStreams()
        {
            if (_jobStreamsLoaded)
            {
                return;
            }

            lock (syncObject)
            {
                if (_jobStreamsLoaded)
                {
                    return;
                }

                _jobStreamsLoaded = true;
            }

            try
            {
                DoLoadJobStreams();
            }
            catch (Exception e)
            {
                // third party call-out for platform API
                // Therefore it is fine to eat the exception
                // here
                using (PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource())
                {
                    tracer.TraceException(e);
                }
            }
        }

        private bool _jobStreamsLoaded;

        /// <summary>
        /// Unload the required job streams.
        /// </summary>
        public void UnloadJobStreams()
        {
            if (!_jobStreamsLoaded) return;

            lock (syncObject)
            {
                if (!_jobStreamsLoaded) return;
                _jobStreamsLoaded = false;
            }

            try
            {
                DoUnloadJobStreams();
            }
            catch (Exception e)
            {
                // third party call-out for platform API
                // Therefore it is fine to eat the exception
                // here
                using (PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource())
                {
                    tracer.TraceException(e);
                }
            }
        }

        /// <summary>
        /// Gets or sets the output buffer. Output of job is written
        /// into this buffer.
        /// </summary>
        /// <exception cref="ArgumentNullException">
        /// Cannot set to a null value.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// Object is disposed.
        /// </exception>
        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public PSDataCollection<PSObject> Output
        {
            get
            {
                LoadJobStreams(); // for delayed loading
                return _output;
            }

            set
            {
                if (value == null)
                {
                    throw PSTraceSource.NewArgumentNullException("Output");
                }

                lock (syncObject)
                {
                    AssertChangesAreAccepted();
                    _outputOwner = false;
                    _output = value;
                    _jobStreamsLoaded = true;
                }
            }
        }

        /// <summary>
        /// Gets or sets the error buffer. Errors of job are written
        /// into this buffer.
        /// </summary>
        /// <exception cref="ArgumentNullException">
        /// Cannot set to a null value.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// Object is disposed.
        /// </exception>
        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public PSDataCollection<ErrorRecord> Error
        {
            get
            {
                LoadJobStreams(); // for delayed loading
                return _error;
            }

            set
            {
                if (value == null)
                {
                    throw PSTraceSource.NewArgumentNullException("Error");
                }

                lock (syncObject)
                {
                    AssertChangesAreAccepted();
                    _errorOwner = false;
                    _error = value;
                    _jobStreamsLoaded = true;
                }
            }
        }

        /// <summary>
        /// Gets or sets the progress buffer. Progress of job is written
        /// into this buffer.
        /// </summary>
        /// <exception cref="ArgumentNullException">
        /// Cannot set to a null value.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// Object is disposed.
        /// </exception>
        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public PSDataCollection<ProgressRecord> Progress
        {
            get
            {
                LoadJobStreams(); // for delayed loading
                return _progress;
            }

            set
            {
                if (value == null)
                {
                    throw PSTraceSource.NewArgumentNullException("Progress");
                }

                lock (syncObject)
                {
                    AssertChangesAreAccepted();
                    _progressOwner = false;
                    _progress = value;
                    _jobStreamsLoaded = true;
                }
            }
        }

        /// <summary>
        /// Gets or sets the verbose buffer. Verbose output of job is written to
        /// this stream.
        /// </summary>
        /// <exception cref="ObjectDisposedException">
        /// Object is disposed.
        /// </exception>
        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public PSDataCollection<VerboseRecord> Verbose
        {
            get
            {
                LoadJobStreams(); // for delayed loading
                return _verbose;
            }

            set
            {
                if (value == null)
                {
                    throw PSTraceSource.NewArgumentNullException("Verbose");
                }

                lock (syncObject)
                {
                    AssertChangesAreAccepted();
                    _verboseOwner = false;
                    _verbose = value;
                    _jobStreamsLoaded = true;
                }
            }
        }

        /// <summary>
        /// Gets or sets the debug buffer. Debug output of Job is written
        /// to this buffer.
        /// <exception cref="ArgumentNullException">
        /// Cannot set to a null value.
        /// </exception>
        /// </summary>
        /// <exception cref="ObjectDisposedException">
        /// Object is disposed.
        /// </exception>
        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public PSDataCollection<DebugRecord> Debug
        {
            get
            {
                LoadJobStreams(); // for delayed loading
                return _debug;
            }

            set
            {
                if (value == null)
                {
                    throw PSTraceSource.NewArgumentNullException("Debug");
                }

                lock (syncObject)
                {
                    AssertChangesAreAccepted();
                    _debugOwner = false;
                    _debug = value;
                }
            }
        }

        /// <summary>
        /// Gets or sets the warning buffer. Warnings of job are written to
        /// this buffer.
        /// </summary>
        /// <exception cref="ArgumentNullException">
        /// Cannot set to a null value.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// Object is disposed.
        /// </exception>
        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public PSDataCollection<WarningRecord> Warning
        {
            get
            {
                LoadJobStreams(); // for delayed loading
                return _warning;
            }

            set
            {
                if (value == null)
                {
                    throw PSTraceSource.NewArgumentNullException("Warning");
                }

                lock (syncObject)
                {
                    AssertChangesAreAccepted();
                    _warningOwner = false;
                    _warning = value;
                    _jobStreamsLoaded = true;
                }
            }
        }

        /// <summary>
        /// Gets or sets the information buffer. Information records of job are written to
        /// this buffer.
        /// </summary>
        /// <exception cref="ArgumentNullException">
        /// Cannot set to a null value.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// Object is disposed.
        /// </exception>
        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public PSDataCollection<InformationRecord> Information
        {
            get
            {
                LoadJobStreams(); // for delayed loading
                return _information;
            }

            set
            {
                if (value == null)
                {
                    throw PSTraceSource.NewArgumentNullException("Information");
                }

                lock (syncObject)
                {
                    AssertChangesAreAccepted();
                    _informationOwner = false;
                    _information = value;
                    _jobStreamsLoaded = true;
                }
            }
        }

        /// <summary>
        /// Indicates a location where this job is running.
        /// </summary>
        public abstract string Location { get; }

        #endregion results

        #region Connect/Disconnect

        /// <summary>
        /// Returns boolean indicating whether the underlying
        /// transport for the job (or child jobs) supports
        /// connect/disconnect semantics.
        /// </summary>
        internal virtual bool CanDisconnect
        {
            get { return false; }
        }

        /// <summary>
        /// Returns runspaces associated with the Job, including
        /// child jobs.
        /// </summary>
        /// <returns>IEnumerable of RemoteRunspaces.</returns>
        internal virtual IEnumerable<RemoteRunspace> GetRunspaces()
        {
            return null;
        }

        #endregion

        #endregion Job Properties

        #region Job State and State Change Event

        /// <summary>
        /// Event raised when state of the job changes.
        /// </summary>
        [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
        public event EventHandler<JobStateEventArgs> StateChanged;

        /// <summary>
        /// Sets Job State.
        /// </summary>
        /// <param name="state">
        /// New State of Job
        /// </param>
        protected void SetJobState(JobState state)
        {
            AssertNotDisposed();
            SetJobState(state, null);
        }

        /// <summary>
        /// Sets Job State.
        /// </summary>
        /// <param name="state">
        /// New State of Job
        /// </param>
        /// <param name="reason">
        /// Reason associated with the state.
        /// </param>
        internal void SetJobState(JobState state, Exception reason)
        {
            using (PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource())
            {
                AssertNotDisposed();

                bool alldone = false;
                JobStateInfo previousState = JobStateInfo;

                lock (syncObject)
                {
                    JobStateInfo = new JobStateInfo(state, reason);

                    if (state == JobState.Running)
                    {
                        // BeginTime is set only once.
                        if (PSBeginTime == null)
                        {
                            PSBeginTime = DateTime.Now;
                        }
                    }
                    else if (IsFinishedState(state))
                    {
                        alldone = true;

                        // EndTime is set only once.
                        if (PSEndTime == null)
                        {
                            PSEndTime = DateTime.Now;
                        }
                    }
                }

                if (alldone)
                {
                    CloseAllStreams();

                    if (_processingOutput)
                    {
                        try
                        {
                            // Still marked as processing output.  Send final state changed.
                            HandleOutputProcessingStateChanged(this, new OutputProcessingStateEventArgs(false));
                        }
                        catch (Exception)
                        {
                        }
                    }
                }

#pragma warning disable 56500
                // Exception raised in the eventhandler are not error in job.
                // silently ignore them.
                try
                {
                    tracer.WriteMessage("Job", "SetJobState", Guid.Empty, this, "Invoking StateChanged event", null);
                    StateChanged.SafeInvoke(this, new JobStateEventArgs(JobStateInfo.Clone(), previousState));
                }
                catch (Exception exception) // ignore non-severe exceptions
                {
                    tracer.WriteMessage("Job", "SetJobState", Guid.Empty, this,
                                        "Some Job StateChange event handler threw an unhandled exception.", null);
                    tracer.TraceException(exception);
                }

                // finished needs to be set after StateChanged event
                // has been raised
                if (alldone)
                {
                    lock (syncObject)
                    {
                        _finished?.Set();
                    }
                }
#pragma warning restore 56500
            }
        }

        #endregion Job State and State Change Event

        #region Job Public Methods

        /// <summary>
        /// Stop this job object. If job contains child job, this should
        /// stop child job objects also.
        /// </summary>
        public abstract void StopJob();

        #endregion Job Public Methods

        #region Private/Internal Methods

        /// <summary>
        /// Returns the items in results collection
        /// after clearing up all the internal
        /// structures.
        /// </summary>
        /// <returns>Collection of stream objects.</returns>
        internal Collection<PSStreamObject> ReadAll()
        {
            Output.Clear();
            Error.Clear();
            Debug.Clear();
            Warning.Clear();
            Verbose.Clear();
            Progress.Clear();

            return Results.ReadAll();
        }

        /// <summary>
        /// Helper function to check if job is finished.
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>
        internal bool IsFinishedState(JobState state)
        {
            lock (syncObject)
            {
                return (state == JobState.Completed || state == JobState.Failed || state == JobState.Stopped);
            }
        }

        internal bool IsPersistentState(JobState state)
        {
            lock (syncObject)
            {
                return (IsFinishedState(state) || state == JobState.Disconnected || state == JobState.Suspended);
            }
        }

        /// <summary>
        /// Checks if the current instance can accept changes like
        /// changing one of the properties like Output, Error etc.
        /// If changes are not allowed, throws an exception.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Powershell instance cannot be changed in its
        /// current state.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// Object is disposed.
        /// </exception>
        private void AssertChangesAreAccepted()
        {
            AssertNotDisposed();
            lock (syncObject)
            {
                if (JobStateInfo.State == JobState.Running)
                {
                    throw new InvalidJobStateException(JobState.Running);
                }
            }
        }

        /// <summary>
        /// Automatically generate a job name if the user
        /// does not supply one.
        /// </summary>
        /// <returns>Auto generated job name.</returns>
        /// <remarks>Since the user can script/program against the
        /// job name, the auto generated name will not be
        /// localizable</remarks>
        protected string AutoGenerateJobName()
        {
            return "Job" + Id.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
        }

        /// <summary>
        /// Checks if the current powershell instance is disposed.
        /// If disposed, throws ObjectDisposedException.
        /// </summary>
        /// <exception cref="ObjectDisposedException">
        /// Object is disposed.
        /// </exception>
        internal void AssertNotDisposed()
        {
            if (_isDisposed)
            {
                throw PSTraceSource.NewObjectDisposedException("PSJob");
            }
        }

        /// <summary>
        /// A helper method to close all the streams.
        /// </summary>
        internal void CloseAllStreams()
        {
            // The Complete() method includes raising public notification events that third parties can
            // handle and potentially throw exceptions on the notification thread.  We don't want to
            // propagate those exceptions because it prevents this thread from completing its processing.
            if (_resultsOwner) { try { _results.Complete(); } catch (Exception e) { TraceException(e); } }

            if (_outputOwner) { try { _output.Complete(); } catch (Exception e) { TraceException(e); } }

            if (_errorOwner) { try { _error.Complete(); } catch (Exception e) { TraceException(e); } }

            if (_progressOwner) { try { _progress.Complete(); } catch (Exception e) { TraceException(e); } }

            if (_verboseOwner) { try { _verbose.Complete(); } catch (Exception e) { TraceException(e); } }

            if (_warningOwner) { try { _warning.Complete(); } catch (Exception e) { TraceException(e); } }

            if (_debugOwner) { try { _debug.Complete(); } catch (Exception e) { TraceException(e); } }

            if (_informationOwner) { try { _information.Complete(); } catch (Exception e) { TraceException(e); } }
        }

        private static void TraceException(Exception e)
        {
            using (PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource())
            {
                tracer.TraceException(e);
            }
        }

        /// <summary>
        /// Gets the job for the specified location.
        /// </summary>
        /// <param name="location">Location to filter on.</param>
        /// <returns>Collection of jobs.</returns>
        internal List<Job> GetJobsForLocation(string location)
        {
            List<Job> returnJobList = new List<Job>();

            foreach (Job job in ChildJobs)
            {
                if (string.Equals(job.Location, location, StringComparison.OrdinalIgnoreCase))
                {
                    returnJobList.Add(job);
                }
            }

            return returnJobList;
        }

        #endregion Private/Internal Methods

        #region IDisposable Members

        /// <summary>
        /// Dispose all managed resources. This will suppress finalizer on the object from getting called by
        /// calling System.GC.SuppressFinalize(this).
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            // To prevent derived types with finalizers from having to re-implement System.IDisposable to call it,
            // unsealed types without finalizers should still call SuppressFinalize.
            System.GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Release all the resources.
        /// </summary>
        /// <param name="disposing">
        /// if true, release all the managed objects.
        /// </param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!_isDisposed)
                {
                    CloseAllStreams();

                    // release the WaitHandle
                    lock (syncObject)
                    {
                        if (_finished != null)
                        {
                            _finished.Dispose();
                            _finished = null;
                        }
                    }

                    // Only dispose the collections if we've created them...
                    if (_resultsOwner) _results.Dispose();
                    if (_outputOwner) _output.Dispose();
                    if (_errorOwner) _error.Dispose();
                    if (_debugOwner) _debug.Dispose();
                    if (_informationOwner) _information.Dispose();
                    if (_verboseOwner) _verbose.Dispose();
                    if (_warningOwner) _warning.Dispose();
                    if (_progressOwner) _progress.Dispose();

                    _isDisposed = true;
                }
            }
        }

        private bool _isDisposed;

        #endregion IDisposable Members

        #region MonitorOutputProcessing

        internal event EventHandler<OutputProcessingStateEventArgs> OutputProcessingStateChanged;

        private bool _processingOutput;

        /// <summary>
        /// MonitorOutputProcessing.
        /// </summary>
        internal bool MonitorOutputProcessing
        {
            get;
            set;
        }

        internal void SetMonitorOutputProcessing(IOutputProcessingState outputProcessingState)
        {
            if (outputProcessingState != null)
            {
                outputProcessingState.OutputProcessingStateChanged += HandleOutputProcessingStateChanged;
            }
        }

        internal void RemoveMonitorOutputProcessing(IOutputProcessingState outputProcessingState)
        {
            if (outputProcessingState != null)
            {
                outputProcessingState.OutputProcessingStateChanged -= HandleOutputProcessingStateChanged;
            }
        }

        private void HandleOutputProcessingStateChanged(object sender, OutputProcessingStateEventArgs e)
        {
            _processingOutput = e.ProcessingOutput;
            OutputProcessingStateChanged.SafeInvoke<OutputProcessingStateEventArgs>(this, e);
        }

        #endregion
    }

    /// <summary>
    /// Top level job object for remoting. This contains multiple child job
    /// objects. Each child job object invokes command on one remote machine.
    /// </summary>
    /// <remarks>
    /// Not removing the prefix "PS" as this signifies powershell specific remoting job
    /// </remarks>
    internal class PSRemotingJob : Job
    {
        #region Internal Constructors

        /// <summary>
        /// Internal constructor for initializing PSRemotingJob using
        /// computer names.
        /// </summary>
        /// <param name="computerNames">names of computers for
        /// which the job object is being created</param>
        /// <param name="computerNameHelpers">list of helper objects
        /// corresponding to the computer names
        /// </param>
        /// <param name="remoteCommand">remote command corresponding to this
        /// job object</param>
        /// <param name="name"> a friendly name for the job object
        /// </param>
        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal PSRemotingJob(string[] computerNames,
                        List<IThrottleOperation> computerNameHelpers, string remoteCommand, string name)
            : this(computerNames, computerNameHelpers, remoteCommand, 0, name)
        { }

        /// <summary>
        /// Internal constructor for initializing job using
        /// PSSession objects.
        /// </summary>
        /// <param name="remoteRunspaceInfos">array of runspace info
        /// objects on which the remote command is executed</param>
        /// <param name="runspaceHelpers">List of helper objects for the
        /// runspaces</param>
        /// <param name="remoteCommand"> remote command corresponding to this
        /// job object</param>
        /// <param name="name">a friendly name for the job object
        /// </param>
        internal PSRemotingJob(PSSession[] remoteRunspaceInfos,
                        List<IThrottleOperation> runspaceHelpers, string remoteCommand, string name)
            : this(remoteRunspaceInfos, runspaceHelpers, remoteCommand, 0, name)
        { }

        /// <summary>
        /// Internal constructor for initializing PSRemotingJob using
        /// computer names.
        /// </summary>
        /// <param name="computerNames">names of computers for
        /// which the result object is being created</param>
        /// <param name="computerNameHelpers">list of helper objects
        /// corresponding to the computer names
        /// </param>
        /// <param name="remoteCommand">remote command corresponding to this
        /// result object</param>
        /// <param name="throttleLimit">Throttle limit to use.</param>
        /// <param name="name">A friendly name for the job object.</param>
        internal PSRemotingJob(string[] computerNames,
                        List<IThrottleOperation> computerNameHelpers, string remoteCommand,
                            int throttleLimit, string name)
            : base(remoteCommand, name)
        {
            // Create child jobs for each object in the list
            foreach (ExecutionCmdletHelperComputerName helper in computerNameHelpers)
            {
                // Create Child Job and Register for its StateChanged Event
                PSRemotingChildJob childJob = new PSRemotingChildJob(remoteCommand,
                                            helper, _throttleManager);
                childJob.StateChanged += HandleChildJobStateChanged;
                childJob.JobUnblocked += HandleJobUnblocked;

                // Add this job to list of childjobs
                ChildJobs.Add(childJob);
            }

            CommonInit(throttleLimit, computerNameHelpers);
        }

        /// <summary>
        /// Internal constructor for initializing job using
        /// PSSession objects.
        /// </summary>
        /// <param name="remoteRunspaceInfos">array of runspace info
        /// objects on which the remote command is executed</param>
        /// <param name="runspaceHelpers">List of helper objects for the
        /// runspaces</param>
        /// <param name="remoteCommand"> remote command corresponding to this
        /// result object</param>
        /// <param name="throttleLimit">Throttle limit to use.</param>
        /// <param name="name"></param>
        internal PSRemotingJob(PSSession[] remoteRunspaceInfos,
                        List<IThrottleOperation> runspaceHelpers, string remoteCommand,
                        int throttleLimit, string name)
            : base(remoteCommand, name)
        {
            // Create child jobs for each object in the list
            for (int i = 0; i < remoteRunspaceInfos.Length; i++)
            {
                ExecutionCmdletHelperRunspace helper = (ExecutionCmdletHelperRunspace)runspaceHelpers[i];

                // Create Child Job object and Register for its state changed event
                PSRemotingChildJob job = new PSRemotingChildJob(remoteCommand,
                                helper, _throttleManager);
                job.StateChanged += HandleChildJobStateChanged;
                job.JobUnblocked += HandleJobUnblocked;

                // Add the child job to list of child jobs
                ChildJobs.Add(job);
            }

            CommonInit(throttleLimit, runspaceHelpers);
        }

        /// <summary>
        /// Creates a job object and child jobs for each disconnected pipeline/runspace
        /// provided in the list of ExecutionCmdletHelperRunspace items.  The runspace
        /// object must have a remote running command that can be connected to.
        /// Use Connect() method to transition to the connected state.
        /// </summary>
        /// <param name="helpers">List of DisconnectedJobOperation objects with disconnected pipelines.</param>
        /// <param name="throttleLimit">Throttle limit value.</param>
        /// <param name="name">Job name.</param>
        /// <param name="aggregateResults">Aggregate results.</param>
        internal PSRemotingJob(List<IThrottleOperation> helpers,
                               int throttleLimit, string name, bool aggregateResults)
            : base(string.Empty, name)
        {
            // All pipeline objects must be in "disconnected" state and associated to running
            // remote commands.  Once the jobs are connected they can be stopped using the
            // ExecutionCmdletHelperRunspace object and ThrottleManager.
            foreach (ExecutionCmdletHelper helper in helpers)
            {
                PSRemotingChildJob job = new PSRemotingChildJob(helper, _throttleManager, aggregateResults);
                job.StateChanged += HandleChildJobStateChanged;
                job.JobUnblocked += HandleJobUnblocked;

                ChildJobs.Add(job);
            }

            // Since no results are produced by any streams. We should
            // close all the streams.
            base.CloseAllStreams();

            // Set status to "disconnected".
            SetJobState(JobState.Disconnected);

            // Submit the disconnected operation helpers to the throttle manager
            _throttleManager.ThrottleLimit = throttleLimit;
            _throttleManager.SubmitOperations(helpers);
            _throttleManager.EndSubmitOperations();
        }

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected PSRemotingJob() { }

        /// <summary>
        /// Initialization common to both constructors.
        /// </summary>
        private void CommonInit(int throttleLimit, List<IThrottleOperation> helpers)
        {
            // Since no results are produced by any streams. We should
            // close all the streams
            base.CloseAllStreams();

            // set status to "in progress"
            SetJobState(JobState.Running);

            // submit operations to the throttle manager
            _throttleManager.ThrottleLimit = throttleLimit;
            _throttleManager.SubmitOperations(helpers);
            _throttleManager.EndSubmitOperations();
        }
        #endregion Internal Constructors

        #region internal methods

        /// <summary>
        /// Get entity result for the specified computer.
        /// </summary>
        /// <param name="computerName">computername for which entity
        /// result is required</param>
        /// <returns>Entity result.</returns>
        internal List<Job> GetJobsForComputer(string computerName)
        {
            List<Job> returnJobList = new List<Job>();

            foreach (Job j in ChildJobs)
            {
                if (j is not PSRemotingChildJob child) continue;
                if (string.Equals(child.Runspace.ConnectionInfo.ComputerName, computerName,
                                StringComparison.OrdinalIgnoreCase))
                {
                    returnJobList.Add(child);
                }
            }

            return returnJobList;
        }

        /// <summary>
        /// Get entity result for the specified runspace.
        /// </summary>
        /// <param name="runspace">runspace for which entity
        /// result is required</param>
        /// <returns>Entity result.</returns>
        internal List<Job> GetJobsForRunspace(PSSession runspace)
        {
            List<Job> returnJobList = new List<Job>();

            foreach (Job j in ChildJobs)
            {
                if (j is not PSRemotingChildJob child) continue;
                if (child.Runspace.InstanceId.Equals(runspace.InstanceId))
                {
                    returnJobList.Add(child);
                }
            }

            return returnJobList;
        }

        /// <summary>
        /// Get entity result for the specified helper object.
        /// </summary>
        /// <param name="operation">helper for which entity
        /// result is required</param>
        /// <returns>Entity result.</returns>
        internal List<Job> GetJobsForOperation(IThrottleOperation operation)
        {
            List<Job> returnJobList = new List<Job>();
            ExecutionCmdletHelper helper = operation as ExecutionCmdletHelper;

            foreach (Job j in ChildJobs)
            {
                if (j is not PSRemotingChildJob child) continue;
                if (child.Helper.Equals(helper))
                {
                    returnJobList.Add(child);
                }
            }

            return returnJobList;
        }

        #endregion internal methods

        #region Connection Support

        /// <summary>
        /// Connect all child jobs if they are in a disconnected state.
        /// </summary>
        internal void ConnectJobs()
        {
            // Create connect operation objects for each child job object to connect.
            List<IThrottleOperation> connectJobOperations = new List<IThrottleOperation>();
            foreach (PSRemotingChildJob childJob in ChildJobs)
            {
                if (childJob.JobStateInfo.State == JobState.Disconnected)
                {
                    connectJobOperations.Add(new ConnectJobOperation(childJob));
                }
            }

            if (connectJobOperations.Count == 0)
            {
                return;
            }

            // Submit the connect job operation.
            // Return only after the connect operation completes.
            SubmitAndWaitForConnect(connectJobOperations);
        }

        /// <summary>
        /// Connect a single child job associated with the provided runspace.
        /// </summary>
        /// <param name="runspaceInstanceId">Runspace instance id for child job.</param>
        internal void ConnectJob(Guid runspaceInstanceId)
        {
            List<IThrottleOperation> connectJobOperations = new List<IThrottleOperation>();
            PSRemotingChildJob childJob = FindDisconnectedChildJob(runspaceInstanceId);
            if (childJob != null)
            {
                connectJobOperations.Add(new ConnectJobOperation(childJob));
            }

            if (connectJobOperations.Count == 0)
            {
                return;
            }

            // Submit the connect job operation.
            // Return only after the connect operation completes.
            SubmitAndWaitForConnect(connectJobOperations);
        }

        private static void SubmitAndWaitForConnect(List<IThrottleOperation> connectJobOperations)
        {
            using (ThrottleManager connectThrottleManager = new ThrottleManager())
            {
                using (ManualResetEvent connectResult = new ManualResetEvent(false))
                {
                    EventHandler<EventArgs> throttleCompleteEventHandler =
                        (object sender, EventArgs eventArgs) => connectResult.Set();

                    connectThrottleManager.ThrottleComplete += throttleCompleteEventHandler;
                    try
                    {
                        connectThrottleManager.ThrottleLimit = 0;
                        connectThrottleManager.SubmitOperations(connectJobOperations);
                        connectThrottleManager.EndSubmitOperations();

                        connectResult.WaitOne();
                    }
                    finally
                    {
                        connectThrottleManager.ThrottleComplete -= throttleCompleteEventHandler;
                    }
                }
            }
        }

        /// <summary>
        /// Simple throttle operation class for connecting jobs.
        /// </summary>
        private sealed class ConnectJobOperation : IThrottleOperation
        {
            private readonly PSRemotingChildJob _psRemoteChildJob;

            internal ConnectJobOperation(PSRemotingChildJob job)
            {
                _psRemoteChildJob = job;
                _psRemoteChildJob.StateChanged += ChildJobStateChangedHandler;
            }

            internal override void StartOperation()
            {
                bool startedSuccessfully = true;

                try
                {
                    _psRemoteChildJob.ConnectAsync();
                }
                catch (InvalidJobStateException e)
                {
                    startedSuccessfully = false;

                    string msg = StringUtil.Format(RemotingErrorIdStrings.JobConnectFailed, _psRemoteChildJob.Name);
                    Exception reason = new RuntimeException(msg, e);
                    ErrorRecord errorRecord = new ErrorRecord(reason, "PSJobConnectFailed", ErrorCategory.InvalidOperation, _psRemoteChildJob);
                    _psRemoteChildJob.WriteError(errorRecord);
                }

                if (!startedSuccessfully)
                {
                    RemoveEventCallback();
                    SendStartComplete();
                }
            }

            internal override void StopOperation()
            {
                RemoveEventCallback();

                // Cannot stop a connect attempt.
                OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs();
                operationStateEventArgs.OperationState = OperationState.StopComplete;
                OperationComplete.SafeInvoke(this, operationStateEventArgs);
            }

            internal override event EventHandler<OperationStateEventArgs> OperationComplete;

            private void ChildJobStateChangedHandler(object sender, JobStateEventArgs eArgs)
            {
                if (eArgs.JobStateInfo.State == JobState.Disconnected)
                {
                    return;
                }

                RemoveEventCallback();
                SendStartComplete();
            }

            private void SendStartComplete()
            {
                OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs();
                operationStateEventArgs.OperationState = OperationState.StartComplete;
                OperationComplete.SafeInvoke(this, operationStateEventArgs);
            }

            private void RemoveEventCallback()
            {
                _psRemoteChildJob.StateChanged -= ChildJobStateChangedHandler;
            }
        }

        /// <summary>
        /// Finds the disconnected child job associated with this runspace and returns
        /// the PowerShell object that is remotely executing the command.
        /// </summary>
        /// <param name="runspaceInstanceId">Runspace instance Id.</param>
        /// <returns>Associated PowerShell object.</returns>
        internal PowerShell GetAssociatedPowerShellObject(Guid runspaceInstanceId)
        {
            PowerShell ps = null;
            PSRemotingChildJob childJob = FindDisconnectedChildJob(runspaceInstanceId);
            if (childJob != null)
            {
                ps = childJob.GetPowerShell();
            }

            return ps;
        }

        /// <summary>
        /// Helper method to find a disconnected child job associated with
        /// a given runspace.
        /// </summary>
        /// <param name="runspaceInstanceId">Runspace Id.</param>
        /// <returns>PSRemotingChildJob object.</returns>
        private PSRemotingChildJob FindDisconnectedChildJob(Guid runspaceInstanceId)
        {
            PSRemotingChildJob rtnJob = null;

            foreach (PSRemotingChildJob childJob in this.ChildJobs)
            {
                if ((childJob.Runspace.InstanceId.Equals(runspaceInstanceId)) &&
                    (childJob.JobStateInfo.State == JobState.Disconnected))
                {
                    rtnJob = childJob;
                    break;
                }
            }

            return rtnJob;
        }

        /// <summary>
        /// Internal method to stop a job without first connecting it if it is in
        /// a disconnected state.  This supports Receive-PSSession where it abandons
        /// a currently running/disconnected job when user selects -OutTarget Host.
        /// </summary>
        internal void InternalStopJob()
        {
            if (_isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State))
            {
                return;
            }

            lock (_syncObject)
            {
                if (_isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State))
                {
                    return;
                }

                _stopIsCalled = true;
            }

            _throttleManager.StopAllOperations();

            Finished.WaitOne();
        }

        #endregion

        private bool _moreData = true;
        /// <summary>
        /// Indicates if more data is available.
        /// </summary>
        /// <remarks>
        /// This has more data if any of the child jobs have more data.
        /// </remarks>
        public override bool HasMoreData
        {
            get
            {
                // moreData is initially set to true, and it
                // will remain so until the async result
                // object has completed execution.

                if (_moreData && IsFinishedState(JobStateInfo.State))
                {
                    bool atleastOneChildHasMoreData = false;

                    for (int i = 0; i < ChildJobs.Count; i++)
                    {
                        if (ChildJobs[i].HasMoreData)
                        {
                            atleastOneChildHasMoreData = true;
                            break;
                        }
                    }

                    _moreData = atleastOneChildHasMoreData;
                }

                return _moreData;
            }
        }

        private bool _stopIsCalled = false;
        /// <summary>
        /// Stop Job.
        /// </summary>
        public override void StopJob()
        {
            // If the job is in a disconnected state then try to connect it
            // so that it can be stopped on the server.
            if (JobStateInfo.State == JobState.Disconnected)
            {
                bool ConnectSuccessful;

                try
                {
                    ConnectJobs();
                    ConnectSuccessful = true;
                }
                catch (InvalidRunspaceStateException)
                {
                    ConnectSuccessful = false;
                }
                catch (PSRemotingTransportException)
                {
                    ConnectSuccessful = false;
                }
                catch (PSInvalidOperationException)
                {
                    ConnectSuccessful = false;
                }

                if (!ConnectSuccessful && this.Error.IsOpen)
                {
                    string msg = StringUtil.Format(RemotingErrorIdStrings.StopJobNotConnected, this.Name);
                    Exception reason = new RuntimeException(msg);
                    ErrorRecord errorRecord = new ErrorRecord(reason, "StopJobCannotConnectToServer",
                        ErrorCategory.InvalidOperation, this);
                    WriteError(errorRecord);

                    return;
                }
            }

            InternalStopJob();
        }

        private string _statusMessage;
        /// <summary>
        /// Message indicating status of the job.
        /// </summary>
        public override string StatusMessage
        {
            get
            {
                return _statusMessage;
            }
        }

        /// <summary>
        /// Used by Invoke-Command cmdlet to show/hide computername property value.
        /// Format and Output has capability to understand RemoteObjects and this property lets
        /// Format and Output decide whether to show/hide computername.
        /// Default is true.
        /// </summary>
        internal bool HideComputerName
        {
            get
            {
                return _hideComputerName;
            }

            set
            {
                _hideComputerName = value;
                foreach (Job job in this.ChildJobs)
                {
                    PSRemotingChildJob rJob = job as PSRemotingChildJob;
                    if (rJob != null)
                    {
                        rJob.HideComputerName = value;
                    }
                }
            }
        }

        private bool _hideComputerName = true;

        // ISSUE: Implement StatusMessage
        /// <summary>
        /// Checks the status of remote command execution.
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        private void SetStatusMessage()
        {
            _statusMessage = "test";
            //        bool localErrors = false; // if local errors are present
            //        bool setFinished = false;    // if finished needs to be set

            //        statusMessage = "OK";

            //        lock (syncObject)
            //        {
            //            if (finishedCount == ChildJobs.Count)
            //            {
            //                // ISSUE: Change this code to look in to child jobs for exception
            //                if (errors.Count > 0)
            //                {
            //                    statusMessage = "LocalErrors";
            //                    localErrors = true;
            //                }

            //                // check for status of remote command
            //                for (int i = 0; i < ChildJobs.Count; i++)
            //                {
            //                    PSRemotingChildJob childJob = ChildJobs[i] as PSRemotingChildJob;
            //                    if (childJob == null) continue;
            //                    if (childJob.ContainsErrors)
            //                    {
            //                        if (localErrors)
            //                        {
            //                            statusMessage = "LocalAndRemoteErrors";
            //                        }
            //                        else
            //                        {
            //                            statusMessage = "RemoteErrors";
            //                        }
            //                        break;
            //                    }
            //                }

            //                setFinished = true;
            //            }
            //        }
        }

        #region finish logic

        // This variable is set to true if at least one child job failed.
        private bool _atleastOneChildJobFailed = false;

        // count of number of child jobs which have finished
        private int _finishedChildJobsCount = 0;

        // count of number of child jobs which are blocked
        private int _blockedChildJobsCount = 0;

        // count of child jobs that are in disconnected state.
        private int _disconnectedChildJobsCount = 0;

        // count of child jobs that are in Debug halted state.
        private int _debugChildJobsCount = 0;

        /// <summary>
        /// Handles the StateChanged event from each of the child job objects.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HandleChildJobStateChanged(object sender, JobStateEventArgs e)
        {
            // Update object state to reflect disconnect state related changes in child jobs.
            CheckDisconnectedAndUpdateState(e.JobStateInfo.State, e.PreviousJobStateInfo.State);

            if (e.JobStateInfo.State == JobState.Blocked)
            {
                // increment count of blocked child jobs
                lock (_syncObject)
                {
                    _blockedChildJobsCount++;
                }

                // if any of the child job is blocked, we set state to blocked
                SetJobState(JobState.Blocked, null);
                return;
            }

            // Handle transition of child job to Debug halt state.
            if (e.JobStateInfo.State == JobState.AtBreakpoint)
            {
                lock (_syncObject) { _debugChildJobsCount++; }

                // If any child jobs are Debug halted, we set state to Debug.
                SetJobState(JobState.AtBreakpoint);
                return;
            }

            // Handle transition of child job back to running state.
            if ((e.JobStateInfo.State == JobState.Running) &&
                (e.PreviousJobStateInfo.State == JobState.AtBreakpoint))
            {
                int totalDebugCount;
                lock (_syncObject) { totalDebugCount = --_debugChildJobsCount; }

                if (totalDebugCount == 0)
                {
                    SetJobState(JobState.Running);
                    return;
                }
            }

            // Ignore state changes which are not resulting in state change to finished.
            if (!IsFinishedState(e.JobStateInfo.State))
            {
                return;
            }

            if (e.JobStateInfo.State == JobState.Failed)
            {
                // If any of the child job failed, we set status to failed
                _atleastOneChildJobFailed = true;
            }

            bool allChildJobsFinished = false;
            lock (_syncObject)
            {
                _finishedChildJobsCount++;

                // We are done
                if (_finishedChildJobsCount + _disconnectedChildJobsCount
                    == ChildJobs.Count)
                {
                    allChildJobsFinished = true;
                }
            }

            if (allChildJobsFinished)
            {
                // if any child job failed, set status to failed
                // If stop was called set, status to stopped
                // else completed
                if (_disconnectedChildJobsCount > 0)
                {
                    SetJobState(JobState.Disconnected);
                }
                else if (_atleastOneChildJobFailed)
                {
                    SetJobState(JobState.Failed);
                }
                else if (_stopIsCalled)
                {
                    SetJobState(JobState.Stopped);
                }
                else
                {
                    SetJobState(JobState.Completed);
                }
            }
        }

        /// <summary>
        /// Updates the parent job state based on state of all child jobs.
        /// </summary>
        /// <param name="newState">New child job state.</param>
        /// <param name="prevState">Previous child job state.</param>
        private void CheckDisconnectedAndUpdateState(JobState newState, JobState prevState)
        {
            if (IsFinishedState(JobStateInfo.State))
            {
                return;
            }

            // Do all logic inside a lock to ensure it is atomic against
            // multiple job thread state changes.
            lock (_syncObject)
            {
                if (newState == JobState.Disconnected)
                {
                    ++(_disconnectedChildJobsCount);

                    // If previous state was Blocked then we need to decrement the count
                    // since it is now Disconnected.
                    if (prevState == JobState.Blocked)
                    {
                        --_blockedChildJobsCount;
                    }

                    // If all unfinished and unblocked child jobs are disconnected then this
                    // parent job becomes disconnected.
                    if ((_disconnectedChildJobsCount +
                         _finishedChildJobsCount +
                         _blockedChildJobsCount) == ChildJobs.Count)
                    {
                        SetJobState(JobState.Disconnected, null);
                    }
                }
                else
                {
                    if (prevState == JobState.Disconnected)
                    {
                        --(_disconnectedChildJobsCount);
                    }

                    if ((newState == JobState.Running) && (JobStateInfo.State == JobState.Disconnected))
                    {
                        // Note that SetJobState() takes a lock so it is unnecessary to do
                        // this under a lock here.
                        SetJobState(JobState.Running, null);
                    }
                }
            }
        }

        #endregion finish logic

        /// <summary>
        /// Release all the resources.
        /// </summary>
        /// <param name="disposing">
        /// if true, release all the managed objects.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_isDisposed)
                {
                    return;
                }

                lock (_syncObject)
                {
                    if (_isDisposed)
                    {
                        return;
                    }

                    _isDisposed = true;
                }

                try
                {
                    if (!IsFinishedState(JobStateInfo.State))
                    {
                        StopJob();
                    }

                    foreach (Job job in ChildJobs)
                    {
                        job.Dispose();
                    }

                    _throttleManager.Dispose();
                }
                finally
                {
                    base.Dispose(disposing);
                }
            }
        }

        private bool _isDisposed = false;

        private string ConstructLocation()
        {
            StringBuilder location = new StringBuilder();

            if (ChildJobs.Count > 0)
            {
                foreach (PSRemotingChildJob job in ChildJobs)
                {
                    location.Append(job.Location);
                    location.Append(',');
                }

                location.Remove(location.Length - 1, 1);
            }

            return location.ToString();
        }

        /// <summary>
        /// Computers on which this job is running.
        /// </summary>
        public override string Location
        {
            get
            {
                return ConstructLocation();
            }
        }

        /// <summary>
        /// Returns boolean indicating whether the underlying
        /// transport for the job (or child jobs) supports
        /// connect/disconnect semantics.
        /// </summary>
        internal override bool CanDisconnect
        {
            get
            {
                // If one child job can disconnect then all of them can since
                // all child jobs use the same remote runspace transport.
                return (ChildJobs.Count > 0) && ChildJobs[0].CanDisconnect;
            }
        }

        /// <summary>
        /// Returns runspaces associated with the Job, including
        /// child jobs.
        /// </summary>
        /// <returns>IEnumerable of RemoteRunspaces.</returns>
        internal override IEnumerable<RemoteRunspace> GetRunspaces()
        {
            List<RemoteRunspace> runspaces = new List<RemoteRunspace>();
            foreach (PSRemotingChildJob job in ChildJobs)
            {
                runspaces.Add(job.Runspace as RemoteRunspace);
            }

            return runspaces;
        }

        /// <summary>
        /// Handles JobUnblocked event from a child job and decrements
        /// count of blocked child jobs. When count reaches 0, sets the
        /// state of the parent job to running.
        /// </summary>
        /// <param name="sender">Sender of this event, unused.</param>
        /// <param name="eventArgs">event arguments, should be empty in this
        /// case</param>
        private void HandleJobUnblocked(object sender, EventArgs eventArgs)
        {
            bool unblockjob = false;

            lock (_syncObject)
            {
                _blockedChildJobsCount--;

                if (_blockedChildJobsCount == 0)
                {
                    unblockjob = true;
                }
            }

            if (unblockjob)
            {
                SetJobState(JobState.Running, null);
            }
        }

        #region Private Members

        private readonly ThrottleManager _throttleManager = new ThrottleManager();

        private readonly object _syncObject = new object();           // sync object

        #endregion Private Members
    }

    #region DisconnectedJobOperation class

    /// <summary>
    /// Simple throttle operation class for PSRemoting jobs created in the
    /// disconnected state.
    /// </summary>
    internal class DisconnectedJobOperation : ExecutionCmdletHelper
    {
        internal DisconnectedJobOperation(Pipeline pipeline)
        {
            this.pipeline = pipeline;
            this.pipeline.StateChanged += HandlePipelineStateChanged;
        }

        internal override void StartOperation()
        {
            // This is a no-op since disconnected jobs (pipelines) have
            // already been started.
        }

        internal override void StopOperation()
        {
            if (pipeline.PipelineStateInfo.State == PipelineState.Running ||
                pipeline.PipelineStateInfo.State == PipelineState.Disconnected ||
                pipeline.PipelineStateInfo.State == PipelineState.NotStarted)
            {
                // If the pipeline state has reached Complete/Failed/Stopped
                // by the time control reaches here, then this operation
                // becomes a no-op. However, an OperationComplete would have
                // already been raised from the handler.
                pipeline.StopAsync();
            }
            else
            {
                // Will have to raise OperationComplete from here,
                // else ThrottleManager will have
                SendStopComplete();
            }
        }

        internal override event EventHandler<OperationStateEventArgs> OperationComplete;

        private void HandlePipelineStateChanged(object sender, PipelineStateEventArgs stateEventArgs)
        {
            PipelineStateInfo stateInfo = stateEventArgs.PipelineStateInfo;

            switch (stateInfo.State)
            {
                case PipelineState.Running:
                case PipelineState.NotStarted:
                case PipelineState.Stopping:
                case PipelineState.Disconnected:
                    return;
            }

            SendStopComplete(stateEventArgs);
        }

        private void SendStopComplete(EventArgs eventArgs = null)
        {
            OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs();
            operationStateEventArgs.BaseEvent = eventArgs;
            operationStateEventArgs.OperationState = OperationState.StopComplete;
            OperationComplete.SafeInvoke(this, operationStateEventArgs);
        }
    }

    #endregion

    /// <summary>
    /// Class for RemotingChildJob object. This job object invokes command
    /// on one remote machine.
    /// </summary>
    /// <remarks>
    /// TODO: I am not sure whether to change this internal to just RemotingChildJob.
    /// </remarks>
    /// <remarks>
    /// Not removing the prefix "PS" as this signifies powershell specific remoting job
    /// </remarks>
    internal class PSRemotingChildJob : Job, IJobDebugger
    {
        #region Internal Constructor

        /// <summary>
        /// Creates an instance of PSRemotingChildJob.
        /// </summary>
        /// <param name="remoteCommand">Command invoked by this job object.</param>
        /// <param name="helper"></param>
        /// <param name="throttleManager"></param>
        internal PSRemotingChildJob(string remoteCommand, ExecutionCmdletHelper helper, ThrottleManager throttleManager)
            : base(remoteCommand)
        {
            UsesResultsCollection = true;
            Dbg.Assert(helper.Pipeline is RemotePipeline, "Pipeline passed should be a remote pipeline");

            Helper = helper;
            Runspace = helper.Pipeline.Runspace;
            _remotePipeline = helper.Pipeline as RemotePipeline;
            _throttleManager = throttleManager;

            RemoteRunspace remoteRS = Runspace as RemoteRunspace;
            if ((remoteRS != null) && (remoteRS.RunspaceStateInfo.State == RunspaceState.BeforeOpen))
            {
                remoteRS.URIRedirectionReported += HandleURIDirectionReported;
            }

            AggregateResultsFromHelper(helper);

            Runspace.AvailabilityChanged += HandleRunspaceAvailabilityChanged;

            RegisterThrottleComplete(throttleManager);
        }

        /// <summary>
        /// Constructs a disconnected child job that is able to connect to a remote
        /// runspace/command on a server.  The ExecutionCmdletHelperRunspace must
        /// contain a remote pipeline object in a disconnected state.  In addition
        /// the pipeline runspace must be associated with a valid running remote
        /// command that can be connected to.
        /// </summary>
        /// <param name="helper">ExecutionCmdletHelper object containing runspace and pipeline objects.</param>
        /// <param name="throttleManager">ThrottleManger object.</param>
        /// <param name="aggregateResults">Aggregate results.</param>
        internal PSRemotingChildJob(ExecutionCmdletHelper helper, ThrottleManager throttleManager, bool aggregateResults = false)
        {
            UsesResultsCollection = true;
            Dbg.Assert((helper.Pipeline is RemotePipeline), "Helper pipeline object should be a remote pipeline");
            Dbg.Assert((helper.Pipeline.PipelineStateInfo.State == PipelineState.Disconnected), "Remote pipeline object must be in Disconnected state.");

            Helper = helper;
            _remotePipeline = helper.Pipeline as RemotePipeline;
            Runspace = helper.Pipeline.Runspace;
            _throttleManager = throttleManager;

            if (aggregateResults)
            {
                AggregateResultsFromHelper(helper);
            }
            else
            {
                _remotePipeline.StateChanged += HandlePipelineStateChanged;
                _remotePipeline.Output.DataReady += HandleOutputReady;
                _remotePipeline.Error.DataReady += HandleErrorReady;
            }

            Runspace.AvailabilityChanged += HandleRunspaceAvailabilityChanged;

            IThrottleOperation operation = helper as IThrottleOperation;
            operation.OperationComplete += HandleOperationComplete;

            SetJobState(JobState.Disconnected, null);
        }

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected PSRemotingChildJob()
        {
        }

        #endregion Internal Constructor

        #region Internal Methods

        /// <summary>
        /// Connects the remote pipeline that this job represents.
        /// </summary>
        internal void ConnectAsync()
        {
            if (JobStateInfo.State != JobState.Disconnected)
            {
                throw new InvalidJobStateException(JobStateInfo.State);
            }

            _remotePipeline.ConnectAsync();
        }

        #endregion

        #region stop

        // bool isStopCalled = false;
        /// <summary>
        /// Stops the job.
        /// </summary>
        public override void StopJob()
        {
            if (_isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State))
            {
                return;
            }

            lock (SyncObject)
            {
                if (_isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State))
                {
                    return;
                }

                _stopIsCalled = true;
            }

            _throttleManager.StopOperation(Helper);

            // if IgnoreStop is set, then StopOperation will
            // return immediately, but StopJob should only
            // return when job is complete. Waiting on the
            // wait handle will ensure that its blocked
            // until the job reaches a terminal state
            Finished.WaitOne();
        }

        #endregion stop

        #region Properties

        /// <summary>
        /// Status Message associated with the Job.
        /// </summary>
        public override string StatusMessage
        {
            get
            {
                // ISSUE implement this.
                return string.Empty;
            }
        }

        /// <summary>
        /// Indicates if there is more data available in
        /// this Job.
        /// </summary>
        public override bool HasMoreData
        {
            get
            {
                return (Results.IsOpen || Results.Count > 0);
            }
        }

        /// <summary>
        /// Returns the computer on which this command is
        /// running.
        /// </summary>
        public override string Location
        {
            get
            {
                return (Runspace != null) ? Runspace.ConnectionInfo.ComputerName : string.Empty;
            }
        }

        /// <summary>
        /// </summary>
        public Runspace Runspace { get; }

        /// <summary>
        /// Helper associated with this entity.
        /// </summary>
        internal ExecutionCmdletHelper Helper { get; } = null;

        /// <summary>
        /// Used by Invoke-Command cmdlet to show/hide computername property value.
        /// Format and Output has capability to understand RemoteObjects and this property lets
        /// Format and Output decide whether to show/hide computername.
        /// Default is true.
        /// </summary>
        internal bool HideComputerName
        {
            get
            {
                return _hideComputerName;
            }

            set
            {
                _hideComputerName = value;
                foreach (Job job in this.ChildJobs)
                {
                    PSRemotingChildJob rJob = job as PSRemotingChildJob;
                    if (rJob != null)
                    {
                        rJob.HideComputerName = value;
                    }
                }
            }
        }

        private bool _hideComputerName = true;

        /// <summary>
        /// Property that indicates this disconnected child job was
        /// previously in the Blocked state.
        /// </summary>
        internal bool DisconnectedAndBlocked { get; private set; } = false;

        /// <summary>
        /// Returns boolean indicating whether the underlying
        /// transport for the job (or child jobs) supports
        /// connect/disconnect semantics.
        /// </summary>
        internal override bool CanDisconnect
        {
            get
            {
                RemoteRunspace remoteRS = Runspace as RemoteRunspace;
                return remoteRS != null && remoteRS.CanDisconnect;
            }
        }

        #endregion Properties

        #region IJobDebugger

        /// <summary>
        /// Job Debugger.
        /// </summary>
        public Debugger Debugger
        {
            get
            {
                if (_jobDebugger == null)
                {
                    lock (this.SyncObject)
                    {
                        if ((_jobDebugger == null) &&
                            (Runspace.Debugger != null))
                        {
                            _jobDebugger = new RemotingJobDebugger(Runspace.Debugger, Runspace, this.Name);
                        }
                    }
                }

                return _jobDebugger;
            }
        }

        /// <summary>
        /// True if job is synchronous and can be debugged.
        /// </summary>
        public bool IsAsync
        {
            get { return _isAsync; }

            set { _isAsync = true; }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Handler which will handle output ready events of the
        /// pipeline. The output objects are queued on to the
        /// internal stream.
        /// </summary>
        /// <param name="sender">the pipeline reader which raised
        /// this event</param>
        /// <param name="eventArgs">Information describing the ready event.</param>
        private void HandleOutputReady(object sender, EventArgs eventArgs)
        {
            PSDataCollectionPipelineReader<PSObject, PSObject> reader =
                    sender as PSDataCollectionPipelineReader<PSObject, PSObject>;

            Collection<PSObject> output = reader.NonBlockingRead();

            foreach (PSObject dataObject in output)
            {
                // attach origin information only if it doesn't exist
                // in case of a second-hop scenario, the origin information
                // will already be added at the second hop machine
                if (dataObject != null)
                {
                    // if the server has already added some properties, which we do not
                    // want to trust, we simply replace them with the server's
                    // identity we know of

                    if (dataObject.Properties[RemotingConstants.ComputerNameNoteProperty] != null)
                    {
                        dataObject.Properties.Remove(RemotingConstants.ComputerNameNoteProperty);
                    }

                    if (dataObject.Properties[RemotingConstants.RunspaceIdNoteProperty] != null)
                    {
                        dataObject.Properties.Remove(RemotingConstants.RunspaceIdNoteProperty);
                    }

                    dataObject.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, reader.ComputerName));
                    dataObject.Properties.Add(new PSNoteProperty(RemotingConstants.RunspaceIdNoteProperty, reader.RunspaceId));
                    // PSShowComputerName is present for all the objects (from remoting)..this is to allow PSComputerName to be selected.
                    // Ex: Invoke-Command localhost,blah { gps } | select PSComputerName should work.
                    if (dataObject.Properties[RemotingConstants.ShowComputerNameNoteProperty] == null)
                    {
                        PSNoteProperty showComputerNameNP = new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, !_hideComputerName);
                        dataObject.Properties.Add(showComputerNameNP);
                    }
                }

                this.WriteObject(dataObject);
            }
        }

        /// <summary>
        /// Handler which will handle error ready events of the
        /// pipeline. The error records are queued on to the
        /// internal stream.
        /// </summary>
        /// <param name="sender">the pipeline reader which raised
        /// this event</param>
        /// <param name="eventArgs">Information describing the ready event.</param>
        private void HandleErrorReady(object sender, EventArgs eventArgs)
        {
            PSDataCollectionPipelineReader<ErrorRecord, object> reader =
                sender as PSDataCollectionPipelineReader<ErrorRecord, object>;

            Collection<object> error = reader.NonBlockingRead();

            foreach (object errorData in error)
            {
                ErrorRecord er = errorData as ErrorRecord;
                if (er != null)
                {
                    OriginInfo originInfo = new OriginInfo(reader.ComputerName, reader.RunspaceId);

                    RemotingErrorRecord errorRecord =
                        new RemotingErrorRecord(er, originInfo);
                    errorRecord.PreserveInvocationInfoOnce = true;

                    // ISSUE: Add an Assert for ErrorRecord.
                    // Add to the PSRemotingChild jobs streams
                    this.WriteError(errorRecord);
                }
            }
        }

        /// <summary>
        /// When the client remote session reports a URI redirection, this method will report the
        /// message to the user as a Warning using Host method calls.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        protected void HandleURIDirectionReported(object sender, RemoteDataEventArgs<Uri> eventArgs)
        {
            string message = StringUtil.Format(RemotingErrorIdStrings.URIRedirectWarningToHost, eventArgs.Data.OriginalString);
            this.WriteWarning(message);
        }

        /// <summary>
        /// Handle method executor stream events.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="eventArgs">The event args.</param>
        private void HandleHostCalls(object sender, EventArgs eventArgs)
        {
            ObjectStream hostCallsStream = sender as ObjectStream;

            if (hostCallsStream != null)
            {
                Collection<object> hostCallMethodExecutors =
                    hostCallsStream.NonBlockingRead(hostCallsStream.Count);

                lock (SyncObject)
                {
                    foreach (ClientMethodExecutor hostCallMethodExecutor in hostCallMethodExecutors)
                    {
                        Results.Add(new PSStreamObject(PSStreamObjectType.MethodExecutor, hostCallMethodExecutor));

                        // if the call id of the underlying remote host call is not ServerDispatchTable.VoidCallId
                        // then the call is waiting on user input. Change state to Blocked
                        if (hostCallMethodExecutor.RemoteHostCall.CallId != ServerDispatchTable.VoidCallId)
                        {
                            SetJobState(JobState.Blocked, null);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Handle changes in pipeline states.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void HandlePipelineStateChanged(object sender, PipelineStateEventArgs e)
        {
            if ((Runspace != null) && (e.PipelineStateInfo.State != PipelineState.Running))
            {
                // since we got state changed event..we dont need to listen on
                // URI redirections anymore
                ((RemoteRunspace)Runspace).URIRedirectionReported -= HandleURIDirectionReported;
            }

            PipelineState state = e.PipelineStateInfo.State;
            switch (state)
            {
                case PipelineState.Running:
                    if (DisconnectedAndBlocked)
                    {
                        DisconnectedAndBlocked = false;
                        SetJobState(JobState.Blocked);
                    }
                    else
                    {
                        SetJobState(JobState.Running);
                    }

                    break;

                case PipelineState.Disconnected:
                    DisconnectedAndBlocked = (JobStateInfo.State == JobState.Blocked);
                    SetJobState(JobState.Disconnected);
                    break;
            }

            // Question: Why is the DoFinish() call on terminal pipeline state deleted
            // Answer: Because in the runspace case, when pipeline reaches a terminal state
            // OperationComplete will be raised and DoFinish() is called on OperationComplete
            // In the computer name case, once pipeline reaches a terminal state, runspace is
            // closed which will result in an OperationComplete event
        }

        /// <summary>
        /// Handle a throttle complete event.
        /// </summary>
        /// <param name="sender">Sender of this event.</param>
        /// <param name="eventArgs">Not used in this method.</param>
        private void HandleThrottleComplete(object sender, EventArgs eventArgs)
        {
            // Question: Why do we register for HandleThrottleComplete when we have already
            // registered for PipelineStateChangedEvent?
            // Answer: Because ThrottleManager at a given time can have some pipelines which are
            // still not started. If TM.Stop() is called, then it simply discards those pipelines and
            // PipelineStateChangedEvent is not called for them. For such jobs, we depend on
            // HandleThrottleComplete to mark the finish of job.

            // Question: So it is possible in some cases DoFinish can be called twice.
            // Answer: Yes: One from PipelineStateChangedEvent and Another here. But
            // DoFinish has logic to check if it has been already called and second call
            // becomes noOp.
            DoFinish();
        }

        /// <summary>
        /// Handle the operation complete event.
        /// </summary>
        /// <param name="sender">Sender of this event.</param>
        /// <param name="stateEventArgs">Operation complete event args.</param>
        protected virtual void HandleOperationComplete(object sender, OperationStateEventArgs stateEventArgs)
        {
            // Question:Why are we registering for OperationComplete if we already
            // registering for StateChangedEvent and ThrottleComplete event
            // Answer:Because in case of computer, if Runspace.Open it self fails,
            // no pipeline is created and no pipeline state changed event is raised.
            // We can wait for throttle complete, but it is raised only when all the
            // operations are completed and this means that status of job is not updated
            // until Operation Complete.
            ExecutionCmdletHelper helper = sender as ExecutionCmdletHelper;
            Dbg.Assert(helper != null, "Sender of OperationComplete has to be ExecutionCmdletHelper");

            DeterminedAndSetJobState(helper);
        }

        private bool _doFinishCalled = false;

        /// <summary>
        /// This method marks the completion state for Job. Also if job failed, it processes the
        /// reason of failure.
        /// </summary>
        protected virtual void DoFinish()
        {
            if (_doFinishCalled)
                return;

            lock (SyncObject)
            {
                if (_doFinishCalled)
                    return;

                _doFinishCalled = true;
            }

            DeterminedAndSetJobState(Helper);

            DoCleanupOnFinished();
        }

        /// <summary>
        /// This is the pretty formated error record associated with the reason of failure.
        /// </summary>
        private ErrorRecord _failureErrorRecord;

        /// <summary>
        /// This is the pretty formated error record associated with the reason of failure.
        /// This is set if Job state is Failed and Reason has a exception.
        /// </summary>
        internal ErrorRecord FailureErrorRecord
        {
            get
            {
                return _failureErrorRecord;
            }
        }

        /// <summary>
        /// Process the exceptions to decide reason for job failure.
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="failureException"></param>
        /// <param name="failureErrorRecord"></param>
        protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception failureException,
                            out ErrorRecord failureErrorRecord)
        {
            //      There are three errors possible
            //      1. The remote runspace is in (or went into) a
            //         broken state. This information is available
            //         in the runspace state information
            //      2. The remote pipeline failed because of an
            //         exception. This information is available
            //         in the pipeline state information
            //      3. Runspace.OpenAsync or Pipeline.InvokeAsync threw exception
            //         They are in Helper.InternalException

            Dbg.Assert(helper != null, "helper is null");

            RemotePipeline pipeline = helper.Pipeline as RemotePipeline;
            Dbg.Assert(pipeline != null, "pipeline is null");

            RemoteRunspace runspace = pipeline.GetRunspace() as RemoteRunspace;
            Dbg.Assert(runspace != null, "runspace is null");

            failureException = null;
            failureErrorRecord = null;

            if (helper.InternalException != null)
            {
                string errorId = "RemotePipelineExecutionFailed";
                failureException = helper.InternalException;
                if ((failureException is InvalidRunspaceStateException) || (failureException is InvalidRunspacePoolStateException))
                {
                    errorId = "InvalidSessionState";
                    if (!string.IsNullOrEmpty(failureException.Source))
                    {
                        errorId = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{errorId},{failureException.Source}");
                    }
                }

                failureErrorRecord = new ErrorRecord(helper.InternalException,
                       errorId, ErrorCategory.OperationStopped,
                            helper);
            }
            // there is a failure reason available in the runspace
            else if ((runspace.RunspaceStateInfo.State == RunspaceState.Broken) ||
                     (runspace.RunspaceStateInfo.Reason != null))
            {
                failureException = runspace.RunspaceStateInfo.Reason;
                object targetObject = runspace.ConnectionInfo.ComputerName;

                string errorDetails = null;

                // set the transport message in the error detail so that
                // the user can directly get to see the message without
                // having to mine through the error record details
                PSRemotingTransportException transException =
                            failureException as PSRemotingTransportException;

                string fullyQualifiedErrorId =
                    System.Management.Automation.Remoting.Client.WSManTransportManagerUtils.GetFQEIDFromTransportError(
                        (transException != null) ? transException.ErrorCode : 0,
                        "PSSessionStateBroken");

                if (transException != null)
                {
                    errorDetails = "[" + runspace.ConnectionInfo.ComputerName + "] ";

                    if (transException.ErrorCode ==
                        Remoting.Client.WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED)
                    {
                        // Handling a special case for redirection..we should talk about
                        // AllowRedirection parameter and WSManMaxRedirectionCount preference
                        // variables
                        string message = PSRemotingErrorInvariants.FormatResourceString(
                            RemotingErrorIdStrings.URIRedirectionReported,
                            transException.Message,
                            "MaximumConnectionRedirectionCount",
                            Microsoft.PowerShell.Commands.PSRemotingBaseCmdlet.DEFAULT_SESSION_OPTION,
                            "AllowRedirection");

                        errorDetails += message;
                    }
                    else if (!string.IsNullOrEmpty(transException.Message))
                    {
                        errorDetails += transException.Message;
                    }
                    else if (!string.IsNullOrEmpty(transException.TransportMessage))
                    {
                        errorDetails += transException.TransportMessage;
                    }
                }

                failureException ??= new RuntimeException(
                    PSRemotingErrorInvariants.FormatResourceString(
                        RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState,
                        runspace.RunspaceStateInfo.State));

                failureErrorRecord = new ErrorRecord(failureException, targetObject,
                                fullyQualifiedErrorId, ErrorCategory.OpenError,
                                null, null, null, null, null, errorDetails, null);
            }
            else if (pipeline.PipelineStateInfo.State == PipelineState.Failed
                || (pipeline.PipelineStateInfo.State == PipelineState.Stopped
                    && pipeline.PipelineStateInfo.Reason != null
                    && pipeline.PipelineStateInfo.Reason is not PipelineStoppedException))
            {
                // Pipeline stopped state is also an error condition if the associated exception is not 'PipelineStoppedException'.
                object targetObject = runspace.ConnectionInfo.ComputerName;
                failureException = pipeline.PipelineStateInfo.Reason;
                if (failureException != null)
                {
                    RemoteException rException = failureException as RemoteException;

                    ErrorRecord errorRecord = null;
                    if (rException != null)
                    {
                        errorRecord = rException.ErrorRecord;

                        // A RemoteException will hide a PipelineStoppedException, which should be ignored.
                        if (errorRecord != null &&
                            errorRecord.FullyQualifiedErrorId.Equals("PipelineStopped", StringComparison.OrdinalIgnoreCase))
                        {
                            // PipelineStoppedException should not be reported as error.
                            failureException = null;
                            return;
                        }
                    }
                    else
                    {
                        // at this point, there may be no failure reason available in
                        // the runspace because the remoting protocol
                        // layer may not have yet assigned it to the runspace
                        // in such a case, the remoting protocol layer would have
                        // assigned an exception in the client end to the pipeline
                        // create an error record from it and write it out
                        errorRecord = new ErrorRecord(pipeline.PipelineStateInfo.Reason,
                                                        "JobFailure", ErrorCategory.OperationStopped,
                                                            targetObject);
                    }

                    string computerName = ((RemoteRunspace)pipeline.GetRunspace()).ConnectionInfo.ComputerName;
                    Guid runspaceId = pipeline.GetRunspace().InstanceId;

                    OriginInfo originInfo = new OriginInfo(computerName, runspaceId);

                    failureErrorRecord = new RemotingErrorRecord(errorRecord, originInfo);
                }
            }
        }

        /// <summary>
        /// Release all the resources.
        /// </summary>
        /// <param name="disposing">
        /// if true, release all the managed objects.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_isDisposed)
                {
                    return;
                }

                lock (SyncObject)
                {
                    if (_isDisposed)
                    {
                        return;
                    }

                    _isDisposed = true;
                }

                try
                {
                    DoCleanupOnFinished();
                }
                finally
                {
                    base.Dispose(disposing);
                }
            }
        }

        private bool _isDisposed = false;

        private bool _cleanupDone = false;

        /// <summary>
        /// Cleanup after state changes to finished.
        /// </summary>
        protected virtual void DoCleanupOnFinished()
        {
            bool doCleanup = false;
            if (!_cleanupDone)
            {
                lock (SyncObject)
                {
                    if (!_cleanupDone)
                    {
                        _cleanupDone = true;
                        doCleanup = true;
                    }
                }
            }

            if (!doCleanup) return;

            StopAggregateResultsFromHelper(Helper);
            Runspace.AvailabilityChanged -= HandleRunspaceAvailabilityChanged;
            IThrottleOperation operation = Helper as IThrottleOperation;
            operation.OperationComplete -= HandleOperationComplete;
            UnregisterThrottleComplete(_throttleManager);
            _throttleManager = null;
        }

        /// <summary>
        /// Aggregates results from the pipeline associated
        /// with the specified helper.
        /// </summary>
        /// <param name="helper">helper whose pipeline results
        /// need to be aggregated</param>
        protected void AggregateResultsFromHelper(ExecutionCmdletHelper helper)
        {
            // Get the pipeline associated with this helper and register for appropriate events
            Pipeline pipeline = helper.Pipeline;
            pipeline.Output.DataReady += HandleOutputReady;
            pipeline.Error.DataReady += HandleErrorReady;
            pipeline.StateChanged += HandlePipelineStateChanged;

            // Register handler for method executor object stream.
            Dbg.Assert(pipeline is RemotePipeline, "pipeline is RemotePipeline");
            RemotePipeline remotePipeline = pipeline as RemotePipeline;
            remotePipeline.MethodExecutorStream.DataReady += HandleHostCalls;
            remotePipeline.PowerShell.Streams.Progress.DataAdded += HandleProgressAdded;
            remotePipeline.PowerShell.Streams.Warning.DataAdded += HandleWarningAdded;
            remotePipeline.PowerShell.Streams.Verbose.DataAdded += HandleVerboseAdded;
            remotePipeline.PowerShell.Streams.Debug.DataAdded += HandleDebugAdded;
            remotePipeline.PowerShell.Streams.Information.DataAdded += HandleInformationAdded;

            // Enable method executor stream so that host methods are queued up
            // on it instead of being executed asynchronously when they arrive.
            remotePipeline.IsMethodExecutorStreamEnabled = true;

            IThrottleOperation operation = helper as IThrottleOperation;
            operation.OperationComplete += HandleOperationComplete;
        }

        /// <summary>
        /// If the pipeline is not null, returns the pipeline's PowerShell
        /// If it is null, then returns the PowerShell with the specified
        /// instance Id.
        /// </summary>
        /// <param name="pipeline">Remote pipeline.</param>
        /// <param name="instanceId">Instance as described in event args.</param>
        /// <returns>PowerShell instance.</returns>
        private PowerShell GetPipelinePowerShell(RemotePipeline pipeline, Guid instanceId)
        {
            if (pipeline != null)
            {
                return pipeline.PowerShell;
            }

            return GetPowerShell(instanceId);
        }

        /// <summary>
        /// When a debug message is raised in the underlying PowerShell
        /// add it to the jobs debug stream.
        /// </summary>
        /// <param name="sender">Unused.</param>
        /// <param name="eventArgs">Arguments describing this event.</param>
        private void HandleDebugAdded(object sender, DataAddedEventArgs eventArgs)
        {
            int index = eventArgs.Index;
            PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId);

            if (powershell != null)
            {
                this.Debug.Add(powershell.Streams.Debug[index]);
            }
        }

        /// <summary>
        /// When a verbose message is raised in the underlying PowerShell
        /// add it to the jobs verbose stream.
        /// </summary>
        /// <param name="sender">Unused.</param>
        /// <param name="eventArgs">Arguments describing this event.</param>
        private void HandleVerboseAdded(object sender, DataAddedEventArgs eventArgs)
        {
            int index = eventArgs.Index;
            PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId);

            if (powershell != null)
            {
                this.Verbose.Add(powershell.Streams.Verbose[index]);
            }
        }

        /// <summary>
        /// When a warning message is raised in the underlying PowerShell
        /// add it to the jobs warning stream.
        /// </summary>
        /// <param name="sender">Unused.</param>
        /// <param name="eventArgs">Arguments describing this event.</param>
        private void HandleWarningAdded(object sender, DataAddedEventArgs eventArgs)
        {
            int index = eventArgs.Index;
            PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId);

            if (powershell != null)
            {
                WarningRecord warningRecord = powershell.Streams.Warning[index];
                this.Warning.Add(warningRecord);
                this.Results.Add(new PSStreamObject(PSStreamObjectType.WarningRecord, warningRecord));
            }
        }

        /// <summary>
        /// When a progress message is raised in the underlying PowerShell
        /// add it to the jobs progress tream.
        /// </summary>
        /// <param name="sender">Unused.</param>
        /// <param name="eventArgs">Arguments describing this event.</param>
        private void HandleProgressAdded(object sender, DataAddedEventArgs eventArgs)
        {
            int index = eventArgs.Index;
            PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId);

            if (powershell != null)
            {
                this.Progress.Add(powershell.Streams.Progress[index]);
            }
        }

        /// <summary>
        /// When a Information message is raised in the underlying PowerShell
        /// add it to the jobs Information stream.
        /// </summary>
        /// <param name="sender">Unused.</param>
        /// <param name="eventArgs">Arguments describing this event.</param>
        private void HandleInformationAdded(object sender, DataAddedEventArgs eventArgs)
        {
            int index = eventArgs.Index;
            PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId);

            if (powershell != null)
            {
                InformationRecord informationRecord = powershell.Streams.Information[index];
                this.Information.Add(informationRecord);

                // Host output is handled by the hosting APIs directly, so we need to add a tag that it was
                // forwarded so that it is not written twice.
                //  For all other Information records, forward them.
                if (informationRecord.Tags.Contains("PSHOST"))
                {
                    informationRecord.Tags.Add("FORWARDED");
                }

                this.Results.Add(new PSStreamObject(PSStreamObjectType.Information, informationRecord));
            }
        }

        /// <summary>
        /// Stops collecting results from the pipeline associated with
        /// the specified helper.
        /// </summary>
        /// <param name="helper">helper class whose pipeline results
        /// aggregation has to be stopped</param>
        protected void StopAggregateResultsFromHelper(ExecutionCmdletHelper helper)
        {
            // Get the pipeline associated with this helper and register for appropriate events
            RemoveAggreateCallbacksFromHelper(helper);

            Pipeline pipeline = helper.Pipeline;
            pipeline.Dispose();
            pipeline = null;
        }

        /// <summary>
        /// Removes aggregate callbacks from pipeline so that a new job object can
        /// be created and can add its own callbacks.
        /// This is to support Invoke-Command auto-disconnect where a new PSRemoting
        /// job must be created to pass back to user for connection.
        /// </summary>
        /// <param name="helper">Helper class.</param>
        protected void RemoveAggreateCallbacksFromHelper(ExecutionCmdletHelper helper)
        {
            // Remove old data output callbacks from pipeline so new callbacks can be added.
            Pipeline pipeline = helper.Pipeline;
            pipeline.Output.DataReady -= HandleOutputReady;
            pipeline.Error.DataReady -= HandleErrorReady;
            pipeline.StateChanged -= HandlePipelineStateChanged;

            // Remove old data aggregation and host calls.
            Dbg.Assert(pipeline is RemotePipeline, "pipeline is RemotePipeline");
            RemotePipeline remotePipeline = pipeline as RemotePipeline;
            remotePipeline.MethodExecutorStream.DataReady -= HandleHostCalls;
            if (remotePipeline.PowerShell != null)
            {
                remotePipeline.PowerShell.Streams.Progress.DataAdded -= HandleProgressAdded;
                remotePipeline.PowerShell.Streams.Warning.DataAdded -= HandleWarningAdded;
                remotePipeline.PowerShell.Streams.Verbose.DataAdded -= HandleVerboseAdded;
                remotePipeline.PowerShell.Streams.Debug.DataAdded -= HandleDebugAdded;
                remotePipeline.PowerShell.Streams.Information.DataAdded -= HandleInformationAdded;
                remotePipeline.IsMethodExecutorStreamEnabled = false;
            }
        }

        /// <summary>
        /// Register for throttle complete from the specified
        /// throttlemanager.
        /// </summary>
        /// <param name="throttleManager"></param>
        protected void RegisterThrottleComplete(ThrottleManager throttleManager)
        {
            throttleManager.ThrottleComplete += HandleThrottleComplete;
        }

        /// <summary>
        /// Unregister for throttle complete from the specified
        /// throttle manager.
        /// </summary>
        /// <param name="throttleManager"></param>
        protected void UnregisterThrottleComplete(ThrottleManager throttleManager)
        {
            throttleManager.ThrottleComplete -= HandleThrottleComplete;
        }

        /// <summary>
        /// Determine the current state of the job based on the underlying
        /// pipeline state and set the state accordingly.
        /// </summary>
        /// <param name="helper"></param>
        protected void DeterminedAndSetJobState(ExecutionCmdletHelper helper)
        {
            Exception failureException;
            // Process the reason in case of failure.
            ProcessJobFailure(helper, out failureException, out _failureErrorRecord);

            if (failureException != null)
            {
                SetJobState(JobState.Failed, failureException);
            }
            else
            {
                // Get the state of the pipeline
                PipelineState state = helper.Pipeline.PipelineStateInfo.State;
                if (state == PipelineState.NotStarted)
                {
                    // This is a case in which pipeline was not started and TM.Stop was
                    // called. See comment in HandleThrottleComplete
                    SetJobState(JobState.Stopped);
                }
                else if (state == PipelineState.Completed)
                {
                    SetJobState(JobState.Completed);
                }
                else
                {
                    SetJobState(JobState.Stopped);
                }
            }
        }

        /// <summary>
        /// Set the state of the current job from blocked to
        /// running and raise an event indicating to this
        /// parent job that this job is unblocked.
        /// </summary>
        internal void UnblockJob()
        {
            Dbg.Assert(JobStateInfo.State == JobState.Blocked,
                "Current state of job must be blocked before it can be unblocked");

            SetJobState(JobState.Running, null);

            Dbg.Assert(JobUnblocked != null, "Parent job must register for JobUnblocked event from all child jobs");
            JobUnblocked.SafeInvoke(this, EventArgs.Empty);
        }

        /// <summary>
        /// Returns the PowerShell for the specified instance id.
        /// </summary>
        /// <param name="instanceId">Instance id of powershell.</param>
        /// <returns>Powershell instance.</returns>
        internal virtual PowerShell GetPowerShell(Guid instanceId)
        {
            // this should be called only in the derived implementation
            throw PSTraceSource.NewInvalidOperationException();
        }

        /// <summary>
        /// Returns the PowerShell object associated with this remote child job.
        /// </summary>
        /// <returns>PowerShell object.</returns>
        internal PowerShell GetPowerShell()
        {
            PowerShell ps = null;
            if (_remotePipeline != null)
            {
                ps = _remotePipeline.PowerShell;
            }

            return ps;
        }

        /// <summary>
        /// Monitor runspace availability and if it goes to RemoteDebug then set
        /// job state to Debug.  Set back to Running when availability goes back to
        /// Busy (indicating the script/command is running again).
        /// </summary>
        /// <param name="sender">Runspace.</param>
        /// <param name="e">RunspaceAvailabilityEventArgs.</param>
        private void HandleRunspaceAvailabilityChanged(object sender, RunspaceAvailabilityEventArgs e)
        {
            RunspaceAvailability prevAvailability = _prevRunspaceAvailability;
            _prevRunspaceAvailability = e.RunspaceAvailability;

            if (e.RunspaceAvailability == RunspaceAvailability.RemoteDebug)
            {
                SetJobState(JobState.AtBreakpoint);
            }
            else if ((prevAvailability == RunspaceAvailability.RemoteDebug) &&
                     (e.RunspaceAvailability == RunspaceAvailability.Busy))
            {
                SetJobState(JobState.Running);
            }
        }

        /// <summary>
        /// Event raised by this job to indicate to its parent that
        /// its now unblocked by the user.
        /// </summary>
        internal event EventHandler JobUnblocked;

        #endregion Private Methods

        #region Private Members

        // helper associated with this job object
        private readonly RemotePipeline _remotePipeline = null;

        // object used for synchronization
        protected object SyncObject = new object();

        private ThrottleManager _throttleManager;
        private bool _stopIsCalled = false;

        private volatile Debugger _jobDebugger;

        private bool _isAsync = true;

        private RunspaceAvailability _prevRunspaceAvailability = RunspaceAvailability.None;

        #endregion Private Members
    }

    /// <summary>
    /// This is a debugger wrapper class used to allow debugging of
    /// remoting jobs that implement the IJobDebugger interface.
    /// </summary>
    internal sealed class RemotingJobDebugger : Debugger
    {
        #region Members

        private readonly Debugger _wrappedDebugger;
        private readonly Runspace _runspace;
        private readonly string _jobName;

        #endregion

        #region Constructor

        private RemotingJobDebugger() { }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="debugger">Debugger to wrap.</param>
        /// <param name="runspace">Remote runspace.</param>
        /// <param name="jobName">Name of associated job.</param>
        public RemotingJobDebugger(
            Debugger debugger,
            Runspace runspace,
            string jobName)
        {
            if (debugger == null)
            {
                throw new PSArgumentNullException(nameof(debugger));
            }

            if (runspace == null)
            {
                throw new PSArgumentNullException(nameof(runspace));
            }

            _wrappedDebugger = debugger;
            _runspace = runspace;
            _jobName = jobName ?? string.Empty;

            // Create handlers for wrapped debugger events.
            _wrappedDebugger.BreakpointUpdated += HandleBreakpointUpdated;
            _wrappedDebugger.DebuggerStop += HandleDebuggerStop;
        }

        #endregion

        #region Debugger overrides

        /// <summary>
        /// Evaluates provided command either as a debugger specific command
        /// or a PowerShell command.
        /// </summary>
        /// <param name="command">PowerShell command.</param>
        /// <param name="output">Output.</param>
        /// <returns>DebuggerCommandResults.</returns>
        public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataCollection<PSObject> output)
        {
            // Special handling for the prompt command.
            if (command.Commands[0].CommandText.Trim().Equals("prompt", StringComparison.OrdinalIgnoreCase))
            {
                return HandlePromptCommand(output);
            }

            return _wrappedDebugger.ProcessCommand(command, output);
        }

        /// <summary>
        /// Adds the provided set of breakpoints to the debugger.
        /// </summary>
        /// <param name="breakpoints">Breakpoints to set.</param>
        /// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
        public override void SetBreakpoints(IEnumerable<Breakpoint> breakpoints, int? runspaceId) =>
            _wrappedDebugger.SetBreakpoints(breakpoints, runspaceId);

        /// <summary>
        /// Get a breakpoint by id, primarily for Enable/Disable/Remove-PSBreakpoint cmdlets.
        /// </summary>
        /// <param name="id">Id of the breakpoint you want.</param>
        /// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
        /// <returns>A breakpoint with the specified id.</returns>
        public override Breakpoint GetBreakpoint(int id, int? runspaceId) =>
            _wrappedDebugger.GetBreakpoint(id, runspaceId);

        /// <summary>
        /// Returns breakpoints on a runspace.
        /// </summary>
        /// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
        /// <returns>A list of breakpoints in a runspace.</returns>
        public override List<Breakpoint> GetBreakpoints(int? runspaceId) =>
            _wrappedDebugger.GetBreakpoints(runspaceId);

        /// <summary>
        /// Sets a command breakpoint in the debugger.
        /// </summary>
        /// <param name="command">The name of the command that will trigger the breakpoint. This value may not be null.</param>
        /// <param name="action">The action to take when the breakpoint is hit. If null, PowerShell will break into the debugger when the breakpoint is hit.</param>
        /// <param name="path">The path to the script file where the breakpoint may be hit. If null, the breakpoint may be hit anywhere the command is invoked.</param>
        /// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
        /// <returns>The command breakpoint that was set.</returns>
        public override CommandBreakpoint SetCommandBreakpoint(string command, ScriptBlock action, string path, int? runspaceId) =>
            _wrappedDebugger.SetCommandBreakpoint(command, action, path, runspaceId);

        /// <summary>
        /// Sets a line breakpoint in the debugger.
        /// </summary>
        /// <param name="path">The path to the script file where the breakpoint may be hit. This value may not be null.</param>
        /// <param name="line">The line in the script file where the breakpoint may be hit. This value must be greater than or equal to 1.</param>
        /// <param name="column">The column in the script file where the breakpoint may be hit. If 0, the breakpoint will trigger on any statement on the line.</param>
        /// <param name="action">The action to take when the breakpoint is hit. If null, PowerShell will break into the debugger when the breakpoint is hit.</param>
        /// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
        /// <returns>The line breakpoint that was set.</returns>
        public override LineBreakpoint SetLineBreakpoint(string path, int line, int column, ScriptBlock action, int? runspaceId) =>
            _wrappedDebugger.SetLineBreakpoint(path, line, column, action, runspaceId);

        /// <summary>
        /// Sets a variable breakpoint in the debugger.
        /// </summary>
        /// <param name="variableName">The name of the variable that will trigger the breakpoint. This value may not be null.</param>
        /// <param name="accessMode">The variable access mode that will trigger the breakpoint.</param>
        /// <param name="action">The action to take when the breakpoint is hit. If null, PowerShell will break into the debugger when the breakpoint is hit.</param>
        /// <param name="path">The path to the script file where the breakpoint may be hit. If null, the breakpoint may be hit anywhere the variable is accessed using the specified access mode.</param>
        /// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
        /// <returns>The variable breakpoint that was set.</returns>
        public override VariableBreakpoint SetVariableBreakpoint(string variableName, VariableAccessMode accessMode, ScriptBlock action, string path, int? runspaceId) =>
            _wrappedDebugger.SetVariableBreakpoint(variableName, accessMode, action, path, runspaceId);

        /// <summary>
        /// Removes a breakpoint from the debugger.
        /// </summary>
        /// <param name="breakpoint">The breakpoint to remove from the debugger. This value may not be null.</param>
        /// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
        /// <returns>True if the breakpoint was removed from the debugger; false otherwise.</returns>
        public override bool RemoveBreakpoint(Breakpoint breakpoint, int? runspaceId) =>
            _wrappedDebugger.RemoveBreakpoint(breakpoint, runspaceId);

        /// <summary>
        /// Enables a breakpoint in the debugger.
        /// </summary>
        /// <param name="breakpoint">The breakpoint to enable in the debugger. This value may not be null.</param>
        /// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
        /// <returns>The updated breakpoint if it was found; null if the breakpoint was not found in the debugger.</returns>
        public override Breakpoint EnableBreakpoint(Breakpoint breakpoint, int? runspaceId) =>
            _wrappedDebugger.EnableBreakpoint(breakpoint, runspaceId);

        /// <summary>
        /// Disables a breakpoint in the debugger.
        /// </summary>
        /// <param name="breakpoint">The breakpoint to enable in the debugger. This value may not be null.</param>
        /// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
        /// <returns>The updated breakpoint if it was found; null if the breakpoint was not found in the debugger.</returns>
        public override Breakpoint DisableBreakpoint(Breakpoint breakpoint, int? runspaceId) =>
            _wrappedDebugger.DisableBreakpoint(breakpoint, runspaceId);

        /// <summary>
        /// Sets the debugger resume action.
        /// </summary>
        /// <param name="resumeAction">DebuggerResumeAction.</param>
        public override void SetDebuggerAction(DebuggerResumeAction resumeAction)
        {
            _wrappedDebugger.SetDebuggerAction(resumeAction);
        }

        /// <summary>
        /// Stops a running command.
        /// </summary>
        public override void StopProcessCommand()
        {
            _wrappedDebugger.StopProcessCommand();
        }

        /// <summary>
        /// Returns current debugger stop event arguments if debugger is in
        /// debug stop state.  Otherwise returns null.
        /// </summary>
        /// <returns>DebuggerStopEventArgs.</returns>
        public override DebuggerStopEventArgs GetDebuggerStopArgs()
        {
            return _wrappedDebugger.GetDebuggerStopArgs();
        }

        /// <summary>
        /// Sets the parent debugger, breakpoints, and other debugging context information.
        /// </summary>
        /// <param name="parent">Parent debugger.</param>
        /// <param name="breakPoints">List of breakpoints.</param>
        /// <param name="startAction">Debugger mode.</param>
        /// <param name="host">PowerShell host.</param>
        /// <param name="path">Current path.</param>
        public override void SetParent(
            Debugger parent,
            IEnumerable<Breakpoint> breakPoints,
            DebuggerResumeAction? startAction,
            PSHost host,
            PathInfo path)
        {
            // For now always enable step mode debugging.
            SetDebuggerStepMode(true);
        }

        /// <summary>
        /// Sets the debugger mode.
        /// </summary>
        public override void SetDebugMode(DebugModes mode)
        {
            _wrappedDebugger.SetDebugMode(mode);

            base.SetDebugMode(mode);
        }

        /// <summary>
        /// Returns IEnumerable of CallStackFrame objects.
        /// </summary>
        /// <returns></returns>
        public override IEnumerable<CallStackFrame> GetCallStack()
        {
            return _wrappedDebugger.GetCallStack();
        }

        /// <summary>
        /// Sets debugger stepping mode.
        /// </summary>
        /// <param name="enabled">True if stepping is to be enabled.</param>
        public override void SetDebuggerStepMode(bool enabled)
        {
            _wrappedDebugger.SetDebuggerStepMode(enabled);
        }

        /// <summary>
        /// CheckStateAndRaiseStopEvent.
        /// </summary>
        internal void CheckStateAndRaiseStopEvent()
        {
            RemoteDebugger remoteDebugger = _wrappedDebugger as RemoteDebugger;
            remoteDebugger?.CheckStateAndRaiseStopEvent();
        }

        /// <summary>
        /// True when debugger is stopped at a breakpoint.
        /// </summary>
        public override bool InBreakpoint
        {
            get { return _wrappedDebugger.InBreakpoint; }
        }

        #endregion

        #region Private methods

        private void HandleDebuggerStop(object sender, DebuggerStopEventArgs e)
        {
            Pipeline remoteRunningCmd = null;
            try
            {
                // For remote debugging drain/block output channel.
                remoteRunningCmd = DrainAndBlockRemoteOutput();

                this.RaiseDebuggerStopEvent(e);
            }
            finally
            {
                RestoreRemoteOutput(remoteRunningCmd);
            }
        }

        private Pipeline DrainAndBlockRemoteOutput()
        {
            // We only do this for remote runspaces.
            if (_runspace is not RemoteRunspace) { return null; }

            Pipeline runningCmd = _runspace.GetCurrentlyRunningPipeline();
            if (runningCmd != null)
            {
                runningCmd.DrainIncomingData();
                runningCmd.SuspendIncomingData();

                return runningCmd;
            }

            return null;
        }

        private static void RestoreRemoteOutput(Pipeline runningCmd) => runningCmd?.ResumeIncomingData();

        private void HandleBreakpointUpdated(object sender, BreakpointUpdatedEventArgs e)
        {
            this.RaiseBreakpointUpdatedEvent(e);
        }

        private DebuggerCommandResults HandlePromptCommand(PSDataCollection<PSObject> output)
        {
            // Nested debugged runspace prompt should look like:
            // [DBG]: [JobName]: PS C:\>>
            string promptScript = "'[DBG]: '" + " + " + "'[" + CodeGeneration.EscapeSingleQuotedStringContent(_jobName) + "]: '" + " + " + @"""PS $($executionContext.SessionState.Path.CurrentLocation)>> """;
            PSCommand promptCommand = new PSCommand();
            promptCommand.AddScript(promptScript);
            _wrappedDebugger.ProcessCommand(promptCommand, output);

            return new DebuggerCommandResults(null, true);
        }

        #endregion
    }

    /// <summary>
    /// This job is used for running as a job the results from multiple
    /// pipelines. This is used in synchronous Invoke-Expression execution.
    /// </summary>
    /// <remarks>
    /// TODO: I am not sure whether to change this internal to just InvokeExpressionSyncJob.
    /// </remarks>
    /// <remarks>
    /// Not removing the prefix "PS" as this signifies powershell specific remoting job
    /// </remarks>
    internal class PSInvokeExpressionSyncJob : PSRemotingChildJob
    {
        #region Private Members

        private readonly List<ExecutionCmdletHelper> _helpers = new List<ExecutionCmdletHelper>();
        private readonly ThrottleManager _throttleManager;
        private readonly Dictionary<Guid, PowerShell> _powershells = new Dictionary<Guid, PowerShell>();

        private int _pipelineFinishedCount;
        private int _pipelineDisconnectedCount;

        #endregion Private Members

        #region Constructors

        /// <summary>
        /// Construct an invoke-expression sync job.
        /// </summary>
        /// <param name="operations">List of operations to use.</param>
        /// <param name="throttleManager">throttle manager to use for
        /// this job</param>
        internal PSInvokeExpressionSyncJob(List<IThrottleOperation> operations, ThrottleManager throttleManager)
        {
            UsesResultsCollection = true;
            Results.AddRef();

            _throttleManager = throttleManager;
            RegisterThrottleComplete(_throttleManager);

            foreach (IThrottleOperation operation in operations)
            {
                ExecutionCmdletHelper helper = operation as ExecutionCmdletHelper;

                RemoteRunspace remoteRS = helper.Pipeline.Runspace as RemoteRunspace;
                if (remoteRS != null)
                {
                    remoteRS.StateChanged += HandleRunspaceStateChanged;

                    if (remoteRS.RunspaceStateInfo.State == RunspaceState.BeforeOpen)
                    {
                        remoteRS.URIRedirectionReported += HandleURIDirectionReported;
                    }
                }

                _helpers.Add(helper);
                AggregateResultsFromHelper(helper);

                Dbg.Assert(helper.Pipeline is RemotePipeline, "Only remote pipeline can be used in InvokeExpressionSyncJob");
                RemotePipeline pipeline = helper.Pipeline as RemotePipeline;
                _powershells.Add(pipeline.PowerShell.InstanceId, pipeline.PowerShell);
            }
        }

        #endregion Constructors

        #region Protected Methods

        private bool _cleanupDone = false;

        /// <summary>
        /// Clean up once job is finished.
        /// </summary>
        protected override void DoCleanupOnFinished()
        {
            bool doCleanup = false;
            if (!_cleanupDone)
            {
                lock (SyncObject)
                {
                    if (!_cleanupDone)
                    {
                        _cleanupDone = true;
                        doCleanup = true;
                    }
                }
            }

            if (!doCleanup) return;

            foreach (ExecutionCmdletHelper helper in _helpers)
            {
                // cleanup remote runspace related handlers
                RemoteRunspace remoteRS = helper.PipelineRunspace as RemoteRunspace;
                if (remoteRS != null)
                {
                    remoteRS.StateChanged -= HandleRunspaceStateChanged;
                    remoteRS.URIRedirectionReported -= HandleURIDirectionReported;
                }

                StopAggregateResultsFromHelper(helper);
            }

            UnregisterThrottleComplete(_throttleManager);
            // throttleManager = null;

            Results.DecrementRef();
        }

        /// <summary>
        /// Release all resources.
        /// </summary>
        /// <param name="disposing">True if called by Dispose().</param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }

        /// <summary>
        /// Handles operation complete from the operations. Adds an error record
        /// to results whenever an error is encountered.
        /// </summary>
        /// <param name="sender">Sender of this event.</param>
        /// <param name="stateEventArgs">Arguments describing this event, unused.</param>
        protected override void HandleOperationComplete(object sender, OperationStateEventArgs stateEventArgs)
        {
            ExecutionCmdletHelper helper = sender as ExecutionCmdletHelper;
            Dbg.Assert(helper != null, "Sender of OperationComplete has to be ExecutionCmdletHelper");

            Exception failureException;
            // Process the reason in case of failure.
            ErrorRecord failureErrorRecord;

            ProcessJobFailure(helper, out failureException, out failureErrorRecord);

            if (failureErrorRecord != null)
            {
                this.WriteError(failureErrorRecord);
            }
        }

        /// <summary>
        /// Handle changes in pipeline states.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void HandlePipelineStateChanged(object sender, PipelineStateEventArgs e)
        {
            PipelineState state = e.PipelineStateInfo.State;
            switch (state)
            {
                case PipelineState.Running:
                    SetJobState(JobState.Running);
                    break;

                case PipelineState.Completed:
                case PipelineState.Failed:
                case PipelineState.Stopped:
                case PipelineState.Disconnected:
                    CheckForAndSetDisconnectedState(state);
                    break;
            }
        }

        /// <summary>
        /// Checks for a condition where all pipelines are either finished
        /// or disconnected and at least one pipeline is disconnected.
        /// In this case the Job state is set to Disconnected.
        /// </summary>
        private void CheckForAndSetDisconnectedState(PipelineState pipelineState)
        {
            bool setJobStateToDisconnected;
            lock (SyncObject)
            {
                if (IsTerminalState())
                {
                    return;
                }

                switch (pipelineState)
                {
                    case PipelineState.Completed:
                    case PipelineState.Failed:
                    case PipelineState.Stopped:
                        _pipelineFinishedCount += 1;
                        break;

                    case PipelineState.Disconnected:
                        _pipelineDisconnectedCount += 1;
                        break;
                }

                setJobStateToDisconnected = ((_pipelineFinishedCount + _pipelineDisconnectedCount) == _helpers.Count &&
                                              _pipelineDisconnectedCount > 0);
            }

            if (setJobStateToDisconnected)
            {
                // Job cannot finish with pipelines in disconnected state.
                // Set Job state to Disconnected.
                SetJobState(JobState.Disconnected);
            }
        }

        /// <summary>
        /// Used to stop all operations.
        /// </summary>
        public override void StopJob()
        {
            _throttleManager.StopAllOperations();
        }

        private bool _doFinishCalled = false;

        /// <summary>
        /// This method marks the completion state for Job. Also if job failed, it processes the
        /// reason of failure.
        /// </summary>
        protected override void DoFinish()
        {
            if (_doFinishCalled)
                return;

            lock (SyncObject)
            {
                if (_doFinishCalled)
                    return;

                _doFinishCalled = true;
            }

            foreach (ExecutionCmdletHelper helper in _helpers)
            {
                DeterminedAndSetJobState(helper);
            }

            if (_helpers.Count == 0 && this.JobStateInfo.State == JobState.NotStarted)
            {
                SetJobState(JobState.Completed);
            }

            DoCleanupOnFinished();
        }

        /// <summary>
        /// Returns the PowerShell instance for the specified id.
        /// </summary>
        /// <param name="instanceId">Instance id of PowerShell.</param>
        /// <returns>PowerShell instance.</returns>
        internal override PowerShell GetPowerShell(Guid instanceId)
        {
            PowerShell powershell = null;

            _powershells.TryGetValue(instanceId, out powershell);

            return powershell;
        }

        #endregion Protected Methods

        #region Event Handlers

        /// <summary>
        /// Used to unregister URI Redirection handler.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs e)
        {
            RemoteRunspace remoteRS = sender as RemoteRunspace;
            // remote runspace must be connected (or connection failed)
            // we dont need URI redirection any more..so clear it
            if (remoteRS != null)
            {
                if (e.RunspaceStateInfo.State != RunspaceState.Opening)
                {
                    remoteRS.URIRedirectionReported -= HandleURIDirectionReported;

                    if (e.RunspaceStateInfo.State != RunspaceState.Opened)
                    {
                        remoteRS.StateChanged -= HandleRunspaceStateChanged;
                    }
                }
            }
        }

        #endregion

        #region Internal Methods

        /// <summary>
        /// Submits the operations created in the constructor for invocation.
        /// </summary>
        internal void StartOperations(List<IThrottleOperation> operations)
        {
            // submit operations to the throttle manager
            _throttleManager.SubmitOperations(operations);
            _throttleManager.EndSubmitOperations();
        }

        /// <summary>
        /// Determines if the job is in a terminal state.
        /// </summary>
        /// <returns>True, if job in terminal state
        /// false otherwise.</returns>
        internal bool IsTerminalState()
        {
            return (IsFinishedState(this.JobStateInfo.State) ||
                    this.JobStateInfo.State == JobState.Disconnected);
        }

        /// <summary>
        /// Returns a collection of all powershells for this job.
        /// </summary>
        /// <returns>Collection of PowerShell objects.</returns>
        internal Collection<PowerShell> GetPowerShells()
        {
            Collection<PowerShell> powershellsToReturn = new Collection<PowerShell>();
            foreach (PowerShell ps in _powershells.Values)
            {
                powershellsToReturn.Add(ps);
            }

            return powershellsToReturn;
        }

        /// <summary>
        /// Returns a disconnected remoting job object that contains all
        /// remote pipelines/runspaces that are in the Disconnected state.
        /// </summary>
        /// <returns></returns>
        internal PSRemotingJob CreateDisconnectedRemotingJob()
        {
            List<IThrottleOperation> disconnectedJobHelpers = new List<IThrottleOperation>();
            foreach (var helper in _helpers)
            {
                if (helper.Pipeline.PipelineStateInfo.State == PipelineState.Disconnected)
                {
                    // Remove data callbacks from the old helper.
                    RemoveAggreateCallbacksFromHelper(helper);

                    // Create new helper used to create the new Disconnected PSRemoting job.
                    disconnectedJobHelpers.Add(new DisconnectedJobOperation(helper.Pipeline));
                }
            }

            if (disconnectedJobHelpers.Count == 0)
            {
                return null;
            }

            return new PSRemotingJob(disconnectedJobHelpers, 0, Name, true);
        }

        #endregion Internal Methods
    }

    #region OutputProcessingState class

    internal class OutputProcessingStateEventArgs : EventArgs
    {
        internal bool ProcessingOutput { get; }

        internal OutputProcessingStateEventArgs(bool processingOutput)
        {
            ProcessingOutput = processingOutput;
        }
    }

#nullable enable
    internal interface IOutputProcessingState
    {
        event EventHandler<OutputProcessingStateEventArgs>? OutputProcessingStateChanged;
    }

    #endregion
}