2012年5月25日 星期五

Watch Virtual / Physical Memory Usage

With previous article http://twnin.blogspot.com/2012/05/watch-process-memory-usage.html
There is another way to watch memory usage in program with win32 api.


    MEMORYSTATUS ms;
    ms.dwLength = sizeof(ms);
    GlobalMemoryStatus(&ms);

    const int nBufSize = 512;
    TCHAR chBuf[nBufSize];
    ::ZeroMemory(chBuf,nBufSize);

    // Process-specific info (for calling process)
    wsprintf(chBuf,_T("TotalVirtual: %ld\n"), ms.dwTotalVirtual);
    OutputDebugString(chBuf);
    wsprintf(chBuf,_T("AvailVirtual: %ld\n"), ms.dwAvailVirtual);
    OutputDebugString(chBuf);

    // Process virtual memory usage (reserved + commit)
    wsprintf(chBuf,_T("UsageVirtual: %ld\n"), ms.dwTotalVirtual - ms.dwAvailVirtual);
    OutputDebugString(chBuf);

    // System info
    wsprintf(chBuf,_T("MemoryLoad: %ld\n"), ms.dwMemoryLoad);
    OutputDebugString(chBuf);
    wsprintf(chBuf,_T("TotalPhys: %ld\n"), ms.dwTotalPhys);
    OutputDebugString(chBuf);
    wsprintf(chBuf,_T("AvailPhys: %ld\n"), ms.dwAvailPhys);
    OutputDebugString(chBuf);

    // System usage
    wsprintf(chBuf,_T("UsagePhys: %ld\n"), ms.dwTotalPhys - ms.dwAvailPhys);
    OutputDebugString(chBuf);

    // Unused/unsupported
    wsprintf(chBuf,_T("TotalPageFile: %lu\n"), ms.dwTotalPageFile);
    OutputDebugString(chBuf);
    wsprintf(chBuf,_T("AvailPageFile: %lu\n"), ms.dwAvailPageFile);
    OutputDebugString(chBuf);

Watch Process Memory Usage


To watch current process memory usage, we can use GetProcessMemoryInfo to get paging information.
It is sample code below.

    HANDLE hProcess = ::GetCurrentProcess();
    PROCESS_MEMORY_COUNTERS pmc;
    pmc.cb = sizeof(PROCESS_MEMORY_COUNTERS);
    ::GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc));

    const int nBufSize = 512;
    TCHAR chBuf[nBufSize];
    ::ZeroMemory(chBuf,nBufSize);

    wsprintf(chBuf,_T("PageFaultCount: 0x%08X\n"), pmc.PageFaultCount );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("PeakWorkingSetSize: 0x%08X\n"),
    pmc.PeakWorkingSetSize );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("WorkingSetSize: 0x%08X\n"), pmc.WorkingSetSize );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("QuotaPeakPagedPoolUsage: 0x%08X\n"),
    pmc.QuotaPeakPagedPoolUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("QuotaPagedPoolUsage: 0x%08X\n"),
    pmc.QuotaPagedPoolUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("QuotaPeakNonPagedPoolUsage: 0x%08X\n"),
    pmc.QuotaPeakNonPagedPoolUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("QuotaNonPagedPoolUsage: 0x%08X\n"),
    pmc.QuotaNonPagedPoolUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("PagefileUsage: 0x%08X\n"), pmc.PagefileUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("PeakPagefileUsage: 0x%08X\n"),
    pmc.PeakPagefileUsage );
    OutputDebugString(chBuf);

    CloseHandle(hProcess);


Reference:
http://msdn.microsoft.com/en-us/library/ms682050(v=VS.85).aspx
http://blog.csdn.net/caimouse/article/details/1947575

Work around link error:
error lnk2019: unresolved external symbol _getprocessmemoryinfo@12 referenced in function
http://lanvu.wordpress.com/tag/error-lnk2019-unresolved-external-symbol-_getprocessmemoryinfo12-referenced-in-function/

It seems doesn't work on windows ce.
https://groups.google.com/group/microsoft.public.pocketpc.developer/browse_thread/thread/22c685d1df9ec17d/e05ad892433d56aa?lnk=raot&pli=1

Structure of PROCESS_MEMORY_COUNTERS
http://blog.csdn.net/zhsp1029/article/details/3162048

2012年5月17日 星期四

[C++] error C2662 cannot convert 'this' pointer from 'const class' to 'class &


