Save text from javascript variable to .txt file - javascript

I am trying this code, but can't get it to work, it says "The name "text" does not exist in the current context"
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("for(var i = 0; i < elems1.length; i++){ var textt = elems1[i].innerText}");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine(textt);
}
How can I make variable "textt" accessible?
Here is a full code:
private void button3_Click(object sender, EventArgs e)
{
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("var elems1 = document.getElementsByClassName('question-text')");
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("for(var i = 0; i < elems1.length; i++){var textt = elems1[i].innerText}");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine(textt);
}
}

You might be looking for ContinueWith() which can be chained after ExecuteJavaScriptAsync().
In this example you need to use your JavaScript code as a function which returns anything (ex. textt). So I've created something like this:
var myScript = #"(function () {
var textt = "";
var elems1 = document.getElementsByClassName('question-text');
for(var i = 0; i < elems1.length; i++){
textt += elems1[i].innerText
}
return textt;
})();";
than I asynchronously evaluate it and catch the result which I am returning from that function:
var result = await CurBrowser
.GetMainFrame()
.EvaluateScriptAsync(myScript)
.ContinueWith(t => {
var result = t.Result; // your textt
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true)) {
outputFile.WriteLine(result);
}
});
this is just a suggestion of how it might work.

Related

NodeJS using a class from another file

I have a java script file that is referencing another javascript file that contains a class using
const Champion = require("./championgg_webscraper_cheerio.js");
I then try to instantiate an object of the class Champion by
var temp = new Champion("hello");
console.log(temp);
And when I do it prints this to the console indicating and undefined variable:
Champion {}
Also when i try to print out the properties of the class I get undefined, I think it might not have access to the most_frequent_completed_build variable.
console.log(temp.most_frequent_completed_build);
Here is a look at the championgg_webscraper_cheerio.js file
function Champion(champName) {
//CHEERIO webscraping
var cheerio = require('cheerio');
//REQUEST http library
var request = require('request');
//url of the champion
var url = "http://champion.gg/champion/Camille/Top?";
var most_frequent_completed_build;
var highest_win_percentage_completed_build;
request(url,
function(error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
var final_build_items = $(".build-wrapper a");
var mfcb = [];
var hwpcb = [];
for (i = 0; i < 6; i++) {
var temp = final_build_items.get(i);
temp = temp.attribs.href;
//slices <'http://leagueoflegends.wikia.com/wiki/> off the href
temp = temp.slice(38);
mfcb.push(temp);
}
for (i = 6; i < 12; i++) {
var temp = final_build_items.get(i);
temp = temp.attribs.href;
//slices <'http://leagueoflegends.wikia.com/wiki/> off the href
temp = temp.slice(38);
hwpcb.push(temp);
}
most_frequent_completed_build = mfcb;
highest_win_percentage_completed_build = hwpcb;
} else {
console.log("Response Error: " + response.statusCode);
}
}
);
};
module.exports = Champion;
I think you want a Function constructor named Champion (a prototype or blue-print like classes in other programming languages like Java).
As an alternative I would suggest you to learn ES6 way of writing classes which is similar to that of Java.
You can achieve that by adding all the variables or methods to the this variable inside the Function Constructor so that you can access them using an object created using the 'new' keyword i.e make them Class members or methods.
In your case,
function Champion(champName) {
//Some code
this.most_frequent_completed_build = NULL;
//Rest of code
}
module.exports = Champion;
Just make sure whenever you try to access Class variables always use this.variable_name like this.most_frequent_completed_build.
So when you create a new object of this Class in main app you will be able to access all Class members and methods.
const Champion = require("./championgg_webscraper_cheerio.js");
var temp = new Champion("hello");
console.log(temp.most_frequent_completed_build);
You are exporting a function
All you have to do is call that function like
var temp = Champion();
You can read more about new keyword here and here
function Champion(champName) {
//CHEERIO webscraping
var cheerio = require('cheerio');
//REQUEST http library
var request = require('request');
//url of the champion
var url = "http://champion.gg/champion/Camille/Top?";
var most_frequent_completed_build;
var highest_win_percentage_completed_build;
request(url,
function(error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
var final_build_items = $(".build-wrapper a");
var mfcb = [];
var hwpcb = [];
for (i = 0; i < 6; i++) {
var temp = final_build_items.get(i);
temp = temp.attribs.href;
//slices <'http://leagueoflegends.wikia.com/wiki/> off the href
temp = temp.slice(38);
mfcb.push(temp);
}
for (i = 6; i < 12; i++) {
var temp = final_build_items.get(i);
temp = temp.attribs.href;
//slices <'http://leagueoflegends.wikia.com/wiki/> off the href
temp = temp.slice(38);
hwpcb.push(temp);
}
most_frequent_completed_build = mfcb;
highest_win_percentage_completed_build = hwpcb;
} else {
console.log("Response Error: " + response.statusCode);
}
}
);
return {most_frequent_completed_build:most_frequent_completed_build};
};
module.exports = Champion;
var temp = new Champion("hello");
console.log(temp.most_frequent_completed_build);

