Chrome opening for split second and throws exception using Selenium - c#

namespace Selenium_test
{
class Program
{
static void Main(string[] args)
{
string Path = #"C:\Users\Anjali10\.nuget\packages\WebDriverChromeDriver\2.10.0\tools";
//Create the reference of our browser
IWebDriver driver = new ChromeDriver(Path);
// Thread.Sleep(TimeSpan.FromSeconds(3000));
Thread.Sleep(300000);
//Navigate to google page
driver.Navigate().GoToUrl("https://www.google.com");
//Find the element
IWebElement element = driver.FindElement(By.Name("q"));
//Perform Operation
element.SendKeys("Dynamics Lifecycle Services");
driver.Close();
}
}
}
this code opens chrome for split second and then throws exception as below
An unhandled exception of type 'System.InvalidOperationException'
occurred in WebDriver.dll
Additional information: unknown error: unrecognized Blink revision:
49721773c8dd62828e471ca69e2c89767f98c690
A cmd promt opens with message :
Only local connections are allowed.
Please help to resolve. thanks in advance

Related

is there a method to SelfUpdate a console application in MSVSC C# .net5

I'm develop a simple Console Application c# (GT-AutoPatcher.exe) with MSVSC2022 .NET5 capable of update some files in windows systems, include itselfs. The problem is, when i try to update the "updater" (the created app called GT-AutoPatcher.exe) i get stucked because i dont know the correct way to update a running program...
I'm trying this
using (WebClient web1 = new WebClient()) {
web1.Headers.Add("user-agent", "Other");
web1.DownloadFile("http://*/","GT-AutoPatcher.exe");
}
But result is:
Unhandled exception. System.Net.WebException: An exception occurred during a WebClient request.
---> System.IO.IOException: The process cannot access the file 'C:\*\bin\Debug\net5.0\GT-AutoPatcher.exe' because it is being used by another process.
Reasons:
The console application is running. How can i close it to donwload a new version?
If you want to close the program, you can refer to this code:
public static class Program1
{
static void Main(string[] args)
{
CloseApp("your file type");//Change this to what you want to turn off
}
private static void CloseApp(string ArrayProcessName)
{
string[] processName = ArrayProcessName.Split(',');
foreach (string appName in processName)
{
Process[] localByNameApp = Process.GetProcessesByName(appName);//Get all processes with program name
if (localByNameApp.Length > 0)
{
foreach (var app in localByNameApp)
{
if (!app.HasExited && app.MainWindowTitle == "your file name")
{
app.Kill();//close the process
}
}
}
}
}
}

System.Net.WebException : The remote server returned an error: (404) Not Found

In order to avoid browser driver version mismatch issue every time I execute my Selenium tests using xUnit test runner, I have added below line of code to my .cs file
new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser);
but, when I execute my test, I'm getting below error
SampleXUnitTestProject.FirstSeleniumTests.CorrectTitleDisplayed_When_NavigateToHomePage
Source: FirstSeleniumTests.cs line 25
Duration: 1 ms
Message:
System.Net.WebException : The remote server returned an error: (404) Not Found.
Stack Trace:
HttpWebRequest.GetResponse()
ChromeConfig.GetLatestVersion(String url)
ChromeConfig.GetMatchingBrowserVersion()
DriverManager.GetVersionToDownload(IDriverConfig config, String version)
DriverManager.SetUpDriver(IDriverConfig config, String version, Architecture architecture)
FirstSeleniumTests.ctor() line 18
My test is getting passed if I remove VersionResolveStrategy.MatchingBrowser argument from SetUpDriver, but correct version of drivers matching my current version of installed browsers will be downloaded only when I pass VersionResolveStrategy.MatchingBrowser argument to the SetUpDriver. Can someone help me to resolve the above error?
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using System;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
using WebDriverManager.Helpers;
using Xunit;
namespace SampleXUnitTestProject
{
public class FirstSeleniumTests : IDisposable
{
private IWebDriver _driver;
public FirstSeleniumTests()
{
new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser);
_driver = new ChromeDriver();
_driver.Manage().Window.Maximize();
}
[Fact]
public void CorrectTitleDisplayed_When_NavigateToHomePage()
{
_driver.Navigate().GoToUrl("https://lambdatest.github.io/sample-todo-app/");
Assert.Equal("Sample page - lambdatest.com", _driver.Title);
}
public void Dispose()
{
_driver.Quit();
}
}
}

