How do I grab and store URL using C# selenium - c#

I have a URL with multiple paths. For example:
https://stackoverflow.com/questions/120250
I want to grab the URLS entire path and save it, then I want to call the URL later to duplicate the URL with all the paths. URL path is dynamic.
So for I have attempted this
public Shared DuplicateTheChromeBrowser()
{
String selectLinkOpeninNewTab = (Keys.Alt + "d" + Keys.Enter);
var SavedURL = Driver.Instance.Url();
SavedURL.SendKeys(selectLinkOpeninNewTab);
return this;
}

Try this out. It saves the url of the page you go to or are on, then uses JS to create a new tab and send the URL from the original page to the new tab. Initbrowser() is my method for initiating an instance, so it its not necessarily part of the solution.
public Shared DuplicateTheChromeBrowser()
{
//Initiate Browser Instance(this is my method, initiate how you did in our code which isnt visible in your question)
IWebDriver driver = InitBrowser("chrome");
//Go to page
driver.Url = "https://stackoverflow.com/questions/120250?params=testparam";
//Save Current URL
var SavedUrl = driver.Url;
//Uses JS to open new tab
((IJavaScriptExecutor)driver).ExecuteScript("window.open();");
driver.SwitchTo().Window(driver.WindowHandles.Last());
//Changes Url of new tab to saved URL including param
driver.Url = SavedUrl;
}

Related

Redirecting Virtual User to Content Editor Programatically

