How to use new method of Microsoft.Playwright.Core.Stream class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Stream.new

BotCore.cs

Source:BotCore.cs Github

copy

Full Screen

...11using Newtonsoft.Json;12namespace BotCore;13public class Core14{15 private static readonly ConcurrentQueue<IBrowser> Browsers = new();16 private static readonly Random _random = new();17 public static string ZipDirectory = string.Empty;18 public static string StreamUrl = string.Empty;19 public static bool Headless;20 public static int BrowserLimit;21 private readonly JsonSerializerSettings _isoDateFormatSettings = new()22 {23 DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,24 DateParseHandling = DateParseHandling.DateTime25 };26 private readonly object _lockObject = new();27 private readonly string _loginCookiesPath =28 Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "loginCookies.json");29 private readonly ConcurrentBag<string> _chatMessages = new();30 private StreamReader _file;31 private bool _firstPage = true;32 private List<Process> _initialChromeProcesses = new();33 private IPlaywright _playwright;34 private int _refreshInterval;35 private bool _useLowCpuRam;36 public Action AllBrowsersTerminated;37 public bool CanRun = true;38 public Action DecreaseViewer;39 public Action DidItsJob;40 public Action IncreaseViewer;41 public Action<Exception> InitializationError;42 public Action<string> LiveViewer;43 public Action<Exception> LogMessage;44 public string PreferredQuality;45 public void Start(ExecuteNeedsDto executeNeeds)46 {47 if (executeNeeds.UseLowCpuRam)48 executeNeeds.RefreshInterval = 1;49 if (_playwright != null)50 _playwright.Dispose();51 _playwright = Playwright.CreateAsync().GetAwaiter().GetResult();52 BrowserLimit = executeNeeds.BrowserLimit;53 CanRun = true;54 _firstPage = true;55 _useLowCpuRam = executeNeeds.UseLowCpuRam;56 Headless = executeNeeds.Headless;57 PreferredQuality = executeNeeds.PreferredQuality;58 _refreshInterval = executeNeeds.RefreshInterval;59 var i = 0;60 StreamUrl = executeNeeds.Stream;61 62 var executeNeedsChatMessages = executeNeeds.ChatMessages;63 Shuffle(ref executeNeedsChatMessages);64 foreach (var item in executeNeedsChatMessages) _chatMessages.Add(item);65 if (BrowserLimit > 0)66 {67 var thr = new Thread(LoopWithLimit);68 thr.Start();69 }70 71 _initialChromeProcesses = Process.GetProcessesByName("chrome").ToList();72 do73 {74 try75 {76 _file = new StreamReader(executeNeeds.ProxyListDirectory);77 string line;78 while (CanRun && (line = _file.ReadLine()) != null)79 {80 line = line.Replace(" ", "");81 if (string.IsNullOrEmpty(line))82 continue;83 var array = line.Split(':');84 var proxy = new Proxy85 {86 Server = "http://" + array[0] + ":" + array[1],87 Username = array[2],88 Password = array[3]89 };90 var thr = new Thread(Request) {Priority = ThreadPriority.AboveNormal};91 var r = new Random();92 var rInt = r.Next(5000, 8000);93 while (BrowserLimit > 0 && Browsers.Count >= BrowserLimit) Thread.Sleep(1000);94 if (!CanRun)95 continue;96 executeNeeds.LoginInfos.TryDequeue(out var loginInfo);97 thr.Start(new SessionConfigurationDto98 {99 Url = line,100 Count = i,101 PreferredQuality = executeNeeds.PreferredQuality,102 LoginInfo = loginInfo,103 Service = executeNeeds.Service,104 Proxy = proxy105 });106 i++;107 Thread.Sleep(BrowserLimit == 0 ? rInt : 1000);108 }109 _file.Close();110 }111 catch (Exception e)112 {113 InitializationError?.Invoke(e is IndexOutOfRangeException114 ? new Exception("Please select a valid proxy file.")115 : e);116 }117 if (!CanRun)118 break;119 } while (executeNeeds.BrowserLimit > 0);120 DidItsJob?.Invoke();121 }122 private void Shuffle(ref List<string> list)123 {124 var n = list.Count;125 while (n > 1)126 {127 n--;128 var k = _random.Next(n + 1);129 (list[k], list[n]) = (list[n], list[k]);130 }131 }132 private void StoreCookie(Tuple<string, List<BrowserContextCookiesResult>> cookie)133 {134 var myCookie = new List<MyCookie>();135 foreach (var item in cookie.Item2)136 myCookie.Add(new MyCookie137 {138 Domain = item.Domain,139 Expiry = item.Expires,140 HttpOnly = Convert.ToBoolean(item.HttpOnly),141 Name = item.Name,142 Path = item.Path,143 Value = item.Value,144 Secure = Convert.ToBoolean(item.Secure)145 });146 lock (_lockObject)147 {148 if (!File.Exists(_loginCookiesPath))149 {150 var item = new Dictionary<string, List<MyCookie>> {{cookie.Item1, myCookie}};151 File.WriteAllText(_loginCookiesPath, JsonConvert.SerializeObject(item), Encoding.UTF8);152 return;153 }154 var readCookiesJson = File.ReadAllText(_loginCookiesPath);155 var readCookies = JsonConvert.DeserializeObject<Dictionary<string, List<MyCookie>>>(readCookiesJson);156 readCookies.TryGetValue(cookie.Item1, out var value);157 if (value?.Count > 0)158 readCookies[cookie.Item1] = myCookie;159 else160 readCookies.Add(cookie.Item1, myCookie);161 File.WriteAllText(_loginCookiesPath, JsonConvert.SerializeObject(readCookies), Encoding.UTF8);162 }163 }164 private List<MyCookie> GetCookie(string username)165 {166 lock (_lockObject)167 {168 if (!File.Exists(_loginCookiesPath)) return new List<MyCookie>();169 var readCookiesJson = File.ReadAllText(_loginCookiesPath);170 var readCookies = JsonConvert.DeserializeObject<Dictionary<string, List<MyCookie>>>(readCookiesJson);171 return readCookies.FirstOrDefault(x => x.Key == username).Value;172 }173 }174 private void KillAllProcesses()175 {176 var allChromeProcesses = Process.GetProcessesByName("chrome");177 foreach (var process in allChromeProcesses)178 if (_initialChromeProcesses.All(x => x.Id != process.Id))179 {180 var startInfo = new ProcessStartInfo181 {182 CreateNoWindow = true,183 FileName = "CMD.exe"184 };185 var strCmd = $"/C taskkill /F /PID {process.Id}";186 startInfo.Arguments = strCmd;187 var processTemp = new Process();188 processTemp.StartInfo = startInfo;189 processTemp.Start();190 }191 _initialChromeProcesses.Clear();192 var allChromeDriverProcesses = Process.GetProcessesByName("chromedriver");193 foreach (var chromeDriverService in allChromeDriverProcesses)194 try195 {196 chromeDriverService.Kill();197 }198 catch (Exception)199 {200 //ignored201 }202 }203 public void Stop()204 {205 CanRun = false;206 _file?.Close();207 KillAllProcesses();208 209 Browsers.Clear();210 AllBrowsersTerminated?.Invoke();211 }212 private void LoopWithLimit()213 {214 while (CanRun)215 try216 {217 if (Browsers.Count >= BrowserLimit)218 {219 KillAllProcesses();220 Browsers.Clear();221 }222 Thread.Sleep(500);223 }224 catch (Exception)225 {226 //ignored227 }228 }229 private void Request(object obj)230 {231 try232 {233 var r = new Random();234 var itm = (SessionConfigurationDto) obj;235 var array = itm.Url.Split(':');236 var args = new List<string>();237 string[] resolutions =238 {"1480,900", "1550,790", "1600,900", "1920,1080", "1480,768", "1780,940"};239 var browserLaunchOptions = new BrowserTypeLaunchOptions()240 {241 Headless = false,242 Channel = "chrome",243 Timeout = 120000,244 Proxy = itm.Proxy245 };246 if (_useLowCpuRam)247 {248 args.Add("--disable-extensions-except=" + AppDomain.CurrentDomain.BaseDirectory +249 "\\Extensions\\TwitchAlternative.crx");250 args.Add("--load-extension=" + AppDomain.CurrentDomain.BaseDirectory +251 "\\Extensions\\TwitchAlternative.crx");252 }253 if (Headless) browserLaunchOptions.Headless = true;254 var localChrome = AppDomain.CurrentDomain.BaseDirectory + "\\Extensions\\LocalChrome\\chrome.exe";255 if (File.Exists(localChrome)) browserLaunchOptions.ExecutablePath = localChrome;256 args.Add("--mute-audio");257 args.Add("--enable-automation");258 args.Add("--useAutomationExtension=false");259 browserLaunchOptions.Args = args;260 var browser = _playwright.Chromium.LaunchAsync(browserLaunchOptions).GetAwaiter().GetResult();261 var page = browser.NewPageAsync(new BrowserNewPageOptions()262 {263 ViewportSize = new ViewportSize264 {265 Width = Convert.ToInt32(resolutions[r.Next(0, resolutions.Length - 1)].Split(',')[0]),266 Height = Convert.ToInt32(resolutions[r.Next(0, resolutions.Length - 1)].Split(',')[1])267 },268 UserAgent =269 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36",270 Geolocation = new Geolocation() {Latitude = r.Next(-90, 90), Longitude = r.Next(-180, 180)},271 }).GetAwaiter().GetResult();272 page.GotoAsync(StreamUrl, new PageGotoOptions() {Timeout = 120000, WaitUntil = WaitUntilState.Load})273 .GetAwaiter().GetResult();274 if (BrowserLimit > 0)275 {276 Thread.Sleep(1000);277 return;278 }279 Browsers.Enqueue(browser);280 IncreaseViewer?.Invoke();281 var firstPage = false;282 var startDate = DateTime.Now;283 var messageStartDate = DateTime.Now;284 var messageInterval = _random.Next(1, 10);285 if (itm.Service == StreamService.Service.Twitch)286 {287 if (!Headless && !_useLowCpuRam)288 try289 {290 page.EvaluateAsync("window.localStorage.setItem('video-quality', '" + itm.PreferredQuality +291 "');");292 page.ReloadAsync().GetAwaiter().GetResult();293 }294 catch (Exception)295 {296 //ignored297 }298 var matureClicked = false;299 var matureCheckCount = 0;300 var cacheClicked = false;301 var cacheCheckCount = 0;302 if (itm.LoginInfo != null)303 {304 Thread.Sleep(1000);305 var allCookies = GetCookie(itm.LoginInfo.Username);306 if (allCookies != null)307 foreach (var cookie in allCookies)308 {309 Cookie[] cookies =310 {311 new()312 {313 Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,314 Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,315 HttpOnly = cookie.HttpOnly, Value = cookie.Value316 }317 };318 page.Context.AddCookiesAsync(cookies);319 }320 try321 {322 var loginButton =323 page.Locator(324 "xpath=/html/body/div[1]/div/div[2]/nav/div/div[3]/div[3]/div/div[1]/div[1]/button/div/div");325 if (loginButton.CountAsync().GetAwaiter().GetResult() > 0)326 {327 Click(ref loginButton);328 Thread.Sleep(1000);329 var usernameBox =330 page.Locator(331 "xpath=/html/body/div[3]/div/div/div/div/div/div[1]/div/div/div[3]/form/div/div[1]/div/div[2]/input");332 if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)333 {334 Click(ref usernameBox);335 Thread.Sleep(1000);336 usernameBox.TypeAsync(itm.LoginInfo.Username).GetAwaiter().GetResult();337 var passwordBox =338 page.Locator(339 "xpath=/html/body/div[3]/div/div/div/div/div/div[1]/div/div/div[3]/form/div/div[2]/div/div[1]/div[2]/div[1]/input");340 if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)341 {342 Click(ref passwordBox);343 Thread.Sleep(1000);344 passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();345 Thread.Sleep(1000);346 var login = page.Locator(347 "xpath=/html/body/div[3]/div/div/div/div/div/div[1]/div/div/div[3]/form/div/div[3]/button/div/div");348 Thread.Sleep(1000);349 if (login.CountAsync().GetAwaiter().GetResult() > 0)350 Click(ref login);351 }352 }353 }354 }355 catch (Exception ex)356 {357 LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));358 }359 while (true)360 {361 Thread.Sleep(1000);362 var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult()363 .Any(x => x.Name == "auth-token");364 if (cookie)365 {366 StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,367 new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()368 .GetResult().ToArray())));369 break;370 }371 }372 }373 while (true)374 {375 try376 {377 if (_firstPage)378 {379 firstPage = true;380 _firstPage = false;381 }382 if (firstPage)383 {384 var liveViewers =385 page.Locator(386 "xpath=/html/body/div[1]/div/div[2]/div[1]/main/div[2]/div[3]/div/div/div[1]/div[1]/div[2]/div/div[1]/div/div/div/div[2]/div[2]/div[2]/div/div/div[1]/div[1]/div/p/span");387 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)388 {389 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());390 Thread.Sleep(5000);391 }392 }393 }394 catch (Exception)395 {396 LiveViewer.Invoke("N/A");397 }398 Thread.Sleep(1000);399 try400 {401 var connectionError =402 page.Locator(403 "xpath=/html/body/div[1]/div/div[2]/div[1]/main/div[2]/div[3]/div/div/div[2]/div/div[2]/div/div/div/div/div[7]/div/div[3]/button/div/div[2]");404 if (connectionError.CountAsync().GetAwaiter().GetResult() > 0)405 connectionError.ClickAsync().GetAwaiter().GetResult();406 }407 catch (Exception)408 {409 //ignored410 }411 412 try413 {414 if (!matureClicked && matureCheckCount < 5)415 try416 {417 var mature =418 page.Locator(419 "xpath=/html/body/div[1]/div/div[2]/div[1]/main/div[2]/div[3]/div/div/div[2]/div/div[2]/div/div/div/div/div[5]/div/div[3]/button/div/div");420 if (mature.CountAsync().GetAwaiter().GetResult() > 0)421 {422 Click(ref mature);423 matureClicked = true;424 matureCheckCount++;425 }426 }427 catch428 {429 //ignored because there is no mature button430 }431 }432 catch (Exception)433 {434 // ignored435 }436 try437 {438 if (!cacheClicked && cacheCheckCount < 5)439 try440 {441 var cache = page.Locator(442 "xpath=/html/body/div[1]/div/div[2]/div[1]/div/div/div[3]/button/div/div/div");443 if (cache.CountAsync().GetAwaiter().GetResult() > 0)444 {445 Click(ref cache);446 cacheClicked = true;447 }448 cacheCheckCount++;449 }450 catch (Exception)451 {452 //ignored because there is no cache button453 }454 }455 catch (Exception)456 {457 // ignored458 }459 try460 {461 if (_refreshInterval != 0 &&462 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))463 {464 page.ReloadAsync().GetAwaiter().GetResult();465 startDate = DateTime.Now;466 }467 }468 catch (Exception)469 {470 //ignored471 }472 try473 {474 if (messageInterval != 0 &&475 DateTime.Now - messageStartDate > TimeSpan.FromMinutes(messageInterval) &&476 itm.LoginInfo != null)477 {478 SendMessage();479 messageStartDate = DateTime.Now;480 }481 }482 catch (Exception)483 {484 //ignored485 }486 }487 void SendMessage()488 {489 try490 {491 var chatBox = page.WaitForSelectorAsync(".chat-wysiwyg-input__editor").GetAwaiter()492 .GetResult();493 if (_chatMessages.TryTake(out var message))494 {495 chatBox?.TypeAsync(message).GetAwaiter().GetResult();496 page.Keyboard.PressAsync("Enter").GetAwaiter().GetResult();497 }498 }499 catch (Exception)500 {501 //ignored 502 }503 }504 }505 if (itm.Service == StreamService.Service.Youtube)506 {507 Thread.Sleep(3000);508 try509 {510 var play = page.Locator(511 "xpath=/html/body/ytd-app/div/ytd-page-manager/ytd-watch-flexy/div[5]/div[1]/div/div[1]/div/div/div/ytd-player/div/div/div[5]/button");512 play?.ClickAsync().GetAwaiter().GetResult();513 }514 catch (Exception)515 {516 //ignored517 }518 while (true)519 {520 try521 {522 if (_firstPage)523 {524 firstPage = true;525 _firstPage = false;526 }527 if (firstPage)528 {529 var liveViewers = page.Locator(530 "xpath=/html/body/ytd-app/div/ytd-page-manager/ytd-watch-flexy/div[5]/div[1]/div/div[6]/div[2]/ytd-video-primary-info-renderer/div/div/div[1]/div[1]/ytd-video-view-count-renderer/span[1]");531 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)532 {533 LiveViewer.Invoke(534 liveViewers.InnerTextAsync().GetAwaiter().GetResult().Split(' ')[0]);535 Thread.Sleep(5000);536 }537 }538 }539 catch (Exception)540 {541 LiveViewer.Invoke("N/A");542 }543 try544 {545 if (_refreshInterval != 0 &&546 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))547 {548 page.ReloadAsync().GetAwaiter().GetResult();549 startDate = DateTime.Now;550 }551 }552 catch553 {554 //ignored555 }556 }557 }558 if (itm.Service == StreamService.Service.DLive)559 {560 Thread.Sleep(3000);561 var isPlaying = false;562 while (true)563 {564 try565 {566 if (_firstPage)567 {568 firstPage = true;569 _firstPage = false;570 }571 if (firstPage)572 {573 try574 {575 var liveViewers =576 page.Locator(577 "xpath=/html/body/div/div[1]/div[20]/div[2]/div/div[2]/div/div/div/div[1]/div/div[1]/div[3]/div/div[1]/div/div[2]/div[2]");578 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)579 {580 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult()581 .Split(" ")[0]);582 Thread.Sleep(5000);583 }584 }585 catch (Exception)586 {587 //ignored588 }589 try590 {591 var liveViewers =592 page.Locator(593 "xpath=/html/body/div/div[1]/div[18]/div[2]/div/div/div/div/div/div/div/div/div[3]/div/div[3]/div/div/div[1]/div/div[1]/div[2]/div/div[1]/span");594 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)595 {596 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());597 Thread.Sleep(5000);598 }599 }600 catch (Exception)601 {602 //ignored603 }604 }605 if (!isPlaying)606 {607 var play = page.Locator(608 "xpath=/html/body/div/div[1]/div[14]/div[2]/div/div[2]/div/div/div/div/div/div/div[1]/div/div/div/div/div[4]/div[2]/button/svg");609 if (play.CountAsync().GetAwaiter().GetResult() > 0)610 {611 Click(ref play);612 isPlaying = true;613 }614 }615 Thread.Sleep(1000);616 }617 catch (Exception)618 {619 //ignored620 }621 try622 {623 if (_refreshInterval != 0 &&624 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))625 {626 page.ReloadAsync().GetAwaiter().GetResult();627 isPlaying = false;628 startDate = DateTime.Now;629 }630 }631 catch (Exception)632 {633 //ignored634 }635 }636 }637 if (itm.Service == StreamService.Service.NimoTv)638 {639 Thread.Sleep(3000);640 var isPlaying = false;641 if (itm.LoginInfo != null)642 {643 Thread.Sleep(1000);644 var allCookies = GetCookie(itm.LoginInfo.Username);645 if (allCookies != null)646 foreach (var cookie in allCookies)647 {648 Cookie[] cookies =649 {650 new()651 {652 Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,653 Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,654 HttpOnly = cookie.HttpOnly, Value = cookie.Value655 }656 };657 page.Context.AddCookiesAsync(cookies);658 }659 try660 {661 var loginButton =662 page.Locator("xpath=/html/body/div[2]/div[1]/div/div[2]/div/div[2]/button");663 if (loginButton.CountAsync().GetAwaiter().GetResult() > 0)664 {665 Click(ref loginButton);666 Thread.Sleep(1000);667 var usernameBox =668 page.Locator(669 "xpath=/html/body/div[6]/div/div[2]/div/div[2]/div/div/div[3]/div[1]/div[2]/input");670 if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)671 {672 Click(ref usernameBox);673 Thread.Sleep(1000);674 usernameBox.TypeAsync(itm.LoginInfo.Username.Split('/')[1]).GetAwaiter()675 .GetResult();676 var countryCodeArrow =677 page.Locator(678 "xpath=/html/body/div[6]/div/div[2]/div/div[2]/div/div/div[3]/div[1]/div[2]/div[1]");679 if (countryCodeArrow.CountAsync().GetAwaiter().GetResult() > 0)680 {681 Click(ref countryCodeArrow);682 Thread.Sleep(1000);683 var searchCountryCode =684 page.Locator(685 "xpath=/html/body/div[6]/div/div[2]/div/div[4]/div/div/div/div[1]/input");686 if (searchCountryCode.CountAsync().GetAwaiter().GetResult() > 0)687 {688 searchCountryCode.TypeAsync(itm.LoginInfo.Username.Split('/')[0]689 .Replace("+", string.Empty)).GetAwaiter().GetResult();690 Thread.Sleep(1000);691 var firstElement =692 page.Locator(693 "xpath=/html/body/div[6]/div/div[2]/div/div[4]/div/div/div/div[2]/div[1]/div[2]");694 if (firstElement.CountAsync().GetAwaiter().GetResult() > 0)695 Click(ref firstElement);696 }697 }698 var passwordBox =699 page.Locator(700 "xpath=/html/body/div[6]/div/div[2]/div/div[2]/div/div/div[3]/div[1]/div[3]/input");701 if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)702 {703 Click(ref passwordBox);704 Thread.Sleep(1000);705 passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();706 Thread.Sleep(1000);707 var login = page.Locator(708 "xpath=/html/body/div[6]/div/div[2]/div/div[2]/div/div/div[3]/div[1]/button");709 Thread.Sleep(1000);710 if (login.CountAsync().GetAwaiter().GetResult() > 0)711 Click(ref login);712 }713 }714 }715 }716 catch (Exception ex)717 {718 LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));719 }720 while (true)721 {722 Thread.Sleep(1000);723 var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult()724 .Any(x => x.Name == "userName");725 if (cookie)726 {727 StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,728 new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()729 .GetResult().ToArray())));730 break;731 }732 }733 }734 while (true)735 {736 try737 {738 if (_firstPage)739 {740 firstPage = true;741 _firstPage = false;742 }743 if (firstPage)744 {745 var liveViewers =746 page.Locator(747 "xpath=/html/body/div[2]/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/div[1]/div[1]/div/div[2]/div[3]/span");748 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)749 {750 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());751 Thread.Sleep(5000);752 }753 }754 }755 catch (Exception)756 {757 LiveViewer.Invoke("N/A");758 }759 try760 {761 if (!isPlaying)762 {763 var play = page.Locator(764 "xpath=/html/body/div[2]/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/div[1]/div[2]/div[1]/div[2]/div/span");765 if (play.CountAsync().GetAwaiter().GetResult() > 0)766 {767 Click(ref play);768 isPlaying = true;769 }770 }771 }772 catch (Exception)773 {774 //ignored775 }776 try777 {778 if (_refreshInterval != 0 &&779 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))780 {781 page.ReloadAsync().GetAwaiter().GetResult();782 isPlaying = false;783 startDate = DateTime.Now;784 }785 }786 catch (Exception)787 {788 //ignored789 }790 try791 {792 if (messageInterval != 0 &&793 DateTime.Now - messageStartDate > TimeSpan.FromMinutes(messageInterval) &&794 itm.LoginInfo != null)795 {796 SendMessage();797 messageStartDate = DateTime.Now;798 }799 }800 catch (Exception)801 {802 //ignored803 }804 void SendMessage()805 {806 try807 {808 var chatBox = page.WaitForSelectorAsync(".nimo-room__chatroom__chat-box__input")809 .GetAwaiter().GetResult();810 if (chatBox != null && _chatMessages.TryTake(out var message))811 {812 chatBox.TypeAsync(message).GetAwaiter().GetResult();813 page.Keyboard.PressAsync("Enter");814 }815 }816 catch (Exception)817 {818 //ignored 819 }820 }821 Thread.Sleep(1000);822 }823 }824 if (itm.Service == StreamService.Service.Twitter)825 {826 Thread.Sleep(3000);827 while (true)828 {829 try830 {831 if (_firstPage)832 {833 firstPage = true;834 _firstPage = false;835 }836 if (firstPage)837 {838 var liveViewers =839 page.Locator(840 "xpath=/html/body/div[2]/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/div[1]/div[1]/div/div[2]/div[3]/span");841 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)842 {843 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());844 Thread.Sleep(5000);845 }846 }847 }848 catch (Exception)849 {850 LiveViewer.Invoke("N/A");851 }852 try853 {854 if (_refreshInterval != 0 &&855 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))856 {857 page.ReloadAsync().GetAwaiter().GetResult();858 startDate = DateTime.Now;859 }860 }861 catch (Exception)862 {863 //ignored864 }865 Thread.Sleep(1000);866 }867 }868 if (itm.Service == StreamService.Service.Facebook)869 {870 Thread.Sleep(3000);871 if (itm.LoginInfo != null)872 {873 Thread.Sleep(1000);874 var allCookies = GetCookie(itm.LoginInfo.Username);875 if (allCookies != null)876 foreach (var cookie in allCookies)877 {878 Cookie[] cookies =879 {880 new()881 {882 Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,883 Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,884 HttpOnly = cookie.HttpOnly, Value = cookie.Value885 }886 };887 page.Context.AddCookiesAsync(cookies);888 }889 try890 {891 var usernameBox =892 page.Locator(893 "xpath=/html/body/div[1]/div/div[1]/div/div[2]/div[2]/div[2]/div/form/div[2]/div[1]/label/input");894 if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)895 {896 Click(ref usernameBox);897 Thread.Sleep(1000);898 usernameBox.TypeAsync(itm.LoginInfo.Username).GetAwaiter().GetResult();899 var passwordBox =900 page.Locator(901 "xpath=/html/body/div[1]/div/div[1]/div/div[2]/div[2]/div[2]/div/form/div[2]/div[2]/label/input");902 if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)903 {904 Click(ref passwordBox);905 Thread.Sleep(1000);906 passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();907 Thread.Sleep(1000);908 var login = page.Locator(909 "xpath=/html/body/div[1]/div/div[1]/div/div[2]/div[2]/div[2]/div/form/div[2]/div[3]/div/div/div[1]/div/span/span");910 Thread.Sleep(1000);911 if (login.CountAsync().GetAwaiter().GetResult() > 0)912 Click(ref login);913 }914 }915 }916 catch (Exception ex)917 {918 LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));919 }920 Thread.Sleep(3000);921 page.ReloadAsync().GetAwaiter().GetResult();922 while (true)923 {924 Thread.Sleep(1000);925 var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult()926 .Any(x => x.Name == "c_user");927 if (cookie)928 {929 StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,930 new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()931 .GetResult().ToArray())));932 break;933 }934 }935 }936 while (true)937 {938 try939 {940 if (_firstPage)941 {942 firstPage = true;943 _firstPage = false;944 }945 if (firstPage)946 {947 var liveViewers =948 page.Locator(949 "xpath=/html/body/div[1]/div/div[1]/div/div[3]/div/div/div[1]/div[2]/div[1]/div/div/div/div[1]/div[1]/div/div/div/div[2]/div/div[5]/div[2]/span[2]");950 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)951 {952 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());953 Thread.Sleep(5000);954 }955 }956 }957 catch (Exception)958 {959 //ignored960 }961 try962 {963 if (_refreshInterval != 0 &&964 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))965 {966 page.ReloadAsync().GetAwaiter().GetResult();967 startDate = DateTime.Now;968 }969 }970 catch (Exception)971 {972 //ignored973 }974 }975 }976 if (itm.Service == StreamService.Service.TrovoLive)977 {978 Thread.Sleep(5000);979 if (!Headless && !_useLowCpuRam)980 try981 {982 page.EvaluateAsync("window.localStorage.setItem('live/userClarityLevel', '" +983 itm.PreferredQuality + "');");984 page.ReloadAsync().GetAwaiter().GetResult();985 }986 catch (Exception)987 {988 //ignored989 }990 if (itm.LoginInfo != null)991 {992 Thread.Sleep(1000);993 var allCookies = GetCookie(itm.LoginInfo.Username);994 if (allCookies != null)995 foreach (var cookie in allCookies)996 {997 Cookie[] cookies =998 {999 new()1000 {1001 Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,1002 Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,1003 HttpOnly = cookie.HttpOnly, Value = cookie.Value1004 }1005 };1006 page.Context.AddCookiesAsync(cookies);1007 }1008 try1009 {1010 var loginSignUpButton =1011 page.Locator("xpath=/html/body/div[1]/div/div/nav/div[3]/div[3]/button");1012 if (loginSignUpButton.CountAsync().GetAwaiter().GetResult() > 0)1013 {1014 Click(ref loginSignUpButton);1015 Thread.Sleep(4000);1016 ILocator usernameBox;1017 try1018 {1019 usernameBox =1020 page.Locator(1021 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[1]/div/input");1022 }1023 catch1024 {1025 usernameBox =1026 page.Locator(1027 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[1]/div[1]/input");1028 }1029 if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)1030 {1031 Click(ref usernameBox);1032 Thread.Sleep(1000);1033 usernameBox.TypeAsync(itm.LoginInfo.Username).GetAwaiter().GetResult();1034 Thread.Sleep(1000);1035 var passwordBox =1036 page.Locator(1037 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[3]/div/input");1038 if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)1039 {1040 passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();1041 var login = page.Locator(1042 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/button");1043 Thread.Sleep(1000);1044 if (login.CountAsync().GetAwaiter().GetResult() > 0)1045 Click(ref login);1046 }1047 }1048 }1049 }1050 catch (Exception ex)1051 {1052 LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));1053 }1054 Thread.Sleep(3000);1055 page.ReloadAsync().GetAwaiter().GetResult();1056 while (true)1057 {1058 Thread.Sleep(1000);1059 var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult().Any(x => x.Name == "uid");1060 if (cookie)1061 {1062 StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,1063 new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()1064 .GetResult().ToArray())));1065 break;1066 }1067 }1068 }1069 var matureClicked = false;1070 var chatRulesClicked = false;1071 var matureCheckCount = 0;1072 while (true)1073 {1074 try1075 {1076 if (_firstPage)1077 {1078 firstPage = true;1079 _firstPage = false;1080 }1081 if (firstPage)1082 {1083 var liveViewers =1084 page.Locator(1085 "xpath=/html/body/div[1]/div/div[1]/div/div[3]/div/div/div[1]/div[2]/div[1]/div/div/div/div[1]/div[1]/div/div/div/div[2]/div/div[5]/div[2]/span[2]");1086 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)1087 {1088 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());1089 Thread.Sleep(5000);1090 }1091 }1092 }1093 catch (Exception)1094 {1095 //ignored1096 }1097 try1098 {1099 if (_refreshInterval != 0 &&1100 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))1101 {1102 page.ReloadAsync().GetAwaiter().GetResult();1103 startDate = DateTime.Now;1104 }1105 }1106 catch (Exception)1107 {1108 //ignored1109 }1110 try1111 {1112 if (!matureClicked && matureCheckCount < 5)1113 try1114 {1115 ILocator mature = null;1116 try1117 {1118 mature = page.Locator(1119 "xpath=/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div[1]/div[1]/div/div[4]/div[3]/section/div/button[2]");1120 }1121 catch1122 {1123 //ignored1124 }1125 if (mature.CountAsync().GetAwaiter().GetResult() == 0)1126 mature = page.Locator(1127 "xpath=/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div[1]/div[1]/div/div[2]/div[3]/section/div/button[2]");1128 if (mature.CountAsync().GetAwaiter().GetResult() > 0)1129 {1130 Click(ref mature);1131 matureClicked = true;1132 }1133 matureCheckCount++;1134 }1135 catch1136 {1137 //ignored because there is no mature button1138 }1139 }1140 catch (Exception)1141 {1142 // ignored1143 }1144 if (!chatRulesClicked)1145 try1146 {1147 var chatRules = page.Locator(1148 "xpath=/html/body/div[1]/div/div/div/div[2]/div/section/div[3]/div/section/section/div/button");1149 if (chatRules.CountAsync().GetAwaiter().GetResult() > 0)1150 {1151 chatRules.ClickAsync().GetAwaiter().GetResult();1152 chatRulesClicked = true;1153 }1154 }1155 catch (Exception)1156 {1157 //ignored1158 }1159 try1160 {1161 if (messageInterval != 0 &&1162 DateTime.Now - messageStartDate > TimeSpan.FromMinutes(messageInterval) &&1163 itm.LoginInfo != null)1164 {1165 SendMessage();1166 messageStartDate = DateTime.Now;1167 }1168 }1169 catch (Exception)1170 {1171 //ignored1172 }1173 void SendMessage()1174 {1175 try1176 {1177 var chatBox =1178 page.Locator(1179 "xpath=/html/body/div[1]/div/div/div/div[2]/div/section/div[3]/div/section/div[1]/div[1]/div[1]");1180 if (chatBox.CountAsync().GetAwaiter().GetResult() > 0 &&1181 _chatMessages.TryTake(out var message))1182 {1183 chatBox.TypeAsync(message).GetAwaiter().GetResult();1184 page.Keyboard.PressAsync("Enter");1185 }1186 }1187 catch (Exception)1188 {1189 //ignored 1190 }1191 }1192 Thread.Sleep(1000);1193 }1194 }1195 if (itm.Service == StreamService.Service.BigoLive)1196 {1197 Thread.Sleep(2000);1198 page.ReloadAsync().GetAwaiter().GetResult();1199 1200 /*if (itm.LoginInfo != null)1201 {1202 Thread.Sleep(1000);1203 var allCookies = GetCookie(itm.LoginInfo.Username);1204 if (allCookies != null)1205 foreach (var cookie in allCookies)1206 {1207 Cookie[] cookies =1208 {1209 new()1210 {1211 Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,1212 Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,1213 HttpOnly = cookie.HttpOnly, Value = cookie.Value1214 }1215 };1216 page.Context.AddCookiesAsync(cookies);1217 }1218 try1219 {1220 var loginSignUpButton =1221 page.Locator("xpath=/html/body/div/div/div/header/div[2]/div/button");1222 if (loginSignUpButton.CountAsync().GetAwaiter().GetResult() > 0)1223 {1224 Click(ref loginSignUpButton);1225 1226 var withCredentialsButton =1227 page.Locator("xpath=/html/body/div/div[2]/div/header/div[3]/div/div[2]");1228 if (withCredentialsButton.CountAsync().GetAwaiter().GetResult() > 0)1229 {1230 Click(ref withCredentialsButton);1231 Thread.Sleep(4000);1232 ILocator usernameBox;1233 try1234 {1235 usernameBox =1236 page.Locator(1237 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[1]/div/input");1238 }1239 catch1240 {1241 usernameBox =1242 page.Locator(1243 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[1]/div[1]/input");1244 }1245 if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)1246 {1247 Click(ref usernameBox);1248 Thread.Sleep(1000);1249 usernameBox.TypeAsync(itm.LoginInfo.Username).GetAwaiter().GetResult();1250 Thread.Sleep(1000);1251 var passwordBox =1252 page.Locator(1253 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[3]/div/input");1254 if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)1255 {1256 passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();1257 var login = page.Locator(1258 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/button");1259 Thread.Sleep(1000);1260 if (login.CountAsync().GetAwaiter().GetResult() > 0)1261 Click(ref login);1262 }1263 }1264 }1265 }1266 }1267 catch (Exception ex)1268 {1269 LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));1270 }1271 Thread.Sleep(3000);1272 page.ReloadAsync().GetAwaiter().GetResult();1273 while (true)1274 {1275 Thread.Sleep(1000);1276 var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult().Any(x => x.Name == "uid");1277 if (cookie)1278 {1279 StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,1280 new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()1281 .GetResult().ToArray())));1282 break;1283 }1284 }1285 }*/1286 while (true)1287 {1288 try1289 {1290 if (_firstPage)1291 {1292 firstPage = true;1293 _firstPage = false;1294 }1295 if (firstPage)1296 {1297 var liveViewers = page.WaitForSelectorAsync(".info-view-nums").GetAwaiter().GetResult();1298 1299 if (liveViewers != null)1300 {1301 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());1302 Thread.Sleep(5000);1303 }1304 }1305 }1306 catch (Exception)1307 {1308 //ignored1309 }1310 try1311 {1312 if (_refreshInterval != 0 &&1313 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))1314 {1315 page.ReloadAsync().GetAwaiter().GetResult();1316 startDate = DateTime.Now;1317 }1318 }1319 catch (Exception)1320 {1321 //ignored1322 }1323 Thread.Sleep(1000);1324 }1325 }1326 try1327 {1328 page.CloseAsync().GetAwaiter().GetResult();1329 }1330 catch (Exception)1331 {1332 //ignored1333 }1334 }1335 catch (InvalidOperationException ex)1336 {1337 if (ex.Message.Contains("only supports Chrome version"))1338 {1339 CanRun = false;1340 InitializationError?.Invoke(new Exception("Please update your Google Chrome!"));1341 }1342 }1343 catch (Exception ex)1344 {1345 InitializationError?.Invoke(ex);1346 }1347 }1348 private void Click(ref ILocator locator)1349 {1350 locator.ClickAsync().GetAwaiter().GetResult();1351 }1352 private class MyCookie1353 {1354 public bool Secure { get; set; }...

Full Screen

Full Screen

BingEntitySearchSkill.cs

Source:BingEntitySearchSkill.cs Github

copy

Full Screen

...170 [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,171 ILogger log)172 {173 log.LogInformation("Entity Search function: C# HTTP trigger function processed a request.");174 var response = new WebApiResponse();175 response.values = new List<OutputRecord>();176 string requestBody = new StreamReader(req.Body).ReadToEnd();177 var data = JsonConvert.DeserializeObject<WebApiRequest>(requestBody);178 // Do some schema validation179 if (data == null)180 {181 return new BadRequestObjectResult("The request schema does not match expected schema.");182 }183 if (data.values == null)184 {185 return new BadRequestObjectResult("The request schema does not match expected schema. Could not find values array.");186 }187 // Calculate the response for each value.188 foreach (var record in data.values)189 {190 if (record == null || record.recordId == null) continue;191 OutputRecord responseRecord = new OutputRecord();192 responseRecord.RecordId = record.recordId;193 try194 {195 string nameName = record.data.name;196 responseRecord.Data = GetEntityMetadata(nameName).Result;197 }198 catch (Exception e)199 {200 // Something bad happened, log the issue.201 var error = new OutputRecord.OutputRecordMessage202 {203 Message = e.Message204 };205 responseRecord.Errors = new List<OutputRecord.OutputRecordMessage>();206 responseRecord.Errors.Add(error);207 }208 finally209 {210 response.values.Add(responseRecord);211 }212 }213 return (ActionResult)new OkObjectResult(response);214 }215 #endregion216 #region Methods to call the Bing API217 public class RetryHandler : DelegatingHandler218 {219 // Strongly consider limiting the number of retries - "retry forever" is220 // probably not the most user friendly way you could respond to "the221 // network cable got pulled out."222 private const int MaxRetries = 10;223 public RetryHandler(HttpMessageHandler innerHandler)224 : base(innerHandler)225 { }226 protected override async Task<HttpResponseMessage> SendAsync(227 HttpRequestMessage request,228 CancellationToken cancellationToken)229 {230 HttpResponseMessage response = null;231 for (int i = 0; i < MaxRetries; i++)232 {233 response = await base.SendAsync(request, cancellationToken);234 if (response.IsSuccessStatusCode)235 {236 return response;237 }238 //Log.Info("Retrying " + request.RequestUri.ToString());239 Thread.Sleep(1000);240 }241 return response;242 }243 }244 /// <summary>245 /// Helper function that replaces nulls for empty strings.246 /// </summary>247 /// <param name="value"></param>248 /// <returns></returns>249 public static String EmptyOrValue(String value)250 {251 if (value == null) return "";252 return value;253 }254 /// <summary>255 /// Gets metadata for a particular entity based on its name using Bing Entity Search256 /// </summary>257 /// <param name="nameName">The image to extract objects for.</param>258 /// <returns>Asynchronous task that returns objects identified in the image. </returns>259 async static Task<OutputRecord.OutputRecordData> GetEntityMetadata(string nameName)260 {261 var uri = bingApiEndpoint + "?q=" + nameName + "&mkt=en-us&count=10&offset=0&safesearch=Moderate";262 var result = new OutputRecord.OutputRecordData();263 using (var client = new HttpClient(new RetryHandler(new HttpClientHandler())))264 using (var request = new HttpRequestMessage())265 {266 request.Method = HttpMethod.Get;267 request.RequestUri = new Uri(uri);268 request.Headers.Add("Ocp-Apim-Subscription-Key", key);269 var response = await client.SendAsync(request);270 var responseBody = await response.Content.ReadAsStringAsync();271 result = JsonConvert.DeserializeObject<OutputRecord.OutputRecordData>(responseBody);272 // In addition to the list of entities that could match the name, for simplicity let's return information273 // for the top match as additional metadata at the root object.274 result = AddTopEntityMetadata(result);275 // Do some cleanup on the returned result.276 result.ImageUrl = EmptyOrValue(result.ImageUrl);277 result.Description = EmptyOrValue(result.Description);278 if (result.Name == null) { result.Name = EmptyOrValue(nameName); }279 result.Url = EmptyOrValue(result.Url);280 result.LicenseAttribution = EmptyOrValue(result.LicenseAttribution);281 }282 return result;283 }284 public class CoreData285 {286 public string description;287 public string name;288 public string imageUrl;289 public string url;290 public string licenseAttribution;291 }292 static OutputRecord.OutputRecordData AddTopEntityMetadata(OutputRecord.OutputRecordData rootObject)293 {294 CoreData coreData = new CoreData();295 if (rootObject.Entities != null)296 {297 foreach (BingEntity entity in rootObject.Entities.value)298 {299 if (entity.EntityPresentationInfo != null)300 {301 if (entity.EntityPresentationInfo.EntityTypeHints != null)302 {303 if (entity.EntityPresentationInfo.EntityTypeHints[0] != "Person" &&304 entity.EntityPresentationInfo.EntityTypeHints[0] != "Organization" &&305 entity.EntityPresentationInfo.EntityTypeHints[0] != "Location"306 )307 {308 continue;...

Full Screen

Full Screen

AspNetProcess.cs

Source:AspNetProcess.cs Github

copy

Full Screen

...42 ILogger logger = null)43 {44 _developmentCertificate = cert;45 _output = output;46 _httpClient = new HttpClient(new HttpClientHandler()47 {48 AllowAutoRedirect = true,49 UseCookies = true,50 CookieContainer = new CookieContainer(),51 ServerCertificateCustomValidationCallback = (request, certificate, chain, errors) => (certificate.Subject != "CN=localhost" && errors == SslPolicyErrors.None) || certificate?.Thumbprint == _developmentCertificate.CertificateThumbprint,52 })53 {54 Timeout = TimeSpan.FromMinutes(2)55 };56 output.WriteLine("Running ASP.NET Core application...");57 string process;58 string arguments;59 if (published)60 {61 if (usePublishedAppHost)62 {63 // When publishingu used the app host to run the app. This makes it easy to consistently run for regular and single-file publish64 process = Path.ChangeExtension(dllPath, OperatingSystem.IsWindows() ? ".exe" : null);65 arguments = null;66 }67 else68 {69 process = DotNetMuxer.MuxerPathOrDefault();70 arguments = $"exec {dllPath}";71 }72 }73 else74 {75 process = DotNetMuxer.MuxerPathOrDefault();76 arguments = "run --no-build";77 }78 logger?.LogInformation($"AspNetProcess - process: {process} arguments: {arguments}");79 var finalEnvironmentVariables = new Dictionary<string, string>(environmentVariables)80 {81 ["ASPNETCORE_Kestrel__Certificates__Default__Path"] = _developmentCertificate.CertificatePath,82 ["ASPNETCORE_Kestrel__Certificates__Default__Password"] = _developmentCertificate.CertificatePassword,83 };84 Process = ProcessEx.Run(output, workingDirectory, process, arguments, envVars: finalEnvironmentVariables);85 logger?.LogInformation("AspNetProcess - process started");86 if (hasListeningUri)87 {88 logger?.LogInformation("AspNetProcess - Getting listening uri");89 ListeningUri = ResolveListeningUrl(output);90 logger?.LogInformation($"AspNetProcess - Got {ListeningUri}");91 }92 }93 public async Task VisitInBrowserAsync(IPage page)94 {95 _output.WriteLine($"Opening browser at {ListeningUri}...");96 await page.GoToAsync(ListeningUri.AbsoluteUri);97 }98 public async Task AssertPagesOk(IEnumerable<Page> pages)99 {100 foreach (var page in pages)101 {102 await AssertOk(page.Url);103 await ContainsLinks(page);104 }105 }106 public async Task ContainsLinks(Page page)107 {108 var response = await RetryHelper.RetryRequest(async () =>109 {110 var request = new HttpRequestMessage(111 HttpMethod.Get,112 new Uri(ListeningUri, page.Url));113 return await _httpClient.SendAsync(request);114 }, logger: NullLogger.Instance);115 Assert.Equal(HttpStatusCode.OK, response.StatusCode);116 var parser = new HtmlParser();117 var html = await parser.ParseAsync(await response.Content.ReadAsStreamAsync());118 foreach (IHtmlLinkElement styleSheet in html.GetElementsByTagName("link"))119 {120 Assert.Equal("stylesheet", styleSheet.Relation);121 await AssertOk(styleSheet.Href.Replace("about://", string.Empty));122 }123 foreach (var script in html.Scripts)124 {125 if (!string.IsNullOrEmpty(script.Source))126 {127 await AssertOk(script.Source);128 }129 }130 Assert.True(html.Links.Length == page.Links.Count(), $"Expected {page.Url} to have {page.Links.Count()} links but it had {html.Links.Length}");131 foreach ((var link, var expectedLink) in html.Links.Zip(page.Links, Tuple.Create))132 {133 IHtmlAnchorElement anchor = (IHtmlAnchorElement)link;134 if (string.Equals(anchor.Protocol, "about:"))135 {136 Assert.True(anchor.PathName.EndsWith(expectedLink, StringComparison.Ordinal), $"Expected next link on {page.Url} to be {expectedLink} but it was {anchor.PathName}: {html.Source.Text}");137 await AssertOk(anchor.PathName);138 }139 else140 {141 Assert.True(string.Equals(anchor.Href, expectedLink), $"Expected next link to be {expectedLink} but it was {anchor.Href}.");142 var result = await RetryHelper.RetryRequest(async () =>143 {144 return await _httpClient.GetAsync(anchor.Href);145 }, logger: NullLogger.Instance);146 Assert.True(IsSuccessStatusCode(result), $"{anchor.Href} is a broken link!");147 }148 }149 }150 private Uri ResolveListeningUrl(ITestOutputHelper output)151 {152 // Wait until the app is accepting HTTP requests153 output.WriteLine("Waiting until ASP.NET application is accepting connections...");154 var listeningMessage = GetListeningMessage();155 if (!string.IsNullOrEmpty(listeningMessage))156 {157 listeningMessage = listeningMessage.Trim();158 // Verify we have a valid URL to make requests to159 var listeningUrlString = listeningMessage.Substring(listeningMessage.IndexOf(160 ListeningMessagePrefix, StringComparison.Ordinal) + ListeningMessagePrefix.Length);161 output.WriteLine($"Detected that ASP.NET application is accepting connections on: {listeningUrlString}");162 listeningUrlString = string.Concat(listeningUrlString.AsSpan(0, listeningUrlString.IndexOf(':')),163 "://localhost",164 listeningUrlString.AsSpan(listeningUrlString.LastIndexOf(':')));165 output.WriteLine("Sending requests to " + listeningUrlString);166 return new Uri(listeningUrlString, UriKind.Absolute);167 }168 else169 {170 return null;171 }172 }173 private string GetListeningMessage()174 {175 var buffer = new List<string>();176 try177 {178 foreach (var line in Process.OutputLinesAsEnumerable)179 {180 if (line != null)181 {182 buffer.Add(line);183 if (line.Trim().Contains(ListeningMessagePrefix, StringComparison.Ordinal))184 {185 return line;186 }187 }188 }189 }190 catch (OperationCanceledException)191 {192 }193 throw new InvalidOperationException(@$"Couldn't find listening url:194{string.Join(Environment.NewLine, buffer)}");195 }196 private bool IsSuccessStatusCode(HttpResponseMessage response)197 {198 return response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.Redirect;199 }200 public Task AssertOk(string requestUrl)201 => AssertStatusCode(requestUrl, HttpStatusCode.OK);202 public Task AssertNotFound(string requestUrl)203 => AssertStatusCode(requestUrl, HttpStatusCode.NotFound);204 internal Task<HttpResponseMessage> SendRequest(string path) =>205 RetryHelper.RetryRequest(() => _httpClient.GetAsync(new Uri(ListeningUri, path)), logger: NullLogger.Instance);206 internal Task<HttpResponseMessage> SendRequest(Func<HttpRequestMessage> requestFactory)207 => RetryHelper.RetryRequest(() => _httpClient.SendAsync(requestFactory()), logger: NullLogger.Instance);208 public async Task AssertStatusCode(string requestUrl, HttpStatusCode statusCode, string acceptContentType = null)209 {210 var response = await RetryHelper.RetryRequest(() =>211 {212 var request = new HttpRequestMessage(213 HttpMethod.Get,214 new Uri(ListeningUri, requestUrl));215 if (!string.IsNullOrEmpty(acceptContentType))216 {217 request.Headers.Add("Accept", acceptContentType);218 }219 return _httpClient.SendAsync(request);220 }, logger: NullLogger.Instance);221 Assert.True(statusCode == response.StatusCode, $"Expected {requestUrl} to have status '{statusCode}' but it was '{response.StatusCode}'.");222 }223 public void Dispose()224 {225 _httpClient.Dispose();226 Process.Dispose();227 }228 public override string ToString()...

Full Screen

Full Screen

Startup.cs

Source:Startup.cs Github

copy

Full Screen

...22 {23 #region null checks24 if (builder is null)25 {26 throw new ArgumentNullException(nameof(builder));27 }28 #endregion29#pragma warning disable CA2000 // Dispose objects before losing scope30 // Replace the Console.Error stream to record error output from Playwright in Application Insights31 var telemetryClient = new TelemetryClient(new TelemetryConfiguration(Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY")));32 var errorStream = new ApplicationInsightsStream(10240, telemetryClient);33 Console.SetError(TextWriter.Synchronized(new StreamWriter(errorStream)34 {35 AutoFlush = true,36 }));37#pragma warning restore CA2000 // Dispose objects before losing scope38 var playwrightBrowsersPath = Environment.GetEnvironmentVariable("PLAYWRIGHT_BROWSERS_PATH")!;39 // Create the Playwright browsers directory manually so we get a clear exception message if we don't have permission40 Directory.CreateDirectory(playwrightBrowsersPath);41 // Install the browser required by Playwright 42 Microsoft.Playwright.Program.Main(new[] { "install", "chromium" });43 var connectionString = Environment.GetEnvironmentVariable("AzureAppConfigurationConnectionString");44 if (string.IsNullOrEmpty(connectionString))45 {46 throw new InvalidOperationException("AzureAppConfigurationConnectionString app setting is required");47 }48 var configuration = new ConfigurationBuilder()49 .AddCatalogueScannerAzureAppConfiguration(connectionString, out var refresherSupplier)50 .Build();51 var localConfiguration = new ConfigurationBuilder()52 .AddEnvironmentVariables("CatalogueScanner:")53 .Build();54 ICatalogueScannerHostBuilder catalogueScannerHostBuilder = new CatalogueScannerHostBuilder(builder, configuration, localConfiguration);55 catalogueScannerHostBuilder.Services.SetConfigurationRefresher(refresherSupplier);56 catalogueScannerHostBuilder57 .AddPlugin<CoreCatalogueScannerPlugin>()58 .AddPlugin<OrchardCoreLocalisationCatalogueScannerPlugin>()59 .AddPlugin<SaleFinderCatalogueScannerPlugin>()60 .AddPlugin<WebScrapingCatalogueScannerPlugin>()61 .AddPlugin<WoolworthsOnlineCatalogueScannerPlugin>();62 }63 }64}...

Full Screen

Full Screen

PlaywrightVisualTestBuilder.cs

Source:PlaywrightVisualTestBuilder.cs Github

copy

Full Screen

...8 public class PlaywrightVisualTestBuilder : VisualTestBuilderBase9 {10 public PlaywrightVisualTestBuilder(IPage page, string name) :11 base(name,12 () => new Bitmap(new MemoryStream(page.ScreenshotAsync().Result)),13 () => new Bitmap(new MemoryStream(page.ScreenshotAsync(new PageScreenshotOptions14 {15 FullPage = true16 }).Result)))17 {}18 public PlaywrightVisualTestBuilder SetWebElement(IElementHandle element)19 {20 var rect = element.BoundingBoxAsync().Result;21 SetViewportRectangle(new Rectangle((int) rect.X, (int) rect.Y, (int) rect.Width, (int) rect.Height));22 return this;23 }24 public PlaywrightVisualTestBuilder SetIgnoredElements(List<(IElementHandle, Color)> ignoredElements)25 {26 var ignoredRectangles = new List<(Rectangle, Color)>();27 foreach (var (element, color) in ignoredElements)28 {29 var rect = element.BoundingBoxAsync().Result;30 ignoredRectangles.Add((new Rectangle((int) rect.X, (int) rect.Y, (int) rect.Width, (int) rect.Height), color));31 }32 SetIgnoredRectangles(ignoredRectangles);33 return this;34 }35 }36}...

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Core;2using System;3using System.Collections.Generic;4using System.IO;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8{9 {10 static async Task Main(string[] args)11 {12 var playwright = await Playwright.CreateAsync();13 var browser = await playwright.Chromium.LaunchAsync();14 var page = await browser.NewPageAsync();15 var stream = await response.BodyAsync();16 var streamReader = new StreamReader(stream);17 var text = await streamReader.ReadToEndAsync();18 Console.WriteLine(text);19 }20 }21}22using Microsoft.Playwright.Core;23using System;24using System.Collections.Generic;25using System.IO;26using System.Linq;27using System.Text;28using System.Threading.Tasks;29{30 {31 static async Task Main(string[] args)32 {33 var playwright = await Playwright.CreateAsync();34 var browser = await playwright.Chromium.LaunchAsync();35 var page = await browser.NewPageAsync();36 var stream = await response.BodyAsync();37 var streamReader = new StreamReader(stream);38 var text = await streamReader.ReadToEndAsync();39 Console.WriteLine(text);40 }41 }42}43[PlaywrightTest.zip](

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1var stream = await page.ScreenshotStreamAsync();2var bytes = new byte[stream.Length];3stream.Read(bytes, 0, (int)stream.Length);4File.WriteAllBytes("screenshot.png", bytes);5using (var stream = await page.ScreenshotStreamAsync())6{7 using (FileStream fileStream = new FileStream("screenshot.png", FileMode.Create))8 {9 await stream.CopyToAsync(fileStream);10 }11}12var stream = await page.ScreenshotStreamAsync();13var bytes = new byte[stream.Length];14stream.Read(bytes, 0, (int)stream.Length);15File.WriteAllBytes("screenshot.png", bytes);16using (var stream = await page.ScreenshotStreamAsync())17{18 using (FileStream fileStream = new FileStream("screenshot.png", FileMode.Create))19 {20 await stream.CopyToAsync(fileStream);21 }22}23var stream = await page.ScreenshotStreamAsync();24var bytes = new byte[stream.Length];25stream.Read(bytes, 0, (int)stream.Length);26File.WriteAllBytes("screenshot.png", bytes);27using (var stream = await page.ScreenshotStreamAsync())28{29 using (FileStream fileStream = new FileStream("screenshot.png", FileMode.Create))30 {31 await stream.CopyToAsync(fileStream);32 }33}34var stream = await page.ScreenshotStreamAsync();35var bytes = new byte[stream.Length];36stream.Read(bytes, 0, (int)stream.Length);37File.WriteAllBytes("screenshot.png", bytes);38using (var stream = await page.ScreenshotStreamAsync())39{40 using (FileStream fileStream = new FileStream("screenshot.png", FileMode.Create))41 {42 await stream.CopyToAsync(fileStream);43 }44}45var stream = await page.ScreenshotStreamAsync();46var bytes = new byte[stream.Length];47stream.Read(bytes, 0

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Core;2using Microsoft.Playwright.Core.Stream;3using System;4using System.Collections.Generic;5using System.IO;6using System.Linq;7using System.Text;8using System.Threading.Tasks;9{10 {11 public static async Task Main(string[] args)12 {13 var path = Path.Combine(Directory.GetCurrentDirectory(), "test.pdf");14 using var stream = new FileStream(path, FileMode.Create);15 await stream.WriteAsync(Encoding.ASCII.GetBytes("Hello World"));16 await stream.FlushAsync();17 var streamReader = new StreamReader(stream);18 Console.WriteLine(streamReader.ReadToEnd());19 Console.WriteLine("File created at : " + path);20 Console.ReadLine();21 }22 }23}24using Microsoft.Playwright.Core;25using Microsoft.Playwright.Core.Stream;26using System;27using System.Collections.Generic;28using System.IO;29using System.Linq;30using System.Text;31using System.Threading.Tasks;32{33 {34 public static async Task Main(string[] args)35 {36 var path = Path.Combine(Directory.GetCurrentDirectory(), "test.pdf");37 using var stream = new FileStream(path, FileMode.Create);38 await stream.WriteAsync(Encoding.ASCII.GetBytes("Hello World"));39 await stream.FlushAsync();40 var streamReader = new StreamReader(stream);41 Console.WriteLine(streamReader.ReadToEnd());42 Console.WriteLine("File created at : " + path);43 Console.ReadLine();44 }45 }46}

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1var stream = await page.ScreenshotStreamAsync();2var screenshot = new Bitmap(stream);3screenshot.Save("screenshot.png");4var stream = await page.ScreenshotStreamAsync();5var screenshot = new Bitmap(stream.Stream);6screenshot.Save("screenshot.png");7var stream = await page.ScreenshotStreamAsync();8var screenshot = new Bitmap(stream.Stream);9screenshot.Save("screenshot.png");10var stream = await page.ScreenshotStreamAsync();11var screenshot = new Bitmap(stream);12screenshot.Save("screenshot.png");

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1var reader = new StreamReader(stream);2var content = await reader.ReadToEndAsync();3Console.WriteLine(content);4var content = await stream.ReadToEndAsync();5Console.WriteLine(content);6var reader = new StreamReader(stream);7var content = await reader.ReadToEndAsync();8Console.WriteLine(content);9var content = await stream.ReadToEndAsync();10Console.WriteLine(content);11var reader = new StreamReader(stream);12var content = await reader.ReadToEndAsync();13Console.WriteLine(content);14var content = await stream.ReadToEndAsync();15Console.WriteLine(content);16var reader = new StreamReader(stream);17var content = await reader.ReadToEndAsync();18Console.WriteLine(content);

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1var stream = await page.EvaluateHandleAsync("() => document.querySelector('#file').files[0]");2var buffer = await stream.AsStream().ReadAllBytesAsync();3File.WriteAllBytes(@"C:\Users\user\Downloads\file.txt", buffer);4var stream = await page.EvaluateHandleAsync("() => document.querySelector('#file').files[0]");5var buffer = await stream.AsStream().ReadAllBytesAsync();6File.WriteAllBytes(@"C:\Users\user\Downloads\file.txt", buffer);7var stream = await page.EvaluateHandleAsync("() => document.querySelector('#file').files[0]");8var buffer = await stream.AsStream().ReadAllBytesAsync();9File.WriteAllBytes(@"C:\Users\user\Downloads\file.txt", buffer);10var stream = await page.EvaluateHandleAsync("() => document.querySelector('#file').files[0]");11var buffer = await stream.AsStream().ReadAllBytesAsync();12File.WriteAllBytes(@"C:\Users\user\Downloads\file.txt", buffer);13var stream = await page.EvaluateHandleAsync("() => document.querySelector('#file').files[0]");14var buffer = await stream.AsStream().ReadAllBytesAsync();15File.WriteAllBytes(@"C:\Users\user\Downloads\file.txt", buffer);16var stream = await page.EvaluateHandleAsync("() => document.querySelector('#file').files[0]");17var buffer = await stream.AsStream().ReadAllBytesAsync();18File.WriteAllBytes(@"C:\Users\user\Downloads\file.txt", buffer);19var stream = await page.EvaluateHandleAsync("() => document.querySelector('#file').files[0]");20var buffer = await stream.AsStream().ReadAllBytesAsync();21File.WriteAllBytes(@"C:\Users\user\Downloads\file.txt", buffer);22var stream = await page.EvaluateHandleAsync("() => document.querySelector('#file').files[0]");23var buffer = await stream.AsStream().ReadAllBytesAsync();

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Core;2{3 {4 public async Task Test()5 {6 var stream = new Stream();7 var data = await stream.ReadAllAsync();8 }9 }10}11using Microsoft.Playwright;12{13 {14 public async Task Test()15 {16 var data = await stream.ReadAllAsync();17 }18 }19}20using Microsoft.Playwright;21{22 {23 public async Task Test()24 {25 var data = await stream.ReadAllAsync();26 }27 }28}29using Microsoft.Playwright;30{31 {32 public async Task Test()33 {34 var data = await stream.ReadAllAsync();35 }36 }37}38using Microsoft.Playwright;39{40 {41 public async Task Test()42 {43 var data = await stream.ReadAllAsync();44 }45 }46}47using Microsoft.Playwright;48{49 {50 public async Task Test()51 {

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful