Wednesday, July 16, 2014

How to get system IP, Gateway, Subnet Mask address.

#include "winsock2.h"
#include "iphlpapi.h"
#include "stdio.h"
#include "stdlib.h"
#pragma comment(lib, "IPHLPAPI.lib")

#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))


int _tmain(int argc, _TCHAR* argv[])
{
   
    PIP_ADAPTER_INFO pAdapterInfo;
    PIP_ADAPTER_INFO pAdapter = NULL;
    DWORD dwRetVal = 0;
    UINT i;

/* variables used to print DHCP time info */
    struct tm newtime;
    char buffer[32];
    errno_t error;

    ULONG ulOutBufLen = sizeof (IP_ADAPTER_INFO);
    pAdapterInfo = (IP_ADAPTER_INFO *) MALLOC(sizeof (IP_ADAPTER_INFO));
    if (pAdapterInfo == NULL) {
        printf("Error allocating memory needed to call GetAdaptersinfo\n");
        return 1;
    }
// Make an initial call to GetAdaptersInfo to get
// the necessary size into the ulOutBufLen variable
    if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
        FREE(pAdapterInfo);
        pAdapterInfo = (IP_ADAPTER_INFO *) MALLOC(ulOutBufLen);
        if (pAdapterInfo == NULL) {
            printf("Error allocating memory needed to call GetAdaptersinfo\n");
            return 1;
        }
    }

    if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) {
        pAdapter = pAdapterInfo;
        while (pAdapter) {
            printf("\tComboIndex: \t5d\n", pAdapter->ComboIndex);
            printf("\tAdapter Name: \t%s\n", pAdapter->AdapterName);
            printf("\tAdapter Desc: \t%s\n", pAdapter->Description);
            printf("\tAdapter Addr: \t");
            for (i = 0; i < pAdapter->AddressLength; i++) {
                if (i == (pAdapter->AddressLength - 1))
                    printf("%.2X\n", (int) pAdapter->Address[i]);
                else
                    printf("%.2X-", (int) pAdapter->Address[i]);
            }
            printf("\tIndex: \t%d\n", pAdapter->Index);
            printf("\tType: \t");
            switch (pAdapter->Type) {
            case MIB_IF_TYPE_OTHER:
                printf("Other\n");
                break;
            case MIB_IF_TYPE_ETHERNET:
                printf("Ethernet\n");
                break;
            case MIB_IF_TYPE_TOKENRING:
                printf("Token Ring\n");
                break;
            case MIB_IF_TYPE_FDDI:
                printf("FDDI\n");
                break;
            case MIB_IF_TYPE_PPP:
                printf("PPP\n");
                break;
            case MIB_IF_TYPE_LOOPBACK:
                printf("Lookback\n");
                break;
            case MIB_IF_TYPE_SLIP:
                printf("Slip\n");
                break;
            default:
                printf("Unknown type %ld\n", pAdapter->Type);
                break;
            }

            printf("\tIP Address: \t%s\n",
                   pAdapter->IpAddressList.IpAddress.String);
            printf("\tIP Mask: \t%s\n", pAdapter->IpAddressList.IpMask.String);

            printf("\tGateway: \t%s\n", pAdapter->GatewayList.IpAddress.String);
            printf("\t***\n");

            if (pAdapter->DhcpEnabled) {
                printf("\tDHCP Enabled: Yes\n");
                printf("\t  DHCP Server: \t%s\n",
                       pAdapter->DhcpServer.IpAddress.String);

                printf("\t  Lease Obtained: ");
                /* Display local time */
                error = _localtime32_s(&newtime, (__time32_t*) &pAdapter->LeaseObtained);
                if (error)
                    printf("Invalid Argument to _localtime32_s\n");
                else {
                    // Convert to an ASCII representation
                    error = asctime_s(buffer, 32, &newtime);
                    if (error)
                        printf("Invalid Argument to asctime_s\n");
                    else
                        /* asctime_s returns the string terminated by \n\0 */
                        printf("%s", buffer);
                }

                printf("\t  Lease Expires:  ");
                error = _localtime32_s(&newtime, (__time32_t*) &pAdapter->LeaseExpires);
                if (error)
                    printf("Invalid Argument to _localtime32_s\n");
                else {
                    // Convert to an ASCII representation
                    error = asctime_s(buffer, 32, &newtime);
                    if (error)
                        printf("Invalid Argument to asctime_s\n");
                    else
                        /* asctime_s returns the string terminated by \n\0 */
                        printf("%s", buffer);
                }
            } else
                printf("\tDHCP Enabled: No\n");

            if (pAdapter->HaveWins) {
                printf("\tHave Wins: Yes\n");
                printf("\t  Primary Wins Server:    %s\n",
                       pAdapter->PrimaryWinsServer.IpAddress.String);
                printf("\t  Secondary Wins Server:  %s\n",
                       pAdapter->SecondaryWinsServer.IpAddress.String);
            } else
                printf("\tHave Wins: No\n");
            pAdapter = pAdapter->Next;
            printf("\n");
        }
    } else {
        printf("GetAdaptersInfo failed with error: %d\n", dwRetVal);

    }
    if (pAdapterInfo)
        FREE(pAdapterInfo);

    return 0;

   
}