I am trying to create a Virtual user with and redirect to content editor as below.
string userId = string.Format("{0}\\{1}", "sitecore", "testadmin");
var scUser = AuthenticationManager.BuildVirtualUser(userId, true);
scUser.RuntimeSettings.IsAdministrator = true;
scUser.RuntimeSettings.AddedRoles.Add(#"sitecore\Sitecore Client Authoring");
AuthenticationManager.Login(scUser);
string url = "/sitecore/shell/sitecore/content/Applications/Content Editor.aspx?id=%7b110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9%7d&la=en&fo=%7b110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9%7d";
url = string.IsNullOrEmpty(url) ? "/" : url;
HttpContext.Current.Response.Redirect(url, false);
But it always redirects the user to sitecore/login page.
Any idea what is the issue here?
Interesting. I'm not entirely sure that approach is a supported scenario. However, the Content Editor runs off the "shell" website, possibly that is your issue.
Try putting this code around your entire code block.
using(new SiteContextSwitcher("shell")) {
}
You need to change:
AuthenticationManager.Login(scUser);
to
AuthenticationManager.LoginVirtualUser(scUser);

How to verify that a new tab is opened in a browser with TestComplete using C#

I am testing a website. In the body of website has a URL. After clicking that URL it should be opened in a new tab, not in same window. After clicking the URL link it is opened in new tab browser. I have tested it manually.
I want to verify that feature by using TestComplete with C#Script. How to do it?
You can simulate a click to this link and then check whether the URL of the current page object has been changed and whether a new page object with the target URL has appeared.
function Test1()
{
var browser = Sys.Browser("firefox");
var numOfTabs = browser.FindAllChildren("ObjectType", "Page").toArray().length;
var page = browser.ToUrl("http://www.w3schools.com/html/tryit.asp?filename=tryhtml_links_target");
var pageUrl = page.Url;
frame = page.Panel(0).Panel(1).Panel(0).Panel(1).Frame("iframeResult");
frame.Link(0).Click();
if (page.Url != pageUrl)
Log.Error("The page's URL has been changed!");
if (browser.FindAllChildren("ObjectType", "Page").toArray().length == numOfTabs)
Log.Error("A new tab has not been opened!");
}

PhantomJS click link not working

I am trying to get the URL of the second page of a yellowpages result with the following code:
var driverService = PhantomJSDriverService.CreateDefaultService();
var driver = new PhantomJSDriver(driverService);
driver.Navigate().GoToUrl(new Uri("http://www.yellowpages.com/los-angeles-ca/pizza?g=Los+Angeles%2C+CA"));
string url = driver.Url;
var next = driver.FindElementByCssSelector(".next");
next.Click();
string newUrl = driver.Url;
The "next" link is found and clicked but I do not get the new URL after calling next.Click().
Other pages work fine. I am only having problems on yellowpages right now.
Any ideas?
Try this for clicking on the web element instead of using click():
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", next);
Make sure you have turned on console output, so you could see the exact error:
service.HideCommandPromptWindow = true;
I had similar problem, and when i turned on console output I noticed the following error: "can't find variable: __doPostBack".
In my case, that was because of site declined defaut Phantom's user agent, so I had to change it (based on this answer).

Invalid paths using CloudFront create invalidation in C#

I am trying to invalidate CloudFront objects in C#/.NET and gettign the following exception:
Your request contains one or more invalid invalidation paths.
My Function:
public bool InvalidateFiles(string[] arrayofpaths)
{
for (int i = 0; i < arrayofpaths.Length; i++)
{
arrayofpaths[i] = Uri.EscapeUriString(arrayofpaths[i]);
}
try
{
Amazon.CloudFront.AmazonCloudFrontClient oClient = new Amazon.CloudFront.AmazonCloudFrontClient(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, Amazon.RegionEndpoint.USEast1);
CreateInvalidationRequest oRequest = new CreateInvalidationRequest();
oRequest.DistributionId = ConfigurationManager.AppSettings["CloudFrontDistributionId"];
oRequest.InvalidationBatch = new InvalidationBatch
{
CallerReference = DateTime.Now.Ticks.ToString(),
Paths = new Paths
{
Items = arrayofpaths.ToList<string>(),
Quantity = arrayofpaths.Length
}
};
CreateInvalidationResponse oResponse = oClient.CreateInvalidation(oRequest);
oClient.Dispose();
}
catch
{
return false;
}
return true;
}
The array passed to the function contains a single Url like so:
images/temp_image.jpg
The image exists in the S3 bucket and loaded in the browser in the CloudFront URL.
What am I doing wrong?
You invalidation file paths need a / at the front of the string.
If you are in doubt, you can log onto AWS Management, go to Cloudfront, select the distribution you are trying to invalidate files from, select Distribution setting and go to the Invalidations tab.
You can then create validations manually, which allows you to check that your paths are correct.
When you send invalidation request to some object in CloudFront, you still can see your picture in the browser in the CloudFront URL even when invalidation completed, because invalidation does not delete object from S3 bucket and with new request to this image from you browser CloudFront again cached these URl to images/temp_image.jpg in edge locations.
Invalidation of object will be seen, when you update image with the same name.
Your Invalidation function is correct.
Have you tried adding the forward slash at the beginning of the path? (/images/temp_image.jpg)

Get the Control on a page by passing URL? Also get the current page URL?

My Requirement: I want to know which page I am currently in so that if any test fails I want to pass the current page's URL to a method and get the home button link. Ultimately navigating to the home link in case of any exception.
Is there a way to achieve it ?
The URL should be in the address bar of the browser, just read it out of there.
One way of reading out the value is to record an assertion on the value in the address bar, then copy the part of the code in the recorded assertion method that accesses the value.
Another way is to use the cross-hairs tool to select the address area, then (click the double-chevron icon to open the left hand pane and) add the UI control for the selected area. Then access the value.
This will return the top Browser:
BrowserWindow bw = null;
try
{
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.AllThreads;
var browser = new BrowserWindow() /*{ TechnologyName = "MSAA" }*/;
PropertyExpressionCollection f = new PropertyExpressionCollection();
f.Add("TechnologyName", "MSAA");
f.Add("ClassName", "IEFrame");
f.Add("ControlType", "Window");
browser.SearchProperties.AddRange(f);
UITestControlCollection coll = browser.FindMatchingControls();
// get top of browser stack
foreach (BrowserWindow win in coll)
{
bw = win;
break;
}
String url = bw.Uri.ToString(); //this is the value you want to save
}
catch (Exception e)
{
throw new Exception("Exception getting active (top) browser: - ------" + e.Message);
}
finally
{
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.UIThreadOnly;
}

Categories