Selenium: web application dead and not running launched with Selenium using C# - c#

I am new to automation, I just learned about Selenium for 3 days and built a simple C# console application with Selenium which trying to automate "sell" request on a trading website.
I noticed when I login the trading website with normal Chrome, the site is working as normal. But when I launch it with my C# console app, it seems like the trading website is not functioning as normal, seems dead.
Here I attached with both developer console picture as reference.
Normal Chrome browser:
enter image description here
Launched with C# console app:
enter image description here
Am I missing any part of my code, and cause the launched Chrome is being "locked".
Please help me
below is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
namespace ii.tfxBot
{
class Program
{
static void Main(string[] args)
{
string ExecuteUrl = "https://tex.tfxi.com/#/exchange/tfx_usdt";
Console.WriteLine("test case started ");
//create the reference for the browser
//new DriverManager().SetUpDriver(new ChromeConfig());
var ccOptions = new ChromeOptions();
ccOptions.LeaveBrowserRunning = true;
//ccOptions.AttachToEdgeChrome = true;
//change the path accordingly
//ccOptions.EdgeExecutablePath = "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe";
new DriverManager().SetUpDriver(new ChromeConfig());
var driver = new ChromeDriver(#"C:\WebDriver\bin", ccOptions);
// navigate to URL
driver.Navigate().GoToUrl("https://tex.tfxi.com/#/login");
Thread.Sleep(2000);
// identify the Google search text box
//IWebElement ele = driver.FindElement(By.Name("q"));
////enter the value in the google search text box
//ele.SendKeys("javatpoint tutorials");
//Thread.Sleep(2000);
////identify the google search button
//IWebElement ele1 = driver.FindElement(By.Name("btnK"));
//// click on the Google search button
//ele1.Click();
bool isUrl = false;
while (isUrl == false)
{
if (driver.Url == ExecuteUrl)
{
StartExecution(driver);
break;
}
Console.WriteLine("Execute Url not matched... try again in 1 second");
Thread.Sleep(5000);
}
//close the browser
//driver.Close();
Thread.Sleep(8000000);
Console.WriteLine("test case ended ");
}
private static void StartExecution(ChromeDriver driver)
{
var inputElements = driver.FindElements(By.CssSelector(".ivu-input.ivu-input-default"));
int i = 0;
foreach (var inputElement in inputElements)
{
Console.WriteLine("input count " + i.ToString() + " : " + inputElement.GetAttribute("placeholder").ToString());
string plText = inputElement.GetAttribute("placeholder").ToString();
if (plText == "出售數量")
{
Console.WriteLine("found the input number: " + i.ToString());
}
else
{
//inputElement.SendKeys("28000");
}
i++;
}
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(300));
IWebElement divLimit;
bool found = false;
while (found == false)
{
//divLimit = driver.FindElement(By.ClassName("bd bd_limited"));
//divLimit = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("bd bd_limited")));
divLimit = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(".bd.bd_limited"))); ;
if (divLimit != null)
{
Console.WriteLine("item found, proceed to get selling price!");
GetSellingPrice(divLimit);
break;
}
Console.WriteLine("item NOT found!");
Thread.Sleep(300);
}
int tfxBal = GetTfxBalance(driver);
WaitforElement(driver, By.CssSelector(".mask2"), tfxBal);
}
public static int GetTfxBalance(ChromeDriver driver)
{
int TfxBal = 0;
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(300));
IWebElement divHdLogin;
divHdLogin = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(".hd.hd_login")));
//(IWebElement)driver.FindElements(By.CssSelector(".hd.hd_login"));
var targetKeys = divHdLogin.FindElements(By.TagName("span"));
Console.WriteLine("targetKeys 0 : " + targetKeys[0].Text);
Console.WriteLine("targetKeys 1 : " + targetKeys[1].Text);
Console.WriteLine("targetKeys 2 : " + targetKeys[2].Text);
decimal o = Convert.ToDecimal(targetKeys[1].Text);
if (targetKeys[1].Text.Contains("."))
{
var a = targetKeys[1].Text.Split('.');
TfxBal = Convert.ToInt32(a[0]);
}
else
{
TfxBal = Convert.ToInt32(targetKeys[1].Text);
}
return TfxBal;
}
public static void GetSellingPrice(IWebElement divLimit)
{
IWebElement divFormContent = divLimit.FindElement(By.CssSelector(".ivu-form-item-content"));
IWebElement ipSellPrice = divFormContent.FindElement(By.CssSelector(".ivu-input.ivu-input-default"));
Console.WriteLine(ipSellPrice.GetAttribute("value"));
}
public static bool Elexists(By by, WebDriver driver)
{
try
{
driver.FindElement(by);
IWebElement divPopup = driver.FindElement(by);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(300));
// textLeft countNumber
IWebElement divcountNumber;
divcountNumber = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(".textLeft.countNumber")));
//Console.WriteLine("count number: " + divcountNumber.Text);
string popupStyle = divPopup.GetAttribute("style");
//Console.WriteLine("div Popup Style : " + popupStyle);
if (popupStyle == "display: none;")
{
//Console.WriteLine("No Pop up..");
return false;
}
else
{
Console.WriteLine("Pop up display has changed!");
return true;
}
}
catch (NoSuchElementException)
{
return false;
}
}
public static void WaitforElement(WebDriver driver, By by, int tfxBalance = 0)
{
// waitforMin = 2 hours
int waitforMin = 60 * 1000 * 2 * 2 * 2;
for (int i = 0; i < waitforMin; i++)
{
System.Threading.Thread.Sleep(250);
if (Elexists(by, driver))
{
Console.WriteLine("Pop up appears! Performing selling now");
var inputElements = driver.FindElements(By.CssSelector(".ivu-input.ivu-input-default"));
IWebElement SellBtn = driver.FindElement(By.CssSelector(".bg-red.ivu-btn.ivu-btn-default.ivu-btn-long"));
foreach (var inputElement in inputElements)
{
string plText = inputElement.GetAttribute("placeholder").ToString();
if (plText == "出售數量")
{
Console.WriteLine("found the input box");
inputElement.SendKeys("28000");
SellBtn.Click();
}
}
break;
}
Console.Write(".");
}
}
public static void SellTfx()
{
//
}
}
}
I am expecting some solution to fix my code

