How to upload files in MongoDB through mongocxx C++ driver? - c++

I want to use the mongo-cxx-driver to upload files but can't find a way. Tried to use the gridfs feature of mongodb but couldn't integrate. Using current stable version mongodb-cxx-driver (3.1.1).
gridFs throws error when try to store file like this:
gfs.storeFile("filepath", "filename");
Error: store_file: /usr/include/boost/smart_ptr/scoped_ptr.hpp:99: T* boost::scoped_ptr::operator->() const [with T = mongo::AtomicWord]: Assertion `px != 0' failed.
Aborted (core dumped)
Also if mongo client is initialized it provides segmentation fault error.
#include "mongo/client/dbclient.h"
#include <iostream>
#include <cstdlib>
using namespace std;
using namespace mongo;
int main(int argc, const char** argv) {
cout<<"good so far"<<endl;
client::GlobalInstance instance; //everytime producing segmentation fault
if (!instance.initialized()) {
std::cout << "failed to initialize the client driver: " << instance.status() << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Successfully initialized the client driver: " << instance.status() << std::endl;
}
return EXIT_SUCCESS;
}

That looks like the legacy client, not the stable 3.1.1 version.
GridFS is not yet available for the stable client (initial priority was on essential CRUD features), but GridFS is under active development and will be available in the 3.2.0 release expected in the next couple months. If you want to keep an eye on progress, the relevant JIRA ticket is CXX-1130.

Related

how to use mysql-connector-c++ 8.0: Cannot connect to remote Alibaba cloud database hosted

Can anyone tell me the answer, I have been unable to eat for a few days, thank you for being my benefactor
I'm using the mysql-connector-c++ 8.0 to mysql 8.0.x
I want to connect to a remote cloud database. After trying countless times, I have encountered great difficulties. Is there something wrong with my code? I am a newbie to msyql
The strange thing is that mysql - h xxx - root - p can be executed on the linux command
line, but it fails in c++ alone, and the error is always one:
CDK Error: Connection attempt to the server was aborted. Timeout of 10000 milliseconds was exceeded
#include <iostream>
#include <string>
#include <list>
#include <cstdlib>
#include <mysqlx/xdevapi.h>
using namespace mysqlx;
int main() {
try {
Session sess(SessionOption::USER, "root",
SessionOption::PWD, "123456",
SessionOption::HOST, "172.29.207.112",
//SessionOption::HOST, "rm-bp1qp1x588kzb49rf.mysql.rds.aliyuncs.com",
SessionOption::PORT, 33060,
SessionOption::DB, "demo");
auto result = sess.sql("select * from person").execute();
for (auto row : result.fetchAll()) {
std::cout << row[0] << " " << row[1] << "\n";
}
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
}
}
I finally know the answer. The reason is that the cloud database provider does not support 33060 of X Protocol. Currently, Alibaba Cloud does not support it. I learned this from the intelligent problem robot, but it is not mentioned in the document. Alibaba Cloud should update documentation! !

MariaDB connector c ++ memory protection violation

I am having a problem connecting to the database using MariaDB. When I try to do anything with conn, it prints a memory violation.
I use Linux Mint 20.1!!
#include <iostream>
#include <memory>
#include <mariadb/conncpp.hpp>
int main(int argc, char**argv)
{
sql::Driver* driver = sql::mariadb::get_driver_instance();
sql::SQLString url("///");
sql::SQLString base("///");
std::cout << driver->getName() << std::endl;
sql::Properties properties({
{"base", "base"},
{"password", "password"}
});
sql::Connection*conn = driver->connect(url,properties);
conn->setSchema(base);// here
}
Does anyone know what the problem is?
Thank you in advance for your help.
driver->connect may return nullptr. I guess that is happening. You don't check conn.
There is also DriverManager::getConnection, that unlike Driver::connect will throw an exception in such case.

I invoke LSCopyApplicationURLsForURL() using C++, but get a segment fault

I want to write a C++ program to get associated applications which are suitable to open specified file. I find the LSCopyApplicationURLsForURL API, and create a command line C++ application by XCode.
But after running this program, I always get segment fault. XCode shows EXEC_BAD_ACCESS(code=1, address....) error.
I also tryied running it from sudo, but the same result. What is the problem?
The code:
#include <iostream>
#include <objc/objc.h>
#include <objc/objc-runtime.h>
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
using namespace std;
int main(int argc, const char * argv[]) {
auto url = CFURLRef("file:///Users/efan/src/a.cpp");
auto ret = LSCopyApplicationURLsForURL(url, kLSRolesAll);
cout << ret << endl;
return 0;
}
Try creating your CFURLRef using one of the proper CFURLCreate* methods. See "Creating a CFURL" here.
For example:
auto tempStringURL = CFStringCreateWithCString(nullptr, "/Users/efan/src/a.cpp", kCFStringEncodingUTF8);
auto url = CFURLCreateWithFileSystemPath(nullptr, tempStringURL, kCFURLPOSIXPathStyle, FALSE);
auto ret = LSCopyApplicationURLsForURL(url, kLSRolesAll);
You need to Release the "Created" variables to clean up memory.

Error in calling Microsoft vision API from C++

I want to call Microsoft Vision API from C++ and I am using cpr library to make requests. Now I'm run the following code:
#include <iostream>
#include <cpr/cpr.h>
#include <json.hpp>
int main(int argc, char** argv) {
auto response = cpr::Post(
cpr::Url{"https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/analyze"},
cpr::Body{{"url","https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/Broadway_and_Times_Square_by_night.jpg/450px-Broadway_and_Times_Square_by_night.jpg"}},
cpr::Header{{"Ocp-Apim-Subscription-Key", "xxxxxxxx"}}
);
std::cout << response.status_code ;
auto json = nlohmann::json::parse(response.text);
std::cout << json.dump(4) << std::endl;
}
Though the code is running by cmake, so make was successful. But when I executed the executable, the following error appeared:
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_M_create
Aborted (core dumped)
PS: the documentation for Microsoft Vision API can be found here
So, tell me if I am doing some mistake. Also if someone know that how to send http requests in QtQuick app please tell me
Can you try this?
auto my_json = nlohmann::json::object({
{ "url","https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/Broadway_and_Times_Square_by_night.jpg/450px-Broadway_and_Times_Square_by_night.jpg" }
});
response = cpr::Post(
cpr::Url{"https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/analyze"},
cpr::Body{ my_json.dump() },
cpr::Header{{"Ocp-Apim-Subscription-Key", "XXXXXX"}}
);

c++ Debug Assertion Failed on HTTP Request

I'm doing some code where i need to do a GET request and manipulate the info received. For this i'm using C++ REST SDK (codename "Casablanca") for the request
This is my code
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
using namespace utility;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;
//This method i saw on the Microsoft documentation
pplx::task<void> HTTPStreamingAsync()
{
http_client client(L"http://localhost:10000/Something"); //The api is running at the moment
// Make the request and asynchronously process the response.
return client.request(methods::GET).then([](http_response response)
{
// Print the status code.
std::wostringstream ss;
ss << L"Server returned returned status code " << response.status_code() << L'.' << std::endl;
std::wcout << ss.str();
// TODO: Perform actions here reading from the response stream.
auto bodyStream = response.body();
// In this example, we print the length of the response to the console.
ss.str(std::wstring());
ss << L"Content length is " << response.headers().content_length() << L" bytes." << std::endl;
std::wcout << ss.str();
});
}
void main(int argc, char **argv)
{
HTTPStreamingAsync().wait();
//...
}
And when i use debug i get error on the following line:
return client.request(methods::GET).then([](http_response response)
With debug i see that variable "client" has content, but i still receive this error:
Image with the Error Message
I google it the error, and most of the people say that it is error on the code (trying to access some parts of the memory)...
Any ideas?
This issue can happen when the cpprestsdk DLL is build with Multi-Threaded DLL /MD and the calling library is build with Multi-Threaded /MT. Since the cpprestsdk does not offer a configuration for a .lib file, you are forced to use /MD. At least that is best to my knowledge, as I haven't been able to compile cpprestsdk.lib out of the box without a bunch of linker errors.