Onega

a lot of VC++ posts, a few C# posts, and some miscellaneous stuff

Thursday, July 14, 2005

custom sort for std::set and CArray

// set_test.cpp : Test customized sort function for a set

#include "stdafx.h"
#pragma warning(disable:4786)
#include <set>
#include <iostream>
class bb
{
public:
    bb(int i)
    {
        m_i = i;
    }
    ~bb()
    {
        
    }
    bool operator<(const bb& abb) const
    {
        return m_i<abb.m_i;
    }
    void seti(int i)
    {
        m_i = i;
    }
    int geti()
    {
        return m_i;
    }
private:
    int m_i;
    
};
struct compare_bb
{
//welcome to www.fruitfruit.com 
    // VC6(SP6)
    bool operator()(const bb* a, const bb* b) 
    {
        if(!a)
            return false;
        if(!b)
            return true;
        return a->operator<(*b);
    }
};
int main(int argc, char* argv[])
{
    typedef std::set<bb*,compare_bb> BBSet;
    BBSet bcol;
    bcol.insert(new bb(3));
    bcol.insert(new bb(1));
    bcol.insert(new bb(2));
    for(BBSet::iterator it = bcol.begin();
        it!= bcol.end();
        it++)
            std::cout<<(*it)->geti()<<std::endl;
    return 0;
}

// sort_carray.cpp : Defines the entry point for the console application.

//


#include "stdafx.h"
#include "sort_carray.h"
#include <afxtempl.h>
#include <string>
#include <sstream>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

using namespace std;
struct MyData
{
    MyData():m_data1(0),m_data2(-1){
    }
    MyData(int a, double b):m_data1(a),m_data2(b){
    }
    int m_data1;
    double m_data2;
    std::string to_string()
    {
        std::stringstream ss;
        ss<<"{"<<m_data1<<","<<m_data2<<"}"<<std::endl;
        return ss.str();
    }
};

int bydouble(const void * v1, const void * v2)
{
    MyData data1 = *(MyData *)v1;
    MyData data2 = *(MyData *)v2;
    return data1.m_data2 - data2.m_data2;
} // byname1
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;

    // initialize MFC and print and error on failure
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    {
        // TODO: change error code to suit your needs
        cerr << _T("Fatal Error: MFC initialization failed") << endl;
        nRetCode = 1;
    }
    else
    {
        CArray<MyData,MyData> myarray;
        myarray.Add(MyData(1,1.2));
        myarray.Add(MyData(2,0.2));
        myarray.Add(MyData(2,5.2));
        for(int i=0;i<myarray.GetSize();i++)
        {
            MyData tmp = myarray.GetAt(i);
            std::cout<<tmp.to_string()<<std::endl;
        }
        qsort(myarray.GetData(),myarray.GetSize(),sizeof(MyData),bydouble);
        std::cout<<"after sort"<<std::endl;
        for( i=0;i<myarray.GetSize();i++)
        {
            MyData tmp = myarray.GetAt(i);
            std::cout<<tmp.to_string()<<std::endl;
        }
    }

    return nRetCode;
}

Tuesday, July 12, 2005

get affected record count via ODBC and ADO

rc = ::SQLExecDirect(sql_stmt,(SQLCHAR*)(const

char*)sqlcmds,strlen(sqlcmds));

SQLLEN rowcount = 0;

rc = ::SQLRowCount(sql_stmt,&rowcount);



_bstr_t bstrEmpty;

Conn1.CreateInstance( __uuidof( ADODB::Connection ) );

Conn1->ConnectionString = bstrConnect;

Conn1->Open( bstrConnect, bstrEmpty, bstrEmpty, -1 );

_variant_t records_affected;

Conn1->Execute((LPCTSTR)sqlcmds,&records_affected,0);//VT_I4,lVal

Monday, July 11, 2005

wmi start stop service

#define _WIN32_DCOM

#include <Wbemidl.h>

#pragma comment(lib,"Wbemuuid.lib")

#include <atlbase.h>

#include "objbase.h"

#include <windows.h>

#include <comutil.h>

#pragma comment(lib, "comsupp.lib")

#include <iostream>







int main()

