visual c++ cURL webpage source to String^ - visual-studio-2010

Im' looking for solution how to read website to system::String^
i found curl to std::string idea but after converting linker has a few errors ;/
here is my code:
using namespace std;
string contents;
size_t handle_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
int numbytes = size*nmemb;
// The data is not null-terminated, so get the last character, and replace
// it with '\0'.
char lastchar = *((char *) ptr + numbytes - 1);
*((char *) ptr + numbytes - 1) = '\0';
contents.append((char *)ptr);
contents.append(1,lastchar);
*((char *) ptr + numbytes - 1) = lastchar; // Might not be necessary.
return size*nmemb;
}
..
CURL* curl = curl_easy_init();
if(curl)
{
// Tell libcurl the URL
curl_easy_setopt(curl,CURLOPT_URL, "google.com");
// Tell libcurl what function to call when it has data
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,handle_data);
// Do it!
CURLcode res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
textBox2->Text = gcnew String(contents.c_str());
}

If you're using .Net why don't you use it for the download?
using namespace System;
using namespace System::Net;
int main(array<System::String ^> ^args)
{
WebClient web;
String^ text = web.DownloadString("http://www.google.de");
Console::WriteLine(text);
return 0;
}
If you have to use cURL for some reasons this should work
std::vector<char> LoadFromUrl(const char* url)
{
struct Content
{
std::vector<char> data;
static size_t Write(char * data, size_t size, size_t nmemb, void * p)
{
return static_cast<Content*>(p)->WriteImpl(data, size, nmemb);
}
size_t WriteImpl(char* ptr, size_t size, size_t nmemb)
{
data.insert(end(data), ptr, ptr + size * nmemb);
return size * nmemb;
}
};
Content content;
CURL* curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &Content::Write);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_perform(curl);
content.data.push_back('\0');
return content.data;
}
int main(array<System::String ^> ^args)
{
auto content = LoadFromUrl("http://www.google.de");
String^ text = gcnew String(&content.front());
Console::WriteLine(text);
return 0;
}

Related

ESP32-C3-DevKitC-02 Getting Junk Data on UART for AT commands