Look at following sample
class myClass
{
public:
    int get();
private:
    int m_member;
};

int myClass::get()
{
    return m_member;
}

int main()
{
    const myClass own;
    own.get();  // compiling error
    return 0;
}

A const object try to call non-const function, it is risk to change value of const object.
For the reason, we have to define myClass::get() to be a const function so that we could call the function by a const object.
int myClass::get() const

Or we also can define own to be a non-const object.
myClass own;


Reference: 
http://hi.baidu.com/idealsoft/blog/item/629ae129a7f14afb99250af4.html http://forums.codeguru.com/archive/index.php/t-416873.html

2012年5月16日 星期三

[WebKit] WebDatabase openDatabase()

This is a simple memo for myself about web sql databse function flow.

Java script code

  var db = openDatabase("Todo", "1.0", "Todo manager", 1024*1024);


WebKit code

// call window.openDatabase
PassRefPtr<Database> DOMWindowSQLDatabase::openDatabase(DOMWindow* window, const String& name, const String& version, const String& displayName, unsigned long estimatedSize, PassRefPtr<DatabaseCallback> creationCallback, ExceptionCode& ec)

// Database::openDatabase
PassRefPtr<Database> Database::openDatabase(ScriptExecutionContext* context, const String& name, const String& expectedVersion, const String& displayName, unsigned long estimatedSize, PassRefPtr<DatabaseCallback> creationCallback, ExceptionCode& e)
// call Database & AbstractDatabase constructor
Database::Database(ScriptExecutionContext* context, const String& name, const String& expectedVersion, const String& displayName, unsigned long estimatedSize) : AbstractDatabase(context, name, expectedVersion, displayName, estimatedSize, AsyncDatabase) , m_transactionInProgress(false) , m_isTransactionQueueEnabled(true) , m_deleted(false)

// Insert database into tracker (called in constructor of AbstractDatabase)
String DatabaseTracker::fullPathForDatabase(SecurityOrigin* origin, const String& name, bool createIfNotExists)
String DatabaseTracker::fullPathForDatabaseNoLock(SecurityOrigin* origin, const String& name, bool createIfNotExists)
bool DatabaseTracker::addDatabase(SecurityOrigin* origin, const String& name, const String& path)
// open database
bool Database::openAndVerifyVersion(bool setVersionInNewDatabase, ExceptionCode& e, String& errorMessage)
bool Database::performOpenAndVerify(bool setVersionInNewDatabase, ExceptionCode& e, String& errorMessage)
void DatabaseThread::recordDatabaseOpen(Database* database)

// set database detail infomation
void DatabaseTracker::setDatabaseDetails(SecurityOrigin* origin, const String& name, const String& displayName, unsigned long estimatedSize)

>> return RefPtr<Database>


2012年5月15日 星期二

[BDB] Building Berkeley DB for CE6 (ARMV4I)

This is a memo which copy from Oracle for building berkeley DB.


There are many possible target CPU architectures for a Windows Mobile application. This section outlines the process required to add a new target architecture to the project files supplied with Berkeley DB.
The Visual Studio 2005 project files will by default build for Pocket PC 2003 and Smartphone 2003, and Windows Mobile 6.5.3 Professional. If you want to build for other platforms such as Windows Mobile 6.0, 6.1, or 6.5, you need to follow the steps provided in this section.
Different target architectures are available in different Platform SDK or DTK downloads from Microsoft. The appropriate SDK must be installed for your mobile architecture before you can build for that platform. You can find the downloads at the Microsoft Developer Center page.

Build via Visual Studio 2008

  1. Choose File -> Open Workspace.... Navigate to the build_wince directory, select Berkeley_DB and click Open.
  2. From the Solution explorer window, right-click the Solution Berkeley_DB and select Configuration manager...
  3. In the Active solution platform: drop down box select New...
  4. From the Type or select the new platform drop-down box, select a configuration from the ones available and click OK. (Copy Setting From Pocket PC 2003 (ARMV4))
  5. Click Close from the Configuration Manager dialog box.
  6. The target platform drop-down now contains the platform just added.
  7. Build as per the instructions given at the beginning of this chapter.

build error
error LNK2019: unresolved external symbol localtime_s referenced in function localtimeOffset date.obj

trouble shooting
open date.c in db_sql project
modify #define HAVE_LOCALTIME_S 1 to #define HAVE_LOCALTIME_S 0


Reference:
http://docs.oracle.com/cd/E17076_02/html/installation/index.html