Related

How can I make an auto injection detector in c#?

I want to make an auto injection scanner in any given website and I have to use c#.
I tried some things that I found online and none of them worked for me, until i find selenium but i keep getting this error message: "OpenQA.Selenium.ElementNotInteractableException: 'element not interactable", and I have no idea why.
I didn't find anything helpful online and I think the problem may be with selenium.
I tried to find SQL, JS and BASH injections, but the script fails when i try to interact with an input. I am using OWASP juice shop to test my code.
This is my code:
static int _crntTypeOfInjection;
const int ESQL = 0, EJS = 1, EBASH = 2;
static public bool IsImportantInput(string type)
{
bool valid = false;
string[] importantTypes = new string[] { "text", "email", "password", "search", "url" };
foreach (string check in importantTypes)
{
if (type == check)
{
return true;
}
}
return false;
}
public static string getCrntInjection()
{
switch (_crntTypeOfInjection)
{
case ESQL:
return "\' OR 1=1;--";
break;
case EBASH:
return "; echo Test";
break;
case EJS:
return "<img src=\"http:\\\\url.to.file.which\\not.exist\" onerror=alert(\"JS injection success\");>";
break;
}
return "defult";
}
static public bool AttackSuccessful(string normalPage, string InjectedPage, string MainUrl, string afterClickUrl)
{
if (afterClickUrl != MainUrl || InjectedPage.Contains("Internal Server Error") || InjectedPage.Contains("JS injection success") || InjectedPage.Contains("Test"))
{
return true;
}
return false;
}
static public void Injection(string url)
{
string InjectedPage = "", NormalPage = "", AfterClickUrl = "";
var driver = new ChromeDriver("C:\\Users\\nirya\\");
driver.Url = url;
Console.WriteLine(driver.PageSource);
Actions a = new Actions(driver);
foreach (var button in driver.FindElements(By.CssSelector("button")))
{
// INJECTED PAGE
a.MoveByOffset(0, 0).Click().Perform();
foreach (IWebElement input in driver.FindElements(By.TagName("input")))
{
Console.WriteLine(input.Text);
Console.WriteLine(input.TagName);
try
{
if (IsImportantInput(input.GetAttribute("type")))
{
input.Click(); // *** HERE IS THE PROBLEM ***
input.Clear();
input.SendKeys(getCrntInjection());
}
}
catch (NoSuchElementException)
{
continue;
}
}
button.Click();
InjectedPage = driver.PageSource;
AfterClickUrl = driver.Url;
driver.Navigate().Back();
// NORMAL PAGE
a.MoveByOffset(0, 0).Click().Perform();
foreach (IWebElement input in driver.FindElements(By.CssSelector("input")))
{
try
{
if (IsImportantInput(input.GetAttribute("type")))
{
input.Clear();
input.SendKeys("normal");
}
}
catch (NoSuchElementException)
{
continue;
}
}
button.Click();
NormalPage = driver.PageSource;
driver.Navigate().Back();
if (AttackSuccessful(NormalPage, InjectedPage, url, AfterClickUrl))
{
// add to database
}
}
}
static void Main(string[] args)
{
Injection("http://localhost:3000/#/login");
}
Is there a problem with my code? Or is there another library that i can use instead?

Extend Report in C# for Multiple Test Classes is NOT working?