{   //start/stop service on windows 2000 Professional SP4, VC6 SP6 by

Onega

       CComBSTR path = ("root\\cimv2");

       CComBSTR InstancePath =("Win32_Service.Name='Spooler'");



       HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);

       if(SUCCEEDED(hr))

               hr = CoInitializeSecurity(NULL, -1, NULL, NULL,

       RPC_C_AUTHN_LEVEL_CONNECT,

       RPC_C_IMP_LEVEL_IMPERSONATE,

       NULL, EOAC_NONE, 0

       );



       {

               CComPtr<IWbemLocator> spLoc;

               //      hr = spLoc.CoCreateInstance(CLSID_WbemLocator);

               if(SUCCEEDED(hr))

                       hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER,

           IID_IWbemLocator, (LPVOID *) &spLoc);

               CComBSTR bstrNamespace("\\\\.\\root\\CIMV2");

               CComPtr<IWbemServices> spServices;

               if(SUCCEEDED(hr))

                       hr = spLoc->ConnectServer(bstrNamespace, NULL, NULL, 0,

                       NULL, 0, 0, &spServices);

               IWbemServices *pNamespace = spServices;

               if(SUCCEEDED(hr))

                       hr = CoSetProxyBlanket(spServices, RPC_C_AUTHN_DEFAULT,

                       RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,

                       RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);

               {

                       CComBSTR ClassPath = ("Win32_Service");

                       CComBSTR MethodName = "StopService";

                       _variant_t varProperty;

                       CComBSTR bstrPropName = "state";

                       CComPtr<IWbemClassObject> spInstance;

                       hr = pNamespace->GetObject(InstancePath,0,NULL,&spInstance,NULL);

                       hr = spInstance->Get(bstrPropName,0,&varProperty,NULL,0);

                       if( VT_BSTR == varProperty.vt &&

                               _wcsicmp(varProperty.bstrVal, L"Stopped") == 0)

                       {

                               MethodName = "StartService";

                       }

                       CComPtr<IWbemClassObject>  pClass ;

                       CComPtr<IWbemClassObject>  pOutInst;

                       CComPtr<IWbemClassObject>  pInClass;

                       CComPtr<IWbemClassObject>  pInInst;

                       CComPtr<IWbemClassObject>  pOutClass;

                       if(SUCCEEDED(hr))

                               hr = pNamespace->GetObject(ClassPath, 0, NULL,

                               &pClass, NULL);



                       if(SUCCEEDED(hr))

                               hr = pClass->GetMethod(MethodName, 0, &pInClass, &pOutClass);

                       if(SUCCEEDED(hr) && pInClass)

                               hr = pInClass->SpawnInstance(0, &pInInst);

                       CComBSTR return_value_name = "ReturnValue";

                       if(SUCCEEDED(hr))

                               hr = pNamespace->ExecMethod(InstancePath, MethodName,

                               0, NULL, pInInst,&pOutInst, NULL);

                       _variant_t ret_value;

                       hr = pOutInst->Get(return_value_name, 0, &ret_value, 0, 0);

                       std::wcout<<L"Execute "<<(LPCWSTR)MethodName<<L" return "

                               <<(long)ret_value<<std::endl;



               }

       }

       std::cout<< "finished "<<std::endl;

       CoUninitialize();

       return ERROR_SUCCESS;

}

list and add contacts of outlook via VC

#include <iostream>

#include <tchar.h>



#import "G:\Program Files\Microsoft Office\OFFICE11\MSOUTL.OLB"

named_guids, raw_interfaces_only

#include <comdef.h>

#include <atlcomcli.h>

#include <comutil.h>

#pragma comment(lib,"comsupp.lib")

#include <iomanip>

struct InitOle {

       InitOle()  { ::CoInitialize(NULL); }

       ~InitOle() { ::CoUninitialize();   }

} _init_InitOle_;

HRESULT create_contact(LPDISPATCH pDisp,LPCTSTR name)

{

       HRESULT hr = S_OK;

       Outlook::_ContactItemPtr pContact;

       if(pDisp)

               hr =

pDisp->QueryInterface(__uuidof(Outlook::_ContactItem),(LPVOID*)&pConta

ct);

       if(pContact)

       {

               hr = pContact->put_LastName(_bstr_t(name));

               SYSTEMTIME st;

               st.wYear = 1980;

               st.wMonth = 1;

               st.wDay = 1;

               st.wHour = 1;

               st.wMinute = 1;

               st.wSecond = 1;

               st.wMilliseconds = 0;

               DATE dt;

               SystemTimeToVariantTime(&st,&dt);

               hr = pContact->put_Birthday(dt);

               hr = pContact->Save();

       }

       return hr;

}

int _tmain(int argc, _TCHAR* argv[])