I am interfacing A7672S 4G module with ESP32-C3-DevKitC-02 over Uart0
The problem i am facing is for any AT command published,i am getting lot of junk data
I have tried publising AT to the same 4G module using arduino ,i am able to get the correct response only with this ESP module i am seeing such issues
void uart_init(void)
{
const uart_config_t uart_config = {
.baud_rate = 115200,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
.source_clk = UART_SCLK_DEFAULT,
};
// We won't use a buffer for sending data.
uart_driver_install(UART_NUM_0, RX_BUF_SIZE * 2, 0, 0, NULL, 0);
uart_param_config(UART_NUM_0, &uart_config);
uart_set_pin(UART_NUM_0, TXD_PIN, RXD_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
}
#define RX_BUF_SIZE 1024
int sendData( const char *data)
{
static const char *TX_TASK_TAG = "TX_TASK";
esp_log_level_set(TX_TASK_TAG, ESP_LOG_VERBOSE);
const int len = strlen(data);
const int txBytes = uart_write_bytes(UART_NUM_0, data, len);
ESP_LOGI(TX_TASK_TAG, "Wrote %d bytes", txBytes);
return txBytes;
}
static uint8_t receiveData(uint8_t *data,unsigned int delay_ms)
{
uint8_t rxBytes = 0;
static const char *RX_TASK_TAG = "RX_TASK";
esp_log_level_set(RX_TASK_TAG, ESP_LOG_VERBOSE);
rxBytes = uart_read_bytes(UART_NUM_0, data,RX_BUF_SIZE, delay_ms / portTICK_PERIOD_MS);
data[rxBytes]='\0';
ESP_LOGI(RX_TASK_TAG, "Received %d bytes:\nRxData:%s\n", rxBytes,data);
return rxBytes;
}
uint8_t *data = (uint8_t *)malloc(RX_BUF_SIZE + 1);
uint8_t len=0;
static const char *MAIN_TAG = "MAIN_FUNCTION";
esp_log_level_set(MAIN_TAG, ESP_LOG_VERBOSE);
memset(data, 0, RX_BUF_SIZE + 1);
uart_init();
vTaskDelay(20);
uart_flush(UART_NUM_0);
sendData("AT+CGMI\r\n");
len = receiveData(data,2000);
if(OK == check_response(data,(unsigned char*)"OK"))
{
ESP_LOGI(MAIN_TAG,"Incorporated AT Response Received");
}
else
{
ESP_LOGI(MAIN_TAG,"AT Response Not Received");
}

Convert PUCHAR to PWCHAR in Minifilter

Before i use Minifilter,i was change PUCHAR to char* and then use GetWC to change this into wchar_t Like:
wchar_t* GetWC(const char* c)
{
long cSize = strlen(c) + 1;
wchar_t* wc = ExAllocatePool(POOL_FLAG_NON_PAGED, cSize);
if (!wc)
{
return NULL;
}
mbstowcs(wc, c, cSize);
return wc;
}
wchar_t* pathwchart = GetWC((char*)ntpath);
but now I use Minifilter,and when i use ExAllocatePool in the CallBacks of Minifilter,it will back a SYSTEM_SERVICE_EXCEPTION 0X3B error in blue screen,so how can i Convert PUCHAR to PWCHAR in Minifilter.
wchar_t* GetWC(const char* c) {
long cSize = strlen(c) + 1;
wchar_t* wc = ExAllocatePool2(POOL_FLAG_PAGED, cSize,"TAGHERE");
if (!wc)
{
return NULL;
}
mbstowcs(wc, c, cSize);
return wc; }
just change the ExAllocatePool to ExAllocatePool2 and page flag and solve the question

Cast a (void const *x) to a (unsigned char const *y)

I'm going through a source code analyzing its implementations where I have a method defined :
unsigned int rs_calc_weak_sum(void const *p, int len) {
unsigned char const *buf = (unsigned char const *) p;
}
What type of parameter should be passed into this method??
please help me.
thanks.
Any pointer can be passed to a void * parameter. What 'should' be passed, depends on what the code does with that parameter.
char array[12] = "Hello World";
unsigned in res = 0;
res = rs_calc_weak_sum(array, 12);
#include <stdio.h>
int main ( void )
{
char filename[] = "file.txt";
FILE *file = fopen ( filename, "r" );
if (file != NULL) {
char line [1000];
while(fgets(line,sizeof line,file)!= NULL) /* read a line from a file */ {
res = rs_calc_weak_sum(line, 1000);
}
fclose(file);
}
else {
perror(filename); //print the error message on stderr.
}
return 0;
}

C++/CLI HTTP Proxy problems

I'm trying(very hard) to make a small HTTP Proxy server which I can use to save all communications to a file. Seeing as I dont really have any experience in the area, I used a class from codeproject.com and some associated code to get started (It was made in the old CLI syntax, so I converted it). I couldn't get it working, so I added lots more code to make it work (threads etc), and now it sort of works. Basically, it recieves something from a client (I just configured Mozilla Firefox to route its connections through this proxy) and then routes it to google.com. After it sends Firefox's data to google, recieves a responce, and sends that to Firefox. This works fine, but then the proxy fails to recieve any data from Firefox. It just loops in the Sleep(50) section. Anyway, heres the code:
ProxyTest.cpp:
#include "stdafx.h"
#include "windows.h"
#include "CHTTPProxy.h"
public ref class ClientThread {
public:
System::Net::Sockets::TcpClient ^ pClient;
CHttpProxy ^ pProxy;
System::Int32 ^ pRecieveBufferSize;
System::Threading::Thread ^ Thread;
ClientThread(System::Net::Sockets::TcpClient ^ sClient,
CHttpProxy ^ sProxy,
System::Int32 ^ sRecieveBufferSize) {
pClient = sClient;
pProxy = sProxy;
pRecieveBufferSize = sRecieveBufferSize;
};
void StartReading() {
Thread = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(this,&ClientThread::ThreadEntryPoint));
Thread->Start();
};
void ThreadEntryPoint() {
char * bytess;
bytess = new char[(int)pRecieveBufferSize];
memset(bytess, 0, (int)pRecieveBufferSize);
array<unsigned char> ^ bytes = gcnew array<unsigned char>((int)pRecieveBufferSize);
array<unsigned char> ^ sendbytes;
do {
if (pClient->GetStream()->DataAvailable) {
try {
do {
Sleep(100); //Lets wait for whole packet to get cached (If it even does...)
unsigned int k = pClient->GetStream()->Read(bytes, 0, (int)pRecieveBufferSize); //Read it
for (unsigned int i=0; i<(int)pRecieveBufferSize; i++) bytess[i] = bytes[i];
Console::WriteLine("Packet Received:\n"+gcnew System::String(bytess));
pProxy->SendToServer(bytes,pClient->GetStream()); //Now send it to google!
} while (pClient->GetStream()->DataAvailable);
} catch (Exception ^ e) {
break;
}
} else {
Sleep(50);
if (!(pClient->Connected)) break;
};
} while (pClient->GetStream()->CanRead);
delete [] bytess;
pClient->Close();
};
};
int main(array<System::String ^> ^args)
{
System::Collections::Generic::Stack<ClientThread ^> ^ Clients =
gcnew System::Collections::Generic::Stack<ClientThread ^>();
System::Net::Sockets::TcpListener ^ pTcpListener = gcnew System::Net::Sockets::TcpListener(8080);
pTcpListener->Start();
System::Net::Sockets::TcpClient ^ pTcpClient;
while (1) {
pTcpClient = pTcpListener->AcceptTcpClient(); //Wait for client
ClientThread ^ Client = gcnew ClientThread(pTcpClient,
gcnew CHttpProxy("www.google.com.au", 80),
pTcpClient->ReceiveBufferSize); //Make a new object for this client
Client->StartReading(); //Start the thread
Clients->Push(Client); //Add it to the list
};
pTcpListener->Stop();
return 0;
}
CHTTPProxy.h, from http://www.codeproject.com/KB/IP/howtoproxy.aspx with a lot of modifications:
#using <mscorlib.dll>
#using <SYSTEM.DLL>
using namespace System;
using System::Net::Sockets::TcpClient;
using System::String;
using System::Exception;
using System::Net::Sockets::NetworkStream;
#include <stdio.h>
ref class CHttpProxy
{
public:
CHttpProxy(System::String ^ szHost, int port);
System::String ^ m_host;
int m_port;
void SendToServer(array<unsigned char> ^ Packet, System::Net::Sockets::NetworkStream ^ sendstr);
};
CHttpProxy::CHttpProxy(System::String ^ szHost, int port)
{
m_host = gcnew System::String(szHost);
m_port = port;
}
void CHttpProxy::SendToServer(array<unsigned char> ^ Packet, System::Net::Sockets::NetworkStream ^ sendstr)
{
TcpClient ^ tcpclnt = gcnew TcpClient();
try
{
tcpclnt->Connect(m_host,m_port);
}
catch (Exception ^ e )
{
Console::WriteLine(e->ToString());
return;
}
// Send it
if ( tcpclnt )
{
NetworkStream ^ networkStream;
networkStream = tcpclnt->GetStream();
int size = Packet->Length;
networkStream->Write(Packet, 0, size);
array<unsigned char> ^ bytes = gcnew array<unsigned char>(tcpclnt->ReceiveBufferSize);
char * bytess = new char[tcpclnt->ReceiveBufferSize];
Sleep(500); //Wait for responce
do {
unsigned int k = networkStream->Read(bytes, 0, (int)tcpclnt->ReceiveBufferSize); //Read from google
for(unsigned int i=0; i<k; i++) {
bytess[i] = bytes[i];
if (bytess[i] == 0) bytess[i] = ' '; //Dont terminate the string
if (bytess[i] < 8) bytess[i] = ' '; //Somethings making the computer beep, and its not 7?!?!
};
Console::WriteLine("\n\nAbove packet sent to google. Google Packet Received:\n"+gcnew System::String(bytess));
sendstr->Write(bytes,0,k); //Send it to mozilla
Console::WriteLine("\n\nAbove packet sent to client...");
//Sleep(1000);
} while(networkStream->DataAvailable);
delete [] bytess;
}
return;
}
Any help would be much appreciated, I've tried for hours. (Sorry about the indents nobugz, its fixed now)

