WebView2 - How to read data from BLOB URL? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How do i read data as text from a BLOB Url in WebView2 ? I've tried WebView2 callback from Javascript which i couldn't make it work. I appreciate whether it is a Javascript solution or not but i prefer C++.

WebView2 doesn't provide a mechanism to interact with Blobs. You can turn the Blob into text in script and then post the text back to the native side with the window.chrome.webview.postMessage method and the WebMessageReceived event.
If this doesn't work for you, you can make a feature request on the WebView2 Feedback GitHub Project.
async function example() {
function textToBlob(text) {
return new Blob([text], {type : 'text/plain'});
}
async function blobToText(blob) {
return (new Response(blob)).text();
}
const blob = textToBlob("example");
const text = await blobToText(blob);
alert(text);
}
example();

Unfortunately, Webview2 doesn't support async function results in ExecuteScript. I managed to get data by performing synchronous request with ajax.
wstring jquery(L"var jqry = document.createElement('script');"
L"jqry.src = 'https://code.jquery.com/jquery-3.3.1.min.js';"
L"document.getElementsByTagName('head')[0].appendChild(jqry);");
webview->ExecuteScript(jquery.c_str(), Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[](HRESULT errorCode, PCWSTR result) -> HRESULT {
return S_OK;
}).Get());
Sleep(500);
wstring script(L"jQuery.noConflict();"
L"function testAjax() {"
L"var result='';"
L"jQuery.ajax({"
L"url:document.getElementById('test').href,"
L"async: false,"
L"success:function(data) {"
L"result = data; "
L"}"
L"});"
L"return result;"
L"}"
L"(() => {"
L"return testAjax()"
L"})();");
webview->ExecuteScript(script.c_str(), Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[](HRESULT errorCode, LPCWSTR result) -> HRESULT {
wprintf(L"%ls\n", result);
return S_OK;
}).Get());
But synchronous calls block the web code while executing. This is not recommended, but it is ok for my case. If you are looking for another way without blocking the web code, posting the text back to the native side maybe a better idea as #David Risney suggested.

Related

How to read from exchange server asynchronously using IMoniker and IStream Interface

Currently the MFCMAPI uses a single thread to serialize all of the MAPI calls. Mapi provider initializes and stores the folder name, etc as a member variable and then read the mailboxs.
This may result in the slow processing of the exchange messages and attachments. For example, it costly when query for attachment files and wait for it to return. So it would be better if can send a request to read the messages and at same time can do another process (initialize another message).
So, is it possible to query and read messages while initialize for the next next message by IMonikers and IBindStatusCallback::OnDataAvailable.
Or is there any other way to do that?
I have tried to use IMoniker and IStream to read data from exchange server asynchronously, I am trying to use BindToStorage to make an asynchronous bind and read date from OnDataAvailable. The binding code is shown as below.
hRes = CoInitialize(NULL);
CComPtr<IBindCtx> pbc;
CComPtr<IMoniker> pmk;
CComPtr <IStream> lpStream1;
ULONG chEaten = 0;
hRes = CreateBindCtx(0, &pbc);
OLECHAR string[] =
L"Session:3!clsid:10000013-0000-0000-0000-000000000001";
if (FAILED(hRes = MkParseDisplayName(pbc, string, &chEaten, &pmk)))
{
return 0;
}
hRes = pmk->BindToStorage(pbc, NULL, IID_IStream,reinterpret_cast<void **>(&lpStream1));
However when call BindToStorage, it returns Class not Registered.
Does anyone know which part is wrong?
And Is that possible to read data from exchange server asynchronously by this method?
Thanks
Admittedly it's been a while since I closely looked at the MFCMAPI source code, but I don't think it does anything like this.
If you want to retrieve the data asynchronously, you need to start a new thread, initialize MAPI, and do whatever lengthy operation you need to do on that thread.
What kind of data are you trying to read?
MFCMAPI already uses a worker thread to handle QueryRows calls while loading a folder. Beyond that, I wasn't really targeting speed over code clarity/simplicity so I didn't bother with threading.
I'm ignoring your questions about IMoniker and BindToStorage because, for the most part, MAPI is not COM, so I don't see what they have to do with spinning up threads to run MAPI code. If you want to read a stream from a worker thread, just make sure you initialize MAPI on that thread.
Are you trying to redo part of MFCMAPI itself or are you writing code for your own application, using MFCMAPI as a model? If within MFCMAPI, what specific scenario are you targeting?