Outputting PHP string into a JS file causes syntax error

I'm trying to output a string into a JS file using PHP. Here's the PHP code
$embedded_form_js = "document.addEventListener('DOMContentLoaded', function(){
var parts = window.location.search.substr(1).split('&');
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
var temp = parts[i].split('=');
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
var ref = $_GET['ref'];
if (ref === 'undefined')
{
ref = 0;
}
}, false);";
I'm trying to write a JS file like so
$fp = fopen("FOLDER/FILE.js", 'w');
fwrite($fp, $embedded_form_js);
fclose($fp);
The problem is that when I try to write the JS file, this error happens.
syntax error, unexpected '(', expecting ']'
This is in reference to the line:
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
How can I remedy this?
use Nowdocs as it is single-quoted and won't try to interpret the $_GET
$embedded_form_js = <<<'EOS'
document.addEventListener('DOMContentLoaded', function(){
var parts = window.location.search.substr(1).split('&');
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
var temp = parts[i].split('=');
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
var ref = $_GET['ref'];
if (ref === 'undefined')
{
ref = 0;
}
}, false);
EOS;
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc

Need some help converting Js to C#

I need to convert this to c#, but I am not sure how to do it.
getParamsAsStr = function () {
var keys = Object.keys(_self.params ? _self.params : {});
keys.sort();
var response = "";
for (var i = 0 ; i < keys.length ; i++) {
response += _self.params[keys[i]];
}
return response;
}
(Basically, I would love to know what should I use instead of Object.keys)
This function iterates over some object's enumerable properties (Object.keys) and writes out the property values to a string - though without the keys and without any delimiters.
I don't know what _self.params refers to in this context as it isn't a JavaScript intrinsic nor have you provided its definition.
A direct translation to C# is not possible as C#/.NET do not use prototypes with enumerable properties, the closest analogue is to represent _self.params as a Dictionary<Object,String>:
public static String GetParamsAsStr(Dictionary<Object,String> p) {
if( p == null || p.Count == 0 ) return String.Empty;
StringBuilder sb = new StringBuilder();
foreach(Object key in p.Keys) sb.Append( p[key] );
return sb.ToString();
}
I am writing this as an answer to be able to place the whole thing...
This is the original JS code which sets the first parameter to make, later on, some API calls:
var Signer = function () {
this.apkId = getApkId();
this.apkSecret = getApkSecret();
this.servicio = "";
this.sessionToken = "";
this.timestamp = "";
this.requestId = "";
this.params = "";
var _self = this;
this.getParamsAsStr = function () {
var keys = Object.keys(_self.params ? _self.params : {});
keys.sort();
var response = "";
for (var i = 0 ; i < keys.length ; i++) {
response += _self.params[keys[i]];
}
return response;
}
this.getSignature = function () {
var baseString =
_self.apkSecret +
_self.servicio +
_self.sessionToken +
_self.timestamp +
_self.requestId +
_self.getParamsAsStr();
console.log("Signature pre hash:\n" + baseString);
baseString = baseString.toLowerCase();
return sha1(baseString);
}
}
And, so far, what I did in C# is the following:
public class Signer
{
public string appId = getApkId();
public string appSecret = getAppSecret();
public string servicio = "";
public string sessionToken = "";
public string timestamp = "";
public string requestId = "";
public string params = "";
//Here I have to write the getParamsAsStr()
private static string getApkId(){
string id = "xxxxxxxxxxxxxxxx";
return id;
}
private static string getAppSecret(){
string id = "xxxxxxxxxxxxxxxx";
return id;
}
}

