IE changes the system proxy instead of the browser proxy, what can go wrong?
I tried changing the property UsePerProcessProxy, but it did not fix it.
Please see the code below
public InternetExplorerOptions GetOptions()
{
InternetExplorerOptions options = new InternetExplorerOptions
{
IntroduceInstabilityByIgnoringProtectedModeSettings = true,
InitialBrowserUrl = "about:blank",
EnableNativeEvents = true,
EnsureCleanSession = true,
EnablePersistentHover = false,
PageLoadStrategy = InternetExplorerPageLoadStrategy.Normal,
};
options.UsePerProcessProxy = true;
options.Proxy = GetProxy();
return options;
}
public override IWebDriver CreateRemoteDriver()
{
var options = GetOptions();
foreach (var capability in CapabilityProperties)
{
options.AddAdditionalCapability(capability.Name, capability.Value);
}
return new RemoteWebDriver(new Uri(GridUri), options.ToCapabilities());
}
public Proxy GetProxy()
{
if (Proxy != null || ProxyAutoConfigUrl != null)
{
var proxy = new Proxy();
proxy.AddBypassAddresses("localhost", "127.0.0.1");
if (ProxyAutoConfigUrl != null)
{
proxy.Kind = ProxyKind.ProxyAutoConfigure;
proxy.ProxyAutoConfigUrl = ProxyAutoConfigUrl;
}
if (Proxy != null)
{
proxy.Kind = ProxyKind.Manual;
proxy.HttpProxy = Proxy;
proxy.SslProxy = Proxy;
}
return proxy;
}
return null;
}
Selenium Standalone Server version 3.10.0
iewebdriverserver 3.9.0 32 bit
Related
I keep coming back to this but what should I be returning from my database service call in my WeightLifting Service I have this code.
public async void CopySessionsPlayersToWeightLiftingBySessionId(int sessionID)
{
List<SessionPlayer> sessionsPlayers = new
List<SessionPlayer>();
sessionsPlayers = db.SessionPlayer.Where(w => w.SessionId ==
sessionID).ToList();
if (sessionsPlayers != null)
{
List<WeightLifting> weightLiftings = new List<WeightLifting>();
foreach (var sessionPlayer in sessionsPlayers)
{
var player = db.Players.Where(w => w.Id ==
sessionPlayer.PlayerId).FirstOrDefault();
WeightLifting weightLifting = new WeightLifting();
weightLifting.SessionStartDate = sessionPlayer.StartDate;
weightLifting.SessionEndDate = sessionPlayer.EndDate;
weightLifting.TeamId=sessionPlayer.TeamId;
weightLifting.SessionId = sessionPlayer.SessionId;
weightLifting.PlayersId = sessionPlayer.PlayerId;
weightLifting.PU = player.DefaultPU;
weightLifting.PUReps = Convert.ToInt32(player.DefaultPUReps);
weightLifting.BP = player.DefaultBP;
weightLifting.TB = player.DefaultTB;
weightLifting.TBReps = Convert.ToInt32(player.DefaultTBReps);
weightLifting.OP = player.DefaultOP;
weightLifting.OPReps = Convert.ToInt32(player.DefaultOPReps);
weightLifting.APU = player.DefaultAdvancedPu;
weightLifting.APUReps = Convert.ToInt32(player.DefaultAdvancedPuReps);
weightLifting.IsActive = true;
weightLifting.IsDeleted = false;
weightLiftings.Add(weightLifting);
}
db.AddRange(weightLiftings);
db.SaveChanges();
}
}
As I am just doing a save out my http client call is basically this.
public async Task<HttpStatusCode>
CopySessionsPlayersToWeightLiftingBySessionId(int Id)
{
EnsureHttpClientCreated();
var json = JsonConvert.SerializeObject(Id);
var httpContent = new StringContent(json, Encoding.UTF8,
"application/json");
var httpResponse = await httpClient.PostAsync(Constants.BaseUrl
+ Constants.ApiSegmant +
Constants.CopySessionsPlayersToWeightLiftingBySessionId +
$"?Id={Id}", httpContent);
return httpResponse.StatusCode;
}
My Create Http Client code
private void EnsureHttpClientCreated()
{
if (httpClient == null)
{
CreateHttpClient();
}
}
private void CreateHttpClient()
{
_httpClientHandler = new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
};
httpClient = new HttpClient(_httpClientHandler, false)
{
Timeout = _timeout
};
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(ClientUserAgent);
if (!string.IsNullOrWhiteSpace(Constants.BaseUrl))
{
httpClient.BaseAddress = new Uri(Constants.BaseUrl);
}
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeJson));
}
At the min only the ui will get a ok but how should I handle sending back an error here yes I could try catch around the save changes then put a BadContent but that feels messy?.
Consider using exception filters. They basically serve as a middleware that runs after your endpoint throws an exception to catch it and turn it into a specific response.
I have used this method designed by Tarun Lalwani to attach a Selenium Chrome driver by reusing the url and the sessionID in C#. This attach is partly working but some driver methods such as FindElement(By.ID) display error "invalid argument: invalid locator (Session info: chrome=91.0.4472.114)" on this line:
var respBase = base.Execute(driverCommandToExecute, parameters);
My guess is that it is due to options or desired capabilities are empty when the driver is attached.But I havent find a way to properly set it on ReuseRemoteWebDriver.
I include an image of the look of the attached driver
here.
How can I solve this issue so I can attach the previous chrome driver and keep all expected selenium functionalities?
static void Main(string[] args)
{
InputSimulator teclado = new InputSimulator();
ChromeOptions options = new ChromeOptions();
options.UseSpecCompliantProtocol = true;
ChromeDriverService service = ChromeDriverService.CreateDefaultService(#"Thepathofchromedriver");
IWebDriver driver;
DesiredCapabilities capabilities = new DesiredCapabilities();
Uri myUri = new Uri("http://127.0.0.1:65431", UriKind.Absolute);
service.Port = 65431;
string ID = "1f42d5f0ad105910e8d2fc7be23480a9";
if (ID != "")
{
IWebDriver drivertest1 = new ChromeDriver(service, options);
IWebDriver drivertest = new ReuseRemoteWebDriver(myUri, ID,capabilities,options);
driver = drivertest;
}
else
{
IWebDriver drivertest = new ChromeDriver(service,options);
driver = drivertest;
}
IWebElement inputUser = driver.FindElement(By.Id("ID"));}
public class ReuseRemoteWebDriver : OpenQA.Selenium.Remote.RemoteWebDriver
{
private String _sessionId;
public ReuseRemoteWebDriver(Uri remoteAddress, String sessionId, OpenQA.Selenium.Remote.DesiredCapabilities capability, ChromeOptions options)
: base(remoteAddress,options)
{
this._sessionId = sessionId;
var sessionIdBase = this.GetType()
.BaseType
.GetField("sessionId",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic);
sessionIdBase.SetValue(this, new OpenQA.Selenium.Remote.SessionId(sessionId));
}
protected override OpenQA.Selenium.Remote.Response
Execute(string driverCommandToExecute, System.Collections.Generic.Dictionary<string, object> parameters)
{
if (driverCommandToExecute == OpenQA.Selenium.Remote.DriverCommand.NewSession)
{
var resp = new OpenQA.Selenium.Remote.Response();
resp.Status = OpenQA.Selenium.WebDriverResult.Success;
resp.SessionId = this._sessionId;
resp.Value = new System.Collections.Generic.Dictionary<String, Object>();
return resp;
}
var respBase = base.Execute(driverCommandToExecute, parameters);
return respBase;
}
}
UPDATE: I could fix most issues, as I indicated in the reply.
the most important functionality I couldn't manage to recover was the inject js scripts with
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
var script = "your script";
js.ExecuteScript(script);
Any idea regarding how to recover the inject script functionality would be appreciated.
In case anyone is interested, I modified the previous class as following, so I can use the sendKeysToElement
public class ReuseRemoteWebDriver : OpenQA.Selenium.Remote.RemoteWebDriver
{
private String _sessionId;
public ReuseRemoteWebDriver(Uri remoteAddress, String sessionId, ChromeOptions options, ChromeDriverService service)
: base(remoteAddress, options)
{
//object x = driver;
this._sessionId = sessionId;
var sessionIdBase = this.GetType()
.BaseType
.GetField("sessionId",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic);
//System.Collections.Generic.Dictionary<string, object> x = this.GetCapabilitiesDictionary(capability);
sessionIdBase.SetValue(this, new OpenQA.Selenium.Remote.SessionId(sessionId));
}
protected override OpenQA.Selenium.Remote.Response
Execute(string driverCommandToExecute, System.Collections.Generic.Dictionary<string, object> parameters)
{
if (driverCommandToExecute == OpenQA.Selenium.Remote.DriverCommand.NewSession)
{
var resp = new OpenQA.Selenium.Remote.Response();
resp.Status = OpenQA.Selenium.WebDriverResult.Success;
resp.SessionId = this._sessionId;
resp.Value = new System.Collections.Generic.Dictionary<String, Object>();
return resp;
}
if (driverCommandToExecute == "sendKeysToElement")
{
object[] array = (object[])parameters["value"];
string stringfinal = (string)array[0].ToString();
parameters.Add("text", stringfinal);
}
if (driverCommandToExecute == "executeScript")
{
Console.WriteLine("");
}
var respBase = base.Execute(driverCommandToExecute, parameters);
return respBase;
}
}
}
In other class I used the following method to properly used Selenium waits.
public Boolean WaitInteligente(WebDriverWait wait, string condition, By selector = null,
IWebElement optionalWebElement = null,string optionalstring = null,
bool optionalbool = false,bool devolverexcepcion=true )
{
TimeSpan Tiempo = wait.Timeout;
var globalclock = Stopwatch.StartNew();
Boolean stop = false;
double segundos = globalclock.Elapsed.TotalSeconds;
Exception exception = null;
//globalclock.Stop();
while (segundos <= Tiempo.TotalSeconds)
{
Thread.Sleep(500);
try
{
segundos = globalclock.Elapsed.TotalSeconds;
if (condition == "ElementExists")
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(selector));
if (condition == "ElementIsVisible")
wait.Until(ExpectedConditions.ElementIsVisible(selector));
if (condition == "ElementToBeClickable")
wait.Until(ExpectedConditions.ElementToBeClickable(selector));
if (condition == "ElementToBeSelected")
wait.Until(ExpectedConditions.ElementToBeSelected(selector));
if (condition == "FrameToBeAvailableAndSwitchToIt")
wait.Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(selector));
if (condition == "InvisibilityOfElementLocated")
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(selector));
if (condition == "PresenceOfAllElementsLocatedBy")
wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(selector));
if (condition == "VisibilityOfAllElementsLocatedBy")
wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(selector));
if (condition == "AlertIsPresent")
wait.Until(ExpectedConditions.AlertIsPresent());
if (condition == "ElementToBeSelected")
wait.Until(ExpectedConditions.ElementToBeSelected(optionalWebElement));
if (condition == "InvisibilityOfElementWithText")
wait.Until(ExpectedConditions.InvisibilityOfElementWithText(selector,optionalstring));
if (condition == "StalenessOf")
wait.Until(ExpectedConditions.StalenessOf(optionalWebElement));
if (condition == "TextToBePresentInElement")
wait.Until(ExpectedConditions.TextToBePresentInElement(optionalWebElement,optionalstring));
if (condition == "TextToBePresentInElementLocated")
wait.Until(ExpectedConditions.TextToBePresentInElementLocated(selector, optionalstring));
if (condition == "TextToBePresentInElementValue")
wait.Until(ExpectedConditions.TextToBePresentInElementValue(selector, optionalstring));
if (condition == "TitleContains")
wait.Until(ExpectedConditions.TitleContains(optionalstring));
if (condition == "TitleIs")
wait.Until(ExpectedConditions.TitleIs(optionalstring));
if (condition == "UrlContains")
wait.Until(ExpectedConditions.UrlContains(optionalstring));
if (condition == "UrlMatches")
wait.Until(ExpectedConditions.UrlMatches(optionalstring));
if (condition == "UrlToBe")
wait.Until(ExpectedConditions.UrlToBe(optionalstring));
if (condition == "FrameToBeAvailableAndSwitchToIt")
wait.Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(optionalstring));
if (condition == "AlertState")
wait.Until(ExpectedConditions.AlertState(optionalbool));
if (condition == "ElementSelectionStateToBe")
wait.Until(ExpectedConditions.ElementSelectionStateToBe(selector,optionalbool));
if (condition == "ElementSelectionStateToBe")
wait.Until(ExpectedConditions.ElementSelectionStateToBe(selector, optionalbool));
stop = true;
break;
}
catch (Exception e)
{
e = new Exception(selector.ToString() + condition + e.Message);
exception = e;
}
}
if (!stop && devolverexcepcion)
throw exception;
return stop;
}
The methods that are not working properly when attached are
driver.FindElement(By.Id) and driver.FindElement(By.ClassName) which can be easily circumvented by using a By.CssSelector call to the ID or Classname respectively.
The most important functionality I couldn't recover was the inject js scripts with
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
var script = "your script";
js.ExecuteScript(script);
Any idea regarding how to recover the inject script functionality would be appreciated.
I'm using the Saucelabs Selenium implementation to automate my testing across multiple devices and platforms.
Using the demo code from SauceLabs (below) doesn't work behind a proxy.
I've tried adding the proxy details to the DesiredCapibilities but this doesn't seem to do anything
[TestMethod]
public void TestSauceLabs()
{
DesiredCapabilities caps = new DesiredCapabilities();
caps.SetCapability("browserName", "Safari");
caps.SetCapability("platform", "macOS 10.13");
caps.SetCapability("version", "11.1");
caps.SetCapability("username", _sauceUserName);
caps.SetCapability("accessKey", _sauceAccessKey);
caps.SetCapability("name", _name);
var tags = new List<string> {"demoTest", "sauceDemo"};
caps.SetCapability("tags", tags);
caps.SetCapability("maxDuration", 3600);
caps.SetCapability("commandTimeout", 600);
caps.SetCapability("idleTimeout", 1000);
caps.SetCapability("build", "SauceDemo");
/****************************************
* Edited demo code here
* Added proxy config to DesiredCapabilities **
*/
var proxy = new Proxy
{
IsAutoDetect = false,
HttpProxy = $"{_proxyScheme}://{_proxyHost}:{_proxyPort}",
SslProxy = $"{_proxyScheme}://{_proxyHost}:{_proxyPort}",
FtpProxy = $"{_proxyScheme}://{_proxyHost}:{_proxyPort}"
};
caps.SetCapability(CapabilityType.Proxy, proxy);
/*
*****************************************/
var uri = new Uri("https://ondemand.eu-central-1.saucelabs.com/wd/hub");
_driver = new RemoteWebDriver(uri,
caps, TimeSpan.FromSeconds(600));
_javascriptExecutor = ((IJavaScriptExecutor) _driver);
_javascriptExecutor.ExecuteScript("sauce:context=Open SauceDemo.com");
_driver.Navigate().GoToUrl(_url);
_javascriptExecutor.ExecuteScript("sauce:context=Sleep for 10000ms");
Thread.Sleep(10000);
Assert.IsTrue(true);
var passed = true;
_javascriptExecutor.ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
_driver?.Quit();
}
Found the solution was to use the HttpCommandExecutor when using the RemoteWebDriver behind a proxy.
Here is my example code:
[TestMethod]
public void TestSauceLabs_Chrome()
{
var remoteOptions = new Dictionary<string, object>
{
{ "username", _sauceUserName },
{ "accessKey", _sauceAccessKey },
{ "name", _name },
{ "maxDuration", 3600 },
{ "commandTimeout", 600 },
{ "idleTimeout", 1000 }
};
var options = new ChromeOptions()
{
PlatformName = "Windows 10",
BrowserVersion = "latest"
};
//Remote options need to be global
options.AddAdditionalCapability("sauce:options", remoteOptions, true);
var caps = options.ToCapabilities();
/*
Using the HttpCommandExecutor persists the proxy details
and allows you to pass in credentials if required
*/
var executor = new HttpCommandExecutor(
new Uri("https://ondemand.eu-central-1.saucelabs.com/wd/hub"),
TimeSpan.FromSeconds(600))
{
Proxy = GenerateProxy()
};
_driver = new RemoteWebDriver(executor, caps);
_javascriptExecutor = ((IJavaScriptExecutor)_driver);
_javascriptExecutor.ExecuteScript($"sauce:context=Open {_url}");
_driver.Navigate().GoToUrl(_url);
_javascriptExecutor.ExecuteScript("sauce:context=Sleep for 10000ms");
Thread.Sleep(10000);
Assert.IsTrue(true);
var passed = true;
_javascriptExecutor.ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
_driver?.Quit();
}
public WebProxy GenerateProxy()
{
var proxy = new WebProxy
{
Address = new Uri($"{_proxyScheme}://{_proxyHost}:{_proxyPort}"),
BypassProxyOnLocal = false,
UseDefaultCredentials = _networkCredential != null,
Credentials = _networkCredential
};
return proxy;
}
Please i use a service windows to acced to my email. i have this exception when i try to bind my folder
Here is my code
private static readonly ExchangeVersion _ExchangeServerVersion = ExchangeVersion.Exchange2010;
private static readonly IWebProxy _ExchangeWebProxy;
public static EmailClient CreateClient(string account, string password, string domain, string mailtowatch=null ,TimeSpan? timeout = null )
{
if (!timeout.HasValue)
{
timeout = new TimeSpan(0, 5, 0);
}
EmailClient result = new EmailClient();
result.Mailbox = mailtowatch;
ExchangeService client = new ExchangeService(_ExchangeServerVersion);
client.UseDefaultCredentials = true;
if (!string.IsNullOrEmpty(password))
{
client.Credentials = new WebCredentials(account, password, domain);
}
try
{
client.AutodiscoverUrl(mailtowatch);
}
catch (Exception)
{
client.Url = new Uri("https://office.natixis.com/EWS/Exchange.asmx");
}
client.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mailtowatch);
client.WebProxy = WebRequest.DefaultWebProxy;
client.WebProxy = _ExchangeWebProxy;
result.Service = client;
client.Timeout = (int)(timeout.Value.TotalMilliseconds);
return result;
}
*******************************
and i call it here
*******************************
Folder folder = null;
FolderId id = null;
if (criteria.FolderName != null)
{
log.Debug(string.Format("Getting folder {0}", criteria.FolderName));
id = GetFolderId(criteria.FolderName);
}
log.Debug("Start binding folder");
if (criteria.Password == null)
{
var folderTemp = new FolderId(WellKnownFolderName.Inbox, criteria.EmailToWatch); //Or the folder you want to search in
folder = Folder.Bind(Service, folderTemp);
}
else
{
//client.UseDefaultCredentials = true;
folder = Folder.Bind(Service, id ?? new FolderId(WellKnownFolderName.Inbox, new Mailbox( criteria.EmailToWatch) ));
}
but on bindid the folder i have an exception ErrorNonExistentMailbox.
Even when i use UseDefaultCredentials = true is not working
I'm using Managed Wifi to get the radio state of my Wifi adapter.
How can I turn the radio ON in case it is actually off ?
Something like this :
WlanClient wlanClient = new WlanClient()
var targetInterface = wlanClient.Interfaces.FirstOrDefault()
if (targetInterface != null)
{
bool radioIsOff = targetInterface .RadioState.PhyRadioState[0].dot11SoftwareRadioState == Wlan.Dot11RadioState.Off;
if (radioIsOff)
{
// TODO
}
}
I just added this to the WlanInterface class of the Managed Wifi API :
IntPtr radioStatePtr = new IntPtr(0L);
try
{
Wlan.WlanPhyRadioState radioState = new Wlan.WlanPhyRadioState();
radioState.dwPhyIndex = 0; // TODO : can change ???
radioState.dot11HardwareRadioState = Wlan.Dot11RadioState.On; // ignored in fact, according to http://msdn.microsoft.com/en-us/library/windows/desktop/ms706791(v=vs.85).aspx
radioState.dot11SoftwareRadioState = Wlan.Dot11RadioState.On;
radioStatePtr = Marshal.AllocHGlobal(Marshal.SizeOf(radioState));
Marshal.StructureToPtr(radioState, radioStatePtr, false);
Wlan.ThrowIfError(
Wlan.WlanSetInterface(
client.clientHandle,
info.interfaceGuid,
Wlan.WlanIntfOpcode.RadioState,
(uint)Marshal.SizeOf(typeof(Wlan.WlanPhyRadioState)),
radioStatePtr,
IntPtr.Zero));
}
finally
{
if (radioStatePtr.ToInt64() != 0)
Marshal.FreeHGlobal(radioStatePtr);
}
Tested on Win 7.
I was struggling with this and I just want to share my solution
(download managed wifi recommended above)
Add WlanApi.cs and Interop.cs to your project.
Add using NativeWifi.
In WlanApi.cs
change to:
public IntPtr clientHandle;
(You need the clientHandle. Not sure why it was set to private?)
Use this code:
string arg1 = "true"; //set to false if you want to turn it off.
arg1 = arg1.ToLower();
IntPtr radioStatePtr = new IntPtr(0L);
try
{
WlanClient wc = new WlanClient();
foreach (var iface in wc.Interfaces)
{
//WlanInterface
if(iface.InterfaceName.ToLower()=="wifi")
{
Wlan.WlanPhyRadioState radioState = new Wlan.WlanPhyRadioState();
radioState.dwPhyIndex = 0;
if(arg1=="true")
{
radioState.dot11HardwareRadioState = Wlan.Dot11RadioState.On;
radioState.dot11SoftwareRadioState = Wlan.Dot11RadioState.On;
}
else
{
radioState.dot11HardwareRadioState = Wlan.Dot11RadioState.Off;
radioState.dot11SoftwareRadioState = Wlan.Dot11RadioState.Off;
}
radioStatePtr = Marshal.AllocHGlobal(Marshal.SizeOf(radioState));
Marshal.StructureToPtr(radioState, radioStatePtr, false);
Wlan.WlanSetInterface(wc.clientHandle, iface.InterfaceGuid, Wlan.WlanIntfOpcode.RadioState, (uint)Marshal.SizeOf(typeof(Wlan.WlanPhyRadioState)), radioStatePtr, IntPtr.Zero);
}
}
}
finally
{
if (radioStatePtr.ToInt64() != 0)
Marshal.FreeHGlobal(radioStatePtr);
}
Good luck :)