Install OpenSSL for MSVC2017 on 64-bit Windows 10 - javascript

.pro
LIBS += -LC:\Qt\Tools\OpenSSL\Win_x86\lib -llibssl
LIBS += -LC:\Qt\Tools\OpenSSL\Win_x86\lib -llibcrypto
INCLUDEPATH += C:\Qt\Tools\OpenSSL\Win_x86\include
main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.0
Window {
visible: true
width: 640
height: 480
Component.onCompleted: getPage(logResults)
function logResults(results) {
console.log("RESULTS: " + results)
}
function getPage(callback) {
var xhttp = new XMLHttpRequest();
var url = "https://www.google.com/"
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4 && xhttp.status === 200) {
console.log("calling callback")
callback(xhttp.responseText)
}
};
xhttp.open("GET", url);
xhttp.send();
}
}
expected output
qml: calling callback
qml: RESULTS: <html>
actual output
qt.network.ssl: QSslSocket: cannot resolve SSL_CTX_set_ciphersuites
qt.network.ssl: QSslSocket: cannot resolve SSL_set_psk_use_session_callback
qt.network.ssl: QSslSocket: cannot call unresolved function SSL_set_psk_use_session_callback
qml: calling callback
Windows 10 64-bit OS, running MSVC2017 QML project
I ran C:\Qt\MaintenanceTool.exe to install Developer and Designer Tools > OpenSSL 1.1.1d Toolkit
I've tried following a previous tutorial and another one for MSVC2017 but no luck in resolving the errors or getting xhttp.responseText. Found out the code works in ubuntu 19.4 so it just has to be that I'm running it on my windows machine that something funky is happening with the OpenSSL. I couldn't find any resolution by googling the outputted error messages. I've read that accidentally installing openSSL to "the windows directory" can cause errors, but I've not been able to actually locate "the windows directory" in question to check if I did.
edit
From C:\Qt\Tools\OpenSSL\Win_x64\bin I copied libcrypto-1_1-x64.dll and libssl-1_1-x64.dll to my project's \debug and \release folders. This removed the qt.network.ssl errors, however I am still not getting the expected output of qml: RESULTS: <html>

You ran C:\Qt\MaintenanceTool.exe to install Developer and Designer
Tools > OpenSSL 1.1.1d Toolkit
That is also my recommendation. The alternative is to compile OpenSSL yourself, or download a binary package from a third party provider. I have one of those packages installed at "C:\Program Files\OpenSSL-Win64\bin", and programs using Qt+=network are able to locate and load the libraries when their path is included in the PATH environment variable. The problem is that you will need to take care of the updates yourself, but the Qt packages are automatically updated with the MaintenanceTool along with Qt and Qt Creator. So pick your choice.
Anyway, even if you have another set of OpenSSL DLLs in your path, if you copy the libraries to the output directory of your executable, these libraries will be loaded instead. Two questions need to be answered here: 1) how do you copy the DLLs automatically each time they are needed?, and 2) how do you verify which DLLs are loaded when you run your program?
1) You may add the following to your project .pro:
win32 {
CONFIG += file_copies
CONFIG(debug, debug|release) {
openssllibs.path = $$OUT_PWD/debug
} else {
openssllibs.path = $$OUT_PWD/release
}
contains(QMAKE_TARGET.arch, x86_64) {
openssllibs.files = C:/Qt/Tools/OpenSSL/Win_x64/bin/libcrypto-1_1-x64.dll \
C:/Qt/Tools/OpenSSL/Win_x64/bin/libssl-1_1-x64.dll
} else {
openssllibs.files = C:/Qt/Tools/OpenSSL/Win_x86/bin/libcrypto-1_1.dll \
C:/Qt/Tools/OpenSSL/Win_x86/bin/libssl-1_1.dll
}
COPIES += openssllibs
}
That is it. Now your program will always have the latest libraries from Qt/Tools copied to the output directory of your project, without worrying if you compile in debug or release mode, or 32/64 bits, or another Qt Kit.
2) Run your program while inspecting the loaded DLLs with Process Explorer, by Mark Russinovich. To do so, in Process Explorer->View->Show lower pane, and select your running program in the upper pane. The lower pane lists all your loaded DLLs and origins. There are other similar utilities out there, like the open source Process Hacker.
Even understanding all of the above, and following exactly the recipe, your program still does not print the desired output. Please change the function logResults() in your qml like this:
function logResults(results) {
console.log("RESULTS Length=", results.length);
console.log("results.substr=", results.substr(0, 20));
}
You will get the following output:
qml: calling callback
qml: RESULTS Length= 47932
qml: results.substr= <!doctype html><html
Explanation: looks like console.log() has a limitation of about 32K in Windows (it doesn't on Linux). The document retrieved from the remote host is much larger, and this breaks the logging function. This is probably a bug in Qt (it should not fail silently like that).
Another advice for anybody coming here in the future: It is not strictly needed, but you may want to verify in your main() function that SSL is available, with something like this code:
#include <QDebug>
#include <QSslSocket>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
if (!QSslSocket::supportsSsl()) {
qDebug() << "Sorry, OpenSSL is not supported";
return -1;
}
qDebug() << "build-time OpenSSL version:" << QSslSocket::sslLibraryBuildVersionString();
qDebug() << "run-time OpenSSL version:" << QSslSocket::sslLibraryVersionString();
[...]
}