{

       //Attach to the running instance...

       HRESULT hr = S_OK;

       CLSID clsid;

       LPCTSTR app_progid = _T("Outlook.Application");

       CLSIDFromProgID(_bstr_t(app_progid), &clsid);

       CComPtr<IUnknown> pUnk = NULL;

       Outlook::_ApplicationPtr pApp;



       for(int i=1;i<=5;i++) //try attaching for up to 5 attempts

       {

               HRESULT hr = GetActiveObject(clsid, NULL, (IUnknown**)&pUnk);

               if(SUCCEEDED(hr))

               {

                       pUnk->QueryInterface(__uuidof(Outlook::_Application),(void**)&pApp)

;

                       break;

               }

               ::Sleep(1000);

       }

       if(NULL == pApp)

               pApp.CreateInstance(app_progid);

       _variant_t  vtEmpty (DISP_E_PARAMNOTFOUND, VT_ERROR);



       Outlook::_NameSpacePtr pNameSpace;

       if(pApp)

       {

               pApp->GetNamespace(_bstr_t("MAPI"),&pNameSpace);

       }

       if(pNameSpace)

               pNameSpace->Logon(vtEmpty, vtEmpty, vtEmpty, vtEmpty);

       Outlook::MAPIFolderPtr pFolder;

       if(pNameSpace)

       pNameSpace->GetDefaultFolder(Outlook::olFolderContacts,&pFolder);

       long item_count = 0;

       Outlook::_ItemsPtr pItems;

       if(pFolder)

               pFolder->get_Items(&pItems);

       if(pItems)

       pItems->get_Count(&item_count);

       for(long index = 1; index <= item_count; index++)

       {

               CComPtr<IDispatch> pDisp = NULL;



               pItems->Item(_variant_t(index), (LPDISPATCH*)&pDisp);

               Outlook::_ContactItemPtr pContact;

               pDisp->QueryInterface(__uuidof(Outlook::_ContactItem),(LPVOID*)&pCon

tact);



               if(pContact)

               {

                       _bstr_t bsname;

                       pContact->get_LastName(bsname.GetAddress());

                       std::cout<<"contact ["<<index<<"]";

                       if(bsname.length())

                       std::cout<<(LPCTSTR)bsname<<" ";

                       DATE dt = 0;

                       HRESULT hr = pContact->get_Birthday(&dt);

                       if(SUCCEEDED(hr))

                       {

                               SYSTEMTIME st;

                               VariantTimeToSystemTime(dt,&st);

                               std::cout<<" birthday:"<<

st.wYear<<"/"<<std::setw(2)<<std::setfill('0')<<st.wMonth<<"/"

                                       <<std::setw(2)<<std::setfill('0')<<st.wDay;

                       }

                       std::cout<<std::endl;

               }

       }

       //create contact in outlook2003 via VC2003 by Onega

       if(pItems)

       {

               CComPtr<IDispatch> pDisp;

               hr =

pItems->Add(_variant_t((long)Outlook::olContactItem,VT_I4),&pDisp);

               hr = create_contact(pDisp,"by Items");

       }

       if(pApp)

       {

               CComPtr<IDispatch> pDisp;

               hr = pApp->CreateItem(( Outlook::olContactItem),&pDisp);

               hr = create_contact(pDisp,"by app");

       }

       system("pause");

       return 0;

}


wmi enum all cddrive and dump properties

//The following can run on windows 2000 professional when login as

guest

#define _WIN32_DCOM

#include <Wbemidl.h>

#pragma comment(lib,"Wbemuuid.lib")

#include <atlbase.h>

#include "objbase.h"

#include <windows.h>

#include <comutil.h>

#pragma comment(lib, "comsupp.lib")

#include <iostream>



void print_property(CComBSTR bstrPropName, _variant_t& varProperty)

{

                       std::cout<<"  "<<(LPCTSTR)_bstr_t(bstrPropName);

               std::cout<<" = ";



               if(varProperty.vt !=VT_EMPTY && VT_NULL != varProperty.vt)

               {

                       _variant_t vDest;

                       HRESULT hr = VariantChangeType(&vDest, &varProperty,0,VT_BSTR);

                       if(SUCCEEDED(hr))

                               std::cout<< (LPCTSTR)_bstr_t(varProperty);

                       else

                       {

                               if(varProperty.vt == (VT_ARRAY | VT_I4) )

                               {

                                       SAFEARRAY* psa = varProperty.parray;

                                       int *pIntArray = NULL;

                                       SafeArrayAccessData(psa,(VOID**)&pIntArray);

                                       UINT uDim = SafeArrayGetDim(psa);

                                       if(1==uDim)

                                       {

                                               long lLbound,lRbound;

                                               SafeArrayGetLBound(psa,1,&lLbound);

                                               SafeArrayGetUBound(psa,1,&lRbound);

                                               for(long i=lLbound;i<=lRbound;i++)

                                               {

                                                       std::cout<< pIntArray[i]<<" ";

                                               }

                                       }

                                       SafeArrayUnaccessData(psa);

                               }

                               else

                               {

                                       std::cout<< varProperty.vt << " type ";

                               }

                       }

               }

               else

               {

                       if(varProperty.vt == VT_EMPTY)

                               std::cout<< "VT_EMPTY ";

                       else

                               std::cout<< "VT_NULL";

               }

               std::cout<<std::endl;

}



