/// <summary> /// Encapsulate the login flow with <see cref="EmbedIOAuthServer"/>, useful for console application. /// </summary> public async Task Login() { var server = new EmbedIOAuthServer(new Uri(_config.CallbackUrl), _config.CallbackPort); await server.Start(); var auth = new TaskCompletionSource(); server.AuthorizationCodeReceived += async(_, response) => { await CompleteLogin(response.Code); auth.SetResult(); }; var result = await TryLogin(); await result.IfSomeAsync(async url => { BrowserUtil.Open(new Uri(url)); await auth.Task; }); await server.Stop(); server.Dispose(); }
public void CanLoginLocallyAfterChangingEmail() { var firstEmail = "*****@*****.**"; var secondEmail = "*****@*****.**"; var password = "******"; using (var site = new KeyHubWebDriver()) { SiteUtil.CreateLocalAccount(site, firstEmail, password); using (var browser = BrowserUtil.GetBrowser()) { browser.Navigate().GoToUrl(site.UrlFor("/")); SiteUtil.SubmitLoginForm(browser, firstEmail, password); browser.Navigate().GoToUrl(site.UrlFor("/")); browser.FindElementByCssSelector("a[href^='/Account']").Click(); browser.FindElementByCssSelector("a[href^='/Account/Edit']").Click(); var emailForm = browser.FindElementByCssSelector("#Email"); emailForm.Clear(); emailForm.SendKeys(secondEmail); browser.FindElementByCssSelector("input[value='Save']").Click(); // Ensure the change saves by waiting for the browser to return to the account edit page browser.FindElementByCssSelector("a[href^='/Account/Edit']"); } using (var browser = BrowserUtil.GetBrowser()) { browser.Navigate().GoToUrl(site.UrlFor("/")); SiteUtil.SubmitLoginForm(browser, secondEmail.ToUpper(), password); } } }
public void UseStyle(DynamicWorkItemSixStyle style) { switch (style) { case DynamicWorkItemSixStyle.FourLastHyperLink: this.tbkAfterNameTwo.TextTrimming = TextTrimming.WordEllipsis; this.tbkAfterNameTwo.HorizontalAlignment = HorizontalAlignment.Left; this.tbkAfterNameTwo.Style = (base.FindResource("TitleStyle") as Style); this.tbkAfterNameTwo.MouseLeftButtonDown += delegate { BrowserUtil.OpenHyperlinkHandler(this.urlFour); }; this.tbkAfterToNameFour.TextTrimming = TextTrimming.WordEllipsis; this.tbkAfterToNameFour.HorizontalAlignment = HorizontalAlignment.Left; this.tbkAfterToNameFour.Style = (base.FindResource("TitleStyle") as Style); this.tbkAfterToNameFour.MouseLeftButtonDown += delegate { BrowserUtil.OpenHyperlinkHandler(this.urlSix); }; break; case DynamicWorkItemSixStyle.LastHyperLink: this.tbkAfterNameTwo.Foreground = new SolidColorBrush(Color.FromRgb(0, 109, 131)); this.tbkAfterToNameFour.TextTrimming = TextTrimming.WordEllipsis; this.tbkAfterToNameFour.HorizontalAlignment = HorizontalAlignment.Left; this.tbkAfterToNameFour.Style = (base.FindResource("TitleStyle") as Style); this.tbkAfterToNameFour.MouseLeftButtonDown += delegate { BrowserUtil.OpenHyperlinkHandler(this.urlSix); }; break; } }
public static async Task Main() { _server = new EmbedIOAuthServer( new Uri("http://localhost:5000/callback"), 5000, Assembly.GetExecutingAssembly(), "Example.CLI.CustomHTML.Resources.custom_site" ); await _server.Start(); _server.AuthorizationCodeReceived += OnAuthorizationCodeReceived; var request = new LoginRequest(_server.BaseUri, clientId, LoginRequest.ResponseType.Code) { Scope = new List <string> { UserReadEmail } }; Uri uri = request.ToUri(); try { BrowserUtil.Open(uri); } catch (Exception) { Console.WriteLine("Unable to open URL, manually open: {0}", uri); } Console.ReadKey(); }
/// <summary> /// Authenticates a FitBit user using the FitBit Web API. /// </summary> /// <returns> A FitBit Authentication token </returns> public async Task <FitBitAuthenticationToken> GetFitBitAuthToken() { await FitBitAuthServer.Start(); var exchangeToken = string.Empty; var authTokenAsString = string.Empty; FitBitAuthServer.AuthorizationCodeReceived += async(sender, response) => { await StravaAuthServer.Stop(); exchangeToken = response.Code; var client = new RestClient("https://api.fitbit.com/oauth2/token?client_id=22CCZ8&grant_type=authorization_code&redirect_uri=http://localhost:5002/fitbittoken"); var request = new RestRequest(Method.POST); request.AddHeader("Authorization", "Basic MjJDQ1o4OmQ3M2YzMzhiNzEyMWQzNDdkYTM2YmU5NTAwMGM5NTli"); request.AddParameter("code", exchangeToken); IRestResponse accessTokenResponse = client.Execute(request); fitBitAuthToken = JsonConvert.DeserializeObject <FitBitAuthenticationToken>(accessTokenResponse.Content); }; var authTokenUri = new Uri("https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=22CCZ8&redirect_uri=http://localhost:5002/fitbittoken&scope=activity%20heartrate"); BrowserUtil.Open(authTokenUri); Task.Delay(20000).Wait(); return(fitBitAuthToken); }
virtual public async Task <WebClientStringResult> GetString(WebRequest request) { logger.Debug(string.Format("IWebClient.GetString(Url:{0})", request.Url)); var result = await Run(request); WebClientStringResult stringResult = Mapper.Map <WebClientStringResult>(result); Encoding encoding = null; if (request.Encoding != null) { encoding = request.Encoding; } else if (result.Headers.ContainsKey("content-type")) { Regex CharsetRegex = new Regex(@"charset=([\w-]+)", RegexOptions.Compiled); var CharsetRegexMatch = CharsetRegex.Match(result.Headers["content-type"][0]); if (CharsetRegexMatch.Success) { var charset = CharsetRegexMatch.Groups[1].Value; try { encoding = Encoding.GetEncoding(charset); } catch (Exception ex) { logger.Error(string.Format("IWebClient.GetString(Url:{0}): Error loading encoding {0} based on header {1}: {2}", request.Url, charset, result.Headers["content-type"][0], ex)); } } else { logger.Error(string.Format("IWebClient.GetString(Url:{0}): Got header without charset: {0}", request.Url, result.Headers["content-type"][0])); } } if (encoding == null) { logger.Error(string.Format("IWebClient.GetString(Url:{0}): No encoding detected, defaulting to UTF-8", request.Url)); encoding = Encoding.UTF8; } string decodedContent = null; if (result.Content != null) { decodedContent = encoding.GetString(result.Content); } stringResult.Content = decodedContent; logger.Debug(string.Format("IWebClient: Returning {0} => {1}", result.Status, (result.IsRedirect ? result.RedirectingTo + " " : "") + (decodedContent == null ? "<NULL>" : decodedContent))); string[] server; if (stringResult.Headers.TryGetValue("server", out server)) { if (server[0] == "cloudflare-nginx") { stringResult.Content = BrowserUtil.DecodeCloudFlareProtectedEmailFromHTML(stringResult.Content); } } return(stringResult); }
/// <summary> /// Gets an authentication token from the strava API. /// </summary> /// <returns> A Strava Authentication token</returns> public async Task <StravaAuthenticationToken> GetStravaAuthToken() { await StravaAuthServer.Start(); var exchangeToken = string.Empty; var authTokenAsString = string.Empty; // Temporary auth server lsitens for Strava callback. StravaAuthServer.AuthorizationCodeReceived += async(sender, response) => { await StravaAuthServer.Stop(); exchangeToken = response.Code; var client = new RestClient("https://www.strava.com/oauth/token?client_id=61391&client_secret=8b0eb19e37bbbeffc8b8ba75efdb1b7f9c2cfc95&grant_type=authorization_code"); var request = new RestRequest(Method.POST); request.AddParameter("code", exchangeToken); IRestResponse accessTokenResponse = client.Execute(request); stravaAuthToken = JsonConvert.DeserializeObject <StravaAuthenticationToken>(accessTokenResponse.Content); }; // Open page for login request var authTokenUri = new Uri("http://www.strava.com/oauth/authorize?client_id=61391&response_type=code&redirect_uri=http://localhost:5001/stravatoken&approval_prompt=force&scope=activity:read_all"); BrowserUtil.Open(authTokenUri); Task.Delay(20000).Wait(); return(stravaAuthToken); }
public void CanLoginLocallyAfterChangingPassword() { var email = "*****@*****.**"; var firstPassword = "******"; var secondPassword = "******"; using (var site = new KeyHubWebDriver()) { SiteUtil.CreateLocalAccount(site, email, firstPassword); using (var browser = BrowserUtil.GetBrowser()) { browser.Navigate().GoToUrl(site.UrlFor("/")); SiteUtil.SubmitLoginForm(browser, email, firstPassword); browser.Navigate().GoToUrl(site.UrlFor("/")); browser.FindElementByCssSelector("a[href^='/Account']").Click(); browser.FindElementByCssSelector("a[href^='/Account/ChangePassword']").Click(); browser.FindElementByCssSelector("#OldPassword").SendKeys(firstPassword); browser.FindElementByCssSelector("#NewPassword").SendKeys(secondPassword); browser.FindElementByCssSelector("#ConfirmPassword").SendKeys(secondPassword); browser.FindElementByCssSelector("input[type='submit']").Click(); // Ensure the change saves by waiting for the browser to return to the account edit page browser.FindElementByCssSelector("a[href^='/Account/Edit']"); } using (var browser = BrowserUtil.GetBrowser()) { browser.Navigate().GoToUrl(site.UrlFor("/")); SiteUtil.SubmitLoginForm(browser, email, secondPassword); } } }
public async void StartAuthentification() { // Validate config values if (_authConfig.RedirectUri == string.Empty && _authConfig.ServerPort <= 0) { // Problem with user's config, use default values _authConfig.RedirectUri = "http://localhost:5000/callback"; _authConfig.ServerPort = 5000; return; } // Start server _server = new EmbedIOAuthServer(new Uri(_authConfig.RedirectUri), _authConfig.ServerPort); await _server.Start(); // Await token recieved _server.ImplictGrantReceived += this.OnImplicitGrantReceived; // Create request LoginRequest request = new LoginRequest(_server.BaseUri, _authConfig.ClientID, LoginRequest.ResponseType.Token) { Scope = _authConfig.APIScopes, }; BrowserUtil.Open(request.ToUri()); }
private async Task LoginToSpotify(TaskCompletionSource <bool> tcs) { Server = new EmbedIOAuthServer(new Uri("http://localhost:5000/callback"), 5000); await Server.Start(); Server.ImplictGrantReceived += async(object sender, ImplictGrantResponse response) => { await Server.Stop(); if (response.AccessToken != null) { Spotify = new SpotifyClient(response.AccessToken); Profile = await Spotify.UserProfile.Current(); tcs.SetResult(Spotify != null); } else { Log("Error when attempting to log in"); tcs.SetResult(false); } }; var request = new LoginRequest(Server.BaseUri, SpotifySecrets.CLIENT_ID, LoginRequest.ResponseType.Token) { Scope = new List <string> { Scopes.UserLibraryRead, Scopes.PlaylistModifyPublic } }; BrowserUtil.Open(request.ToUri()); }
public static async Task StartRemote(Action <SpotifyClient> onComplete) { (string verifier, string challenge) = PKCEUtil.GenerateCodes(); m_AuthServer = new EmbedIOAuthServer(m_CallbackUri, 5000); await m_AuthServer.Start(); m_AuthServer.AuthorizationCodeReceived += async(sender, response) => { await m_AuthServer.Stop(); PKCETokenResponse token = await new OAuthClient().RequestToken( new PKCETokenRequest(m_ClientId, response.Code, m_AuthServer.BaseUri, verifier) ); File.WriteAllText(m_TokenPath, JsonConvert.SerializeObject(token)); StartCached(onComplete); }; var request = new LoginRequest(m_AuthServer.BaseUri, m_ClientId, LoginRequest.ResponseType.Code) { CodeChallenge = challenge, CodeChallengeMethod = "S256", Scope = new List <string> { Scopes.PlaylistModifyPublic } }; Uri uri = request.ToUri(); BrowserUtil.Open(uri); }
public void VendorCanRenameAndRemovePrivateKeys() { using (var site = new KeyHubWebDriver()) { var scenario = new WithAVendorScenario(); scenario.Setup(site); using (var browser = BrowserUtil.GetBrowser()) { browser.Navigate().GoToUrl(site.UrlFor("/")); SiteUtil.SubmitLoginForm(browser, scenario.UserEmail, scenario.UserPassword); var privateKeyName = VendorUtil.CreatePrivateKey(browser, scenario.VendorName); var privateKeyRow = browser.FindElementByXPath("//td[contains(text(),'" + privateKeyName + "')]/ancestor::tr"); privateKeyRow.FindElement((By.CssSelector("a[href^='/PrivateKey/Edit']"))).Click(); var nameInput = browser.FindElementByCssSelector("input#PrivateKey_DisplayName"); nameInput.Clear(); nameInput.SendKeys("second name"); browser.FindElementByCssSelector("form[action^='/PrivateKey/Edit'] input[type='submit']").Click(); privateKeyRow = browser.FindElementByXPath("//td[contains(text(),'second name')]/ancestor::tr"); Assert.Equal(1, browser.FindElementsByCssSelector(".private-key-list").Count()); Assert.Equal(1, browser.FindElementsByCssSelector(".private-key-list tbody tr").Count()); privateKeyRow.FindElement((By.CssSelector("a[href^='/PrivateKey/Remove']"))).Click(); browser.FindElementByCssSelector("form[action^='/PrivateKey/Remove'] input[type='submit']").Click(); Assert.Equal(1, browser.FindElementsByCssSelector(".private-key-list").Count()); Assert.Equal(0, browser.FindElementsByCssSelector(".private-key-list tbody tr").Count()); } } }
public void VendorCanEditAFeature() { using (var site = new KeyHubWebDriver()) { var scenario = new WithAVendorScenario(); scenario.Setup(site); using (var browser = BrowserUtil.GetBrowser()) { browser.Navigate().GoToUrl(site.UrlFor("/")); SiteUtil.SubmitLoginForm(browser, scenario.UserEmail, scenario.UserPassword); VendorUtil.CreateFeature(browser, "first feature", scenario.VendorName); var featureRow = browser.FindElement(By.XPath("//td[contains(text(),'first feature')]/ancestor::tr")); featureRow.FindElement(By.CssSelector("a[href^='/Feature/Edit']")).Click(); var nameInput = browser.FindElementByCssSelector("#Feature_FeatureName"); nameInput.Clear(); nameInput.SendKeys("second name"); browser.FindElementByCssSelector("form[action^='/Feature/Edit'] input[type='submit']").Click(); browser.FindElementByCssSelector(".success"); browser.FindElement(By.XPath("//td[contains(text(),'second name')]")); } } }
private async Task Authorize() { Logger.LogInformation("Started the Spotify authorization process..."); Server = new EmbedIOAuthServer(new Uri(RedirectUri), SpotifyOptions.Value.AuthServerPort); await Server.Start(); Server.AuthorizationCodeReceived += OnAuthorizationCodeReceived; var loginRequest = new LoginRequest(Server.BaseUri, SpotifyOptions.Value.ClientId, LoginRequest.ResponseType.Code) { CodeChallengeMethod = "S256", CodeChallenge = Challenge, Scope = new[] { Scopes.UserReadCurrentlyPlaying } }; var uri = loginRequest.ToUri(); try { BrowserUtil.Open(uri); } catch (Exception) { Logger.LogCritical("Unable to open a browser. Please manually open: {0}", uri); } }
public void AdminShouldBeAbleToCreateUsers() { var username = "******"; var password = "******"; using (var site = new KeyHubWebDriver()) { using (var browser = BrowserUtil.GetBrowser()) { browser.Navigate().GoToUrl(site.UrlFor("/Account/Create")); SiteUtil.SubmitLoginForm(browser, "admin", "password"); browser.FindElementByCssSelector("#User_Email").SendKeys(username); browser.FindElementByCssSelector("#User_Password").SendKeys(password); browser.FindElementByCssSelector("#User_ConfirmPassword").SendKeys(password); browser.FindElementByCssSelector("input[value='Save']").Click(); var successMessage = browser.FindElementByCssSelector(".success"); Assert.Contains("New user succesfully created", successMessage.Text); } using (var browser = BrowserUtil.GetBrowser()) { browser.Navigate().GoToUrl(site.UrlFor("/")); SiteUtil.SubmitLoginForm(browser, "admin", "password"); } } }
public void Setup(KeyHubWebDriver site, bool canDeleteManualDomainsOfLicense = true) { using (var browser = BrowserUtil.GetBrowser()) { base.Setup(site); browser.Navigate().GoToUrl(site.UrlFor("/")); SiteUtil.SubmitLoginForm(browser, UserEmail, UserPassword); VendorUtil.CreatePrivateKey(browser, VendorName); VendorUtil.CreateFeature(browser, "first feature", VendorName); VendorUtil.CreateFeature(browser, "second feature", VendorName); VendorUtil.CreateSku(browser, "first sku", VendorName, "first feature", canDeleteManualDomainsOfLicense); VendorUtil.CreateSku(browser, "second sku", VendorName, "second feature", canDeleteManualDomainsOfLicense); // Create a Customer var customerName = VendorUtil.CreateCustomer(browser); // Create a License VendorUtil.CreateLicense(browser, "first sku", customerName); VendorUtil.CreateLicense(browser, "second sku", customerName); } }
public static IWebDriver SetAppTestEnvironment(bool needToInitializeDriver = false) { if (driver == null) { BrowserUtil.CloseAllBrowsers(); if (Constant.TargetedBrowser.ToLower().Contains("ch")) { ChromeOptions options = new ChromeOptions(); string user = Environment.UserName; options.AddArguments("user-data-dir=C:\\Users\\" + user + "\\AppData\\Local\\Google\\Chrome\\User Data\\Default", "--disable-session-crashed-bubble"); try { driver = new ChromeDriver(Environment.CurrentDirectory, options); } catch (Exception ex) { throw new Exception(ex.Message + ex.StackTrace + ex.Source); } } else if (Constant.TargetedBrowser.ToLower().Contains("ie")) { driver = new InternetExplorerDriver(); } else { throw new Exception("Failed: Trgeted browser entry is not valid "); } } return(driver); }
public static IWebDriver CreateWebDriver(BrowserUtil browser, string pathDriver, bool headless) { IWebDriver webDriver = null; switch (browser) { case BrowserUtil.Firefox: FirefoxOptions optionsFF = new FirefoxOptions(); if (headless) { optionsFF.AddArgument("--headless"); } webDriver = new FirefoxDriver(pathDriver, optionsFF); break; case BrowserUtil.Chrome: ChromeOptions optionsChr = new ChromeOptions(); if (headless) { optionsChr.AddArgument("--headless"); } webDriver = new ChromeDriver(pathDriver, optionsChr); break; } return(webDriver); }
private static async Task StartAuthentication() { _server = new EmbedIOAuthServer(new Uri("http://localhost:5050/callback"), 5050); await _server.Start(); _server.AuthorizationCodeReceived += OnAuthorizationCodeReceived; var request = new LoginRequest(_server.BaseUri, clientId !, LoginRequest.ResponseType.Code) { Scope = new List <string> { UserReadEmail, UserReadPrivate, PlaylistReadPrivate, PlaylistReadCollaborative, UserLibraryRead, UserLibraryModify, UserReadCurrentlyPlaying, UserReadPlaybackPosition, UserReadPlaybackState } }; Uri uri = request.ToUri(); try { BrowserUtil.Open(uri); } catch (Exception) { Console.WriteLine("[AUTH] Unable to open URL, manually open: {0}", uri); } }
public override Control GetControl() { if (HtmlBrowser == null || HtmlBrowser.IsDisposed) { _lastNav = DateTime.UtcNow; BrowserUtil.SetBrowserEmulationMode(); HtmlBrowser = new WebBrowser { Dock = DockStyle.Fill, WebBrowserShortcutsEnabled = false, ScriptErrorsSuppressed = true }; HtmlBrowser.Navigate("about:blank"); while (HtmlBrowser.Document?.Body == null) { Application.DoEvents(); } HtmlBrowser.DocumentText = _printer.GetHtmlPage(); HtmlBrowser.DocumentCompleted += AfterPageLoad; HtmlBrowser.Navigating += BrowserNavigating; HtmlBrowser.Document.MouseMove += MouseOver; return(HtmlBrowser); } return(HtmlBrowser); }
public ElephantBet(string url, string userName, string password) { _browser = new BrowserUtil(); ChooseRoute(url); LogIn(userName, password); }
private void openFreenetMenuItem_Click(object sender = null, EventArgs e = null) { Start(); BeginInvoke(new Action(() => { var fproxyListening = false; var showSlowOpen = Settings.Default.ShowSlowOpenTip; var openArgs = e as OpenArgs; if (openArgs != null) { showSlowOpen = openArgs.ShowSlow; } /* * TODO: Programatic way to get loopback address? This would not support IPv6. * Use FProxy bind interface? */ var loopback = new IPAddress(new byte[] { 127, 0, 0, 1 }); var timer = new Stopwatch(); using (var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { timer.Start(); while (_node.IsRunning()) { try { sock.Connect(loopback, _node.FProxyPort); fproxyListening = true; break; } catch (SocketException ex) { Log.Debug("Connecting got error: {0}", Enum.GetName(typeof(SocketError), ex.SocketErrorCode)); Thread.Sleep(SocketPollInterval); } // Show a startup notification if it's taking a while. if (showSlowOpen && timer.ElapsedMilliseconds > SlowOpenThreshold) { trayIcon.BalloonTipText = strings.FreenetStarting; trayIcon.ShowBalloonTip(SlowOpenTimeout); showSlowOpen = false; } } timer.Stop(); } if (fproxyListening) { Log.Debug("FProxy listening after {0}", timer.Elapsed); BrowserUtil.Open(new Uri(String.Format("http://localhost:{0:d}", _node.FProxyPort)), true); } })); }
private void TextBlockMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { TextBlock text = e.Source as TextBlock; if (text.Tag != null) { BrowserUtil.OpenNoticBrowserHandler(text.Tag.ToString()); } }
public FrmLegendsViewer(string file = "") { InitializeComponent(); // Start local http server LocalFileProvider.Run(); Coordinator = new LvCoordinator(this); FileLoader = summaryTab1.CreateLoader(); FileLoader.AfterLoad += (sender, args) => AfterLoad(args.Arg); Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); _version = fvi.FileVersion; var versionNumbers = _version.Split('.'); if (versionNumbers.Length > 3) { _version = $"{versionNumbers[0]}.{versionNumbers[1]}.{versionNumbers[2]}"; } Text = "Legends Viewer"; lblVersion.Text = "v" + _version; lblVersion.Left = scWorld.Panel2.ClientSize.Width - lblVersion.Width - 3; tcWorld.Height = scWorld.Panel2.ClientSize.Height; Browser = new DwarfTabControl(World) { Location = new Point(0, btnBack.Bottom + 3) }; Browser.Size = new Size(scWorld.Panel2.ClientSize.Width - Browser.Left, scWorld.Panel2.ClientSize.Height - Browser.Top); Browser.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right; scWorld.Panel2.Controls.Add(Browser); foreach (TabPage tp in tcWorld.TabPages) { foreach (TabControl tabControl in tp.Controls.OfType <TabControl>()) { HideTabControlBorder(tabControl); } } if (file != "") { _commandFile = file; } foreach (var v in tcWorld.TabPages.OfType <TabPage>().SelectMany(x => x.Controls.OfType <BaseSearchTab>())) { v.Coordinator = Coordinator; } BrowserUtil.SetBrowserEmulationMode(); Browser.Navigate(ControlOption.ReadMe); }
private static void VendorManuallyCreatesTransaction(Action <RemoteWebDriver> vendorActionBeforeCreatingTransaction, Action <RemoteWebDriver> transactionSubmitHandler) { var vendorScenario = new WithAVendorDBScenario(); var vendorEmail = "*****@*****.**"; var vendorPassword = "******"; using (var site = new KeyHubWebDriver()) { string editVendorUserUrl = null; SiteUtil.CreateLocalAccount(site, vendorEmail, vendorPassword, firstBrowser => { firstBrowser.FindElementByCssSelector("a[href='/Account/LogOff']"); firstBrowser.Navigate().GoToUrl(site.UrlFor("/Account")); editVendorUserUrl = firstBrowser.FindElementByCssSelector("a[href^='/Account/Edit']").GetAttribute("href"); }); // Log in as admin to give the new vendor account vendor permissions using (var browser = BrowserUtil.GetBrowser()) { browser.Navigate().GoToUrl(site.UrlFor(editVendorUserUrl)); SiteUtil.SubmitLoginForm(browser, "admin", "password"); AdminUtil.CreateAccountRightsFor(browser, vendorEmail, ObjectTypes.Vendor, vendorScenario.VendorName); } using (var browser = BrowserUtil.GetBrowser()) { browser.Navigate().GoToUrl(site.UrlFor("/")); SiteUtil.SubmitLoginForm(browser, vendorEmail, vendorPassword); vendorActionBeforeCreatingTransaction(browser); browser.Navigate().GoToUrl(site.UrlFor("/")); browser.FindElementByCssSelector("a[href='/Transaction/Create']").Click(); SiteUtil.SetValueForChosenJQueryControlMulti(browser, "div#Transaction_SelectedSKUGuids_chzn", vendorScenario.SkuCode); browser.FindElementByCssSelector("form[action^='/Transaction/Create'] input[type='submit']").Click(); transactionSubmitHandler(browser); var appKeyValue = GetAppKeyFromTransactionCompletePage(browser); LicenseValidatorTests.AssertRemoteValidationCheckPasses( site, "example.com", appKeyValue, vendorScenario.FeatureCode, vendorScenario.PublicKeyXml); } } }
public void CanManageVendorCredentials() { using (var site = new KeyHubWebDriver()) { using (var browser = BrowserUtil.GetBrowser()) { // Log in as pre-created admin user browser.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(3)); browser.Navigate().GoToUrl(site.UrlFor("/")); SiteUtil.SubmitLoginForm(browser, "admin", "password"); // Create a vendor AdminUtil.CreateVendor(browser); // Create a VendorCredential for the vendor browser.FindElementByCssSelector("a[href^='/VendorCredential/Create']").Click(); var firstVendorCredentialName = "first vendor secret name"; var firstVendorCredentialValue = "vendor secret shared secret"; FillVendorCredentialForm(browser, firstVendorCredentialName, firstVendorCredentialValue); browser.FindElementByCssSelector("form[action^='/VendorCredential/Create'] input[type=submit]").Click(); // Make sure the VendorCredential was created, and edit it. var editButton = browser.FindElementByCssSelector("a[href^='/VendorCredential/Edit']"); Assert.Contains(firstVendorCredentialName, browser.PageSource); editButton.Click(); AssertVendorCredentialFormValues(browser, firstVendorCredentialName, firstVendorCredentialValue); var secondVendorCredentialName = "second vendor secret name"; var secondVendorCredentialValue = "second vendor secret"; FillVendorCredentialForm(browser, secondVendorCredentialName, secondVendorCredentialValue); browser.FindElementByCssSelector("form[action^='/VendorCredential/Edit'] input[type=submit]").Click(); // Check the VendorCredential edit page to ensure the edit saved editButton = browser.FindElementByCssSelector("a[href^='/VendorCredential/Edit']"); Assert.DoesNotContain(firstVendorCredentialName, browser.PageSource); Assert.Contains(secondVendorCredentialValue, browser.PageSource); editButton.Click(); AssertVendorCredentialFormValues(browser, secondVendorCredentialName, secondVendorCredentialValue); // Return to the Vendor edit page browser.FindElementByCssSelector("a[href^='/Vendor/Details']").Click(); // Remove the VendorCredential var removeButton = browser.FindElementByCssSelector("a[href^='/VendorCredential/Remove']"); removeButton.Click(); browser.FindElementByCssSelector("form[action^='/VendorCredential/Remove'] input[type=submit]").Click(); browser.FindElementByCssSelector(".success"); Assert.DoesNotContain(firstVendorCredentialName, browser.PageSource); Assert.DoesNotContain(secondVendorCredentialValue, browser.PageSource); } } }
private void hlMessageTitle_Click(object sender, System.EventArgs e) { try { BrowserUtil.OpenNoticBrowserHandler(this.link); } catch (System.Exception) { } }
/// <summary> /// Initiates the configuration object by loading all values from the app.config file. /// </summary> public Configuration() { _logTruncateAfterNumberOfFiles = ConfigUtil.GetOrCreateAppSetting(LOG_TRUNCATE_AFTER_NUMBER_OF_FILES_KEY, Constants.LOGS_TRUNCATE_AFTER_FILES); _lastUsedVersion = string.IsNullOrEmpty(ConfigUtil.GetOrCreateAppSetting(LAST_USED_VERSION_KEY)) ? null : new Version(ConfigUtil.GetOrCreateAppSetting(LAST_USED_VERSION_KEY)); _checkUpdatesOnStartup = ConfigUtil.GetOrCreateAppSetting(CHECK_UPDATES_ON_STARTUP_KEY, true); Browser systemBrowser = BrowserUtil.GetSystemDefaultBrowser(); _loadAllProperties = ConfigUtil.GetOrCreateAppSetting(LOAD_ALL_PROPERTIES_KEY, false); _logLevel = ConfigUtil.GetOrCreateAppSetting(LOG_LEVEL_KEY, LogLevel.Exception); }
/// <summary> /// Obtain a new Spotify token /// </summary> private static void ObtainToken() { var request = new LoginRequest(Server.BaseUri, CLIENT_ID, LoginRequest.ResponseType.Token) { Scope = new List <string> { Scopes.PlaylistModifyPrivate, Scopes.PlaylistModifyPublic, Scopes.PlaylistReadPrivate, Scopes.PlaylistReadCollaborative } }; BrowserUtil.Open(request.ToUri()); }
public void VendorCanManuallyCreateLicensedApplicationAndChangeItsSkus() { var vendorAndCustomerScenario = new VendorWithALicensedCustomerScenario(); using (var site = new KeyHubWebDriver()) { vendorAndCustomerScenario.Setup(site); var firstCustomerAppName = "customerApp.name1"; var secondCustomerAppName = "customerApp.name2"; using (var browser = BrowserUtil.GetBrowser()) { browser.Navigate().GoToUrl(site.UrlFor("/")); SiteUtil.SubmitLoginForm(browser, vendorAndCustomerScenario.UserEmail, vendorAndCustomerScenario.UserPassword); // Create a CustomerApp / Licensed Application browser.Navigate().GoToUrl(site.UrlFor("/")); browser.FindElementByCssSelector("a[href='/CustomerApp']").Click(); browser.FindElementByCssSelector("a[href='/CustomerApp/Create']").Click(); browser.FindElementByCssSelector("input#ApplicationName").SendKeys(firstCustomerAppName); SiteUtil.SetValueForChosenJQueryControlMulti(browser, "#SelectedLicenseGUIDs_chzn", "first sku"); browser.FindElementByCssSelector("form[action='/CustomerApp/Create'] input[type=submit]").Click(); browser.FindElementByCssSelector(".success"); AssertApplicationNameIs(browser, firstCustomerAppName); AssertApplicationSkuIs(browser, "first sku"); // Rename the customer app browser.FindElementByCssSelector("a[href^='/CustomerApp/Edit']").Click(); var nameElement = browser.FindElementByCssSelector("input#ApplicationName"); nameElement.Clear(); nameElement.SendKeys(secondCustomerAppName); browser.FindElementByCssSelector("form[action^='/CustomerApp/Edit'] input[type='submit']").Click(); browser.FindElementByCssSelector(".success"); AssertApplicationNameIs(browser, secondCustomerAppName); // Switch licenses on the customer app browser.FindElementByCssSelector("a[href^='/CustomerApp/Edit']").Click(); SiteUtil.SetValueForChosenJQueryControlMulti(browser, "#SelectedLicenseGUIDs_chzn", "second sku", clearExisting: true); browser.FindElementByCssSelector("form[action^='/CustomerApp/Edit'] input[type='submit']").Click(); browser.FindElementByCssSelector(".success"); AssertApplicationSkuIs(browser, "second sku"); // Remove the customer app browser.FindElementByCssSelector("a[href^='/CustomerApp/Remove']").Click(); browser.FindElementByCssSelector("form[action^='/CustomerApp/Remove'] input[type='submit']").Click(); browser.FindElementByCssSelector(".success"); Assert.Equal(0, browser.FindElementsByCssSelector("a[href^='/CustomerApp/Remove']").Count()); } } }