How convert QNetworkCookie to QString? - c++

I am trying to convert QNetworkCookie to QString but I can't find a way how to do this.
For example, I've tried to do something like this
QString cookie = QVariant(cookies_[i]).toString();
and this
QString cookie = (QString*)cookies_[i];
Nothing worked.

As #Aditya told, QNetworkCookie::value() works as QByteArray.
So, problem solvetion for me is:
auto cookie = reply->manager()->cookieJar()->cookiesForUrl(webReportsUrl);//).value(0);
cookies = cookie[0].name() + "=" + cookie[0].value() + "; domain=" + cookie[0].domain() + "; path=" + cookie[0].path();
qDebug() << "Cookie: " << cookies;
But presented returns only cookies' value without a name, domain, and others.

Related

Protobuf: Serialize/DeSerialize C++ to Js

I'm using protobuf to send/receive binary data from Cpp to Js and vice-versa and I'm using QWebChannel to communicate with the HTML client.
Question: How to deserialize binary data in cpp which is serialized and sent from Js?
Following I tried:
//Serialization: Cpp to JS - WORKING
tutorial::PhoneNumber* ph = new tutorial::PhoneNumber();
ph->set_number("555-515-135");
ph->set_type(500);
QByteArray bytes = QByteArray::fromStdString(ph->SerializeAsString());
QString args = "\"" + bytes.toBase64(QByteArray::Base64Encoding) + "\"";
QString JsFunctionCall = QString("DeserializePhoneNumber(%1);").arg(args);
m_pWebView->page()->runJavaScript(JsFunctionCall);
//Deserialization In JS - Js Code - WORKING
var obj = phone_msg.PhoneNumber.deserializeBinary(data);
console.log("PhoneNumber: " + obj.getNumber());
console.log("Type: " + obj.getType());
//Serialization in Js - WORKING
var phNum = new phone_msg.PhoneNumber;
phNum.setNumber("555-515-135");
phNum.setId(500);
var base64Str = btoa(phNum.serializeBinary());
console.log("base64Str: " + base64Str);
//Call Cpp function from Js
MainChannel.SendMsgToCpp(base64Str);
Deserialization in Cpp - NOT WORKING
bool WebRelay::ReceiveMsgFromJs(QVariant data)
{
QString str = data.toString();
QByteArray bytedata = str.toLatin1();
QByteArray base64data = QByteArray::fromBase64(bytedata);
std::string stdstr = base64data.toStdString();
tutorial::PhoneNumber cppPhNum;
//THIS IS NOT WORKING. Text and id are invalid
cppPhNum.ParseFromArray(base64data.constData(), base64data.size());
qDebug() << "Text:" << itemData.number();
qDebug() << "id:" << cppPhNum.id();
}
Found the problem.
I was getting comma-separated bytes from Js like:
10,7,74,115,73,116,101,109,49,16,45
I split the strings by ',' and created a QByteArray
QStringList strList = str.split(',');
QByteArray bytedata;
foreach(const QString & str, strList)
{
bytedata+= (str.toUInt());
}
std::string stdstr = bytedata.toStdString();
itemData.ParseFromString(stdstr);
It works.
Also in JS, I removed convertion of the binary string to base64:
var base64Str = phNum.serializeBinary();

Why do profile pic URLs returned from graph.facebook result in a 404

The backend of my application makes a request to:
https://graph.facebook.com/v2.8/me?access_token=<firebase-access-token>&fields=id,name,first_name,birthday,email,picture.type(large){url}&format=json&method=get&pretty=0&suppress_http_code=1
I get a successful (200) response with the JSON data I expect and picture field as such:
"picture": {
"data": {
"url": "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=<asid>&height=200&width=200&ext=<ext>&hash=<hash>"
}
}
(where in place of <asid> and <ext>, there are numbers and <hash> is some alphanumeric string).
However, when I make a GET request to the platform-lookaside URL above, I get a 404 error.
It's been happening every time since my very first graph.facebook request for the same user. The very first one returned a platform-lookaside URL which pointed to a proper image (not sure if this is simply coincidence).
Is there something I'm doing wrong or is this likely a bug with the Facebook API?
FB currently seems to have issues with some CDNs and therefore your issue might be only temporary. You should also see missing/broken images on some places on fb dot com. Worst time to debug your issue :)
Try this code it worked for me
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Insert your code here
try {
String name = object.getString("name");
String email = object.getString("email");
String last_name = object.getString("last_name");
String first_name = object.getString("first_name");
String middle_name = object.getString("middle_name");
String link = object.getString("link");
String picture = object.getJSONObject("picture").getJSONObject("data").getString("url");
Log.e("Email = ", " " + email);
Log.e("facebookLink = ", " " + link);
Log.e("name = ", " " + name);
Log.e("last_name = ", " " + last_name);
Log.e("first_name = ", " " + first_name);
Log.e("middle_name = ", " " + middle_name);
Log.e("pictureLink = ", " " + picture);
} catch (JSONException e) {
e.printStackTrace();
Log.e("Sttaaaaaaaaaaaaaaaaa", e.getMessage());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,link,last_name,first_name,middle_name,picture");
request.setParameters(parameters);
request.executeAsync();

QProcess::execute Environment Variables Expanded Strings

How do I get this to work:
QProcess::execute("%windir%\system32\SnippingTool.exe")
I assume expanded environment variables strings are being ignored by QProcess.
I guess I'll need to parse the string and see if % exists and then get the environment variable to complete the full string path. Sounds like hassle and something that should be handled by QProcess. Am I missing something?
Thanks in advance! :)
If you want to use %windir% directly, you can do something like this:
QProcess::execute("cmd.exe /c start /WAIT "" %windir%\\system32\\SnippingTool.exe");
Else, you can use for example qgetenv("windir") or qEnvironmentVariable("windir") to get the windows folder path.
Hope it helps you.
Thanks to #TomKim answer for handling expanded strings in his answer, I got that problem solved. But unfortunately white spaces caused other issues for me that made me come up with this solution that hopefully will help others. Not the prettiest solution though, but it does exactly I needed for multiple platforms:
void QuickCut::executeProcess(const std::string & szProc, const std::string & szArgs)
{
// QProc won't expand environment variable strings.
// Invoking using the user console will allow for expanded string to work as expected.
#ifdef Q_OS_WIN
QString szCommand = "cmd /c start \"\" \"" + QString::fromStdString(szProc) + "\"";
QString szExt = ".cmd";
#elif Q_OS_UNIX
QString szCommand = "sh -c '" + QString::fromStdString(szProc) + "'";
QString szExt = ".sh";
#endif
QStringList qArgsTmp = QString::fromStdString(szArgs).trimmed().split(",");
for (auto && arg : qArgsTmp)
{
QString argTrimmed = arg.trimmed();
if (argTrimmed.isEmpty()) continue;
szCommand += " " + argTrimmed;
}
qDebug() << "[QuickCut::executeProcess] - Execute Command: " << szCommand;
QString szFilePath = applicationDirPath() + "/tempCmd" + szExt;
QFile file(szFilePath);
file.open(QIODevice::ReadWrite);
QTextStream ts(&file);
ts << szCommand;
file.close();
QProcess::execute(szFilePath);
file.remove();
}