GdipCreateBitmapFromStream change of contract on Windows 7?

We have a perfectly functional app that just broke on Windows 7 because (the GDI+ primitive) GdipCreateBitmapFromStream refuses JPEG images presented to it (without problem on XP and even Vista).
We don't directly call GDI+, we call the documented ATL CImage class, and it calls that, and gets the error.
It's our own OLE stream implementation.
Has anyone seen a way around this?
Here is a complete test case:
#include <atlbase.h>
#include <atlimage.h>
#include <gdiplus.h>
#include <time.h>
#include <sys/stat.h>
// GSMemoryStream.h : Declaration of the GSMemoryStream
/* No ATL or class factory support is needed here. You get one of these via "new", with zero reference count...
Image.Load(IStreamPtr(new GSMemoryStream(ptr, len));
and the smart pointer will provoke its deletion at the right time....
*/
// GSMemoryStream
class GSMemoryStream :
public IStream
{
private:
ULONG m_Length;
ULONG m_CurPtr;
PBYTE m_Base;
int m_rc;
public:
GSMemoryStream(PBYTE _p, DWORD _len) {
m_Length = _len;
m_CurPtr = 0;
m_Base = _p;
m_rc = 0;
}
GSMemoryStream () {
m_Length = 0;
m_CurPtr = 0;
m_Base = NULL;
m_rc = 0;
}
STDMETHODIMP Read(void *,ULONG,ULONG *);
STDMETHODIMP Write(const void *,ULONG,ULONG *) {return E_FAIL;}
STDMETHODIMP Seek(LARGE_INTEGER,DWORD,ULARGE_INTEGER *);
STDMETHODIMP SetSize(ULARGE_INTEGER) {return E_FAIL;}
STDMETHODIMP CopyTo(IStream *,ULARGE_INTEGER,ULARGE_INTEGER *,ULARGE_INTEGER *);
STDMETHODIMP Commit(DWORD) {return S_OK;}
STDMETHODIMP Revert(void) {return S_OK;}
STDMETHODIMP LockRegion(ULARGE_INTEGER,ULARGE_INTEGER,DWORD) {return S_OK;}
STDMETHODIMP UnlockRegion(ULARGE_INTEGER,ULARGE_INTEGER,DWORD) {return S_OK;}
STDMETHODIMP Stat(STATSTG *,DWORD);
STDMETHODIMP Clone(IStream ** ) {return E_FAIL;}
STDMETHODIMP QueryInterface(const IID & iid,void ** d) throw() {
if (IsEqualGUID(iid, IID_IUnknown) || IsEqualGUID (iid, __uuidof(IStream))) {
*d = (PVOID)this;
AddRef();
return S_OK;
}
return E_FAIL;
}
ULONG STDMETHODCALLTYPE AddRef(void) throw() {
m_rc++;
return S_OK;
}
ULONG STDMETHODCALLTYPE Release(void) throw() {
if (--m_rc == 0)
delete this; // can never go negative, because the m_rc won't be around any more once it is 0.
// so it's not even meaningful to test for it and breakpoint or throw.
return S_OK;
}
};
// CGSMemoryStream
STDMETHODIMP GSMemoryStream::Read(void * p,ULONG n, ULONG * pNread) {
ATLTRACE(L"GSMS$Read p %p bufct %d m_curptr %d\r\n", p, n, m_CurPtr);
if ((n + m_CurPtr) > m_Length)
n = m_Length - m_CurPtr;
memcpy(p, m_Base + m_CurPtr, n);
if (pNread)
*pNread = n;
m_CurPtr += n;
ATLTRACE(L"GSMS$Read(final) n %d m_CurPtr %d\r\n", n, m_CurPtr);
return S_OK;
}
STDMETHODIMP GSMemoryStream::Seek(LARGE_INTEGER pos,DWORD type,ULARGE_INTEGER * newpos) {
LONG lpos = (LONG)pos.LowPart;
ATLTRACE(L"GSMS$Seek type %d lpos %d m_CurPtr %d\r\n", type, lpos, m_CurPtr);
switch (type) {
case STREAM_SEEK_SET:
if (lpos < 0 || lpos > (LONG) m_Length)
return E_POINTER;
m_CurPtr = (ULONG)lpos;
break;
case STREAM_SEEK_CUR:
if (lpos + m_CurPtr < 0 || lpos + m_CurPtr > m_Length)
return E_POINTER;
m_CurPtr += lpos;
break;
case STREAM_SEEK_END:
if (lpos > 0)
lpos = -lpos;
if (lpos + m_Length < 0)
return E_POINTER;
m_CurPtr = m_Length + lpos;
break;
default:
return E_FAIL;
}
ATLTRACE(L"GSMS$Seek end m_CurPtr %d\r\n", m_CurPtr);
if (newpos) {
newpos->HighPart = 0;
newpos->LowPart = m_CurPtr;
}
return S_OK;
}
STDMETHODIMP GSMemoryStream::CopyTo(IStream * pstm,ULARGE_INTEGER cb,ULARGE_INTEGER * pNread,ULARGE_INTEGER * pNwritten){
ATLTRACE("GSMS$CopyTo\r\n");
if (cb.HighPart)
return E_INVALIDARG;
ULONG n = cb.LowPart;
if ((n + m_CurPtr) > m_Length)
n = m_Length - m_CurPtr;
ULONG nwritten = 0;
HRESULT hr = pstm->Write(m_Base+m_CurPtr, n, &nwritten);
if (nwritten < n)
nwritten = n;
if (pNread) {
pNread->HighPart = 0;
pNread->LowPart = n;
}
if (pNwritten) {
pNwritten->HighPart = 0;
pNwritten->LowPart = nwritten;
}
m_CurPtr += n;
return hr;
}
STDMETHODIMP GSMemoryStream::Stat(STATSTG * ps,DWORD krazyflag) {
ATLTRACE(L"GSMS$Stat kf %d\r\n", krazyflag);
memset(ps, 0, sizeof(STATSTG));
ps->type = STGTY_STREAM;
ps->cbSize.LowPart = m_Length;
ps->cbSize.HighPart = 0;
#if 0
ps->mtime = (DWORD)time(NULL);
ps->ctime = (DWORD)time(NULL);
ps->atime = (DWORD)time(NULL);
#endif
return S_OK;
}
int main (int argc, char ** argv) {
if (argc < 2) {
fprintf(stderr, "Need image file pathname\n");
exit(2);
}
struct _stat SSTAT;
const char* fn = argv[1];
int failed = _stat(fn, &SSTAT);
if (failed) {
fprintf(stderr, "Can't open file: %s\n", fn);
exit(3);
}
size_t len = SSTAT.st_size;
printf ("Len = %d\n", len);
FILE* f = fopen(fn, "rb");
unsigned char * buf = new unsigned char [len];
size_t got = fread (buf, 1, len, f);
printf ("Got = %d\n", got);
fclose(f);
CoInitialize(NULL);
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
GSMemoryStream G(buf, len);
CImage cim;
HRESULT hr = cim.Load(&G);
printf("HRESULT = 0x%08X\n", hr);
delete [] buf;
CoUninitialize();
return 0;
}
Have you tried using the documented Bitmap object instead of using the undocumented GDI+ entrypoints?
Further research reveals that W7 queries an additional optional interface on the stream, and it's essential to return E_NOINTERFACE instead of E_NOTIMPL for it.

Resources