Get variable from web page with javascript in C++ Builder - windows

I have a MiFi modem (Huawei e5776) which comes with its own web page that displays total traffic per month. I want to extract this value and display a meter in the icon tray. I'm sure this is possible in C++ Builder (or Delphi) but even though I'm pretty experienced in using C++ Builder, I am not in anything web related. Can someone give me some pointers how to do this? I assume I need to run the script and then extract the variable somewhere, how do I do this?
Thanks.
PS: I'd add the contents of the page but can't see a way to attach a document. Here's the first few lines..
// JavaScript Document
var g_monitoring_traffic_statistics = null;
var g_wlan_security_settings = null;
var g_wlan_basic_settings = null;
var g_connection_trafficresponse = null;
//Prefix string of ssid2 of Multi-SSID
var g_prefixWifiSsid = "ssid2_";
function getTrafficInfo(bit) {
var final_number = 0;
var final_str = "";
if(g_monitoring_dumeter_kb > bit) {
final_number = formatFloat(parseFloat(bit), 2);
final_str = final_number + " B";
}
else if(g_monitoring_dumeter_kb <= bit && g_monitoring_dumeter_mb > bit) {
final_number = formatFloat(parseFloat(bit) / g_monitoring_dumeter_kb, 2);
final_str = final_number + " KB";
}
else if(g_monitoring_dumeter_mb <= bit && g_monitoring_dumeter_gb > bit) {
final_number = formatFloat((parseFloat(bit) / g_monitoring_dumeter_mb), 2);
final_str = final_number + " MB";
}
else if(g_monitoring_dumeter_gb <= bit && g_monitoring_dumeter_tb > bit) {
final_number = formatFloat((parseFloat(bit) / g_monitoring_dumeter_gb), 2);
final_str = final_number + " GB";
}
else {
final_number = formatFloat((parseFloat(bit) / g_monitoring_dumeter_tb), 2);
final_str = final_number + " TB";
}
return final_str;
}

I suggest you to use a great html wrapper (named BCB HTML) for mshtml writed specially for C++Builder; With this wrapper you can execute java script inside C++ Builder cpp codes:
THTMLDocument document;
document.create();
document.write(
"<html><body><script>"
"function myFunc(n)"
"{"
"return n * n;"
"}"
"</script></body></html>");
document.parentWindow.execScript("alert(myFunc(3))", "javascript");
For your jscript:
String value = document.parentWindow.execScript("getTrafficInfo(1024)", "javascript");
Also it is possible to handle html events inside BCB, access html objects , ...
you can download it from here.
To use this source add html.cpp to your project.
If you use TWebBrowser to load a html page, you need just define document in global scope and write below code to connect/attach document variable to WebBrowser1->Document:
void __fastcall TForm1::WebBrowser1DocumentComplete(TObject *ASender,
const IDispatch *pDisp, const OleVariant &URL)
{
document.documentFromVariant(WebBrowser1->Document);
String value = document.parentWindow.execScript("getTrafficInfo(1024)", "javascript");
}

Related

Xamarin UILabel not updating

I've a basic for loop that's basically download files. It's supposed to update the label as long as it progress.
By searching here at Stack Overflow, I found an orientation to use SetNeedsDisplay(). But it's still refuses to update. Any idea ?
for (int i = 0; i < files.Length; i++)
{
status.Text = "Downloading file " + (i + 1) + " of " + files.Length + "...";
status.SetNeedsDisplay();
string remoteFile = assetServer + files[i];
var webClient2 = new WebClient();
string localFile = files[i];
string localPath3 = Path.Combine(documentsPath, localFile);
webClient2.DownloadFile(remoteFile, localPath3);
}
As previously suggested try to avoid blocking the UI when doing heavy transactions in it. WebClient already has a async method which you can use.
webClient2.DownloadFileasync(new System.Uri(remoteFile), localPath3);
and to prevent you from accessing the UI from a different thread use the built-in method InvokeOnMainThread when accessing UI elements.
InvokeOnMainThread (() => {
status.Text = "Downloading file " + (i + 1) + " of " + files.Length + "...";
status.SetNeedsDisplay ();
});
and finally use the using statement to help you with the resources disposal.
using (var webClient2 = new WebClient ())
{
webClient2.DownloadFileAsync (new System.Uri (remoteFile), localPath3);
}
You could also have the iteration inside the using statement this way you don't have to create a WebClient object for each file instead you will use the same object to download all files available in your files array.