Friday, June 21, 2013

Build .Net application which works on multiple .net framework...

Step 1: Create a .net application and change the .Net Target framework to 3.5.
Step 2: In app.config file enter both .net framework 4.0 and 3.5 like below







Tuesday, February 14, 2012

UCHAR array ( or BYTE array ) to variant type

UCHAR szBuf[8];
szBuf50[0] = 0;
szBuf50[1] = 0;
szBuf50[2] = 0;
szBuf50[3] = 1;
szBuf50[4] = 0;
szBuf50[5] = 0;
szBuf50[6] = 3;
szBuf50[7] = 231;

VARIANT data;
SAFEARRAY * safeArray;
UCHAR *safeArrayData;
safeArray = SafeArrayCreateVector( VT_UI1, 0, 8 );

SafeArrayAccessData( safeArray, ( void ** ) &safeArrayData );
CopyMemory( safeArrayData, szBuf, 8 );
SafeArrayUnaccessData( safeArray );

VariantInit( &data );
data.vt = VT_ARRAY | VT_UI1;
data.parray = safeArray;
//after using the data delete it if no longer needed..
VariantClear( &data );

Friday, January 6, 2012

How ro run build.xml using ant

Step 1:

Install Ant ( or copy Ant folder to c: )

Step 2:

Install Java sdk

Then system user environmetal variable set the following environmental variable

ANT_HOME c:\Ant
JAVA_HOME C:\Program Files\Java\jdk1.6.0_27

in system environmental variable "Path" include this value as well C:\Ant\bin

Step 3:

Now in coomand prompt type Example => ant Install32

( Install32 is taget name in build.xml )

Thursday, December 1, 2011

Enumurating all names and values of registry key

HKEY hKey = NULL;
if( RegOpenKeyEx(HKEY_LOCAL_MACHINE,L"SOFTWARE\\Hewlett-Packard\\LaserJetService\\{488E28CB-3EAC-4EF3-8ACA-EE161849B618}",0,KEY_READ,&hKey) == ERROR_SUCCESS)
{

DWORD cSubKeys; // number of subkeys
DWORD cbMaxSubKey; // longest subkey size
DWORD cchMaxClass; // longest class string
DWORD cValues = 0; // number of values for key
DWORD cchMaxValue; // longest value name
DWORD cbMaxValueData; // longest value data
DWORD cbSecurityDescriptor; // size of security descriptor
FILETIME ftLastWriteTime; // last write time

DWORD j;
DWORD retValue;

// Get the class name and the value count.
retValue = RegQueryInfoKey(hKey, // key handle
NULL, // buffer for class name
NULL, // length of class string
NULL, // reserved
&cSubKeys, // number of subkeys
&cbMaxSubKey, // longest subkey size
&cchMaxClass, // longest class string
&cValues, // number of values for this key
&cchMaxValue, // longest value name
&cbMaxValueData, // longest value data
&cbSecurityDescriptor, // security descriptor
&ftLastWriteTime); // last write time

// Enumerate the child keys, until RegEnumKeyEx fails.

TCHAR *achValueName = new TCHAR[cchMaxValue+1];
if (!achValueName) return;

TCHAR *achValueData = new TCHAR[cbMaxValueData+1];
if (!achValueData)
{
delete [] achValueName;
return;
}


// Enumerate the key values.

if (cValues && cValues!=-1 && retValue==ERROR_SUCCESS)
{
for (j = 0, retValue = ERROR_SUCCESS; j < cValues; j++)
{
DWORD cchValueName = cchMaxValue + 1;
DWORD cchValueData = cbMaxValueData + 1;
DWORD dwType;

achValueName[0] = _T('\0');
achValueData[0] = _T('\0');

retValue = RegEnumValue(hKey, j, achValueName,
&cchValueName,
NULL,
&dwType,
(LPBYTE) achValueData,
&cchValueData);

if (retValue == ERROR_SUCCESS)
{
int n = 8;
}

}

} // end if (cValues && cValues!=-1)

if (achValueData)
delete [] achValueData;
if (achValueName)
delete [] achValueName;

RegCloseKey(hKey);
}