HRESULT PrintObject(IWbemClassObject* spInstance)

{

//      std::cout<<__FUNCTION__<<" start "<<std::endl;

       LPSAFEARRAY psa = NULL;

       HRESULT hres;

       hres = spInstance->GetNames(   NULL,

               WBEM_FLAG_ALWAYS | WBEM_FLAG_NONSYSTEM_ONLY,

               NULL,

               &psa);

       long   lLower, lUpper;

       SafeArrayGetLBound(psa , 1, &lLower);

       SafeArrayGetUBound(psa , 1, &lUpper);

       for (long i = lLower; i <= lUpper; ++i)

       {

               CComBSTR   bstrPropName;

               if (S_OK !=  (hres = SafeArrayGetElement(psa, &i, &bstrPropName)) )

               {

                       if (NULL != psa)

                               SafeArrayDestroy(psa);

                       return hres;

               }

               _variant_t varProperty;

               HRESULT hr = spInstance->Get(bstrPropName,0,&varProperty,NULL,0);

               print_property(bstrPropName,varProperty);

       }

       if (NULL != psa)

               SafeArrayDestroy(psa);

//      std::cout<<__FUNCTION__<<" end "<<std::endl;

       return S_OK;

}

main()

{

       CoInitialize(NULL);

       {

       HRESULT hr = S_OK;

       CComPtr<IWbemLocator> spLoc;

       hr = spLoc.CoCreateInstance(CLSID_WbemLocator);

       CComBSTR bstrNamespace("\\\\.\\root\\CIMV2");

       CComPtr<IWbemServices> spServices;

       hr = spLoc->ConnectServer(bstrNamespace, NULL, NULL, 0,

               NULL, 0, 0, &spServices);

       hr = CoSetProxyBlanket(spServices, RPC_C_AUTHN_DEFAULT,

               RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,

               RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);

               {

                       CComPtr<IEnumWbemClassObject> spEnumInst;

                       hr = spServices->CreateInstanceEnum(CComBSTR("Win32_CDROMDrive"),

                               WBEM_FLAG_SHALLOW, NULL, &spEnumInst);

                       bool bFinished = false;

                       while (!bFinished)

                       {

                               ULONG uNumOfInstances = 0;

                               CComPtr<IWbemClassObject> spInstance;

                               HRESULT hrNext = spEnumInst->Next(10000, 1, &spInstance,

                                       &uNumOfInstances);

                               if (hrNext == WBEM_S_FALSE)

                                       bFinished = true;

                               else if (hrNext == WBEM_S_NO_ERROR)

                               {

                                       CComBSTR bstrPropName = "Drive";

                                       _variant_t varProperty;

                                       hr = spInstance->Get(bstrPropName,0,&varProperty,NULL,0);

                                       print_property(bstrPropName,varProperty);

                                       if(SUCCEEDED(hr) && VT_BSTR == varProperty.vt)

                                       {

                                               _bstr_t bsdrive = varProperty;

                                               bstrPropName = "Caption";

                                               hr = spInstance->Get(bstrPropName,0,&varProperty,NULL,0);

                                               if(SUCCEEDED(hr) && VT_BSTR == varProperty.vt)

                                               {



                                               }

                                               print_property(bstrPropName,varProperty);



                                       }

                               }

                       }

               }

       }



       std::cout<< "finished "<<std::endl;

       CoUninitialize();

}

enum resource of a process -- does not work

// resource_dump.cpp : this is expected to work, but it does not.

//



#include "stdafx.h"

//#pragma warning(disable:4786)

//#include <windows.h>

//#include <strsafe.h>

//#include <iostream>

//#include <psapi.h>

//#pragma comment(lib,"psapi.lib")

//#include <string>

//#include <algorithm>

//#include <map>

char szBuffer[80]; // print buffer for EnumResourceTypes

DWORD cbWritten;   // number of bytes written to res. info. file

size_t cbString;      // length of string in sprintf

HRESULT hResult;

HANDLE hFile;

LPCTSTR line_return = ("\n");

class HandleWrapper

{

public:

       HandleWrapper(HANDLE h):m_handle(h){

       }

       ~HandleWrapper()

       {

               if(NULL != m_handle)

                       CloseHandle(m_handle);

       }

       HANDLE Detach()

       {

               HANDLE h = m_handle;

               m_handle = NULL;

               return h;

       }

private:

       HANDLE m_handle;

};



void ErrorHandler(LPCTSTR msg)

{

       std::cout<<msg<<std::endl;

}

HANDLE get_process_handle(DWORD processID)

{

               HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |

                       PROCESS_VM_READ,

                       FALSE, processID );

       return hProcess;

}



bool res_type_to_str(LPTSTR szBuffer,int sizeofbuf,DWORD res_type)

