EdgeDriver - Cannot change window size in Edge - c#

I am using the EdgeDriver for running automation tests on my browser (Edge 38.14393.0.0). My tests are in C#, so I am using the .NET driver:
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Edge;
var options = new EdgeOptions();
options.PageLoadStrategy = EdgePageLoadStrategy.Normal;
RemoteWebDriver driver = return new EdgeDriver(Environment.CurrentDirectory, options, TimeSpan.FromSeconds(60));
driver.SetDocumentSize(new Size(800, 600)); // HERE!
The error
This code is the one I run at the beginning of the test. And it fails at the last line with:
Class Initialization method
Web.TestSuite.UIRendering.RenderingTestSuiteEdge.TestClassInitialize
threw exception. System.InvalidOperationException:
System.InvalidOperationException: A window size operation failed
because the window is not currently available.
With this stack trace:
OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse) in c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs: line 1126
OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters) in c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs: line 920
OpenQA.Selenium.Remote.RemoteWindow.set_Size(Size value) in ...
FYI Be aware that I have other tests running on Chrome and IE11 using their respective drivers. When I call SetDocumentSize on those, I get no errors.
Open issues
I could find some open issues related to this problem:
https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9340417/
https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8778306/
Questions
So, these are my questions:
Has anybody succeeded in setting the window size in Edge?
Is this problem I am hitting a known issue? If so, is it fixed? The referenced issues (which look similar) are still open and no status provided.
Is there any workaround?

Try one of those for C#:
driver.Manage().Window.Size = new Size(1920, 1080);
driver.Manage().Window.Maximize();
Although I encounter that error for different reason (like the one here -> https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/10319887/).
Now I kill all process of the driver & edge before each test so hopefully it will be resolved like that:
try
{
foreach (var process in Process.GetProcessesByName("MicrosoftWebDriver"))
{
process.Kill();
}
foreach (var process in Process.GetProcessesByName("MicrosoftEdge"))
{
process.Kill();
}
}
catch (Exception)
{
}
Also if you run them on remote machine via RDP for example it will make the same error when you close the RDP. This is the current workaround that I found for it:
Create a batch file with this code:
for /f "skip=1 tokens=3" %%s in ('query user %USERNAME%') do (
%windir%\System32\tscon.exe %%s /dest:console
)
Create a desktop shortcut to this file. To do this, right-click the batch
file and select Send to | Desktop (create shortcut).
In the shortcut properties, click Advanced and select Run as administrator.
Now, when you need to disconnect from Remote Desktop, double-click this shortcut on the remote computer (in the Remote Desktop window).
Thanks to https://support.smartbear.com/testcomplete/docs/testing-with/running/via-rdp/keeping-computer-unlocked.html for the script.

This works for me:
driver.manage().window().setSize(new Dimension(1250, 720));

Related

Execute Powershell cmdlet that have user prompts within C# WPF application