Friday, October 21, 2011

Convert UNICODE to ANSI...and UTF-8 to UNICODE

string sPath;

sPath = ConvertAnsiToUnicode(argv[0],_tcslen(argv[0]));

------------------------

string ConvertAnsiToUnicode(wchar_t *szString,int nSzie)
{
int cbMultiByte = ::WideCharToMultiByte(CP_UTF8, 0, szString, nSzie+1, NULL, 0,
NULL, NULL);

char* pMultiByteStr = NULL;
string result;

if (cbMultiByte > 0)

{

pMultiByteStr = new char[cbMultiByte];

cbMultiByte = ::WideCharToMultiByte(CP_UTF8, 0, szString, nSzie+1, pMultiByteStr,
cbMultiByte, NULL, NULL);

if (cbMultiByte > 0 && pMultiByteStr[cbMultiByte-1] == NULL)
{
cbMultiByte--;
}


if (cbMultiByte > 0)
{
result.assign(pMultiByteStr, cbMultiByte);
}

delete[] pMultiByteStr;

}

return result;
}
----------------------------------------------------------------------------------------------------------------

std::wstring CStringUtils::WStringFromChar(const char* pSource, int cchSource)
{
    std::wstring result;
    if (pSource != NULL)
    {
        if (cchSource == -1)
        {
            cchSource = (int)strlen(pSource) + 1;
        }
        int cchWideChar = ::MultiByteToWideChar(CP_UTF8, 0, pSource, cchSource, NULL, 0);
        if (cchWideChar > 0)
        {
            wchar_t* pWideCharStr = NULL;
            try
            {
                pWideCharStr = new wchar_t[cchWideChar];
                cchWideChar = ::MultiByteToWideChar(CP_UTF8, 0, pSource, cchSource, pWideCharStr, cchWideChar);
                if (cchWideChar > 0 && pWideCharStr[cchWideChar-1] == NULL)
                {
                    cchWideChar--;
                }
                if (cchWideChar > 0)
                {
                    result.assign(pWideCharStr, cchWideChar);
                }
            }
            catch (...)
            {
            }
            delete[] pWideCharStr;
        }
    }
    return result;
}

Monday, August 29, 2011

WinSock server..

#include "stdafx.h"
#include
#include

#include
#include