{

       //return true if the type is known,

       //return false if the type is unknown

       std::map<USHORT,std::string> res_type_name;

       res_type_name[(USHORT)RT_CURSOR] = "RT_CURSOR";

       res_type_name[(USHORT)RT_BITMAP] = "RT_BITMAP";

       res_type_name[(USHORT)RT_ICON] = "RT_ICON";

       res_type_name[(USHORT)RT_MENU] = "RT_MENU";

       res_type_name[(USHORT)RT_DIALOG] = "RT_DIALOG";

       res_type_name[(USHORT)RT_STRING] = "RT_STRING";

       res_type_name[(USHORT)RT_FONTDIR] = "RT_FONTDIR";

       res_type_name[(USHORT)RT_FONT] = "RT_FONT";

       res_type_name[(USHORT)RT_ACCELERATOR] = "RT_ACCELERATOR";

       res_type_name[(USHORT)RT_RCDATA] = "RT_RCDATA";

       res_type_name[(USHORT)RT_MESSAGETABLE] = "RT_MESSAGETABLE";

       res_type_name[(USHORT)RT_VERSION] = "RT_VERSION";

       res_type_name[(USHORT)RT_DLGINCLUDE] = "RT_DLGINCLUDE";

       res_type_name[(USHORT)RT_MANIFEST] = "RT_MANIFEST";

       res_type_name[(USHORT)RT_HTML] = "RT_HTML";

       res_type_name[(USHORT)RT_ANIICON] = "RT_ANIICON";

       res_type_name[(USHORT)RT_ANICURSOR] = "RT_ANICURSOR";

       res_type_name[(USHORT)RT_VXD] = "RT_VXD";

       res_type_name[(USHORT)RT_PLUGPLAY] = "RT_PLUGPLAY";

       if(res_type_name.find(res_type)!=res_type_name.end())

       {

               hResult = StringCchPrintf(szBuffer, sizeofbuf, "Type: %s\n",

                       res_type_name[(USHORT)res_type].c_str());

               return true;

       }

       return false;

}

//    FUNCTION: EnumLangsFunc(HANDLE, LPSTR, LPSTR, WORD, LONG)

//

//    PURPOSE:  Resource language callback

BOOL EnumLangsFunc(

   HANDLE hModule,  // module handle

   LPCTSTR lpType,  // address of resource type

   LPCTSTR lpName,  // address of resource name

   WORD wLang,      // resource language

   LONG lParam)     // extra parameter, could be

                    // used for error checking

{

   HANDLE hResInfo;

   char szBuffer[80];

   size_t cbString = 0;

       HRESULT hResult;



   hResInfo = FindResourceEx((HMODULE)hModule, lpType, lpName,

wLang);

   // Write the resource language to the resource information file.

       hResult = StringCchPrintf(szBuffer, 80/sizeof(TCHAR),

               "\t\tLanguage: %u\n", (USHORT) wLang);

               if (FAILED(hResult))

               {

               // Add code to fail as securely as possible.

                       return FALSE;

               }

               hResult = StringCchLength(szBuffer, 80/sizeof(TCHAR), &cbString);

       if (FAILED(hResult))

               {

               // Add code to fail as securely as possible.

                       return FALSE;

               }

   WriteFile(hFile, szBuffer, (DWORD) cbString,

       &cbWritten, NULL);

   // Write the resource handle and size to buffer.

   cbString = StringCchPrintf(szBuffer,

               sizeof(szBuffer)/sizeof(szBuffer[0]),

       "\t\thResInfo == %lx,  Size == %lu\n\n",

       hResInfo,

       SizeofResource((HMODULE)hModule, (HRSRC)hResInfo));

   WriteFile(hFile, szBuffer, (DWORD) cbString,

       &cbWritten, NULL);

   return TRUE;

}

//    FUNCTION: EnumNamesFunc(HANDLE, LPSTR, LPSTR, LONG)

//

//    PURPOSE:  Resource name callback

BOOL EnumNamesFunc(

   HANDLE hModule,   // module handle

   LPCTSTR lpType,   // address of resource type

   LPTSTR lpName,    // address of resource name

   LONG lParam)      // extra parameter, could be

                     // used for error checking