I am attempting to create a WPF application that will execute some powershell commands using a 3rd party module (ShareGate). After extensive research and banging my head on the keyboard, I have gotten the application to at least execute the cmdlets I have asked for. The cmdlet in question, if run in powershell, will prompt the user to log into a web service using edge I believe. When running the cmdlet from the application, it throws an error which is misleading "during the last update edge was not able to be installed...."
I think that this error is coming up because this implementation isn't allowing powershell to pop open the browser like it does within a powershell window.
My question is this: "How can I redirect the user prompt to come up within the wpf application? or can I?"
here is my method:
public Task StartSGMigrations(IProgress<string> progress)
{
var sharegatePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Apps\\ShareGate\\Sharegate.Automation.dll";
if (client != null)
{
try
{
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new string[] { sharegatePath });
using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss))
{
myRunSpace.Open();
using (PowerShell powershell = PowerShell.Create())
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
powershell.AddScript("New-CopySettings -OnContentItemExists IncrementalUpdate");
powershell.AddScript("Connect-box -email " + _admin + " -admin");
powershell.AddScript("Connect-Site -Url \"https://xxxx-admin.sharepoint.com\" -Browser");
powershell.Runspace = myRunSpace;
var results = powershell.Invoke();
var errors = myRunSpace.SessionStateProxy.PSVariable.GetValue("Error");
foreach (var result in results)
{
progress.Report(result.ToString() + Environment.NewLine);
}
}
myRunSpace.Close();
}
}
catch (Exception ex)
{
progress.Report(ex.Message);
}
}
else
{
progress.Report("not connected to Box");
}
return Task.CompletedTask;
}
}
This will be fairly tricky to do if the commands you are calling do not support noninteractive execution.
What's going on:
Your application using the PowerShell api to call your scripts. This part's good. The problem is your scripts are using functionality of the PowerShell host (possibly prompting for credentials). Because the runspace is not associated with a host, any interactive capabilities will simply fail.
So you'd need to attach a host in order for it to work as expected (and that host would need to work the same as PowerShell.exe/pwsh.exe for whatever purposes your underlying cmdlets need).
If there were lots of implementations of a PowerShell host in the wild, I'd link you to them. Unfortunately, there are not. So unless you want to go down a deep rabbit hole, I'd suggest these alternatives:
If the cmdlet supports providing credentials directly, try this
If it does not, see if it "persists" credentials for a given user. (That is, open up a shell, login, close the shell, open another shell, and see if you can use the module without providing credentials).
If credentials do persist (and you can't do option 1), you should be able to call PowerShell.exe/pwsh.exe once to log in, and then load code normally.
If the credentials do not persist, you're stuck in a much more unfortunate situation, leaving you with paths 3,4, or 5:
Call powershell.exe/pwsh.exe (hopefully in in a minimized window) and send the output back via JSON or CLIXML.
Go down the rabbit hole and build yourself a host.
Beg the cmdlet authors to better support noninteractive scenarios.
Between those options, I'd start with the last one.
Best of luck.

Microsoft Edge not stay open when run by Microsoft WebDriver

My OS Build: 16299.309 so
I download MS WebDriver, ver. 5.16299 release: 16299, from https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
My SetEdgeDriver() method in C#:
private IWebDriver SetEdgeDriver()
{
try
{
var path = #"C:\FolderWhereMSWebDriverExeFile ";
var option = new EdgeOptions();
option.PageLoadStrategy = PageLoadStrategy.Normal;
return new EdgeDriver(path, option);
}
catch (Exception)
{
throw;
}
}
When the unit test is executed, Edge browser opens briefly then it closes with an error saying "Unexpected error. Unknown error"
The test is just about going to Google search site and works fine with Chrome.
I have followed this: Edge browser crashing after initial watir-webdriver launch
but no luck. Please advice.
You can try a different constructor:
IWebDriver wrappedWebDriver = new EdgeDriver(new EdgeOptions());
This works for me. No need to specify the folder. Also, think that the normal search patter is the default one.

how to get already opened IE browser handle in selenium?

I have one already opened IE browser , with some url.
After this, I Run below code which will open another IE browser. however it gives me only one window handle in below code.
Is it possible to get previously opened IE browser handle ?
IWebDriver IEdriver = new InternetExplorerDriver();
IReadOnlyCollection<String> browsers = IEdriver.WindowHandles;
foreach (String item in browsers)
{
IEdriver.SwitchTo().Window(item);
String url = IEdriver.Url;
}
I think this is what you're looking for:
String winHandleBefore = driver.getWindowHandle();
//Do whatever operations you have to do
for(String winHandle : IEdriver.getWindowHandles()){
IEdriver.switchTo().window(winHandle);
}
Be careful as what you are trying to do, is not robust solution to write tests cases. If one test case causes browser to crash you will be getting all the test cases failed.
Also I don't think it should be possible to get handles on previously opened window by default, because when you write code
IWebDriver IEdriver = new InternetExplorerDriver();
It calls for a constructor of InternetExplorerDriver class and opens new instance of Internet Explorer.
You can either go for close all browsers before starting your test case execution by killing the ie process from task manager.
foreach (Process process in Process.GetProcessesByName("iexplore"))
{
process.Kill();
}

Selenium server start within .NET

I'm using Selenium to control Opera within C#. I'm using selenium-server-standalone-2.33.0 .
When i start the server from command line there is no problem . My code work well.
But I need to start the server from C# and I can start it with a bat file execution. I can start the server and create a driver.
(I'm using "java -jar selenium-server-standalone-2.33.0.jar -trustAllSSLCertificates" command to start the server in both cases.)
My problem is:
If the server started from C# code, my code can't find the element and throwing exception: (Driver's page source property contains xxx element.)
My Code which throws the exception:
element = driver.FindElement(By.Id("xxx"));
All properties of the element throw an exception.
I think it's because of the process.start privileges when i start server. I've searched a lot but i couldn't find anything.
Thanks
I can start sever with this command "java -jar selenium-server-standalone-2.33.0.jar -trustAllSSLCertificates" from command line and C# code. Server starting well i can create driver and can see the page source .
IWebDriver driver = new RemoteWebDriver(new System.Uri("http://localhost:4444/wd/hub"), DesiredCapabilities.Opera());
driver.Navigate().GoToUrl(url);
driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(100));
But when i want to reach WebElement through this code element throws lots of exception ('element.Displayed' threw an exception of type 'System.InvalidOperationException')
IWebElement element; // FindElement(driver, "txtUserName", 100);
element = driver.FindElement(By.Id("txtUserName"));
string name = element.GetAttribute("Name");

Remote Webdriver Chrome throws a "path to the driver executable" error

Hi when i use the following code
IWebDriver _webDriver = new RemoteWebDriver(new Uri("http://127.0.0.1:4444/wd/hub"),
DesiredCapabilities.Chrome());
I get the follwing error
System.InvalidOperationException : The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromedriver/downloads/list
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
at Testframework.Browser.RemoteGoto(String browser, String url) in Browser.cs: line 86
at Testframework.CommonAction.RemoteBrowser(String browser) in CommonAction.cs: line 70
at Test.RegistrationTest.InvalidRegistrationTest(String browser, String username, String password, String confirmPassword, String securityQuestion, String securityAnswer, String errorMessageText, String firstname, String lastname) in RegistrationTest.cs: line 50
--TearDown
at Testframework.CommonAction.CaptureScreen(String fileName) in CommonAction.cs: line 121
at Test.RegistrationTest.SnapshotOnFailure() in RegistrationTest.cs: line 590
The clue really is in the error.
Chrome should be installed on the system where the tests are either running on or being pointed to.
Take a step back, look at the documentation:
https://code.google.com/p/selenium/wiki/ChromeDriver
Also, if Chrome is installed in a peculiar place, you'll need to point Selenium to it's location. Again, this is explained in the documentation.
In C#:
DesiredCapabilities capabilities = DesiredCapabilities.Chrome();
capabilities.SetCapability("chrome.binary", this.binaryLocation);
or:
ChromeOptions options = new ChromeOptions();
options.BinaryLocation = "pathtogooglechrome";
capabilities.SetCapability(ChromeOptions.Capability, options);
Instead of changing the code you can have other way round.
Download the chrome driver and set the PATH environment variable pointing to the directory where the chromedriver.exe is present.
Restart your IDE / Command console and run the tests. It works!!!

Categories

Resources