void ServerThread(void* pParam)
{
//A SOCKET is simply a typedef for an unsigned int.
//In Unix, socket handles were just about same as file
//handles which were again unsigned ints.
//Since this cannot be entirely true under Windows
//a new data type called SOCKET was defined.

FILE *pFile;
struct stat fileinfo;

SOCKET server;

//WSADATA is a struct that is filled up by the call
//to WSAStartup
WSADATA wsaData;

//The sockaddr_in specifies the address of the socket
//for TCP/IP sockets. Other protocols use similar structures.
sockaddr_in local;

//WSAStartup initializes the program for calling WinSock.
//The first parameter specifies the highest version of the
//WinSock specification, the program is allowed to use.
int wsaret=WSAStartup(0x101,&wsaData);

//WSAStartup returns zero on success.
//If it fails we exit.
if(wsaret!=0)
{
// return 0;
}

//Now we populate the sockaddr_in structure
local.sin_family=AF_INET; //Address family
local.sin_addr.s_addr = inet_addr("127.0.0.1"); // 16.182.218.213"); //16.182.218.240
local.sin_port = htons(631);

//the socket function creates our SOCKET
server=socket(AF_INET,SOCK_STREAM,0);

//If the socket() function fails we exit
if(server==INVALID_SOCKET)
{
// return 0;
}

//bind links the socket we just created with the sockaddr_in
//structure. Basically it connects the socket with
//the local address and a specified port.
//If it returns non-zero quit, as this indicates error
if(bind(server,(sockaddr*)&local,sizeof(local))!=0)
{
// return 0;
}

//listen instructs the socket to listen for incoming
//connections from clients. The second arg is the backlog
if(listen(server,10)!=0)
{
// return 0;
}

//we will need variables to hold the client socket.
//thus we declare them here.
SOCKET client;
sockaddr_in from;
int fromlen=sizeof(from);

while(true)//we are looping endlessly
{
char temp[4096];

client=accept(server,
(struct sockaddr*)&from,&fromlen);

int bytes = 0;
int h = 0;
do
{
bytes = 0;
memset(&temp,0,4096);
bytes = recv(client,temp,4096,0);
if (bytes<4096) break;


}while ( bytes > 0 );

char* szFileBuf= NULL;
bytes=0;
const char filename[] = "c:\\Result_PrintJob.txt";
FILE *file;
struct stat fileinfo;
if (filename != NULL)
{
if (stat(filename, &fileinfo))
{
return ;
}
if ((file = fopen(filename, "rb")) == NULL)
{
return ;
}

rewind(file);
szFileBuf = new char[(size_t)fileinfo.st_size];
bytes = fread(szFileBuf, 1, (size_t)fileinfo.st_size, file);

if (file)
fclose(file);
h = send(client,szFileBuf,bytes,0);

break;
}


// cout << "Connection from " << inet_ntoa(from.sin_addr) <<"\r\n";

//close the client socket
closesocket(client);

}

//closesocket() closes the socket and releases the socket descriptor
closesocket(server);

//originally this function probably had some use
//currently this is just for backward compatibility
//but it is safer to call it as I still believe some
//implementations use this to terminate use of WS2_32.DLL
WSACleanup();

// return 0;
}



int _tmain(int argc, _TCHAR* argv[])
{
int nRetCode = 0;

_beginthread( ServerThread, 0, NULL );

while(_getch()!=27);

return nRetCode;

}

Adding BGCOLOR to Menu

In OnInitDialog add this code..

CBrush* NewBrush;
NewBrush = new CBrush;
NewBrush->CreateSolidBrush(RGB(32,137,223)); //(143,197,239));
MENUINFO MenuInfo = {0};
MenuInfo.cbSize = sizeof(MenuInfo);
MenuInfo.hbrBack = *NewBrush; // Brush you want to draw
MenuInfo.fMask = MIM_BACKGROUND;
MenuInfo.dwStyle = MNS_AUTODISMISS;

CMenu menu;
menu.LoadMenu(IDR_MENU_FILE);
SetMenuInfo(menu.GetSafeHmenu(),&MenuInfo);
SetMenu(&menu);

Coloring Button BGCOLOR using MFC


Step 1:

Chnage Button Owner Draw propery to TRUE

Step 2:

Add WM_DRAWITEM message for the parent Dialog

And add this handler function..

void CStaticDataItem::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
if(nIDCtl==IDC_BTN_OK) //checking for the button
{
CDC dc;
RECT rect;
dc.Attach(lpDrawItemStruct ->hDC); // Get the Button DC to CDC

rect = lpDrawItemStruct->rcItem; //Store the Button rect to our local rect.

dc.Draw3dRect(&rect,RGB(255,255,255),RGB(0,0,0));// 32,137,223 100,200,155

dc.FillSolidRect(&rect,RGB(32,137,223));//Here you can define the required color to appear on the Button.

UINT state=lpDrawItemStruct->itemState; //This defines the state of the Push button either pressed or not.

if((state & ODS_SELECTED))
{
dc.DrawEdge(&rect,EDGE_SUNKEN,BF_RECT);

}
else
{
dc.DrawEdge(&rect,EDGE_RAISED,BF_RECT);
}

dc.SetBkColor(RGB(200,200,123)); //Setting the Text Background color
dc.SetTextColor(RGB(255,0,0)); //Setting the Text Color


TCHAR buffer[MAX_PATH]; //To store the Caption of the button.
ZeroMemory(buffer,MAX_PATH ); //Intializing the buffer to zero
::GetWindowText(lpDrawItemStruct->hwndItem,buffer,MAX_PATH); //Get the Caption of Button Window

dc.DrawText(buffer,&rect,DT_CENTER|DT_VCENTER|DT_SINGLELINE);//Redraw the Caption of Button Window

dc.Detach(); // Detach the Button DC
}

