how to contruct HttpSendRequest method of WININET - visual-c++

I have dummy web service with URI =http://localhost/IO_100_Service.svc/xml?id={id} which return data in XML format
I want to call this service using WINInet APi in VC++.Can anybody help me how to use contruct "HttpSendRequest" method to add header and data to call this service .

Here is a sample code you should be able to modify to your needs. I tested it with VS2005 using command line template project.
#include <tchar.h>
#include <wininet.h>
/// ....
HINTERNET hIntSession =
::InternetOpen(_T("MyApp"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
HINTERNET hHttpSession =
InternetConnect(hIntSession, _T("api.twitter.com"), 80, 0, 0, INTERNET_SERVICE_HTTP, 0, NULL);
HINTERNET hHttpRequest = HttpOpenRequest(
hHttpSession,
_T("GET"),
_T("1/statuses/user_timeline.xml?screen_name=twitterapi"),
0, 0, 0, INTERNET_FLAG_RELOAD, 0);
TCHAR* szHeaders = _T("Content-Type: text/html\nMySpecialHeder: whatever");
CHAR szReq[1024] = "";
if( !HttpSendRequest(hHttpRequest, szHeaders, _tcslen(szHeaders), szReq, strlen(szReq))) {
DWORD dwErr = GetLastError();
/// handle error
}
CHAR szBuffer[1025];
DWORD dwRead=0;
while(::InternetReadFile(hHttpRequest, szBuffer, sizeof(szBuffer)-1, &dwRead) && dwRead) {
szBuffer[dwRead] = 0;
OutputDebugStringA(szBuffer);
dwRead=0;
}
::InternetCloseHandle(hHttpRequest);
::InternetCloseHandle(hHttpSession);
::InternetCloseHandle(hIntSession);

Related

Anybody also noticed that Windows 11 multithreaded font usage causes a heap corruption in GDI?

we have multiple printing applications that draw text into (an enhmetafile) GDI. When these painting actions (in short something like CreateFont(), SelectFont(), DrawText(), GetObject(), ... DeselectFont(), DeleteFont()) are done in threads, the application crashes very soon in DeleteObject() of a font handle. If the threads are synchronized, it does not happen. Under Windows 10 there's is no problem at all.
Reproduction by some simple code is not trivial, and our code is a little complex querying the LOGFONT, querying current object, ... to lay out the page to paint into (including wordbreak etc), and a simple multithreaded sample does not show this behaviour. It must be an unfortunate combination of the font APIs (or a combination with other GDI object APIs).
Trace of the crash is always in the same place, a corrupted heap caused by the DeleteObject API:
ntdll.dll!_RtlReportCriticalFailure#12() Unknown
ntdll.dll!_RtlpReportHeapFailure#4() Unknown
ntdll.dll!_RtlpHpHeapHandleError#12() Unknown
ntdll.dll!_RtlpLogHeapFailure#24() Unknown
ntdll.dll!_RtlpFreeHeapInternal#20() Unknown
ntdll.dll!RtlFreeHeap() Unknown
gdi32full.dll!_vFreeCFONTCrit#4() Unknown
gdi32full.dll!_vDeleteLOCALFONT#4() Unknown
gdi32.dll!_InternalDeleteObject#4() Unknown
gdi32.dll!_DeleteObject#4() Unknown
I do write it here in the hope of finding someone who has the same problem - or to be found by someone looking for others (like me here) ;)
OK, the culprit for our case of printing in a metafile DC has been found: the APIs GetTextExtentPoint() and its alias GetTextExtentPoint32() are not threadsafe in Windows 11 and do corrupt the GDI heap if GDI text operations are used by multiple threads.
More findings:
DC is a metafile DC:
heap becomes corrupted if `GetTextExtentPoint()ยด is being used
everything works without this API
DC is a Window DC:
the code always hangs in an endless loop in ExtTextOut() or GetTextExtentPoint() (if opted in) in the application's painting loop. BTW: Even in Windows 10...! Not a deadlock, but full processor load (one at least one of the CPUs, so there's some kind of synchronization)
The code is attached, you may play around with the macros SHOW_ERROR and USE_METAFILE...:
#include "stdafx.h"
#include <windows.h>
#include <windowsx.h>
#include <process.h>
#include <assert.h>
#define SHOW_ERROR 1
#define USE_METAFILE 0
#define sizeofTSTR(b) (sizeof(b)/sizeof(TCHAR))
const int THREADCOUNT = 20;
struct scThreadData
{
public:
volatile LONG* _pnFinished;
TCHAR _szFilename[MAX_PATH];
DWORD _dwFileSize;
};
void _cdecl g_ThreadFunction(void* pParams)
{
scThreadData* pThreadData = reinterpret_cast<scThreadData*>(pParams);
PRINTDLG pd = {0};
HDC hDC = NULL;
::Sleep(rand() % 1000);
printf("start %d\n", ::GetCurrentThreadId());
#if USE_METAFILE
pd.lStructSize = sizeof(pd);
pd.Flags = PD_RETURNDC | PD_RETURNDEFAULT;
::PrintDlg(&pd);
RECT rcPage = {0,0,10000,10000};
hDC = ::CreateEnhMetaFile(pd.hDC, pThreadData->_szFilename, &rcPage, _T("Hallo"));
#else
hDC = ::GetDC(NULL);
#endif
for (int i = 0; i < 20000; ++i)
{
HFONT newFont = ::CreateFont(-100, 0, 0, 0, 0, 0, 0, 0, DEFAULT_CHARSET, OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, 0, L"Arial");
HFONT oldFont = SelectFont(hDC, newFont);
::ExtTextOut(hDC, 0, 0, 0, NULL, _T("x"), 1, NULL);
#if SHOW_ERROR
SIZE sz = {};
::GetTextExtentPoint(hDC, L"Hallo", 5, &sz); // <<-- causes GDI heap to be corrupted
#endif
SelectFont(hDC, oldFont);
::DeleteFont(newFont);
}
#if USE_METAFILE
::DeleteEnhMetaFile(::CloseEnhMetaFile(hDC));
::DeleteDC(pd.hDC);
#else
::DeleteDC(hDC);
#endif
::DeleteFile(pThreadData->_szFilename);
printf("end %d\n", ::GetCurrentThreadId());
// done
::InterlockedIncrement(pThreadData->_pnFinished);
}
int _tmain(int argc, _TCHAR* argv[])
{
volatile LONG nFinished(0);
scThreadData TD[THREADCOUNT];
TCHAR szUserName[30];
TCHAR szComputerName[30];
DWORD dwLen;
dwLen = sizeofTSTR(szUserName);
::GetUserName(szUserName,&dwLen);
dwLen = sizeofTSTR(szComputerName);
::GetComputerName(szComputerName,&dwLen);
for (int nThread = 0; nThread < THREADCOUNT; ++nThread)
{
TD[nThread]._pnFinished = &nFinished;
_stprintf_s(TD[nThread]._szFilename,MAX_PATH,_T("test-%s-%d.emf"),szUserName,nThread);
_beginthread(g_ThreadFunction,10000,(void*)&TD[nThread]);
::Sleep(200);
}
Sleep(1000);
while (nFinished < THREADCOUNT)
{
::Sleep(100);
}
return 0;
}

Can't send data and receive data after open ComPort Visual C++

I'm making Windows Console app to write and read data via COM port.
However, I can't send and receive any data, although the COM port was successfullly opened.
"Open COM-port" code:
unsigned int c;
LPCWSTR portCom;
TCHAR ComString[30];
HANDLE hComm;
DCB port;
int main(int argc, char* argv[])
{
// Open COM port
_stprintf_s(ComString, 11, _T("\\\\.\\COM3"));
hComm = CreateFile(ComString, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
if (hComm == INVALID_HANDLE_VALUE)
{
abort();
}
memset(&port, 0, sizeof(port));
port.DCBlength = sizeof(port);
if (!::GetCommState(hComm, &port))
{
abort();
}
port.BaudRate = CBR_115200;
port.ByteSize = 8;
port.Parity = NOPARITY;
port.StopBits = ONESTOPBIT;
if (!::SetCommState(hComm, &port))
{
abort();
}
"Send and receive data" code:
// Send and receive data
unsigned char sendData[8];
unsigned int rcvData = 0;
DWORD dwWritten;
DWORD dwRead;
sendData[0] = 'A';
WriteFile(hComm, &sendData[0], 1, &dwWritten, NULL);
dwRead = 0;
while (dwRead == 0) {
ReadFile(hComm, &rcvData, 1, &dwRead, NULL);
}
return 0;
}
I resolved my problem.
I found that I need to set FLAG when open COM port using CreateFas 0.
Thank you all.

How to compile shader with newest Effect Framework?

I usually use the Microsoft DirectX SDK (June 2010) which is deprecated. I download vs2015 which includes newest directx sdk and latest version FX11 on github. I don't know how to compile shader now.
before I can compile shader like this
ID3D10Blob *compiledShader = 0;
ID3D10Blob *compilationMsgs = 0;
result = D3DX11CompileFromFile("SolidColor.fx", 0, 0, 0, "fx_5_0", shaderFlags,
0, 0, &compiledShader, &compilationMsgs, 0);
if (compilationMsgs != 0)
{
MessageBox(0, (char*)compilationMsgs->GetBufferPointer(), 0, 0);
compilationMsgs->Release();
compilationMsgs = 0;
}
if (FAILED(result))
{
MessageBox(0, "error", 0, 0);
return false;
}
result = D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(),
0, m_pd3dDevice, &m_pFx);
compiledShader->Release();
if (FAILED(result))
{
MessageBox(0, "error", 0, 0);
return false;
}
m_pTechnique = m_pFx->GetTechniqueByName("ColorTech");
m_pFxWorldViewProj = m_pFx->GetVariableByName("gWorldViewProj")->AsMatrix();
But now how to compile shader? use D3DX11CompileEffectFromFile or D3DX11CreateEffectFromFile? Please give sample code,thank you.
I know, it is so easy, just one function D3DX11CompileEffectFromFile is OK.
//compile shader
ID3DBlob* errorBlob;
DWORD shaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined _DEBUG || defined DEBUG
shaderFlags = D3DCOMPILE_DEBUG;
#endif
hr = D3DX11CompileEffectFromFile(L"color.fx", nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, shaderFlags,
0, m_pd3dDevice, &m_pFx, &errorBlob);
if (FAILED(hr))
{
MessageBox(nullptr, (LPCWSTR)errorBlob->GetBufferPointer(), L"error", MB_OK);
return hr;
}
m_pTechnique = m_pFx->GetTechniqueByName("ColorTech");
m_pFxWorldViewProj = m_pFx->GetVariableByName("gWorldViewProj")->AsMatrix();

Does refresh() need to be called at least once, when using windows in ncurses?

I've been testing ncurses, I tried doing a simple code using windows, by reading the code from the tutorials it seemed to me like calling wrefresh() was enough if changes were made just to one window. So I tried the following code, but it doesn't work, does anyone know why?
#include <ncurses.h>
int main (void) {
int ch;
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
WINDOW *my_window = newwin(10, 20, 3, 4);
box(my_window, 0, 0);
wrefresh(my_window);
while ((ch=getch()) != 'q');
endwin();
return 0;
}
If I add an extra call to refresh() before wrefresh() everything works fine.
#include <ncurses.h>
int main (void) {
int ch;
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
WINDOW *my_window = newwin(10, 20, 3, 4);
box(my_window, 0, 0);
refresh();
wrefresh(my_window);
while ((ch=getch()) != 'q');
endwin();
return 0;
}
I've tried several things, for instance calling refresh() after wrefresh() doesn't work either, using only refresh() also does not work. Also example 7 in this guide shows after calling refresh() once, it is enough to just call wrefresh() in the while loop.
Is it always mandatory to make a call to refresh() at least once after initscr()? the documentation does not seem to mention this.
Calling getch is the same as wgetch(stdscr). When you call wgetch, it refreshes the window that it uses as a parameter. If you are trying to refresh a different window (such as my_window), then you should use that window as the parameter.
In your example, there is nothing interesting that is written to stdscr. So you can omit the plain refresh() call.
With those changes, the program is
#include <ncurses.h>
int main (void) {
int ch;
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
WINDOW *my_window = newwin(10, 20, 3, 4);
box(my_window, 0, 0);
while ((ch=wgetch(my_window)) != 'q');
endwin();
return 0;
}
For a more interesting demo, you could write into the window. That is best done with a subwindow, so that it can be scrolled, e.g.,
#include <ncurses.h>
int main (void) {
WINDOW *my_window;
WINDOW *my_scroller;
int ch;
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
if ((my_window = newwin(10, 20, 3, 4)) != 0) {
box(my_window, 0, 0);
wrefresh(my_window);
if ((my_scroller = derwin(my_window, 8, 18, 1, 1)) != 0) {
scrollok(my_scroller, TRUE);
while ((ch=wgetch(my_scroller)) != 'q') {
wprintw(my_scroller, "%#x - %s\n", ch, keyname(ch));
}
}
}
endwin();
return 0;
}

how to embed dll in vc++? how to extract that emeded dll to local drive? how to create tlb file based on the dll runtime?

I am working with vb.net .. I am new in vc++. I need to write some code in vc++ in some case. I need vc++ for following reason.
I created one dll in vb.net and make a tlb file based on vb.net dll. I import physical tlb file in my vc++ code with static value, as mentioned following.
#import "C:\Documents and Settings\Ankit.ass\My Documents\Visual Studio 2010\Projects\SetupValidationPro\SetupValidationPro\bin\Debug\SetupValidationPro.tlb" named_guids raw_interfaces_only
That's work fine.. My problem is that, I want to create a tlb file dynamically or runtime using vc++ and load that tlb file dynamically.
So, I need to embed a dll in vc++. How can I embed dll in vc++?
Now, I want to extract my embed dll to some physical file. so how can I extract my dll to physical location in vc++?
And, at the last step I want to create a tlb file dynamically using that extracted dll using vc++.. and load tlb file dynamically.
How can I achieve this?
Thanks
Ankit
I resolve the issue after lots of googling.. This is the code from where my issue is resolve. I don't need native code for this..
#include "stdafx.h"
#include "stdafx.h"
#include <Msi.h>
#include <WinUser.h>
#include "windows.h"
#include <afxwin.h>
#include <afx.h>
#include <WinSpool.h>
#include <assert.h>
#include <WinBase.h>
#include "resource.h"
#define IDR_DLL1 101
#define IDR_EXE1 102
bool ExtractDll(const HINSTANCE hInstance, WORD resourceID, LPCTSTR szOutputFilename);
bool ExtractExe(const HINSTANCE hInstance, WORD resourceID, LPCTSTR szOutputFilename);
bool cmd();
CString AppPath();
#define RtlCopyMemory(Destination,Source,Length) memcpy((Destination),(Source),(Length))
#import "dv.tlb" named_guids raw_interfaces_only
using namespace dv;
UINT __stdcall Validation( MSIHANDLE hModule )
{
/*BOOL qw = ExtractDll(AfxGetResourceHandle(), IDR_DLL1, _T("C:\\VBDLL.dll") );
BOOL qw1 = ExtractExe(AfxGetResourceHandle(), IDR_EXE1, _T("C:\\RegAsm.exe") );*/
BOOL qw = ExtractDll(AfxGetResourceHandle(), IDR_DLL1, (LPCTSTR)(AppPath() + _T("\\dv.dll")) );
if (qw == false)
{
return ERROR_INSTALL_USEREXIT;
}
BOOL qw1 = ExtractExe(AfxGetResourceHandle(), IDR_EXE1, (LPCTSTR)(AppPath() + _T("\\RegAsm.exe")) );
if (qw1 == false)
{
return ERROR_INSTALL_USEREXIT;
}
BOOL retCmd = cmd();
if (retCmd==false)
{
return ERROR_INSTALL_USEREXIT;
}
IkeyvalidationPtr pICalc(__uuidof(SetupClass));
long retun =0;
BSTR strVer = SysAllocString(L"4.0.1517");
pICalc->keyValidation(strVer,&retun);
if (retun==1)
{
return ERROR_INSTALL_USEREXIT;
}
return ERROR_SUCCESS;
}
CString AppPath()
{
try
{
TCHAR path [MAX_PATH];
ITEMIDLIST* pidl;
HRESULT hRes = SHGetSpecialFolderLocation( NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE , &pidl );
if (hRes==NOERROR)
{
SHGetPathFromIDList( pidl, path);
}
CString apPath;
apPath = path;
apPath = apPath + _T("\\path");
CreateDirectory((LPCWSTR) apPath,NULL);
return apPath;
}
catch(...)
{
}
}
bool cmd()
{
CString m1=_T('');
CString temp1 = _T("");
CString temp = temp1 + _T('"');
//CString s1 = temp + AppPath() + _T("\\RegAsm.exe"); // Cascading concatenation
CString s1 = temp + AppPath() + _T("\\RegAsm.exe") + _T('"'); // Cascading concatenation
CString s2 = _T(" /codebase");
CString message = s1 + _T('"')+ _T(' ')+ _T('"') + AppPath() + _T("\\dv.dll") + _T('"') +_T(' ') + _T("/tlb:")+('"') + AppPath() + _T("\\dv.tlb") + _T('"')+ s2;
CString message1 = _T('"') + AppPath() + _T("\\dv.dll") + _T('"') +_T(' ') + _T("/tlb:")+('"') + AppPath() + _T("\\dv.tlb") + _T('"')+ s2;
SHELLEXECUTEINFO ExecuteInfo;
memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
ExecuteInfo.cbSize = sizeof(ExecuteInfo);
ExecuteInfo.fMask = 0;
ExecuteInfo.hwnd = 0;
ExecuteInfo.lpVerb = L"runas"; // Operation to perform
ExecuteInfo.lpFile = s1;
ExecuteInfo.lpParameters = message1; // Additional parameters
ExecuteInfo.lpDirectory = 0; // Default directory
ExecuteInfo.nShow = SW_HIDE;
//ExecuteInfo.nShow = SW_SHOW;
ExecuteInfo.hInstApp = 0;
if(ShellExecuteEx(&ExecuteInfo) == FALSE)
{
return false;
}
return true;
}
bool ExtractDll(const HINSTANCE hInstance, WORD resourceID, LPCTSTR szOutputFilename)
{
TCHAR sResName[5] = _T("#101");
TCHAR sRestype[4] = _T("DLL");
HRSRC hres = FindResource(AfxGetResourceHandle(), sResName,sRestype);
if (hres == 0)
{
return false;
}
HGLOBAL hbytes = LoadResource(hInstance, hres);
// Lock the resource
LPVOID pdata = LockResource(hbytes);
DWORD dwSize = SizeofResource(hInstance, hres);
HANDLE hFile = CreateFile(szOutputFilename, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
/// INSERT DATA IN FILE
HANDLE hFilemap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, dwSize, NULL);
LPVOID lpBaseAddress = MapViewOfFile(hFilemap, FILE_MAP_WRITE, 0, 0, 0);
try
{
RtlCopyMemory(lpBaseAddress,pdata,dwSize);
}
catch ( ... )
{
return false;
}
UnmapViewOfFile(lpBaseAddress);
CloseHandle(hFilemap);
CloseHandle(hFile);
return true ;
}
bool ExtractExe(const HINSTANCE hInstance, WORD resourceID, LPCTSTR szOutputFilename)
{
/*LPTSTR sArgv = argv[1];
LPTSTR sArgv2 = argv[2];*/
TCHAR sResName[5] = _T("#102");
TCHAR sRestype[4] = _T("EXE");
//HINSTANCE Nl=AfxGetInstanceHandle();
HRSRC hres = FindResource(AfxGetResourceHandle(), sResName, sRestype);
if (hres == 0)
{
return false;
}
HGLOBAL hbytes = LoadResource(hInstance, hres);
// Lock the resource
LPVOID pdata = LockResource(hbytes);
DWORD dwSize = SizeofResource(hInstance, hres);
HANDLE hFile = CreateFile(szOutputFilename, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
/// INSERT DATA IN FILE
HANDLE hFilemap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, dwSize, NULL);
LPVOID lpBaseAddress = MapViewOfFile(hFilemap, FILE_MAP_WRITE, 0, 0, 0);
try
{
RtlCopyMemory(lpBaseAddress,pdata,dwSize);
}
catch ( ... )
{
return false;
}
UnmapViewOfFile(lpBaseAddress);
CloseHandle(hFilemap);
CloseHandle(hFile);
return true;
}
This is the MFC code from which solved my issue. This code embeds the resources, extracts the resources and registers the type library at run-time.

Resources