UploadFile doesn´t work

Hi we are using "dropnet" API and works fine until today, just is not working the UploadFile method, play media, move or delete works fine, but the upload is not working can someone help to figuredout why?
basically the process upload the file and returns no error, but the file (.mp3 files) is not uploaded into my dropbox account as had been doing until last Friday. We tried to move or delete a file, also play the mp3 from my web page and it works perfect! How can we try to catch the error?
we use this code:
var fecha = DateTime.Now.ToString("dd-MM-yyyy");
DropNet.Models.MetaData uploaded = new DropNet.Models.MetaData();
uploaded = _client.UploadFile("/CRM_Proximitas/" + portal + "/" + Request.QueryString["idReclamo"].ToString() + "/" + fecha, hidTipo.Value.ToString() + hidID.Value.ToString() + "_" + fecha + "_" + usuario + "." + uplArchivo.FileName.ToLower().Split('.')[1], uplArchivo.FileBytes);
if (uploaded != null)
{
if (hidTipo.Value.ToString() == "R")
{
objCommand.CommandText = "INSERT INTO ReclamoAudio (idReclamo,path,Autor,Fecha) VALUES (" + Request.QueryString["idReclamo"].ToString() + ",'" + uploaded.Path.ToString() + "'," + Session["UserID"].ToString() + ",getdate())";
}
else if (hidTipo.Value.ToString() == "T")
{
objCommand.CommandText = "INSERT INTO ReclamoAudio (idReclamo,idTransaccion,path,Autor,Fecha) VALUES (" + Request.QueryString["idReclamo"].ToString() + "," + hidID.Value.ToString() + ",'" + uploaded.Path.ToString() + "'," + Session["UserID"].ToString() + ",getdate())";
}
objCommand.CommandType = CommandType.Text;
objCon.Open();
drContacto = objCommand.ExecuteReader();
objCon.Close();
string codigo = "window.opener.location.reload();self.close();";
Page.ClientScript.RegisterStartupScript(this.GetType(), "FinalizarCarga", codigo, true);
}
We have a website with IIS 7 + Framework 2.0, also the Dropbox App now is in Development Status, this can we cause an issue?
Please I need your help.
Thanks a lot!

insert multiple char * into a const char* with pre filled text

i have setup a working mysql connector for my c++ project. Now i'm making a login for registered users.
i want to get the username and password into the SQLquery string.
i am trying to get this working:
currently its displaying noting and the game crashes.
#include "boost/lexical_cast.hpp" //boost
#include <cgl\cgl.h> // game library (core media library)
#include <sstream> // sstream
char* username=DEFSER;
char* password=PASS12345;
const char *SQLquery;
std::string SQLquery("SELECT * FROM Users WHERE UserName='" + boost::lexical_cast<std::string>(username) + "' AND PassWord='" + boost::lexical_cast<std::string>(password) + "'");
what i want to get out of SQLquery:
SELECT * FROM Users WHERE UserName='DEFSER' AND PassWord='PASS12345'
and i execute it in this way:
res = stmt->executeQuery(SQLquery);
this is not a fully working code i only want to know how i can get the username and password into the SQLquery.
error when i try to run the query:
Run-Time Check Failure #3 - The variable 'SQLquery' is being used without being initialized.
What you are doing is not concatenating strings, you are adding std::string objects to a literal string pointer.
The std::string class handles concatenation of C-style strings just fine without any lexical_cast, so just do e.g.
std::string SQLquery = "SELECT * FROM Users WHERE UserName='" +
username + "' AND PassWord='" + password + "'";
After testing the above solution doesn't actually work for me. But the following does:
std::string SQLQuery = (std::ostringstream() << "SELECT * FROM Users WHERE UserName='"
<< username << "' AND PassWord='" << password << "'").str();