Get InnertText from input with pupperteer-sharp using C# and XPath - xpath

How to get the innerText from a <input> using XPath?
I have this to work but with CSS, but it do not work for me with XPath
IElementHandle ha = await page.QuerySelectorAsync(xpath);
IJSHandle ith = await ha.GetPropertyAsync("value");
string val = ith.RemoteObject.Value.ToString();

The following works for me:
using PuppeteerSharp;
using var browserFetcher = new BrowserFetcher();
await browserFetcher.DownloadAsync();
await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
using (var page = await browser.NewPageAsync())
{
await page.GoToAsync("http://www.google.de/");
var input = (await page.XPathAsync("/html/body/div[1]/div[3]/form/div[1]/div[1]/div[4]/center/input[1]"))[0];
var ith = await input.GetPropertyAsync("value");
var val = ith.RemoteObject.Value.ToString();
Console.Write(val);
}

Related

Getting Ansible Tower API authentication token from C#

I tried using this C# code below, but getting status code 401 (reason:unautherized):
var baseUri = "https://ansibletower1.test1.com";
var data = #"{'username':'test123', 'password':'a1b2c3Z0!-99', 'description':'Ansible Api token', 'scope':'write'}";
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(baseUri);
var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = httpClient.PostAsync("api/v2/tokens", content).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
var result = response.Content.ReadAsStringAsync().Result;
if (result != null)
{
return result;
}
}
}
Try-2: Using Basic Authorization header.. getting same error (401- unautherized).
I tried from python script, it works. Used Basic Authorization header in it.
var baseUri = "https://ansibletower1.test1.com";
var jsonObject = new {description = "Tower API token", scope = "write" };
var username="test123";
var password="a1b2c3Z0!-99";
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(baseUri);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes($"{username}:{password}")));
var content = new StringContent(JsonConvert.SerializeObject(jsonObject), Encoding.UTF8, "application/json");
var response = httpClient.PostAsync("api/v2/tokens", content).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
var result = response.Content.ReadAsStringAsync().Result;
if (result != null)
{
return result;
}
}
}
I figured out. The url "api/v2/tokens" is missing "/" at the end.
It should be:
var response = httpClient.PostAsync("api/v2/tokens/", content).Result;

Convert image to base64 in flutter

How can I convert it to base64? I able to store it, but how to get base64 from there?
I using this plugin https://pub.dev/packages/signature_pad/example
final image = await sign.getData();
var data = await image.toByteData(format: ui.ImageByteFormat.png);
var savedDir = await getApplicationDocumentsDirectory();
String appDocPath = savedDir.path;
await Directory('$appDocPath/Signature/').create(recursive: true);
var file = File(file).writeAsBytesSync(data.buffer.asInt8List());
I get the file and do like this
List<int> imageBytes = await File(file).readAsBytes();
String base64Image = base64Encode(imageBytes);
print(base64Image);
Full code
final image = await sign.getData();
var data = await image.toByteData(format: ui.ImageByteFormat.png);
var savedDir = await getApplicationDocumentsDirectory();
String appDocPath = savedDir.path;
await Directory('$appDocPath/Signature/').create(recursive: true);
var file = File(file).writeAsBytesSync(data.buffer.asInt8List());
List<int> imageBytes = await File(file).readAsBytes();
String base64Image = base64Encode(imageBytes);
print(base64Image);
Are there any cleaner way ?

JavaScript - How to pass a variable from one async function to another?