{

   size_t cbString;

       HRESULT hResult;



    // Write the resource name to a resource information file.

    // The name may be a string or an unsigned decimal

    // integer, so test before printing.

   if ((ULONG)lpName & 0xFFFF0000)

   {

               hResult = StringCchPrintf(szBuffer, 80/sizeof(TCHAR),

                       "\tName: %s\n", lpName);

               if (FAILED(hResult))

               {

               // Add code to fail as securely as possible.

                       return FALSE;

               }

   }

   else

   {

               hResult = StringCchPrintf(szBuffer, 80/sizeof(TCHAR),

                       "\tName: %u\n", (USHORT)lpName);

               if (FAILED(hResult))

               {

               // Add code to fail as securely as possible.

                       return FALSE;

               }

   }

       hResult = StringCchLength(szBuffer, 80/sizeof(TCHAR), &cbString);

       if (FAILED(hResult))

               {

               // Add code to fail as securely as possible.

                       return FALSE;

               }



   WriteFile(hFile, szBuffer, (DWORD) cbString,

       &cbWritten, NULL);

    // Find the languages of all resources of type

    // lpType and name lpName.

   EnumResourceLanguages((HMODULE)hModule,

       lpType,

       lpName,

       (ENUMRESLANGPROC)EnumLangsFunc,

       0);



   return TRUE;

}





//    FUNCTION: EnumTypesFunc(HANDLE, LPSTR, LONG)

//

//    PURPOSE:  Resource type callback

BOOL EnumTypesFunc(

   HANDLE hModule,   // module handle

   LPTSTR lpType,    // address of resource type

   LONG lParam)      // extra parameter, could be

                     // used for error checking

{

   size_t cbString;

       HRESULT hResult;



   // Write the resource type to a resource information file.

   // The type may be a string or an unsigned decimal

   // integer, so test before printing.

   if ((ULONG)lpType & 0xFFFF0000)

   {

               long res_type = atoi(lpType);

               if(res_type_to_str(szBuffer,80/sizeof(TCHAR),res_type) == false)

               hResult = StringCchPrintf(szBuffer, 80/sizeof(TCHAR),

               "Type: %s\n", lpType);

               if (FAILED(hResult))

               {

               // Add code to fail as securely as possible.

                       return FALSE;

               }

   }

   else

   {

               if(res_type_to_str(szBuffer,80/sizeof(TCHAR),(USHORT)lpType) ==

false)

                       hResult = StringCchPrintf(szBuffer, 80/sizeof(TCHAR),

                                               "Type: %u\n", (USHORT)lpType);

               if (FAILED(hResult))

               {

               // Add code to fail as securely as possible.

                       return FALSE;

               }

   }

 hResult = StringCchLength(szBuffer, 80/sizeof(TCHAR), &cbString);

       if (FAILED(hResult))

               {

               // Add code to fail as securely as possible.

                       return FALSE;

               }

   WriteFile(hFile, szBuffer, (DWORD) cbString,

       &cbWritten, NULL);

   // Find the names of all resources of type lpType.

   EnumResourceNames((HMODULE)hModule,

       lpType,

       (ENUMRESNAMEPROC)EnumNamesFunc,

       0);



   return TRUE;

}



DWORD get_process_id(LPCTSTR process_name)

{

       DWORD ret = -1;

   DWORD aProcesses[1024], cbNeeded = 0, cProcesses = 0;

   unsigned int i = 0;

   if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )

       return ret;

       std::string key = process_name;

       std::transform(key.begin(), key.end(), key.begin(),

              (int(*)(int)) toupper);

   cProcesses = cbNeeded / sizeof(DWORD);

   for ( i = 0; i < cProcesses; i++ )

       {

               DWORD processID = aProcesses[i];

               char szProcessName[MAX_PATH] = "<unknown>";

               HANDLE hProcess = get_process_handle( processID );

               HandleWrapper proce_obj(hProcess);

               if (NULL != hProcess )

               {

                       HMODULE hMod;

                       DWORD cbNeeded;

                       if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),

                               &cbNeeded) )

                       {

                               GetModuleBaseName( hProcess, hMod, szProcessName,

                                       sizeof(szProcessName) );

                       }

               }

               std::transform(szProcessName, szProcessName+sizeof(szProcessName),

                       szProcessName,

              (int(*)(int)) toupper);

               if(strstr(szProcessName,key.c_str()))

                       return processID;

       }

       return ret;

}

void dump_res(LPCTSTR process_name)