How Can Set Icon for each node by c# Ajax Response in Jstree?

How Can Set Icon for each node by c# Ajax Response in Jstree?
in this line see Ajax jstree :
Webmethod is not fired by jsTree
the ajax jstree successfully run, but how can show Icon for each node ?
in this line :
_GG_JSTree.icons = ""; How Can set icons?
private static List<GG_JSTree> AddChildNodes(int _ParentID, int NumOfChildren, string ParentName)
{
List<GG_JSTree> GG_JSTreeArray = new List<GG_JSTree>();
int n = 10;
for (int i = 0; i < NumOfChildren; i++)
{
int CurrChildId = (_ParentID == 0) ? n : ((_ParentID * 10) + i);
GG_JSTree _GG_JSTree = new GG_JSTree();
_GG_JSTree.data = (_ParentID == 0) ? "root" + "-Child" + i.ToString() : ParentName + CurrChildId.ToString() + i.ToString();
_GG_JSTree.state = "closed"; //For async to work
_GG_JSTree.icons = ""; How Can set?
_GG_JSTree.IdServerUse = (int)CurrChildId;
_GG_JSTree.children = null;
_GG_JSTree.attr = new GG_JSTreeAttribute { id = CurrChildId.ToString(), selected = false };
GG_JSTreeArray.Add(_GG_JSTree);
n = n + 10;
}
return GG_JSTreeArray;
}
Take a look at the format spec:
https://github.com/vakata/jstree#the-required-json-format
The property name is icon, not icons.
( state should be an object, no a string, etc.
As for the icon property it is explained in the above link:
icon - a string which will be used for the node's icon - this can either be a path to a file, or a className (or list of classNames), which you can style in your CSS (font icons also work).
Basically - just take a deeper look at the docs and you should be fine.
try following
_GG_JSTree.icon = "glyphicon glyphicon-heart";
if u use bootstrap to show heart icon
'icon' defined in 'Type' plugin section may override this.

is my if statement doing what i think its doing?

Here I have tis function that is querying data and returning it to me and im putting that data in to html elements to make a post.my if statement at the bottom is where im having a bit of problem i trying to only apply my comment window once to the new clones once they have been pushed over to the new div called story board, i believe im telling my if statement that if the class already exists in that new clone then do nothing else apply it there.. to seee what i am talking about...here is my test domain...http://subdomain.jason-c.com/
sign in is "kio" pass is the same and when you hit publish on the stories, everytime a nw one hits it will apply comment box to a post in the storyboard window that already has a comment text area. what am i doing wrong.
function publishWindowHandler(){
var query = new Parse.Query('Post');
console.log(currentUser);
query.equalTo("User", currentUser);
query.include("User");
query.descending("createdAt")
console.log(user.get('username'));
query.find({
success:function(results){
document.getElementById("publishCenter").textContent = "";
for(var i =0; i < results.length; i++){
var userPost = results[i];
//console.log(userPost.get("User") + " / " + userPost.get("Author") + " / " + userPost.get("Story") + " / " + userPost.get("objectId"));
var authorTitle = document.createElement("p");
var newPost = document.createElement("P");
var title = document.createElement("P");
var userLabel = document.createElement("p");
var postId = userPost.id;
var postBtn = document.createElement("INPUT");
postBtn.className ="publishBtn";
postBtn.id ="publishBtn";
postBtn.setAttribute("Type", "button");
postBtn.setAttribute("value", "Publish");
title.textContent = "Story: " + userPost.get("Title");
authorTitle.textContent = "Author: " + userPost.get("Author");
newPost.textContent = userPost.get("Story");
userLabel.textContent = "Published by: " +userPost.get("User").get ("username");
var postWrapper = document.createElement("DIV");
postWrapper.className = "postWrapper";
postWrapper.id = postId;
document.getElementById("publishCenter").appendChild(postWrapper);
postWrapper.appendChild(title);
postWrapper.appendChild(authorTitle);
postWrapper.appendChild(newPost);
postWrapper.appendChild(userLabel);
postWrapper.appendChild(postBtn);
postBtn.addEventListener("click", publicViewHandler);
function publicViewHandler(){
$(this).parent(".postWrapper").clone().appendTo(".storyBoard");
function testWindow(){
if($(publicBoard).children().hasClass(".commentWindow")){
}
else
{
$(".storyBoard").children().append(commentWindow);
}
}
testWindow();
}
}
}
})
}
According to the documentation, jquery hasClass doesn't need '.' prefixing the passed in class name.
https://api.jquery.com/hasclass/
Try removing that and see if that get's you anywhere.
Also, where is the variable commentWindow defined? Is it global?
var myClone = $(this).parent().clone(true);
myClone.appendTo(".storyBoard");
console.log(publicBoard);
console.log("hello",$(this));
console.log($(publicBoard).find('.postWrapper').find("commentWindow"));
myClone.append($(commentWindow).clone());
this is what i ended up doing to solve my issue took me a while and a little help from a friend.

Download zip file (contains xml and images) through ajax and store binary data in localstorage in IE

I was able to download the zip file (2mb) from server through ajax call and storing binary data in the web storage where as this is not working in IE (7,8,9). Below is my code.
var req = new XMLHttpRequest();
req.open('GET', filename, false);
req.onreadystatechange=function()
{
if (req.readyState == 4)
{
if(req.status!=200){
chk_file = false;
alert('Sorry, Error occured while downloading the question paper. HTTP Error Code: '+req.status);
}
}
}
if (req.overrideMimeType) {
req.overrideMimeType('text/plain; charset=x-user-defined');
} else {
req.setRequestHeader('Accept-Charset', 'x-user-defined');
}
req.send('hello');
var buffer = "";
var dbata;
try {
bdata = BinaryToArray(req.responseBody).toArray();
for (var i = 0, len = bdata.length - 1; i < len; i++) {// dbata is one byte too long. Why ???
buffer += String.fromCharCode(bdata[i] & 0xFF);
}
} catch(e) {
bdata = req.responseText;
for (var i = 0, len = bdata.length; i < len; i++) {
buffer += String.fromCharCode(bdata.charCodeAt(i) & 0xFF);
}
}
Converting Binary data to array in VB script . following is the code.
var IE_HACK = (/msie/i.test(navigator.userAgent) &&
!/opera/i.test(navigator.userAgent));
if (IE_HACK) {
var vbScript = '<scr' + 'ipt type="text/vbscript">\n'+
'<!-' + '-\n' +
'Function BinaryToArray(Binary)\n'+
' Dim i\n'+
' ReDim byteArray(LenB(Binary))\n'+
' For i = 1 To LenB(Binary)\n'+
' byteArray(i-1) = AscB(MidB(Binary, i, 1))\n'+
' Next\n'+
' BinaryToArray = byteArray\n'+
'End Function\n'+
'--' + '>\n' +
'</scr' + 'ipt>';
//$(vbScript).insertAfter("script:last");
document.write(vbScript);
Storing this buffer value in html5 web storage.
I am not getting complete content in IE where it is working in FF, Chrome.
Any help!
Maybe this can help you, but guess you solved this by now, but it might help people that sees this question
is there a cross-browser alternative to the xhr.overrideMimeType() function?
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
https://github.com/eligrey/FileSaver.js
http://stuk.github.io/jszip/

Performance difference when reading/writing many files with EPPlus versus Spreadsheet Gear

I've made a simple performance test between EPPlus and Spreadsheet Gear to see if there is any significant difference that would justify buying Spreadsheet Gear.
I am no expert at either application so it's possible the tests aren't written the most efficient way.
The test does the following:
1. Opens an existing Excel-file with 1000 rows and 3 columns. Saves the three values into an entity that is saved into a List<>.
2. Open a new Excel-object
3. Create a header row (bold) with the title of each column.
4. Write back the 1000 entities.
5. Save the new Excelfile.
If I run this test once EPPlus comes out the winner (approx times are EPPlus = 280ms, SG = 500ms). If I run the test 10 times in a row instead (a for-loop opening, copying, saving 10 seperate times) Spreadsheet Gear is faster instead (approx times per file: EPPlus = 165ms, SG = 95ms). For 20 tests the approx times are EPPlus = 160ms / file and SG = 60ms / file.
It seems like (to a certain extent at least) Spreadsheet Gears gets faster and faster the more files I create.
Could anyone explain why EPPlus is the slower one when running consecutive tests? And can I make changes to the code to change this?
EPPlus test function:
var timer = new Stopwatch();
timer.Start();
var data = new List<Item>();
using (var excelIn = new ExcelPackage(new FileInfo(folder + fileIn)))
{
var sheet = excelIn.Workbook.Worksheets[1];
var row = 2;
while (sheet.Cells[row, 1].Value != null)
{
data.Add(new Item()
{
Id = int.Parse(sheet.Cells[row, 1].Text),
Title = sheet.Cells[row, 2].Text,
Value = int.Parse(sheet.Cells[row, 3].Text)
});
row++;
}
}
using (var excelOut = new ExcelPackage())
{
var sheet = excelOut.Workbook.Worksheets.Add("Out");
sheet.Cells.LoadFromCollection(data);
sheet.InsertRow(1, 1);
sheet.Cells[1, 1, 1, 3].Style.Font.Bold = true;
sheet.Cells[1, 1].Value = "Id";
sheet.Cells[1, 2].Value = "Title";
sheet.Cells[1, 3].Value = "Value";
excelOut.SaveAs(new FileInfo(folder + "EPPlus_" + Guid.NewGuid() + ".xlsx"));
}
timer.Stop();
return timer.ElapsedMilliseconds;
Spreadsheet Gear:
var timer = new Stopwatch();
timer.Start();
var data = new List<Item>();
var excelIn = Factory.GetWorkbook(folder + fileIn);
var sheetIn = excelIn.Worksheets[0];
var rowIn = 1;
while (sheetIn.Cells[rowIn, 0].Value != null)
{
data.Add(new Item()
{
Id = int.Parse(sheetIn.Cells[rowIn, 0].Text),
Title = sheetIn.Cells[rowIn, 1].Text,
Value = int.Parse(sheetIn.Cells[rowIn, 2].Text)
});
rowIn++;
}
excelIn.Close();
var excelOut = Factory.GetWorkbook();
var sheetOut = excelOut.Worksheets.Add();
sheetOut.Name = "Out";
var rowOut = 0;
sheetOut.Cells[rowOut, 0, rowOut, 2].Font.Bold = true;
sheetOut.Cells[rowOut, 0].Value = "Id";
sheetOut.Cells[rowOut, 1].Value = "Title";
sheetOut.Cells[rowOut++, 2].Value = "Value";
foreach (var item in data)
{
sheetOut.Cells[rowOut, 0].Value = item.Id;
sheetOut.Cells[rowOut, 1].Value = item.Title;
sheetOut.Cells[rowOut++, 2].Value = item.Value;
}
excelOut.SaveAs(folder + "SpreadsheetGear_" + Guid.NewGuid() + ".xlsx", FileFormat.OpenXMLWorkbook);
excelOut.Close();
timer.Stop();
return timer.ElapsedMilliseconds;
Main function
var runs = 1;
var testerG = new TestSpreadsheetGear();
var testerE = new TestEpPlus();
var msE = 0.0;
var msG = 0.0;
var i = 0;
for (i = 0; i < runs; ++i)
{
msG += new TestSpreadsheetGear().Run(folder, originalFile);
}
for(i = 0; i < runs; ++i)
{
msE += new TestEpPlus().Run(folder, originalFile);
}
Console.WriteLine("Spreadsheet time: " + msG + ". Per file: " + msG / runs);
Console.WriteLine("EP Plus time: " + msE + ". Per file: " + msE / runs);
Console.ReadKey();
I believe that the reason for the results you are seeing is the fact that on the first run the .NET CLR must JIT the code. Since SpreadsheetGear is a complete spreadsheet engine under the hood (as opposed to a read / write library) there is more code to JIT - thus the first run is taking longer for SpreadsheetGear than EPPlus (I am speculating here but have a great deal of experience in benchmarking .NET code over the last 10 years).
I do not have EPPlus installed but I did write a test which tries to do the same thing you are doing. with SpreadsheetGear 2012 Since I don't have your starting workbook I first build the workbook. Then, I used more optimal SpreadsheetGear APIs. The first time I run I get 141 milliseconds for SpreadsheetGear 2012. After the first run I get 9 or 10 milliseconds for each run on an overclocked Core i7-980x running Win7 x86 and a release build run without debugger.
I have pasted my code below (just paste it into a .NET 4.0 C# console application).
One more thought I have is that this is a very small test case. To really see the performance of SpreadsheetGear 2012 try this with 100,000 rows or even 1 million rows.
Disclaimer: I own SpreadsheetGear LLC
using System;
using System.Collections.Generic;
using System.Diagnostics;
using SpreadsheetGear;
namespace SGvsEPPlus
{
class Program
{
internal struct Item
{
internal Item(int id, string title, int value)
{
Id = id;
Title = title;
Value = value;
}
internal int Id;
internal string Title;
internal int Value;
}
static void Test(int rows)
{
string filename = #"C:\tmp\MyWorkbook.xlsx";
Console.Write("Test({0})...", rows);
var timer = new Stopwatch();
// Create workbook since we don't have poster's original workbook.
timer.Restart();
var workbook = Factory.GetWorkbook();
var values = (SpreadsheetGear.Advanced.Cells.IValues)workbook.Worksheets[0];
for (int row = 1; row <= rows; row++)
{
values.SetNumber(row, 0, row);
values.SetText(row, 1, "Title " + row);
values.SetNumber(row, 2, row * 10);
}
Console.Write("Create workbook={0:0}...", timer.Elapsed.TotalMilliseconds);
// Save workbook
timer.Restart();
workbook.SaveAs(filename, FileFormat.OpenXMLWorkbook);
Console.Write("Save workbook={0:0}...", timer.Elapsed.TotalMilliseconds);
// Track total time of original test.
var totalTimer = Stopwatch.StartNew();
// Open workbook
timer.Restart();
var excelIn = Factory.GetWorkbook(filename);
Console.Write("Open excelIn={0:0}...", timer.Elapsed.TotalMilliseconds);
// Copy workbook to list
timer.Restart();
var sheetIn = excelIn.Worksheets[0];
var valuesIn = (SpreadsheetGear.Advanced.Cells.IValues)sheetIn;
var rowIn = 1;
var data = new List<Item>(rows);
while (valuesIn[rowIn, 0] != null)
{
data.Add(new Item(
(int)valuesIn[rowIn, 0].Number,
valuesIn[rowIn, 1].Text,
(int)valuesIn[rowIn, 2].Number));
rowIn++;
}
excelIn.Close(); // Not necessary but left for consistency.
Console.Write("excelIn->data={0:0}...", timer.Elapsed.TotalMilliseconds);
timer.Restart();
var excelOut = Factory.GetWorkbook();
var sheetOut = excelOut.Worksheets[0];
var valuesOut = (SpreadsheetGear.Advanced.Cells.IValues)sheetOut;
sheetOut.Name = "Out";
var rowOut = 0;
sheetOut.Cells[rowOut, 0, rowOut, 2].Font.Bold = true;
sheetOut.Cells[rowOut, 0].Value = "Id";
sheetOut.Cells[rowOut, 1].Value = "Title";
sheetOut.Cells[rowOut++, 2].Value = "Value";
foreach (var item in data)
{
valuesOut.SetNumber(rowOut, 0, item.Id);
valuesOut.SetText(rowOut, 1, item.Title);
valuesOut.SetNumber(rowOut, 2, item.Value);
rowOut++;
}
Console.Write("data->excelOut={0:0}...", timer.Elapsed.TotalMilliseconds);
timer.Restart();
excelOut.SaveAs(#"C:\tmp\SpreadsheetGear_" + Guid.NewGuid() + ".xlsx", FileFormat.OpenXMLWorkbook);
excelOut.Close(); // Again - not necessary.
Console.WriteLine("Save excelOut={0:0}...", timer.Elapsed.TotalMilliseconds);
Console.WriteLine(" Total={0:0}", totalTimer.Elapsed.TotalMilliseconds);
}
static void Main(string[] args)
{
// Do it three times with 1000 rows. Note that the first
// time takes longer because code must be JITted.
Test(1000);
Test(1000);
Test(1000);
}
}
}

Resources