CDialog::OnDrawItem(nIDCtl, lpDrawItemStruct);
}

Friday, August 12, 2011

Uploading chunk data to server using winhttp

DWORD cbWritten=0,cbData=100;


////////////////////////////////
UCHAR* szFileBuf= NULL;
long bytes=0;
const char filename[] = "c:\\PrintJob.txt"; //IPP_Content.txt";
FILE *file;
struct stat fileinfo;
if (filename != NULL)
{
if (stat(filename, &fileinfo))
{
LPVOID lpMsgBuf;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(),
0, (LPTSTR) &lpMsgBuf, 0, NULL );

::MessageBox( NULL, (LPCTSTR)lpMsgBuf, L"dfsd", MB_OK | MB_ICONINFORMATION );
return ;
}
if ((file = fopen(filename, "rb")) == NULL)
{
return ;
}

rewind(file);
szFileBuf = new UCHAR[(size_t)fileinfo.st_size];
bytes = fread(szFileBuf, 1, (size_t)fileinfo.st_size, file);

if (bytes<=0) return ;

if (file)
fclose(file);
}




DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
BOOL bResults = FALSE;
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;

DWORD dwStatusCode = 0;
DWORD dwSupportedSchemes=0;
DWORD dwFirstScheme=0;
DWORD dwTarget=0;

hSession = WinHttpOpen( L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);

if (hSession)
hConnect = WinHttpConnect( hSession, L"16.182.218.240",
631, 0); //INTERNET_DEFAULT_HTTP_PORT


CString str;
str += L"Content-Type: application/ipp\r\n";
str += L"HOST: 16.182.218.240:631\r\n";
str += L"Transfer-Encoding: chunked\r\n";

if (hConnect)
hRequest = WinHttpOpenRequest( hConnect, L"POST",
L"ipp/printer",// cs1,//urlComp.lpszUrlPath,
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_REFRESH);



if (hRequest)
bResults = WinHttpSendRequest( hRequest, str, -1,WINHTTP_NO_REQUEST_DATA, 0,WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH, NULL);
// bResults = WinHttpSendRequest( hRequest, str, -1,(LPVOID)szFileBuf, bytes,bytes, 0);

int k = GetLastError();

if (!bResults)
{
LPVOID lpMsgBuf;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(),
0, (LPTSTR) &lpMsgBuf, 0, NULL );
::MessageBox( NULL, (LPCTSTR)lpMsgBuf, L"dfsd", MB_OK | MB_ICONINFORMATION );

}

char szHttpChunkHeaderA[32];
char szHttpChunkFooterA[] = "\r\n";
StringCchPrintfA(szHttpChunkHeaderA,ARRAYSIZE(szHttpChunkHeaderA),"%X\r\n",bytes );

cbWritten = 0;
bResults = WinHttpWriteData(hRequest, szHttpChunkHeaderA,(DWORD)( strlen(szHttpChunkHeaderA) * sizeof(char) ),&cbWritten );

if (!bResults)
{
LPVOID lpMsgBuf;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(),
0, (LPTSTR) &lpMsgBuf, 0, NULL );
::MessageBox( NULL, (LPCTSTR)lpMsgBuf, L"dfsd", MB_OK | MB_ICONINFORMATION );

}

cbWritten = 0;
bResults = WinHttpWriteData( hRequest, (LPVOID)szFileBuf, bytes, &cbWritten );


cbWritten = 0;
bResults = WinHttpWriteData(
hRequest,
szHttpChunkFooterA,
(DWORD)( strlen(szHttpChunkFooterA) * sizeof(char) ),
&cbWritten
);

if (!bResults)
{
LPVOID lpMsgBuf;
int y = GetLastError();
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(),
0, (LPTSTR) &lpMsgBuf, 0, NULL );
::MessageBox( NULL, (LPCTSTR)lpMsgBuf, L"dfsd", MB_OK | MB_ICONINFORMATION );

}
cbWritten = 0 ;
bResults = WinHttpWriteData( hRequest, "0\r\n",(DWORD)( strlen("0\r\n") * sizeof(char)), &cbWritten );