Related

CefSharp offscreen with .net core 2.0 Runtime Error , System.IO.FileNotFoundException: 'Could not load file or assembly 'CefSharp.Core,

I am getting this error
System.IO.FileNotFoundException: 'Could not load file or assembly 'CefSharp.Core, Version=63.0.3.0, Culture=neutral, PublicKeyToken=40c4b6fc221f4138'. The system cannot find the file specified.'
I am trying to run the cefsharp.minimalexample.offscreen program in .net core 2.0. in visual studio 2017
what I have done so far
1 . Created .net core console application
2 . Installed NuGet packages Cefsharp.Offscreen (which installs the dependencies cefsharp.common and redist)
3 . Installed Microsoft.windows.compatibility nuget package to get the system.drawing in .net core (It was not working with System.Drawing.Common as the Cefsharp ScreenshotAsync function using system.drawing)
These steps will clear all the errors and the project will build successfully.
I am getting the above mentioned error.
I have checked all the required files mentioned in the Cefsharp documentation in the current running folder (debug). All files are available ,Still error is not going away.
It works fine in old Dot net versions 4.6.
I could not find any helping documents for implementing cefsharp.offscreen with .net core any where.
This is the code from the example provided in the Cefsharp.offscreen.
Please let me know if you can shed some light on this issue. Thanks in advance.
public class Program
{
private static ChromiumWebBrowser browser;
public static void Main(string[] args)
{
const string testUrl = "https://www.google.com/";
Console.WriteLine("This example application will load {0}, take a screenshot, and save it to your desktop.", testUrl);
Console.WriteLine("You may see Chromium debugging output, please wait...");
Console.WriteLine();
var settings = new CefSettings()
{
//By default CefSharp will use an in-memory cache, you need to specify a Cache Folder to persist data
CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache")
};
//Perform dependency check to make sure all relevant resources are in our output directory.
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
// Create the offscreen Chromium browser.
browser = new ChromiumWebBrowser(testUrl);
// An event that is fired when the first page is finished loading.
// This returns to us from another thread.
browser.LoadingStateChanged += BrowserLoadingStateChanged;
// We have to wait for something, otherwise the process will exit too soon.
Console.ReadKey();
// Clean up Chromium objects. You need to call this in your application otherwise
// you will get a crash when closing.
Cef.Shutdown();
}
private static void BrowserLoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
// Check to see if loading is complete - this event is called twice, one when loading starts
// second time when it's finished
// (rather than an iframe within the main frame).
if (!e.IsLoading)
{
// Remove the load event handler, because we only want one snapshot of the initial page.
browser.LoadingStateChanged -= BrowserLoadingStateChanged;
var scriptTask = browser.EvaluateScriptAsync("document.getElementById('lst-ib').value = 'CefSharp Was Here!'");
scriptTask.ContinueWith(t =>
{
//Give the browser a little time to render
Thread.Sleep(500);
// Wait for the screenshot to be taken.
var task = browser.ScreenshotAsync();
task.ContinueWith(x =>
{
// Make a file to save it to (e.g. C:\Users\jan\Desktop\CefSharp screenshot.png)
var screenshotPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CefSharp screenshot.png");
Console.WriteLine();
Console.WriteLine("Screenshot ready. Saving to {0}", screenshotPath);
// Save the Bitmap to the path.
// The image type is auto-detected via the ".png" extension.
task.Result.Save(screenshotPath);
// We no longer need the Bitmap.
// Dispose it to avoid keeping the memory alive. Especially important in 32-bit applications.
task.Result.Dispose();
Console.WriteLine("Screenshot saved. Launching your default image viewer...");
// Tell Windows to launch the saved image.
Process.Start(screenshotPath);
Console.WriteLine("Image viewer launched. Press any key to exit.");
}, TaskScheduler.Default);
});
}
}
}

Getting "picked up Java tool options" error while running a test script in HPALM integrated with CA LISA