2012年5月13日 星期日

[WebKit] IndexedDB open()

This is a simple memo for myself about webkit function flow.

Java script code
var request = webkitIndexedDB.open("todos");


Webkit code

// get webkitIndexedDB object
static IDBFactory* webkitIndexedDB(DOMWindow*);

// call IDBFactory::open
PassRefPtr<IDBRequest> open(ScriptExecutionContext*, const String& name, ExceptionCode&);

// get IDBFactory.m_backend
RefPtr<IDBFactoryBackendInterface> m_backend;

// call IDBFactoryBackendInterface::open
virtual void open(const String& name, IDBCallbacks*, PassRefPtr<SecurityOrigin>, Frame*, const String& dataDir) = 0;

// call IDBFactoryBackendImpl::open to implement IDBFactoryBackendInterface::open
virtual void open(const String& name, IDBCallbacks*, PassRefPtr<SecurityOrigin>, Frame*, const String& dataDir);

// call IDBFactoryBackendImpl::openInternal in IDBFactoryBackendImpl::open
void openInternal(const String& name, IDBCallbacks*, PassRefPtr<SecurityOrigin>, const String& dataDir);

// branch 1, If database exist, call IDBDatabaseBackendImpl::openConnection
void openConnection(PassRefPtr<IDBCallbacks>);

        // call IDBDatabaseBackendImpl::openInternal
        void IDBDatabaseBackendImpl::openInternal()

        // call IDBBackingStore::getIDBDatabaseMetaData to get meta data from from physical database
        virtual bool getIDBDatabaseMetaData(const String& name, String& foundVersion, int64_t& foundId) = 0;

        // call IDBDatabaseBackendImpl::loadObjectStores
        void IDBDatabaseBackendImpl::loadObjectStores()

                // call IDBBackingStore::getObjectStores to get all ObjectStores from physical database
                virtual void getObjectStores(int64_t databaseId, Vector<int64_t>& foundIds, Vector<String>& foundNames, Vector<String>& foundKeyPaths, Vector<bool>& foundAutoIncrementFlags) = 0;

                // call IDBObjectStoreBackendImpl::create
                static PassRefPtr<IDBObjectStoreBackendImpl> create(IDBBackingStore* backingStore, int64_t databaseId, int64_t id, const String& name, const String& keyPath, bool autoIncrement)



// branch 2, If database doesn't exist, call IDBDatabaseBackendImpl::create
static PassRefPtr<IDBDatabaseBackendImpl> create(const String& name, IDBBackingStore* database, IDBTransactionCoordinator* coordinator, IDBFactoryBackendImpl* factory, const String& uniqueIdentifier)


>>> back to trunk
// call IDBCallbacks::onSuccess
void IDBRequest::onSuccess(PassRefPtr<IDBDatabaseBackendInterface> backend)

// call IDBDatabase::create
PassRefPtr<IDBDatabase> IDBDatabase::create(ScriptExecutionContext* context, PassRefPtr<IDBDatabaseBackendInterface> database)

// create request result for IDBRequest
static PassRefPtr<IDBAny> create(PassRefPtr<T> idbObject)

// summit success event
static IDBRequest::PassRefPtr<Event> createSuccessEvent()
        void IDBRequest::enqueueEvent(PassRefPtr<Event> event)



2012年5月4日 星期五

[HTML5] Web SQL Database

List some useful function for web sql database.

    Prototype
    openDatabase(name, version, displayName, estimatedSize, creationCallback)

    // to open database
    var db;
    openDatabase('documents', '1', 'Local document storage', 1024 * 1024,
        function(database) {
            db = database;
        });
    }

    // another example to open database 
    db = openDatabase('documents', '1', 'Local document storage', 1024 * 1024);


    Prototype
    transaction(callback, errorCallback, successCallback)

    // to create transaction
    db.transaction(
        function(tx) {
        ...
        },
        function(error) {
        ...
        },
        function() {
        ...
        }
    }


    Prototype
    executeSql(sql, args, callback, errorCallback)

    // to execute sql for non-query command
    tx.executeSql("create table Book(id, name)");
    tx.executeSql("insert into Book values(?, ?)",  [1, "good book"]);
    var name = "bad book";
    tx.executeSql("update Book set name = ?",  [name]);

    // to execute sql for query command
    tx.executeSql("select id, name from Book", [],
        function(tx, rs) {
            for (var i=0; i < rs.rows.length; i++) {
                var row = rs.rows.item(i);
                var bookData = "ID=" + row.id + " / Name=" row.name;
            }
        });