// bResults = WinHttpWriteData(hRequest,szHttpChunkFooterA,(DWORD)( strlen(szHttpChunkFooterA) * sizeof(char) ),&cbWritten );

if (!bResults)
{
LPVOID lpMsgBuf;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(),
0, (LPTSTR) &lpMsgBuf, 0, NULL );
::MessageBox( NULL, (LPCTSTR)lpMsgBuf, L"dfsd", MB_OK | MB_ICONINFORMATION );

}

cbWritten = 0;
bResults = WinHttpWriteData(
hRequest,
szHttpChunkFooterA,
(DWORD)( strlen(szHttpChunkFooterA) * sizeof(char) ),
&cbWritten
);
if( !bResults )
{
return;
}


// End the request.
if (bResults)
bResults = WinHttpReceiveResponse( hRequest, NULL);
CString respage=L""; // The buffer that'll contain the
// extracted Web page data


delete[] szFileBuf;

if (!bResults)
{
LPVOID lpMsgBuf;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(),
0, (LPTSTR) &lpMsgBuf, 0, NULL );
::MessageBox( NULL, (LPCTSTR)lpMsgBuf, L"dfsd", MB_OK | MB_ICONINFORMATION );

}


int h = GetLastError();

/* bResults = WinHttpQueryAuthSchemes( hRequest,
&dwSupportedSchemes,
&dwFirstScheme,
&dwTarget );*/





h = GetLastError();

if (bResults)
{
WCHAR *lpOutBuffer = NULL;
WinHttpQueryHeaders( hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF ,
WINHTTP_HEADER_NAME_BY_INDEX, NULL,
&dwSize, WINHTTP_NO_HEADER_INDEX);

int b =GetLastError( );

// Allocate memory for the buffer.
if( GetLastError( ) == ERROR_INSUFFICIENT_BUFFER )
{
lpOutBuffer = new WCHAR[dwSize/sizeof(WCHAR)];

// Now, use WinHttpQueryHeaders to retrieve the header.
bResults = WinHttpQueryHeaders( hRequest,
WINHTTP_QUERY_RAW_HEADERS_CRLF, // WINHTTP_QUERY_STATUS_CODE
WINHTTP_HEADER_NAME_BY_INDEX,
(LPVOID)lpOutBuffer, &dwSize,
WINHTTP_NO_HEADER_INDEX);

RetrieveHeader(lpOutBuffer,dwSize);

b =GetLastError( );
}

if (lpOutBuffer)
delete[] lpOutBuffer;
}



// Keep checking for data until there is nothing left.
if (bResults)
do
{

// Check for available data.
dwSize = 0;
if (!WinHttpQueryDataAvailable( hRequest, &dwSize))
printf("Error %u in WinHttpQueryDataAvailable.\n",
GetLastError());

// Allocate space for the buffer.
pszOutBuffer = new char[dwSize+1];
if (!pszOutBuffer)
{
printf("Out of memory\n");
dwSize=0;
}
else
{
// Read the Data.
ZeroMemory(pszOutBuffer, dwSize+1);

if (!WinHttpReadData( hRequest,
(LPVOID)pszOutBuffer,
dwSize, &dwDownloaded))
printf("Error %u in WinHttpReadData.\n",
GetLastError());
else
{
CString csData(pszOutBuffer);
respage += csData;
}

// Free the memory allocated to the buffer.
delete [] pszOutBuffer;
}

} while (dwSize>0);

AfxMessageBox(respage);

Tuesday, July 5, 2011

Multi Map sample ( STL )

Header files used

#include <map>
#include <string>
using namespace std;

multimap<string,string> mymm;
multimap<string,string>::iterator it;


mymm.insert(pair<string,string>("Name","Senthil"));
mymm.insert(pair<string,string>("Name","Senthil"));
mymm.insert(pair<string,string>("Name","Vel"));
mymm.insert(pair<string,string>("Name","Vel"));
mymm.insert(pair<string,string>("Name","Kumar"));
mymm.insert(pair<string,string>("Name","Senthil"));

for (it=mymm.equal_range("Name").first; it!=mymm.equal_range("Name").second; ++it)
cout << (*it).second;

Tuesday, March 22, 2011

Handling any type of exception...

Normally NULL pointer exception can not be handled by normal try..catch..

For that we need to use structured exception handling...

