selenium icon indicating copy to clipboard operation
selenium copied to clipboard

IEDriverServer 2.52.2 throws "Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'OpenQA.Selenium.Proxy'"

Open sophiaatif opened this issue 10 years ago • 4 comments

Expected Behavior -

As stated in Changelog, it should resolve the issue of not finding element, in my case IE failed to find elements when it opens a new tab/window in IE11.

Actual Behavior -

IE is launched but crashes with this exception : "Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'OpenQA.Selenium.Proxy'."

Steps to reproduce -

I have just replaced IEDriverServer to 2.52.2, on hub, test server and node where i is running, if I try it only on local it throes the same error. Is there something that Im missing? the same code works with previous versions.

sophiaatif avatar Mar 15 '16 16:03 sophiaatif

Please supply the .NET code that produces the error.

jimevans avatar Mar 15 '16 19:03 jimevans

Hi Jim, Here is the code:

public T GetCapability<T>(String type) { var h = this.Capabilities; ** object c = this.Capabilities.GetCapability(type);** return c == null ? default(T) : (T)c; }

public void LogCapabilities() { Log.Info("Browser.................{0}", GetCapability<String>(CapabilityType.BrowserName)); Log.Info("Browser version.........{0}", GetCapability<String>(CapabilityType.Version)); Log.Info("Platform................{0}", GetCapability<OpenQA.Selenium.Platform>(CapabilityType.Platform).PlatformType); Log.Info("JavaScriptEnabled.......{0}", GetCapability<Boolean>(CapabilityType.IsJavaScriptEnabled)); Log.Info("AcceptSslCertificates...{0}", GetCapability<Boolean>(CapabilityType.AcceptSslCertificates)); Log.Info("Native Events...........{0}", GetCapability<Boolean>(CapabilityType.HasNativeEvents)); Log.Info("Rotatable...............{0}", GetCapability<Boolean>(CapabilityType.Rotatable)); Log.Info("SupportsFindingByCss....{0}", GetCapability<Boolean>(CapabilityType.SupportsFindingByCss)); Log.Info("Takes screenshots.......{0}", GetCapability<Boolean>(CapabilityType.TakesScreenshot)); if (GetCapability<Proxy>(CapabilityType.Proxy) != null) Log.Info("Browser Proxy...........{0}", GetCapability<Proxy>(CapabilityType.Proxy).HttpProxy);

and this is where it fails, while fetching the proxy from capabilities: (Im pasting the local variable values from debugger)

  • OpenQA.Selenium.ICapabilities.GetCapability returned Count = 1 System.Collections.Generic.Dictionary<string, object>
  •   [0] {[proxyType, ]} System.Collections.Generic.KeyValuePair<string, object>
    

Below Im going to paste the complete class: `using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Web.Script.Serialization; using ConturAutomation.Mapping; using ConturAutomation.Remote; using ConturAutomation.Remote.STAFSharp; using ConturAutomation.Remote.STAFSharp.Services; using NLog; using NLog.LayoutRenderers; using Notebook; using OpenQA.Selenium; using OpenQA.Selenium.Interactions; using OpenQA.Selenium.Remote; using ConturAutomation;

namespace ConturAutomation {

public class ActiveDrivers { public static List RemoteDrivers = new List();

}

///

/// Wrapper class for the RemoteWebDriver (the driver that controls a started browser instance) ///

public class RemoteDriver : RemoteWebDriver,IParent {

    private static readonly Logger Log = LogManager.GetCurrentClassLogger();
    public enum Family { Chrome, InternetExplorer, Firefox, Opera, Safari,  HTMLUnitWithJava, HTMLUnit };

public enum Platform
{
  Windows = PlatformType.Windows, 
  OSX = PlatformType.Mac, 
  //MAC = PlatformType.Mac, 
  ANY = PlatformType.Any
};

public String HostIp = null;

//public Int32 ;
public Int32 DriverProcessId;

private readonly Hub _hub;

public Hub GetHub()
{
  return this._hub;
}

public RequestedCapabilities requestedCapabilities = null;



public Host GetHost()
{
  return HostLookup.GetHost(this.HostIp);
}

public Host Host
{
  get { return GetHost(); }
}



 public RemoteDriver(Hub hub, ICapabilities capabilities, TimeSpan t)
  : base(hub.Uri, capabilities, t)
 {
  this._hub = hub;
  Log.Info("Got Session Id : {0}", SessionIdString);
  Log.Info("Fetching host Info of session : {0}", SessionIdString);
  this.HostIp = GetActualTestNode();
  Log.Info("Host Info fetch done");
}
    public RemoteDriver(Hub hub, ICapabilities capabilities)
  : this(hub, capabilities,new TimeSpan(0,0,1))
{
}

public RemoteDriver(Uri uri, ICapabilities capabilities, TimeSpan t)
  : base(uri, capabilities, t)
{
}

public RemoteDriver(Uri uri, ICapabilities capabilities)
  : this(uri, capabilities, new TimeSpan(0, 0, 120))
{
}



    public ISearchContext AsSearchContext()
{
  return this;
}

public Locator AsLocator()
{
  return new Locator(){alias = "RemoteDriver"};
}

public string WindowHandle { get { return this.CurrentWindowHandle; } set{} }
public IParent Parent { get { return this;} set {throw new NotSupportedException("A driver has no parent");} }
public RemoteDriver Driver { get { return this; } }

private String SessionIdString
{
  get
  {
    return SessionId.ToString();
  }

}

/// <summary>
/// Get IP of the testnode we are using
/// </summary>
private String GetActualTestNode()
{
  int numRetries = 5;

  do
  {
    try
    {
      String uri = @"http://" + this._hub.hostname + @":" + this._hub.port + @"/grid/api/testsession?session=" + this.SessionIdString;
      Log.Info("URI = {0}", uri);

      Uri testSessionApi = new Uri(uri);

      HttpWebRequest http = (HttpWebRequest)WebRequest.Create(testSessionApi);
      http.ContentType = "application/json; charset=utf-8";
      http.Method = WebRequestMethods.Http.Post;
      HttpWebResponse response = (HttpWebResponse)http.GetResponse();

      string responseJson = null;
      using (StreamReader sr = new StreamReader(response.GetResponseStream()))
      {
        responseJson = sr.ReadToEnd();
      }
      Log.Info("JSON = {0}", responseJson);

      // Sample : "proxyId":"http://192.168.1.61:5555"

      var jss = new JavaScriptSerializer();
      var dict = jss.Deserialize<Dictionary<string, string>>(responseJson);

      String proxyId = (String)dict["proxyId"];
      Log.Info("Proxy id = {0} ", proxyId);

      proxyId = (proxyId.Substring(7).Split(':'))[0];
      Log.Info("IP = {0} ", proxyId);

      return proxyId;
    }
    catch (Exception e)
    {
      Log.Fatal("Failed to get host ip/name", e);
      if (numRetries <= 0) throw;
    }

    Log.Info("Retrying...");
    Pause.seconds(1);
  } while (numRetries-- > 0);

  throw new Exception("Failed to get host/ip from driver session");
}

/// <summary>
/// Fetch the browser type according the the driver
/// </summary>
public Family BrowserFamily
{
  get
  {
    String family = this.Capabilities.BrowserName.ToLower();

    if (family.Contains("explorer"))
      return Family.InternetExplorer;

    if (family.Contains("firefox"))
      return Family.Firefox;

    if (family.Contains("safari"))
      return Family.Safari;

    if (family.Contains("chrome"))
      return Family.Chrome;

    return Family.Opera;
  }
}

/// <summary>
/// Return browser version 
/// </summary>
public String BrowserVersion
{
  get
  {
    String version = this.Capabilities.Version.ToLower();
    return version;
  }
}

/// <summary>
/// Return Platform ( OSX or Windows )
/// </summary>
public Platform OsFamily
{
  get
  {
    var p = this.Capabilities.Platform;
    return p.PlatformType == PlatformType.Mac
             ? Platform.OSX
             : Platform.Windows;
  }
}

/// <summary>
/// 
/// </summary>
public string OsVersion
{
  get
  {
    String version = this.Capabilities.Version.ToLower();
    return version;
  }
}


public T GetCapability<T>(String type)
{
  var h = this.Capabilities;
  object c = this.Capabilities.GetCapability(type);
  return c == null ? default(T) : (T)c;
}

public void LogCapabilities()
{
  Log.Info("Browser.................{0}", GetCapability<String>(CapabilityType.BrowserName));
  Log.Info("Browser version.........{0}", GetCapability<String>(CapabilityType.Version));
  Log.Info("Platform................{0}", GetCapability<OpenQA.Selenium.Platform>(CapabilityType.Platform).PlatformType);
  Log.Info("JavaScriptEnabled.......{0}", GetCapability<Boolean>(CapabilityType.IsJavaScriptEnabled));
  Log.Info("AcceptSslCertificates...{0}", GetCapability<Boolean>(CapabilityType.AcceptSslCertificates));
  Log.Info("Native Events...........{0}", GetCapability<Boolean>(CapabilityType.HasNativeEvents));
  Log.Info("Rotatable...............{0}", GetCapability<Boolean>(CapabilityType.Rotatable));
  Log.Info("SupportsFindingByCss....{0}", GetCapability<Boolean>(CapabilityType.SupportsFindingByCss));
  Log.Info("Takes screenshots.......{0}", GetCapability<Boolean>(CapabilityType.TakesScreenshot));
  if (GetCapability<Proxy>(CapabilityType.Proxy) != null)
    Log.Info("Browser Proxy...........{0}", GetCapability<Proxy>(CapabilityType.Proxy).HttpProxy);
  if (this.BrowserFamily == Family.InternetExplorer)
  {
    Log.Info("requireWindowFocus...................{0}", GetCapability<Boolean>("requireWindowFocus"));
    Log.Info("enablePersistentHover................{0}", GetCapability<Boolean>("enablePersistentHover"));
    Log.Info("ie.ensureCleanSession................{0}", GetCapability<Boolean>("ie.ensureCleanSession"));
    Log.Info("unexpectedAlertBehaviour.............{0}", GetCapability<String>("unexpectedAlertBehaviour"));
  }
  if (this.BrowserFamily == RemoteDriver.Family.Safari)
  {
    Log.Info("cleanSession...................{0}", GetCapability<Boolean>("cleanSession"));
  }



}



public List<GeneralDialog> GetGeneralDialogs()
  {
  return null;
  }

public String GetActualBrowser()
{
  return this.GetCapability<String>(CapabilityType.BrowserName);
}

public String GetActualBrowserVersion()
{
  return this.GetCapability<String>(CapabilityType.Version);
}

public static RemoteDriver Launch(Hub hub, RequestedCapabilities requestedCapabilities)
    {

        RemoteDriver driver = null;
        int numRetries = 1;
    if (requestedCapabilities.BrowserFamily == Family.Safari)
    numRetries = 5;


        Log.Info("Initiating Remote Webdriver...");
  Log.Info("Hub      : {0}", hub.hostname);
  Log.Info("Hub port : {0}", hub.port);
  TimeSpan t = requestedCapabilities.CommandTimeout;

  do
  {
    // Give tests a second chance to init driver on failure

    try
    {

      Log.Info("Creating driver with CommandTimeout {0} ...", t.TotalSeconds);
      if (t != TimeSpan.MinValue)
      {
        driver = new RemoteDriver(hub, requestedCapabilities.ToDesiredCapabilities(), t);
      }
      else
      {
        Log.Info("Creating driver default CommandTimeout...");
        driver = new RemoteDriver(hub, requestedCapabilities.ToDesiredCapabilities());
      }

      Log.Info("Capabilities after initiating driver !");
      driver.LogCapabilities();
      Log.Info("Checking up the node we got");
      Log.Info("Actual host = {0} ", driver.HostIp);
      Log.Info("OS          = {0} ", driver.Host.OS);
      break;
    }
    catch (System.InvalidOperationException e)
    {
      Log.Warn("Driver creation failed !", e);

      if (e.Message.Contains(@"Error forwarding the new session cannot find : Capabilities"))
      {
        Log.Info("No node exists that matches Your request !");
        throw;
      }

      if (e.Message.Contains(@"waiting for a node to become available."))
      {
        Log.Fatal("No node is yet available matching your request!", e);
        Log.Info("Resetting numRetries...");
        numRetries = 1;
        if (requestedCapabilities.BrowserFamily == Family.Safari)
          numRetries = 5;
      }
      else if (e.Message.Contains("Failed to connect to SafariDriver"))
      {
        Log.Warn("Failed to connect to SafariDriver, retrying ");
      }
      else
      {
         throw;
      }



      try
      {
        driver.Quit();
        driver.Dispose();
      }
      catch (Exception exception)
      {
        Log.Warn("Failed disposing the failed driver instance...", exception);
      }

      Pause.seconds(5);

    }
    catch (Exception e)
    {
      Log.Fatal("Driver creation failed !", e);

      try
      {
        driver.Quit();
        driver.Dispose();
      }
      catch (Exception exception)
      {
        Log.Warn("Failed disposing the failed driver instance...", exception);
      }


      if (numRetries <= 0) throw;  // improved to avoid silent failure
    }

    Log.Info("Retrying...");

  } while (numRetries-- > 0);


  try
  {

    Log.Info("Successfully Initiated Remote Webdriver...");
    Log.Info("Storing RequestedCapabilities for history");
    driver.requestedCapabilities = requestedCapabilities;

    Log.Info("Adding driver [session = {0}] to Active List...",driver.SessionIdString);
    ActiveDrivers.RemoteDrivers.Add(driver);

    if (requestedCapabilities.Device != null)
    {
      Pause.seconds(2);
      return null;
    }

    if (driver.BrowserFamily != Family.Safari)
    {
      Log.Info("Deleting all Cookies");
      driver.Manage().Cookies.DeleteAllCookies();
      Log.Info("Deleting all Cookies done");
    }
    else
    {

      var process = new FileSystem()
      {
         Task = FileSystem.ServiceTask.DELETE,
         Confirm = true,
         Children = true,
         Extension = "localstorage",
         Entry = "/Users/localadmin/Library/Safari/LocalStorage"
      };

      UInt32 RC = process.Submit(driver.HostIp);


      if (RC == STAFResult.Ok)
      {

      }
      else
      {
        throw new ConturAutomationException("Failed running {0} on {1} : STAF EXITCODE {2}".Params("rm storage",
          driver.HostIp, RC));
      }


       process = new FileSystem()
      {
        Task = FileSystem.ServiceTask.DELETE,
        Confirm = true,
        Children = true,
        Extension = "binarycookies",
        Entry = "/Users/localadmin/Library/Cookies"
      };

       RC = process.Submit(driver.HostIp);

      if (RC == STAFResult.Ok)
      {


      }
      else
      {
        throw new ConturAutomationException("Failed running {0} on {1} : STAF EXITCODE {2}".Params("rm cookies",
          driver.HostIp, RC));
      }

      driver.Host.KillProcessByName("cookied");
    }  

    Log.Info("Performing browser specific operations");
    Log.Info("OS Family = {0} ", driver.OsFamily);


    // On mac we need to set the browser to frontmost applicatdriverion
    switch (driver.OsFamily)
    {
      case Platform.OSX:
      {
        driver.OSX_specific_setup();
      }
        break;

      case Platform.Windows:
      {
        driver.WIN_specific_setup();
      }
        break;
    }


    Log.Info("Start browser in 1280 x 1024 by default");
    Pause.seconds(1);
    driver.Manage().Window.Size = new System.Drawing.Size(1280, 1024);

    Log.Info("Move Browser to 0,0");
    driver.Manage().Window.Position = new System.Drawing.Point(0, 0);

    Log.Info("Browser pos = {0},{1}", driver.Manage().Window.Position.X,driver.Manage().Window.Position.Y);

  }
  catch(Exception e)
  {
    Log.Fatal("Init of driver failed ",e);
    try
    {
      driver.Quit();
      driver.Dispose();
    }
    catch (Exception exception)
    {
      Log.Warn("Failed disposing the failed driver instance...", exception);
    }
    throw;
  }


  return driver;
}

private void OSX_specific_setup()
{
  switch (BrowserFamily)
  {
    case Family.Safari:

      Log.Info("We need to activate the app on MAC to make it frontmost!");
      Log.Info("Activating browser {0} on host {1}", BrowserFamily, Driver.HostIp);


      Boolean waitUntilLocalhostUrl = Wait.Until(() => Driver.Url.Contains("localhost"), "Waiting for localhost URL", 5);

      if (!waitUntilLocalhostUrl)
      {
        String theURL1 = Url;
        String theTitle1 = Title;
        Log.Info("Browser URL   : {0}", theURL1);
        Log.Info("Browser Title : {0}", theTitle1);
        Log.Info("Window count : {0}", WindowHandles.Count);

        String handle = CurrentWindowHandle;
        Log.Info("Window handle : {0} ", handle);



        foreach (var hwnd in WindowHandles)
        {
          if (hwnd != handle)
          {
            Log.Info("Found the other window : {0} , switching to it after closing the first one", hwnd);
            Close(); // Close handle
            Log.Info("Window count after close : {0}", Driver.WindowHandles.Count);
            Log.Info("Starting switch");
            this.SwitchTo().Window(hwnd);
            Log.Info("Switch completed");
            break;
          }
        }
      }


      Log.Info("Getting URL and title");
      String theURL = Url;
      String theTitle2 = Title;
      Log.Info("Browser URL   : {0}", theURL);
      Log.Info("Browser Title : {0}", theTitle2);

      String theTitle = theURL.Replace(@"http://", "");
      Log.Info("Browser title to look for {0} ", theTitle);

        var process = new ToolProcess()
        {
          Command = "WinWaitActivate.applescript",
          Wait = 30
        };

        process.ParameterList.AddItems(theTitle,"20");
        UInt32 RC = process.Submit(this.HostIp);


      if (RC == STAFResult.Ok)
      {
        var info = process.Result<Process.CompletionInfo>();
        if(info.rc!=0)
          throw new ConturAutomationException("WinWaitActivate.applescript failed with exitcode {0}".Params(info.rc));

      }
      else
      {
        throw new ConturAutomationException("Failed running {0} on {1} : STAF EXITCODE {2}".Params("WinWaitActivate.applescript",
          HostIp,RC));
      }


      break;

    case Family.Firefox:
      // Remove status bar
      SwitchTo().DefaultContent();         
      Actions myAction = new Actions(this);
      myAction.SendKeys(Keys.Command + Keys.Divide).Build().Perform();


      break;

  }

}


private void WIN_specific_setup()
{
  Log.Info("Performing Windows specific operations");
  switch (BrowserFamily)
  {

    case Family.Firefox:
      Log.Info("Performing Firefox specific operations");
      // Remove status bar
      SwitchTo().DefaultContent();
      Actions myAction = new Actions(this);
      myAction.SendKeys(Keys.LeftControl + Keys.Divide).Build().Perform();
      break;

    case Family.InternetExplorer:
    case Family.Chrome:
      Log.Info("Performing Chrome & IE specific operations");


       Process process = new Process
        {
          Command = Host.PathCombine(Host.ConturToolsBinDirectory,"MouseMove"),
          Parameters = "-x 1400 -y 20",
          Wait = 30
        };

       UInt32 RC = process.Submit(this.HostIp);

       if (RC != 0)
       {
         throw new ConturAutomationException("MouseMove failed on {0}".Params(HostIp));
       }


      break;
  }

}

} public class IEDriver:InternetExplorerDriver { }

}

public class PageGeneric : PageObject
{
  public PageGeneric() : base() { }
}

[Root("Dialog.Generic")] public class GeneralDialog : Notebook.Dialog {

public Text title;


public Text message;

public String GetTitle()
{
  return this.title.Text;
}
public String GetMessage()
{
  return this.message.Text;
}

} `

sophiaatif avatar Mar 15 '16 22:03 sophiaatif

This is entirely expected. When getting returned capabilities, the language bindings do not deserialize proxy information into a Proxy object. It returns a Dictionary<string, object>, which you can then use to check for a key of httpProxy.

jimevans avatar Mar 16 '16 17:03 jimevans

i have a same problem ,i need help

that is my code ` [OneTimeSetUp]

    public void SetupTest()
    {

        var capabilities = DesiredCapabilities.Chrome();
        ChromeOptions options = new ChromeOptions();
        options.AddArguments("test-type");
        options.BinaryLocation = @"C:\Users\ebrahimpour.l\Documents\Visual Studio 2015\Projects\FirstPackage\FirstPackage\bin\Debug\chro‌​medriver.exe";
        capabilities.SetCapability("chrome.binary", @"C:\Users\ebrahimpour.l\Documents\Visual Studio 2015\Projects\FirstPackage\FirstPackage\bin\Debug\chro‌​medriver.exe");
        capabilities.SetCapability(ChromeOptions.Capability, options);
        System.Environment.SetEnvironmentVariable("webdriver.chrome.‌​driver",
            @"C:\Users\ebrahimpour.l\Documents\Visual Studio 2015\Projects\FirstPackage\FirstPackage\bin\Debug\chro‌​medriver.exe");
        driver = new ChromeDriver(@"C:\Users\ebrahimpour.l\Documents\Visual Studio 2015\Projects\FirstPackage\FirstPackage\bin\Debug");
        capabilities.SetCapability(ChromeOptions.Capability, options.ToString());
        capabilities.SetCapability(capabilities.Platform.ProtocolPlatformType, "WebDriver");
        capabilities.SetCapability(CapabilityType.BrowserName, "chrome");
        capabilities.SetCapability(capabilities.Version, "57");
        capabilities.SetCapability(CapabilityType.Platform, "WinNT");
        capabilities.SetCapability(ChromeOptions.Capability, options);
        if (driver != null)
        {
            driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4444/wd/hub"), capabilities,
                TimeSpan.FromSeconds(200));
        }
        baseURL = "http://192.168.10.173:8080/";
        // driver.Manage().Window.Maximize();
        verificationErrors = new StringBuilder();
    }`

and my stacktrace is

at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse) at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters) at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities) at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities) at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(Uri remoteAddress, ICapabilities desiredCapabilities, TimeSpan commandTimeout) at FirstPackage.Methods.SetupTest() in C:\Users\ebrahimpour.l\Documents\Visual Studio 2015\Projects\FirstPackage\FirstPackage\Methods.cs:line 83

error message: Unable to cast object of type 'System.String' to type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]'.

liaeb avatar May 07 '17 10:05 liaeb