Best Puppeteer-sharp code snippet using PuppeteerSharp.LauncherBase
LauncherBase.cs
Source:LauncherBase.cs  
...12    /// <summary>13    /// Represents a Base process and any associated temporary user data directory that have created14    /// by Puppeteer and therefore must be cleaned up when no longer needed.15    /// </summary>16    public class LauncherBase : IDisposable17    {18        #region Instance fields19        private readonly LaunchOptions _options;20        private readonly TaskCompletionSource<string> _startCompletionSource = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);21        private readonly TaskCompletionSource<bool> _exitCompletionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);22        private State _currentState = State.Initial;23        #endregion24        #region Constructor25        /// <summary>26        /// Creates a new <see cref="LauncherBase"/> instance.27        /// </summary>28        /// <param name="executable">Full path of executable.</param>29        /// <param name="options">Options for launching Base.</param>30        /// <param name="loggerFactory">Logger factory</param>31        public LauncherBase(string executable, LaunchOptions options)32        {33            _options = options;34            Process = new Process35            {36                EnableRaisingEvents = true37            };38            Process.StartInfo.UseShellExecute = false;39            Process.StartInfo.FileName = executable;40            Process.StartInfo.RedirectStandardError = true;41            SetEnvVariables(Process.StartInfo.Environment, options.Env, Environment.GetEnvironmentVariables());42            if (options.DumpIO)43            {44                Process.ErrorDataReceived += (sender, e) => Console.Error.WriteLine(e.Data);45            }46        }47        #endregion48        #region Dispose49        /// <summary>50        /// Finalizer.51        /// </summary>52        ~LauncherBase()53        {54            Dispose(false);55        }56        /// <inheritdoc />57        public void Dispose()58        {59            Dispose(true);60            GC.SuppressFinalize(this);61        }62        /// <summary>63        /// Disposes Base process and any temporary user directory.64        /// </summary>65        /// <param name="disposing">Indicates whether disposal was initiated by <see cref="Dispose()"/> operation.</param>66        protected virtual void Dispose(bool disposing) => _currentState.Dispose(this);67        #endregion68        #region Properties69        /// <summary>70        /// Gets Base process details.71        /// </summary>72        public Process Process { get; }73        /// <summary>74        /// Gets Base endpoint.75        /// </summary>76        public string EndPoint => _startCompletionSource.Task.IsCompleted77            ? _startCompletionSource.Task.Result78            : null;79        /// <summary>80        /// Indicates whether Base process is exiting.81        /// </summary>82        public bool IsExiting => _currentState.IsExiting;83        /// <summary>84        /// Indicates whether Base process has exited.85        /// </summary>86        public bool HasExited => _currentState.IsExited;87        internal TempDirectory TempUserDataDir { get; set; }88        /// <summary>89        /// Gets Base process current state.90        /// </summary>91        protected State CurrentState { get => _currentState; }92        #endregion93        #region Public methods94        /// <summary>95        /// Asynchronously starts Base process.96        /// </summary>97        /// <returns></returns>98        public Task StartAsync() => _currentState.StartAsync(this);99        /// <summary>100        /// Asynchronously waits for graceful Base process exit within a given timeout period.101        /// Kills the Base process if it has not exited within this period.102        /// </summary>103        /// <param name="timeout">The maximum waiting time for a graceful process exit.</param>104        /// <returns></returns>105        public Task EnsureExitAsync(TimeSpan? timeout) => timeout.HasValue106            ? _currentState.ExitAsync(this, timeout.Value)107            : _currentState.KillAsync(this);108        /// <summary>109        /// Asynchronously kills Base process.110        /// </summary>111        /// <returns></returns>112        public Task KillAsync() => _currentState.KillAsync(this);113        /// <summary>114        /// Waits for Base process exit within a given timeout.115        /// </summary>116        /// <param name="timeout">The maximum wait period.</param>117        /// <returns><c>true</c> if Base process has exited within the given <paramref name="timeout"/>,118        /// or <c>false</c> otherwise.</returns>119        public async Task<bool> WaitForExitAsync(TimeSpan? timeout)120        {121            if (timeout.HasValue)122            {123                bool taskCompleted = true;124                await _exitCompletionSource.Task.WithTimeout(125                    () =>126                    {127                        taskCompleted = false;128                    }, timeout.Value).ConfigureAwait(false);129                return taskCompleted;130            }131            await _exitCompletionSource.Task.ConfigureAwait(false);132            return true;133        }134        #endregion135        #region Private methods136        /// <summary>137        /// Set Env Variables138        /// </summary>139        /// <param name="environment">The environment.</param>140        /// <param name="customEnv">The customEnv.</param>141        /// <param name="realEnv">The realEnv.</param>142        protected static void SetEnvVariables(IDictionary<string, string> environment, IDictionary<string, string> customEnv, IDictionary realEnv)143        {144            foreach (DictionaryEntry item in realEnv)145            {146                environment[item.Key.ToString()] = item.Value.ToString();147            }148            if (customEnv != null)149            {150                foreach (var item in customEnv)151                {152                    environment[item.Key] = item.Value;153                }154            }155        }156        #endregion157        #region State machine158        /// <summary>159        /// Represents state machine for Base process instances. The happy path runs along the160        /// following state transitions: <see cref="Initial"/>161        /// -> <see cref="Starting"/>162        /// -> <see cref="Started"/>163        /// -> <see cref="Exiting"/>164        /// -> <see cref="Exited"/>.165        /// -> <see cref="Disposed"/>.166        /// </summary>167        /// <remarks>168        /// <para>169        /// This state machine implements the following state transitions:170        /// <code>171        /// State     Event              Target State Action172        /// ======== =================== ============ ==========================================================173        /// Initial  --StartAsync------> Starting     Start process and wait for endpoint174        /// Initial  --ExitAsync-------> Exited       Cleanup temp user data175        /// Initial  --KillAsync-------> Exited       Cleanup temp user data176        /// Initial  --Dispose---------> Disposed     Cleanup temp user data177        /// Starting --StartAsync------> Starting     -178        /// Starting --ExitAsync-------> Exiting      Wait for process exit179        /// Starting --KillAsync-------> Killing      Kill process180        /// Starting --Dispose---------> Disposed     Kill process; Cleanup temp user data;  throw ObjectDisposedException on outstanding async operations;181        /// Starting --endpoint ready--> Started      Complete StartAsync successfully; Log process start182        /// Starting --process exit----> Exited       Complete StartAsync with exception; Cleanup temp user data183        /// Started  --StartAsync------> Started      -184        /// Started  --EnsureExitAsync-> Exiting      Start exit timer; Log process exit185        /// Started  --KillAsync-------> Killing      Kill process; Log process exit186        /// Started  --Dispose---------> Disposed     Kill process; Log process exit; Cleanup temp user data; throw ObjectDisposedException on outstanding async operations;187        /// Started  --process exit----> Exited       Log process exit; Cleanup temp user data188        /// Exiting  --StartAsync------> Exiting      - (StartAsync throws InvalidOperationException)189        /// Exiting  --ExitAsync-------> Exiting      -190        /// Exiting  --KillAsync-------> Killing      Kill process191        /// Exiting  --Dispose---------> Disposed     Kill process; Cleanup temp user data; throw ObjectDisposedException on outstanding async operations;192        /// Exiting  --exit timeout----> Killing      Kill process193        /// Exiting  --process exit----> Exited       Cleanup temp user data; complete outstanding async operations;194        /// Killing  --StartAsync------> Killing      - (StartAsync throws InvalidOperationException)195        /// Killing  --KillAsync-------> Killing      -196        /// Killing  --Dispose---------> Disposed     Cleanup temp user data; throw ObjectDisposedException on outstanding async operations;197        /// Killing  --process exit----> Exited       Cleanup temp user data; complete outstanding async operations;198        /// Exited   --StartAsync------> Killing      - (StartAsync throws InvalidOperationException)199        /// Exited   --KillAsync-------> Exited       -200        /// Exited   --Dispose---------> Disposed     -201        /// Disposed --StartAsync------> Disposed     -202        /// Disposed --KillAsync-------> Disposed     -203        /// Disposed --Dispose---------> Disposed     -204        /// </code>205        /// </para>206        /// </remarks>207        protected abstract class State208        {209            #region Predefined states210            /// <summary>211            /// Set initial state.212            /// </summary>213            public static readonly State Initial = new InitialState();214            private static readonly StartingState Starting = new StartingState();215            private static readonly StartedState Started = new StartedState();216            private static readonly ExitingState Exiting = new ExitingState();217            private static readonly KillingState Killing = new KillingState();218            private static readonly ExitedState Exited = new ExitedState();219            private static readonly DisposedState Disposed = new DisposedState();220            #endregion221            #region Properties222            /// <summary>223            /// Get If process exists.224            /// </summary>225            public bool IsExiting => this == Killing || this == Exiting;226            /// <summary>227            /// Get If process is exited.228            /// </summary>229            public bool IsExited => this == Exited || this == Disposed;230            #endregion231            #region Methods232            /// <summary>233            /// Attempts thread-safe transitions from a given state to this state.234            /// </summary>235            /// <param name="p">The Base process</param>236            /// <param name="fromState">The state from which state transition takes place</param>237            /// <returns>Returns <c>true</c> if transition is successful, or <c>false</c> if transition238            /// cannot be made because current state does not equal <paramref name="fromState"/>.</returns>239            protected bool TryEnter(LauncherBase p, State fromState)240            {241                if (Interlocked.CompareExchange(ref p._currentState, this, fromState) == fromState)242                {243                    fromState.Leave(p);244                    return true;245                }246                return false;247            }248            /// <summary>249            /// Notifies that state machine is about to transition to another state.250            /// </summary>251            /// <param name="p">The Base process</param>252            protected virtual void Leave(LauncherBase p)253            {254            }255            /// <summary>256            /// Handles process start request.257            /// </summary>258            /// <param name="p">The Base process</param>259            /// <returns></returns>260            public virtual Task StartAsync(LauncherBase p) => Task.FromException(InvalidOperation("start"));261            /// <summary>262            /// Handles process exit request.263            /// </summary>264            /// <param name="p">The Base process</param>265            /// <param name="timeout">The maximum waiting time for a graceful process exit.</param>266            /// <returns></returns>267            public virtual Task ExitAsync(LauncherBase p, TimeSpan timeout) => Task.FromException(InvalidOperation("exit"));268            /// <summary>269            /// Handles process kill request.270            /// </summary>271            /// <param name="p">The Base process</param>272            /// <returns></returns>273            public virtual Task KillAsync(LauncherBase p) => Task.FromException(InvalidOperation("kill"));274            /// <summary>275            /// Handles wait for process exit request.276            /// </summary>277            /// <param name="p">The Base process</param>278            /// <returns></returns>279            public virtual Task WaitForExitAsync(LauncherBase p) => p._exitCompletionSource.Task;280            /// <summary>281            /// Handles disposal of process and temporary user directory282            /// </summary>283            /// <param name="p"></param>284            public virtual void Dispose(LauncherBase p) => Disposed.EnterFrom(p, this);285            /// <inheritdoc />286            public override string ToString()287            {288                string name = GetType().Name;289                return name.Substring(0, name.Length - "State".Length);290            }291            private Exception InvalidOperation(string operationName)292                => new InvalidOperationException($"Cannot {operationName} in state {this}");293            /// <summary>294            /// Kills process if it is still alive.295            /// </summary>296            /// <param name="p"></param>297            private static void Kill(LauncherBase p)298            {299                try300                {301                    if (!p.Process.HasExited)302                    {303                        p.Process.Kill();304                    }305                }306                catch (InvalidOperationException)307                {308                    // Ignore309                }310            }311            #endregion312            #region Concrete state classes313            private class InitialState : State314            {315                public override Task StartAsync(LauncherBase p) => Starting.EnterFromAsync(p, this);316                public override Task ExitAsync(LauncherBase p, TimeSpan timeout)317                {318                    Exited.EnterFrom(p, this);319                    return Task.CompletedTask;320                }321                public override Task KillAsync(LauncherBase p)322                {323                    Exited.EnterFrom(p, this);324                    return Task.CompletedTask;325                }326                public override Task WaitForExitAsync(LauncherBase p) => Task.FromException(InvalidOperation("wait for exit"));327            }328            private class StartingState : State329            {330                public Task EnterFromAsync(LauncherBase p, State fromState)331                {332                    if (!TryEnter(p, fromState))333                    {334                        // Delegate StartAsync to current state, because it has already changed since335                        // transition to this state was initiated.336                        return p._currentState.StartAsync(p);337                    }338                    return StartCoreAsync(p);339                }340                public override Task StartAsync(LauncherBase p) => p._startCompletionSource.Task;341                public override Task ExitAsync(LauncherBase p, TimeSpan timeout) => Exiting.EnterFromAsync(p, this, timeout);342                public override Task KillAsync(LauncherBase p) => Killing.EnterFromAsync(p, this);343                public override void Dispose(LauncherBase p)344                {345                    p._startCompletionSource.TrySetException(new ObjectDisposedException(p.ToString()));346                    base.Dispose(p);347                }348                private async Task StartCoreAsync(LauncherBase p)349                {350                    var output = new StringBuilder();351                    void OnProcessDataReceivedWhileStarting(object sender, DataReceivedEventArgs e)352                    {353                        if (e.Data != null)354                        {355                            output.AppendLine(e.Data);356                            var match = Regex.Match(e.Data, "^DevTools listening on (ws:\\/\\/.*)");357                            if (match.Success)358                            {359                                p._startCompletionSource.TrySetResult(match.Groups[1].Value);360                            }361                        }362                    }363                    void OnProcessExitedWhileStarting(object sender, EventArgs e)364                        => p._startCompletionSource.TrySetException(new ProcessException($"Failed to launch Base! {output}"));365                    void OnProcessExited(object sender, EventArgs e) => Exited.EnterFrom(p, p._currentState);366                    p.Process.ErrorDataReceived += OnProcessDataReceivedWhileStarting;367                    p.Process.Exited += OnProcessExitedWhileStarting;368                    p.Process.Exited += OnProcessExited;369                    CancellationTokenSource cts = null;370                    try371                    {372                        p.Process.Start();373                        await Started.EnterFromAsync(p, this).ConfigureAwait(false);374                        p.Process.BeginErrorReadLine();375                        int timeout = p._options.Timeout;376                        if (timeout > 0)377                        {378                            cts = new CancellationTokenSource(timeout);379                            cts.Token.Register(() => p._startCompletionSource.TrySetException(380                                new ProcessException($"Timed out after {timeout} ms while trying to connect to Base!")));381                        }382                        try383                        {384                            await p._startCompletionSource.Task.ConfigureAwait(false);385                            await Started.EnterFromAsync(p, this).ConfigureAwait(false);386                        }387                        catch388                        {389                            await Killing.EnterFromAsync(p, this).ConfigureAwait(false);390                            throw;391                        }392                    }393                    finally394                    {395                        cts?.Dispose();396                        p.Process.Exited -= OnProcessExitedWhileStarting;397                        p.Process.ErrorDataReceived -= OnProcessDataReceivedWhileStarting;398                    }399                }400            }401            private class StartedState : State402            {403                public Task EnterFromAsync(LauncherBase p, State fromState)404                {405                    if (TryEnter(p, fromState))406                    {407                    }408                    return Task.CompletedTask;409                }410                protected override void Leave(LauncherBase p) { }411                public override Task StartAsync(LauncherBase p) => Task.CompletedTask;412                public override Task ExitAsync(LauncherBase p, TimeSpan timeout) => Exiting.EnterFromAsync(p, this, timeout);413                public override Task KillAsync(LauncherBase p) => Killing.EnterFromAsync(p, this);414            }415            private class ExitingState : State416            {417                public Task EnterFromAsync(LauncherBase p, State fromState, TimeSpan timeout)418                    => !TryEnter(p, fromState) ? p._currentState.ExitAsync(p, timeout) : ExitAsync(p, timeout);419                public override async Task ExitAsync(LauncherBase p, TimeSpan timeout)420                {421                    var waitForExitTask = WaitForExitAsync(p);422                    await waitForExitTask.WithTimeout(423                        async () =>424                        {425                            await Killing.EnterFromAsync(p, this).ConfigureAwait(false);426                            await waitForExitTask.ConfigureAwait(false);427                        },428                        timeout,429                        CancellationToken.None).ConfigureAwait(false);430                }431                public override Task KillAsync(LauncherBase p) => Killing.EnterFromAsync(p, this);432            }433            private class KillingState : State434            {435                public async Task EnterFromAsync(LauncherBase p, State fromState)436                {437                    if (!TryEnter(p, fromState))438                    {439                        // Delegate KillAsync to current state, because it has already changed since440                        // transition to this state was initiated.441                        await p._currentState.KillAsync(p).ConfigureAwait(false);442                    }443                    try444                    {445                        if (!p.Process.HasExited)446                        {447                            p.Process.Kill();448                        }449                    }450                    catch (InvalidOperationException)451                    {452                        // Ignore453                        return;454                    }455                    await WaitForExitAsync(p).ConfigureAwait(false);456                }457                public override Task ExitAsync(LauncherBase p, TimeSpan timeout) => WaitForExitAsync(p);458                public override Task KillAsync(LauncherBase p) => WaitForExitAsync(p);459            }460            private class ExitedState : State461            {462                public void EnterFrom(LauncherBase p, State fromState)463                {464                    while (!TryEnter(p, fromState))465                    {466                        // Current state has changed since transition to this state was requested.467                        // Therefore retry transition to this state from the current state. This ensures468                        // that Leave() operation of current state is properly called.469                        fromState = p._currentState;470                        if (fromState == this)471                        {472                            return;473                        }474                    }475                    p._exitCompletionSource.TrySetResult(true);476                    p.TempUserDataDir?.Dispose();477                }478                public override Task ExitAsync(LauncherBase p, TimeSpan timeout) => Task.CompletedTask;479                public override Task KillAsync(LauncherBase p) => Task.CompletedTask;480                public override Task WaitForExitAsync(LauncherBase p) => Task.CompletedTask;481            }482            private class DisposedState : State483            {484                public void EnterFrom(LauncherBase p, State fromState)485                {486                    if (!TryEnter(p, fromState))487                    {488                        // Delegate Dispose to current state, because it has already changed since489                        // transition to this state was initiated.490                        p._currentState.Dispose(p);491                    }492                    else if (fromState != Exited)493                    {494                        Kill(p);495                        p._exitCompletionSource.TrySetException(new ObjectDisposedException(p.ToString()));496                        p.TempUserDataDir?.Dispose();497                    }498                }499                public override Task StartAsync(LauncherBase p) => throw new ObjectDisposedException(p.ToString());500                public override Task ExitAsync(LauncherBase p, TimeSpan timeout) => throw new ObjectDisposedException(p.ToString());501                public override Task KillAsync(LauncherBase p) => throw new ObjectDisposedException(p.ToString());502                public override void Dispose(LauncherBase p)503                {504                    // Nothing to do505                }506            }507            #endregion508        }509        #endregion510    }511}...ChromiumStartingState.cs
Source:ChromiumStartingState.cs  
...10    {11        public ChromiumStartingState(StateManager stateManager) : base(stateManager)12        {13        }14        public override Task EnterFromAsync(LauncherBase p, State fromState, TimeSpan timeout)15        {16            if (!StateManager.TryEnter(p, fromState, this))17            {18                // Delegate StartAsync to current state, because it has already changed since19                // transition to this state was initiated.20                return StateManager.CurrentState.StartAsync(p);21            }22            return StartCoreAsync(p);23        }24        public override Task StartAsync(LauncherBase p) => p.StartCompletionSource.Task;25        public override Task ExitAsync(LauncherBase p, TimeSpan timeout) => StateManager.Exiting.EnterFromAsync(p, this, timeout);26        public override Task KillAsync(LauncherBase p) => StateManager.Killing.EnterFromAsync(p, this);27        public override void Dispose(LauncherBase p)28        {29            p.StartCompletionSource.TrySetException(new ObjectDisposedException(p.ToString()));30            base.Dispose(p);31        }32        protected virtual async Task StartCoreAsync(LauncherBase p)33        {34            var output = new StringBuilder();35            void OnProcessDataReceivedWhileStarting(object sender, DataReceivedEventArgs e)36            {37                if (e.Data != null)38                {39                    output.AppendLine(e.Data);40                    var match = Regex.Match(e.Data, "^DevTools listening on (ws:\\/\\/.*)");41                    if (match.Success)42                    {43                        p.StartCompletionSource.TrySetResult(match.Groups[1].Value);44                    }45                }46            }...KillingState.cs
Source:KillingState.cs  
...6    {7        public KillingState(StateManager stateManager) : base(stateManager)8        {9        }10        public override async Task EnterFromAsync(LauncherBase p, State fromState, TimeSpan timeout)11        {12            if (!StateManager.TryEnter(p, fromState, this))13            {14                // Delegate KillAsync to current state, because it has already changed since15                // transition to this state was initiated.16                await StateManager.CurrentState.KillAsync(p).ConfigureAwait(false);17            }18            try19            {20                if (!p.Process.HasExited)21                {22                    p.Process.Kill();23                }24            }25            catch (InvalidOperationException)26            {27                // Ignore28                return;29            }30            await WaitForExitAsync(p).ConfigureAwait(false);31        }32        public override Task ExitAsync(LauncherBase p, TimeSpan timeout) => WaitForExitAsync(p);33        public override Task KillAsync(LauncherBase p) => WaitForExitAsync(p);34    }35}...ExitedState.cs
Source:ExitedState.cs  
...6    {7        public ExitedState(StateManager stateManager) : base(stateManager)8        {9        }10        public void EnterFrom(LauncherBase p, State fromState)11        {12            while (!StateManager.TryEnter(p, fromState, this))13            {14                // Current state has changed since transition to this state was requested.15                // Therefore retry transition to this state from the current state. This ensures16                // that Leave() operation of current state is properly called.17                fromState = StateManager.CurrentState;18                if (fromState == this)19                {20                    return;21                }22            }23            p.ExitCompletionSource.TrySetResult(true);24            p.TempUserDataDir?.Dispose();25        }26        public override Task ExitAsync(LauncherBase p, TimeSpan timeout) => Task.CompletedTask;27        public override Task KillAsync(LauncherBase p) => Task.CompletedTask;28        public override Task WaitForExitAsync(LauncherBase p) => Task.CompletedTask;29    }30}...ExitingState.cs
Source:ExitingState.cs  
...8    {9        public ExitingState(StateManager stateManager) : base(stateManager)10        {11        }12        public override Task EnterFromAsync(LauncherBase p, State fromState, TimeSpan timeout)13            => !StateManager.TryEnter(p, fromState, this) ? StateManager.CurrentState.ExitAsync(p, timeout) : ExitAsync(p, timeout);14        public override async Task ExitAsync(LauncherBase p, TimeSpan timeout)15        {16            var waitForExitTask = WaitForExitAsync(p);17            await waitForExitTask.WithTimeout(18                async () =>19                {20                    await StateManager.Killing.EnterFromAsync(p, this, timeout).ConfigureAwait(false);21                    await waitForExitTask.ConfigureAwait(false);22                },23                timeout,24                CancellationToken.None).ConfigureAwait(false);25        }26        public override Task KillAsync(LauncherBase p) => StateManager.Killing.EnterFromAsync(p, this);27    }28}...DisposedState.cs
Source:DisposedState.cs  
...6    {7        public DisposedState(StateManager stateManager) : base(stateManager)8        {9        }10        public override Task EnterFromAsync(LauncherBase p, State fromState, TimeSpan timeSpan)11        {12            if (fromState == StateManager.Exited)13            {14                return null;15            }16            Kill(p);17            p.ExitCompletionSource.TrySetException(new ObjectDisposedException(p.ToString()));18            p.TempUserDataDir?.Dispose();19            return null;20        }21        public override Task StartAsync(LauncherBase p) => throw new ObjectDisposedException(p.ToString());22        public override Task ExitAsync(LauncherBase p, TimeSpan timeout) => throw new ObjectDisposedException(p.ToString());23        public override Task KillAsync(LauncherBase p) => throw new ObjectDisposedException(p.ToString());24        public override void Dispose(LauncherBase p)25        {26            // Nothing to do27        }28    }29}...InitialState.cs
Source:InitialState.cs  
...6    {7        public InitialState(StateManager stateManager) : base(stateManager)8        {9        }10        public override Task StartAsync(LauncherBase p) => StateManager.Starting.EnterFromAsync(p, this, TimeSpan.Zero);11        public override Task ExitAsync(LauncherBase p, TimeSpan timeout)12        {13            StateManager.Exited.EnterFromAsync(p, this);14            return Task.CompletedTask;15        }16        public override Task KillAsync(LauncherBase p)17        {18            StateManager.Exited.EnterFromAsync(p, this);19            return Task.CompletedTask;20        }21        public override Task WaitForExitAsync(LauncherBase p) => Task.FromException(InvalidOperation("wait for exit"));22        private Exception InvalidOperation(string v)23        {24            throw new NotImplementedException();25        }26    }27}...StartedState.cs
Source:StartedState.cs  
...6    {7        public StartedState(StateManager stateManager) : base(stateManager)8        {9        }10        public override Task EnterFromAsync(LauncherBase p, State fromState, TimeSpan timeout)11        {12            StateManager.TryEnter(p, fromState, this);13            return Task.CompletedTask;14        }15        public override Task StartAsync(LauncherBase p) => Task.CompletedTask;16        public override Task ExitAsync(LauncherBase p, TimeSpan timeout) => new ExitingState(StateManager).EnterFromAsync(p, this, timeout);17        public override Task KillAsync(LauncherBase p) => new KillingState(StateManager).EnterFromAsync(p, this);18    }19}...LauncherBase
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static async Task Main(string[] args)7        {8            {9                Args = new string[] { "--start-maximized" }10            };11            using (var browser = await Puppeteer.LaunchAsync(options))12            {13                var page = await browser.NewPageAsync();14                await page.ScreenshotAsync("google.png");15            }16        }17    }18}19using System;20using System.Threading.Tasks;21using PuppeteerSharp;22{23    {24        static async Task Main(string[] args)25        {26            {27                Args = new string[] { "--start-maximized" }28            };29            using (var browser = await Puppeteer.LaunchAsync(options))30            {31                var page = await browser.NewPageAsync();32                await page.ScreenshotAsync("google.png");33            }34        }35    }36}37using System;38using System.Threading.Tasks;39using PuppeteerSharp;40{41    {42        static async Task Main(string[] args)43        {44            {45                Args = new string[] { "--start-maximized" }46            };47            using (var browser = await Puppeteer.LaunchAsync(options))48            {49                var page = await browser.NewPageAsync();50                await page.ScreenshotAsync("google.png");51            }52        }53    }54}55using System;56using System.Threading.Tasks;57using PuppeteerSharp;58{59    {60        static async Task Main(string[] args)61        {62            {LauncherBase
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5    {6        static async Task Main(string[] args)7        {8            Console.WriteLine("Hello World!");9            var options = new LaunchOptions { Headless = true };10            using (var browser = await Puppeteer.LaunchAsync(options))11            {12                using (var page = await browser.NewPageAsync())13                {14                    await page.ScreenshotAsync("google.png");15                }16            }17        }18    }19}LauncherBase
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5    {6        static void Main(string[] args)7        {8            MainAsync().Wait();9        }10        static async Task MainAsync()11        {12            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions13            {14                Args = new string[] { "--no-sandbox" }15            }))16            {17                var page = await browser.NewPageAsync();18                Console.ReadKey();19            }20        }21    }22}LauncherBase
Using AI Code Generation
1using PuppeteerSharp;2using System.Threading.Tasks;3{4    {5        static async Task Main(string[] args)6        {7            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))9            {LauncherBase
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5    {6        static void Main(string[] args)7        {8            RunAsync().Wait();9        }10        static async Task RunAsync()11        {12            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))13            {14                using (var page = await browser.NewPageAsync())15                {16                    await Task.Delay(5000);17                }18            }19        }20    }21}22using PuppeteerSharp;23using System;24using System.Threading.Tasks;25{26    {27        static void Main(string[] args)28        {29            RunAsync().Wait();30        }31        static async Task RunAsync()32        {33            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))34            {35                using (var page = await browser.NewPageAsync())36                {37                    await Task.Delay(5000);38                }39            }40        }41    }42}43using PuppeteerSharp;44using System;45using System.Threading.Tasks;46{47    {48        static void Main(string[] args)49        {50            RunAsync().Wait();51        }52        static async Task RunAsync()53        {54            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))55            {56                using (var page = await browser.NewPageAsync())57                {58                    await Task.Delay(5000);59                }60            }61        }62    }63}LauncherBase
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5    {6        public static Task<Browser> LaunchAsync(LaunchOptions options = null)7        {8            return Task.FromResult(new Browser());9        }10    }11}12using PuppeteerSharp;13using System;14using System.Threading.Tasks;15{16    {17        public Task<Page> NewPageAsync()18        {19            return Task.FromResult(new Page());20        }21    }22}23using PuppeteerSharp;24using System;25using System.Threading.Tasks;26{27    {28        public Task<string> GoToAsync(string url, NavigationOptions options = null)29        {30            return Task.FromResult("Page");31        }32    }33}34using PuppeteerSharp;35using System;36using System.Threading.Tasks;37{38    {39    }40}41using PuppeteerSharp;42using System;43using System.Threading.Tasks;44{45    {46        static void Main(string[] args)47        {48            var task = MainAsync();49            task.Wait();50        }51        static async Task MainAsync()52        {53            var options = new LaunchOptions { Headless = true };54            using (var browser = await LauncherBase.LaunchAsync(options))55            using (var page = await browser.NewPageAsync())56            {57            }58        }59    }60}LauncherBase
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5    {6        public static async Task MainTest(string[] args)7        {8            {9                Args = new[] { "--disable-extensions" }10            };11            using (var browser = await Puppeteer.LaunchAsync(options))12            {13                using (var page = await browser.NewPageAsync())14                {15                    await page.ScreenshotAsync(@"C:\Users\Public\Pictures\Sample Pictures\chromium.png");16                }17            }18        }19    }20}LauncherBase
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static async Task Main(string[] args)7        {8            var browser = await Puppeteer.LaunchAsync(new LaunchOptions9            {10            });11            var page = await browser.NewPageAsync();12            Console.WriteLine("Title of the page: " + await page.GetTitleAsync());13            await browser.CloseAsync();14        }15    }16}17using System;18using System.Threading.Tasks;19using PuppeteerSharp;20{21    {22        static async Task Main(string[] args)23        {24            var browser = await Puppeteer.LaunchAsync(new LaunchOptions25            {26            });27            var page = await browser.NewPageAsync();28            await page.TypeAsync("input[title='Search']", "puppeteer");29            await page.Keyboard.PressAsync("Enter");30            Console.WriteLine("Title of the page: " + await page.GetTitleAsync());31            await browser.CloseAsync();32        }33    }34}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