{

       //dump resource of a process

       if(NULL == process_name || '\0' == process_name[0])

               return;

       HANDLE hExe = get_process_handle(get_process_id(process_name));

       if (hExe == NULL)

       {

               ErrorHandler("Failed to find the process");

               return;

       }

       // Create a file to contain the resource info.

       hFile = CreateFile("resinfo.txt",      // name of file

               GENERIC_READ | GENERIC_WRITE,      // access mode

               0,                                 // share mode

               (LPSECURITY_ATTRIBUTES) NULL,      // default security

               CREATE_ALWAYS,                     // create flags

               FILE_ATTRIBUTE_NORMAL,             // file attributes

               (HANDLE) NULL);                    // no template

       if (hFile == INVALID_HANDLE_VALUE) {

               ErrorHandler("Could not open file.");

       }

       HandleWrapper file_handle_obj(hFile);

       hResult = StringCchPrintf(szBuffer, 80/sizeof(TCHAR),

               "The file contains the following resources:\n\n");

       if (FAILED(hResult))

       {

               // Add code to fail as securely as possible.

               return;

       }

       hResult = StringCchLength(szBuffer, 80/sizeof(TCHAR), &cbString);

       if (FAILED(hResult))

       {

               // Add code to fail as securely as possible.

               return;

       }

       WriteFile(hFile,           // file to hold resource info.

               szBuffer,              // what to write to the file

               (DWORD) cbString,      // number of bytes in szBuffer

               &cbWritten,            // number of bytes written

               NULL);                 // no overlapped I/O



   HMODULE hMods[1024];

   DWORD cbNeeded = 0;

       unsigned int i = 0;

   if( EnumProcessModules(hExe, hMods, sizeof(hMods), &cbNeeded))

   {

       for ( i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ )

       {

           char szModName[MAX_PATH];

                               DWORD dwcount = 0;

           // Get the full path to the module's file.

           if ( GetModuleFileNameEx( hExe, hMods[i], szModName,

                                     sizeof(szModName)))

           {

               // Print the module name and handle value.

               printf("\t%s (0x%08X)\n", szModName, hMods[i] );

                               WriteFile(hFile,szModName,strlen(szModName),&dwcount,NULL);

                               WriteFile(hFile,line_return,strlen(line_return),&dwcount,

                                       NULL);

           }

                       SetErrorMode(SEM_FAILCRITICALERRORS);SEM_NOOPENFILEERRORBOX;

                       HMODULE hDllModule =

LoadLibraryEx(szModName,NULL,LOAD_LIBRARY_AS_DATAFILE);

                       SetErrorMode(0);

                       if(hDllModule)

                       {

                               EnumResourceTypes(hDllModule,              // module handle

                                       (ENUMRESTYPEPROC)EnumTypesFunc,  // callback function

                                       0);

                               FreeLibrary(hDllModule);// extra parameter

                       }

                       else

                       {

                               LPCTSTR load_failed = "failed to load the file\n";

                               WriteFile(hFile,load_failed,strlen(load_failed),&dwcount,

                                       NULL);

                       }

       }

   }

}

int main(int argc, char* argv[])

{

       printf("Dump resource of a process!\n");

       dump_res("uedit32.exe");

       system("pause");

       return 0;

}

SQLServer extended stored proc access ASP

#include "stdafx.h"

#define DBNTWIN32

#include <windows.h>

//G:\Program Files\Microsoft SQL

Server\80\Tools\DevTools\Include\sqlfront.h

#include <sqlfront.h>

#include <sqldb.h>

#include <srv.h>

#include <sstream>

#include <UrlMon.h>

#pragma comment(lib,"urlmon.lib")

#define XP_NOERROR                      0

#define XP_ERROR                        1

#define MAX_BINDTOKEN                   256

#define MAX_SERVER_ERROR 20000

#define XP_HELLO_ERROR MAX_SERVER_ERROR+1

//G:\Program Files\Microsoft SQL

Server\80\Tools\DevTools\Lib\opends60.lib

//G:\Program Files\Microsoft SQL

Server\80\Tools\DevTools\Lib\ntwdblib.lib

#pragma comment(lib,"opends60.lib")

#pragma comment(lib,"Ntwdblib.lib")

//need to download the following dlls

//G:\Program Files\Microsoft SQL Server\80\Tools\Binn\OPENDS60.DLL

//G:\Program Files\Microsoft SQL Server\80\Tools\Binn\ums.DLL

extern "C" __declspec(dllexport) ULONG WINAPI __GetXpVersion()

{

       return ODS_VERSION;

}

extern "C" __declspec(dllexport) BOOL APIENTRY DllMain( HANDLE

hModule,

                      DWORD  ul_reason_for_call,

                      LPVOID lpReserved

                                        )

{

   return TRUE;

}

// send XP usage info to client

void printUsage (SRV_PROC *pSrvProc)

{

       // usage: exec xp_call_asp_by_onega <@table_name input> <@record_id

input> <@additional_info input>

       // Example:

       // exec xp_call_asp_by_onega 'table1',1,'for table1'

       //build by Onega at 2005/04/23 with VC2003, Windows 2003, SQLServer

2000

       srv_sendmsg(pSrvProc, SRV_MSG_ERROR, XP_HELLO_ERROR, SRV_INFO, 1,

               NULL, 0, (DBUSMALLINT) __LINE__,

               "Usage: exec xp_call_asp_by_onega <@table_name input> <@record_id

input> <@additional_info input>",

               SRV_NULLTERM);

       srv_senddone(pSrvProc, (SRV_DONE_ERROR | SRV_DONE_MORE), 0, 0);

}



// send szErrorMsg to client

