I have driver.close() and driver.quit() in my code but sometimes app gets crashed and those drivers, chrome.exe and conhosts are still open...
I do not have any idea how to prevent it
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MetroFramework.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Diagnostics;
using OpenQA.Selenium.Support.UI;
namespace WindowsFormsApplication4
{
public partial class Form1 : MetroForm
{
private IWebDriver driver;
private ChromeOptions option;
private List<string[]> list = new List<string[]>();
public Form1()
{
option = new ChromeOptions();
option.AddArgument("--headless --user-agent=Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
InitializeComponent();
LoadEngines();
}
private void LoadEngines() {
List<string[]> lista = File.ReadLines(#"C:\Redirect\sites.txt")
.Select(line => line.Split(','))
.ToList();
for (int i = 0; i < lista.Count; i++)
{
engines.Text += lista[i][0]+ "\r\n";
}
list = lista;
}
private void metroButton1_Click(object sender, EventArgs e)
{
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
service.SuppressInitialDiagnosticInformation = true;
if (inL.Text != String.Empty) {
List<string> inUrls = new List<string>(
inL.Text.Split(new string[] { "\r\n" },
StringSplitOptions.RemoveEmptyEntries));
Debug.WriteLine(inUrls[0]);
}
else
{
status.Text = "Enter Urls";
return;
}
try
{
driver = new ChromeDriver(service, option);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
for (int i = 0; i < list.Count; i++)
{
try
{
driver.Navigate().GoToUrl(list[i][0]);
driver.FindElement(By.XPath(list[i][1])).SendKeys("http://google.com");
driver.FindElement(By.XPath(list[i][2])).Click();
outL.Text += driver.FindElement(By.XPath(list[i][3])).GetAttribute(list[i][4]) + "\r\n";
}
catch (NoSuchElementException err)
{
Logs.Text += $"No such element: {err} could be found.";
continue;
}
}
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
ss.SaveAsFile("C://Image.png",
ScreenshotImageFormat.Png);
}
catch
{
throw;
}
finally
{
driver.Close();
driver.Quit();
driver.Dispose();
}
}
}
}
Edited: So I have added code, maybe it will help to fix my test.
I need to automatically close chromedriver.exe and chrome.exe after every run.
Is remote server a good solutions?
Ideally the chromedriver.exe thread should get purged after driver.quit() call. In case , if it doesn't you can invoke system level commands to do the job. You can create a batch file with the following code :
#echo off
rem just killing stray local chromedriver.exe instances.
taskkill /im chromedriver.exe /f
In your C# code, call this bat at the end of test suite :
System.Diagnostics.Process.Start("c:\\batchfilename.bat");
Related
What i'm trying to do is use the Selenium WebDriver to control Chrome instead of using Javascript, so basically combine Selenium & cefsharp so I can use .sendKeys().
I have docked the browser in a panel here panelBrowserMain.Controls.Add(browser); and read the official docs here: https://bitbucket.org/chromiumembedded/cef/wiki/UsingChromeDriver.md this example loads a seperate client cefClient.exe where as I just want to interact using my embedded browser located here panelBrowserMain.Controls.Add(browser);.
When I do a testing at LinkLabel1_LinkClicked to show the page source i'm getting System.NullReferenceException: Object reference not set to an instance of an object. errors, so the _driver is not being assigned (even though I do in the code)
I have Google'd quite a bit and their is hardly any information or solutions that I can see, is my code even correct, any help or tips would be appreciated.
using CefSharp;
using CefSharp.WinForms;
using OpenQA.Selenium.Chrome;
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows.Forms;
namespace projectname
{
public partial class FormBrowser : Form
{
public ChromiumWebBrowser browser;
private ChromeDriver _driver;
private void FormBrowser_Load(object sender, EventArgs e)
{
try
{
// Fix for the formClosing event not firing.
FormClosing += new FormClosingEventHandler(FormBrowser_FormClosed);
Text = string.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}", Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion);
}
catch (Exception ex)
{
ClassHelpers.DebugLogging($"[{DateTime.Now}]-[{ex}]");
}
}
private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
ClassHelpers.ReturnMessage(_driver.PageSource);
//_driver.FindElement(By.Name("user[profile_attributes][first_name]")).SendKeys("UserName");
}
catch (Exception ex)
{
ClassHelpers.DebugLogging($"[{DateTime.Now}]-[{ex}]");
}
}
public FormBrowser(string[] sites, string mode, FormMain formMain, ClassProject project)
{
InitializeComponent();
InitializeBrowser(sites, project);
}
public void InitializeBrowser(string[] sites, ClassProject project)
{
try
{
if (!Cef.IsInitialized)
{
// CEF.
CefSettings settings = new CefSettings()
{
LogFile = "cef/cefsharp.log",
CachePath = Path.GetFullPath("cef/cache/"),
UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"
};
settings.BrowserSubprocessPath = Path.GetFullPath("cef/cefsharp/CefSharp.BrowserSubprocess.exe");
settings.LocalesDirPath = Path.GetFullPath("cef/cefsharp/locales");
settings.ResourcesDirPath = Path.GetFullPath("cef/cefsharp/");
settings.RemoteDebuggingPort = 8088;
settings.UserDataPath = Path.GetFullPath("cef/cefsharp/cefuserdata");
if (project.Proxy != "ip:port")
{
settings.CefCommandLineArgs.Add("proxy-server", project.Proxy);
}
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
// CEF.
sitesCount = sites.Count();
// Load in the first URL that was checked, which is index 0.
browser = new ChromiumWebBrowser(sites[counter])
{
MenuHandler = new MyCustomMenuHandler()
};
browser.AddressChanged += OnBrowserAddressChanged;
panelBrowserMain.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
browserMain.Text = sites[counter];
// Selenium WebDriver.
ChromeOptions options = new ChromeOptions
{
DebuggerAddress = "localhost:8088"
};
options.AddArguments("--no-sandbox");
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
_driver = new ChromeDriver(service, options, TimeSpan.FromSeconds(180));
// Selenium WebDriver.
}
else
{
// IMPORTANT: Cef is already initialized, do not do it again.
browser = new ChromiumWebBrowser(sites[counter])
{
MenuHandler = new MyCustomMenuHandler()
};
browser.AddressChanged += OnBrowserAddressChanged;
panelBrowserMain.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
browserMain.Text = sites[counter];
// Add the code here once we get it working above.
}
}
catch (Exception ex)
{
ClassHelpers.DebugLogging($"[{DateTime.Now}]-[{ex}]");
}
}
}
}
I wrote the following script on my computer at work, where the script ran perfectly. However, I can't get it to run on my computer at home. I have the exact version of Visual Studio installed.
I click build, it successfully builds, however, it doesn't lead to the test being added to the test explorer.
My code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
using OpenQA.Selenium.Support.UI;
namespace TrainLineTest
{
public class Program
{
public static IWebDriver driver = new ChromeDriver();
public static void Main(string[] args)
{ }
public static void SetUp()
{
driver.Manage().Window.Maximize();
driver.Url = "https://www.thetrainline.com";
}
[Test]
public static void EnterDetails()
{
SetUp();
var OriginStation = driver.FindElement(By.Id("originStation"));
OriginStation.SendKeys("London Euston");
var DestinationStation = driver.FindElement(By.Id("destinationStation"));
DestinationStation.SendKeys("Manchester Picadilly");
var TravelMethod = driver.FindElement(By.Id("journey-type-return"));
TravelMethod.Click();
var OutDate = driver.FindElement(By.Id("outDate"));
OutDate.Clear();
OutDate.SendKeys("26-Aug-17");
OutDate.SendKeys(Keys.Tab);
Thread.Sleep(700);
new SelectElement(driver.FindElement(By.Id("outDepartOrArrive"))).SelectByValue("B");
Thread.Sleep(700);
new SelectElement(driver.FindElement(By.Id("outHour"))).SelectByValue("9");
new SelectElement(driver.FindElement(By.Id("outMinute"))).SelectByValue("30");
Thread.Sleep(700);
var ReturnDate = driver.FindElement(By.Id("returnDate"));
ReturnDate.Clear();
ReturnDate.SendKeys("15-Sep-17");
ReturnDate.SendKeys(Keys.Tab);
Thread.Sleep(500);
new SelectElement(driver.FindElement(By.Id("returnDepartOrArrive"))).SelectByValue("B");
Thread.Sleep(500);
new SelectElement(driver.FindElement(By.Id("returnHour"))).SelectByValue("14");
new SelectElement(driver.FindElement(By.Id("returnMinute"))).SelectByValue("30");
Thread.Sleep(500);
var Passengers = driver.FindElement(By.ClassName("passenger-summary-people"));
Passengers.Click();
Thread.Sleep(500);
new SelectElement(driver.FindElement(By.Name("AdultsTravelling"))).SelectByValue("2");
Thread.Sleep(500);
new SelectElement(driver.FindElement(By.Name("ChildrenTravelling"))).SelectByValue("1");
Thread.Sleep(500);
var JourneyComplete = driver.FindElement(By.CssSelector("#extendedSearchForm > div:nth-child(6) > div:nth-child(1) > div > div > button"));
JourneyComplete.Click();
Thread.Sleep(5000);
var ExtendedSearch = driver.FindElement(By.Id("submitButton"));
ExtendedSearch.Click();
Thread.Sleep(5000);
}
[TearDown]
public void CloseApp()
{
driver.Close();
}
}
}
If you are using NUnit3, you'll need to get NUnit3TestAdapter from the NuGet package manager. Once you have this package you'll be able to build your solution and have them show in Visual Studio's Test Explorer
i want to connect the myo wristband to the hololens. This is the end goal, but I am anyway but close to that :-/
The idea is to set up a Bluetooth LE Connection with UWP.
I wanted to do this, as explanined in this Microsoft Document
The search for the devices workes fine, but when I try to connect to a device, this line (Point "Connecting to the device"
): GattDeviceServicesResult result = await device.GetGattServicesAsync();
raises the error:
System.InvalidCastException: "Unable to cast object of type
'Windows.Devices.Bluetooth.BluetoothLEDevice' to type
'Windows.Devices.Bluetooth.IBluetoothLEDevice3'."
I have no idea what the IBluetoothLEDevice3 has to do there :-)
I was not able to find a solution for this on the microsoft documentation or the internet :-/
I work on Visual Studio 2017, build for Windows 10 (15063) and Bluetooth is enabled in the manifest.
This is my code so fare. I added only one thing and that is the Task. I wanted to make sure, that the BluetoothLEDDevice is not null or anything, since it is not synchron. Without its not working either.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Diagnostics;
using Windows.Devices.Enumeration;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth.Advertisement;
// Die Elementvorlage "Leere Seite" wird unter https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x407 dokumentiert.
namespace Bluetooth17
{
/// <summary>
/// Eine leere Seite, die eigenständig verwendet oder zu der innerhalb eines Rahmens navigiert werden kann.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
blue();
}
void blue()
{
// Query for extra properties you want returned
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
DeviceWatcher deviceWatcher =
DeviceInformation.CreateWatcher(
BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
// Added, Updated and Removed are required to get all nearby devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
// EnumerationCompleted and Stopped are optional to implement.
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start the watcher.
deviceWatcher.Start();
}
private void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
{
Debug.WriteLine("Stopped");
}
private void DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object args)
{
Debug.WriteLine("Enum complete");
}
private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
{
Debug.WriteLine(args.Id + " Removed");
}
private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
{
Debug.WriteLine(args.Id + " Update");
}
private void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
{
Debug.WriteLine(args.Id + " " + args.Name);
if (args.Name.Equals("Myo"))
{
Debug.WriteLine("Try to connect to Myo");
getServices(args);
}
}
async Task<BluetoothLEDevice> ConnectDevice(DeviceInformation deviceInfo)
{
Debug.WriteLine("Asyc");
// Note: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent.
return await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);
}
async void getServices(DeviceInformation deviceInfo)
{
Task<BluetoothLEDevice> task = ConnectDevice(deviceInfo);
task.Wait();
BluetoothLEDevice device = task.Result;
GattDeviceServicesResult result = await device.GetGattServicesAsync();
if (result.Status == GattCommunicationStatus.Success)
{
var services = result.Services;
// ...
}
}
}
}
Thank you
If you target your application to Build 15063 and you know the device you are connecting to than just use:
device = await BluetoothLEDevice.FromBluetoothAddressAsync(blueToothAddress);
This is much more stable than your code and no need for device watcher.
Here is an example that works for my device(not a MIO but a HM10) :
using System;
using System.Diagnostics;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.UI.Xaml.Controls;
namespace App1
{
public sealed partial class MainPage : Page
{
private BluetoothLEDevice device;
GattDeviceServicesResult serviceResult = null;
public MainPage()
{
this.InitializeComponent();
StartDevice();
}
private async void StartDevice()
{
//To get your blueToothAddress add: ulong blueToothAddress = device.BluetoothAddress to your old code.
ulong blueToothAddress = 88396936323791; //fill in your device address!!
device = await BluetoothLEDevice.FromBluetoothAddressAsync(blueToothAddress);
if (device != null)
{
string deviceName = device.DeviceInformation.Name;
Debug.WriteLine(deviceName);
int servicesCount = 3;//Fill in the amount of services from your device!!
int tryCount = 0;
bool connected = false;
while (!connected)//This is to make sure all services are found.
{
tryCount++;
serviceResult = await device.GetGattServicesAsync();
if (serviceResult.Status == GattCommunicationStatus.Success && serviceResult.Services.Count >= servicesCount)
{
connected = true;
Debug.WriteLine("Connected in " + tryCount + " tries");
}
if (tryCount > 5)//make this larger if faild
{
Debug.WriteLine("Failed to connect to device ");
return;
}
}
}
}
}
}
NEED A SOLUTION
Background agent is working only once. After There is no occurrence of a background agent. It works at the first time and it works perfectly as soon as the page opens. however, after that it takes forever and ever to do that again. sometimes page close and open doesn't work. that would probably because of not removing the agenet
My background Agent Code:
#define DEBUG_AGENT
using System;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Info;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Threading;
using Microsoft.Xna.Framework.Media;
using System.Windows.Input;
using Microsoft.Devices;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.Net.Sockets;
using System.Text;
using System.Net;
namespace ScheduledTaskAgent1
{
public class ScheduledAgent : ScheduledTaskAgent
{
private static volatile bool _classInitialized;
//private DispatcherTimer s;
Socket _socket = null;
ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 5000;
const int MAX_BUFFER_SIZE = 2048;
double lat = 7.16126666666667;
static ScheduledAgent()
{
// Subscribe to the managed exception handler
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Application.Current.UnhandledException += UnhandledException;
});
}
/// Code to execute on Unhandled Exceptions
private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
protected override void OnInvoke(ScheduledTask task)
{
//TODO: Add code to perform your task in background
string toastTitle = "";
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
lat += 0.001;
string snmea = DD2NMEA(lat, 80.44506);
string dates = DateTime.UtcNow.ToString("ddMMyy");
string UTCTime = DateTime.UtcNow.ToString("hhmmss") + ".000";
string s1 = Checksum("$FRCMD,869444005499999,_SendMessage,,0809.67600,N,8050.70360,E,1.0,1.08,3.0,141013,055642.000,1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
string s = Send("$FRCMD,869444005499999,_SendMessage,," + snmea + ",1.0,1.08,3.0," + dates + "," + UTCTime + ",1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
startToastTask(task, toastTitle);
}
private void startToastTask(ScheduledTask task, string toastTitle)
{
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
#endif
// Call NotifyComplete to let the system know the agent is done working.
NotifyComplete();
}
}
}
My Page from app which calls the agent
PeriodicTask toastPeriodicTask;
const string toastTaskName = "ToastPeriodicAgent";
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
toastPeriodicTask = ScheduledActionService.Find(toastTaskName) as PeriodicTask;
StartPeriodicAgent(toastTaskName);
}
private void StartPeriodicAgent(string taskName)
{
toastPeriodicTask = ScheduledActionService.Find(taskName) as PeriodicTask;
if (toastPeriodicTask != null)
{
RemoveAgent(taskName);
}
toastPeriodicTask = new PeriodicTask(taskName);
toastPeriodicTask.Description = periodicTaskDesc;
try
{
ScheduledActionService.Add(toastPeriodicTask);
#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(2));
#endif
}
catch (InvalidOperationException exception)
{
if (exception.Message.Contains("BNS Error: The action is disabled"))
{
MessageBox.Show("Background agents for this application have been disabled by the user.");
}
else if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
{
MessageBox.Show("BNS Error: The maximum number of ScheduledActions of this type have already been added.");
}
else
{
MessageBox.Show("An InvalidOperationException occurred.");
}
}
catch (SchedulerServiceException)
{
}
}
Ensure that your project has DEBUG_AGENT defined. This is a setting within your project properties. To set this flag, follow these steps
Right click the project within VS and select Properties
Select the Build tab
Add DEBUG_AGENT to the "Conditional compilation symbols" field.
If that is set, I've found it's best to give at least 30 seconds in the LaunchForTest. Sometimes it doesn't quite schedule it when you tell it to.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Security;
namespace SampleProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String input = textBox1.Text;
try
{
Process ps = new Process();
ps.StartInfo.FileName = #"\\199.63.55.163\d$\hello.bat";
ps.StartInfo.Arguments = input;
ps.StartInfo.CreateNoWindow = false;
String domain = ps.StartInfo.Domain;
ps.StartInfo.RedirectStandardOutput = true;
ps.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
ps.StartInfo.WorkingDirectory = #"d:\praveen";
ps.StartInfo.UserName = "Raj";
ps.StartInfo.Domain = "domain";
ps.StartInfo.Password = Encrypt("Hello123");
ps.StartInfo.UseShellExecute = false;
ps.Start();
ps.WaitForExit();
MessageBox.Show(ps.StandardOutput.ReadToEnd());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void label1_Click(object sender, EventArgs e)
{
}
public static SecureString Encrypt(String pwd)
{
SecureString ss = new SecureString();
for (int i = 0; i < pwd.Length; i++)
{
ss.AppendChar(pwd[i]);
}
return ss;
}
}
}
It's a shot in the dark, but I think that you can't read the processes standard output once it has exited.
Also you have to redirect it - take a look at this documentation: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
Duplicate of .NET Process Start Process Error using credentials (The handle is invalid) ? You need to assign RedirectStandardInput, RedirectStandardOutput, RedirectStandardError