__try
{
int k = 6;
int g = add(3,7);
//int y = sum(3);
// struct A *a=NULL;

int j = fun(NULL);
int u = 0;
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION )
{
AfxMessageBox(L"senthil");
return;

}
}

Tuesday, August 18, 2009

Fast file download

URLDownloadToFile(NULL,L"http://www.piercemattie.com/blogs/car.bmp",L"d:\\ab.bmp",0,NULL);

Loading JPG images in Picture Control dynamically

1. Add header file add

#include

2. In the SampleDlg.h file add

CString m_csPath;

3. In the OnPaint function

void CSampleDlg::OnPaint()
{

CPaintDC dc(this); // device context for painting

CRect rect1;
CWnd *pWnd=NULL;
pWnd = GetDlgItem(IDC_STATIC_PIC);
if( NULL != pWnd && NULL != pWnd->GetSafeHwnd() )
{
pWnd->GetWindowRect( rect1 );
}

ScreenToClient( rect1 );

HDC hDC = dc.GetSafeHdc();
CImage img;
if( !m_csPath.IsEmpty() )
{
img.Load( m_csPath );
if( !img.IsNull() )
{

int nWidth1 = img.GetWidth();
int nHeight1 = img.GetHeight();

SetStretchBltMode(hDC, HALFTONE);
img.StretchBlt( hDC, rect1.left, rect1.top, rect1.Width(), rect1.Height(), 0, 0, nWidth1, nHeight1, SRCCOPY );

}
}

}

In the button click event

void CSampleDlg::OnBnClickedButton1()
{
TCHAR szFilters[]= _T("Image Files (*.bmp,*.jpg)|*.bmp;*.jpg|All Files (*.*)|*.*||");
CFileDialog objFileDialog( TRUE,0, 0,
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, szFilters);
CString csPath;

objFileDialog.m_ofn.lpstrTitle = _T("Select the image");

if( objFileDialog.DoModal() == IDOK)
{
m_csPath = objFileDialog.GetPathName();
if( !m_csPath.IsEmpty() )
{
CImage img;
img.Load( m_csPath );

if( !img.IsNull() )
{
//Invalidate();
CRect rect;
GetDlgItem( IDC_STATIC_PIC )->GetWindowRect( &rect );
ScreenToClient( rect );
InvalidateRect( rect, FALSE);
}
}
}
}

Friday, August 14, 2009

Downloading and writing binary file

Step1:

call GetFTPFile("http://www.speedace.info.jpg");

In the GetFTPFile function

void GetFTPFile(CString csPath)
{
CInternetSession csiSession;
DWORD dwServiceType = 0;
CString sServerName, sObject,csData;

INTERNET_PORT nPort; CString csTemp;

CString sGetFromURL; //( _T("") );

sGetFromURL =csQuery;

if ( !AfxParseURL ( sGetFromURL, dwServiceType, sServerName, sObject, nPort ) )
throw;

CHttpConnection* pHTTPServer = NULL;
pHTTPServer = csiSession.GetHttpConnection ( sServerName, nPort );
CHttpFile* pFile = NULL;
pFile = pHTTPServer->OpenRequest ( CHttpConnection::HTTP_VERB_GET, sObject, NULL, 1, NULL, NULL, INTERNET_FLAG_RELOAD );
pFile->SendRequest();
TCHAR sRaw [1024];
memset(sRaw,0,1024);
long lt = 0;
CFile fil;
CFileException fe;
int n = fil.Open("d:\\sen.jpg", CFile::modeWrite || CFile::typeBinary ,&fe );
while ( pFile->Read ( sRaw, 1024 ) )
{
fil.Write(sRaw,1024);
memset(sRaw,0,1024);
}

fil.Close();

pFile->Close();

pHTTPServer->Close();

}

Tuesday, August 11, 2009

Always dialog as top most window

In the dialog properties change system modal to TRUE

Round edged dialog

In dialog .h file

Add member variable

CRgn m_rgn;

In .cpp file in OnInitDialog function insert
this code after the line .....Dialog::OnInitDialog();
-------------------------------------------------------
CRect rect;
GetClientRect(rect);
m_rgn.CreateRoundRectRgn( rect.left, rect.top, rect.right, rect.bottom, 5,5);
SetWindowRgn((HRGN)m_rgn, TRUE);
--------------------------------------------------------