Base class is Report Class and Other two Test classes 1.TelerikOutlook and 2.UnitTest1
I am Extended Report class in to Both Classes but in html Report file only last test report details is displayed
it is Not working properly the Report is Generated but contains only last test class
using AventStack.ExtentReports;
using AventStack.ExtentReports.Reporter;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Outlook
{
public class Report
{
protected ExtentReports _extent;
protected ExtentTest _test;
public Report()
{ }
[OneTimeSetUp]
public void BeforeClass()
{
try
{
//To create report directory and add HTML report into it
_extent = new ExtentReports();
var dir = AppDomain.CurrentDomain.BaseDirectory.Replace("\\bin\\Debug", "");
DirectoryInfo di = Directory.CreateDirectory(dir + "\\Test_Execution_Reports");
var htmlReporter = new ExtentHtmlReporter(dir + "\\Test_Execution_Reports" + "\\Automation_Report" + ".html");
_extent.AddSystemInfo("Environment", "Journey of Quality");
_extent.AddSystemInfo("User Name", "Sanoj");
_extent.AttachReporter(htmlReporter);
}
catch (Exception e)
{
throw (e);
}
}
[SetUp]
public void BeforeTest()
{
try
{
_test = _extent.CreateTest(TestContext.CurrentContext.Test.Name);
}
catch (Exception e)
{
throw (e);
}
}
[TearDown]
public void AfterTest()
{
try
{
var status = TestContext.CurrentContext.Result.Outcome.Status;
var stacktrace = "" + TestContext.CurrentContext.Result.StackTrace + "";
var errorMessage = TestContext.CurrentContext.Result.Message;
Status logstatus;
switch (status)
{
case TestStatus.Failed:
logstatus = Status.Fail;
// string screenShotPath = Capture(driver,
TestContext.CurrentContext.Test.Name);
_test.Log(logstatus, "Test ended with " + logstatus + " – " + errorMessage);
// _test.Log(logstatus, "Snapshot below: "
+_test.AddScreenCaptureFromPath(screenShotPath));
break;
case TestStatus.Skipped:
logstatus = Status.Skip;
_test.Log(logstatus, "Test ended with " + logstatus);
break;
default:
logstatus = Status.Pass;
_test.Log(logstatus, "Test ended with " + logstatus);
break;
}
}
catch (Exception e)
{
throw (e);
}
}
[OneTimeTearDown]
public void AfterClass()
{
try
{
_extent.Flush();
}
catch (Exception e)
{
throw (e);
}
}
}
}
Telerik class extends Report class
Test case 1 ->
using NUnit.Framework;
using System;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using TestStack.White;
using TestStack.White.Configuration;
using TestStack.White.InputDevices;
using TestStack.White.UIItems;
using TestStack.White.UIItems.Finders;
using TestStack.White.UIItems.WindowItems;
namespace Outlook
{
[TestFixture]
public class TelerikOutlook : Report
{
[Test]
public void TestMethod()
{
_test = _extent.CreateTest("TestMethod");
var outlook_path ="C:\\jUsers\\ajay.b\\AppData\\Local\\Apps\\2.0\\
OA613NLD.BW2\\PTQ504M2.OJL\\tele..tion_0ec16cac1aa370e1_0
7e2.0002_8d746ee446d800cb\\TelerikOutlookInspiredApp.EXE";
// launch the application
var application = Application.Launch(outlook_path);
//Thread.Sleep(70000);
//Application Window
var window = application.GetWindow("My Application");
// wait till window visible
window.WaitTill(delegate () { return window.Visible; });
var calendarBtn = window.Get(SearchCriteria.ByText("Calendar"));
Mouse.Instance.Location = calendarBtn.ClickablePoint;
Mouse.Instance.Click();
//Calendar window
var calendar = application.GetWindow("mark#telerikdomain.com - calendar");
#region Current Month View
var day = calendar.Get(SearchCriteria.ByText("26"));
Mouse.Instance.Location = day.ClickablePoint;
Mouse.Instance.Click();
#endregion
#region Create Appointment
//to enable Create Appointment Button
Point p = new Point(674, 377);
Mouse.Instance.Click(p);
//click on create appointment Buttton
var appointment = calendar.Get(SearchCriteria.ByText("Create appointment"));
// var list = calendar.Get(SearchCriteria.ByText("03-02-2020 00:00:00"));
Mouse.Instance.Location = appointment.ClickablePoint;
Mouse.Instance.Click();
//Get Window of Create Appointment
var appointmentWindows = application.GetWindows();
Window appointmentWindow = null;
foreach (var item in appointmentWindows)
{
if (item.Name == "Telerik.Windows.Controls.AppointmentDialogViewModel")
{
appointmentWindow = item;
}
}
//appointmentWindow = application.GetWindow("Appointment-Untitled");
//Subject Input field
var subject = appointmentWindow.Get<TextBox>(
SearchCriteria.ByAutomationId("SubjectTextBox"));
// CoreAppXmlConfiguration.Instance.BusyTimeout = 20000;
// subject.ClickAtCenter();
Mouse.Instance.Location = subject.ClickablePoint;
Mouse.Instance.Click();
Thread.Sleep(1000);
Keyboard.Instance.Enter("Automated Subject of appointment");
//Description Input field
var description = appointmentWindow.Get<TextBox>
(SearchCriteria.ByAutomationId("DescriptionTextBox"));
Mouse.Instance.Location = description.ClickablePoint;
Mouse.Instance.Click();
Thread.Sleep(1000);
Keyboard.Instance.Enter("Automated Description of appointment");
//Start time input
var startDate = appointmentWindow.Get(SearchCriteria.ByAutomationId("PART_DateTimeInput"));
Mouse.Instance.Location = startDate.ClickablePoint;
Mouse.Instance.Click();
Thread.Sleep(1000);
Keyboard.Instance.Enter("06-02-2020 00:00");
//save n close of appointment
var okBtn = appointmentWindow.Get(SearchCriteria.ByAutomationId("OKButton"));
Mouse.Instance.Location = okBtn.ClickablePoint;
Mouse.Instance.Click();
#endregion
#region Drag N Drop Element
//getting appointment element and drop at any date
var drag = calendar.Get(SearchCriteria.ByText("abcd : 06-02-2020 00:00:00 - 06-02-2020
00:00:00"));
var drop = calendar.Get(SearchCriteria.ByText("03-02-2020 00:00:00"));
Point d = drag.ClickablePoint;
Thread.Sleep(2000);
application.WaitWhileBusy();
Thread.Sleep(2000);
// drag.Click();
// Mouse.Instance.DragAndDrop(drag,drop);
// Thread.Sleep(2000);
Mouse.Instance.Click(d);
Mouse.LeftDown();
// Thread.Sleep(2000);
var stepCount = 30;
var stepAmount = (float)(drag.ClickablePoint.Y - drop.ClickablePoint.Y) / stepCount;
for (var i = 0; i < stepCount; i++)
{
Mouse.Instance.Location = new Point(Mouse.Instance.Location.X, Mouse.Instance.Location.Y
- stepAmount);
Thread.Sleep(75);
}
Thread.Sleep(2000);
Mouse.LeftUp();
Thread.Sleep(2000);
#endregion
application.Close();
}
}
}
UnitTest1 extends Report class
Testcase 2-
using System;
using System.IO;
using TestStack.White;
using TestStack.White.UIItems.Finders;
using TestStack.White.Factory;
using System.Runtime.InteropServices;
using Outlook1 = Microsoft.Office.Interop.Outlook;
using System.Threading;
using System.Linq;
using TestStack.White.UIItems;
using TestStack.White.UIItems.WindowItems;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AventStack.ExtentReports;
using AventStack.ExtentReports.Reporter;
namespace Outlook
{
[TestClass]
public class UnitTest1 : Report
{
[TestMethod]
public void TestMethod12()
{
_test = _extent.CreateTest("TestMethod12");
//var outlookPath = Path.Combine(
// Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
// #"Microsoft Office\Office16\OUTLOOK.EXE");
//var application = Application.Launch(outlookPath);
var outlook_path = "C:\\jProgram Files\\Microsoft Office\\root\\Office16\\OUTLOOK.EXE";
//verify the path
Assert.AreEqual(outlook_path, "C:\\Program Files\\Microsoft
Office\\root\\Office16\\OUTLOOK.EXE");
// launch the application
var application = Application.Launch(outlook_path);
Thread.Sleep(2000);
//verify the launched application
Assert.AreEqual(application.Name, "OUTLOOK");
// var windows1 = application.GetWindows();
// get explorer window
var explorer = application.GetWindow("Inbox - ajay.bhosale#afourtech.com - Outlook");
explorer.DisplayState = DisplayState.Maximized;
//verify the screen
Assert.AreEqual(explorer.Name, "Inbox - ajay.bhosale#afourtech.com - Outlook");
// click "New E-mail" button to start composing new email
var newEmailBtn = explorer.Get(SearchCriteria.ByText("New Email"));
newEmailBtn.Click();
//verify "New E-mail" Button is clicked
Assert.IsTrue(newEmailBtn.Enabled);
// get composer window
var composer = application.GetWindow(
SearchCriteria.ByText("Untitled - Message (HTML) "),
InitializeOption.NoCache);
//verify create appointment window
Assert.AreEqual(composer.Name, "Untitled - Message (HTML) ");
// fill out "To" field
var toField = composer.Get<TextBox>
(SearchCriteria.ByClassName("RichEdit20WPT").AndByText("To"));
toField.Enter("ajay.bhosale#afourtech.com");
//verify input text of "To" field
Assert.IsTrue(toField.Text.Equals("ajay.bhosale#afourtech.com"));
// fill out "Subject" field
var subjectField = composer.Get<TextBox>
(SearchCriteria.ByClassName("RichEdit20WPT").AndByText("Subject"));
subjectField.Enter("Test Automated UI email");
//verify input text of "Subject" field
Assert.IsTrue(subjectField.Text.Equals("Test Automated UI email"));
//var message = composer.Get(SearchCriteria.ByText("Untitled Message"));
//message.Enter("asdfghjklkjhgfdsasdfghjkkjhgfdssdfghjklkjhgfds");
//Thread.Sleep(2000);
//var message = composer.Get(SearchCriteria.ByText("Message"));
//message.GetType();
//message.SetValue("Automated appointment message");
//message.Enter("Automated appointment message");
//change focus to get Outlook process registered in running object table
Thread.Sleep(5000);
var windows = WindowFactory.Desktop.DesktopWindows();
//Thread.Sleep(20000);
var desktop = windows.Last().GetElement(SearchCriteria.ByClassName("SysListView32"));
// Thread.Sleep(15000);
desktop.SetFocus();
Thread.Sleep(15000);
Outlook1.Application outlookCom = Marshal.GetActiveObject("Outlook.Application") as Outlook1.Application;
var sentMailItem = outlookCom.ActiveInspector().CurrentItem as Outlook1.MailItem;
var body = sentMailItem.Body;
//var body = sentMailItem.HTMLBody;
//var index = body.IndexOf(#"</body", StringComparison.InvariantCultureIgnoreCase);
//var index1 = body.IndexOf(#"</p", StringComparison.InvariantCultureIgnoreCase);
var bodydata = "Hi, " + " " + "\n This is an Automated Email. \n" + "Thanks & Regards \n" + "Afourtech Pvt Ltd. ";
//sentMailItem.HTMLBody = body.Insert(bodydata);
sentMailItem.Body = body.Insert(1, bodydata);
//click on send button
var send = composer.Get(SearchCriteria.ByText("Send").AndByClassName("Button"));
Thread.Sleep(3000);
send.Click();
//verify save and close button is clicked
Assert.IsFalse(send.Visible);
// give Outlook time to send off the email
Thread.Sleep(TimeSpan.FromSeconds(5));
application.WaitWhileBusy();
explorer.Close();
application.Close();
}
}
}
If the test classes extend the Report class, then the [OneTimeSetUp] will run before each class. You can create a new class marked [SetUpFixture] for the [OneTimeSetUp] and [OneTimeTearDown] methods, and this way they will only run before/after ALL test classes.
What Andrea says here worked for me.
I have a Base Test class that is inheriting from the Reporter class. And my test classes inherit Base.
I added [SetUpFixture] to my Reporter class and then added the methods for OneTimeSetUp and OneTimeTearDown here.

The type or namespace name 'BluetoothAddress' could not be found

I use vs 2017 and windows 7.
I have installed 32feet.NET following this: Looking to write Bluetooth 'hcitool' equivelant in Windows.
But I get the errors:
The type or namespace name 'BluetoothAddress' could not be found
The type or namespace name 'BluetoothClient' could not be found
The type or namespace name 'BluetoothSecurity' could not be found
The type or namespace name 'BluetoothDeviceInfo' could not be found
The type or namespace name 'ServiceRecord' could not be found
I have successfully installed InTheHand.Devices.Bluetooth and There is no warning in the using sentence so the namespace is successfully referenced.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using InTheHand.Devices.Bluetooth;
using InTheHand.Networking;
using InTheHand.Networking.Sockets;
using InTheHand;
using System.Diagnostics;
using System.Net.Sockets;
namespace hcitool
{
partial class Program
{
static bool infoRatherThanName;
static BluetoothAddress _searchAddress;
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Please specify command.");
return 2;
}
var cmd = args[0];
switch (cmd)
{
case "name":
infoRatherThanName = false;
break;
case "info":
infoRatherThanName = true;
break;
//-
case "dev":
return ShowRadios();
//case "auth":
// return CauseAuth(GETADDRESS());
default:
throw new NotImplementedException("Command: '" + cmd + "'");
}
if (args.Length < 2)
{
Console.WriteLine("Please specify device address.");
return 2;
}
var addrS = args[1];
_searchAddress = BluetoothAddress.Parse(addrS);
//
//var dev = new BluetoothDeviceInfo(_searchAddress);
var dev = new BluetoothDevice();
bool isInRange = GetCanConnectTo(dev);
if (isInRange)
{
PrintDevice(dev);
}
else
{
Console.WriteLine("Can't see that device.");
}
//
Console.WriteLine("simple");
return Simple();
//return Fancier();
}
//----
private static int ShowRadios()
{
BluetoothRadio[] list;
try
{
list = BluetoothRadio.AllRadios;
}
catch (Exception)
{
return 1;
}
Debug.Assert(list.Length != 0, "Expect zero radios case to raise an error.");
foreach (var curR in list)
{
Console.WriteLine("* {0} '{1}'", curR.LocalAddress, curR.Name);
Console.WriteLine("{0}", curR.SoftwareManufacturer);
Console.WriteLine("{0}", curR.Manufacturer);
Console.WriteLine("{0}", curR.Mode);
}//for
return 0;
}
private static int CauseAuth(BluetoothAddress addr)
{
BluetoothSecurity.PairRequest(addr, null);
return 0;
}
//----
static int Simple()
{
BluetoothDeviceInfo[] devices;
BluetoothDeviceInfo foundDev = null;
var cli = new BluetoothClient();
// Fast: Remembered/Authenticated
devices = cli.DiscoverDevices(255, true, true, false, false);
SimpleCheckDevice(devices, ref foundDev);
if (foundDev == null)
{
// Slow: Inquiry
cli.DiscoverDevices(255, false, false, true, false);
SimpleCheckDevice(devices, ref foundDev);
}
//
if (foundDev != null)
{
return 0;
}
else
{
return 1;
}
}
private static void SimpleCheckDevice(IEnumerable<BluetoothDeviceInfo> devices,
ref BluetoothDeviceInfo foundDev)
{
foreach (var cur in devices)
{
if (cur.DeviceAddress == _searchAddress)
{
foundDev = cur;
PrintDevice(cur);
}
}//for
}
private static void PrintDevice(BluetoothDeviceInfo cur)
{
Console.WriteLine("* Found device: '{0}' ", cur.DeviceName);
if (infoRatherThanName)
{
try
{
var vs = cur.GetVersions();
Console.WriteLine(vs.Manufacturer);
Console.WriteLine(vs.LmpVersion);
Console.WriteLine(vs.LmpSubversion);
Console.WriteLine(vs.LmpSupportedFeatures);
}
catch (Exception ex)
{
Console.WriteLine("Failed to get remote device versions info: "
+ ex.Message);
}
}
}
//----
private static bool GetCanConnectTo(BluetoothDeviceInfo device)
{
bool inRange;
Guid fakeUuid = new Guid("{F13F471D-47CB-41d6-9609-BAD0690BF891}");
try
{
ServiceRecord[] records = device.GetServiceRecords(fakeUuid);
Debug.Assert(records.Length == 0, "Why are we getting any records?? len: " + records.Length);
inRange = true;
}
catch (SocketException)
{
inRange = false;
}
return inRange;
}
}
}
The BluetoothAddress is in the 32feet.NET nuget package.
You're using the preview version of InTheHand which is missing the BluetoothAddress, the BluetoothRadio, BluetoothDeviceInfo and others.
I think you're referencing the wiki for the 32feet.NET, which is the legacy nuget package.
If you install 32feet.NET v3.5.0.0, you will find all your missing bindings.
Adding 32feet.NET and changing a couple of things:
var dev = new BluetoothDevice();
//this becomes this:
var dev = new BluetoothDeviceInfo(_searchAddress);
it will compile succesfully.
Try to add the following namespaces to your code:
using InTheHand.Net;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;

Element not found Selenium C#

URL: http://bcmprod.brill.com/rsuite-cms/
I am trying to automate downloading of manuscripts from the client site above. I am using selenium phantomjs in C#.
I have the user credentials. But the elements that make up the login form (e.g. username, password) are not existing in the page source, but are existing when you inspect those elements in the browser.
These are the xpaths I'm using to locate them from "Inspect element" (IDs are dynamically assigned that's why I didn't use them):
string xpathUsername = ".//input[#name='user']";
string xpathPassword = ".//input[#name='pass']";
string xpathBtnLogin = ".//button[#type='submit'][#aria-label='Log In']";
How can I successfully login when the source returned by the driver has no login elements thus cannot be found, but yet existing when I inspect them in the browser?
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.IO;
using OpenQA.Selenium;
using OpenQA.Selenium.PhantomJS;
using OpenQA.Selenium.Support.UI;
using WebCrawler.Helper;
namespace WebCrawler.Webcodes
{
class RSuite : IWebcode
{
List<string> errors = new List<string>();
string xpathUsername = ".//input[#name='user']";
string xpathPassword = ".//input[#name='pass']";
string xpathBtnLogin = ".//button[#type='submit'][#aria-label='Log In']";
public RSuite()
{ }
public List<Record> GetRecords()
{
Console.WriteLine(string.Format("Crawling: {0}", Config.Url));
List<Record> recordList = new List<Record>();
try
{
PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
using (IWebDriver driver = new PhantomJSDriver(service))
{
driver.Navigate().GoToUrl(Config.Url);
Console.WriteLine("\nChecking elements availability ...");
// code exception here: I couldn't get all these elements
IWebElement username = Element("User ID", GetElement(driver, xpathUsername));
IWebElement password = Element("Password", GetElement(driver, xpathPassword));
IWebElement btnlogin = Element("Login Button", GetElement(driver, xpathBtnLogin));
// input credentials
Console.WriteLine("\nAttempting to login ...");
if (username != null && password != null && btnlogin != null)
{
username.Clear();
username.SendKeys(Config.Username);
password.Clear();
password.SendKeys(Config.Password);
// is button clicked & loaded a new page? (If true, login is successful)
if (IsPageLoaded(driver, btnlogin))
{
Console.WriteLine("Logged in successfully.");
// do some action
// download files
}
else
{ ErrorHandler("Login failed."); }
}
else
{ ErrorHandler("Login failed."); }
}
// release
service.Dispose();
}
catch (Exception err)
{ ErrorHandler(err.GetBaseException().ToString()); }
// generate report for caught errors, if any
if (errors.Count() > 0)
Config.ErrorReport(this.GetType().Name.Trim().ToUpper(), string.Join("\n\n", errors));
return recordList;
}
private IWebElement GetElement(IWebDriver driver, string xPath)
{
IWebElement element = null;
try
{
// wait for elements to load
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
Func<IWebDriver, IWebElement> waitForElement = new Func<IWebDriver, IWebElement>((IWebDriver d) =>
{
element = d.FindElement(By.XPath(xPath));
if (element != null)
{ return element; }
return null;
});
return wait.Until(waitForElement);
}
catch (Exception err)
{
ErrorHandler(err.GetBaseException().ToString());
return null;
}
}
private IWebElement Element(string label, IWebElement element)
{
if (element != null)
{ Console.WriteLine(string.Format("{0}: Yes", label)); }
else
{ Console.WriteLine(string.Format("{0}: No", label)); }
return element;
}
private bool IsPageLoaded(IWebDriver driver, IWebElement element)
{
try
{
// page redirected? Or is the element still attached to the DOM?
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
element.Click();
return wait.Until(ExpectedConditions.StalenessOf(element));
}
catch (Exception err)
{
ErrorHandler(err.GetBaseException().ToString());
return false;
}
}
private void ErrorHandler(string error)
{
Console.WriteLine(error);
errors.Add(error);
}
}
}
As per your question the url http://bcmprod.brill.com/rsuite-cms/ is based on Ember.js so you have to induce WebDriverWait inconjunction with ExpectedConditions method ElementToBeClickable() while you look out for the elements.
The Locator Strategies to identify the desired fileds are as follows:
User ID:
string username = "//input[#class='ember-view ember-text-field finput text-field component' and #name='user']";
Password:
string password = "//input[#class='ember-view ember-text-field finput text-field component' and #name='pass']";
Log In:
string loginbtn = "//label[#class='ui-button-text']";

How to implement and do OCR in a C# project?

I ve been searching for a while and all that i ve seen some OCR library requests. I would like to know how to implement the purest, easy to install and use OCR library with detailed info for installation into a C# project.
If posible, I just wanna implement it like a usual dll reference...
Example:
using org.pdfbox.pdmodel;
using org.pdfbox.util;
Also a little OCR code example would be nice, such as:
public string OCRFromBitmap(Bitmap Bmp)
{
Bmp.Save(temppath, System.Drawing.Imaging.ImageFormat.Tiff);
string OcrResult = Analyze(temppath);
File.Delete(temppath);
return OcrResult;
}
So please consider that I'm not familiar to OCR projects and give me an answer like talking to a dummy.
Edit:
I guess people misunderstood my request. I wanted to know how to implement those open source OCR libraries to a C# project and how to use them. The link given as dup is not giving answers that I requested at all.
If anyone is looking into this, I've been trying different options and the following approach yields very good results. The following are the steps to get a working example:
Add .NET Wrapper for tesseract to your project. It can be added via NuGet package Install-Package Tesseract(https://github.com/charlesw/tesseract).
Go to the Downloads section of the official Tesseract project (https://code.google.com/p/tesseract-ocr/ EDIT: It's now located here: https://github.com/tesseract-ocr/langdata).
Download the preferred language data, example: tesseract-ocr-3.02.eng.tar.gz English language data for Tesseract 3.02.
Create tessdata directory in your project and place the language data files in it.
Go to Properties of the newly added files and set them to copy on build.
Add a reference to System.Drawing.
From .NET Wrapper repository, in the Samples directory copy the sample phototest.tif file into your project directory and set it to copy on build.
Create the following two files in your project (just to get started):
Program.cs
using System;
using Tesseract;
using System.Diagnostics;
namespace ConsoleApplication
{
class Program
{
public static void Main(string[] args)
{
var testImagePath = "./phototest.tif";
if (args.Length > 0)
{
testImagePath = args[0];
}
try
{
var logger = new FormattedConsoleLogger();
var resultPrinter = new ResultPrinter(logger);
using (var engine = new TesseractEngine(#"./tessdata", "eng", EngineMode.Default))
{
using (var img = Pix.LoadFromFile(testImagePath))
{
using (logger.Begin("Process image"))
{
var i = 1;
using (var page = engine.Process(img))
{
var text = page.GetText();
logger.Log("Text: {0}", text);
logger.Log("Mean confidence: {0}", page.GetMeanConfidence());
using (var iter = page.GetIterator())
{
iter.Begin();
do
{
if (i % 2 == 0)
{
using (logger.Begin("Line {0}", i))
{
do
{
using (logger.Begin("Word Iteration"))
{
if (iter.IsAtBeginningOf(PageIteratorLevel.Block))
{
logger.Log("New block");
}
if (iter.IsAtBeginningOf(PageIteratorLevel.Para))
{
logger.Log("New paragraph");
}
if (iter.IsAtBeginningOf(PageIteratorLevel.TextLine))
{
logger.Log("New line");
}
logger.Log("word: " + iter.GetText(PageIteratorLevel.Word));
}
} while (iter.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word));
}
}
i++;
} while (iter.Next(PageIteratorLevel.Para, PageIteratorLevel.TextLine));
}
}
}
}
}
}
catch (Exception e)
{
Trace.TraceError(e.ToString());
Console.WriteLine("Unexpected Error: " + e.Message);
Console.WriteLine("Details: ");
Console.WriteLine(e.ToString());
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
private class ResultPrinter
{
readonly FormattedConsoleLogger logger;
public ResultPrinter(FormattedConsoleLogger logger)
{
this.logger = logger;
}
public void Print(ResultIterator iter)
{
logger.Log("Is beginning of block: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Block));
logger.Log("Is beginning of para: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Para));
logger.Log("Is beginning of text line: {0}", iter.IsAtBeginningOf(PageIteratorLevel.TextLine));
logger.Log("Is beginning of word: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Word));
logger.Log("Is beginning of symbol: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Symbol));
logger.Log("Block text: \"{0}\"", iter.GetText(PageIteratorLevel.Block));
logger.Log("Para text: \"{0}\"", iter.GetText(PageIteratorLevel.Para));
logger.Log("TextLine text: \"{0}\"", iter.GetText(PageIteratorLevel.TextLine));
logger.Log("Word text: \"{0}\"", iter.GetText(PageIteratorLevel.Word));
logger.Log("Symbol text: \"{0}\"", iter.GetText(PageIteratorLevel.Symbol));
}
}
}
}
FormattedConsoleLogger.cs
using System;
using System.Collections.Generic;
using System.Text;
using Tesseract;
namespace ConsoleApplication
{
public class FormattedConsoleLogger
{
const string Tab = " ";
private class Scope : DisposableBase
{
private int indentLevel;
private string indent;
private FormattedConsoleLogger container;
public Scope(FormattedConsoleLogger container, int indentLevel)
{
this.container = container;
this.indentLevel = indentLevel;
StringBuilder indent = new StringBuilder();
for (int i = 0; i < indentLevel; i++)
{
indent.Append(Tab);
}
this.indent = indent.ToString();
}
public void Log(string format, object[] args)
{
var message = String.Format(format, args);
StringBuilder indentedMessage = new StringBuilder(message.Length + indent.Length * 10);
int i = 0;
bool isNewLine = true;
while (i < message.Length)
{
if (message.Length > i && message[i] == '\r' && message[i + 1] == '\n')
{
indentedMessage.AppendLine();
isNewLine = true;
i += 2;
}
else if (message[i] == '\r' || message[i] == '\n')
{
indentedMessage.AppendLine();
isNewLine = true;
i++;
}
else
{
if (isNewLine)
{
indentedMessage.Append(indent);
isNewLine = false;
}
indentedMessage.Append(message[i]);
i++;
}
}
Console.WriteLine(indentedMessage.ToString());
}
public Scope Begin()
{
return new Scope(container, indentLevel + 1);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
var scope = container.scopes.Pop();
if (scope != this)
{
throw new InvalidOperationException("Format scope removed out of order.");
}
}
}
}
private Stack<Scope> scopes = new Stack<Scope>();
public IDisposable Begin(string title = "", params object[] args)
{
Log(title, args);
Scope scope;
if (scopes.Count == 0)
{
scope = new Scope(this, 1);
}
else
{
scope = ActiveScope.Begin();
}
scopes.Push(scope);
return scope;
}
public void Log(string format, params object[] args)
{
if (scopes.Count > 0)
{
ActiveScope.Log(format, args);
}
else
{
Console.WriteLine(String.Format(format, args));
}
}
private Scope ActiveScope
{
get
{
var top = scopes.Peek();
if (top == null) throw new InvalidOperationException("No current scope");
return top;
}
}
}
}
Here's one: (check out http://hongouru.blogspot.ie/2011/09/c-ocr-optical-character-recognition.html or http://www.codeproject.com/Articles/41709/How-To-Use-Office-2007-OCR-Using-C for more info)
using MODI;
static void Main(string[] args)
{
DocumentClass myDoc = new DocumentClass();
myDoc.Create(#"theDocumentName.tiff"); //we work with the .tiff extension
myDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, true, true);
foreach (Image anImage in myDoc.Images)
{
Console.WriteLine(anImage.Layout.Text); //here we cout to the console.
}
}
I'm using tesseract OCR engine with TessNet2 (a C# wrapper - http://www.pixel-technology.com/freeware/tessnet2/).
Some basic code:
using tessnet2;
...
Bitmap image = new Bitmap(#"u:\user files\bwalker\2849257.tif");
tessnet2.Tesseract ocr = new tessnet2.Tesseract();
ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,$-/#&=()\"':?"); // Accepted characters
ocr.Init(#"C:\Users\bwalker\Documents\Visual Studio 2010\Projects\tessnetWinForms\tessnetWinForms\bin\Release\", "eng", false); // Directory of your tessdata folder
List<tessnet2.Word> result = ocr.DoOCR(image, System.Drawing.Rectangle.Empty);
string Results = "";
foreach (tessnet2.Word word in result)
{
Results += word.Confidence + ", " + word.Text + ", " + word.Left + ", " + word.Top + ", " + word.Bottom + ", " + word.Right + "\n";
}
Some online API's work pretty well: ocr.space and Google Cloud Vision. Both of these are free, as long as you do less than 1000 OCR's per month. You can drag & drop an image to do a quick manual test to see how they perform for your images.
I find OCR.space easier to use (no messing around with nuget libraries), but, for my purpose, Google Cloud Vision provided slightly better results than OCR.space.
Google Cloud Vision example:
GoogleCredential cred = GoogleCredential.FromJson(json);
Channel channel = new Channel(ImageAnnotatorClient.DefaultEndpoint.Host, ImageAnnotatorClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
ImageAnnotatorClient client = ImageAnnotatorClient.Create(channel);
Image image = Image.FromStream(stream);
EntityAnnotation googleOcrText = client.DetectText(image).First();
Console.Write(googleOcrText.Description);
OCR.space example:
string uri = $"https://api.ocr.space/parse/imageurl?apikey=helloworld&url={imageUri}";
string responseString = WebUtilities.DoGetRequest(uri);
OcrSpaceResult result = JsonConvert.DeserializeObject<OcrSpaceResult>(responseString);
if ((!result.IsErroredOnProcessing) && !String.IsNullOrEmpty(result.ParsedResults[0].ParsedText))
return result.ParsedResults[0].ParsedText;
A new API is OcrEngine.RecognizeAsync from WinRT/UWP. It can also be used in WinForms:
...
//for AsBuffer
using System.Runtime.InteropServices.WindowsRuntime;
...
async private void button5_Click(object sender, EventArgs e)
{
OcrEngine ocrEngine = null;
ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages();
if (ocrEngine == null) return;
//convert the image to BGRA8 format which is needed by SoftwareBitmap
//is there a better method for this?
Bitmap img = new Bitmap(#"1.png");
byte[] ba = new byte[img.Width * img.Height * 4];
int o = 0;
for (int y = 0; y < img.Height; y++)
{
for (int x = 0; x < img.Width; x++)
{
var p = img.GetPixel(x, y);
ba[o++] = p.B;
ba[o++] = p.G;
ba[o++] = p.R;
ba[o++] = p.A;
}
}
var buffer = ba.AsBuffer();
var outputBitmap = SoftwareBitmap.CreateCopyFromBuffer(
buffer,
BitmapPixelFormat.Bgra8,
img.Width,
img.Height);
var ocrResult = await ocrEngine.RecognizeAsync(outputBitmap);
}
To use WinRT/UWP API in WinForms, add Nuget package "Microsoft.Windows.SDK.Contracts" (version 10.0.17134.100 for Win10 1803 SDK tested here) as described here.

Categories

Resources