How to use TempDirectory class of PuppeteerSharp.Helpers package

Best Puppeteer-sharp code snippet using PuppeteerSharp.Helpers.TempDirectory

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

TempDirectory.cs

Source: TempDirectory.cs Github

copy
1using System;
2using System.IO;
3using System.Threading;
4using System.Threading.Tasks;
5using PathHelper = System.IO.Path;
6
7namespace PuppeteerSharp.Helpers
8{
9    /// <summary>
10    /// Represents a directory that is deleted on disposal.
11    /// </summary>
12    internal class TempDirectory : IDisposable
13    {
14        private Task _deleteTask;
15
16        public TempDirectory()
17            : this(PathHelper.Combine(PathHelper.GetTempPath(), PathHelper.GetRandomFileName()))
18        { }
19
20        public TempDirectory(string path)
21        {
22            if (string.IsNullOrEmpty(path))
23            {
24                throw new ArgumentException("Path must be specified", nameof(path));
25            }
26
27            Directory.CreateDirectory(path);
28            this.Path = path;
29        }
30
31        ~TempDirectory()
32        {
33            Dispose(false);
34        }
35
36        public string Path { get; }
37
38        public void Dispose()
39        {
40            GC.SuppressFinalize(this);
41            Dispose(true);
42        }
43
44        protected void Dispose(bool disposing)
45        {
46            if (_deleteTask == null)
47            {
48                _ = DeleteAsync();
49            }
50        }
51
52        public override string ToString() => Path;
53
54        public Task DeleteAsync(CancellationToken cancellationToken = default)
55            => _deleteTask ?? (_deleteTask = DeleteAsync(Path, CancellationToken.None));
56
57        private static async Task DeleteAsync(string path, CancellationToken cancellationToken = default)
58        {
59            const int minDelayInMsec = 200;
60            const int maxDelayInMsec = 8000;
61
62            var retryDelay = minDelayInMsec;
63            while (true)
64            {
65                if (!Directory.Exists(path))
66                {
67                    return;
68                }
69
70                cancellationToken.ThrowIfCancellationRequested();
71                try
72                {
73                    Directory.Delete(path, true);
74                    return;
75                }
76                catch
77                {
78                    await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false);
79                    if (retryDelay < maxDelayInMsec)
80                    {
81                        retryDelay = Math.Min(2 * retryDelay, maxDelayInMsec);
82                    }
83                }
84            }
85        }
86    }
87}
88
Full Screen

ChromiumLauncher.cs

Source: ChromiumLauncher.cs Github

copy
1using PuppeteerSharp.Helpers;
2using System;
3using System.Collections.Generic;
4using System.Diagnostics;
5using System.Linq;
6
7namespace PuppeteerSharp
8{
9    /// <summary>
10    /// Represents a Chromium process and any associated temporary user data directory that have created
11    /// by Puppeteer and therefore must be cleaned up when no longer needed.
12    /// </summary>
13    public class ChromiumLauncher : LauncherBase
14    {
15        #region Constants
16
17        internal static readonly string[] DefaultArgs = {
18            "--disable-background-networking",
19            "--enable-features=NetworkService,NetworkServiceInProcess",
20            "--disable-background-timer-throttling",
21            "--disable-backgrounding-occluded-windows",
22            "--disable-breakpad",
23            "--disable-client-side-phishing-detection",
24            "--disable-component-extensions-with-background-pages",
25            "--disable-default-apps",
26            "--disable-dev-shm-usage",
27            "--disable-extensions",
28            "--disable-features=TranslateUI",
29            "--disable-hang-monitor",
30            "--disable-ipc-flooding-protection",
31            "--disable-popup-blocking",
32            "--disable-prompt-on-repost",
33            "--disable-renderer-backgrounding",
34            "--disable-sync",
35            "--force-color-profile=srgb",
36            "--metrics-recording-only",
37            "--no-first-run",
38            "--enable-automation",
39            "--password-store=basic",
40            "--use-mock-keychain"
41        };
42
43        private const string UserDataDirArgument = "--user-data-dir";
44
45        #endregion
46
47        #region Constructor
48
49        /// <summary>
50        /// Creates a new <see cref="ChromiumLauncher"/> instance.
51        /// </summary>
52        /// <param name="executable">Full path of executable.</param>
53        /// <param name="options">Options for launching Chromium.</param>
54        /// <param name="loggerFactory">Logger factory</param>
55        public ChromiumLauncher(string executable, LaunchOptions options)
56            : base(executable, options)
57        {
58            PrepareChromiumArgs(options, out List<string> chromiumArgs, out TempDirectory TempUserDataDir);
59            Process.StartInfo.Arguments = string.Join(" ", chromiumArgs);
60        }
61
62        #endregion
63
64        #region Public methods
65
66        /// <inheritdoc />
67        public override string ToString() => $"Chromium process; EndPoint={EndPoint}; State={CurrentState}";
68
69        #endregion
70
71        #region Private methods
72
73        private static void PrepareChromiumArgs(LaunchOptions options, out List<string> chromiumArgs, out TempDirectory tempUserDataDirectory)
74        {
75
76            chromiumArgs = new List<string>();
77
78            if (!options.IgnoreDefaultArgs)
79            {
80                chromiumArgs.AddRange(GetDefaultArgs(options));
81            }
82            else if (options.IgnoredDefaultArgs?.Length > 0)
83            {
84                chromiumArgs.AddRange(GetDefaultArgs(options).Except(options.IgnoredDefaultArgs));
85            }
86            else
87            {
88                chromiumArgs.AddRange(options.Args);
89            }
90
91            tempUserDataDirectory = null;
92
93            if (!chromiumArgs.Any(argument => argument.StartsWith("--remote-debugging-", StringComparison.Ordinal)))
94            {
95                chromiumArgs.Add("--remote-debugging-port=0");
96            }
97
98            string userDataDirOption = chromiumArgs.FirstOrDefault(i => i.StartsWith(UserDataDirArgument, StringComparison.Ordinal));
99            if (string.IsNullOrEmpty(userDataDirOption))
100            {
101                tempUserDataDirectory = new TempDirectory();
102                chromiumArgs.Add($"{UserDataDirArgument}={tempUserDataDirectory.Path.Quote()}");
103            }
104        }
105
106        internal static string[] GetDefaultArgs(LaunchOptions options)
107        {
108            var chromiumArguments = new List<string>(DefaultArgs);
109
110            if (!string.IsNullOrEmpty(options.UserDataDir))
111            {
112                chromiumArguments.Add($"{UserDataDirArgument}={options.UserDataDir.Quote()}");
113            }
114
115            if (options.Devtools)
116            {
117                chromiumArguments.Add("--auto-open-devtools-for-tabs");
118            }
119
120            if (options.Headless)
121            {
122                chromiumArguments.AddRange(new[] {
123                    "--headless",
124                    "--hide-scrollbars",
125                    "--mute-audio"
126                });
127            }
128
129            if (options.Args.All(arg => arg.StartsWith("-", StringComparison.Ordinal)))
130            {
131                chromiumArguments.Add("about:blank");
132            }
133
134            chromiumArguments.AddRange(options.Args);
135            return chromiumArguments.ToArray();
136        }
137
138        #endregion
139    }
140}
141
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in TempDirectory

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)