void printError (SRV_PROC *pSrvProc, CHAR* szErrorMsg)

{

       srv_sendmsg(pSrvProc, SRV_MSG_ERROR, XP_HELLO_ERROR, SRV_INFO, 1,

               NULL, 0, (DBUSMALLINT) __LINE__,

               szErrorMsg,

               SRV_NULLTERM);



       srv_senddone(pSrvProc, (SRV_DONE_ERROR | SRV_DONE_MORE), 0, 0);

}



extern "C" __declspec(dllexport) SRVRETCODE WINAPI

xp_call_asp_by_onega(SRV_PROC* pSrvProc)

{

       BYTE        bType;

       long        cbMaxLen;

       long        cbActualLen;

       BOOL        fNull;

       // Count up the number of input parameters.

       //http://community.csdn.net/Expert/TopicView3.asp?id=3960017

       //table_name string,record_id int,additional_info string

       if (srv_rpcparams(pSrvProc) != 3)

       {

               printUsage(pSrvProc);

               return (XP_ERROR);

       }



       // Use srv_paraminfo to get data type and length information.

       int parameter_index = 1;

       if (srv_paraminfo(pSrvProc, parameter_index, &bType,

(ULONG*)&cbMaxLen, (ULONG*)&cbActualLen,

               NULL, &fNull) == FAIL)

       {

               printError (pSrvProc, "srv_paraminfo failed...");

               return (XP_ERROR);

       }

       // Make sure the parameter is of char or varchar datatype

       if (bType != SRVBIGVARCHAR && bType != SRVBIGCHAR)

       {

               printUsage(pSrvProc);

               return (XP_ERROR);

       }

       char szTable[128];

       memset(szTable,0,sizeof(szTable));

       memcpy(szTable, srv_paramdata(pSrvProc, parameter_index),

srv_paramlen(pSrvProc, parameter_index));

       parameter_index = 2;



       int record_id = 0;

       memcpy(&record_id, srv_paramdata(pSrvProc, parameter_index),

               srv_paramlen(pSrvProc, parameter_index));

       parameter_index = 3;

       if (srv_paraminfo(pSrvProc, parameter_index, &bType,

(ULONG*)&cbMaxLen,

               (ULONG*)&cbActualLen,

               NULL, &fNull) == FAIL)

       {

               printError (pSrvProc, "srv_paraminfo failed...");

               return (XP_ERROR);

       }

       // Make sure the parameter is of char or varchar datatype

       if (bType != SRVBIGVARCHAR && bType != SRVBIGCHAR)

       {

               printUsage(pSrvProc);

               return (XP_ERROR);

       }



       char szAdditionalInfo[128];

       memset(szAdditionalInfo,0,sizeof(szAdditionalInfo));

       memcpy(szAdditionalInfo, srv_paramdata(pSrvProc, parameter_index),

               srv_paramlen(pSrvProc, parameter_index));

       //check received parameter:

       std::stringstream ss;

       ss<<"xp_call_asp_by_onega('"<<szTable<<"',"<<record_id<<",'"<<szAddit

ionalInfo<<"')";

       OutputDebugString(ss.str().c_str());

       ss.str("");

       ss<<"http://127.0.0.1/xp_call_asp_by_onega.asp?table_name="<<szTable<

<"&record_id="

               <<record_id<<"&additional_info="

               <<szAdditionalInfo;

       LPCTSTR download_file_name = "c:\\xp_call_asp_by_onega.htm";

       DeleteFile(download_file_name);

       URLDownloadToFile(NULL,ss.str().c_str(),download_file_name,0,NULL);

       OutputDebugString(ss.str().c_str());

       srv_senddone(pSrvProc, (SRV_DONE_COUNT | SRV_DONE_MORE), 0, 1);

       return (XP_NOERROR);

}



/*

//def file

LIBRARY extended_proc_call_asp

EXPORTS

xp_call_asp_by_onega

__GetXpVersion

*/

/*

--install to G:\Program Files\Microsoft SQL

Server\80\Tools\Binn\extended_proc_call_asp.dll

--sp_addextendedproc 'xp_call_asp_by_onega',

'extended_proc_call_asp.dll'

exec xp_call_asp_by_onega 'table2', 2, 'exec xp test'

--sp_dropextendedproc 'xp_call_asp_by_onega'

*/

/*  xp_call_asp_by_onega.asp

<%

table_name = request.querystring("table_name")

record_id = request.querystring("record_id")

additional_info = request.querystring("additional_info")

if len(table_name)>0 AND len(additional_info)>0 then

application(table_name & cstr(record_id) ) = table_name & "," _

& CStr(record_id) & "," & additional_info

end if





for each x in Application.Contents

Response.Write(x & "=" & Application.Contents(x) & "<br />")

next



%>

*/