Brother QL-700 B-PAC SDK error 'System.IO.FileNotFoundException' in mscorlib.dll

I have the Brother QL-700 label printer and i have installed latest B-PAC SDK V3.2.001 64bit which was released end of last month. Also i have installed "B-PAC client component" on my windows 10 64 bit computer as well. Given template file(addr.LBX) prints successfully from P-touch Editor 5.2.
However B-Pac sdk faild to print from below C# program. It gives below error when executing the given code snippet,
'NamePlt.vshost.exe' (CLR v2.0.50727: NamePlt.vshost.exe): Loaded 'C:\Program Files\Brother bPAC3 SDK\Samples\VCS\NamePlt\bin\Debug\Interop.bpac.dll'. Module was built without symbols.Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.dll
Any support highly appreciated!
private const string TEMPLATE_DIRECTORY = #"C:\Program Files\Brother bPAC3 SDK\Templates\"; // Template file path
private const string TEMPLATE_FILE = "addr.LBX"; // Template file printing fine from the P-touch Editor
public Form1()
{
InitializeComponent();
}
private void btnPrint_Click(object sender, EventArgs e)
{
string templatePath = TEMPLATE_DIRECTORY;
templatePath += TEMPLATE_FILE;
bpac.DocumentClass doc = new DocumentClass();
if (doc.Open(templatePath) != false)
{
//doc.GetObject("objCompany").Text = txtCompany.Text;
//doc.GetObject("objName").Text = txtName.Text;
// doc.SetMediaById(doc.Printer.GetMediaId(), true);
doc.StartPrint("", PrintOptionConstants.bpoDefault);
doc.PrintOut(1, PrintOptionConstants.bpoDefault);
doc.EndPrint();
doc.Close();
MessageBox.Show("Error code : " + doc.ErrorCode);
}
else
{
MessageBox.Show("Open() Error: " + doc.ErrorCode);
}
}

An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll

I was executing code below :
class Program
{
static void Main(string[] args)
{
PerformanceCounter performanceCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", "Intel(R) 82579V Gigabit Network Connection");
Console.WriteLine(performanceCounter.NextValue().ToString());
}
}
I'm getting this exception.
An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll
Additional information: Instance 'Intel(R) 82579V Gigabit Network Connection' does not exist in the specified Category.
I have tested the parameters with windows perfmon tool , it was working but in code its giving exception.
Can anybody please help..
Have you checked if the name is spelled correctly? Even with a minor error, this most likely won't work.
To check which names exist in this category, try (as suggested here: https://stackoverflow.com/a/29270209/1648463)
PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");
String[] instancename = category.GetInstanceNames();
foreach (string name in instancename)
{
Console.WriteLine(name);
}
For example, one of the existing names for network interfaces on my computer is
Intel[R] 82579LM Gigabit Network Connection
(with brackets instead of round brackets).

Unable to cast to System.String in Selenium 2.0 Webdriver NUnit Test Case

Below I'm debugging and throwing an exception on purpose to find out the value of a JavaScript call from WebDriver. How can I cast the jQuery call so I can print a string (based on the number of tr tags in my table with id of "viewtable") in my exception message? I imagine this has absolutely nothing to do with the C# code. I bet the driver can't execute the jQuery call properly, but I don't know the correct syntax.
Exception thrown by NUnit:
Selenium.ProductPricing.TheUntitledTest:
System.InvalidCastException : Unable to cast object of type 'System.Int64' to type 'System.String'.
Environment:
Class Library project is called Selenium.sln/Selenium.csproj
project referencing NUnit dll & Selenium C# client drivers including WebDriver dll files
project has one class class called ProductPricing.cs
running class library dll in NUnit 2.6
Test Case C# code:
(search for "BAD!" below)
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Chrome;
using Selenium;
using System.Text;
using System;
namespace Selenium
{
[TestFixture]
public class ProductPricing
{
private IWebDriver driver;
private StringBuilder verificationErrors;
private string baseURL;
[SetUp]
public void Setup()
{
driver = new FirefoxDriver();
baseURL = "http://buyemp.qa.xxx.com/";
ISelenium selenium = new WebDriverBackedSelenium(driver, baseURL);
selenium.Start();
verificationErrors = new StringBuilder();
}
[TearDown]
public void TeardownTest()
{
try
{
driver.Quit();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual("", verificationErrors.ToString());
}
[Test]
public void TheUntitledTest()
{
//String var_skip_product = "false";
String var_admin_user = "coders#xxx.com";
String var_admin_pass = "notsure";
driver.Navigate().GoToUrl(baseURL + "/admin");
driver.FindElement(By.Id("email")).Clear();
driver.FindElement(By.Id("email")).SendKeys(var_admin_user);
driver.FindElement(By.Id("password")).Clear();
driver.FindElement(By.Id("password")).SendKeys(var_admin_pass);
driver.FindElement(By.CssSelector("input[type=\"submit\"]")).Click();
driver.WaitForElement(By.LinkText("Products"));
driver.FindElement(By.LinkText("Products")).Click();
String var_product_row = "24"; // force script to start on row 24/25
//// ERROR: Caught exception [unknown command [getTableTrCount]]
// Command: getTableTrCount | Target: viewtable | Value: var_table_row_count (user extensions don't work in WebDriver)
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
// this one throws an exception with value 22 - GOOD!
//int x = Convert.ToInt32((string)js.ExecuteScript("return '22'"));
// this one throws an exception with the cast exception - BAD!
int x = Convert.ToInt32((string)js.ExecuteScript("return $('#viewtable tr').length"));
// explicitly throwing Selenium exception so we can debug this code in NUnit
throw new SeleniumException(x.ToString());
// Command: storeText | Target: //a[#title='last page']/text() | Value: var_page_total_text
// Conversion: String var_page_total_text = driver.FindElement(By.XPath("//a[#title='last page']/text()")).Text;
String var_page_total_text = driver.FindElement(By.XPath("//a[#title='last page']")).Text;
//// ERROR: Caught exception [ERROR: Unsupported command [getEval]]
// Command: eval | Target: javascript{storedVars['var_page_total_text'].substring(1,storedVars['var_page_total_text'].length-1)}
//int var_page_total = Convert.ToInt32(var_page_total_text.Substring(1,var_page_total_text.Length-1));
}
private bool IsElementPresent(By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
}
}
Just from the exception I'm assuming that ExecuteScript is returning an int64 for $("query").length and a string for $("query").html().
So you might want to try this:
string x = js.ExecuteScript("return $('#viewtable tr').length").ToString();
or if you prefer a number:
long x = (long)js.ExecuteScript("return $('#viewtable tr').length");
Not sure about the second one but the first one should work.
Seems like this is a bug, or else Selenium doesn't like the assignment of the selector. If you have an idea, let me know. Unless the syntax I'm using for the appended tr in the selector isn't supported in the version of jQuery on this site.
Although that's not the case because the Selenium IDE user extensions custom command below works fine.
function jQuery(selector)
{
return selenium.browserbot.getUserWindow().jQuery(selector);
}
Selenium.prototype.doGetTableTrCount = function(tableName, varStore) {
this.doStore(jQuery('#' + tableName + ' tr').length,varStore);
};
This works:
IWebElement webElement = (RemoteWebElement)js.ExecuteScript("return $('#viewtable').get(0);");
string jQuerySelector = "arguments[0]";
string x = (string)js.ExecuteScript("return $(" + jQuerySelector + ").html()", webElement);
throw new SeleniumException(x);
This works:
string x = (string)js.ExecuteScript("return $('#viewtable').html()");
throw new SeleniumException(x);
This doesn't work:
IWebElement webElement = (RemoteWebElement)js.ExecuteScript("return $('#viewtable tr').get(0);");
string jQuerySelector = "arguments[0]";
string x = (string)js.ExecuteScript("return $(" + jQuerySelector + ").length", webElement);
throw new SeleniumException(x);
This doesn't work:
string x = (string)js.ExecuteScript("return $('#viewtable tr').length");
throw new SeleniumException(x);

Categories

Resources