Getting C# Method With jQuery in asp.net

I am using the code below to display an uploaded picture in asp.net . The Image name is change to a unique name and args.get_fileName retrieves the original name of the file instead of the new unique name.
How can I retrieve the new unique name:
protected void FileUploadComplete(object sender, EventArgs e)
{
var date = DateTime.Now.ToString("yyyy-MM-dd-hh_mm_ss");
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
AsyncFileUpload1.SaveAs("~/listingImages/" + date + filename);
}
Script:
function uploadStarted() {
$get("imgDisplay").style.display = "none";
}
function uploadComplete(sender, args) {
var imgDisplay = $get("imgDisplay");
imgDisplay.src = "images/loader.gif";
imgDisplay.style.cssText = "";
var img = new Image();
img.onload = function () {
imgDisplay.style.cssText = "height:100px;width:100px";
imgDisplay.src = img.src;
};
img.src = "/listingImages/" + args.get_fileName();
$('#bodyContent_Label1').html("/listingImages/" + args.get_fileName());
}
You should use password generating concept
private static string CreateRandomPassword(int passwordLength)
{
string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!#$?_-";
char[] chars = new char[passwordLength];
Random rd = new Random();
for (int i = 0; i < passwordLength; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
}

Trying to sort repeater rows with this jQuery

I am trying to sort repeater rows with this jquery . But I am not able to save sort items. Please help me . how can save sorting in database as well as in .aspx page?Thank you in advance
<script language="javascript" type="text/javascript">
$("#defaultList").sortable();
$(document).ready(function () {
$("#defaultList").sortable(
{
update: function (ev, ui) {
var result = $('#defaultList').sortable('toArray');
updateSequenceNumber(result);
}
}
);
});
function updateSequenceNumber(items) {
var originalIdAndSequenceNumber = '';
var index = 0;
for (i = 0; i <= items.length - 1; i++) {
if (items[i].length == 0)
continue;
var item = $('#' + items[i])[0];
originalIdAndSequenceNumber += item.attributes["originalId"].nodeValue + ":" + index.toString();
originalIdAndSequenceNumber += "|";
index = index + 1;
}
persistPositionUsingAjax(originalIdAndSequenceNumber);
}
function persistPositionUsingAjax(originalIdAndSequenceNumber) {
$.ajax(
{
type: "POST",
dataType: "text",
url: "AjaxService.asmx/UpdateSequenceNumber",
data: "s=" + originalIdAndSequenceNumber,
success: function (response) {
}
}
);
}
my ajax method:
[WebMethod]
public string UpdateSequenceNumber(string s)
{
s = s.TrimEnd('|');
string updateQuery = #"update dnn_Table_1 set SortId = {0}
where ImageId = {1}";
StringBuilder sb = new StringBuilder();
string[] originalIdAndSeqNumberArray = s.Split('|');
foreach (var originalIdAndSeqNumberCombined in originalIdAndSeqNumberArray)
{
var tempArray = originalIdAndSeqNumberCombined.Split(':');
int originalId = Convert.ToInt32(tempArray[0]);
int sequenceNumber = Convert.ToInt32(tempArray[1]);
sb.Append(String.Format(updateQuery, sequenceNumber, originalId));
sb.Append(System.Environment.NewLine);
}
UpdateInDatabase(sb.ToString());
return "Hello World";
}
private void UpdateInDatabase(string updateQuery)
{
SqlDataProvider sqd = new SqlDataProvider();
string ConnectionString = sqd.ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(updateQuery, conn);
command.CommandText = updateQuery;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
What status code does the ajax call return?
To me it looks like a 500. You are building an update statement that after a few iterations will look something like this
update dnn_Table_1 set SortId = 3 where ImageId = 2update dnn_Table_1 set SortId = 2 where ImageId = 4update dnn_Table_1 set SortId = 7 where ImageId = 6
That just won't work. Try eihter constructing the SQL update differently or move UpdateInDatabase into the foreach loop.
There might be other issues which I didn't spot, but this might be a starting point.
Hope that helps

Categories

Resources