I am trying to integrate HP-ALM with CA-LISA (a service virtualization tool). On trying to run the below test script
function Test_Main(Debug, CurrentTestSet, CurrentTest, CurrentRun)
{
try
{
TDOutput.Clear();
lisa = new ActiveXObject("MercuryLisaBridge.MercuryTestRunner");
lisa.Init(TDConnection, TDOutput);
lisa.Reload(ThisTest);
if (Debug) lisa.Debug(ThisTest);
if (!Debug) lisa.Run(CurrentTest, CurrentRun);
}
catch(e)
{
TDOutput.Print("Run-time error [" + (e.number & 0xFFFF) + "] : " + e.description);
}
}
I am getting this error
Run-time error [5376] : Picked up JAVA_TOOL_OPTIONS: -agentlib:jvmhook
Picked up _JAVA_OPTIONS: -Xbootclasspath/a:"C:\Program Files (x86)\HP\Unified Functional Testing\bin\java_shared\classes\jasmine.jar"
Picked up JAVA_TOOL_OPTIONS: -agentlib:jvmhook
_JAVA_OPTIONS and JAVA_TOOL_OPTIONS are environment variables which allows you to provide default values for Java options which will be picked up by every JVM (see details on http://progexc.blogspot.com.cy/2013/12/what-i-discovered-while-trying-to-pass.html and Difference between _JAVA_OPTIONS JAVA_TOOL_OPTIONS and JAVA_OPTS for details).
This variables are set by UFT installer (and probably by some other HP ALM related stuff).
I'm not sure why it causes your script to fail (maybe because they are written in standard error stream - I don't remember), but if you want to elimimate them you need to clear those two environment variables on the machine where script is running. I would clear them for a particular process, but leave them untouched globally, because it may affect UFT stuff.

How does NodeJS OS Module work

Nodejs has a built in OS module that we can use by having this line in our code
var os = require('os');
There are a number of functions to use such as getting free memory, total memory, cpu usage, load average, etc.
My question here is HOW does nodejs calculate this information?
For example, the free/total RAM memory, how is that being done under curtains. Is it calling another process to read stats from the system? is it running a separate command like iostat or dstat? How is it actually retrieving that data for us?
The os.totalmem function is a native function from process.binding('os') called getTotalMem. Their implementations can be found in the Node source code:
The following code can be found in src/node_os.cc:
static void GetTotalMemory(const FunctionCallbackInfo<Value>& args) {
double amount = uv_get_total_memory();
if (amount < 0)
return;
args.GetReturnValue().Set(amount);
}
// ...
env->SetMethod(target, "getTotalMem", GetTotalMemory);
The uv_get_total_memory function has several implementations based on the host OS.
Here is the Linux implementation deps/uv/src/unix/linux-core.c:
uint64_t uv_get_total_memory(void) {
struct sysinfo info;
if (sysinfo(&info) == 0)
return (uint64_t) info.totalram * info.mem_unit;
return 0;
}
The Linux build uses sysinfo to get this information. It does not need to spawn another another process.

IPython notebook ~ Using javascript to run python code?