Example
        var db = openDatabase('Book', '1', 'Local storage', 1024 * 1024);

        db.transaction(
            function(tx) {
                tx.executeSql("drop table Book");
            });
         
        db.transaction(
            function(tx) {
                tx.executeSql("create table Book(id integer primary key autoincrement, name)");
            });

        db.transaction(
            function(tx) {
                tx.executeSql("insert into Book (name) values(?)", ["book1"],
                function(tx, rs) {
                    alert("id=" + rs.insertId);
                });
            });
         
        db.transaction(
        function(tx) {
            tx.executeSql("select id, name from Book", [],
                function(tt, rs) {
                    for (var i = 0; i < rs.rows.length; i++) {
                        var row = rs.rows.item(i);
                        alert(row.name);
                    }
                });
        });


Reference:
HTML5 & API NYUMON by Shunpei Shiraishi
http://dev.w3.org/html5/webdatabase/#introduction

[HTML5] Web Local Storage


Here bring up some samples for local storage in html5.
Remember that all data is stored as String.
It is stored in sqlite data for Chrome browser, and you can find the sqlite data in folder
C:\Documents and Settings\(UserNmae)\Local Settings\Application Data\Google\Chrome\User Data\Default\Local Storage

    // to detect browser whether support local storage
    function supports_html5_storage() {
        return ('localStorage' in window) && window['localStorage'] !== null;
    }

    // to get and set local storage
    localStorage.setItem("bar1", "haha - foo1");
    var foo1 = localStorage.getItem("bar1");

    // to get and set local storage using square-bracket
    localStorage["bar2"] = "haha - foo2";
    var foo2 = localStorage["bar2"];

    // to remove specify key-value pair
    localStorage.removeItem("bar1");

    // to clear storage
    localStorage.clear();

    // to get total number of values in the storage area.
    var storageLength = localStorage.length;

    // to get the name of each key by index.
    var keyName = localStorage.key(0);


Reference:
[OReilly] HTML5 Up and Running

2012年5月2日 星期三

[CLOC] A freeware to get line count of code

Official website:  http://cloc.sourceforge.net/

It is easy to use.
Just download it from official website.
Open command line program and execute it 
C:\> cloc <directory path>
F:\Work\Melco\Source>cloc-1.56 F:\Work\Melco\Source\work_R4.4
  110067 text files.
   94873 unique files.
   62916 files ignored.

http://cloc.sourceforge.net v 1.56  T=7040.0 s (6.3 files/s, 1282.8 lines/s)
---------------------------------------------------------------

Language              files       blank     comment        code

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

C                      2285      271788      338944     1526777

HTML                  17635      203290       20777     1093148

C++                    4044      190284      185459      925764

C/C++ Header           9196      251235      723200      833570

Python                 3269      124116      180884      580909

Javascript             4629      102041      151691      397103

Bourne Shell            190       27479       30154      200180

PHP                     413       17722       35413       84820

Perl                    470       20386       25871       75488

Objective C++           255       15993       12059       68903

m4                       31        5097         892       44023

XML                     641       11305        7312       35004

IDL                     546        3986           0       33302

CSS                     278        4877        2060       25497

make                    190        4587        3483       22708

Tcl/Tk                   90        2906        7257       19903

Assembly                 36        1493        1584        9347

Java                     99        2026        3234        8317

DTD                      19        2100        2442        7763

Objective C              71        1835        2150        6861

Teamcenter def           35         264         250        5800

Lisp                      4         542         532        3711

yacc                      3         462         142        3690

Expect                   29           9           1        3281

C#                       21         175         213        2547

CMake                     8         182          74        2278

XSLT                     47         133         124        1796

DOS Batch                37          84          93        1639

Ruby                     15         315         249        1320

XSD                       8         165         122         621

Visual Basic              6          70          25         351

Korn Shell                1          39          46         223

Bourne Again Shell        2          25          76         173

vim script                1          36           7         104

MSBuild scripts           2           0          14         103

YAML                      5          20          16          84

NAnt scripts              4           2           0          60

awk                       1           2          26          48

sed                       4           1          10          34

D                         1           3          24          13

ASP.Net                   1           0           0           1

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

SUM:                  44622     1267075     1736910     6027264

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

Reference: 
http://blog.miniasp.com/post/2009/08/24/Useful-tool-CLOC-Count-Lines-of-Code.aspx