HTTP Requests in C++ without external libraries? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So this question has been asked before, but the general answer pointed to was using an external library such as cURLpp. So I was curious as to if HTTP requests could be done using only the standard libraries as of C++14. How difficult would this be?
Say for example, I wanted to get an XML document and store it in a string to be parsed. What steps would have to be taken to achieve this?
If anyone is curious, I'm doing this as a learning experience to better understand how HTTP requests work.
It sounds like to me that you want to implement the HTTP protocol from scratch on top of the POSIX sockets API. I have done this myself, it was quite fun.
Read about the sockets API here: http://en.wikipedia.org/wiki/Berkeley_sockets
If you want to work on Windows, see here.
This link, posted in the comments, provides a pretty good starting-point example for using the API, although it weirdly includes both the client and the server as serial logic within the same program -- which may allow it to bypass some of the calls (such as waiting for incoming connections) required to implement a client or server as a standalone program.
Assuming you are implementing an HTTP server in C++, you might choose to implement the client as a web page (running on your favorite browser), as the following hack demonstrates...
<html>
<head>
</head>
<body>
This web page sends the entered text back to the server upon a button press.
The server's response is then displayed in the box below.
This is only a hack for learning purposes, and not a demonstration of best-practices.
<br>
<textarea id="INP">
Hello world!
</textarea>
<br>
<button onclick="return make_request('INP','GET','test1')">GET Request</button>
<button onclick="return make_request('INP','POST','test2')">POST Request</button>
<div id="result" style='border-style:solid;'>?</div>
<script>
function make_request( textID, request_type, webfn )
{
var url = "" + "?webfn="+webfn // assumes this page was served by the same server
if ( request_type != 'POST' ) url += "&value="+document.getElementById(textID).value;
var req = new XMLHttpRequest();
req.open( request_type, url, /*async*/false );
req.send( request_type=='POST' ? document.getElementById(textID).value : null );
if ( req.readyState == 4/*complete*/ && req.status == 200/*OK*/ )
{
result = req.responseXML.documentElement.getElementsByTagName('value')[0].firstChild.data;
document.getElementById('result').innerHTML = req.responseText;
}
else alert("HTTP request failed");
return false;
}
</script>
</body>
</html>

How to communicate with Firefox using C++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am on project right now which is a very simple parental control software, but, I want to know what is the url requested in firefox to take respond based on it ... if you may help because I don't know how to let my software know what is the url requested by firefox .. How to do that?
I have to use C++ in most of my software.. but if there are better language to do this task please advice me
In Firefox you need to use XPCOM component called nsIHTTPChannel. This script below will block abort all rqeuests to google. The channel is opened but aborted before opening connection to server.
var {classes: Cc, results: Cr, utils: Cu} = Components;
Cu.import('resource://gre/modules/Services.jsm');
var httpRequestObserver =
{
observe: function(subject, topic, data)
{
var httpChannel, requestURL;
if (topic == 'http-on-modify-request') {
httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
requestURL = httpChannel.URI.spec;
if (/google\.com/.test(requestURL)) {
httpChanel.cancel(Cr.NS_BINDING_ABORTED);
}
return;
}
}
};
Services.obs.addObserver(httpRequestObserver, 'http-on-modify-request', false);
//Services.obs.removeObserver(httpRequestObserver, "http-on-modify-request", false); //run this to remove observer
Can I suggest an alternative approach? Instead of writing an extension for Firefox and an extension for Chrome and an extension for IE... listen on the OS network interfaces for traffic and block undesirable URLS.
This is traditionally the job of a firewall. Using an existing solution will provide the most efficient means of solving your problem. I'm not familiar with the capabilities of the built in Windows firewall or 3rd party alternatives but something like this would be trivial with iptables (Linux).

how to send json using wt?

I'm trying a C++ framework for web development - Wt (WebToolkit).
I want to extract data from text fields, create json-object and send it to the server by POST.
void LoginForm::sendLogInRequest()
{
Json::Object data;
data["username"] = usernameTextEdit->text();
data["password"] = passwordTextEdit->text();
}
then I want to send data. how can I do this?
There's a Wt::Http::Client that can post that data for you. The manual has a usage example.

Time out when calling a Web service

I have a problem when I am using the webservice from a mobile App Im developing in Flex Builder.
I have the following code for a Web service
<s:CallResponder id="readAllPedidosErpResult" result="readAllPedidosErpResult_resultHandler(event)" fault="sincFailResult_faultHandler(event)"/>
protected function readAllPedidosErp():void
{
readAllPedidosErpResult.token = xEasyERPMobileAppWS.readAllPedidosErp
(readFechaSincronizacionPedidoErp(),sC.readComercialUsuario());
}
protected function readAllPedidosErpResult_resultHandler(event:ResultEvent):void
{
var result:ArrayCollection;
var c:PedidoWSMobile;
if(event.token.result is ArrayCollection)
{
result = event.token.result as ArrayCollection;
if(result!=null)
{
//DO SOMETHING
}
}
continueToNext(15);
}
The problem I get is that xEasyERPMobileAppWS.readAllPedidosErp(readFechaSincronizacionPedidoErp(),sC.readComercialUsuario()); takes almost 2 minutes to get the answer but after 30 seconds (more or less) does not wait more and I got a fault (sincFailResult_faultHandler(event)).
How can I give more time to the CallResponder to wait the answer from the Web Service I am calling?
Thanks in advance.
I´ve just found the solution in another thread.
FYI: Adobe Flex 4.6 WebService request timeout
Thanks anyways!