I am trying to execute python code through javascript directly:
I fire up IPython Notebook on Chrome
Using chrome developer tools I open up the javascript console.
In the javascript consolde, I type: IPython.notebook.kernel.execute("2+2")
But I get a strange output: "6CEA73CC644648DDA978FDD6A913E519"
Is there any way to take advantage of all the IPython javascript functions available, to run python code from the javascript console as depicted in the image? I'm sure there's a way but I've been beating at it for way too long and thought I would post here.
(I need this to build an app on top of IPython)
Thanks in advance!
You can call Python code execution from JavaScript with Jupyter.notebook.kernel.execute() function.
Depend on this gist from Craig Dennis you can insert this code in Jupyter cell and run it
%%javascript
window.executePython = function(python) {
return new Promise((resolve, reject) => {
var callbacks = {
iopub: {
output: (data) => resolve(data.content.text.trim())
}
};
Jupyter.notebook.kernel.execute(`${python}`, callbacks);
});
}
function Log_out(r)
{ console.log(r); };
var code =
'for i in range(1,6):'+
' print( "#" + str(i))';
window.executePython( code )
.then(result => Log_out(result)); // Log out
Result would be output to browser javascript console.
Are you aware of this blogpost? http://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/
I think the exact way he uses doesn't work anymore, but maybe it can get you a step forward
After spending two days on it, here is the solution that worked for me.
To run Python code I am simpy using 'Jupyter.notebook.kernel.execute'. To get the answer from it I found usefull information at this link: https://jupyter-notebook.readthedocs.io/en/stable/comms.html
from ipykernel.comm import Comm
js_input = [] #case willing to track
def func_edit(cobj,text):
my_comm = Comm(target_name=cobj) #this is the callback
my_comm.send('' if text == '' else 'Return: ' + text)
global js_input
js_input.append(f'origin={cobj} text={text}')
from IPython.display import display, HTML
html = """
<script>
var comm_name = "this_control";
function fcalc(x)
{
// here I am passing to the Python function the value to edit and the address for getting the return value
IPython.notebook.kernel.execute("func_edit('" + comm_name + "','" + x.value + "')")
}
Jupyter.notebook.kernel.comm_manager.register_target(comm_name, function(comm, msg)
{
// comm is the frontend comm instance, msg is the comm_open message, which can carry data
// Register handlers for later messages:
comm.on_msg(function(msg) {
document.getElementById("out").value = msg.content.data;
});
//comm.on_close(function(msg) {...});
//comm.send({'foo': 40}); what is it??
});
</script>
<label for="in">Input:</label>
<input type="text" id="in" name="in" oninput="fcalc(this)">
<label for="out">Out:</label>
<input type="text" id="out">
"""
display(HTML(html))
In an effort to isolate a minimum viable implementation, I was able to get responses back from the IPython kernel in just a couple of steps using essentially the same approach as ChrCury78.
Since I want to use the data returned from Python within Javascript, in these examples I just stored the message contents in a member on console. (Unlike what ChrCury78 did, where he pushed the result to the output of the notebook cell.) In my real extension, I'll probably just attach it to a name on Jupyter, or maybe an object of my own creation.
>> Jupyter.notebook.kernel.comm_manager.register_target("mycomm", (comm, msg) => {comm.on_msg( m => {console.retval = m.content.data})})
<- undefined
>> Jupyter.notebook.kernel.execute("from ipykernel.comm import Comm; Comm(target_name='mycomm').send('FOO')")
<- "{hex UID}"
>> console.retval
<- "FOO"
Multi-line Python code worked just fine, too; and, since I'd already imported Comm, I didn't need to import it again:
>> Jupyter.notebook.kernel.execute("l = []\nfor x in range(5):\n l.append(x)\nComm(target_name='mycomm').send(l)")
<- "{hex UID}"
>> console.retval
<- Array(5) [ 0, 1, 2, 3, 4 ]
If you want to keep the kernel namespace unpolluted afterward, you could add a del Comm to the end of the Python command.
I'll definitely be writing wrapper functions of some kind for both of these operations.
This is with Python 3.9.11 and the following packages installed:
ipykernel 6.9.2
ipython 8.1.1
ipython-genutils 0.2.0
ipywidgets 7.7.0
jupyter 1.0.0
jupyter-client 7.1.2
jupyter-console 6.4.3
jupyter-contrib-core 0.3.3
jupyter-contrib-nbextensions 0.5.1
jupyter-core 4.9.2
jupyter-highlight-selected-word 0.2.0
jupyter-latex-envs 1.4.6
jupyter-nbextensions-configurator 0.4.1
jupyterlab-pygments 0.1.2
jupyterlab-widgets 1.1.0

Debugging Chrome native messaging

I am a beginner in developing Chrome extensions. I am trying to achieve a native messaging between my extension and a C++ code. Here is the C++ code
int main(int argc, char* argv[]) {
// Define our message
char message[] = "{\"text\": \"This is a response message\"}";
// Collect the length of the message
unsigned int len = strlen(message);
// We need to send the 4 bytes of length information
printf("%c%c%c%c", (char) (len & 0xff),
(char) ((len>>8) & 0xFF),
(char) ((len>>16) & 0xFF),
(char) ((len>>24) & 0xFF));
// Now we can output our message
printf("%s", message);
return 0;
}
The problem is that the extension does receive any thing and I don't know how to debug the program. I've tried opening Chrome from the terminal so that errors are displayed, but nothing is displayed there. here is the code from the background.js
var port = chrome.runtime.connectNative('com.my_company.my_application');
port.onMessage.addListener(function(msg) {
console.log("Received" + msg);
});
port.onDisconnect.addListener(function() {
console.log("Disconnected");
});
Any way I could debug the program?
You can run Chrome with logging enabled and then review the errors using Sawbuck - a handy GUI designed just for that. If the problem is with Chrome, it might shed some light.
see here - http://www.chromium.org/for-testers/enable-logging
There are multiple ways to debug but no end-end IDE like debug exists.
to debug your background and content scripts--- background and page content section in chrome tools
to debug the host --- open chrome from terminal with logging enabled
Also native messaging API offers you some methods which will return appropriate error messages like, runtime.lastError
can refer this

Categories

Resources