I have spent a good few hours on trying to figure this out but drawing a blank.
I need to pass an array from one async function to another. Problem is, I am very new to this whole async/await world.
My code is below. I need to pass elems to the step2 function
var selenium = require('selenium-webdriver');
var Builder = selenium.Builder;
var By = selenium.By;
var Key = selenium.Key;
var util = selenium.util;
var firefox = require('selenium-webdriver/firefox');
var http = require('http');
var querystring = require('querystring');
async function startBot() {
var driver = await new Builder().forBrowser('firefox').build();
await driver.get('randomSite');
if(true){//Putting this here as it may have to do with scope. I am not sure
async function step1(){
for(var p=0; p <5 ; p++){//elems is undefined
var elem1 = await driver.findElement(By.xpath("/html/body/div/div[1]")).getText();
var elem2 = await driver.findElement(By.xpath("/html/body/div/div[2]")).getText();
var elems = [elem1, elem2]; //How do I pass this array to tge step2 funtion?
}
}
if(true){//Putting this here as it may have to do with scope. I am not sure
var char1 = 1;
var char2 = 2;
//button1
async function step2(){
for (var i = 0; i < 2; i++) {
if(elems[i] == char1){//elems is undefined
await driver.findElement(By.xpath("/html/body/div/div[" + i + "]")).click().then(function(res, err){
if(err){ reject(err); };
});
break;
}
}
}
await step1();
await step2();
}
}
};
startBot();
You can pass the elems array as a parameter to the step2 function. However, you have to do some modifications:
async function step1(){
for(var p=0; p <5 ; p++){
var elem1 = await driver.findElement(By.xpath("/html/body/div/div[1]")).getText();
var elem2 = await driver.findElement(By.xpath("/html/body/div/div[2]")).getText();
var elems = [elem1, elem2];
}
return step2(elems);
}
async function step2(elems){
for (var i = 0; i < 2; i++) {
if(elems[i] == char1){
await driver.findElement(By.xpath("/html/body/div/div[" + i + "]")).click().then(function(res, err){
if(err){ reject(err); };
});
break;
}
}
}
And only use await with the step1 function:
await step1();
That's because we returned another promise step2(elems) from the step1 function. Therefore, the await keyword will have to wait for both step1 and step2. Remember that when you call an asynchronous function you always get a promise.
Define elems outside the function.

Azure OCR RecognizePrintedTextInStreamAsync Invalid Image

I'm trying to use the Azure OCR API in Xamarin Forms. Here is the important bits of code. I'm using the ComputerVisionClient .net client
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
SaveToAlbum = false
});
Img = new Image
{
Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
return stream;
}),
};
using (var photoStream = file.GetStream())
{
var text = await _client.RecognizePrintedTextInStreamAsync(true, photoStream);
}
The Img is bound to an image on the view and it shows up when I take a picture so there is definetly an image. However RecognizePrintedTextInStreamAsync returns back "System.IO.FileNotFoundException: 'Invalid Image'" and I'm not sure why. Any ideas?
Edit. Added _client code
public static ComputerVisionClient Authenticate(string endpoint, string key)
{
ComputerVisionClient client =
new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
{ Endpoint = endpoint };
return client;
}
Called from my constructor and set as a global var
_client = Authenticate(endpoint, subscriptionKey);
Thanks

Flutter - Async method in Navigator callback refresh screen

I have a Navigator.push like this:
Navigator.pushNamed(context, "NovoCNPJ").then((value) {
setState(() {
setupList();
});
});
And i need to update my list variable with this setState, my setupList method:
setupList() async {
var banco = await db.initDB();
list = await banco.rawQuery('SELECT * FROM Empresa');
return list;
}
This method is async and so I think it is not running on this code. When i come back from the last screen, the setupList should be activated and reloaded my list with the new item, but the method isn't called.
If async is the problem, Can you try this ?
Navigator.pushNamed(context, "NovoCNPJ").then((value) async {
var banco = await db.initDB();
var tempList = await banco.rawQuery('SELECT * FROM Empresa');
setState(() {
list = tempList
});
});
EDIT:
Navigator.pushNamed(context, "NovoCNPJ").then((value) async {
var banco = await db.initDB();
var tempList = await banco.rawQuery('SELECT * FROM Empresa');
setState(() {
list = new List();
listArray = new List();
list = new List.from(tempList);
});
});

Resources