Friday, May 22, 2009

Datatype convertion

integer to TCHAR array
----------------
TCHAR szStatic[32];
wsprintf(szStatic,_T("%d min(s)"),dwValue);

integer to char array
----------------
char szStatic[32];
sprintf(szStatic,"%d min(s)",dwValue);


CString to char *
----------------
char *szPic=new char[csPic.GetLength()+1] ;
sprintf(szPic,"%S",csPic.GetBuffer(0));

char array to cstring
----------------
char strString[] = "this is a char string";
CString cstring;
cstring = CString( strString );

char array to STL string
---------------------
char buffer[] = "senthil";
string sValue;
sValue.assign((char*)buffer);

LPCSTR to LPCTSTR ( anscii to unicode conversion )
----------------------------------------
LPCSTR psz="senthil";
LPCTSTR m_ptsz=NULL;

const int size = MultiByteToWideChar(CP_ACP, 0, psz, -1, NULL, 0);

if (size == 0) {

ASSERT(!_T("Function \"MultiByteToWideChar\" failed."));
}
m_ptsz = new WCHAR [(sizeof(WCHAR)*size)];
VERIFY(MultiByteToWideChar(CP_ACP, 0, psz, -1, (LPWSTR)m_ptsz, size) != 0);
delete [] m_ptsz;
m_ptsz = NULL;

Dll creation

creation of win32 dll

step 1:
create a win32 project with the name Sampledll

step 2:
A Sampledll.cpp file will be created with Dllmain function
BOOL APIENTRY DllMain(HMODULE hModule,DWORD reason_for_call,LPVOID lpReserved )
{
return TRUE;
}

step 3:
create a .h file named Sampledll.h and expotable APIs and callback function

#ifdef VISUALIMITSINTERFACE_EXPORTS // in the project settings,c++ ->preprocessor we can find this macro
#define MY_DLL DLLEXPORT
#else
#define MY_DLL DLLIMPORT
#endif

typedef void (*fun2)(int, int);
extern "C" MY_DLL int fun1( int a , int b);
extern "C" MY_DLL int fun3(char* sz1,fun2 fpfun2);

step 4:

In the Sampledll.cpp , write exportable function defintions
extern "C" DLLEXPORT int fun1( int a , int b){... ..return n;}
extern "C" DLLEXPORT int fun3(char* sz1,fun2 fpfun2){....fpfun2(i,n); // callback function that used to call a function in Exe
}

step 5:
create a Exe application

Include the file Sampledll.h

Instead of .. extern "C" MY_DLL int fun1( int a , int b);
, we can add the following lines
typedef void (*pfnfun2)(int, int); // callback function
typedef int (*pfnfun1)(char* ,char* );typedef int (*pfnfun3)(char*,pfnfun2);

step 6:

In the SampleDlg.h file declare this

pfnfun1 fun1;
pfnfun3 fun3;

step 7:

In the SampleDlg.cpp file add this callback function

void SampleCallBack(int n, int y)
{
return;
}

In a function call this API to set callback function for the dll

void CVisuaLimitsServerDlg::OnBnClickedBtnTransfer()
{
fun3(szResult,&SampleCallBack);
}

Using Loadlibrary we can load the dll

m_hInstance = LoadLibrary(L"Sampledll.dll");

if (m_hInstance)
{
fun1 = (pfnfun1) GetProcAddress (m_hInstance, "fun1");
fun3 = (pfnfun3) GetProcAddress (m_hInstance, "fun3");
}

Wednesday, November 12, 2008

Timers

SetTimer Function

The SetTimer function creates a timer with the specified time-out value.


This is a small example that will explain you how to use timer function in vc++
Step 1: Create a sample MFC project.
Step 2: create a member variable in the dialog class .h file
Example, UINT m_nTimerID;
Step 3: In the constructor initialize the timer variable
m_nTimerID = 0;
Step 4: In the OnInitDialog function call settimer function
SetTimer(m_nTimerID, 5000, NULL);
Step 5: Write a handler for WM_TIMER message and write your code..
Example , AfxMessageBox(L"Hai");
Step 6: Create a button that will kill the timer
KillTimer(m_nTimerID);

Now when the application is launched , once in 5 seconds the message window "Hai" will appear .
If you want to stop the timer then call killTimer to kill the timer.