Revision: 201001
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Mon, 18 Jan 2010 20:34:07 +0200
changeset 0 c53acadfccc6
child 1 acef663c1218
Revision: 201001 Kit: 201003
clfwrapper/BWINS/CONTENTLISTINGFRAMEWORKU.DEF
clfwrapper/BWINS/MediaCollectionManagerU.DEF
clfwrapper/ClientSrc/CCLFDbItemContainer.cpp
clfwrapper/ClientSrc/CCLFDbItemContainer.h
clfwrapper/ClientSrc/CCLFDbItemContainer.inl
clfwrapper/ClientSrc/CCLFDbItemProvider.cpp
clfwrapper/ClientSrc/CCLFDbItemProvider.h
clfwrapper/ClientSrc/CCLFDefaultOperation.cpp
clfwrapper/ClientSrc/CCLFDefaultOperation.h
clfwrapper/ClientSrc/CCLFEngineImpl.cpp
clfwrapper/ClientSrc/CCLFEngineImpl.h
clfwrapper/ClientSrc/CCLFEventHandler.cpp
clfwrapper/ClientSrc/CCLFEventHandler.h
clfwrapper/ClientSrc/CCLFItemImpl.cpp
clfwrapper/ClientSrc/CCLFItemImpl.h
clfwrapper/ClientSrc/CCLFItemListModelImpl.cpp
clfwrapper/ClientSrc/CCLFItemListModelImpl.h
clfwrapper/ClientSrc/CCLFQueryAdapter.cpp
clfwrapper/ClientSrc/CCLFQueryAdapter.h
clfwrapper/ClientSrc/CCLFServerProxy.cpp
clfwrapper/ClientSrc/CCLFServerProxy.h
clfwrapper/ClientSrc/CCLFSortingStyleImpl.cpp
clfwrapper/ClientSrc/CCLFSortingStyleimpl.h
clfwrapper/ClientSrc/CLF2MdEConsts.h
clfwrapper/ClientSrc/CLFUtils.cpp
clfwrapper/ClientSrc/CLFUtils.h
clfwrapper/ClientSrc/ContentListingFactory.cpp
clfwrapper/ClientSrc/MCLFChangedItemProvider.h
clfwrapper/ClientSrc/MCLFEventHandlerObserver.h
clfwrapper/ClientSrc/MCLFItemProviderObserver.h
clfwrapper/CommonInc/CLFConsts.h
clfwrapper/CommonInc/CLFPanics.h
clfwrapper/CommonInc/CLFUID.hrh
clfwrapper/CommonInc/MGDebugPrint.h
clfwrapper/CommonInc/MGTracePrint.h
clfwrapper/CommonInc/clfvariant.hrh
clfwrapper/CommonInc/contentlistingframeworkprivatecrkeys.h
clfwrapper/EABI/ContentListingFrameworkU.DEF
clfwrapper/EABI/MediaCollectionManagerU.DEF
clfwrapper/cenrep/keys_s60contentlistingframework.xls
clfwrapper/conf/102828AC.txt
clfwrapper/conf/s60contentlistingframework.confml
clfwrapper/conf/s60contentlistingframework_102828AC.crml
clfwrapper/group/bld.inf
clfwrapper/group/contentlistingframework.mmp
clfwrapper/group/mediacollectionmanager.mmp
clfwrapper/mediacollectionmanagersrc/mediacollectionmanagerfactory.cpp
clfwrapper/mediacollectionmanagersrc/mediacollectionmanagerimpl.cpp
clfwrapper/mediacollectionmanagersrc/mediacollectionmanagerimpl.h
clfwrapper/sis/contentlistingframework_stub.sis
clfwrapper/sis/depends.xml
clfwrapper/sis/package.pkg
clfwrapper/sis/stub.pkg
contextengine/bwincw/contextenginewinscw.def
contextengine/data/ContextEngine_Stub.pkg
contextengine/data/ContextEngine_Stub.sis
contextengine/data/Create_STUB_SIS.bat
contextengine/data/contextengine.pkg
contextengine/data/rd-key.pem
contextengine/data/rd.cer
contextengine/eabi/contextenginearm.def
contextengine/group/bld.inf
contextengine/group/contextengine.mmp
contextengine/inc/contextengineao.h
contextengine/inc/contextsnapshotitem.h
contextengine/inc/contextsnapshotitem.inl
contextengine/plugins/calendarplugin/data/102823CA.rss
contextengine/plugins/calendarplugin/group/bld.inf
contextengine/plugins/calendarplugin/group/calendarcontextplugin.mmp
contextengine/plugins/calendarplugin/inc/CalendarContextLogger.h
contextengine/plugins/calendarplugin/inc/CalendarContextLogger.inl
contextengine/plugins/calendarplugin/inc/CalendarContextPlugin.h
contextengine/plugins/calendarplugin/src/CalendarContextPlugin.cpp
contextengine/plugins/calendarplugin/src/proxy.cpp
contextengine/plugins/contextplugininterface/bwincw/contextplugininterfacewinscw.def
contextengine/plugins/contextplugininterface/eabi/contextplugininterfacearm.def
contextengine/plugins/contextplugininterface/group/bld.inf
contextengine/plugins/contextplugininterface/group/contextplugininterface.mmp
contextengine/plugins/contextplugininterface/src/contextplugin.cpp
contextengine/plugins/group/bld.inf
contextengine/plugins/locationplugin/data/200071cf.rss
contextengine/plugins/locationplugin/group/bld.inf
contextengine/plugins/locationplugin/group/locationcontextplugin.mmp
contextengine/plugins/locationplugin/inc/locationcontextplugin.h
contextengine/plugins/locationplugin/src/locationcontextplugin.cpp
contextengine/plugins/locationplugin/src/locationpluginproxy.cpp
contextengine/sis/contextengine_stub.sis
contextengine/sis/depends.xml
contextengine/sis/package.pkg
contextengine/sis/stub.pkg
contextengine/src/contextengine.cpp
contextengine/src/contextengineao.cpp
group/bld.inf
harvester/blacklistclient/bwincw/blacklistclientwinscw.def
harvester/blacklistclient/eabi/blacklistclient.def
harvester/blacklistclient/eabi/blacklistclientarm.def
harvester/blacklistclient/group/blacklistclient.mmp
harvester/blacklistclient/group/bld.inf
harvester/blacklistclient/inc/blacklistclient.h
harvester/blacklistclient/src/blacklistclient.cpp
harvester/blacklistserver/group/blacklistserver.mmp
harvester/blacklistserver/group/bld.inf
harvester/blacklistserver/inc/blacklistcommon.h
harvester/blacklistserver/inc/blacklistserver.h
harvester/blacklistserver/inc/blacklistsession.h
harvester/blacklistserver/src/blacklistserver.cpp
harvester/blacklistserver/src/blacklistsession.cpp
harvester/client/bwincw/harvesterclientwinscw.def
harvester/client/eabi/harvesterclientarm.def
harvester/client/group/bld.inf
harvester/client/group/harvesterclient.mmp
harvester/client/inc/clientharvestitem.h
harvester/client/inc/harvesterclientao.h
harvester/client/inc/harvestereventobserverao.h
harvester/client/inc/harvesterrequestactive.h
harvester/client/inc/harvesterrequestqueue.h
harvester/client/src/clientharvestitem.cpp
harvester/client/src/harvesterclient.cpp
harvester/client/src/harvesterclientao.cpp
harvester/client/src/harvestereventobserverao.cpp
harvester/client/src/harvesterrequestactive.cpp
harvester/client/src/harvesterrequestqueue.cpp
harvester/common/bwincw/harvestercommonwinscw.def
harvester/common/bwincw/harvesterdatawinscw.def
harvester/common/bwincw/harvesterplugininterfacewinscw.def
harvester/common/data/200009FE.txt
harvester/common/data/harvester_settings.xml
harvester/common/eabi/harvestercommonarm.def
harvester/common/eabi/harvesterdataarm.def
harvester/common/eabi/harvesterplugininterfacearm.def
harvester/common/group/bld.inf
harvester/common/group/harvestercommon.mmp
harvester/common/group/harvesterdata.mmp
harvester/common/group/harvesterplugininterface.mmp
harvester/common/inc/blacklistitem.h
harvester/common/inc/clientkeywatcherkeys.h
harvester/common/inc/harvestdata.h
harvester/common/inc/harvestdata.inl
harvester/common/inc/harvesterblacklist.h
harvester/common/inc/harvestercenreputil.h
harvester/common/inc/harvestercommon.h
harvester/common/inc/harvestereventmanager.h
harvester/common/inc/harvesterexifutil.h
harvester/common/inc/harvestermediaidutil.h
harvester/common/inc/harvesterpluginfactory.h
harvester/common/inc/harvesterplugininfo.h
harvester/common/inc/listener.h
harvester/common/inc/mdeobjectwrapper.h
harvester/common/inc/mimetypemapping.h
harvester/common/inc/mimetypemapping.inl
harvester/common/inc/mpropertyobserver.h
harvester/common/inc/processoriginmapperinterface.h
harvester/common/inc/propertywatcher.h
harvester/common/src/blacklistitem.cpp
harvester/common/src/harvesterblacklist.cpp
harvester/common/src/harvestercenreputil.cpp
harvester/common/src/harvesterclientdata.cpp
harvester/common/src/harvesterdata.cpp
harvester/common/src/harvestereventmanager.cpp
harvester/common/src/harvesterexifutil.cpp
harvester/common/src/harvestermediaidutil.cpp
harvester/common/src/harvesterplugin.cpp
harvester/common/src/harvesterpluginfactory.cpp
harvester/common/src/listener.cpp
harvester/common/src/mdeobjectwrapper.cpp
harvester/common/src/placeholderdata.cpp
harvester/common/src/propertywatcher.cpp
harvester/composerplugins/composerplugininterface/bwincw/composerplugininterfacewinscw.def
harvester/composerplugins/composerplugininterface/eabi/composerplugininterfacearm.def
harvester/composerplugins/composerplugininterface/group/bld.inf
harvester/composerplugins/composerplugininterface/group/composerplugininterface.mmp
harvester/composerplugins/composerplugininterface/src/composerplugin.cpp
harvester/composerplugins/group/bld.inf
harvester/composerplugins/imagecomposer/data/20007180.rss
harvester/composerplugins/imagecomposer/group/bld.inf
harvester/composerplugins/imagecomposer/group/composerimageplugin.mmp
harvester/composerplugins/imagecomposer/inc/composerimageplugin.h
harvester/composerplugins/imagecomposer/inc/imagecomposerao.h
harvester/composerplugins/imagecomposer/inc/imagepresentobserver.h
harvester/composerplugins/imagecomposer/inc/locationrelationobserver.h
harvester/composerplugins/imagecomposer/src/composerimageplugin.cpp
harvester/composerplugins/imagecomposer/src/imagecomposerao.cpp
harvester/composerplugins/imagecomposer/src/imagepresentobserver.cpp
harvester/composerplugins/imagecomposer/src/locationrelationobserver.cpp
harvester/composerplugins/imagecomposer/src/proxy.cpp
harvester/conf/harvester.confml
harvester/conf/harvester_200009FE.crml
harvester/data/blacklist_backup_registration.xml
harvester/data/default_origin_mappings.db
harvester/group/bld.inf
harvester/harvesterplugins/AudioPlugin/data/2001116A.rss
harvester/harvesterplugins/AudioPlugin/group/bld.inf
harvester/harvesterplugins/AudioPlugin/group/harvesteraudioplugin.mmp
harvester/harvesterplugins/AudioPlugin/inc/harvesteraudioplugin.h
harvester/harvesterplugins/AudioPlugin/inc/harvesteraudiopluginutils.h
harvester/harvesterplugins/AudioPlugin/src/harvesteraudioplugin.cpp
harvester/harvesterplugins/AudioPlugin/src/harvesteraudiopluginutils.cpp
harvester/harvesterplugins/AudioPlugin/src/proxy.cpp
harvester/harvesterplugins/ImagePlugin/data/200009fb.rss
harvester/harvesterplugins/ImagePlugin/group/bld.inf
harvester/harvesterplugins/ImagePlugin/group/harvesterimageplugin.mmp
harvester/harvesterplugins/ImagePlugin/inc/harvesterimageplugin.h
harvester/harvesterplugins/ImagePlugin/src/harvesterimageplugin.cpp
harvester/harvesterplugins/ImagePlugin/src/proxy.cpp
harvester/harvesterplugins/MessagePlugin/data/102823c8.rss
harvester/harvesterplugins/MessagePlugin/group/bld.inf
harvester/harvesterplugins/MessagePlugin/group/harvestermessageplugin.mmp
harvester/harvesterplugins/MessagePlugin/inc/harvestermessageplugin.h
harvester/harvesterplugins/MessagePlugin/src/harvestermessageplugin.cpp
harvester/harvesterplugins/MessagePlugin/src/proxy.cpp
harvester/harvesterplugins/OMADRMPlugin/data/20010973.rss
harvester/harvesterplugins/OMADRMPlugin/group/bld.inf
harvester/harvesterplugins/OMADRMPlugin/group/harvesteromadrmplugin.mmp
harvester/harvesterplugins/OMADRMPlugin/inc/harvesteromadrmplugin.h
harvester/harvesterplugins/OMADRMPlugin/src/harvesteromadrmplugin.cpp
harvester/harvesterplugins/OMADRMPlugin/src/proxy.cpp
harvester/harvesterplugins/RTPPlugin/data/2000B433.rss
harvester/harvesterplugins/RTPPlugin/group/bld.inf
harvester/harvesterplugins/RTPPlugin/group/harvesterrtpplugin.mmp
harvester/harvesterplugins/RTPPlugin/inc/harvesterrtpmetadatareader.h
harvester/harvesterplugins/RTPPlugin/inc/harvesterrtpplugin.h
harvester/harvesterplugins/RTPPlugin/src/harvesterrtpmetadatareader.cpp
harvester/harvesterplugins/RTPPlugin/src/harvesterrtpplugin.cpp
harvester/harvesterplugins/RTPPlugin/src/harvesterrtpproxy.cpp
harvester/harvesterplugins/VideoPlugin/data/200009f9.rss
harvester/harvesterplugins/VideoPlugin/group/bld.inf
harvester/harvesterplugins/VideoPlugin/group/harvestervideoplugin.mmp
harvester/harvesterplugins/VideoPlugin/inc/harvestervideoplugin.h
harvester/harvesterplugins/VideoPlugin/src/harvestervideoplugin.cpp
harvester/harvesterplugins/VideoPlugin/src/proxy.cpp
harvester/harvesterplugins/WMVPlugin/data/2000B431.rss
harvester/harvesterplugins/WMVPlugin/group/bld.inf
harvester/harvesterplugins/WMVPlugin/group/harvesterwmvplugin.mmp
harvester/harvesterplugins/WMVPlugin/inc/harvesterwmvplugin.h
harvester/harvesterplugins/WMVPlugin/src/harvesterwmvplugin.cpp
harvester/harvesterplugins/WMVPlugin/src/harvesterwmvproxy.cpp
harvester/harvesterplugins/group/bld.inf
harvester/monitorplugins/fileplugin/data/20007182.rss
harvester/monitorplugins/fileplugin/data/20007182.txt
harvester/monitorplugins/fileplugin/group/bld.inf
harvester/monitorplugins/fileplugin/group/filemonitorplugin.mmp
harvester/monitorplugins/fileplugin/inc/FolderRenamer.h
harvester/monitorplugins/fileplugin/inc/fileeventhandlerao.h
harvester/monitorplugins/fileplugin/inc/filemonitorao.h
harvester/monitorplugins/fileplugin/inc/filemonitorplugin.h
harvester/monitorplugins/fileplugin/inc/movetimer.h
harvester/monitorplugins/fileplugin/inc/processoriginmapper.h
harvester/monitorplugins/fileplugin/src/FolderRenamer.cpp
harvester/monitorplugins/fileplugin/src/fileeventhandlerao.cpp
harvester/monitorplugins/fileplugin/src/filemonitorao.cpp
harvester/monitorplugins/fileplugin/src/filemonitorplugin.cpp
harvester/monitorplugins/fileplugin/src/movetimer.cpp
harvester/monitorplugins/fileplugin/src/processoriginmapper.cpp
harvester/monitorplugins/fileplugin/src/proxy.cpp
harvester/monitorplugins/group/bld.inf
harvester/monitorplugins/inc/fsutil.h
harvester/monitorplugins/inc/fsutil.inl
harvester/monitorplugins/inc/mdsfileserverpluginclient.h
harvester/monitorplugins/inc/mdsfileserverpluginclient.inl
harvester/monitorplugins/inc/mdsfspqueue.h
harvester/monitorplugins/inc/mdsfspqueue.inl
harvester/monitorplugins/mdsfileserverplugin/group/bld.inf
harvester/monitorplugins/mdsfileserverplugin/group/mdsfileserverplugin.mmp
harvester/monitorplugins/mdsfileserverplugin/inc/mdsfileserverplugin.h
harvester/monitorplugins/mdsfileserverplugin/src/mdsfileserverplugin.cpp
harvester/monitorplugins/mdsoomplugin/data/2001B2C6.rss
harvester/monitorplugins/mdsoomplugin/group/bld.inf
harvester/monitorplugins/mdsoomplugin/group/mdsoomplugin.mmp
harvester/monitorplugins/mdsoomplugin/inc/mdsoomplugin.h
harvester/monitorplugins/mdsoomplugin/src/mdsoomplugin.cpp
harvester/monitorplugins/mdsoomplugin/src/proxy.cpp
harvester/monitorplugins/messageplugin/data/102823c6.rss
harvester/monitorplugins/messageplugin/group/bld.inf
harvester/monitorplugins/messageplugin/group/messagemonitorplugin.mmp
harvester/monitorplugins/messageplugin/inc/messagemonitorplugin.h
harvester/monitorplugins/messageplugin/inc/messagescannerao.h
harvester/monitorplugins/messageplugin/src/messagemonitorplugin.cpp
harvester/monitorplugins/messageplugin/src/messagescannerao.cpp
harvester/monitorplugins/messageplugin/src/proxy.cpp
harvester/monitorplugins/mmcplugin/data/20007183.rss
harvester/monitorplugins/mmcplugin/data/20007183.txt
harvester/monitorplugins/mmcplugin/group/bld.inf
harvester/monitorplugins/mmcplugin/group/mmcmonitorplugin.mmp
harvester/monitorplugins/mmcplugin/inc/mmcfilelist.h
harvester/monitorplugins/mmcplugin/inc/mmcmonitorao.h
harvester/monitorplugins/mmcplugin/inc/mmcmonitorplugin.h
harvester/monitorplugins/mmcplugin/inc/mmcmounttaskao.h
harvester/monitorplugins/mmcplugin/inc/mmcscannerao.h
harvester/monitorplugins/mmcplugin/inc/mmcusbao.h
harvester/monitorplugins/mmcplugin/src/mmcfilelist.cpp
harvester/monitorplugins/mmcplugin/src/mmcmonitorao.cpp
harvester/monitorplugins/mmcplugin/src/mmcmonitorplugin.cpp
harvester/monitorplugins/mmcplugin/src/mmcmounttaskao.cpp
harvester/monitorplugins/mmcplugin/src/mmcscannerao.cpp
harvester/monitorplugins/mmcplugin/src/mmcusbao.cpp
harvester/monitorplugins/mmcplugin/src/proxy.cpp
harvester/monitorplugins/monitorplugininterface/bwincw/monitorplugininterfacewinscw.def
harvester/monitorplugins/monitorplugininterface/eabi/monitorplugininterfacearm.def
harvester/monitorplugins/monitorplugininterface/group/bld.inf
harvester/monitorplugins/monitorplugininterface/group/monitorplugininterface.mmp
harvester/monitorplugins/monitorplugininterface/src/monitorplugin.cpp
harvester/server/group/bld.inf
harvester/server/group/harvesterserver.mmp
harvester/server/inc/backupsubscriber.h
harvester/server/inc/cclientkeywatcherao.h
harvester/server/inc/harvesterao.h
harvester/server/inc/harvesteroomao.h
harvester/server/inc/harvesterqueue.h
harvester/server/inc/harvesterserver.h
harvester/server/inc/harvesterserversession.h
harvester/server/inc/harvestershutdownobserver.h
harvester/server/inc/mdeobjecthandler.h
harvester/server/inc/mdsactivescheduler.h
harvester/server/inc/ondemandao.h
harvester/server/inc/pauseobserverao.h
harvester/server/inc/reharvesterao.h
harvester/server/inc/restorewatcher.h
harvester/server/inc/unmounthandlerao.h
harvester/server/src/backupsubscriber.cpp
harvester/server/src/cclientkeywatcherao.cpp
harvester/server/src/harvesterao.cpp
harvester/server/src/harvesteroomao.cpp
harvester/server/src/harvesterqueue.cpp
harvester/server/src/harvesterserver.cpp
harvester/server/src/harvesterserversession.cpp
harvester/server/src/harvestershutdownobserver.cpp
harvester/server/src/mdeobjecthandler.cpp
harvester/server/src/mdsactivescheduler.cpp
harvester/server/src/ondemandao.cpp
harvester/server/src/pauseobserverao.cpp
harvester/server/src/reharvesterao.cpp
harvester/server/src/restorewatcher.cpp
harvester/server/src/unmounthandlerao.cpp
harvester/sis/blacklistserver/blacklistserver_stub.sis
harvester/sis/blacklistserver/depends.xml
harvester/sis/blacklistserver/package.pkg
harvester/sis/blacklistserver/stub.pkg
harvester/sis/composerplugins/composerplugins_stub.sis
harvester/sis/composerplugins/depends.xml
harvester/sis/composerplugins/package.pkg
harvester/sis/composerplugins/stub.pkg
harvester/sis/harvester/depends.xml
harvester/sis/harvester/harvester_stub.sis
harvester/sis/harvester/package.pkg
harvester/sis/harvester/stub.pkg
harvester/sis/harvesterplugins/depends.xml
harvester/sis/harvesterplugins/harvesterplugins_stub.sis
harvester/sis/harvesterplugins/package.pkg
harvester/sis/harvesterplugins/stub.pkg
harvester/sis/monitorplugins/depends.xml
harvester/sis/monitorplugins/monitorplugins_stub.sis
harvester/sis/monitorplugins/package.pkg
harvester/sis/monitorplugins/stub.pkg
iadstoprestart/group/bld.inf
iadstoprestart/group/iadrestart.mmp
iadstoprestart/group/iadstop.mmp
iadstoprestart/inc/iadrestart.h
iadstoprestart/inc/iadstop.h
iadstoprestart/src/iadrestart.cpp
iadstoprestart/src/iadstop.cpp
inc/harvesterlog.h
inc/mdccommon.pan
inc/mdccriteria.h
inc/mdcdef.h
inc/mdcitem.h
inc/mdcquery.h
inc/mdcresult.h
inc/mdcserializationbuffer.h
inc/mdcserializationtype.h
inc/mdeharvestersession.h
inc/mdepanic.h
inc/mdscommoninternal.h
inc/mdssqlconnection.inl
inc/mdssqliteconnection.h
inc/mdssqlrow.h
inc/mdssqlrow.inl
inc/mdsutils.h
layers.sysdef.50.xml
layers.sysdef.xml
locationmanager/backup/backup_registration.xml
locationmanager/bwincw/bwinscwlocationtrailu.def
locationmanager/bwincw/bwinslocationmanagerclientu.def
locationmanager/client/bwincw/locationmanagerclientwinscw.def
locationmanager/client/eabi/locationmanagerclientarm.def
locationmanager/client/group/bld.inf
locationmanager/client/group/locationmanagerclient.mmp
locationmanager/client/inc/CTrackLogObserverAO.h
locationmanager/client/src/CTrackLogObserverAO.cpp
locationmanager/client/src/rlocationmanager.cpp
locationmanager/client/src/rlocationobjectmanipulator.cpp
locationmanager/client/src/rlocationtrail.cpp
locationmanager/client/src/rtracklog.cpp
locationmanager/conf/200071BE.txt
locationmanager/conf/locationmanager.confml
locationmanager/conf/locationmanager_200071BE.crml
locationmanager/data/200071BE.txt
locationmanager/data/Location_Manager_settings.xml
locationmanager/group/bld.inf
locationmanager/inc/locationmanagerdebug.h
locationmanager/inc/locationmanagerdebug.inl
locationmanager/inc/locationmanagerdefs.h
locationmanager/locationtrail/bwincw/locationtrailwinscw.def
locationmanager/locationtrail/eabi/locationtrailarm.def
locationmanager/locationtrail/group/bld.inf
locationmanager/locationtrail/group/locationtrail.mmp
locationmanager/locationtrail/inc/cgpxconverterao.h
locationmanager/locationtrail/inc/clocationrecord.h
locationmanager/locationtrail/inc/clocationwrite.h
locationmanager/locationtrail/inc/cnetworkinfo.h
locationmanager/locationtrail/inc/cpositioninfo.h
locationmanager/locationtrail/inc/ctracklog.h
locationmanager/locationtrail/inc/locationremappingao.h
locationmanager/locationtrail/inc/locationtraildefs.h
locationmanager/locationtrail/src/cgpxconverterao.cpp
locationmanager/locationtrail/src/clocationrecord.cpp
locationmanager/locationtrail/src/cnetworkinfo.cpp
locationmanager/locationtrail/src/cpositioninfo.cpp
locationmanager/locationtrail/src/ctracklog.cpp
locationmanager/locationtrail/src/locationremappingao.cpp
locationmanager/server/group/bld.inf
locationmanager/server/group/locationmanagerserver.mmp
locationmanager/server/inc/clocationmanagerserver.h
locationmanager/server/inc/clocationmanagersession.h
locationmanager/server/src/clocationmanagerserver.cpp
locationmanager/server/src/clocationmanagersession.cpp
locationmanager/sis/build-sisx.bat
locationmanager/sis/build-sisx_debug.bat
locationmanager/sis/depends.xml
locationmanager/sis/locationmanager_stub.sis
locationmanager/sis/locutil.pkg
locationmanager/sis/locutildebug.pkg
locationmanager/sis/package.pkg
locationmanager/sis/stub.pkg
mds_plat/content_listing_framework_collection_manager_api/content_listing_framework_collection_manager_api.metaxml
mds_plat/content_listing_framework_collection_manager_api/group/bld.inf
mds_plat/content_listing_framework_collection_manager_api/inc/mediacollectionmanager.h
mds_plat/content_listing_framework_collection_manager_api/tsrc/Bmarm/CollectionMangerTestU.DEF
mds_plat/content_listing_framework_collection_manager_api/tsrc/Bwins/CollectionManagerTestU.DEF
mds_plat/content_listing_framework_collection_manager_api/tsrc/conf/CollectionManagerTest.cfg
mds_plat/content_listing_framework_collection_manager_api/tsrc/eabi/CollectionManagerTestu.def
mds_plat/content_listing_framework_collection_manager_api/tsrc/group/CollectionManagerTest.mmp
mds_plat/content_listing_framework_collection_manager_api/tsrc/group/CollectionManagerTest.pkg
mds_plat/content_listing_framework_collection_manager_api/tsrc/group/bld.inf
mds_plat/content_listing_framework_collection_manager_api/tsrc/inc/CollectionManagerTest.h
mds_plat/content_listing_framework_collection_manager_api/tsrc/init/CollectionManagerTest.ini
mds_plat/content_listing_framework_collection_manager_api/tsrc/src/CollectionManagerTest.cpp
mds_plat/content_listing_framework_collection_manager_api/tsrc/src/CollectionManagerTestBlocks.cpp
mds_plat/content_listing_framework_extended_api/content_listing_framework_extended_api.metaxml
mds_plat/content_listing_framework_extended_api/group/bld.inf
mds_plat/content_listing_framework_extended_api/inc/CLFContentListingExtended.hrh
mds_plat/context_engine_plugin_api/context_engine_plugin_api.metaxml
mds_plat/context_engine_plugin_api/group/bld.inf
mds_plat/context_engine_plugin_api/inc/contextengine.h
mds_plat/context_engine_plugin_api/inc/contextplugin.h
mds_plat/context_engine_plugin_api/tsrc/Bmarm/ContextEnginePluginTestU.DEF
mds_plat/context_engine_plugin_api/tsrc/Bwins/ContextEnginePluginTestU.DEF
mds_plat/context_engine_plugin_api/tsrc/EABI/ContextEnginePluginTestU.def
mds_plat/context_engine_plugin_api/tsrc/conf/ContextEnginePluginTest.cfg
mds_plat/context_engine_plugin_api/tsrc/data/mmc/ContextEnginePluginTest/Animated.gif
mds_plat/context_engine_plugin_api/tsrc/data/mmc/ContextEnginePluginTest/H263.3gp
mds_plat/context_engine_plugin_api/tsrc/data/mmc/ContextEnginePluginTest/Jpg.jpg
mds_plat/context_engine_plugin_api/tsrc/data/mmc/ContextEnginePluginTest/Thumbs.db
mds_plat/context_engine_plugin_api/tsrc/group/ContextEnginePluginTest.mmp
mds_plat/context_engine_plugin_api/tsrc/group/ContextEnginePluginTest.pkg
mds_plat/context_engine_plugin_api/tsrc/group/bld.inf
mds_plat/context_engine_plugin_api/tsrc/inc/ContextEnginePluginTest.h
mds_plat/context_engine_plugin_api/tsrc/init/ContextEnginePluginTest.ini
mds_plat/context_engine_plugin_api/tsrc/src/ContextEnginePluginTest.cpp
mds_plat/context_engine_plugin_api/tsrc/src/ContextEnginePluginTestBlocks.cpp
mds_plat/group/bld.inf
mds_plat/harvester_framework_api/group/bld.inf
mds_plat/harvester_framework_api/harvester_framework_api.metaxml
mds_plat/harvester_framework_api/inc/composerplugin.h
mds_plat/harvester_framework_api/inc/harvesterclient.h
mds_plat/harvester_framework_api/inc/harvesterclientdata.h
mds_plat/harvester_framework_api/inc/harvesterdata.h
mds_plat/harvester_framework_api/inc/harvestereventenum.h
mds_plat/harvester_framework_api/inc/harvesterpauseps.h
mds_plat/harvester_framework_api/inc/harvesterplugin.h
mds_plat/harvester_framework_api/inc/monitorplugin.h
mds_plat/harvester_framework_api/inc/placeholderdata.h
mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/Bmarm/ComposerPluginTestU.DEF
mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/Bwins/ComposerPluginTestU.DEF
mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/EABI/ComposerPluginTestU.def
mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/conf/ComposerPluginTest.cfg
mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/group/ComposerPluginTest.mmp
mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/group/ComposerPluginTest.pkg
mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/group/bld.inf
mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/inc/ComposerPluginTest.h
mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/init/ComposerPluginTest.ini
mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/src/ComposerPluginTest.cpp
mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/src/ComposerPluginTestBlocks.cpp
mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/Bmarm/HarvesterClientTestScripterU.DEF
mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/Bwins/HarvesterClientTestScripterU.DEF
mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/EABI/HarvesterClientTestScripterU.def
mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/conf/HarvesterClientTestScripter.cfg
mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/group/HarvesterClientTestScripter.mmp
mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/group/HarvesterClientTestScripter.pkg
mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/group/bld.inf
mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/inc/HarvesterClientTestScripter.h
mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/init/HarvesterClientTestScripter.ini
mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/src/HarvesterClientTestScripter.cpp
mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/src/HarvesterClientTestScripterBlocks.cpp
mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/Bmarm/HarvesterDataTestU.DEF
mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/Bwins/HarvesterDataTestU.DEF
mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/EABI/HarvesterDataTestU.def
mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/conf/HarvesterDataTest.cfg
mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/group/HarvesterDataTest.mmp
mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/group/HarvesterDataTest.pkg
mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/group/bld.inf
mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/inc/HarvesterDataTest.h
mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/init/HarvesterDataTest.ini
mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/src/HarvesterDataTest.cpp
mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/src/HarvesterDataTestBlocks.cpp
mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/Bmarm/HarvesterPluginTestU.DEF
mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/Bwins/HarvesterPluginTestU.DEF
mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/EABI/HarvesterPluginTestU.def
mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/conf/HarvesterPluginTest.cfg
mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/group/HarvesterPluginTest.mmp
mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/group/HarvesterPluginTest.pkg
mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/group/bld.inf
mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/inc/HarvesterPluginTest.h
mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/init/HarvesterPluginTest.ini
mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/src/HarvesterPluginTest.cpp
mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/src/HarvesterPluginTestBlocks.cpp
mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/Bmarm/MonitorPluginTestU.DEF
mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/Bwins/MonitorPluginTestU.DEF
mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/EABI/MonitorPluginTestU.def
mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/conf/MonitorPluginTest.cfg
mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/group/MonitorPluginTest.mmp
mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/group/MonitorPluginTest.pkg
mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/group/bld.inf
mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/inc/MonitorPluginTest.h
mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/init/MonitorPluginTest.ini
mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/src/MonitorPluginTest.cpp
mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/src/MonitorPluginTestBlocks.cpp
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/00001.mp3
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Animated.gif
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/G31D.TIF
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/G4.TIF
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/GIF87testimage.gif
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/H263.3gp
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Jpg.jpg
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Liverpool.jpg
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/MBMtestimage.mbm
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/MPEG4.3gp
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/MPEG4.mp4
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Mbm.mbm
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/PNGtestimage.png
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/PSRETRO.WMF
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Temp1.jpg
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Temp2.jpg
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Temp3.jpg
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/bmp_burst.bmp
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/gif89a_onemeg.gif
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/ota_bmpiso.ota
mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/wbmp_skull.wbmp
mds_plat/harvester_framework_api/tsrc/group/bld.inf
mds_plat/location_manager_api/group/bld.inf
mds_plat/location_manager_api/inc/locationdatatype.h
mds_plat/location_manager_api/inc/locationeventdef.h
mds_plat/location_manager_api/inc/locationtrailpskeys.h
mds_plat/location_manager_api/inc/rlocationmanager.h
mds_plat/location_manager_api/inc/rlocationobjectmanipulator.h
mds_plat/location_manager_api/inc/rlocationtrail.h
mds_plat/location_manager_api/inc/rtracklog.h
mds_plat/location_manager_api/location_manager_api.metaxml
mds_plat/location_manager_api/tsrc/Bmarm/LocationManagerTestScripterU.DEF
mds_plat/location_manager_api/tsrc/Bwins/LocationManagerTestScripterU.DEF
mds_plat/location_manager_api/tsrc/EABI/LocationManagerTestScripterU.def
mds_plat/location_manager_api/tsrc/conf/LocationManagerTestScripter.cfg
mds_plat/location_manager_api/tsrc/group/LocationManagerTestScripter.mmp
mds_plat/location_manager_api/tsrc/group/LocationManagerTestScripter.pkg
mds_plat/location_manager_api/tsrc/group/bld.inf
mds_plat/location_manager_api/tsrc/inc/LocationManagerTestScripter.h
mds_plat/location_manager_api/tsrc/init/LocationManagerTestScripter.ini
mds_plat/location_manager_api/tsrc/src/LocationManagerTestScripter.cpp
mds_plat/location_manager_api/tsrc/src/LocationManagerTestScripterBlocks.cpp
mds_plat/location_manager_api/tsrc/src/RLocationObjectManipulatorTest.cpp
mds_plat/location_manager_api/tsrc/src/RTrackLogTest.cpp
mds_plat/metadata_engine_api/group/bld.inf
mds_plat/metadata_engine_api/inc/mdccommon.h
mds_plat/metadata_engine_api/inc/mdeboolpropertycondition.h
mds_plat/metadata_engine_api/inc/mdecondition.h
mds_plat/metadata_engine_api/inc/mdeconstants.h
mds_plat/metadata_engine_api/inc/mdedatabuffer.h
mds_plat/metadata_engine_api/inc/mdeerror.h
mds_plat/metadata_engine_api/inc/mdeevent.h
mds_plat/metadata_engine_api/inc/mdeeventcondition.h
mds_plat/metadata_engine_api/inc/mdeeventdef.h
mds_plat/metadata_engine_api/inc/mdeeventquery.h
mds_plat/metadata_engine_api/inc/mdeinstanceitem.h
mds_plat/metadata_engine_api/inc/mdeinternalerror.h
mds_plat/metadata_engine_api/inc/mdeitem.h
mds_plat/metadata_engine_api/inc/mdelogiccondition.h
mds_plat/metadata_engine_api/inc/mdenamespacedef.h
mds_plat/metadata_engine_api/inc/mdenumberproperty.h
mds_plat/metadata_engine_api/inc/mdenumberproperty.inl
mds_plat/metadata_engine_api/inc/mdeobject.h
mds_plat/metadata_engine_api/inc/mdeobjectcondition.h
mds_plat/metadata_engine_api/inc/mdeobjectdef.h
mds_plat/metadata_engine_api/inc/mdeobjectquery.h
mds_plat/metadata_engine_api/inc/mdeorderrule.h
mds_plat/metadata_engine_api/inc/mdeproperty.h
mds_plat/metadata_engine_api/inc/mdepropertycondition.h
mds_plat/metadata_engine_api/inc/mdepropertydef.h
mds_plat/metadata_engine_api/inc/mdequery.h
mds_plat/metadata_engine_api/inc/mderange.h
mds_plat/metadata_engine_api/inc/mderange.inl
mds_plat/metadata_engine_api/inc/mderangepropertycondition.h
mds_plat/metadata_engine_api/inc/mderelation.h
mds_plat/metadata_engine_api/inc/mderelationcondition.h
mds_plat/metadata_engine_api/inc/mderelationdef.h
mds_plat/metadata_engine_api/inc/mderelationquery.h
mds_plat/metadata_engine_api/inc/mdesession.h
mds_plat/metadata_engine_api/inc/mdetextproperty.h
mds_plat/metadata_engine_api/inc/mdetextproperty.inl
mds_plat/metadata_engine_api/inc/mdetextpropertycondition.h
mds_plat/metadata_engine_api/inc/mdeversioncenrepkey.h
mds_plat/metadata_engine_api/metadata_engine_api.metaxml
mds_plat/metadata_engine_api/tsrc/Bmarm/MdETestScripterU.DEF
mds_plat/metadata_engine_api/tsrc/Bwins/MdETestScripterU.DEF
mds_plat/metadata_engine_api/tsrc/EABI/MdETestScripterU.def
mds_plat/metadata_engine_api/tsrc/conf/MdETestScripter.cfg
mds_plat/metadata_engine_api/tsrc/data/mmc/MDETestScripterSchema.mde
mds_plat/metadata_engine_api/tsrc/data/mmc/MDETestScripterSchema2.mde
mds_plat/metadata_engine_api/tsrc/data/mmc/MdETestScripterImportMetadata.mde
mds_plat/metadata_engine_api/tsrc/data/mmc/test26video1.3gp
mds_plat/metadata_engine_api/tsrc/data/mmc/test2video1.3gp
mds_plat/metadata_engine_api/tsrc/data/mmc/test2video2.mp4
mds_plat/metadata_engine_api/tsrc/data/mmc/test3video1.3gp
mds_plat/metadata_engine_api/tsrc/data/mmc/test3video2.mp4
mds_plat/metadata_engine_api/tsrc/data/mmc/test4video1.3gp
mds_plat/metadata_engine_api/tsrc/data/mmc/test4video2
mds_plat/metadata_engine_api/tsrc/data/mmc/testvideo1.3gp
mds_plat/metadata_engine_api/tsrc/data/mmc/testvideo2.mp4
mds_plat/metadata_engine_api/tsrc/group/MdETestScripter.mmp
mds_plat/metadata_engine_api/tsrc/group/MdETestScripter.pkg
mds_plat/metadata_engine_api/tsrc/group/bld.inf
mds_plat/metadata_engine_api/tsrc/inc/MdETestScripter.h
mds_plat/metadata_engine_api/tsrc/inc/MdETestScripterAO.h
mds_plat/metadata_engine_api/tsrc/init/MdETestScripter.ini
mds_plat/metadata_engine_api/tsrc/src/MdETestScripter.cpp
mds_plat/metadata_engine_api/tsrc/src/MdETestScripterAO.cpp
mds_plat/metadata_engine_api/tsrc/src/MdETestScripterBlocks.cpp
mds_plat/metadata_engine_api/tsrc/src/MdETestScripterEditCommands.cpp
mds_plat/metadata_engine_api/tsrc/src/MdETestScripterQueryCommands.cpp
mds_plat/metadata_engine_api/tsrc/src/MdETestScripterSchemaCommands.cpp
mds_pub/content_listing_framework_api/content_listing_framework_api.metaxml
mds_pub/content_listing_framework_api/group/bld.inf
mds_pub/content_listing_framework_api/inc/CLFContentListing.h
mds_pub/content_listing_framework_api/inc/CLFContentListing.hrh
mds_pub/content_listing_framework_api/inc/CLFContentListing.rh
mds_pub/content_listing_framework_api/inc/ContentListingFactory.h
mds_pub/content_listing_framework_api/inc/MCLFChangedItemObserver.h
mds_pub/content_listing_framework_api/inc/MCLFContentListingEngine.h
mds_pub/content_listing_framework_api/inc/MCLFCustomGrouper.h
mds_pub/content_listing_framework_api/inc/MCLFCustomSorter.h
mds_pub/content_listing_framework_api/inc/MCLFItem.h
mds_pub/content_listing_framework_api/inc/MCLFItemListModel.h
mds_pub/content_listing_framework_api/inc/MCLFModifiableItem.h
mds_pub/content_listing_framework_api/inc/MCLFOperationObserver.h
mds_pub/content_listing_framework_api/inc/MCLFPostFilter.h
mds_pub/content_listing_framework_api/inc/MCLFProcessObserver.h
mds_pub/content_listing_framework_api/inc/MCLFSortingStyle.h
mds_pub/content_listing_framework_api/tsrc/bwins/T_CLFApiMdlTestu.def
mds_pub/content_listing_framework_api/tsrc/custom/preset_custom.xml
mds_pub/content_listing_framework_api/tsrc/eabi/T_CLFApiMdlTestu.def
mds_pub/content_listing_framework_api/tsrc/group/T_ContentListingFramework.mmp
mds_pub/content_listing_framework_api/tsrc/group/T_ContentListingFramework.pkg
mds_pub/content_listing_framework_api/tsrc/group/bld.inf
mds_pub/content_listing_framework_api/tsrc/inc/T_CLFApiModuleTests.h
mds_pub/content_listing_framework_api/tsrc/src/CreateTestSuite.cpp
mds_pub/content_listing_framework_api/tsrc/src/T_CLFApiModuleTests.cpp
mds_pub/content_listing_framework_api/tsrc/src/T_ContentListingFramework.rss
mds_pub/group/bld.inf
metadataengine/client/bwincw/mdeclientu.def
metadataengine/client/eabi/mdeclientu.def
metadataengine/client/group/bld.inf
metadataengine/client/group/mdeclient.mmp
metadataengine/client/inc/mdeasynchronousfindao.h
metadataengine/client/inc/mdeengine.pan
metadataengine/client/inc/mdeenginesession.h
metadataengine/client/inc/mdenotifierao.h
metadataengine/client/inc/mdequerycriteriaserialization.h
metadataengine/client/inc/mdequeryimpl.h
metadataengine/client/inc/mdesessionimpl.h
metadataengine/client/inc/mdesessionstartupao.h
metadataengine/client/src/mde.cpp
metadataengine/client/src/mdeasynchronousfindao.cpp
metadataengine/client/src/mdeboolpropertycondition.cpp
metadataengine/client/src/mdecondition.cpp
metadataengine/client/src/mdedatabuffer.cpp
metadataengine/client/src/mdeenginesession.cpp
metadataengine/client/src/mdeevent.cpp
metadataengine/client/src/mdeeventcondition.cpp
metadataengine/client/src/mdeeventdef.cpp
metadataengine/client/src/mdeeventquery.cpp
metadataengine/client/src/mdeharvestersession.cpp
metadataengine/client/src/mdeinstanceitem.cpp
metadataengine/client/src/mdeitem.cpp
metadataengine/client/src/mdelogiccondition.cpp
metadataengine/client/src/mdenamespacedef.cpp
metadataengine/client/src/mdenotifierao.cpp
metadataengine/client/src/mdeobject.cpp
metadataengine/client/src/mdeobjectcondition.cpp
metadataengine/client/src/mdeobjectdef.cpp
metadataengine/client/src/mdeobjectquery.cpp
metadataengine/client/src/mdeorderrule.cpp
metadataengine/client/src/mdepanic.cpp
metadataengine/client/src/mdeproperty.cpp
metadataengine/client/src/mdepropertycondition.cpp
metadataengine/client/src/mdepropertydef.cpp
metadataengine/client/src/mdequery.cpp
metadataengine/client/src/mdequerycriteriaserialization.cpp
metadataengine/client/src/mdequeryimpl.cpp
metadataengine/client/src/mderange.cpp
metadataengine/client/src/mderangepropertycondition.cpp
metadataengine/client/src/mderelation.cpp
metadataengine/client/src/mderelationcondition.cpp
metadataengine/client/src/mderelationdef.cpp
metadataengine/client/src/mderelationquery.cpp
metadataengine/client/src/mdesession.cpp
metadataengine/client/src/mdesessionimpl.cpp
metadataengine/client/src/mdesessionstartupao.cpp
metadataengine/client/src/mdetextpropertycondition.cpp
metadataengine/common/bwincw/mdccommonu.def
metadataengine/common/eabi/mdccommonu.def
metadataengine/common/group/bld.inf
metadataengine/common/group/mdccommon.mmp
metadataengine/common/src/mdccommon.cpp
metadataengine/common/src/mdcdef.cpp
metadataengine/common/src/mdcitem.cpp
metadataengine/common/src/mdcquery.cpp
metadataengine/common/src/mdcresult.cpp
metadataengine/common/src/mdcserializationbuffer.cpp
metadataengine/data/200009F3.txt
metadataengine/data/2000717d.rss
metadataengine/data/Create_STUB_SIS.bat
metadataengine/data/MdS_Server_settings.xml
metadataengine/data/MetadataEngine_Stub.pkg
metadataengine/data/MetadataEngine_Stub.sis
metadataengine/data/defaultimportfile.mde
metadataengine/data/metadataengine.pkg
metadataengine/data/schema.mde
metadataengine/group/bld.inf
metadataengine/group/mde_backup_registration.xml
metadataengine/server/group/bld.inf
metadataengine/server/group/mdsserver.mmp
metadataengine/server/inc/mdebackuprestoreobserver.h
metadataengine/server/inc/mdebackuprestorewatcher.h
metadataengine/server/inc/mdsclausebuffer.h
metadataengine/server/inc/mdsdbconnectionpool.h
metadataengine/server/inc/mdsdiskspacenotifier.h
metadataengine/server/inc/mdseventdef.h
metadataengine/server/inc/mdseventdef.inl
metadataengine/server/inc/mdsfindengine.h
metadataengine/server/inc/mdsfindsequence.h
metadataengine/server/inc/mdsfindsqlclause.h
metadataengine/server/inc/mdsfindsqlclausedef.h
metadataengine/server/inc/mdsgarbagecollector.h
metadataengine/server/inc/mdsgetimeiao.h
metadataengine/server/inc/mdsimportexport.h
metadataengine/server/inc/mdsindexer.h
metadataengine/server/inc/mdsitemdef.h
metadataengine/server/inc/mdsitemdef.inl
metadataengine/server/inc/mdslogger.h
metadataengine/server/inc/mdslogger.inl
metadataengine/server/inc/mdsmaintenanceengine.h
metadataengine/server/inc/mdsmanipulationengine.h
metadataengine/server/inc/mdsnamespacedef.h
metadataengine/server/inc/mdsnamespacedef.inl
metadataengine/server/inc/mdsnotifier.h
metadataengine/server/inc/mdsnotifycomparator.h
metadataengine/server/inc/mdsobjectdef.h
metadataengine/server/inc/mdsobjectdef.inl
metadataengine/server/inc/mdsobjectlocklist.h
metadataengine/server/inc/mdspreferences.h
metadataengine/server/inc/mdspropertydef.h
metadataengine/server/inc/mdspropertydef.inl
metadataengine/server/inc/mdsquerycriteriadeserialization.h
metadataengine/server/inc/mdsrelationdef.h
metadataengine/server/inc/mdsrelationdef.inl
metadataengine/server/inc/mdsschema.h
metadataengine/server/inc/mdsserver.h
metadataengine/server/inc/mdsserversession.h
metadataengine/server/inc/mdsshutdownobserver.h
metadataengine/server/inc/mdssqldbmaintenance.h
metadataengine/server/inc/mdssqlfindoperation.h
metadataengine/server/inc/mdssqlobjectmanipulate.h
metadataengine/server/inc/mdssqlobjectmanipulate.inl
metadataengine/server/src/mdebackuprestorewatcher.cpp
metadataengine/server/src/mdsclausebuffer.cpp
metadataengine/server/src/mdsdbconnectionpool.cpp
metadataengine/server/src/mdsdiskspacenotifier.cpp
metadataengine/server/src/mdseventdef.cpp
metadataengine/server/src/mdsfindengine.cpp
metadataengine/server/src/mdsfindsequence.cpp
metadataengine/server/src/mdsfindsqlclause.cpp
metadataengine/server/src/mdsgarbagecollector.cpp
metadataengine/server/src/mdsgetimeiao.cpp
metadataengine/server/src/mdsimportexport.cpp
metadataengine/server/src/mdsindexer.cpp
metadataengine/server/src/mdsitemdef.cpp
metadataengine/server/src/mdslogger.cpp
metadataengine/server/src/mdsmaintenanceengine.cpp
metadataengine/server/src/mdsmanipulationengine.cpp
metadataengine/server/src/mdsnamespacedef.cpp
metadataengine/server/src/mdsnotifier.cpp
metadataengine/server/src/mdsnotifycomparator.cpp
metadataengine/server/src/mdsobjectdef.cpp
metadataengine/server/src/mdsobjectlocklist.cpp
metadataengine/server/src/mdspreferences.cpp
metadataengine/server/src/mdspropertydef.cpp
metadataengine/server/src/mdsquerycriteriadeserialization.cpp
metadataengine/server/src/mdsrelationdef.cpp
metadataengine/server/src/mdsschema.cpp
metadataengine/server/src/mdsserver.cpp
metadataengine/server/src/mdsserversession.cpp
metadataengine/server/src/mdsshutdownobserver.cpp
metadataengine/server/src/mdssqldbmaintenance.cpp
metadataengine/server/src/mdssqlfindoperation.cpp
metadataengine/server/src/mdssqliteconnection.cpp
metadataengine/server/src/mdssqlobjectmanipulate.cpp
metadataengine/sis/depends.xml
metadataengine/sis/metadataengine_stub.sis
metadataengine/sis/package.pkg
metadataengine/sis/stub.pkg
package_definition.xml
rom/ContentListingFramework.iby
rom/mds.iby
rom/mds_testers.iby
sis/mds/depends.xml
sis/mds/mds_stub.sis
sis/mds/package.pkg
sis/mds/package_separate.pkg
sis/mds/stub.pkg
sis/mdscenrep/depends.xml
sis/mdscenrep/package.pkg
sysdef_1_4_0.dtd
watchdog/group/bld.inf
watchdog/group/watchdog.mmp
watchdog/inc/watchdog.h
watchdog/inc/wdselfshutdownobserver.h
watchdog/inc/wdshutdownobserver.h
watchdog/sis/depends.xml
watchdog/sis/mdswatchdog_stub.sis
watchdog/sis/stub.pkg
watchdog/src/watchdog.cpp
watchdog/src/wdselfshutdownobserver.cpp
watchdog/src/wdshutdownobserver.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/BWINS/CONTENTLISTINGFRAMEWORKU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,6 @@
+EXPORTS
+	?NewContentListingEngineLC@ContentListingFactory@@SAPAVMCLFContentListingEngine@@XZ @ 1 NONAME ; public: static class MCLFContentListingEngine * __cdecl ContentListingFactory::NewContentListingEngineLC(void)
+	?NewModifiableItemLC@ContentListingFactory@@SAPAVMCLFModifiableItem@@XZ @ 2 NONAME ; public: static class MCLFModifiableItem * __cdecl ContentListingFactory::NewModifiableItemLC(void)
+	?NewSortingStyleLC@ContentListingFactory@@SAPAVMCLFSortingStyle@@AAVTResourceReader@@@Z @ 3 NONAME ; public: static class MCLFSortingStyle * __cdecl ContentListingFactory::NewSortingStyleLC(class TResourceReader &)
+	?NewSortingStyleLC@ContentListingFactory@@SAPAVMCLFSortingStyle@@XZ @ 4 NONAME ; public: static class MCLFSortingStyle * __cdecl ContentListingFactory::NewSortingStyleLC(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/BWINS/MediaCollectionManagerU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?CreateCollectionManagerL@MediaCollectionManagerFactory@@SAPAVMMediaCollectionManager@@XZ @ 1 NONAME ; class MMediaCollectionManager * MediaCollectionManagerFactory::CreateCollectionManagerL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFDbItemContainer.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,243 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCLFDbItemContainer.h"
+#include    <mdeobject.h> 
+#include    <f32file.h>
+#include    "CLFPanics.h"
+
+const TInt KCLFContainerArrayGranularity( 25 );
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCLFContainerItem::CCLFContainerItem
+// -----------------------------------------------------------------------------
+//
+CCLFContainerItem::CCLFContainerItem( const CMdEObject* aObject )
+    : iReferenceCount( 0 ), iMdEObject( aObject ), iDeprecated( EFalse ),
+      iItemId( aObject->Id() )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFContainerItem::CCLFContainerItem
+// -----------------------------------------------------------------------------
+//
+CCLFContainerItem::CCLFContainerItem()
+    : iReferenceCount( 0 ), iMdEObject( NULL ), iDeprecated( EFalse ),
+      iItemId( 0 )
+	{
+	}
+
+// -----------------------------------------------------------------------------
+// CCLFContainerItem::NewLC
+// -----------------------------------------------------------------------------
+//
+CCLFContainerItem* CCLFContainerItem::NewLC( const CMdEObject* aObject )
+    {
+    CCLFContainerItem* self = new ( ELeave ) CCLFContainerItem( aObject );
+    CleanupStack::PushL( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFContainerItem::~CCLFContainerItem
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCLFContainerItem::~CCLFContainerItem()
+    {
+    delete iMdEObject;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFContainerItem::Compare
+// -----------------------------------------------------------------------------
+//
+TInt CCLFContainerItem::Compare( const CCLFContainerItem& aFirst,
+					             const CCLFContainerItem& aSecond )
+	{
+	return aFirst.iItemId - aSecond.iItemId;
+	}
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemContainer::TFindHelper::TFindHelper
+// -----------------------------------------------------------------------------
+//
+CCLFDbItemContainer::TFindHelper::TFindHelper()
+    : iItemId( 0 ), 
+      iIndex( 0 )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemContainer::TFindHelper::Reset
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemContainer::TFindHelper::Reset()
+    {
+    iItemId = 0;
+    iIndex = 0;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemContainer::TFindHelper::Set
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemContainer::TFindHelper::Set( TCLFItemId aItemId, 
+                                                   TInt aIndex )
+    {
+    iItemId = aItemId;
+    iIndex = aIndex;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemContainer::CCLFDbItemContainer
+// -----------------------------------------------------------------------------
+//
+CCLFDbItemContainer::CCLFDbItemContainer()
+    : iItemArray( KCLFContainerArrayGranularity ),
+      iArraySorter( CCLFContainerItem::Compare )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemContainer::NewL
+// -----------------------------------------------------------------------------
+//
+CCLFDbItemContainer* CCLFDbItemContainer::NewL()
+    {
+    return new( ELeave ) CCLFDbItemContainer;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemContainer::~CCLFDbItemContainer
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCLFDbItemContainer::~CCLFDbItemContainer()
+    {
+    iItemArray.ResetAndDestroy();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemContainer::ItemById
+// -----------------------------------------------------------------------------
+//
+CCLFContainerItem* CCLFDbItemContainer::ItemById( const TCLFItemId aItemId ) const
+    {
+    CCLFContainerItem* item = NULL;
+    TInt index( FindItem( aItemId, item ) );
+    while ( index >= 0 )
+        {
+		if( !( item->iDeprecated ) )
+			{
+			return item;
+			}
+        index = NextItem( item );
+        }
+    return NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemContainer::ReleaseItem
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemContainer::ReleaseItem( CCLFContainerItem* aItem )
+    {
+    const TInt index( iItemArray.Find( aItem ) );
+    if ( index >= 0 )
+        {
+        aItem->iReferenceCount--;
+        __ASSERT_DEBUG ( aItem->iReferenceCount >= 0,
+                         User::Panic( KCLFPanicText, ECLFNullPointer ) );
+        if ( aItem->iReferenceCount <= 0 )
+            {
+            iItemArray.Remove( index );
+            delete aItem;
+            aItem = NULL;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemContainer::SetDeprecatedItems
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemContainer::SetDeprecatedItems(
+                                    const RArray<TCLFItemId>& aItemIdArray )
+    {
+    const TInt count( aItemIdArray.Count() );
+    for ( TInt i = 0 ; i < count ; ++i )
+        {
+        CCLFContainerItem* item = NULL;
+        TInt index( FindItem( aItemIdArray[i], item ) );
+        while ( index >= 0 )
+            {
+            item->iDeprecated = ETrue;
+            index = NextItem( item );
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemContainer::FindItem
+// -----------------------------------------------------------------------------
+//
+TInt CCLFDbItemContainer::FindItem( TCLFItemId aItemId, 
+                                    CCLFContainerItem*& aItem ) const
+    {
+    iFindHelper.Reset();
+	iFindItem.SetItemId( aItemId );
+    const TInt index ( iItemArray.SpecificFindInOrder( 
+                                        &iFindItem, 
+                                        iArraySorter, 
+                                        EArrayFindMode_First ) );
+	if ( index >= 0 )
+		{
+    	iFindHelper.Set( aItemId, index );
+		aItem = iItemArray[index];
+		return index;
+		}
+    return KErrNotFound;
+    
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemContainer::NextItem
+// -----------------------------------------------------------------------------
+//
+TInt CCLFDbItemContainer::NextItem( CCLFContainerItem*& aItem ) const
+    {
+    const TInt count( iItemArray.Count() );
+    if ( iFindHelper.iIndex < count )
+        {
+        CCLFContainerItem* item = iItemArray[ iFindHelper.iIndex ];
+        if ( iFindHelper.iItemId == item->iItemId )
+            {
+            iFindHelper.iIndex++;
+            aItem = item;
+            return iFindHelper.iIndex - 1;
+            }
+        }
+    return KErrNotFound;
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFDbItemContainer.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,192 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef CCLFDBITEMCONTAINER_H
+#define CCLFDBITEMCONTAINER_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <CLFContentListing.h>
+
+// FORWARD DECLARATIONS
+
+class CMdEObject;
+class CCLFContainerItem;
+
+// CLASS DECLARATION
+
+/**
+*  Container item.
+*
+*  @lib ContentListingFramework.lib
+*  @since S60 3.0
+*/
+NONSHARABLE_CLASS( CCLFContainerItem ) : public CBase
+    {
+    public:
+
+        /**
+        * Two-phased constructor.
+        */    
+        static CCLFContainerItem* NewLC( const CMdEObject* aObject );
+
+        /**
+        * Destructor
+        */
+        virtual ~CCLFContainerItem();
+
+    public:
+
+        /**
+        * Increase reference count of item
+        * @since S60 3.0
+        */
+        inline void IncreaseReferenceCount();
+
+        /**
+        *
+        * @since S60 3.0
+        * @return ref. to DB item
+        */
+        inline const CMdEObject& DbItem() const;
+
+    protected:
+
+        /**
+        * For find in order
+        */
+        static TInt Compare( const CCLFContainerItem& aFirst,
+                             const CCLFContainerItem& aSecond );
+
+        /**
+        * For find in order
+        */
+        inline void SetItemId( TCLFItemId aItemId );
+
+    private:
+
+        /**
+        * Constructors
+        */    
+        CCLFContainerItem( const CMdEObject* aObject );
+
+        CCLFContainerItem();
+
+    private: // data
+
+        // friend classes
+        friend class CCLFDbItemContainer;   // CSI: 36 #  36:Use of friends
+        
+        TInt iReferenceCount;
+        const CMdEObject* iMdEObject; //own
+        TBool iDeprecated;
+        TCLFItemId iItemId;
+    };
+
+/**
+*  DBItem container.
+*
+*  @lib ContentListingFramework.lib
+*  @since S60 3.0
+*/
+NONSHARABLE_CLASS( CCLFDbItemContainer ) : public CBase
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCLFDbItemContainer* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCLFDbItemContainer();
+
+    public:
+
+        /**
+        * @since S60 3.0
+        * @param aItemId
+        * @return Container item by CLF item id, if item is not found in
+        *         conter then NULL pointer is returned
+        */
+        CCLFContainerItem* ItemById( const TCLFItemId aItemId ) const;
+
+        /**
+        * Decrease referency count for item and deletes container item and DB item
+        * @since S60 3.0
+        * @param aItem
+        */
+        void ReleaseItem( CCLFContainerItem* aItem );
+
+        /**
+        * Add container item to container.
+        * @since S60 3.0
+        * @param aItem
+        */
+        inline void AddL( CCLFContainerItem* aItem );
+
+        /**
+        *
+        * @since S60 3.0
+        * @param aItemIdArray
+        */
+        void SetDeprecatedItems( const RArray<TCLFItemId>& aItemIdArray );
+
+    protected:
+
+        TInt FindItem( TCLFItemId aItemId, CCLFContainerItem*& aItem ) const;
+        TInt NextItem( CCLFContainerItem*& aItem ) const;
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CCLFDbItemContainer();
+
+    private:
+    
+        class TFindHelper
+            {
+            public:
+                TFindHelper();
+                void Reset();
+                void Set( TCLFItemId aItemId, TInt aIndex );
+
+            public:    
+                TCLFItemId iItemId;
+                TInt iIndex;
+            };
+
+    private:    // Data
+
+        RPointerArray<CCLFContainerItem> iItemArray;
+
+        TLinearOrder<CCLFContainerItem> iArraySorter;
+        mutable CCLFContainerItem iFindItem;
+        mutable TFindHelper iFindHelper;
+    };
+
+// inline functions
+#include "CCLFDbItemContainer.inl"
+
+#endif      // CCLFDBITEMCONTAINER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFDbItemContainer.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemContainer::AppendL
+// -----------------------------------------------------------------------------
+//
+inline void CCLFDbItemContainer::AddL( CCLFContainerItem* aItem )
+    {
+    // there could be debricated items 
+    iItemArray.InsertInOrderAllowRepeatsL( aItem, iArraySorter );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFContainerItem::IncreaseReferenceCount
+// -----------------------------------------------------------------------------
+//
+inline void CCLFContainerItem::IncreaseReferenceCount()
+    {
+    ++iReferenceCount;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFContainerItem::DbItem
+// -----------------------------------------------------------------------------
+//
+inline const CMdEObject& CCLFContainerItem::DbItem() const
+    {
+    return *iMdEObject;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFContainerItem::SetItemId
+// -----------------------------------------------------------------------------
+//
+inline void CCLFContainerItem::SetItemId( TCLFItemId aItemId )
+    {
+    iItemId = aItemId;
+    }
+    
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFDbItemProvider.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,409 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCLFDbItemProvider.h"
+#include    "CCLFItemImpl.h"
+#include    "MCLFItemProviderObserver.h"
+#include    "CCLFDbItemContainer.h"
+#include    "CLFPanics.h"
+#include    "MGDebugPrint.h"
+#include    "CCLFQueryAdapter.h"
+#include    "CLFUtils.h"
+#include    <mdeobjectquery.h>
+#include    <mdeconstants.h>
+
+const TInt KCLFItemArrayGranularity( 25 );
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::CCLFDbItemProvider
+// -----------------------------------------------------------------------------
+//
+CCLFDbItemProvider::CCLFDbItemProvider( CCLFDbItemContainer& aDbItemContainer,
+                                               CCLFQueryAdapter& aQueryAdapter, CMdESession* aMdESession )
+    : CActive( EPriorityStandard ),
+      iProviderState( EItemsReady ),
+      iObserver( NULL ),
+      iItemArray( KCLFItemArrayGranularity ),
+      iDbItemContainer( aDbItemContainer ),
+      iQueryAdapter( aQueryAdapter ),
+      iObjectQuery( NULL ),
+      iObjDefStr( &KNullDesC ),
+      iMdESession( aMdESession )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemProvider::ConstructL()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::NewL
+// -----------------------------------------------------------------------------
+//
+CCLFDbItemProvider* CCLFDbItemProvider::NewL( CCLFDbItemContainer& aDbItemContainer,
+                                              CCLFQueryAdapter& aQueryAdapter, CMdESession* aMdESession )
+    {
+    CCLFDbItemProvider* self = new( ELeave ) CCLFDbItemProvider( aDbItemContainer, 
+                                                                                                       aQueryAdapter, 
+                                                                                                       aMdESession );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::~CCLFDbItemProvider
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCLFDbItemProvider::~CCLFDbItemProvider()
+    {
+    Cancel();
+    delete iObjectQuery;
+    iItemArray.ResetAndDestroy();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::DoCancel
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemProvider::DoCancel()
+    {
+    MG_DEBUG1( dr1, "[CLF]\t CCLFDbItemProvider::DoCancel" ); 
+
+    if ( iObjectQuery )
+        {
+        iObjectQuery->Cancel();
+        }
+
+    iObjDefStr = &KNullDesC;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::RunL
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemProvider::RunL()
+    {
+    MG_DEBUG2( r1, "[CLF]\t CCLFDbItemProvider::RunL %d", iStatus.Int() );
+
+    TInt error( iStatus.Int() );
+    if ( error == KErrNone )
+        {
+        DoRunL();
+        }
+    if ( EItemsReady == iProviderState )
+        {
+        iObserver->OperationCompleteL( KErrNone );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::DoRunL
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemProvider::DoRunL()
+    {
+    switch ( iProviderState )
+        {
+        case EPrepareItemIds:
+            {
+            DoFetchMdSIdDataCachedL();
+            break;
+            }
+        case EPrepareItems:
+            {
+            DoFetchMdSDataL();
+            break;
+            }
+        default:
+            {
+            User::Leave( ECLFIncorrectCommand );
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::RunError
+// -----------------------------------------------------------------------------
+//
+TInt CCLFDbItemProvider::RunError( const TInt aError )
+    {
+    MG_DEBUG2( re1, "[CLF]\t CCLFDbItemProvider::RunError: %d", aError ); 
+
+    if ( (EItemsReady == iProviderState || aError) && iObserver )
+    	{
+        TRAP_IGNORE( iObserver->OperationCompleteL( aError ) );
+        }
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::PrepareItemsL
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemProvider::PrepareItemsL( const MDesCArray& aMimeTypeArray,
+                                        const TArray< TInt >& aMediaTypeArray,
+                                        MCLFItemProviderObserver& aObserver )
+    {
+    MG_DEBUG1( PI1, "[CLF]\t CCLFDbItemProvider::PrepareItemsL 1" ); 
+
+    Cancel();
+    iObserver = &aObserver;
+    iItemArray.ResetAndDestroy();
+
+    TBool image = EFalse;
+    TBool video = EFalse;
+    TBool audio = EFalse;
+    TBool other = EFalse;
+    
+    // find all mediatypes
+    const TInt typeCount( aMediaTypeArray.Count() );
+    for ( TInt i = 0; i < typeCount; i++ )
+        {
+        iObjDefStr = &KNullDesC;
+        iObjDefStr = &CLFUtils::MapClfType( aMediaTypeArray[ i ] );
+        
+        if (iObjDefStr->Compare(MdeConstants::Image::KImageObject) == 0)
+            {
+            image = ETrue;
+            }
+        else if (iObjDefStr->Compare(MdeConstants::Video::KVideoObject) == 0)
+            {
+            video = ETrue;
+            }
+        else if (iObjDefStr->Compare(MdeConstants::Audio::KAudioObject) == 0)
+            {
+            audio = ETrue;
+            }
+        else
+            {
+            other = ETrue;
+            }
+        }
+    
+    // images & videos (gallery)
+    if (image && video && !audio)
+        {
+        iObjDefStr = &MdeConstants::Object::KBaseObject;
+        }
+    // images
+    else if(image && !video && !audio && !other)
+        {
+        iObjDefStr = &MdeConstants::Image::KImageObject;
+        }
+    // videos
+    else if (!image && video && !audio && !other)
+        {
+        iObjDefStr = &MdeConstants::Video::KVideoObject;
+        }
+    // audio
+    else if (!image && !video && audio && !other)
+        {
+        iObjDefStr = &MdeConstants::Audio::KAudioObject;
+        }
+    // other
+    else
+        {
+        iObjDefStr = &MdeConstants::Object::KBaseObject;
+        }
+    
+    iProviderState = EPrepareItemIds;
+
+    delete iObjectQuery;
+    iObjectQuery = NULL;
+    iQueryAdapter.QueryMdEObjectsL( aMimeTypeArray, aMediaTypeArray, iObjectQuery, iStatus );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::PrepareItemsL
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemProvider::PrepareItemsL( const TArray< TCLFItemId >& aItemIDArray,
+                                        MCLFItemProviderObserver& aObserver )
+    {
+    MG_DEBUG1( PI1, "[CLF]\t CCLFDbItemProvider::PrepareItemsL 2" ); 
+
+    Cancel();
+    iObserver = &aObserver;
+    iItemArray.ResetAndDestroy();
+    iProviderState = EPrepareItems;
+
+    const TDesC& objDefStr = CLFUtils::MapClfType( ECLFMediaTypeUnknown );
+    delete iObjectQuery;
+    iObjectQuery = NULL;
+    iQueryAdapter.QueryMdEObjectsL( aItemIDArray, objDefStr, iObjectQuery, iStatus );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::GetItems
+// -----------------------------------------------------------------------------
+//
+TInt CCLFDbItemProvider::GetItems( RPointerArray< MCLFItem >& aItemArray )
+    {
+    MG_DEBUG1( df1, "[CLF]\t CCLFDbItemProvider::GetItems" ); 
+
+    const TInt KCLFItemIndex( 0 ); // do not change
+
+    while ( iItemArray.Count() )
+        {
+        const TInt error( aItemArray.Append(
+                            iItemArray[ KCLFItemIndex ] ) ); // takes ownership
+        if ( error )
+            {
+            return error;
+            }
+        iItemArray.Remove( KCLFItemIndex );
+        }
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::DoFetchMdSIdDataCachedL
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemProvider::DoFetchMdSIdDataCachedL()
+    {
+    MG_DEBUG1( df1, "[CLF]\t CCLFDbItemProvider::DoFetchMdSIdDataCachedL" ); 
+
+    RArray< TCLFItemId > itemIdArray;
+    CleanupClosePushL( itemIdArray );
+    DoFetchMdSIdDataL( itemIdArray );
+
+    // Check if items are in cache
+    TInt idCount( itemIdArray.Count() );
+    for ( TInt i = 0 ; i < idCount ; ++i )
+        {
+        CCLFContainerItem* containerItem = 
+                                iDbItemContainer.ItemById( itemIdArray[ i ] );
+        if ( containerItem )
+            {
+            // found in cache
+            CreateCLFItemL( *containerItem ); // reserve item for this model
+
+            // remove handled item ID
+            itemIdArray.Remove( i );
+            --i;
+            --idCount;
+            }
+        }
+    iProviderState = EPrepareItems;
+
+    delete iObjectQuery;
+    iObjectQuery = NULL;
+    iQueryAdapter.QueryMdEObjectsL( itemIdArray.Array(), *iObjDefStr, iObjectQuery, iStatus );
+    SetActive();
+    CleanupStack::PopAndDestroy( &itemIdArray );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::DoFetchMdSDataL
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemProvider::DoFetchMdSDataL()
+    {
+#ifdef _DEBUG
+    MG_DEBUG1( df1, "[CLF]\t CCLFDbItemProvider::DoFetchDataL" ); 
+    
+    _LIT( KCLFWIPPanicText, "DoFetchMdSDataL");
+    __ASSERT_DEBUG( iObjectQuery, User::Panic( KCLFWIPPanicText, KErrNotReady ));
+#endif
+
+    const TInt count( iObjectQuery->Count() );
+    for ( TInt index( 0 ); index < count; index++ )
+        {
+        const TInt64 id = (TInt64)iObjectQuery->ResultId( index );
+        CMdEObject* object = iMdESession->GetFullObjectL( id );
+        
+        if( !object )
+            {
+            continue;
+            }
+
+        // check if other model is already put this item to container
+        CCLFContainerItem* containerItem = 
+                                iDbItemContainer.ItemById( id );
+        if ( containerItem )
+            {
+            delete object;
+            object = NULL;
+            continue;
+            }
+        else
+            {
+            // create container item
+            containerItem = CCLFContainerItem::NewLC( object );
+
+            // append container item to container
+            // container takes ownership of container item
+            iDbItemContainer.AddL( containerItem );
+            CleanupStack::Pop( containerItem );
+            }
+        CreateCLFItemL( *containerItem );
+        }
+    iProviderState = EItemsReady;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::DoFetchMdSIdDataL
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemProvider::DoFetchMdSIdDataL( RArray< TCLFItemId >& aItemIDArray )
+    {
+#ifdef _DEBUG
+    MG_DEBUG1( df1, "[CLF]\t CCLFDbItemProvider::DoFetchDataL" ); 
+
+    _LIT( KCLWIPPanicString, "DoFetchMdSIdDataL" );
+    __ASSERT_DEBUG( iObjectQuery,
+                     User::Panic( KCLWIPPanicString, KErrAbort ));
+#endif
+
+    const TInt count( iObjectQuery->Count() );
+    for ( TInt index( 0 ); index < count; index++ )
+        {
+        aItemIDArray.AppendL( (TInt64)iObjectQuery->ResultId( index ));
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::CreateCLFItemL
+// -----------------------------------------------------------------------------
+//
+void CCLFDbItemProvider::CreateCLFItemL( CCLFContainerItem& aCItem )
+    {
+    MG_DEBUG1( cci1, "[CLF]\t CCLFDbItemProvider::CreateCLFItemL" ); 
+
+    // CLF item releases reference in destructor
+    CCLFItemImpl* item = CCLFItemImpl::NewLC( aCItem, iDbItemContainer );
+    iItemArray.AppendL( item ); // array takes ownership of the item
+    CleanupStack::Pop( item );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFDbItemProvider.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,153 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#ifndef CCLFDBITEMPROVIDER_H
+#define CCLFDBITEMPROVIDER_H
+
+//  INCLUDES
+#include <CLFContentListing.hrh>
+#include <CLFContentListing.h>
+#include <mdesession.h>
+#include <bamdesca.h>
+#include <e32base.h>
+
+// FORWARD DECLARATIONS
+class MCLFItem;
+class MCLFItemProviderObserver;
+class CCLFDbItemContainer;
+class CCLFContainerItem;
+class CCLFQueryAdapter;
+
+// CLASS DECLARATION
+
+/**
+*  Helper class to get items from CLF server.
+*
+*  @lib ContentListingFramework.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CCLFDbItemProvider ) : public CActive
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCLFDbItemProvider* NewL( CCLFDbItemContainer& aDbItemContainer,
+                                         CCLFQueryAdapter& aQueryAdapter, CMdESession* iMdESession );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCLFDbItemProvider();
+
+    public: // New functions
+
+        /**
+        * Async function for fething items from server.
+        * @since Series 60 3.0
+        * @param aMimeTypeArray
+        * @param aMediaTypeArray
+        * @param aObserver item provider observer
+        */
+        void PrepareItemsL( const MDesCArray& aMimeTypeArray,
+                            const TArray<TInt>& aMediaTypeArray,
+                            MCLFItemProviderObserver& aObserver );
+
+        void PrepareItemsL( const TArray<TCLFItemId>& aItemIDArray,
+                            MCLFItemProviderObserver& aObserver );
+
+        /**
+        * Get items.
+        * @since Series 60 3.0
+        * @param aItemArray
+        * @return system-wide error code
+        */
+        TInt GetItems( RPointerArray<MCLFItem>& aItemArray );
+
+    protected:  // New functions
+
+        /**
+        * From CActive
+        */
+        void DoRunL();
+
+        /**
+        * From CActive
+        */
+        TInt RunError( TInt aError );
+
+        void DoFetchMdSIdDataCachedL();
+        void DoFetchMdSDataL();
+        void DoFetchMdSIdDataL( RArray< TCLFItemId >& aItemIDArray );
+        void CreateCLFItemL( CCLFContainerItem& aCItem );
+    protected:  // Functions from base classes
+
+        /**
+        * From CActive
+        */
+        void DoCancel();
+
+        /**
+        * From CActive
+        */
+        void RunL();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CCLFDbItemProvider( CCLFDbItemContainer& aDbItemContainer,
+                                   CCLFQueryAdapter& aQueryAdapter, CMdESession* aMdESession );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private:    // Data
+
+        enum TCLFItemProviderState
+            {
+            EPrepareItemIds = 0x1,
+            EPrepareItems,
+            EItemsReady
+            };
+
+        // Own
+        TCLFItemProviderState iProviderState;
+        // Ref
+        MCLFItemProviderObserver* iObserver;
+        // Own
+        RPointerArray< MCLFItem > iItemArray;
+        // Ref
+        CCLFDbItemContainer& iDbItemContainer;
+        // Ref
+        CCLFQueryAdapter& iQueryAdapter;        
+        // Own
+        CMdEObjectQuery* iObjectQuery;
+        // Ref
+        const TDesC* iObjDefStr;
+        // Ref
+        CMdESession* iMdESession;
+    };
+
+#endif      // CCLFDBITEMPROVIDER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFDefaultOperation.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,529 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "CCLFDefaultOperation.h"
+#include    <MCLFSortingStyle.h>
+#include    <MCLFModifiableItem.h>
+#include    <ContentListingFactory.h>
+#include    <collate.h>
+#include    <badesca.h>
+#include    "MGDebugPrint.h"
+
+// CONSTANTS
+const TInt KCLFGroupedItemArrayGranularity( 4 );
+const TInt KCLFSortingStyleArrayGranularity( 3 );
+
+// CLASS DECLARATION
+
+/**
+*  Internal helper class for sorting
+*/
+class TCLFSortingItem
+    {
+    public:
+        TCLFSortingItem()
+            : iData( KNullDesC ),
+              iIntData( 0 ),
+              iTimeData( 0 ),
+              iItem( NULL )
+            {
+            }
+
+        TPtrC iData;
+        TInt32 iIntData;
+        TTime iTimeData;
+        MCLFItem* iItem;
+    };
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CompareAlphaAscending
+// -----------------------------------------------------------------------------
+//
+TInt CompareAlphaAscending( const TCLFSortingItem& aFirst,
+                            const TCLFSortingItem& aSecond )
+    {
+    // get the standard method
+    TCollationMethod m = *Mem::CollationMethodByIndex( 0 );
+    m.iFlags |= TCollationMethod::EIgnoreNone | TCollationMethod::EFoldCase;
+    return aFirst.iData.CompareC( aSecond.iData, 3, &m  );
+    }
+
+// -----------------------------------------------------------------------------
+// CompareIntAscending
+// -----------------------------------------------------------------------------
+//
+TInt CompareIntAscending( const TCLFSortingItem& aFirst,
+                          const TCLFSortingItem& aSecond )
+    {
+    return aFirst.iIntData - aSecond.iIntData;
+    }
+
+// -----------------------------------------------------------------------------
+// CompareTimeAscending
+// -----------------------------------------------------------------------------
+//
+TInt CompareTimeAscending( const TCLFSortingItem& aFirst,
+                           const TCLFSortingItem& aSecond )
+    {
+    if ( aFirst.iTimeData > aSecond.iTimeData )
+        {
+        return 1;
+        }
+    else if ( aFirst.iTimeData < aSecond.iTimeData )
+        {
+        return -1;
+        }
+    return 0;
+    }
+
+// -----------------------------------------------------------------------------
+// AppendItemsArrayL
+// -----------------------------------------------------------------------------
+//
+void AppendItemsToArrayL( const TArray<MCLFItem*>& aSourceArray,
+                          RPointerArray<MCLFItem>& aDestArray )
+    {
+    const TInt count( aSourceArray.Count() );
+    for( TInt i = 0 ; i < count ; ++i )
+        {
+        aDestArray.AppendL( aSourceArray[ i ] );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// AppendItemsToArrayL
+// append aSourceArray items to aDestArray
+// -----------------------------------------------------------------------------
+//
+void AppendItemsToArrayL( const TArray<MCLFItem*>& aSourceArray,
+                          RPointerArray<MCLFItem>& aDestArray,
+                          TCLFUndefinedItemPosition aPosition,
+                          TInt& aItemIndex,
+                          TInt& aLastAddedItemCount )
+    {
+    if( aPosition == ECLFSortingStyleUndefinedFirst )
+        {
+        aItemIndex = aItemIndex - aLastAddedItemCount;
+        }
+
+    aLastAddedItemCount = aSourceArray.Count();
+    for( TInt i = 0 ; i < aLastAddedItemCount ; ++i )
+        {
+        aDestArray.InsertL( aSourceArray[i], aItemIndex );
+        ++aItemIndex;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// AppendSortingItemsArrayL
+// -----------------------------------------------------------------------------
+//
+void AppendSortingItemsToArrayL( const TArray<TCLFSortingItem>& aSourceArray,
+                                 RPointerArray<MCLFItem>& aDestArray )
+    {
+    const TInt count( aSourceArray.Count() );
+    for( TInt i = 0 ; i < count ; ++i )
+        {
+        aDestArray.AppendL( aSourceArray[i].iItem );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// AppendSortingItemsArrayReverseL
+// -----------------------------------------------------------------------------
+//
+void AppendSortingItemsToArrayReverseL(
+                        const TArray<TCLFSortingItem>& aSourceArray,
+                        RPointerArray<MCLFItem>& aDestArray )
+    {
+    for( TInt i = aSourceArray.Count() - 1 ; i > -1 ; --i )
+        {
+        aDestArray.AppendL( aSourceArray[i].iItem );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// MakeSortingItemsL
+// Add/Make items to sorting item array and undefined items to
+// undefined item array
+// -----------------------------------------------------------------------------
+//
+void MakeSortingItemsL( RArray<TCLFSortingItem>& aSortingItemArray,
+                        RPointerArray<MCLFItem>& aUndefinedItemArray,
+                        const TArray<MCLFItem*>& aItemArray,
+                        const TArray<TCLFFieldId> aSortFields,
+                        TCLFItemDataType aSortingDataType )
+    {
+    MG_DEBUG1( MSI1, "MakeSortingItemsL start" );
+
+    const TInt sortingFieldsCount( aSortFields.Count() );
+    const TInt count( aItemArray.Count() );
+    for( TInt i = 0 ; i < count ; ++i )
+        {
+        MCLFItem* seItem = aItemArray[i];
+        TCLFSortingItem sortingItem;
+        TInt fieldIdIndex( -1 );
+        TInt error( KErrNone );
+        do
+            {
+            ++fieldIdIndex;
+            TCLFFieldId fieldId( aSortFields[fieldIdIndex] );
+            switch( aSortingDataType )
+                {
+                case ECLFItemDataTypeDesC:
+                    {
+                    error = seItem->GetField( fieldId, sortingItem.iData );
+                    break;
+                    }
+                case ECLFItemDataTypeTInt32:
+                    {
+                    error = seItem->GetField( fieldId, sortingItem.iIntData );
+                    break;
+                    }
+                case ECLFItemDataTypeTTime:
+                default:
+                    {
+                    error = seItem->GetField( fieldId, sortingItem.iTimeData );
+                    break;
+                    }
+                }
+            } while( ( error != KErrNone ) &&
+                     ( fieldIdIndex < ( sortingFieldsCount - 1 ) ) );
+        if( error == KErrNone )
+            {
+            sortingItem.iItem = seItem;
+            aSortingItemArray.AppendL( sortingItem );
+            }
+        else
+            { // field not found -> undefined item
+            aUndefinedItemArray.AppendL( seItem );
+            }
+        }
+
+    MG_DEBUG1( MSI2, "MakeSortingItemsL end" );
+    }
+
+// -----------------------------------------------------------------------------
+// SortSortingItemsL
+// Select correct sortign operation
+// -----------------------------------------------------------------------------
+//
+void SortSortingItemsL( RArray<TCLFSortingItem>& aItemArray,
+                        TCLFItemDataType aSortingDataType )
+    {
+    TLinearOrder<TCLFSortingItem>* sorter = NULL;
+
+    switch ( aSortingDataType )
+        {
+        case ECLFItemDataTypeDesC:
+            {
+            sorter = new ( ELeave ) TLinearOrder<TCLFSortingItem>
+                        ( CompareAlphaAscending );
+            break;
+            }
+        case ECLFItemDataTypeTInt32:
+            {
+            sorter = new ( ELeave ) TLinearOrder<TCLFSortingItem>
+                        ( CompareIntAscending );
+            break;
+            }
+        case ECLFItemDataTypeTTime:
+        default:
+            {
+            sorter = new ( ELeave ) TLinearOrder<TCLFSortingItem>
+                        ( CompareTimeAscending );
+            break;
+            }
+        }
+
+    aItemArray.Sort( *sorter );
+    delete sorter;
+    sorter = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// SortItemsBySortingStyleL
+// sort aItemArray with aSortingStyle
+// add undefined items to aUndefinedItemArray
+// -----------------------------------------------------------------------------
+//
+void SortItemsBySortingStyleL( RPointerArray<MCLFItem>& aItemArray,
+                               MCLFSortingStyle& aSortingStyle,
+                               RPointerArray<MCLFItem>& aUndefinedItemArray )
+    {
+    RArray<TCLFFieldId> sortingFields;
+    CleanupClosePushL( sortingFields );
+    aSortingStyle.GetFieldsL( sortingFields );
+    const TInt sortingFieldsCount( sortingFields.Count() );
+    if( sortingFieldsCount )  // sort only if there are sorting fields
+        {
+        TCLFItemDataType sortingDataType( aSortingStyle.SortingDataType() );
+
+        RArray<TCLFSortingItem> sortingArray;
+        CleanupClosePushL( sortingArray );
+        MakeSortingItemsL( sortingArray,
+                           aUndefinedItemArray,
+                           aItemArray.Array(),
+                           sortingFields.Array(),
+                           sortingDataType );
+
+        SortSortingItemsL( sortingArray, sortingDataType );
+
+        aItemArray.Reset();
+        if( aSortingStyle.Ordering() == ECLFOrderingAscending )
+            {
+            AppendSortingItemsToArrayL( sortingArray.Array(),
+                                        aItemArray );
+            }
+        else
+            {
+            AppendSortingItemsToArrayReverseL( sortingArray.Array(),
+                                               aItemArray );
+            }
+
+        CleanupStack::PopAndDestroy( &sortingArray ); // sortingArray.Close
+        }
+    CleanupStack::PopAndDestroy( &sortingFields ); // sortingFields.Close
+    }
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCLFDefaultOperation::CCLFDefaultOperation
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCLFDefaultOperation::CCLFDefaultOperation()
+    : iSortingStyle( NULL ),
+      iSortingStyleArray( KCLFSortingStyleArrayGranularity ),
+      iGrouping( ECLFNoGrouping ),
+      iGroupedItemList( KCLFGroupedItemArrayGranularity )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDefaultOperation::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CCLFDefaultOperation* CCLFDefaultOperation::NewL()
+    {
+    return new( ELeave ) CCLFDefaultOperation;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDefaultOperation::NewL
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCLFDefaultOperation::~CCLFDefaultOperation()
+    {
+    iGroupedItemList.ResetAndDestroy();
+    iSortingStyleArray.Close();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCLFDefaultOperation::SetSortingStyle
+// -----------------------------------------------------------------------------
+//
+void CCLFDefaultOperation::SetSortingStyle( MCLFSortingStyle* aSortingStyle )
+    {
+    iSortingStyle = aSortingStyle;
+    iSortingStyleArray.Reset();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDefaultOperation::AppendSortingStyleL
+// -----------------------------------------------------------------------------
+//
+void CCLFDefaultOperation::AppendSortingStyleL(
+                                            MCLFSortingStyle& aSortingStyle )
+    {
+    iSortingStyleArray.AppendL( &aSortingStyle );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDefaultOperation::SetGrouping
+// -----------------------------------------------------------------------------
+//
+void CCLFDefaultOperation::SetGrouping( TCLFGrouping aGrouping )
+    {
+    iGrouping = aGrouping;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDefaultOperation::FilterItemsL
+// -----------------------------------------------------------------------------
+//
+void CCLFDefaultOperation::FilterItemsL( const TArray<MCLFItem*>& aItemList,
+                                   RPointerArray<MCLFItem>& aFilteredItemList )
+    {
+    AppendItemsToArrayL( aItemList, aFilteredItemList );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDefaultOperation::GroupItemsL
+// -----------------------------------------------------------------------------
+//
+void CCLFDefaultOperation::GroupItemsL( const TArray<MCLFItem*>& aSourceList,
+                                        RPointerArray<MCLFItem>& aGroupedList )
+    {
+    MG_DEBUG1( GI1, "CCLFDefaultOperation::GroupItemsL start" );
+
+    iGroupedItemList.ResetAndDestroy();
+    switch ( iGrouping )
+        {
+        case ECLFMusicAlbumGrouping:
+            {
+            DoMusicAlbumGroupingL( aSourceList, aGroupedList );
+            break;
+            }
+        case ECLFNoGrouping:
+        default:
+            {
+            AppendItemsToArrayL( aSourceList, aGroupedList );
+            break;
+            }
+        }
+
+    MG_DEBUG1( GI2, "CCLFDefaultOperation::GroupItemsL end" );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDefaultOperation::SortItemsL
+// -----------------------------------------------------------------------------
+//
+void CCLFDefaultOperation::SortItemsL( RPointerArray<MCLFItem>& aItemArray )
+    {
+    if( iSortingStyle )
+        {
+        RPointerArray<MCLFItem> array;
+        CleanupClosePushL( array );
+        RPointerArray<MCLFItem> array1;
+        CleanupClosePushL( array1 );
+        RPointerArray<MCLFItem>* undefinedItemArray = &array;
+        RPointerArray<MCLFItem>* newUndefinedItemArray = &array1;
+
+        SortItemsBySortingStyleL( aItemArray,
+                                  *iSortingStyle,
+                                  *undefinedItemArray );
+        TInt lastAddedItemCount( aItemArray.Count() );
+        TInt nextItemIndex( lastAddedItemCount );
+        TCLFUndefinedItemPosition position(
+                                    iSortingStyle->UndefinedItemPosition() );
+
+        const TInt secondarySorterCount( iSortingStyleArray.Count() );
+        for( TInt i = 0 ; i < secondarySorterCount ; ++i )
+            {
+            MCLFSortingStyle& sortingStyle = *iSortingStyleArray[i];
+
+            newUndefinedItemArray->Reset();
+            // sort undefined items
+            SortItemsBySortingStyleL( *undefinedItemArray,
+                                      sortingStyle,
+                                      *newUndefinedItemArray );
+
+            // append sorted items to aItemArray
+            AppendItemsToArrayL( undefinedItemArray->Array(),
+                                 aItemArray,
+                                 position,
+                                 nextItemIndex,
+                                 lastAddedItemCount );
+
+
+            position = sortingStyle.UndefinedItemPosition();
+
+            // change pointers
+            RPointerArray<MCLFItem>* tmp = undefinedItemArray;
+            undefinedItemArray = newUndefinedItemArray;
+            newUndefinedItemArray = tmp;
+            }
+
+
+        // copy rest undefined items to correct position
+        AppendItemsToArrayL( undefinedItemArray->Array(),
+                             aItemArray,
+                             position,
+                             nextItemIndex,
+                             lastAddedItemCount );
+
+                                    // close undefined arrays
+        CleanupStack::PopAndDestroy( 2, &array );
+        }
+        // else no sorting
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCLFDefaultOperation::DoMusicAlbumGroupingL
+// -----------------------------------------------------------------------------
+//
+void CCLFDefaultOperation::DoMusicAlbumGroupingL(
+                                    const TArray<MCLFItem*>& aSourceList,
+                                    RPointerArray<MCLFItem>& aGroupedList )
+    {
+    MG_DEBUG1( DMAG1, "CCLFDefaultOperation::DoMusicAlbumGroupingL start" );
+
+    CDesCArray* tempAlbumNameArray =
+                new (ELeave) CDesCArraySeg( KCLFGroupedItemArrayGranularity );
+    CleanupStack::PushL( tempAlbumNameArray );
+
+    const TInt count( aSourceList.Count() );
+    for( TInt i = 0 ; i < count ; ++i )
+        {
+        const MCLFItem* item = aSourceList[i];
+        TPtrC albumName;
+        if( item->GetField( ECLFFieldIdAlbum, albumName ) == KErrNone )
+            {
+            TInt pos( 0 );
+            if( tempAlbumNameArray->Find( albumName, pos ) )
+                {
+                // not found
+                tempAlbumNameArray->AppendL( albumName );
+
+                // make new item
+                MCLFModifiableItem* newItem =
+                                ContentListingFactory::NewModifiableItemLC();
+                newItem->AddFieldL( ECLFFieldIdAlbum, albumName );
+                iGroupedItemList.AppendL( newItem );    // takes ownership
+                CleanupStack::Pop(); // newItem
+
+                TPtrC artistName;
+                if( item->GetField( ECLFFieldIdArtist, artistName ) == KErrNone )
+                    {
+                    newItem->AddFieldL( ECLFFieldIdArtist, artistName );
+                    }
+
+                // add new item to grouper list
+                aGroupedList.AppendL( newItem );
+                }
+            }
+        }
+    CleanupStack::PopAndDestroy( tempAlbumNameArray );
+
+    MG_DEBUG1( DMAG2, "CCLFDefaultOperation::DoMusicAlbumGroupingL end" );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFDefaultOperation.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,130 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+#ifndef CCLFDEFAULTOPERATION_H
+#define CCLFDEFAULTOPERATION_H
+
+//  INCLUDES
+#include <MCLFCustomSorter.h>
+#include <MCLFPostFilter.h>
+#include <MCLFCustomGrouper.h>
+#include <CLFContentListing.hrh>
+#include <CLFContentListing.h>
+#include <e32base.h>
+
+// FORWARD DECLARATIONS
+class MCLFSortingStyle;
+class MCLFModifiableItem;
+
+// CLASS DECLARATION
+
+/**
+*  This class implements operations from
+*  MCLFCustomSorter, MCLFPostFilter and MCLFCustomGrouper.
+*
+*  @lib ContentListingFramework.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CCLFDefaultOperation ) : public CBase,
+                                            public MCLFCustomSorter,
+                                            public MCLFPostFilter,
+                                            public MCLFCustomGrouper
+    {
+
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCLFDefaultOperation* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCLFDefaultOperation();
+
+    public: // New functions
+
+        /**
+        * Set sorting style.
+        * @since Series 60 3.0
+        * @param aSortingStyle Ownership is not transfered
+        */
+        void SetSortingStyle( MCLFSortingStyle* aSortingStyle );
+
+        /**
+        * Append sorting style.
+        * @since Series 60 3.0
+        * @param aSortingStyle Ownership is not transfered
+        */
+        void AppendSortingStyleL( MCLFSortingStyle& aSortingStyle );
+
+        /**
+        * Set item grouping.
+        * @since Series 60 3.0
+        * @param aGrouping Grouping style
+        */
+        void SetGrouping( TCLFGrouping aGrouping );
+
+    protected:  // New functions
+
+        void DoMusicAlbumGroupingL( const TArray<MCLFItem*>& aSourceList,
+                                    RPointerArray<MCLFItem>& aGroupedList );
+
+    protected:  // Functions from base classes
+
+        /**
+        * From MCLFCustomSorter
+        */
+        virtual void SortItemsL( RPointerArray<MCLFItem>& aItemArray );
+
+        /**
+        * From MCLFCustomGrouper
+        */
+        virtual void GroupItemsL( const TArray<MCLFItem*>& aSourceList,
+                                  RPointerArray<MCLFItem>& aGroupedList );
+
+        /**
+        * From MCLFPostFilter
+        */
+        virtual void FilterItemsL( const TArray<MCLFItem*>& aItemList,
+                                   RPointerArray<MCLFItem>& aFilteredItemList );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CCLFDefaultOperation();
+
+    private:    // Data
+        // Ref.
+        MCLFSortingStyle* iSortingStyle;
+        // Ref.
+        RPointerArray<MCLFSortingStyle> iSortingStyleArray;
+        // Grouping style
+        TCLFGrouping iGrouping;
+        // Own. this class owns grouped items
+        RPointerArray<MCLFModifiableItem> iGroupedItemList;
+
+    };
+
+#endif      // CCLFDEFAULTOPERATION_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFEngineImpl.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,542 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    <MCLFOperationObserver.h>
+#include    <MCLFSortingStyle.h>
+#include    <MCLFItem.h>
+#include    <MCLFChangedItemObserver.h>
+#include    "CCLFEngineImpl.h"
+#include    "CCLFDbItemProvider.h"
+#include    "CCLFItemImpl.h"
+#include    "CCLFDefaultOperation.h"
+#include    "CCLFItemListModelImpl.h"
+#include    "CCLFEventHandler.h"
+#include    "CCLFDbItemContainer.h"
+#include    "MGDebugPrint.h"
+#include    "CCLFQueryAdapter.h"
+
+// CONSTANTS
+const TInt KCLFObserverArrayGranularity( 2 );
+const TInt KCLFChangedItemIdArrayGranularity( 10 );
+
+// -----------------------------------------------------------------------------
+// CleanupTempModel
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::CleanupTempModel( TAny* aObj )
+    {
+    static_cast< CCLFEngineImpl::CCLFTempModel* >( aObj )->ResetModelArray();
+    }
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::CCLFEngineImpl
+// -----------------------------------------------------------------------------
+//
+CCLFEngineImpl::CCLFEngineImpl()
+    : iCLFServerProxy( NULL ),
+      iMdESession( NULL ),
+      iError( KErrNone ),
+      iUpdateStartEventHandler( NULL ),
+      iUpdateEndEventHandler( NULL ),
+      iChangedItemObserverArray( KCLFObserverArrayGranularity ),
+      iProcessObserverArray( KCLFObserverArrayGranularity ),
+      iDbItemContainer( NULL ),
+      iItemProvider( NULL ),
+      iQueryAdapter( NULL )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::ConstructL()
+    {
+    iMdESession = CMdESession::NewL( *this );
+    if( !iActiveSchedulerWait.IsStarted() )
+        {
+        iActiveSchedulerWait.Start();
+        }
+    User::LeaveIfError( iError );
+    iCLFServerProxy = CCLFServerProxy::NewL( *iMdESession );
+    iQueryAdapter = CCLFQueryAdapter::NewL( *iMdESession );
+    iUpdateStartEventHandler = CCLFEventHandler::NewL( *iCLFServerProxy, *this );
+    iUpdateEndEventHandler = CCLFEventHandler::NewL( *iCLFServerProxy, *this );
+    iDbItemContainer = CCLFDbItemContainer::NewL();
+    iItemProvider = CCLFDbItemProvider::NewL( *iDbItemContainer, *iQueryAdapter, iMdESession );
+    iUpdateEndEventHandler->ObserverUpdateEndEvent();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::NewLC
+// -----------------------------------------------------------------------------
+//
+CCLFEngineImpl* CCLFEngineImpl::NewLC()
+    {
+    CCLFEngineImpl* self = new( ELeave ) CCLFEngineImpl;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::~CCLFEngineImpl
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCLFEngineImpl::~CCLFEngineImpl()
+    {
+    delete iItemProvider;
+    delete iUpdateStartEventHandler;
+    delete iUpdateEndEventHandler;
+    delete iDbItemContainer;
+    delete iCLFServerProxy;
+    iChangedItemObserverArray.Close();
+    iProcessObserverArray.Close();
+    delete iQueryAdapter;
+    delete iMdESession;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::AddChangedItemObserverL
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::AddChangedItemObserverL( MCLFChangedItemObserver& aObserver )
+    {
+    iChangedItemObserverArray.AppendL( &aObserver );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::RemoveChangedItemObserver
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::RemoveChangedItemObserver( MCLFChangedItemObserver& aObserver )
+    {
+    const TInt index( iChangedItemObserverArray.Find( &aObserver ) );
+    if ( index >= 0 )
+        {
+        iChangedItemObserverArray.Remove( index );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::AddCLFProcessObserverL
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::AddCLFProcessObserverL( MCLFProcessObserver& aObserver )
+    {
+    iProcessObserverArray.AppendL( &aObserver );
+    if ( !iUpdateStartEventHandler->IsActive() )
+        {
+        iUpdateStartEventHandler->ObserverUpdateStartEvent();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::RemoveCLFProcessObserver
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::RemoveCLFProcessObserver( MCLFProcessObserver& aObserver )
+    {
+    const TInt index( iProcessObserverArray.Find( &aObserver ) );
+    if ( index >= 0 )
+        {
+        iProcessObserverArray.Remove( index );
+        }
+
+    StopEventHandling();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::UpdateItemsL
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::UpdateItemsL()
+    {
+    User::LeaveIfError( iCLFServerProxy->UpdateAllItemsL() );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::UpdateItemsL
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::UpdateItemsL( const TArray<TCLFItemId>& aItemIDArray )
+    {
+    User::LeaveIfError( iCLFServerProxy->UpdateItemsL( aItemIDArray ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::UpdateItemsL
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::UpdateItemsL( TInt aSemanticId, const TDesC8& aOpaqueData )
+    {
+    User::LeaveIfError( iCLFServerProxy->UpdateItemsL( aSemanticId, aOpaqueData ) );
+    }
+
+// ---------------------------------------------------------------------------
+// CCLFEngineImpl::HandleSessionOpened
+// ---------------------------------------------------------------------------
+//
+void CCLFEngineImpl::HandleSessionOpened( CMdESession& /* aSession */, const TInt aError )
+    {
+    MG_DEBUG2( HSO, "[CLF]\t CCLFEngineImpl::HandleSessionOpened %d", aError );
+    iActiveSchedulerWait.AsyncStop();
+
+    iError = aError;
+    }
+
+// ---------------------------------------------------------------------------
+// CCLFEngineImpl::HandleSessionError
+// ---------------------------------------------------------------------------
+//
+void CCLFEngineImpl::HandleSessionError( CMdESession& /*aSession*/, const TInt aError )
+    {
+    MG_DEBUG2( HSE, "[CLF]\t CCLFEngineImpl::HandleSessionError %d", aError );
+
+    iError = aError;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::CreateListModelLC
+// -----------------------------------------------------------------------------
+//
+MCLFItemListModel* CCLFEngineImpl::CreateListModelLC(
+                                            MCLFOperationObserver& aObserver )
+    {
+
+    CCLFDbItemProvider* itemProvider = CCLFDbItemProvider::NewL( *iDbItemContainer, *iQueryAdapter, iMdESession );
+    // self takes ownership of itemProvider.
+    CCLFItemListModelImpl* self = CCLFItemListModelImpl::NewLC( itemProvider, aObserver, iChangedItemModel );
+    iChangedItemModel.AddObserverL( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::CreateListModelLC
+// -----------------------------------------------------------------------------
+//
+MCLFItemListModel* CCLFEngineImpl::CreateListModelLC(
+                                            MCLFOperationObserver& aObserver,
+                                            TResourceReader& aReader )
+    {
+    CCLFDbItemProvider* itemProvider = CCLFDbItemProvider::NewL( *iDbItemContainer, *iQueryAdapter, iMdESession );
+    // self takes ownership of itemProvider.
+    CCLFItemListModelImpl* self = CCLFItemListModelImpl::NewLC( itemProvider, aObserver, iChangedItemModel, aReader );
+    iChangedItemModel.AddObserverL( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::HandleUpdateEndEventL
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::HandleUpdateEndEventL( const TInt aError )
+    {
+    if ( aError == KErrNone )
+        {
+        // get changed items and add new ones to array
+        RArray< TCLFItemId > changedItemIdArray;
+        CleanupClosePushL( changedItemIdArray );
+        iUpdateEndEventHandler->GetChangedItemsL( changedItemIdArray );
+        const TInt count( changedItemIdArray.Count() );
+        for ( TInt i = 0; i < count; ++i )
+            {
+            const TCLFItemId id( changedItemIdArray[ i ] );
+            const TInt index(
+                    iChangedItemModel.iChangedItemIdArray.Find( id ) );
+            if ( index == KErrNotFound )
+                {
+                iChangedItemModel.iChangedItemIdArray.AppendL( id );
+                }
+            }
+        CleanupStack::PopAndDestroy( &changedItemIdArray );
+
+        if ( iChangedItemModel.iChangedItemIdArray.Count() )
+            {
+            iDbItemContainer->SetDeprecatedItems(
+                                    iChangedItemModel.iChangedItemIdArray );
+
+            iItemProvider->PrepareItemsL(
+                                iChangedItemModel.iChangedItemIdArray.Array(),
+                                *this );
+            }
+        else
+            {
+            // no changed items -> just notify process observers
+            NotifyProcessObserversL( ECLFUpdateStop );
+            }
+        }
+    else
+        {
+        const TInt count( iChangedItemObserverArray.Count() );
+        for ( TInt i = 0 ; i < count ; ++i )
+            {
+            iChangedItemObserverArray[i]->HandleError( aError );
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::OperationCompleteL
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::OperationCompleteL( const TInt aError )
+    {
+    // make sure that changed item model is reset
+    // array must be reset when changed items are handled (also in leave case)
+    CleanupStack::PushL( TCleanupItem( CleanupTempModel,
+                                       &iChangedItemModel) );
+
+    if ( aError )
+        {
+        const TInt count( iChangedItemObserverArray.Count() );
+        for( TInt i = 0 ; i < count ; ++i )
+            {
+            iChangedItemObserverArray[i]->HandleError( aError );
+            }
+        }
+    else
+        {
+        // put items to container
+        User::LeaveIfError( iItemProvider->GetItems(
+                                    iChangedItemModel.iItemArray ) );
+
+        // notify process observers
+        NotifyProcessObserversL( ECLFUpdateStop );
+
+        // notify changed item observers
+        if ( iChangedItemModel.iChangedItemIdArray.Count() > 0 )
+            {
+            const TInt count( iChangedItemObserverArray.Count() );
+            for( TInt i = 0 ; i < count ; ++i )
+                {
+                iChangedItemObserverArray[i]->HandleItemChangeL(
+                            iChangedItemModel.iChangedItemIdArray.Array() );
+                }
+
+            // notify models
+            iChangedItemModel.NotifyObserverL();
+            }
+        }
+    CleanupStack::PopAndDestroy(); // TCleanupItem
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::HandleUpdateStartEventL
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::HandleUpdateStartEventL( const TInt aError )
+    {
+    if ( aError == KErrNone )
+        {
+        NotifyProcessObserversL( ECLFUpdateStart );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::NotifyProcessObserversL
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::NotifyProcessObserversL( TCLFProcessEvent aEvent )
+    {
+    const TInt count( iProcessObserverArray.Count() );
+    for ( TInt i = 0 ; i < count ; ++i )
+        {
+        iProcessObserverArray[i]->HandleCLFProcessEventL( aEvent );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::StopEventHandling
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::StopEventHandling()
+    {
+    if ( iProcessObserverArray.Count() == 0 )
+        {
+        // stop "start observing"
+        iUpdateStartEventHandler->Cancel();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::CCLFTempModel::IsItemsForModel
+// -----------------------------------------------------------------------------
+//
+TBool CCLFEngineImpl::CCLFTempModel::IsItemsForModel(
+                                        const MDesCArray& aMimeTypes,
+                                        const TArray<TInt>& aMediaTypes,
+                                        const TArray<TUint>& aModelItemIds )
+    {
+    // first from item IDs
+    TInt count( aModelItemIds.Count() );
+    for ( TInt i = 0 ; i < count ; ++i )
+        {
+        const TInt index( iChangedItemIdArray.FindInOrder( aModelItemIds[ i ] ) );
+        if( index >= 0 )
+            {
+            return ETrue;
+            }
+        }
+
+    // find second from media types (faster)
+    count = aMediaTypes.Count();
+    for ( TInt i = 0 ; i < count ; ++i )
+        {
+        const TInt index( iMediaTypeArray.FindInOrder( aMediaTypes[ i ] ) );
+        if ( index >= 0 )
+            {
+            return ETrue;
+            }
+        }
+
+    // and mimetypes, final from mimetypes, 
+    // because descriptor comparation is slow
+    count = aMimeTypes.MdcaCount();
+    const TInt mCount( iMimeTypeArray.MdcaCount() );
+    for ( TInt i = 0 ; i < count ; ++i )
+        {
+        // match model mimetypes to changed item(s) mimetypes
+        const TDesC& modelMimeType = aMimeTypes.MdcaPoint( i );
+        for ( TInt j = 0 ; j < mCount ; ++j )
+            {
+            const TDesC& changedItemMimeType = iMimeTypeArray.MdcaPoint( j );
+            const TInt match( changedItemMimeType.Match( modelMimeType ) );
+            if ( match != KErrNotFound )
+                {
+                return ETrue;
+                }
+            }
+        }
+
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::CCLFTempModel::CCLFTempModel
+// -----------------------------------------------------------------------------
+//
+CCLFEngineImpl::CCLFTempModel::CCLFTempModel()
+    : iItemArray( KCLFChangedItemIdArrayGranularity ),
+      iChangedItemIdArray( KCLFChangedItemIdArrayGranularity ),
+      iChangedItemProviderObserverArray( KCLFChangedItemIdArrayGranularity ),
+      iMimeTypeArray( KCLFChangedItemIdArrayGranularity ),
+      iMediaTypeArray( KCLFChangedItemIdArrayGranularity )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::CCLFTempModel::~CCLFTempModel
+// -----------------------------------------------------------------------------
+//
+CCLFEngineImpl::CCLFTempModel::~CCLFTempModel()
+    {
+    ResetModelArray();
+    iChangedItemProviderObserverArray.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::CCLFTempModel::AddObserverL
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::CCLFTempModel::AddObserverL(
+                                MCLFChangedItemProviderObserver* aObserver )
+    {
+    iChangedItemProviderObserverArray.AppendL( aObserver );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::CCLFTempModel::ResetModelArray
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::CCLFTempModel::ResetModelArray()
+    {
+    iItemArray.ResetAndDestroy();
+    iMimeTypeArray.Reset();
+    iMediaTypeArray.Reset();
+    iChangedItemIdArray.Reset();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::CCLFTempModel::NotifyObserverL
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::CCLFTempModel::NotifyObserverL()
+    {
+    PrepareModelL();
+
+    const TInt providerObserverCount(
+                                    iChangedItemProviderObserverArray.Count() );
+    for ( TInt i = 0 ; i < providerObserverCount ; ++i )
+        {
+        iChangedItemProviderObserverArray[i]->NewChangedItemsL();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::CCLFTempModel::PrepareModelL
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::CCLFTempModel::PrepareModelL()
+    {
+    // sort array for faster find
+    iChangedItemIdArray.Sort();
+
+    // get mimetypes and media types from items
+    const TInt modelCount( iItemArray.Count() );
+    for ( TInt i = 0 ; i < modelCount ; ++i )
+        {
+        MCLFItem* item = iItemArray[ i ];
+
+        TInt32 mediaType( 0 );
+        TInt error( item->GetField( ECLFFieldIdMediaType, mediaType ) );
+        if ( error == KErrNone &&
+            iMediaTypeArray.FindInOrder( mediaType ) == KErrNotFound )
+            {
+            User::LeaveIfError( iMediaTypeArray.InsertInOrder( mediaType ) );
+            }
+        TPtrC mimeType;
+        error = item->GetField( ECLFFieldIdMimeType, mimeType );
+        TInt pos( 0 );
+        if ( error == KErrNone &&
+            iMimeTypeArray.FindIsq( mimeType, pos ) != 0 ) // not found
+            {
+            iMimeTypeArray.InsertIsqL( mimeType );
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEngineImpl::CCLFTempModel::ChangedItemProviderRemoveObserver
+// -----------------------------------------------------------------------------
+//
+void CCLFEngineImpl::CCLFTempModel::RemoveChangedItemProviderObserver(
+                                MCLFChangedItemProviderObserver* aObserver )
+    {
+    const TInt index( iChangedItemProviderObserverArray.Find( aObserver ) );
+    if ( index >= 0 )
+        {
+        iChangedItemProviderObserverArray.Remove( index );
+        }
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFEngineImpl.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,258 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef CCLFENGINEIMPL_H
+#define CCLFENGINEIMPL_H
+
+//  INCLUDES
+#include "MCLFContentListingEngine.h"
+#include "MCLFEventHandlerObserver.h"
+#include "MCLFProcessObserver.h"
+#include "CCLFServerProxy.h"
+#include "MCLFItemProviderObserver.h"
+#include "MCLFChangedItemProvider.h"
+#include <MCLFItem.h>
+#include <badesca.h>
+#include <mdesession.h>
+
+// FORWARD DECLARATIONS
+class CCLFEventHandler;
+class CCLFDbItemContainer;
+class CCLFDbItemProvider;
+class CCLFQueryAdapter;
+class CCLFServerProxy;
+
+// CLASS DECLARATION
+
+/**
+*  Implements MCLFContentListingEngine, MCLFEventHandlerObserver and MCLFItemProviderObserver
+*  interfaces
+*
+*  @lib ContentListingFramework.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CCLFEngineImpl ) : public CBase,
+                                      public MCLFContentListingEngine,
+                                      public MCLFEventHandlerObserver,
+                                      public MCLFItemProviderObserver,
+                                      public MMdESessionObserver
+    {
+    private:
+
+        NONSHARABLE_CLASS( CCLFTempModel ) : public CBase,
+                                             public MCLFChangedItemProvider
+            {
+            public: // Constructors and destructor
+
+                /**
+                * Two-phased constructor.
+                */
+                CCLFTempModel();
+
+                 /**
+                * Destructor.
+                */               
+                virtual ~CCLFTempModel();
+
+            public: // New functions
+
+                void AddObserverL( MCLFChangedItemProviderObserver* aObserver );
+
+                void ResetModelArray();
+
+                void NotifyObserverL();
+
+            protected: // Functions from base classes
+
+                /**
+                * From MCLFChangedItemProvider
+                */
+                TBool IsItemsForModel(
+                                const MDesCArray& aMimeTypes,
+                                const TArray<TInt>& aMediaTypes,
+                                const TArray<TCLFItemId>& aModelItemIds );
+
+                /**
+                * From MCLFChangedItemProvider
+                */
+                void RemoveChangedItemProviderObserver(
+                            MCLFChangedItemProviderObserver* aObserver );
+
+            protected: // New functions
+
+                void PrepareModelL();
+
+
+            public: // Data
+            
+                // Own: temp model for changed items
+                RPointerArray<MCLFItem> iItemArray;
+                RArray<TCLFItemId> iChangedItemIdArray;
+
+            private: // Data
+
+                // Ref. observers
+                RPointerArray<MCLFChangedItemProviderObserver>
+                                            iChangedItemProviderObserverArray;
+                CDesCArraySeg iMimeTypeArray;
+                RArray<TInt> iMediaTypeArray;
+
+            };
+
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCLFEngineImpl* NewLC();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCLFEngineImpl();
+
+    protected:  // Functions from base classes
+
+        /**
+        * From MCLFContentListingEngine
+        */
+        MCLFItemListModel* CreateListModelLC(
+                                    MCLFOperationObserver& aObserver );
+
+        /**
+        * From MCLFContentListingEngine
+        */
+        MCLFItemListModel* CreateListModelLC(
+                                    MCLFOperationObserver& aObserver,
+                                    TResourceReader& aReader );
+
+        /**
+        * From MCLFContentListingEngine
+        */
+        void UpdateItemsL();
+
+        /**
+        * From MCLFContentListingEngine
+        */
+        void UpdateItemsL( const TArray<TCLFItemId>& aItemIDArray );
+
+        /**
+        * From MCLFContentListingEngine
+        */
+        void AddChangedItemObserverL(
+                                    MCLFChangedItemObserver& aObserver );
+
+        /**
+        * From MCLFContentListingEngine
+        */
+        void RemoveChangedItemObserver(
+                                    MCLFChangedItemObserver& aObserver );
+
+        /**
+        * From MCLFContentListingEngine
+        */
+        void UpdateItemsL( TInt aSemanticId, const TDesC8& aOpaqueData );
+
+        /**
+        * From MCLFContentListingEngine
+        */
+        void AddCLFProcessObserverL(
+                        MCLFProcessObserver& aObserver );
+
+        /**
+        * From MCLFContentListingEngine
+        */
+        void RemoveCLFProcessObserver(
+                        MCLFProcessObserver& aObserver );
+
+        /**
+        * From MCLFEventHandlerObserver
+        */
+        void HandleUpdateEndEventL( TInt aError );
+
+        /**
+        * From MCLFEventHandlerObserver
+        */
+        void HandleUpdateStartEventL( TInt aError );
+
+        /**
+        * From MCLFItemProviderObserver
+        */
+        void OperationCompleteL( TInt aError );
+
+        /**
+         * From MMdESessionObserver
+         */
+        void HandleSessionOpened( CMdESession& aSession, TInt aError );
+
+        /**
+         * From MMdESessionObserver
+         */
+        void HandleSessionError( CMdESession& aSession, TInt aError );
+        
+        
+    private:  // New functions
+
+        void StopEventHandling();
+
+        void NotifyProcessObserversL( TCLFProcessEvent aEvent );
+
+        static void CleanupTempModel( TAny* aObj );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CCLFEngineImpl();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private:    // Data
+        // Own
+        CCLFServerProxy* iCLFServerProxy;
+        // Own
+        CMdESession* iMdESession;
+        // Own
+        TInt iError;
+        // Own
+        CActiveSchedulerWait iActiveSchedulerWait;
+        // Own
+        CCLFEventHandler* iUpdateStartEventHandler;
+        // Own
+        CCLFEventHandler* iUpdateEndEventHandler;
+        // Ref. observers
+        RPointerArray< MCLFChangedItemObserver > iChangedItemObserverArray;
+        // Ref. observers
+        RPointerArray< MCLFProcessObserver > iProcessObserverArray;
+        // Own:
+        CCLFDbItemContainer* iDbItemContainer;
+        // Own. to get changed items
+        CCLFDbItemProvider* iItemProvider;
+        // Own:
+        CCLFTempModel iChangedItemModel;
+        // Own
+        CCLFQueryAdapter* iQueryAdapter;        
+    };
+
+#endif      // CCLFENGINEIMPL_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFEventHandler.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,144 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include <e32std.h>
+#include "CCLFEventHandler.h"
+#include "MCLFEventHandlerObserver.h"
+#include "MGDebugPrint.h"
+
+// MACROS
+// Macro for calling a member function through function pointer
+#define CLF_CALL_MEMBER_FN( aObject, aPtrToMember ) \
+                                           (( aObject ).*( aPtrToMember ))
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCLFEventHandler::CCLFEventHandler
+// -----------------------------------------------------------------------------
+//
+CCLFEventHandler::CCLFEventHandler( CCLFServerProxy& aEventHandler,
+                                           MCLFEventHandlerObserver& aObserver )
+    : CActive( CActive::EPriorityStandard ),
+      iEventHandler( aEventHandler ),
+      iObserver( aObserver ),
+      iOperationFunction( &CCLFServerProxy::GetUpdateEndEvent ),
+      iCancelFunction( &CCLFServerProxy::CancelGetEvent ),
+      iObserverFunction( &MCLFEventHandlerObserver::HandleUpdateEndEventL )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEventHandler::NewL
+// -----------------------------------------------------------------------------
+//
+CCLFEventHandler* CCLFEventHandler::NewL( CCLFServerProxy& aEventHandler,
+                                        MCLFEventHandlerObserver& aObserver )
+    {
+    return new( ELeave ) CCLFEventHandler( aEventHandler, aObserver );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEventHandler::~CCLFEventHandler
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCLFEventHandler::~CCLFEventHandler()
+    {
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEventHandler::DoCancel
+// -----------------------------------------------------------------------------
+//
+void CCLFEventHandler::DoCancel()
+    {
+    CLF_CALL_MEMBER_FN( iEventHandler, iCancelFunction )();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEventHandler::RunL
+// -----------------------------------------------------------------------------
+//
+void CCLFEventHandler::RunL()
+    {
+    // observer function can leave
+    CLF_CALL_MEMBER_FN( iObserver, iObserverFunction )( iStatus.Int() );
+    DoStart();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::RunError
+// -----------------------------------------------------------------------------
+//
+TInt CCLFEventHandler::RunError( const TInt aError )
+    {
+    MG_DEBUG2( re1, "[CLF]\t CCLFEventHandler::RunError: %d", aError ); 
+
+    return aError;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEventHandler::ObserverUpdateEndEvent
+// -----------------------------------------------------------------------------
+//
+void CCLFEventHandler::ObserverUpdateEndEvent()
+    {
+    Cancel();
+    iOperationFunction = &CCLFServerProxy::GetUpdateEndEvent;
+    iCancelFunction = &CCLFServerProxy::CancelGetEvent;
+    iObserverFunction = &MCLFEventHandlerObserver::HandleUpdateEndEventL;
+    DoStart();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEventHandler::ObserverUpdateStartEvent
+// -----------------------------------------------------------------------------
+//
+void CCLFEventHandler::ObserverUpdateStartEvent()
+    {
+    Cancel();
+    iOperationFunction = &CCLFServerProxy::GetUpdateStartEvent;
+    iCancelFunction = &CCLFServerProxy::CancelGetUpdateStartEvent;
+    iObserverFunction = &MCLFEventHandlerObserver::HandleUpdateStartEventL;
+    DoStart();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEventHandler::DoStart
+// -----------------------------------------------------------------------------
+//
+void CCLFEventHandler::DoStart()
+    {
+    CLF_CALL_MEMBER_FN( iEventHandler, iOperationFunction )( iStatus );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFEventHandler::GetChangedItemsL
+// -----------------------------------------------------------------------------
+//
+void CCLFEventHandler::GetChangedItemsL( RArray<TUint>& aItemArray )
+    {
+    User::LeaveIfError( iEventHandler.FetchItemListData( aItemArray ) );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFEventHandler.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,124 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#ifndef CCLFEVENTHANDLER_H
+#define CCLFEVENTHANDLER_H
+
+//  INCLUDES
+#include "CCLFServerProxy.h"
+#include <CLFContentListing.h>
+#include <e32base.h>
+
+// FORWARD DECLARATIONS
+class MCLFEventHandlerObserver;
+
+typedef void ( CCLFServerProxy::*TMemberFnOp )( TRequestStatus& aStatus );
+typedef TInt ( CCLFServerProxy::*TMemberFnCancel )();
+typedef void ( MCLFEventHandlerObserver::*TMemberFnObserver )( TInt aError );
+
+// CLASS DECLARATION
+
+/**
+*  Item change event handler.
+*
+*  @lib ContentListingFramework.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CCLFEventHandler ) : public CActive
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCLFEventHandler* NewL( CCLFServerProxy& aEventHandler,
+                                       MCLFEventHandlerObserver& aObserver );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCLFEventHandler();
+
+    public: // New functions
+
+        /**
+        * Start event observing.
+        * @since Series 60 3.0
+        */
+        void ObserverUpdateStartEvent();
+
+        /**
+        * Start event observing.
+        * @since Series 60 3.0
+        */
+        void ObserverUpdateEndEvent();
+
+        /**
+        * Get changed items.
+        * @since Series 60 3.0
+        * @param aItemArray changed item ID array
+        */
+        void GetChangedItemsL( RArray<TCLFItemId>& aItemArray );
+
+    protected:  // Functions from base classes
+
+        /**
+        * From CActive
+        */
+        void DoCancel();
+
+        /**
+        * From CActive
+        */
+        void RunL();
+
+        /**
+        * From CActive
+        */
+        TInt RunError( TInt aError );
+
+    private:
+
+        void DoStart();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CCLFEventHandler( CCLFServerProxy& aEventHandler,
+                                 MCLFEventHandlerObserver& aObserver );
+
+    private:    // Data
+        // Ref. 
+        CCLFServerProxy& iEventHandler;
+
+        // Ref. 
+        MCLFEventHandlerObserver& iObserver;
+
+        TMemberFnOp iOperationFunction;
+
+        TMemberFnCancel iCancelFunction;
+        
+        TMemberFnObserver iObserverFunction;
+
+    };
+
+#endif // CCLFEVENTHANDLER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFItemImpl.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,639 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCLFItemImpl.h"
+#include    "CCLFDbItemContainer.h"
+#include    "CLFConsts.h"
+#include    "CLF2MdEConsts.h"
+#include    <f32file.h>
+#include    "MGDebugPrint.h"
+#include    <mdesession.h>
+#include    <mdetextproperty.h>
+#include    <mdenumberproperty.h>
+#include    <mdeobjectdef.h>
+#include    <mdeconstants.h>
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCLFItemImpl::CCLFItemImpl
+// -----------------------------------------------------------------------------
+//
+CCLFItemImpl::CCLFItemImpl( CCLFContainerItem& aContainerItem,
+                                   CCLFDbItemContainer& aDbItemContainer )
+    : iItem( aContainerItem ),
+      iMdEObject( aContainerItem.DbItem() ),
+      iDbItemContainer( aDbItemContainer )
+    {
+    iItem.IncreaseReferenceCount();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemImpl::NewLC
+// -----------------------------------------------------------------------------
+//
+CCLFItemImpl* CCLFItemImpl::NewLC( CCLFContainerItem& aContainerItem,
+                                   CCLFDbItemContainer& aDbItemContainer )
+    {
+    CCLFItemImpl* self =
+            new ( ELeave ) CCLFItemImpl( aContainerItem, aDbItemContainer );
+
+    CleanupStack::PushL( self );
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemImpl::NewL
+// -----------------------------------------------------------------------------
+//
+CCLFItemImpl* CCLFItemImpl::NewL( CCLFContainerItem& aContainerItem,
+                                   CCLFDbItemContainer& aDbItemContainer )
+    {   
+    return new( ELeave ) CCLFItemImpl( aContainerItem, aDbItemContainer );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemImpl::~CCLFItemImpl
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCLFItemImpl::~CCLFItemImpl()
+    {
+    iDbItemContainer.ReleaseItem( &iItem );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemImpl::ItemId
+// -----------------------------------------------------------------------------
+//
+TCLFItemId CCLFItemImpl::ItemId() const
+    {
+    TCLFItemId id = (TCLFItemId) iMdEObject.Id();
+    return id;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemImpl::DataType
+// -----------------------------------------------------------------------------
+//
+TCLFItemDataType CCLFItemImpl::DataType( const TCLFFieldId aFieldId ) const
+    {
+    MG_DEBUG2( DT, "[CLF]\t CCLFItemImpl::DataType aFieldId: %d", aFieldId );
+
+    TCLFItemDataType ret = ECLFItemDataTypeNull;
+    const TDesC& property = MapFieldToMdEProperty( aFieldId );
+
+    if ( property != KNullDesC )
+        {
+        const CMdEPropertyDef* propertyDef = NULL;
+        TRAP_IGNORE( propertyDef = &iMdEObject.Def().GetPropertyDefL( property ));
+
+        switch ( propertyDef->PropertyType())
+            {
+            case EPropertyBool:
+            case EPropertyInt8:
+            case EPropertyUint8:
+            case EPropertyInt16:
+            case EPropertyUint16:
+            case EPropertyInt32:
+            case EPropertyUint32:
+            case EPropertyInt64:
+            case EPropertyReal32:
+            case EPropertyReal64:
+                {
+                ret = ECLFItemDataTypeTInt32;
+                break;
+                }
+            case EPropertyTime:
+                {
+                ret = ECLFItemDataTypeTTime;
+                break;
+                }
+            case EPropertyText:
+                {
+                ret = ECLFItemDataTypeDesC;
+                break;
+                }
+            default:
+                {
+                /* Fall through */
+                break;
+                }
+            }
+        }
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemImpl::DeduceFieldFromURI
+// -----------------------------------------------------------------------------
+//
+TBool CCLFItemImpl::DeduceFieldFromURI( const TCLFFieldId aFieldId, TPtrC& aValue ) const
+    {
+    TBool done = ETrue;
+    TPtrC path = iMdEObject.Uri();
+    TParsePtrC nameParse( path );
+
+    switch ( aFieldId )
+        {
+        case ECLFFieldIdFileName:
+            {
+            aValue.Set( nameParse.Name() );
+            break;
+            }
+        case ECLFFieldIdFileExtension:
+            {
+            aValue.Set( nameParse.Ext() );
+            break;
+            }
+        case ECLFFieldIdPath:
+            {
+            aValue.Set( nameParse.Path() );
+            break;
+            }
+        case ECLFFieldIdDrive:
+            {
+            aValue.Set( nameParse.Drive() );
+            break;
+            }
+        case ECLFFieldIdFileNameAndPath:
+            {
+            aValue.Set( path );
+            break;
+            }
+        default:
+            {
+            done = EFalse; // Field deduction from URI did not work.
+            break;
+            }
+        }
+    return done;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemImpl::GetMediaTypeL
+// -----------------------------------------------------------------------------
+//
+TInt CCLFItemImpl::GetMediaTypeL( CMdEObjectDef& aObjectDef, TInt32& aValue ) const
+    {
+    const TDesC* mdemediatypes[] =
+        {
+        &MdeConstants::Audio::KAudioObject,
+        &MdeConstants::Video::KVideoObject,
+        &MdeConstants::Image::KImageObject,
+        };
+    const TInt clfmediatypes[] =
+        {
+        ECLFMediaTypeSound,
+        ECLFMediaTypeVideo,
+        ECLFMediaTypeImage,
+        };
+    const TPtrC name = aObjectDef.Name();
+    TInt32 error = KErrNotFound;
+
+    aValue = ECLFMediaTypeUnknown; // Default to this.
+    for ( TInt i = 0; i < sizeof( clfmediatypes ) / sizeof( TInt ); ++i )
+        {
+        if ( name.Compare( *mdemediatypes[ i ] ) == 0 )
+            {
+            aValue = clfmediatypes[ i ];
+            error = KErrNone;
+            break;
+            }
+        }
+
+    if ( aValue == ECLFMediaTypeSound )
+        {
+        DetermineIfMusicL( aObjectDef, aValue );
+        }
+    return error;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemImpl::DetermineIfMusicL
+// -----------------------------------------------------------------------------
+//
+void CCLFItemImpl::DetermineIfMusicL( CMdEObjectDef& aObjectDef, TInt32& aValue ) const
+    {
+    // This is a hard-coded list used to determine if the media type is music. CLF uses a
+    // separate MIME type manager to map MIME types to CLF media types, but this is located on
+    // the CLF server side, which this wrapper removes/obsoletes. The MIME type manager uses a
+    // resource file for mapping MIME types.
+    const TDesC* clfwrappermusictypes[] =
+        {
+        &KCLFWrapperMusicTypeMpeg,
+        &KCLFWrapperMusicTypeAac,
+        &KCLFWrapperMusicTypeMp3,
+        &KCLFWrapperMusicTypeX_Mp3,
+        &KCLFWrapperMusicTypeMp4,
+        &KCLFWrapperMusicType3gpp,
+        &KCLFWrapperMusicTypeM4a,
+        &KCLFWrapperMusicType3gpp2,
+        &KCLFWrapperMusicTypeMpeg4,
+        &KCLFWrapperMusicTypeX_Pn_RealAudio,
+        &KCLFWrapperMusicTypeX_Ms_Wma,
+        };
+
+    const CMdEPropertyDef* propertyDef = NULL;
+    propertyDef = &aObjectDef.GetPropertyDefL( MdeConstants::Object::KItemTypeProperty );
+
+    if ( propertyDef )
+        {
+        // Get the actual data
+        CMdEProperty* prop = NULL;
+        TInt index = iMdEObject.Property( *propertyDef, prop );
+        if ( prop )
+            {
+            const TInt num = sizeof ( clfwrappermusictypes ) / sizeof( TDesC* );
+
+            for ( TInt i = 0; i < num; ++i )
+                {
+                if ( *clfwrappermusictypes[ i ] == prop->TextValueL() )
+                    {
+                    aValue = ECLFMediaTypeMusic;
+                    break;
+                    }
+                }
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemImpl::GetField
+// -----------------------------------------------------------------------------
+//
+TInt CCLFItemImpl::GetField( const TCLFFieldId aFieldId, TPtrC& aValue ) const
+    {
+    MG_DEBUG2( GF, "[CLF]\t CCLFItemImpl::GetField (TPtrC) aFieldId: %d", aFieldId );
+    TInt error = KErrNotFound;
+
+    if ( DeduceFieldFromURI( aFieldId, aValue ))
+        {
+        error = KErrNone;
+        }
+    else
+        {
+        // Get property
+        const TDesC& property = MapFieldToMdEProperty( aFieldId );
+        if ( property != KNullDesC )
+            {
+            CMdEPropertyDef* propertyDef = NULL;
+            TRAP_IGNORE( propertyDef = &iMdEObject.Def().GetPropertyDefL( property ));
+
+            if ( propertyDef )
+                {
+                // Get the actual data
+                CMdEProperty* prop = NULL;
+                const TInt index = iMdEObject.Property( *propertyDef, prop );
+                if ( prop )
+                    {
+                    if ( index >= 0 )
+                        {
+                        CMdETextProperty* textprop = ( CMdETextProperty* ) prop;
+                        aValue.Set( textprop->Value() );
+                        MG_DEBUG2( GF2, "[CLF]\t CCLFItemImpl::GetField value %S", &aValue );
+                        error = KErrNone;          
+                        }
+                    }
+                }
+            }
+        }
+
+    MG_DEBUG2( GF3, "[CLF]\t CCLFItemImpl::GetField (TPtrC) end %d", error );
+    return error;   
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemImpl::GetField
+// -----------------------------------------------------------------------------
+//
+TInt CCLFItemImpl::GetField( const TCLFFieldId aFieldId, TInt32& aValue ) const
+    {
+    MG_DEBUG2( GF4, "[CLF]\t CCLFItemImpl::GetField (TInt) aFieldId: %d", aFieldId );
+    TInt error = KErrNotFound;
+
+    // Get property
+    const TDesC& property = MapFieldToMdEProperty( aFieldId );
+    if ( property != KNullDesC )
+        {
+        CMdEPropertyDef* propertyDef = NULL;
+        TRAP_IGNORE( propertyDef = &iMdEObject.Def().GetPropertyDefL( property ));
+
+        if ( propertyDef )
+            {
+            // Get the actual data
+            CMdEProperty* prop = NULL;
+            const TInt index = iMdEObject.Property( *propertyDef, prop );
+            if ( prop )
+                {
+                if ( index >= 0 )
+                    {
+                    // The following code is a Gallery behavior fix.
+                    if ( &property == &MdeConstants::MediaObject::KTrackProperty )
+                        {
+                        error = KErrNone;
+                        TRAP( error, aValue = prop->Uint16ValueL());
+                        }
+                    else
+                        {
+                        error = KErrNone;
+                        TRAP( error, aValue = prop->Uint32ValueL());
+                        }
+                    }
+                }
+            }
+        }
+    else
+        {
+        // Media type is checked here.
+        if ( aFieldId == ECLFFieldIdMediaType )
+            {
+            CMdEObjectDef& objectDef = iMdEObject.Def();
+            TRAP( error, error = GetMediaTypeL( objectDef, aValue ));
+            }
+        }
+ 
+    return error;   
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemImpl::GetField
+// -----------------------------------------------------------------------------
+//
+TInt CCLFItemImpl::GetField( const TCLFFieldId aFieldId, TTime& aValue ) const
+    {
+    MG_DEBUG2( GF6, "[CLF]\t CCLFItemImpl::GetField (TTime) aFieldId: %d", aFieldId );
+    TInt error = KErrNotFound;
+
+    // Get property
+    const TDesC& property = MapFieldToMdEProperty( aFieldId );
+    if ( property != KNullDesC )
+        {
+        CMdEPropertyDef* propertyDef = NULL;
+        TRAP_IGNORE( propertyDef = &iMdEObject.Def().GetPropertyDefL( property ));
+
+        if ( propertyDef )
+            {
+            // Get the actual data
+            CMdEProperty* prop = NULL;
+            const TInt index = iMdEObject.Property( *propertyDef, prop );
+            if ( prop )
+                {
+                if ( index >= 0 )
+                    {
+                    CMdETimeProperty* timeprop = ( CMdETimeProperty* ) prop;
+                    TRAP_IGNORE( aValue = timeprop->Value() );  // Value() is leaving function
+                    error = KErrNone;
+                    }
+                }
+            }
+        }
+
+    return error;     
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemImpl::MapFieldToMdEProperty
+// -----------------------------------------------------------------------------
+//
+const TDesC& CCLFItemImpl::MapFieldToMdEProperty( const TCLFFieldId aField )
+    {
+    MG_DEBUG2( MFP, "[CLF]\t CCLFItemImpl::MapFieldToMdEProperty aField: %d", aField );
+    const TDesC* ret;
+
+    switch ( aField )
+        {
+        /// integer
+        case ECLFFieldIdFileSize:
+            {
+            ret = &MdeConstants::Object::KSizeProperty;
+            break;
+            }
+        /// File date field:
+        /// date/time
+        case ECLFFieldIdFileDate: 
+            {
+            ret = &MdeConstants::Object::KLastModifiedDateProperty;
+            break;
+            }
+        /// Mime type field:
+        /// descriptor
+        case ECLFFieldIdMimeType:
+            {
+            ret = &MdeConstants::Object::KItemTypeProperty;
+            break;
+            }
+        /// Music file song name tag:
+        /// descriptor
+        case ECLFFieldIdSongName:
+            {
+            ret = &MdeConstants::Object::KTitleProperty;
+            break;
+            }
+        /// Music file artist tag:
+        /// descriptor
+        case ECLFFieldIdArtist:
+            {
+            ret = &MdeConstants::MediaObject::KArtistProperty;
+            break;
+            }
+        /// Music file album tag:
+        /// descriptor
+        case ECLFFieldIdAlbum:
+            {
+            ret = &MdeConstants::Audio::KAlbumProperty;
+            break;
+            }
+        /// Music file genre tag:
+        /// descriptor
+        case ECLFFieldIdGenre:
+            {
+            ret = &MdeConstants::MediaObject::KGenreProperty;
+            break;
+            }
+        /// Music file track number tag:
+        /// integer
+        case ECLFFieldIdTrackNumber:
+            {
+            ret = &MdeConstants::MediaObject::KTrackProperty;
+            break;
+            }
+        /// Music file composer tag:
+        /// descriptor
+        case ECLFFieldIdComposer:
+            {
+            ret = &MdeConstants::Audio::KComposerProperty;
+            break;
+            }
+        default:
+            {
+            ret = &KNullDesC;
+            break;
+            }
+        }
+    return *ret;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFModifiableItemImpl::CCLFModifiableItemImpl
+// -----------------------------------------------------------------------------
+//
+CCLFModifiableItemImpl::CCLFModifiableItemImpl()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFModifiableItemImpl::NewL
+// -----------------------------------------------------------------------------
+//
+CCLFModifiableItemImpl* CCLFModifiableItemImpl::NewL()
+    {
+    return new ( ELeave ) CCLFModifiableItemImpl();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFModifiableItemImpl::~CCLFModifiableItemImpl
+// -----------------------------------------------------------------------------
+//
+CCLFModifiableItemImpl::~CCLFModifiableItemImpl()
+    {
+    iIntMap.Close();
+    iTimeMap.Close();
+    
+    THashMapIter<TCLFFieldId, HBufC*> hashIter(iTextMap);
+    for ( HBufC* const* p = hashIter.NextValue(); p; p = hashIter.NextValue() )
+        {
+        delete *p;
+        }
+    iTextMap.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFModifiableItemImpl::ItemId
+// -----------------------------------------------------------------------------
+//
+TCLFItemId CCLFModifiableItemImpl::ItemId() const
+    {
+    const TInt id = 1;
+    return id;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFModifiableItemImpl::DataType
+// -----------------------------------------------------------------------------
+//
+TCLFItemDataType CCLFModifiableItemImpl::DataType( const TCLFFieldId aFieldId ) const
+    {
+    if (iIntMap.Find(aFieldId))
+        {
+        return ECLFItemDataTypeTInt32;
+        }
+    else if (iTimeMap.Find(aFieldId))
+        {
+        return ECLFItemDataTypeTTime;
+        }
+    else if (iTextMap.Find(aFieldId))
+        {
+        return ECLFItemDataTypeDesC;
+        }
+    else
+        {
+        return ECLFItemDataTypeNull;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFModifiableItemImpl::GetField
+// -----------------------------------------------------------------------------
+//
+TInt CCLFModifiableItemImpl::GetField( const TCLFFieldId aFieldId,
+                                       TPtrC& aValue ) const
+    {
+    if (iTextMap.Find(aFieldId))
+        {
+        aValue.Set( (*iTextMap.Find(aFieldId))->Des() );
+        return KErrNone;
+        }
+        
+    return KErrNotFound;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFModifiableItemImpl::GetField
+// -----------------------------------------------------------------------------
+//
+TInt CCLFModifiableItemImpl::GetField( const TCLFFieldId aFieldId,
+                                       TInt32& aValue ) const
+    {
+    if (iIntMap.Find(aFieldId))
+        {
+        aValue = *iIntMap.Find(aFieldId);
+        return KErrNone;
+        }
+        
+    return KErrNotFound;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFModifiableItemImpl::GetField
+// -----------------------------------------------------------------------------
+//
+TInt CCLFModifiableItemImpl::GetField( const TCLFFieldId aFieldId,
+                                       TTime& aValue ) const
+    {
+    if (iTimeMap.Find(aFieldId))
+        {
+        aValue = TTime(*iTimeMap.Find(aFieldId));
+        return KErrNone;
+        }
+       
+    return KErrNotFound;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFModifiableItemImpl::AddFieldL
+// -----------------------------------------------------------------------------
+//
+void CCLFModifiableItemImpl::AddFieldL( TCLFFieldId aFieldID,
+                                        const TDesC& aValue )
+    {
+    iTextMap.InsertL( aFieldID, aValue.AllocL() );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFModifiableItemImpl::AddFieldL
+// -----------------------------------------------------------------------------
+//
+void CCLFModifiableItemImpl::AddFieldL( TCLFFieldId aFieldID, TInt32 aValue )
+    {
+    iIntMap.InsertL( aFieldID, aValue );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFModifiableItemImpl::AddFieldL
+// -----------------------------------------------------------------------------
+//
+void CCLFModifiableItemImpl::AddFieldL( TCLFFieldId aFieldID,
+                                        const TTime& aValue )
+    {
+    iTimeMap.InsertL( aFieldID, aValue.Int64() );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFItemImpl.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,212 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+
+#ifndef CCLFITEMIMPL_H
+#define CCLFITEMIMPL_H
+
+//  INCLUDES
+#include <MCLFModifiableItem.h>
+#include <e32base.h>
+#include <e32hashtab.h>
+#include <mdesession.h>
+
+// FORWARD DECLARATIONS
+class CMdEObject;
+class CCLFContainerItem;
+class CCLFDbItemContainer;
+
+// CLASS DECLARATION
+
+/**
+*  This class implements MCLFModifiableItem interface.
+*
+*  @lib ContentListingFramework.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CCLFItemImpl ) : public CBase,
+                                    public MCLFItem
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCLFItemImpl* NewLC( CCLFContainerItem& aContainerItem,
+                                    CCLFDbItemContainer& aDbItemContainer );
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCLFItemImpl* NewL( CCLFContainerItem& aContainerItem,
+                                   CCLFDbItemContainer& aDbItemContainer );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCLFItemImpl();
+
+    protected:  // Functions from base classes
+
+        /**
+        * From MCLFItem
+        */
+        virtual TCLFItemId ItemId() const;
+
+        /**
+        * From MCLFItem
+        */
+        virtual TCLFItemDataType DataType( TCLFFieldId aFieldId ) const;
+
+        /**
+        * From MCLFItem
+        */
+        virtual TInt GetField( TCLFFieldId aFieldId, TPtrC& aData ) const;
+
+        /**
+        * From MCLFItem
+        */
+        virtual TInt GetField( TCLFFieldId aFieldId, TInt32& aData ) const;
+
+        /**
+        * From MCLFItem
+        */
+        virtual TInt GetField( TCLFFieldId aFieldId, TTime& aData ) const;
+
+    private:
+
+        TBool DeduceFieldFromURI( const TCLFFieldId aFieldId, TPtrC& aValue ) const;
+
+        /**
+        * Map MdE object definition to CLF media type.
+        * @param aObjectDef Object definition
+        * @param aValue     Media type
+        * @return           KErrNone if media type was identified.
+        *                   KErrNotFound if media type was unknown.
+        */
+        TInt GetMediaTypeL( CMdEObjectDef& aObjectDef, TInt32& aValue ) const;
+
+        void DetermineIfMusicL( CMdEObjectDef& aObjectDef, TInt32& aValue ) const;
+
+
+        /**
+        * Map CLF field to MdE property.
+        * @param aField Field ID.
+        * @return       Property name
+        */
+        static const TDesC& MapFieldToMdEProperty( TCLFFieldId aField );
+
+        /**
+        * C++ default constructor.
+        */
+        CCLFItemImpl( CCLFContainerItem& aContainerItem,
+                             CCLFDbItemContainer& aDbItemContainer );
+
+    private:    // Data
+        
+        // Ref
+        CCLFContainerItem& iItem;
+        // Ref
+        const CMdEObject& iMdEObject;
+        // Ref
+        CCLFDbItemContainer& iDbItemContainer;
+    };
+
+// CLASS DECLARATION
+
+/**
+*  This class implements MCLFModifiableItem interface.
+*
+*  @lib N/A
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CCLFModifiableItemImpl ) : public CBase,
+                                              public MCLFModifiableItem
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCLFModifiableItemImpl* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCLFModifiableItemImpl();
+
+    protected:  // Functions from base classes
+
+        /**
+        * From MCLFModifiableItem
+        */
+        virtual TCLFItemId ItemId() const;
+
+        /**
+        * From MCLFModifiableItem
+        */
+        virtual TCLFItemDataType DataType( TCLFFieldId aFieldId ) const;
+
+        /**
+        * From MCLFModifiableItem
+        */
+        virtual TInt GetField( TCLFFieldId aFieldId, TPtrC& aData ) const;
+
+        /**
+        * From MCLFModifiableItem
+        */
+        virtual TInt GetField( TCLFFieldId aFieldId, TInt32& aData ) const;
+
+        /**
+        * From MCLFModifiableItem
+        */
+        virtual TInt GetField( TCLFFieldId aFieldId, TTime& aData ) const;
+
+        /**
+        * From MCLFModifiableItem
+        */
+        virtual void AddFieldL( TCLFFieldId aFieldID, const TDesC& aValue );
+
+        /**
+        * From MCLFModifiableItem
+        */
+        virtual void AddFieldL( TCLFFieldId aFieldID, TInt32 aValue );
+
+        /**
+        * From MCLFModifiableItem
+        */
+        virtual void AddFieldL( TCLFFieldId aFieldID, const TTime& aValue );
+        
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        inline CCLFModifiableItemImpl();
+
+    private:    // Data
+
+        RHashMap<TCLFFieldId, TInt32> iIntMap;
+        RHashMap<TCLFFieldId, HBufC*> iTextMap;
+        RHashMap<TCLFFieldId, TInt64> iTimeMap;
+        
+    };
+
+#endif      // CCLFITEMIMPL_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFItemListModelImpl.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,556 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCLFItemListModelImpl.h"
+#include    "CCLFDbItemProvider.h"
+#include    "CCLFDefaultOperation.h"
+#include    <MCLFOperationObserver.h>
+#include    <MCLFItem.h>
+#include    <MCLFSortingStyle.h>
+#include    "MGTracePrint.h"
+#include    <ContentListingFactory.h>
+#include    <barsread.h>
+#include    <collate.h>
+#include    "MGDebugPrint.h"
+
+// CONSTANTS
+const TInt KCLFResourceVersionNumber( 1 );
+const TInt KCLFEmptyArrayGranularity( 1 );
+const TInt KCLFSortingStyleArrayGranularity( 3 );
+const TInt KCLFResourceVersion1( 1 );
+const TInt KCLFResourceVersion2( 2 );
+
+_LIT( KCLFAllMimeTypeMatchString, "*" );
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::CCLFItemListModelImpl
+// -----------------------------------------------------------------------------
+//
+CCLFItemListModelImpl::CCLFItemListModelImpl(
+                                        CCLFDbItemProvider* aItemProvider,
+                                        MCLFOperationObserver& aObserver,
+                                        MCLFChangedItemProvider& aChangedItemProvider )
+    : iMimeTypeArray( NULL ),
+      iMediaTypeArray( NULL ),
+      iGrouper( NULL ),
+      iSorter( NULL ),
+      iPostFilter( NULL ),
+      iItemProvider( aItemProvider ),
+      iOperationObserver( aObserver ),
+      iSortingStyleArray( KCLFSortingStyleArrayGranularity ),
+      iChangedItemProvider( aChangedItemProvider ),
+      iIsItemsFetched( EFalse )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::ConstructL()
+    {
+    iMediaTypeArray = new ( ELeave ) CArrayFixFlat< TInt >( KCLFEmptyArrayGranularity );
+    iMimeTypeArray = new ( ELeave ) CDesCArrayFlat( KCLFEmptyArrayGranularity );
+    iDefaultOperation = CCLFDefaultOperation::NewL();
+    iSorter = iDefaultOperation;
+    iGrouper = iDefaultOperation;
+    iPostFilter = iDefaultOperation;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::ConstructL( TResourceReader& aResource )
+   {
+    ConstructL();
+    const TInt version( aResource.ReadInt16() );
+
+    // resource versions are defined in Content Listing framework .rh file
+    if( version != KCLFResourceVersion1 &&
+        version != KCLFResourceVersion2 )
+        {
+        User::Leave( KErrNotSupported );
+        }
+    SetGroupingStyle( TCLFGrouping( aResource.ReadInt32() ) );
+    SetWantedMimeTypesL( aResource );
+    SetWantedMediaTypesL( aResource );
+
+
+    const TInt count(
+        version == KCLFResourceVersion2 ? aResource.ReadInt16() - 1 : 0 );
+
+    MCLFSortingStyle* sortingStyle =
+                        ContentListingFactory::NewSortingStyleLC( aResource );
+    iSortingStyleArray.AppendL( sortingStyle ); // takes ownership
+    CleanupStack::Pop(); // sortingStyle
+    iDefaultOperation->SetSortingStyle( sortingStyle);
+
+    for( TInt i = 0 ; i < count ; ++i )
+        {
+        MCLFSortingStyle* sortingStyle =
+                        ContentListingFactory::NewSortingStyleLC( aResource );
+        iSortingStyleArray.AppendL( sortingStyle ); // takes ownership
+        CleanupStack::Pop(); // sortingStyle
+        iDefaultOperation->AppendSortingStyleL( *sortingStyle );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::NewLC
+// -----------------------------------------------------------------------------
+//
+CCLFItemListModelImpl* CCLFItemListModelImpl::NewLC(
+                                            CCLFDbItemProvider* aItemProvider,
+                                            MCLFOperationObserver& aObserver,
+                                            MCLFChangedItemProvider& aChangedItemProvider )
+    {
+    CCLFItemListModelImpl* self = new( ELeave ) CCLFItemListModelImpl( aItemProvider, aObserver, aChangedItemProvider );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::NewLC
+// -----------------------------------------------------------------------------
+//
+CCLFItemListModelImpl* CCLFItemListModelImpl::NewLC(
+                                            CCLFDbItemProvider* aItemProvider,
+                                            MCLFOperationObserver& aObserver,
+                                            MCLFChangedItemProvider& aChangedItemProvider,
+                                            TResourceReader& aResource)
+    {
+    CCLFItemListModelImpl* self = new( ELeave ) CCLFItemListModelImpl( aItemProvider, aObserver, aChangedItemProvider );
+    CleanupStack::PushL( self );
+    self->ConstructL( aResource );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::~CCLFItemListModelImpl
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCLFItemListModelImpl::~CCLFItemListModelImpl()
+    {
+    iChangedItemProvider.RemoveChangedItemProviderObserver( this );
+    delete iMimeTypeArray;
+    delete iMediaTypeArray;
+    iItemArray.ResetAndDestroy();
+    delete iItemProvider;
+    iResultArray.Close();
+    delete iDefaultOperation;
+    iSortingStyleArray.ResetAndDestroy();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::Item
+// -----------------------------------------------------------------------------
+//
+const MCLFItem& CCLFItemListModelImpl::Item( TInt aIndex ) const
+    {
+    return *( iResultArray[aIndex] );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::ItemCount
+// -----------------------------------------------------------------------------
+//
+TInt CCLFItemListModelImpl::ItemCount() const
+    {
+    return iResultArray.Count();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::SetSortingStyle
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::SetSortingStyle( MCLFSortingStyle* aSortingStyle )
+    {
+    iDefaultOperation->SetSortingStyle( aSortingStyle );
+    iSortingStyleArray.ResetAndDestroy();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::AppendSecondarySortingStyleL
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::AppendSecondarySortingStyleL(
+                                            MCLFSortingStyle& aSortingStyle )
+    {
+    iDefaultOperation->AppendSortingStyleL( aSortingStyle );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::SetCustomSorter
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::SetCustomSorter( MCLFCustomSorter* aCustomSorter )
+    {
+    if( aCustomSorter )
+        {
+        iSorter = aCustomSorter;
+        }
+    else
+        {
+        iSorter = iDefaultOperation;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::SetGroupingStyle
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::SetGroupingStyle( TCLFGrouping aGrouping )
+    {
+    iDefaultOperation->SetGrouping( aGrouping );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::SetCustomGrouper
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::SetCustomGrouper(
+                                            MCLFCustomGrouper* aCustomGrouper )
+    {
+    if( aCustomGrouper )
+        {
+        iGrouper = aCustomGrouper;
+        }
+    else
+        {
+        iGrouper = iDefaultOperation;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::SetPostFilter
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::SetPostFilter( MCLFPostFilter* aPostFilter )
+    {
+    if( aPostFilter )
+        {
+        iPostFilter = aPostFilter;
+        }
+    else
+        {
+        iPostFilter = iDefaultOperation;
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::SetWantedMimeTypesL
+// Method makes new array, because if we can't make new then old array is used
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::SetWantedMimeTypesL( const MDesCArray& aMimeTypes )
+    {
+    const TInt mimeTypeCount( aMimeTypes.MdcaCount() );
+    
+    if( mimeTypeCount > 0 )
+        {
+        if( mimeTypeCount == 1 )
+            {
+            TCollationMethod m = *Mem::CollationMethodByIndex( 0 );
+            m.iFlags = ( TCollationMethod::EIgnoreNone | TCollationMethod::EFoldCase );   
+            
+            const TDesC& mimeType = aMimeTypes.MdcaPoint( 0 );
+            if ( mimeType.CompareC( KCLFAllMimeTypeMatchString, 3, &m ) == 0 )
+                {
+                ResetMimeTypeArrayL();
+                return;
+                }
+            }
+        CDesCArray* array = new (ELeave) CDesCArrayFlat( mimeTypeCount );
+        CleanupStack::PushL( array );
+        for( TInt i = 0 ; i < mimeTypeCount ; ++i )
+            {
+            array->AppendL( aMimeTypes.MdcaPoint( i ) );
+            }
+        CleanupStack::Pop( array );
+        delete iMimeTypeArray;
+        iMimeTypeArray = array;
+        }
+    else
+        {
+        ResetMimeTypeArrayL();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::SetWantedMimeTypesL
+// Method makes new array, because if we can't make new then old array is used
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::SetWantedMimeTypesL( TResourceReader& aResource )
+    {
+    CheckVersionL( aResource, KCLFResourceVersionNumber );
+    const TInt numMimeTypes( aResource.ReadInt16() );
+    if ( numMimeTypes > 0 )
+        {
+        // TResourceReader re-reads the length, have to rewind
+        aResource.Rewind( sizeof( TInt16 ) );
+        CDesCArray* array = aResource.ReadDesCArrayL();
+        delete iMimeTypeArray;
+        iMimeTypeArray = array;
+        }
+    else
+        {
+        ResetMimeTypeArrayL();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::SetWantedMediaTypesL
+// Method makes new array, because if we can't make new then old array is used
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::SetWantedMediaTypesL(
+                            const TArray<TInt>& aMediaTypes )
+    {
+    const TInt count( aMediaTypes.Count() );
+    if( count > 0 )
+        {
+        CArrayFix<TInt>* array =
+                        new ( ELeave ) CArrayFixFlat<TInt>( count );
+        CleanupStack::PushL( array );
+        for( TInt i = 0 ; i < count ; ++i )
+            {
+            array->AppendL( aMediaTypes[i] );
+            }
+        CleanupStack::Pop( array );
+        delete iMediaTypeArray;
+        iMediaTypeArray = array;
+        }
+    else
+        {
+        ResetMediaTypeArrayL();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::SetWantedMediaTypesL
+// Method makes new array, because if we can't make new then old array is used
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::SetWantedMediaTypesL( TResourceReader& aResource )
+    {
+    CheckVersionL( aResource, KCLFResourceVersionNumber );
+    const TInt numMediaTypes( aResource.ReadInt16() );
+    if ( numMediaTypes > 0 )
+        {
+        CArrayFix<TInt>* array =
+                new ( ELeave ) CArrayFixFlat<TInt>( numMediaTypes );
+        CleanupStack::PushL( array );
+        for( TInt i = 0 ; i < numMediaTypes ; ++i )
+            {
+            array->AppendL( aResource.ReadInt32() );
+            }
+        CleanupStack::Pop( array );
+        delete iMediaTypeArray;
+        iMediaTypeArray = array;
+        }
+    else
+        {
+        ResetMediaTypeArrayL();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::RefreshL
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::RefreshL()
+    {
+    MG_TRACE1( KCLFTrace, "CLF list model refresh start" )
+
+    iIsItemsFetched = EFalse;
+    iItemArray.ResetAndDestroy();
+    iItemProvider->PrepareItemsL( *iMimeTypeArray,
+                             iMediaTypeArray->Array(),
+                             *this );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::RefreshL
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::RefreshL( TInt32 aRefreshType )
+    {
+    RPointerArray<MCLFItem> tmpArray;
+    CleanupClosePushL( tmpArray );
+
+    MG_TRACE1( KCLFTrace, "CLF list model refresh post filter start" )
+
+    if( aRefreshType & ECLFRefreshPostFilter )
+        {
+        iPostFilter->FilterItemsL( iItemArray.Array(), tmpArray );
+        }
+    else
+        {
+        CopyArrayL( iItemArray.Array(), tmpArray );
+        }
+    iResultArray.Reset();
+
+    MG_TRACE1( KCLFTrace1, "CLF list model refresh grouping start" )
+
+    if( aRefreshType & ECLFRefreshGrouping )
+        {
+        iGrouper->GroupItemsL( tmpArray.Array(), iResultArray );
+        }
+    else
+        {
+        CopyArrayL( tmpArray.Array(), iResultArray );
+        }
+    CleanupStack::PopAndDestroy( &tmpArray );
+
+    MG_TRACE1( KCLFTrace2, "CLF list model refresh sorting start" )
+
+    if( aRefreshType & ECLFRefreshSorting )
+        {
+        iSorter->SortItemsL( iResultArray );
+        }
+
+    MG_TRACE1( KCLFTrace3, "CLF list model refresh sorting done" )
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::CopyArrayL
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::CopyArrayL( const TArray<MCLFItem*>& aSource,
+                                        RPointerArray<MCLFItem>& aDest )
+    {
+    MG_DEBUG3( AI1, "CCLFItemListModelImpl::CopyArrayL start, aSource: 0x%08x, aDest: 0x%08x",
+               &aSource, &aDest );
+
+    const TInt count( aSource.Count() );
+    for( TInt i = 0 ; i < count ; ++i )
+        {
+        MG_DEBUG3( AI2, "aSource[ %d ]: 0x%08x", i, aSource[ i ] );
+        aDest.AppendL( aSource[i] );
+        }
+
+    MG_DEBUG1( AI3, "CCLFItemListModelImpl::CopyArrayL end" );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::CancelRefresh
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::CancelRefresh()
+    {
+    iItemProvider->Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::OperationCompleteL
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::OperationCompleteL( TInt aError )
+    {
+    MG_TRACE1( KCLFTrace, "CLF list model items ready" )
+
+    TInt error( aError );
+    if ( error == KErrNone )
+        {
+        iIsItemsFetched = ETrue;
+        iResultArray.Reset(); // reset result array before items are deleted
+        iItemArray.ResetAndDestroy();
+        error = iItemProvider->GetItems( iItemArray );
+        if ( error == KErrNone )
+            {
+            TRAP( error, RefreshL( ECLFRefreshAll ) );
+            }
+        }
+    iOperationObserver.HandleOperationEventL( ECLFRefreshComplete, error );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::CheckVersionL
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::CheckVersionL( TResourceReader& aResource,
+                                           TInt aVersion )
+    {
+    const TInt version( aResource.ReadInt16() );
+    if( version != aVersion )
+        {
+        User::Leave( KErrNotSupported );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::ResetMimeTypeArrayL
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::ResetMimeTypeArrayL()
+    {
+    CDesCArray* array =
+                new (ELeave) CDesCArrayFlat( KCLFEmptyArrayGranularity );
+    delete iMimeTypeArray;
+    iMimeTypeArray = array;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::ResetMediaTypeArrayL
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::ResetMediaTypeArrayL()
+    {
+    CArrayFix<TInt>* array =
+                        new ( ELeave ) CArrayFixFlat<TInt>(
+                                            KCLFEmptyArrayGranularity );
+    delete iMediaTypeArray;
+    iMediaTypeArray = array;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFItemListModelImpl::ChangedItemsL
+// -----------------------------------------------------------------------------
+//
+void CCLFItemListModelImpl::NewChangedItemsL()
+    {
+    if( iIsItemsFetched )
+        {
+        const TInt count( iItemArray.Count() );
+        RArray<TCLFItemId> idArray( count == 0 ? 1 : count );
+        CleanupClosePushL( idArray );
+        for( TInt i = 0 ; i < count ; ++i )
+            {
+            idArray.AppendL( iItemArray[i]->ItemId() );
+            }
+        
+        if( iChangedItemProvider.IsItemsForModel( *iMimeTypeArray,
+                                                  iMediaTypeArray->Array(),
+                                                  idArray.Array() ) )
+            {
+            iOperationObserver.HandleOperationEventL( ECLFModelOutdated, KErrNone );
+            }
+        CleanupStack::PopAndDestroy( &idArray );
+        }
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFItemListModelImpl.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,220 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+#ifndef CCLFITEMLISTMODELIMPL_H
+#define CCLFITEMLISTMODELIMPL_H
+
+//  INCLUDES
+#include <MCLFItemListModel.h>
+#include "MCLFItemProviderObserver.h"
+#include "MCLFChangedItemProvider.h"
+#include <badesca.h>
+
+// FORWARD DECLARATIONS
+class MCLFOperationObserver;
+class CCLFDefaultOperation;
+class TResourceReader;
+class CCLFDbItemProvider;
+class CCLFDbItemContainer;
+
+// CLASS DECLARATION
+
+/**
+*  This class implements MCLFItemListModel and MCLFItemProviderObserver
+*  interfaces
+*
+*  @lib ContentListingFramework.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CCLFItemListModelImpl ) : public CBase,
+                                             public MCLFItemListModel,
+                                             public MCLFItemProviderObserver,
+                                             public MCLFChangedItemProviderObserver
+
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCLFItemListModelImpl* NewLC(
+                            CCLFDbItemProvider* aItemProvider,
+                            MCLFOperationObserver& aObserver,
+                            MCLFChangedItemProvider& aChangedItemProvider );
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCLFItemListModelImpl* NewLC(
+                            CCLFDbItemProvider* aItemProvider,
+                            MCLFOperationObserver& aObserver,
+                            MCLFChangedItemProvider& aChangedItemProvider,
+                            TResourceReader& aResource );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCLFItemListModelImpl();
+
+    protected:  // New functions
+
+        void ReadMimeTypeListL( TResourceReader& aResource );
+        void ReadMediaTypeListL( TResourceReader& aResource );
+        void CheckVersionL( TResourceReader& aResource,
+                            TInt aVersion );
+        void CopyArrayL( const TArray<MCLFItem*>& aSource,
+                         RPointerArray<MCLFItem>& aDest );
+        void ResetMimeTypeArrayL();
+        void ResetMediaTypeArrayL();
+
+    protected:  // Functions from base classes
+
+        /**
+        * From MCLFItemListModel
+        */
+        const MCLFItem& Item( TInt aIndex ) const;
+
+        /**
+        * From MCLFItemListModel
+        */
+        TInt ItemCount() const;
+
+        /**
+        * From MCLFItemListModel
+        */
+        void SetSortingStyle( MCLFSortingStyle* aSortingStyle );
+
+        /**
+        * From MCLFItemListModel
+        */
+        void AppendSecondarySortingStyleL(
+                                MCLFSortingStyle& aSortingStyle );
+
+        /**
+        * From MCLFItemListModel
+        */
+        void SetCustomSorter( MCLFCustomSorter* aCustomSorter );
+
+        /**
+        * From MCLFItemListModel
+        */
+        void SetGroupingStyle( TCLFGrouping aGrouping );
+
+        /**
+        * From MCLFItemListModel
+        */
+        void SetCustomGrouper( MCLFCustomGrouper* aCustomGrouper );
+
+        /**
+        * From MCLFItemListModel
+        */
+        void SetPostFilter( MCLFPostFilter* aPostFilter );
+
+        /**
+        * From MCLFItemListModel
+        */
+        void SetWantedMimeTypesL( const MDesCArray& aMimeTypes );
+
+        /**
+        * From MCLFItemListModel
+        */
+        void SetWantedMimeTypesL( TResourceReader& aResource );
+
+        /**
+        * From MCLFItemListModel
+        */
+        void SetWantedMediaTypesL(
+                            const TArray<TInt>& aMediaTypes );
+
+        /**
+        * From MCLFItemListModel
+        */
+        void SetWantedMediaTypesL( TResourceReader& aResource );
+
+        /**
+        * From MCLFItemListModel
+        */
+        void RefreshL( );
+
+        /**
+        * From MCLFItemListModel
+        */
+        void RefreshL( TInt32 aRefreshType );
+
+        /**
+        * From MCLFItemListModel
+        */
+        void CancelRefresh();
+
+        /**
+        * From MCLFItemProviderObserver
+        */
+        void OperationCompleteL( TInt aError );
+
+        void NewChangedItemsL(); 
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CCLFItemListModelImpl(
+                CCLFDbItemProvider* aItemProvider,
+                MCLFOperationObserver& aObserver,
+                MCLFChangedItemProvider& aChangedItemProvider );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        void ConstructL( TResourceReader& aResource );
+
+    private:    // Data
+        // Own. items
+        RPointerArray< MCLFItem > iItemArray;
+        // Ref. items
+        RPointerArray< MCLFItem > iResultArray;
+        // Own mime type list
+        CDesCArray* iMimeTypeArray;
+        // Own media type list
+        CArrayFix< TInt >* iMediaTypeArray;
+        // Ref.
+        MCLFCustomGrouper* iGrouper;
+        // Ref.
+        MCLFCustomSorter* iSorter;
+        // Ref.
+        MCLFPostFilter* iPostFilter;
+        // Own
+        CCLFDbItemProvider* iItemProvider;
+        // Ref.
+        MCLFOperationObserver& iOperationObserver;
+        // Own.
+        CCLFDefaultOperation* iDefaultOperation;
+        // Own: this arrays ows sortings styles that are read from resource.
+        RPointerArray< MCLFSortingStyle > iSortingStyleArray;
+        // Ref:
+        MCLFChangedItemProvider& iChangedItemProvider;
+        // Own
+        TBool iIsItemsFetched;
+    };
+
+#endif      // CCLFITEMLISTMODELIMPL_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFQueryAdapter.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,368 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  QueryAdapter implementation for CLF
+*
+*/
+
+
+// Includes
+#include "CCLFQueryAdapter.h"
+#include "CLFConsts.h"
+#include "CLFPanics.h"
+#include "CLF2MdEConsts.h"
+#include "CLFUtils.h"
+#include <e32base.h>
+#include <e32std.h>
+#include <e32debug.h>
+#include "MGDebugPrint.h"
+#include "MGTracePrint.h"
+#include <mdecondition.h>
+#include <mdeconstants.h>
+#include <mdetextpropertycondition.h>
+#include <mdeobject.h>
+#include <mdeproperty.h>
+#include <mdequery.h>
+#include <mdenamespacedef.h>
+
+// ======== MEMBER FUNCTIONS ========
+
+
+// ---------------------------------------------------------------------------
+// CCLFQueryAdapter::CCLFQueryAdapter
+// Default constructor
+// ---------------------------------------------------------------------------
+//
+CCLFQueryAdapter::CCLFQueryAdapter( CMdESession& aMdESession )
+    : iMdESession( aMdESession ), iDefaultNamespaceDef( NULL )
+    {
+    // pass
+    }
+
+// ---------------------------------------------------------------------------
+// CCLFQueryAdapter::ConstructL
+// Two-phase constructor
+// ---------------------------------------------------------------------------
+//
+void CCLFQueryAdapter::ConstructL()
+    {
+    iDefaultNamespaceDef = &iMdESession.GetDefaultNamespaceDefL();
+    }
+
+// ---------------------------------------------------------------------------
+// CCLFQueryAdapter::NewL
+// Two-phase API constructor
+// ---------------------------------------------------------------------------
+//
+CCLFQueryAdapter* CCLFQueryAdapter::NewL( CMdESession& aMdESession )
+    {
+    CCLFQueryAdapter* self = new( ELeave ) CCLFQueryAdapter( aMdESession );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CCLFQueryAdapter::~CCLFQueryAdapter
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CCLFQueryAdapter::~CCLFQueryAdapter()
+    {
+    iQueryArray.Reset();
+    iStatusArray.Reset();
+    }
+
+// ---------------------------------------------------------------------------
+// CCLFQueryAdapter::QueryMdEObjectsL
+// Queries the objects based on CLF media and mime types
+// ---------------------------------------------------------------------------
+//
+void CCLFQueryAdapter::QueryMdEObjectsL( const MDesCArray& aMimeTypeArray,
+                                         const TArray<TInt>& aMediaTypeArray,
+                                         CMdEObjectQuery*& aQuery,
+                                         TRequestStatus& aStatus )
+    {
+    // hard-coded mime types for music
+    const TDesC* clfwrappermusictypes[] =
+            {
+            &KCLFWrapperMusicTypeMpeg,
+            &KCLFWrapperMusicTypeAac,
+            &KCLFWrapperMusicTypeMp3,
+            &KCLFWrapperMusicTypeX_Mp3,
+            &KCLFWrapperMusicTypeMp4,
+            &KCLFWrapperMusicType3gpp,
+            &KCLFWrapperMusicTypeM4a,
+            &KCLFWrapperMusicType3gpp2,
+            &KCLFWrapperMusicTypeMpeg4,
+            &KCLFWrapperMusicTypeX_Pn_RealAudio,
+            &KCLFWrapperMusicTypeX_Ms_Wma,
+            };
+    
+    CMdEObjectDef& def = iDefaultNamespaceDef->GetObjectDefL( MdeConstants::Object::KBaseObject );
+    __ASSERT_DEBUG( !aQuery, User::Panic( KCLFPanicText, KErrNotReady ));
+    aQuery = iMdESession.NewObjectQueryL( *iDefaultNamespaceDef, def, this );
+    aQuery->SetResultMode( EQueryResultModeId );
+
+    CMdELogicCondition& rootCondition = aQuery->Conditions();
+
+    if ( aMimeTypeArray.MdcaCount() > 0 )
+        {
+        rootCondition.SetOperator( ELogicConditionOperatorOr );
+        CMdEPropertyDef& propDef = def.GetPropertyDefL( MdeConstants::Object::KItemTypeProperty );
+        
+        // Add object conditions based on mime types.
+        for ( TInt index( 0 ); index < aMimeTypeArray.MdcaCount(); index++ )
+            {
+            CMdELogicCondition& logicCond = rootCondition.AddLogicConditionL( ELogicConditionOperatorOr );
+            AddMimeTypeConditionL(logicCond, propDef, aMimeTypeArray.MdcaPoint( index ));
+            }
+        }
+    else
+        {
+        TBool music = EFalse;
+        TBool sounds = EFalse;
+
+        // Add mime conditions for audio types
+        CMdEObjectDef* objDef = NULL;
+        CMdEPropertyDef* propDef = NULL;
+
+        const TInt typeCount( aMediaTypeArray.Count() );
+        
+        // Add object conditions based on CLF media types.
+        if ( typeCount > 0 )
+            {
+            rootCondition.SetOperator( ELogicConditionOperatorOr );
+
+            for ( TInt index( 0 ); index < typeCount; index++ )
+               {
+               const TDesC& type = CLFUtils::MapClfType( aMediaTypeArray[ index ] );
+               if ( type != KNullDesC )
+                   {
+                   CMdEObjectDef& objDef = iDefaultNamespaceDef->GetObjectDefL( type );
+                   if( aMediaTypeArray[ index ] == ECLFMediaTypeSound )
+                       {
+                       sounds = ETrue;
+                       }
+                   else if( aMediaTypeArray[ index ] == ECLFMediaTypeMusic )
+                       {
+                       music = ETrue;
+                       }
+                   else
+                       {
+                       rootCondition.AddObjectConditionL( objDef );     
+                       }
+                   }
+               }
+            if( sounds && music )
+                {
+                CMdEObjectDef& objDef = iDefaultNamespaceDef->GetObjectDefL( CLFUtils::MapClfType( ECLFMediaTypeMusic ) );
+                rootCondition.AddObjectConditionL( objDef );    
+                }
+            else if( sounds )
+                {
+                objDef = &iDefaultNamespaceDef->GetObjectDefL( CLFUtils::MapClfType( ECLFMediaTypeSound ) );
+                propDef = &objDef->GetPropertyDefL( MdeConstants::Object::KItemTypeProperty );
+                CMdELogicCondition& soundCond = rootCondition.AddLogicConditionL( ELogicConditionOperatorAnd );
+
+                // add all necessary mime types to query conditions
+                const TInt num = sizeof ( clfwrappermusictypes ) / sizeof( TDesC* );
+                for ( TInt i = 0; i < num; ++i )
+                    {
+                    CMdELogicCondition& mimeCond = soundCond.AddLogicConditionL( ELogicConditionOperatorOr );
+                    mimeCond.AddPropertyConditionL( *propDef, ETextPropertyConditionCompareEquals, *clfwrappermusictypes[i] );
+                    mimeCond.SetNegate( ETrue );
+                    }  
+                soundCond.AddObjectConditionL( *objDef );
+                }
+            else if( music )
+                {
+                objDef = &iDefaultNamespaceDef->GetObjectDefL( CLFUtils::MapClfType( ECLFMediaTypeMusic ) );
+                propDef = &objDef->GetPropertyDefL( MdeConstants::Object::KItemTypeProperty );
+                CMdELogicCondition& musicCond = rootCondition.AddLogicConditionL( ELogicConditionOperatorAnd );
+
+                // add all necessary mime types to query conditions
+                const TInt num = sizeof ( clfwrappermusictypes ) / sizeof( TDesC* );
+                CMdELogicCondition& mimeCond = musicCond.AddLogicConditionL( ELogicConditionOperatorOr );
+                for ( TInt i = 0; i < num; ++i )
+                    {
+                    mimeCond.AddPropertyConditionL( *propDef, ETextPropertyConditionCompareEquals, *clfwrappermusictypes[i] );
+                    }  
+                musicCond.AddObjectConditionL( *objDef );
+                }
+            }
+        }
+
+    aStatus = KRequestPending;
+    iStatusArray.Append( &aStatus );
+    iQueryArray.Append( aQuery );
+
+    // Check that we can actually execute the query. We can if we have at least one query condition.
+    if ( rootCondition.Count() > 0 )
+        {
+        MG_DEBUG1( QMO5, "[CLF]\t CCLFQueryAdapter::QueryMdEObjectsL execute query");
+        aQuery->FindL();
+        }
+    else
+        {
+        MG_DEBUG1( QMO6, "[CLF]\t CCLFQueryAdapter::QueryMdEObjectsL unknown conditions");
+        CompleteRequest( *aQuery, KErrNone );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CCLFQueryAdapter::QueryMdEObjectsL
+// Queries the objects based on CLF ids
+// ---------------------------------------------------------------------------
+//
+void CCLFQueryAdapter::QueryMdEObjectsL( const TArray< TCLFItemId >& aItemIDArray,
+                                         const TDesC& aObjDefStr,
+                                         CMdEObjectQuery*& aQuery,
+                                         TRequestStatus& aStatus )
+    {
+    CMdEObjectDef& objDef = iDefaultNamespaceDef->GetObjectDefL( aObjDefStr );
+    __ASSERT_DEBUG( !aQuery, User::Panic( KCLFPanicText, KErrNotReady ));
+    aQuery = iMdESession.NewObjectQueryL( *iDefaultNamespaceDef, objDef, this );
+    aQuery->SetResultMode( EQueryResultModeId );
+
+    CMdELogicCondition& rootCondition = aQuery->Conditions();
+    rootCondition.SetOperator( ELogicConditionOperatorOr );
+
+    const TInt idCount( aItemIDArray.Count()  );
+    if ( idCount > 0 )
+        {
+        RArray< TItemId > objectIds;
+
+        // Add object conditions based on CLF ids.
+        for ( TInt index( 0 ); index < idCount; index++ )
+            {
+            objectIds.Append( aItemIDArray[ index ] );
+            }
+        CleanupClosePushL( objectIds );
+        rootCondition.AddObjectConditionL( objectIds );
+        CleanupStack::PopAndDestroy( &objectIds );
+        }
+
+    aStatus = KRequestPending;
+    iStatusArray.Append( &aStatus );
+    iQueryArray.Append( aQuery );
+
+    // Check that we can actually execute the query. We can if we have at least one query condition.
+    if ( rootCondition.Count() > 0 )
+        {
+        MG_DEBUG1( QMO4, "[CLF]\t CCLFQueryAdapter::QueryMdEObjectsL execute query" );
+        aQuery->FindL();
+        }
+    else
+        {
+        MG_DEBUG1( QMO5, "[CLF]\t CCLFQueryAdapter::QueryMdEObjectsL unknown conditions" );
+        CompleteRequest( *aQuery, KErrNone );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CCLFQueryAdapter::HandleQueryNewResults
+// Called to notify the observer that new results have been received 
+// ---------------------------------------------------------------------------
+//
+#ifdef MG_ENABLE_TRACE_PRINT
+void CCLFQueryAdapter::HandleQueryNewResults( CMdEQuery& /* aQuery */,
+                                              const TInt aFirstNewItemIndex,
+                                              const TInt aNewItemCount )
+#else
+void CCLFQueryAdapter::HandleQueryNewResults( CMdEQuery& /* aQuery */,
+                                              const TInt /* aFirstNewItemIndex */,
+                                              const TInt /* aNewItemCount */ )
+#endif
+    {
+    MG_DEBUG3( HQN1, "[CLF]\t HandleQueryNewResults, aFirstNewItemIndex == %d, aNewItemCount == %d",
+               aFirstNewItemIndex, aNewItemCount );
+
+    /* This method could be used to receive metadata query results in batches.
+     * This feature is currently unimplemented. */
+    }
+
+// ---------------------------------------------------------------------------
+// CCLFQueryAdapter::HandleQueryCompleted
+// Called to notify the observer that the query has been completed
+// ---------------------------------------------------------------------------
+//
+void CCLFQueryAdapter::HandleQueryCompleted( CMdEQuery& aQuery, const TInt aError )
+    {
+    MG_DEBUG2( HQC1, "[CLF]\t CCLFQueryAdapter::HandleQueryCompleted %d", aError );
+    MG_DEBUG2( HQC2, "[CLF]\t aQuery.Count() returns: %d", aQuery.Count() );
+    MG_DEBUG2( HQC3, "[CLF]\t Class instance %d", this );
+
+    CompleteRequest( aQuery, aError );
+    }
+
+// ---------------------------------------------------------------------------
+// CCLFQueryAdapter::CompleteRequest
+// ---------------------------------------------------------------------------
+//
+void CCLFQueryAdapter::CompleteRequest( CMdEQuery& aQuery, const TInt aError )
+    {
+    MG_DEBUG1( HQC4, "[CLF]\t CCLFQueryAdapter::CompleteRequest" );
+    const TInt count = iQueryArray.Count();
+    TInt i( 0 );
+
+    for ( i = 0; i < count; ++i )
+        {
+        if ( iQueryArray[ i ] == &aQuery )
+            {
+            User::RequestComplete( iStatusArray[ i ], aError );
+            iStatusArray.Remove( i );
+            iQueryArray.Remove( i );
+            break;
+            }
+        }
+#ifdef _DEBUG
+    _LIT( KCLFWQAPanicText, "HandleQueryCompleted");
+    __ASSERT_DEBUG( i < count, User::Panic( KCLFWQAPanicText, KErrAbort ));
+#endif
+    }
+
+// ---------------------------------------------------------------------------
+// CCLFQueryAdapter::AddMimeTypeConditionL
+// ---------------------------------------------------------------------------
+//
+void CCLFQueryAdapter::AddMimeTypeConditionL( CMdELogicCondition& aLogicCondition,
+                                              const CMdEPropertyDef& aPropDef, 
+                                              const TPtrC& aMimeType ) 
+    {
+    HBufC16* result = HBufC16::NewLC( aMimeType.Length() );
+    TPtr16 modResult = result->Des();
+    modResult.Copy( aMimeType );
+
+    // strip possible left asterisk
+    if ( modResult.Locate( '*' ) == 0 )
+        {
+        modResult.Copy( modResult.Right( modResult.Length() - 1 ));
+        }
+
+    if ( modResult.Length() > 0 )
+        {
+        // strip possible right asterisk
+        if ( modResult.LocateReverse( '*' ) == modResult.Length() - 1 )
+            {
+            modResult.Copy( modResult.Left( modResult.Length() - 1 ));
+            }
+
+        // add type condition
+        aLogicCondition.AddPropertyConditionL( aPropDef, ETextPropertyConditionCompareContains, modResult );
+        }
+    CleanupStack::PopAndDestroy( result );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFQueryAdapter.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,127 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  MetadataEngine query adapter for CLF
+*
+*/
+
+
+#ifndef C_CCLFQUERYADAPTER_H
+#define C_CCLFQUERYADAPTER_H
+
+// INCLUDES
+#include <e32base.h>
+#include <CLFContentListing.hrh>
+#include <CLFContentListing.h>
+#include <bamdesca.h>
+#include <mdesession.h>
+#include <mdeobjectquery.h>
+
+// FORWARD DECLARATIONS
+class CMdEObject;
+class CMdEProperty;
+class CMdEPropertyDefSet;
+
+/**
+ *  Wraps MdE functionality for Content Listing Framework
+ *
+ *  @lib clf2mde
+ *  @since S60 3.1
+ */
+NONSHARABLE_CLASS( CCLFQueryAdapter ) : public CBase, 
+                                        public MMdEQueryObserver
+    {
+    public: // Constructors and destructor
+
+        // 2-phase constructor
+        static CCLFQueryAdapter* NewL( CMdESession& aMdESession );
+
+        // Destructor
+        virtual ~CCLFQueryAdapter();
+
+    public: // New functions
+
+        /**
+         * Queries the mediatypes
+         *
+         * @since S60 3.1
+         * @param aMimeTypeArray array for mime types which are included in result
+         * @param aMediaTypeArray array for media types which are included in result
+         * @param aStatus reference to TRequestStatus which is completed
+         */
+
+        void QueryMdEObjectsL( const MDesCArray& aMimeTypeArray,
+                               const TArray< TInt >& aMediaTypeArray,
+                               CMdEObjectQuery*& aQuery,
+                               TRequestStatus& aStatus );
+
+        void QueryMdEObjectsL( const TArray< TCLFItemId >& aItemIDArray,
+                               const TDesC& aObjDefStr,
+                               CMdEObjectQuery*& aQuery,
+                               TRequestStatus& aStatus );
+
+    protected: // Functions from base classes
+    
+        /**
+         * From MMdEQueryObserver
+         */
+        void HandleQueryNewResults( CMdEQuery& aQuery,
+                                    TInt aFirstNewItemIndex,
+                                    TInt aNewItemCount );
+
+        /**
+         * From MMdEQueryObserver
+         */
+        void HandleQueryCompleted( CMdEQuery& aQuery, TInt aError );
+
+    private: // New functions
+
+        /**
+        * Helper function.
+        */
+        void CompleteRequest( CMdEQuery& aQuery, TInt aError );
+
+        void AddMimeTypeConditionL( CMdELogicCondition& aLogicCondition,
+                                    const CMdEPropertyDef& aPropDef,
+                                    const TPtrC& aMimeType );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CCLFQueryAdapter( CMdESession& aMdESession );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private: // data
+
+        /** MdE session. Ref */
+    	CMdESession& iMdESession;
+
+        /** MdE namespace */
+        CMdENamespaceDef* iDefaultNamespaceDef;
+
+        /** MdE query array */
+        RPointerArray< CMdEQuery > iQueryArray;
+
+        /** Request status array */
+        RPointerArray< TRequestStatus > iStatusArray;
+    };
+
+#endif // C_CCLFQUERYADAPTER_H
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFServerProxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1291 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include <PathInfo.h>
+#include <driveinfo.h>
+#include <s32mem.h>
+#include <bautils.h>
+#include <mdeobjectquery.h>
+#include <mdeconstants.h>
+#include <collate.h>
+#include "CLFConsts.h"
+#include "CLFPanics.h"
+#include "CCLFServerProxy.h"
+#include "mdsutils.h"
+
+// CONSTANTS
+const TInt KCLFDefaultBufferLength( 64 );
+const TInt KCLFDefaultArrayGranularity( 4 );
+const TInt KCLFExtensionArrayGranularity( 49 );
+
+_LIT( KCLFDriveLetterFormatString, ":\\" );
+const TInt KCLFDriveC( 'C' );
+
+const TInt KDelayNotityCLFGetUpdateEventMaxTimes = 30;
+const TInt KCLFWrapperHarvesterEventInterval = 60;
+
+_LIT( KExtensionMp3,    "mp3" );
+_LIT( KExtensionAac,    "aac" );
+_LIT( KExtensionAmr,    "amr" );
+_LIT( KExtensionAwb,    "awb" );
+_LIT( KExtensionMid,    "mid" );
+_LIT( KExtensionMidi,   "midi" );
+_LIT( KExtensionSpMid,  "spmid" );
+_LIT( KExtensionRng,    "rng" );
+_LIT( KExtensionMxmf,   "mxmf" );
+_LIT( KExtensionWav,    "wav" );
+_LIT( KExtensionAu,     "au" );
+_LIT( KExtensionWma,    "wma" );
+_LIT( KExtensionNrt,    "nrt" );
+_LIT( KExtensionRa,    "ra" );
+
+_LIT( KExtJpg, "JPG" );
+_LIT( KExtJpeg, "JPEG" );
+_LIT( KExtJp2, "JP2" );
+_LIT( KExtJ2k, "J2K" ); 
+_LIT( KExtJpx, "JPX" ); 
+_LIT( KExtJpf, "JPF" );
+_LIT( KExtMbm, "MBM" ); 
+_LIT( KExtPng, "PNG" );
+_LIT( KExtGif, "GIF" );
+_LIT( KExtBmp, "BMP" );
+_LIT( KExtTif, "TIF" );
+_LIT( KExtTiff, "TIFF" );
+_LIT( KExtOta, "OTA" );
+_LIT( KExtWbmp, "WBMP" );
+_LIT( KExtWmf, "WMF" ); 
+_LIT( KExtOtb, "OTB" ); 
+
+_LIT(KExtOma1, "dcf");
+_LIT(KExtOma2, "odf");
+_LIT(KExtOma3, "dm");
+_LIT(KExtOma4, "o4a");
+_LIT(KExtOma5, "o4v");
+
+_LIT( KExtensionMp4,   "mp4" );
+_LIT( KExtensionMpg4,  "mpg4" );
+_LIT( KExtensionMpeg4, "mpeg4" );
+_LIT( KExtensionM4v,   "m4v" );
+_LIT( KExtensionM4a,   "m4a" );
+_LIT( KExtension3gp,   "3gp" );
+_LIT( KExtension3gpp,  "3gpp" );
+_LIT( KExtension3g2,   "3g2" );
+_LIT( KExtensionRm,    "rm" );
+_LIT( KExtensionRmvb,  "rmvb" );
+_LIT( KExtensionRam,   "ram" );
+_LIT( KExtensionRv,    "rv" );
+_LIT( KExtensionWmv,    "wmv" );
+_LIT( KExtensionAvi,    "avi" );
+
+// ======== MEMBER FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// CItemsDeletedHandler::CUpdateItemsHandler
+// -----------------------------------------------------------------------------
+//
+inline CUpdateItemsHandler::CUpdateItemsHandler()
+    : iWasNotificationHandled( EFalse ), iParentObserver( NULL ),
+      iParentPresentObserver( NULL ), iRemoveObserver( EFalse )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateIDsHandler::Start
+// -----------------------------------------------------------------------------
+//
+void CUpdateItemsHandler::StartScheduler()
+    {
+    if( !iScheduler.IsStarted() )
+        {
+        iScheduler.Start();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateIDsHandler::AsyncStop
+// -----------------------------------------------------------------------------
+//
+void CUpdateItemsHandler::AsyncStopScheduler()
+    {
+    iScheduler.AsyncStop();
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateIDsHandler::WasNotificationHandled
+// -----------------------------------------------------------------------------
+//
+TBool CUpdateItemsHandler::WasNotificationHandled() const
+    {
+    return iWasNotificationHandled;
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateIDsHandler::WasNotificationHandled
+// -----------------------------------------------------------------------------
+//
+void CUpdateItemsHandler::SetRemoveObserverFlag( TBool aRemove )
+    {
+    iRemoveObserver = aRemove;
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateIDsHandler::NewL
+// -----------------------------------------------------------------------------
+//
+CUpdateIDsHandler* CUpdateIDsHandler::NewL( const TArray< TCLFItemId >& aItemIDArray )
+    {
+    CUpdateIDsHandler* self = new( ELeave ) CUpdateIDsHandler( aItemIDArray );
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateIDsHandler::~CUpdateIDsHandler
+// -----------------------------------------------------------------------------
+//
+CUpdateIDsHandler::~CUpdateIDsHandler()
+    {
+    iIdsPendingUpdate.Reset();
+
+    if ( iScheduler.IsStarted() )
+        {
+        iScheduler.AsyncStop();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::~CUpdateFoldersHandler
+// -----------------------------------------------------------------------------
+//
+void CUpdateIDsHandler::StartHandlingL()
+    {
+    // Pass through.
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateIDsHandler::HandleObjectNotification
+// -----------------------------------------------------------------------------
+//
+void CUpdateIDsHandler::HandleObjectNotification( const TItemId aId, TObserverNotificationType /* aType */ )
+    {
+    iWasNotificationHandled = EFalse;
+
+    TInt index = iIdsPendingUpdate.Find( aId );
+    if ( index != KErrNotFound )
+        {
+        iWasNotificationHandled = ETrue;
+        iIdsPendingUpdate.Remove( index );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateIDsHandler::AllDone
+// -----------------------------------------------------------------------------
+//
+TBool CUpdateIDsHandler::AllDone() const
+    {
+    return iIdsPendingUpdate.Count() == 0 ? ETrue : EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateIDsHandler::CUpdateIDsHandler
+// -----------------------------------------------------------------------------
+//
+inline CUpdateIDsHandler::CUpdateIDsHandler( const TArray< TCLFItemId >& aItemIDArray )
+    {
+    const TInt idCount( aItemIDArray.Count() );
+    for ( TInt i = 0; i < idCount; ++i )
+        {
+        if ( iIdsPendingUpdate.Find( aItemIDArray[ i ] ) == KErrNotFound )
+            {
+            iIdsPendingUpdate.Append( aItemIDArray[ i ] );
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CItemsDeletedHandler::NewL
+// -----------------------------------------------------------------------------
+//
+CItemsDeletedHandler* CItemsDeletedHandler::NewL( CMdESession& aMdESession, 
+                                                                                    const CDesCArray& aUriArray,
+                                                                                    MMdEObjectObserver* aParentObserver,
+                                                                                    MMdEObjectPresentObserver* aParentPresentObserver )
+    {
+    CItemsDeletedHandler* self = new( ELeave ) CItemsDeletedHandler( aMdESession );
+    CleanupStack::PushL( self );
+    self->ConstructL( aUriArray, aParentObserver, aParentPresentObserver );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CItemsDeletedHandler::~CUpdateItemsHandlerWithIDs
+// -----------------------------------------------------------------------------
+//
+CItemsDeletedHandler::~CItemsDeletedHandler()
+    {
+    if( iRemoveObserver )
+        {
+        TRAP_IGNORE( iMdESession.RemoveObjectObserverL( *iParentObserver ) );
+        TRAP_IGNORE( iMdESession.RemoveObjectPresentObserverL( *iParentPresentObserver ) );
+        }
+    iIdsPendingRemoval.Reset();
+    iObjectsPendingRemoval.ResetAndDestroy();
+    
+    if ( iScheduler.IsStarted() )
+        {
+        iScheduler.AsyncStop();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::StartHandlingL
+// -----------------------------------------------------------------------------
+//
+void CItemsDeletedHandler::StartHandlingL()
+    {
+    const TInt count( iObjectsPendingRemoval.Count() );
+    for ( TInt i = 0; i < count; ++i )
+        {
+        // If object for URI to be removed is in MDS, then remove it from MDS. Obviates
+        // the need to rely on unreliable filemonitorplugin.
+        const TItemId id = iMdESession.RemoveObjectL( iObjectsPendingRemoval[ i ]->Id() );
+        
+        if ( id != KNoId )
+            {
+            iIdsPendingRemoval.Append( id );
+            }
+        }
+    iObjectsPendingRemoval.ResetAndDestroy();
+    }
+
+// -----------------------------------------------------------------------------
+// CItemsDeletedHandler::HandleObjectNotification
+// -----------------------------------------------------------------------------
+//
+void CItemsDeletedHandler::HandleObjectNotification( const TItemId aId, TObserverNotificationType aType )
+    {
+    iWasNotificationHandled = EFalse;
+
+    if ( aType == ENotifyRemove )
+        {
+        TInt index = iIdsPendingRemoval.Find( aId );
+        if ( index != KErrNotFound )
+            {
+            iWasNotificationHandled = ETrue;
+            iIdsPendingRemoval.Remove( index );
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateIDsHandler::AllDone
+// -----------------------------------------------------------------------------
+//
+TBool CItemsDeletedHandler::AllDone() const
+    {
+    return iIdsPendingRemoval.Count() == 0 ? ETrue : EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CItemsDeletedHandler::CItemsDeletedHandler
+// -----------------------------------------------------------------------------
+//
+inline CItemsDeletedHandler::CItemsDeletedHandler( CMdESession& aMdESession )
+      : iMdESession( aMdESession )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CItemsDeletedHandler::ConstructL
+// -----------------------------------------------------------------------------
+//
+inline void CItemsDeletedHandler::ConstructL( const CDesCArray& aUriArray,
+                                                                            MMdEObjectObserver* aParentObserver,
+                                                                            MMdEObjectPresentObserver* aParentPresentObserver)
+    {
+    iParentObserver = aParentObserver;
+    iParentPresentObserver = aParentPresentObserver;
+    // This leave is needed, if the handler was deleted earlier and the parent observer was removed 
+    TRAP_IGNORE( iMdESession.AddObjectObserverL( *iParentObserver ) );
+    TRAP_IGNORE( iMdESession.AddObjectPresentObserverL( *iParentPresentObserver ) );
+    const TInt uriCount( aUriArray.Count() );
+    for ( TInt i = 0; i < uriCount; ++i )
+        {
+        CMdEObject* object = NULL;
+
+        object = iMdESession.GetObjectL( aUriArray.MdcaPoint( i ));
+        CleanupStack::PushL( object );
+        if ( object )
+            {
+            iObjectsPendingRemoval.AppendL( object );
+            }
+        CleanupStack::Pop( object );
+        }
+    iRemoveObserver = ETrue;
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::NewL
+// -----------------------------------------------------------------------------
+//
+CUpdateFoldersHandler* CUpdateFoldersHandler::NewL( CMdESession& aMdESession, const CDesCArray& aUriArray,
+                                                                                       MMdEObjectObserver* aParentObserver, 
+                                                                                       MMdEObjectPresentObserver* aParentPresentObserver, 
+																					   RFs& aFs,
+																					   RHarvesterClient& aHarvester,
+																					   CDesCArray* aSupportedTypes )
+    {
+    CUpdateFoldersHandler* self = new( ELeave ) CUpdateFoldersHandler( aMdESession, 
+                                                                            aFs, aHarvester, aSupportedTypes );
+    CleanupStack::PushL( self );
+    self->ConstructL( aUriArray, aParentObserver, aParentPresentObserver );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::~CUpdateFoldersHandler
+// -----------------------------------------------------------------------------
+//
+CUpdateFoldersHandler::~CUpdateFoldersHandler()
+    {
+    if( iRemoveObserver )
+        {
+        TRAP_IGNORE( iMdESession.RemoveObjectObserverL( *iParentObserver ) );
+        TRAP_IGNORE( iMdESession.RemoveObjectPresentObserverL( *iParentPresentObserver ) );
+        }
+    iUrisFound.Reset();
+    iFoldersFound.Reset();
+    iIdsPendingRemoval.Reset();
+    iIdsPendingUpdate.Reset();
+    iIdsHandled.Reset();
+    
+    if ( iScheduler.IsStarted() )
+        {
+        iScheduler.AsyncStop();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::StartHandlingL
+// -----------------------------------------------------------------------------
+//
+void CUpdateFoldersHandler::StartHandlingL()
+    {
+    CMdEObjectQuery* query = NULL;
+
+    iIdsPendingRemoval.Reset();
+    iIdsPendingUpdate.Reset();
+    iIdsHandled.Reset();
+    
+    iStartingHandling = ETrue;
+    DoQueryL( query, iFoldersFound );
+    CleanupStack::PushL( query );
+    if( !iScheduler.IsStarted() )
+        {
+        iScheduler.Start();
+        }
+    TRAP_IGNORE( DetermineIdsToRemoveL( *query ) );
+    TRAP_IGNORE( DetermineIdsToUpdateL( iUrisFound ) );
+    CleanupStack::PopAndDestroy( query );
+    iStartingHandling = EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::HandleObjectNotification
+// -----------------------------------------------------------------------------
+//
+void CUpdateFoldersHandler::HandleObjectNotification( const TItemId aId, TObserverNotificationType aType )
+    {
+    iWasNotificationHandled = EFalse;
+
+    if ( aType == ENotifyRemove )
+        {
+        const TInt index = iIdsPendingRemoval.Find( aId );
+        
+        if ( index != KErrNotFound )
+            {
+            iIdsPendingRemoval.Remove( index );
+            iWasNotificationHandled = ETrue;
+            }
+        }
+    else if ( aType == ENotifyAdd || aType == ENotifyModify )
+        {
+        const TInt index = iIdsPendingUpdate.Find( aId );
+        
+        if ( index != KErrNotFound )
+            {
+            iIdsPendingUpdate.Remove( index );
+            const TInt handledIndex = iIdsHandled.Find( aId );
+            if( handledIndex != KErrNotFound )
+                {
+                iIdsHandled.Remove( handledIndex );
+                }
+            iWasNotificationHandled = ETrue;
+            }
+        else if( iHarvestingOngoing )
+            { 
+            iIdsHandled.Append( aId );
+            iWasNotificationHandled = ETrue;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::AllDone
+// -----------------------------------------------------------------------------
+//
+TBool CUpdateFoldersHandler::AllDone() const
+    {
+    return ( iIdsPendingRemoval.Count() == 0 &&
+             iIdsPendingUpdate.Count() == 0 &&
+             !iStartingHandling ) ? ETrue : EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::HandleQueryNewResults
+// -----------------------------------------------------------------------------
+//
+void CUpdateFoldersHandler::HandleQueryNewResults( CMdEQuery& /* aQuery */, TInt /* aFirstNewItemIndex */, TInt /* aNewItemCount */ )
+    {
+    // Pass through.
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::HandleQueryCompleted
+// -----------------------------------------------------------------------------
+//
+void CUpdateFoldersHandler::HandleQueryCompleted( CMdEQuery& /* aQuery */, TInt /* aError */ )
+    {
+    iScheduler.AsyncStop();
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::CUpdateFoldersHandler
+// -----------------------------------------------------------------------------
+//
+inline CUpdateFoldersHandler::CUpdateFoldersHandler( CMdESession& aMdESession, 
+                                                                                         RFs& aFs,
+                                                                                         RHarvesterClient& aHarvester,
+                                                                                         CDesCArray* aSupportedTypes )
+    : iFs( aFs ),
+      iUrisFound( KCLFDefaultArrayGranularity ),
+      iFoldersFound( KCLFDefaultArrayGranularity ),
+      iMdESession( aMdESession ),
+      iHarvester( aHarvester ),
+      iHarvestError( KErrNone ),
+      iStartingHandling( EFalse ),
+      iExtensionArray( aSupportedTypes ),
+      iHarvestingOngoing( EFalse )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::ConstructL
+// -----------------------------------------------------------------------------
+//
+inline void CUpdateFoldersHandler::ConstructL( const CDesCArray& aUriArray,
+                                                                             MMdEObjectObserver* aParentObserver,
+                                                                             MMdEObjectPresentObserver* aParentPresentObserver )
+    {
+    iParentObserver = aParentObserver;
+    iParentPresentObserver = aParentPresentObserver;
+    // This leave is needed, if the handler was deleted earlier and the parent observer was removed 
+    TRAP_IGNORE( iMdESession.AddObjectObserverL( *iParentObserver ) );
+    TRAP_IGNORE( iMdESession.AddObjectPresentObserverL( *iParentPresentObserver ) );
+
+    for ( TInt i = 0; i < aUriArray.MdcaCount(); ++i )
+        {
+        ScanNodeForUrisL( aUriArray.MdcaPoint( i ), iUrisFound, iFoldersFound );
+        }
+ 
+    iRemoveObserver = ETrue ;
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::ScanNodeForUrisL
+// -----------------------------------------------------------------------------
+//
+void CUpdateFoldersHandler::ScanNodeForUrisL( const TDesC16& aNodeName, CDesCArray& aUriArray, CDesCArray& aFolderArray )
+    {
+    TBool isFolder = EFalse;
+
+    BaflUtils::IsFolder( iFs, aNodeName, isFolder );
+    if ( isFolder )
+        {
+        if ( !BaflUtils::FolderExists( iFs, aNodeName ) )
+            {
+            return;
+            }
+        CDirScan* dirscan = CDirScan::NewL( iFs );
+        CDir* dir = NULL;
+
+        CleanupStack::PushL( dirscan );
+        dirscan->SetScanDataL( aNodeName, KEntryAttNormal, EDirsAnyOrder );
+
+        for ( dirscan->NextL( dir ); dir; dirscan->NextL( dir ) )
+            {
+            CleanupStack::PushL( dir );
+
+            for ( TInt i = 0 ; i < dir->Count() ; ++i )
+                {
+                const TEntry& entry = ( *dir )[ i ];
+                const TInt totalLength = entry.iName.Length() + dirscan->FullPath().Length() + 1;
+
+                if (( !entry.IsDir() ) && ( totalLength <= KMaxFileName ))
+                    {
+                    TFileName currentPath( dirscan->FullPath() );
+                    currentPath.Append( ( *dir )[ i ].iName );
+                    aUriArray.AppendL( currentPath );
+                    }
+                }
+            CleanupStack::PopAndDestroy( dir );
+
+            }
+        aFolderArray.AppendL( aNodeName );
+
+        CleanupStack::PopAndDestroy( dirscan );
+        }
+    else
+        {
+        aUriArray.AppendL( aNodeName );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::DetermineIdsToRemove
+// -----------------------------------------------------------------------------
+//
+void CUpdateFoldersHandler::DetermineIdsToRemoveL ( const CMdEObjectQuery& aQuery )
+    {
+    RProcess process( KCurrentProcessHandle );
+    process.Id().Id(); 
+    if( process.HasCapability( ECapabilityWriteDeviceData ) )
+        {
+        const TInt queryCount( aQuery.Count() );
+        for ( TInt i = 0; i < queryCount; ++i )
+            {
+            CMdEObject& object = aQuery.Result( i );
+            TEntry entry;
+            const TInt err = iFs.Entry( object.Uri(), entry );
+
+            if ( err == KErrNotFound )
+                {
+                // Queried metadata object has a URI that does not match a filesystem URI.
+                // It must therefore be removed.
+                TItemId id( KNoId ); 
+                id = iMdESession.RemoveObjectL( object.Id() );
+                if ( id != KNoId )
+                    {
+                    iIdsPendingRemoval.Append( id );
+                    }
+                }
+            }
+        }
+    process.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::DetermineIdsToRemove
+// -----------------------------------------------------------------------------
+//
+void CUpdateFoldersHandler::DetermineIdsToUpdateL ( const CDesCArray& aUriArray )
+    {
+    const TInt uriCount( aUriArray.Count() );
+    for ( TInt i = 0; i < uriCount; ++i )
+        {
+        CMdEObject* object = NULL;
+        const TDesC& uri = aUriArray.MdcaPoint( i );
+        TPtrC ext;
+        const TBool exists( MdsUtils::GetExt( uri, ext ) );
+        if( !exists || !IsSupportedType( ext ) )
+            {
+            return;
+            }
+
+        object = iMdESession.GetObjectL( uri ); 
+        CleanupStack::PushL( object );
+
+        if ( !object )
+            {
+            // If object for given URI is not in MDS, then determine if an ENotifyAdd
+            // or ENotifyModify  is pending by attempting to harvest the file associated
+            // with the URI.
+            DoHarvestL( uri );
+            }
+        CleanupStack::PopAndDestroy( object );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::DoQueryL
+// -----------------------------------------------------------------------------
+//
+void CUpdateFoldersHandler::DoQueryL( CMdEObjectQuery*& aQuery, const CDesCArray& aFolderArray )
+    {
+    CMdENamespaceDef& defaultNamespaceDef = iMdESession.GetDefaultNamespaceDefL();
+    CMdEObjectDef& objDef = defaultNamespaceDef.GetObjectDefL( MdeConstants::Object::KBaseObject );
+    aQuery = iMdESession.NewObjectQueryL( iMdESession.GetDefaultNamespaceDefL(), objDef, this );
+    CleanupStack::PushL( aQuery );
+    CMdELogicCondition& uriLogicCond = aQuery->Conditions().AddLogicConditionL( ELogicConditionOperatorOr );
+
+    const TInt folderCount( aFolderArray.Count() );
+    for ( TInt i = 0; i < folderCount; ++i )
+        {
+        uriLogicCond.AddObjectConditionL( EObjectConditionCompareUriBeginsWith, aFolderArray.MdcaPoint( i ) );
+        }
+    aQuery->FindL();
+
+    CleanupStack::Pop( aQuery ); // Caller takes ownership.
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::DoHarvest
+// -----------------------------------------------------------------------------
+//
+void CUpdateFoldersHandler::DoHarvestL( const TDesC& aUri )
+    {
+    RArray< TItemId > albumIds;
+
+    TUid uid( KNullUid );
+    iHarvester.SetObserver( this );
+    iHarvestingFile = TFileName( aUri );
+    iHarvestingOngoing = ETrue;
+    iHarvester.HarvestFileWithUID( aUri, albumIds, EFalse, uid );
+    if( !iScheduler.IsStarted() )
+        {
+        iScheduler.Start();
+        }
+
+    albumIds.Close();
+    
+    // Wait until harvest complete before trying again.
+    iHarvester.RemoveObserver( this );
+    if ( iHarvestError == KErrNone )
+        {
+        CMdEObject* object = NULL;
+
+        object = iMdESession.GetObjectL( aUri );
+        if( object )
+            {
+            const TInt index = iIdsHandled.Find( object->Id() );
+            if( index != KErrNotFound )
+                {
+                iIdsHandled.Remove( index );
+                }
+            else
+                {
+                iIdsPendingUpdate.Append( object->Id() ); 
+                }
+            }
+        }
+
+    iHarvestError = KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::HarvestingComplete
+// Callback from harvester client after harvesting
+// -----------------------------------------------------------------------------
+//
+void CUpdateFoldersHandler::HarvestingComplete( TDesC& aURI, const TInt aError )
+    {
+    const TFileName uri( aURI );
+    TBool match( EFalse );
+    TCollationMethod m = *Mem::CollationMethodByIndex( 0 );
+
+    iHarvestError = aError;
+    m.iFlags = ( TCollationMethod::EIgnoreNone | TCollationMethod::EFoldCase );   
+
+    if ( uri.CompareC( iHarvestingFile, 3, &m ) == 0 )
+        {
+        match = ETrue;
+        iHarvestingOngoing = EFalse;
+        }
+    if ( iScheduler.IsStarted() && match )
+        {
+        iScheduler.AsyncStop();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CUpdateFoldersHandler::IsSupportedType
+// -----------------------------------------------------------------------------
+//
+TBool CUpdateFoldersHandler::IsSupportedType( const TDesC& aExtension )
+    {
+    TCollationMethod m = *Mem::CollationMethodByIndex( 0 );
+    m.iFlags = ( TCollationMethod::EIgnoreNone | TCollationMethod::EFoldCase );   
+    
+    for( TInt i( 0 ); i < iExtensionArray->Count(); i++ )
+        {
+        const TDesC& ext = iExtensionArray->MdcaPoint( i );
+        if ( ext.CompareC( aExtension, 3, &m ) == 0 )
+            {
+            return ETrue;
+            }
+        }
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::~CCLFServerProxy
+// Destructor.
+// -----------------------------------------------------------------------------
+//
+CCLFServerProxy::~CCLFServerProxy()
+    {
+    // Reset the arrays this class owns.
+    iStatusArray.Reset();
+    iOpCodeArray.Reset();
+    iUpdatedIds.Reset();
+    TRAP_IGNORE( iMdESession.RemoveObjectObserverL( *this ));
+    TRAP_IGNORE( iMdESession.RemoveObjectPresentObserverL( *this ));
+    iUpdateItemsHandlerArray.ResetAndDestroy();
+    delete iUriArray;
+    delete iExtensionArray;
+    iFs.Close();
+
+    iHC.RemoveHarvesterEventObserver( *this );
+    iHC.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFDbItemProvider::NewL
+// -----------------------------------------------------------------------------
+//
+CCLFServerProxy* CCLFServerProxy::NewL( CMdESession& aMdESession )
+    {
+    CCLFServerProxy* self = new( ELeave ) CCLFServerProxy( aMdESession );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::GetUpdateEndEvent
+// -----------------------------------------------------------------------------
+//
+void CCLFServerProxy::GetUpdateEndEvent( TRequestStatus& aRequestStatus )
+    {
+    GetEvent( aRequestStatus, ECLFGetUpdateEvent );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::CancelEventGets
+// -----------------------------------------------------------------------------
+//
+TInt CCLFServerProxy::CancelGetEvent()
+    {
+    CancelGetEvent( ECLFGetUpdateEvent );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::GetUpdateStartEvent
+// -----------------------------------------------------------------------------
+//
+void CCLFServerProxy::GetUpdateStartEvent( TRequestStatus& aRequestStatus )
+    {
+    GetEvent( aRequestStatus, ECLFProcessStartEvent );
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::CancelGetUpdateStartEvent
+// -----------------------------------------------------------------------------
+//
+TInt CCLFServerProxy::CancelGetUpdateStartEvent()
+    {
+    CancelGetEvent( ECLFProcessStartEvent );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::FetchItemListData
+// -----------------------------------------------------------------------------
+//
+TInt CCLFServerProxy::FetchItemListData( RArray< TCLFItemId >& aItemIDArray )
+    {
+    const TInt count( iUpdatedIds.Count() );
+    for ( TInt i = 0; i < count; ++i )
+        {
+        aItemIDArray.Append( iUpdatedIds[ i ] );
+        }
+
+    iUpdatedIds.Reset();
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::UpdateItems
+// -----------------------------------------------------------------------------
+//
+TInt CCLFServerProxy::UpdateItemsL( const TArray< TCLFItemId >& aItemIDArray )
+    {
+    CUpdateItemsHandler* handler = CUpdateIDsHandler::NewL( aItemIDArray );
+
+    CleanupStack::PushL( handler );
+    StartHandlingL( handler );
+    CleanupStack::Pop( handler );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::UpdateItems
+// -----------------------------------------------------------------------------
+//
+TInt CCLFServerProxy::UpdateItemsL( const TInt aSemanticId, const TDesC8& aOpaqueData )
+    {
+    CDesCArray* uriArray = new ( ELeave ) CDesCArraySeg( KCLFDefaultArrayGranularity );
+    CleanupStack::PushL( uriArray );
+    DeSerializeL( aOpaqueData, *uriArray );
+
+    if ( uriArray->Count() )
+        {
+        CUpdateItemsHandler* handler = NULL;
+        
+        if ( aSemanticId == KCLFItemsDeletedSemanticId )
+            {
+            handler = CItemsDeletedHandler::NewL( iMdESession, *uriArray, this, this );
+            }
+        else if ( aSemanticId == KCLFUpdateFoldersSemanticId )
+            {
+            handler = CUpdateFoldersHandler::NewL( iMdESession, *uriArray, this, this, 
+                              iFs, iHC, iExtensionArray );
+            }
+        else if ( aSemanticId == KCLFUpdateCollectionsSemanticId )
+            {
+            // Pass through; collections are not supported.
+            CleanupStack::PopAndDestroy( uriArray );
+            return KErrNone;
+            }
+
+        CleanupStack::PushL( handler );
+        StartHandlingL( handler );
+        CleanupStack::Pop( handler );
+        }
+    CleanupStack::PopAndDestroy( uriArray );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::UpdateAllItems
+// -----------------------------------------------------------------------------
+//
+TInt CCLFServerProxy::UpdateAllItemsL()
+    {
+    CUpdateItemsHandler* handler = CUpdateFoldersHandler::NewL( iMdESession, 
+                                                         *iUriArray, this, this, iFs, iHC, iExtensionArray );
+    CleanupStack::PushL( handler );
+    StartHandlingL( handler );
+    CleanupStack::Pop( handler );
+    
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// Default constructor
+// ---------------------------------------------------------------------------
+//
+inline CCLFServerProxy::CCLFServerProxy( CMdESession& aMdESession )
+    : iMdESession( aMdESession ),
+    iUriArray( NULL ),
+    iExtensionArray( NULL ),
+    iHEStateFinished( ETrue ),
+    iNeedNotifyCLFGetUpdateEvent( EFalse ),
+    iDelayNotifyCLFGetUpdateEventCount( 0 )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::ConstructL
+// -----------------------------------------------------------------------------
+//
+inline void CCLFServerProxy::ConstructL()
+    {
+    iUriArray = new ( ELeave ) CDesCArraySeg( KCLFDefaultArrayGranularity );
+    User::LeaveIfError( iFs.Connect() );
+    
+    TDriveList driveList;
+    TChar driveLetter; 
+    TInt numOfElements( 0 );
+    User::LeaveIfError( DriveInfo::GetUserVisibleDrives( iFs, 
+                                                         driveList, 
+                                                         numOfElements, 
+                                                         KDriveAttExclude | KDriveAttRemote | KDriveAttRom ) );
+    
+    for( TInt driveNumber = EDriveA ; driveNumber <= EDriveZ ; driveNumber++ ) 
+        { 
+        if ( driveList[driveNumber] ) 
+            {
+            User::LeaveIfError( iFs.DriveToChar( driveNumber, driveLetter ) );
+            HBufC* letter = HBufC::NewLC( KMaxPath );
+            TPtr letterPtr( letter->Des() );
+
+            if( driveLetter == KCLFDriveC )
+                {
+                letterPtr = PathInfo::PhoneMemoryRootPath();
+                }
+            else
+                {
+                letterPtr.Append( driveLetter );
+                letterPtr.Append( KCLFDriveLetterFormatString ); 
+                }   
+                        
+            if( BaflUtils::PathExists( iFs, letterPtr ) )
+                {
+                iUriArray->AppendL( letterPtr );
+                }
+            CleanupStack::PopAndDestroy( letter );
+            }
+        }
+    
+    PopulateSupportedExtensionL();
+    
+    iMdESession.AddObjectObserverL( *this );
+    iMdESession.AddObjectPresentObserverL( *this );
+
+    User::LeaveIfError( iHC.Connect() );
+    iHC.AddHarvesterEventObserver( *this, EHEObserverTypeOverall, KCLFWrapperHarvesterEventInterval );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::HarvestingUpdated
+// -----------------------------------------------------------------------------
+//
+void CCLFServerProxy::HarvestingUpdated( 
+			HarvesterEventObserverType /*aHEObserverType*/, 
+			HarvesterEventState aHarvesterEventState,
+			TInt /*aItemsLeft*/ )
+    {
+    if( aHarvesterEventState == EHEStateFinished ||
+        aHarvesterEventState == EHEStatePaused )
+        {
+        iHEStateFinished = ETrue;
+        if ( iNeedNotifyCLFGetUpdateEvent )
+            {
+            NotifyUpdateEvent( ECLFGetUpdateEvent );
+            }
+        }
+    else
+        {
+        iHEStateFinished = EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::StartHandlingL
+// -----------------------------------------------------------------------------
+//
+void CCLFServerProxy::StartHandlingL( CUpdateItemsHandler* aHandler )
+    {
+    if ( aHandler )
+        {
+        // Notify pending active objects about the event.
+        NotifyUpdateEvent( ECLFProcessStartEvent );
+
+        // Now wait until the update is over, then return.
+        iUpdateItemsHandlerArray.Append( aHandler );
+        TRAPD( err, aHandler->StartHandlingL(); );
+        if( err != KErrNone )
+            {
+            // Remove aHandler, because it is in clean up stack.
+            iUpdateItemsHandlerArray.Remove( iUpdateItemsHandlerArray.Count() - 1 );
+            User::LeaveIfError( err );
+            }
+        if ( aHandler->AllDone() )
+            {
+            delete aHandler;
+            iUpdateItemsHandlerArray.Remove( iUpdateItemsHandlerArray.Count() - 1 );
+            }
+        else
+            {
+            aHandler->StartScheduler();
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::HandleObjectNotification
+// -----------------------------------------------------------------------------
+//
+void CCLFServerProxy::HandleObjectNotification( CMdESession& /*aSession*/,
+                                                TObserverNotificationType aType,
+                                                const RArray< TItemId >& aObjectIdArray )
+    {
+    TBool unhandledIds = EFalse;
+
+    const TInt objectCount( aObjectIdArray.Count() );
+    for ( TInt i = 0; i < objectCount; ++i )
+        {
+        TBool handled = EFalse;
+
+        iUpdatedIds.Append( aObjectIdArray[ i ] );
+        for ( TInt j = 0; j < iUpdateItemsHandlerArray.Count(); ++j )
+            {
+            iUpdateItemsHandlerArray[ j ]->HandleObjectNotification( aObjectIdArray[ i ], aType );
+            handled = handled ? ETrue : iUpdateItemsHandlerArray[ j ]->WasNotificationHandled();
+
+            if ( iUpdateItemsHandlerArray[ j ]->AllDone() )
+                {
+                // If we have a pending update, we can now let it continue.
+                iDelayNotifyCLFGetUpdateEventCount = KDelayNotityCLFGetUpdateEventMaxTimes;
+                NotifyUpdateEvent( ECLFGetUpdateEvent );
+                iUpdateItemsHandlerArray[ j ]->AsyncStopScheduler();
+                iUpdateItemsHandlerArray[j]->SetRemoveObserverFlag( EFalse );
+                delete iUpdateItemsHandlerArray[ j ]; 
+                iUpdateItemsHandlerArray.Remove( j );
+                j--; // Compensate for the removed handler
+                }
+            }
+        unhandledIds = ( unhandledIds || !handled ) ? ETrue : EFalse;
+        }
+
+    if ( unhandledIds )
+        {
+        // If we have an ID that doesn't match a pending update, we assume
+        // that the object notification was generated from outside the current
+        // application, and we therefore must simulate a process end event.
+        if( aType == ENotifyRemove )
+            {
+            // Increase the update triggering value more rapidly to provide remove events faster
+            iDelayNotifyCLFGetUpdateEventCount += 12;
+            }
+        NotifyUpdateEvent( ECLFGetUpdateEvent );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::MMdEObjectPresentObserver
+// -----------------------------------------------------------------------------
+//
+void CCLFServerProxy::HandleObjectPresentNotification( CMdESession& /*aSession*/,
+                                                TBool /*aPresent*/,
+                                                const RArray< TItemId >& aObjectIdArray )
+    {
+    TBool unhandledIds = EFalse;
+
+    const TInt objectCount( aObjectIdArray.Count() );
+    for ( TInt i = 0; i < objectCount; ++i )
+        {
+        TBool handled = EFalse;
+
+        iUpdatedIds.Append( aObjectIdArray[ i ] );
+        for ( TInt j = 0; j < iUpdateItemsHandlerArray.Count(); ++j )
+            {
+            iUpdateItemsHandlerArray[ j ]->HandleObjectNotification( aObjectIdArray[ i ], ENotifyModify );
+            handled = handled ? ETrue : iUpdateItemsHandlerArray[ j ]->WasNotificationHandled();
+
+            if ( iUpdateItemsHandlerArray[ j ]->AllDone() )
+                {
+                // If we have a pending update, we can now let it continue.
+                NotifyUpdateEvent( ECLFGetUpdateEvent );
+                iUpdateItemsHandlerArray[ j ]->AsyncStopScheduler();
+                iUpdateItemsHandlerArray[j]->SetRemoveObserverFlag( EFalse );
+                delete iUpdateItemsHandlerArray[ j ]; 
+                iUpdateItemsHandlerArray.Remove( j );
+                j--; // Compensate for the removed handler
+                }
+            }
+        unhandledIds = ( unhandledIds || !handled ) ? ETrue : EFalse;
+        }
+
+    if ( unhandledIds )
+        {
+        // If we have an ID that doesn't match a pending update, we assume
+        // that the object notification was generated from outside the current
+        // application, and we therefore must simulate a process end event.
+        NotifyUpdateEvent( ECLFGetUpdateEvent );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::NotifyUpdateEvent
+// -----------------------------------------------------------------------------
+//
+void CCLFServerProxy::NotifyUpdateEvent( const TCLFServerOpCodes aOpCode )
+    {
+
+    if ( ECLFGetUpdateEvent == aOpCode
+            && !iHEStateFinished
+            && iDelayNotifyCLFGetUpdateEventCount < KDelayNotityCLFGetUpdateEventMaxTimes )
+        {
+        iNeedNotifyCLFGetUpdateEvent = ETrue;
+        iDelayNotifyCLFGetUpdateEventCount++;
+        return;
+        }
+
+    for ( TInt i = 0; i < iOpCodeArray.Count(); ++i )
+        {
+        if ( iOpCodeArray[ i ] == aOpCode )
+            {
+            User::RequestComplete( iStatusArray[ i ], KErrNone );
+            iStatusArray.Remove( i );
+            iOpCodeArray.Remove( i );
+            }
+        }
+    
+    if ( ECLFGetUpdateEvent == aOpCode )
+        {
+        iNeedNotifyCLFGetUpdateEvent = EFalse;
+        iDelayNotifyCLFGetUpdateEventCount = 0;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::DeSerializeL
+// -----------------------------------------------------------------------------
+//
+void CCLFServerProxy::DeSerializeL( const TDesC8& aData, CDesCArray& aDataArray )
+    {
+    // Check if KNullDesC
+    if ( aData.Length() > 0 )
+        {
+        RDesReadStream readStream( aData );
+        CleanupClosePushL( readStream );
+        const TInt count( readStream.ReadInt32L() );
+
+        HBufC* buffer = HBufC::NewLC( KCLFDefaultBufferLength );
+        TPtr ptr( buffer->Des() );
+        for ( TInt i = 0 ; i < count ; ++i )
+            {
+            const TInt length( readStream.ReadInt32L() );
+            const TUint uintLength( length );
+            const TInt maxLength( KMaxTInt / 2 );
+            if (( length < 0 ) || ( uintLength > maxLength ))
+                {
+                User::Leave( KErrNotSupported );
+                }
+            else if ( length > ptr.MaxLength() )
+                {
+                // create new buffer
+                CleanupStack::PopAndDestroy( buffer );
+                buffer = HBufC::NewLC( length );
+                ptr.Set( buffer->Des() );
+                }
+            else
+                {
+                ptr.Zero();
+                }
+            readStream.ReadL( ptr, length );
+            aDataArray.AppendL( ptr );
+            }
+        CleanupStack::PopAndDestroy( 2, &readStream );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::GetEvent
+// -----------------------------------------------------------------------------
+//
+void CCLFServerProxy::GetEvent( TRequestStatus& aRequestStatus, TCLFServerOpCodes aOpcode )
+    {
+    iStatusArray.Append( &aRequestStatus );
+    iOpCodeArray.Append( aOpcode );
+    aRequestStatus = KRequestPending;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::CancelGetEvent
+// -----------------------------------------------------------------------------
+//
+void CCLFServerProxy::CancelGetEvent( TCLFServerOpCodes aOpcode )
+    {
+    for ( TInt i = 0; i < iStatusArray.Count(); ++i )
+        {
+        if ( iOpCodeArray[ i ] == aOpcode )
+            {
+            User::RequestComplete( iStatusArray[ i ], KErrCancel );
+            iStatusArray.Remove( i );
+            iOpCodeArray.Remove( i );
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFServerProxy::PopulateSupportedExtensionL
+// -----------------------------------------------------------------------------
+//
+void CCLFServerProxy::PopulateSupportedExtensionL()
+    {
+    iExtensionArray = new ( ELeave ) CDesCArraySeg( KCLFExtensionArrayGranularity );
+    iExtensionArray->AppendL( KExtensionMp3 );
+    iExtensionArray->AppendL( KExtensionAac );
+    iExtensionArray->AppendL( KExtensionAmr );
+    iExtensionArray->AppendL( KExtensionAwb );
+    iExtensionArray->AppendL( KExtensionMid );
+    iExtensionArray->AppendL( KExtensionMidi );
+    iExtensionArray->AppendL( KExtensionSpMid );
+    iExtensionArray->AppendL( KExtensionRng );
+    iExtensionArray->AppendL( KExtensionMxmf );
+    iExtensionArray->AppendL( KExtensionWav );
+    iExtensionArray->AppendL( KExtensionAu );
+    iExtensionArray->AppendL( KExtensionNrt );
+    iExtensionArray->AppendL( KExtensionWma );
+    iExtensionArray->AppendL( KExtensionRa );
+    
+    iExtensionArray->AppendL( KExtJpg );
+    iExtensionArray->AppendL( KExtJpeg );
+    iExtensionArray->AppendL( KExtJp2 );
+    iExtensionArray->AppendL( KExtJ2k );
+    iExtensionArray->AppendL( KExtJpx );
+    iExtensionArray->AppendL( KExtJpf );
+    iExtensionArray->AppendL( KExtMbm );
+    iExtensionArray->AppendL( KExtPng );
+    iExtensionArray->AppendL( KExtGif );
+    iExtensionArray->AppendL( KExtBmp );
+    iExtensionArray->AppendL( KExtTif );
+    iExtensionArray->AppendL( KExtTiff );
+    iExtensionArray->AppendL( KExtOta );
+    iExtensionArray->AppendL( KExtWbmp );
+    iExtensionArray->AppendL( KExtWmf );
+    iExtensionArray->AppendL( KExtOtb );
+    
+    iExtensionArray->AppendL( KExtOma1 );
+    iExtensionArray->AppendL( KExtOma2 );
+    iExtensionArray->AppendL( KExtOma3 );
+    iExtensionArray->AppendL( KExtOma4 );
+    iExtensionArray->AppendL( KExtOma5 );
+    
+    iExtensionArray->AppendL( KExtensionMp4 );
+    iExtensionArray->AppendL( KExtensionMpg4 );
+    iExtensionArray->AppendL( KExtensionMpeg4 );
+    iExtensionArray->AppendL( KExtensionM4v );
+    iExtensionArray->AppendL( KExtensionM4a );
+    iExtensionArray->AppendL( KExtension3gp );
+    iExtensionArray->AppendL( KExtension3gpp );
+    iExtensionArray->AppendL( KExtension3g2 );
+    iExtensionArray->AppendL( KExtensionRm );
+    iExtensionArray->AppendL( KExtensionRmvb );
+    iExtensionArray->AppendL( KExtensionRam );
+    iExtensionArray->AppendL( KExtensionRv );
+    iExtensionArray->AppendL( KExtensionWmv );
+    iExtensionArray->AppendL( KExtensionAvi );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFServerProxy.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,428 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef CCLFSERVERPROXY_H
+#define CCLFSERVERPROXY_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <badesca.h>
+#include <f32file.h>
+#include <mdesession.h>
+#include <mdeobjectquery.h>
+#include <harvesterclient.h>
+#include <CLFContentListing.h>
+#include "CLFConsts.h"
+
+// FORWARD DECLARATIONS
+class CActiveSchedulerWait;
+
+// CLASS DECLARATION
+
+/**
+*  Abstract base class for handling different types of UpdateItems requests.
+*
+*  @lib ContentListingFramework.lib
+*  @since Series 60 5.0
+*/
+NONSHARABLE_CLASS( CUpdateItemsHandler ) : public CBase
+    {
+    public:
+        virtual void StartHandlingL() = 0;
+        
+        virtual void HandleObjectNotification( TItemId aId, TObserverNotificationType aType ) = 0;
+
+        virtual TBool WasNotificationHandled() const;
+
+        virtual TBool AllDone() const = 0;
+
+        virtual void StartScheduler();
+
+        virtual void AsyncStopScheduler();
+        
+        virtual void SetRemoveObserverFlag( TBool aRemove );
+
+    public:
+
+        /**
+         * Destructor.
+         */
+        virtual ~CUpdateItemsHandler() {}
+
+    protected:
+
+        /**
+         * C++ default constructor.
+         */
+        inline CUpdateItemsHandler();
+
+    protected:
+        // Ref.
+        CActiveSchedulerWait iScheduler;
+        // Own.
+        TBool iWasNotificationHandled;
+        // Ref.
+        MMdEObjectObserver* iParentObserver;
+        // Ref.
+        MMdEObjectPresentObserver* iParentPresentObserver;
+        // Own
+        TBool iRemoveObserver;
+    };
+
+/**
+*  ID-based UpdateItems request handler.
+*
+*  @lib ContentListingFramework.lib
+*  @since Series 60 5.0
+*/
+NONSHARABLE_CLASS( CUpdateIDsHandler ) : public CUpdateItemsHandler
+    {
+    public: // Constructors and destructor
+
+        /**
+         * Two-phased constructor.
+         */
+        static CUpdateIDsHandler* NewL( const TArray< TCLFItemId >& aItemIDArray );
+
+        /**
+         * Destructor.
+         */
+        virtual ~CUpdateIDsHandler();
+
+    protected: // Functions from base classes
+
+        /**
+         * From CUpdateItemsHandler
+         */
+        virtual void StartHandlingL();
+        
+        /**
+         * From CUpdateItemsHandler
+         */
+        void HandleObjectNotification( TItemId aId, TObserverNotificationType aType );
+
+        /**
+         * From CUpdateItemsHandler
+         */
+        TBool AllDone() const;
+
+    private:
+
+        /**
+         * C++ default constructor.
+         */
+        inline CUpdateIDsHandler( const TArray< TCLFItemId >& aItemIDArray );
+
+    private:
+        // Own.
+        RArray< TCLFItemId > iIdsPendingUpdate;
+    };
+
+/**
+*  UpdateItems request handler for requests with KCLFItemsDeletedSemanticId.
+*
+*  @lib ContentListingFramework.lib
+*  @since Series 60 5.0
+*/
+NONSHARABLE_CLASS( CItemsDeletedHandler ) : public CUpdateItemsHandler
+    {
+    public: // Constructors and destructor
+
+        /**
+         * Two-phased constructor.
+         */
+        static CItemsDeletedHandler* NewL( CMdESession& aMdESession, 
+                                                                const CDesCArray& aUriArray, 
+                                                                MMdEObjectObserver* aParentObserver,
+                                                                MMdEObjectPresentObserver* aParentPresentObserver );
+
+        /**
+         * Destructor.
+         */
+        virtual ~CItemsDeletedHandler();
+
+    protected: // Functions from base classes
+
+        /**
+         * From CUpdateItemsHandler
+         */
+        virtual void StartHandlingL();
+
+        /**
+         * From CUpdateItemsHandler
+         */
+        void HandleObjectNotification( TItemId aId, TObserverNotificationType aType );
+
+        /**
+         * From CUpdateItemsHandler
+         */
+        TBool AllDone() const;
+
+    private:
+
+        /**
+         * C++ default constructor.
+         */
+        inline CItemsDeletedHandler( CMdESession& aMdESession );
+
+        /**
+         * By default Symbian 2nd phase constructor is private.
+         */
+        inline void ConstructL( const CDesCArray& aUriArray, 
+                                             MMdEObjectObserver* aParentObserver,
+                                             MMdEObjectPresentObserver* aParentPresentObserver );
+
+    private:
+        // Own.
+        RPointerArray< CMdEObject > iObjectsPendingRemoval;
+        // Own.
+        RArray< TCLFItemId > iIdsPendingRemoval;
+        // Ref.
+        CMdESession& iMdESession;
+    };
+
+/**
+*  UpdateItems request handler for requests with KCLFUpdateFoldersSemanticId.
+*
+*  @lib ContentListingFramework.lib
+*  @since Series 60 5.0
+*/
+NONSHARABLE_CLASS( CUpdateFoldersHandler ) : public CUpdateItemsHandler,
+                                             public MMdEQueryObserver,
+                                             public MHarvestObserver
+    {
+    public: // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CUpdateFoldersHandler* NewL( CMdESession& aMdESession, 
+                                                                 const CDesCArray& aUriArray,
+                                                                 MMdEObjectObserver* aParentObserver,
+                                                                 MMdEObjectPresentObserver* aParentPresentObserver,
+                                                                 RFs& aFs,
+                                                                 RHarvesterClient& aHarvester,
+                                                                 CDesCArray* aSupportedTypes );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CUpdateFoldersHandler();
+
+    protected: // Functions from base classes
+
+        /**
+         * From CUpdateItemsHandler
+         */
+        virtual void StartHandlingL();
+
+        /**
+         * From CUpdateItemsHandler
+         */
+        void HandleObjectNotification( TItemId aId, TObserverNotificationType aType );
+
+        /**
+         * From CUpdateItemsHandler
+         */
+        TBool AllDone() const;
+
+        /**
+         * From MMdEQueryObserver
+         */
+        void HandleQueryNewResults( CMdEQuery& aQuery, TInt aFirstNewItemIndex, TInt aNewItemCount );
+
+        /**
+         * From MMdEQueryObserver
+         */
+        void HandleQueryCompleted( CMdEQuery& aQuery, TInt aError );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        inline CUpdateFoldersHandler( CMdESession& aMdESession, 
+                                                         RFs& aFs, 
+                                                         RHarvesterClient& aHarvester,
+                                                         CDesCArray* aSupportedTypes );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        inline void ConstructL( const CDesCArray& aUriArray, 
+                                             MMdEObjectObserver* aParentObserver, 
+                                             MMdEObjectPresentObserver* aParentPresentObserver );
+
+        void ScanNodeForUrisL( const TDesC16& aNodeName, CDesCArray& aUriArray, CDesCArray& aFolderArray );
+
+        void DetermineIdsToRemoveL ( const CMdEObjectQuery& aQuery );
+
+        void DetermineIdsToUpdateL ( const CDesCArray& aUriArray );
+
+        void DoQueryL( CMdEObjectQuery*& aQuery, const CDesCArray& aFolderArray );
+
+        void DoHarvestL( const TDesC& aUri );
+
+        void HarvestingComplete( TDesC& aURI, TInt aError );
+        
+        TBool IsSupportedType( const TDesC& aExtension );
+
+    private:
+        // Ref.
+        RFs iFs;
+        // Own.
+        CDesCArraySeg iUrisFound;
+        // Own.
+        CDesCArraySeg iFoldersFound;
+        // Own.
+        RArray< TCLFItemId > iIdsPendingRemoval;
+        // Own
+        RArray< TCLFItemId >  iIdsPendingUpdate;
+        // Own
+        RArray< TCLFItemId > iIdsHandled;
+        // Ref.
+        CMdESession& iMdESession;
+        // Ref.
+        RHarvesterClient iHarvester;
+        // Own.
+        TFileName iHarvestingFile;
+        // Own.
+        TInt iHarvestError;
+        // Own
+        TBool iStartingHandling;
+        // Not owned.
+        CDesCArray* iExtensionArray;
+        
+        TBool iHarvestingOngoing;
+    };
+
+/**
+*  Client-side proxy class for simulating the CLF server.
+*
+*  @lib ContentListingFramework.lib
+*  @since Series 60 5.0
+*/
+NONSHARABLE_CLASS( CCLFServerProxy ) : public CBase,
+                                       public MMdEObjectObserver,
+                                       public MHarvesterEventObserver,//clf_wrapper_improve add
+                                       public MMdEObjectPresentObserver
+    {
+    public: // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCLFServerProxy* NewL( CMdESession& aMdESession );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCLFServerProxy();
+
+    public:
+
+        void GetUpdateEndEvent( TRequestStatus& aRequestStatus );
+
+        TInt CancelGetEvent();
+
+        void GetUpdateStartEvent( TRequestStatus& aRequestStatus );
+
+        TInt CancelGetUpdateStartEvent();
+
+        TInt FetchItemListData( RArray< TCLFItemId >& aItemIDArray );
+
+        TInt UpdateItemsL( const TArray< TCLFItemId >& aItemIDArray );
+
+        TInt UpdateItemsL( TInt aSemanticId, const TDesC8& aOpaqueData );
+
+        TInt UpdateAllItemsL();
+
+        /**
+         * From MMdEObjectObserver
+         */
+         void HandleObjectNotification( CMdESession& aSession,
+                                        TObserverNotificationType aType,
+                                        const RArray<TItemId>& aObjectIdArray );
+         
+         /**
+          * From MMdEObjectPresentObserver
+          */
+          void HandleObjectPresentNotification( CMdESession& aSession, 
+                                                                         TBool aPresent, 
+                                                                         const RArray<TItemId>& aObjectIdArray );
+        // clf_wrapper_improve add
+      	void HarvestingUpdated( 
+      				HarvesterEventObserverType aHEObserverType, 
+      				HarvesterEventState aHarvesterEventState,
+      				TInt aItemsLeft );
+      	// clf_wrapper_improve end
+    private:
+        /**
+        * C++ default constructor.
+        */
+        inline CCLFServerProxy( CMdESession& aMdESession );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        inline void ConstructL();
+
+        void StartHandlingL( CUpdateItemsHandler* aHandler );
+
+         void NotifyUpdateEvent( const TCLFServerOpCodes aOpCode );
+
+         void DeSerializeL( const TDesC8& aData, CDesCArray& aDataArray );
+
+         void ProcessObjectId( const CMdEObject* aObject );
+
+         void GetEvent( TRequestStatus& aRequestStatus, TCLFServerOpCodes aOpcode );
+
+         void CancelGetEvent( TCLFServerOpCodes aOpcode );
+         
+         void PopulateSupportedExtensionL();
+
+    private: // Data
+        // Own.
+        RPointerArray< TRequestStatus > iStatusArray;
+        // Own.
+        RArray< TCLFServerOpCodes > iOpCodeArray;
+        // Own.
+        RArray< TCLFItemId > iUpdatedIds;
+        // Own.
+        RPointerArray< CUpdateItemsHandler > iUpdateItemsHandlerArray;
+        // Ref.
+        CMdESession& iMdESession;
+        // Own.
+        CDesCArray* iUriArray;
+        // Own.
+        CDesCArray* iExtensionArray;
+        // Own.
+        RFs iFs;
+
+        RHarvesterClient iHC;
+        
+        TBool iHEStateFinished;
+        
+        TBool iNeedNotifyCLFGetUpdateEvent;
+        
+        TInt iDelayNotifyCLFGetUpdateEventCount;
+    };
+
+#endif // CCLFSERVERPROXY_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFSortingStyleImpl.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,191 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "CCLFSortingStyleimpl.h"
+#include    <barsread.h>
+
+// CONSTANTS
+const TInt KCLFFieldIdArrayGranularity( 4 );
+const TInt KCLFResourceVersion( 1 );
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::CCLFSortingStyleImpl
+// -----------------------------------------------------------------------------
+//
+CCLFSortingStyleImpl::CCLFSortingStyleImpl()
+    : iFieldIDArray( KCLFFieldIdArrayGranularity ),
+      iDataType( ECLFItemDataTypeNull ),
+      iOrdering( ECLFOrderingAscending ),
+      iUndefinedItemPosition( ECLFSortingStyleUndefinedEnd )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CCLFSortingStyleImpl::ConstructL( TResourceReader& aResource )
+    {
+    const TInt version( aResource.ReadInt16() );
+    if ( version != KCLFResourceVersion )
+        {
+        User::Leave( KErrNotSupported );
+        }
+    iOrdering = TCLFSortingStyleOrdering( aResource.ReadInt32() );
+    iDataType = TCLFItemDataType( aResource.ReadInt32() );
+    iUndefinedItemPosition = TCLFUndefinedItemPosition( aResource.ReadInt8() );
+    const TInt count( aResource.ReadInt16() );
+    for ( TInt i = 0 ; i < count ; ++i )
+        {
+        iFieldIDArray.AppendL( aResource.ReadInt32() );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CCLFSortingStyleImpl* CCLFSortingStyleImpl::NewLC()
+    {
+    CCLFSortingStyleImpl* self = new( ELeave ) CCLFSortingStyleImpl;
+
+    CleanupStack::PushL( self );
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CCLFSortingStyleImpl* CCLFSortingStyleImpl::NewLC( TResourceReader& aResource )
+    {
+    CCLFSortingStyleImpl* self = new( ELeave ) CCLFSortingStyleImpl;
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aResource );
+
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::~CCLFSortingStyleImpl
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCLFSortingStyleImpl::~CCLFSortingStyleImpl()
+    {
+    iFieldIDArray.Close();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::ResetL
+// -----------------------------------------------------------------------------
+//
+void CCLFSortingStyleImpl::ResetL()
+    {
+    iFieldIDArray.Reset();
+    iOrdering = ECLFOrderingAscending;
+    iUndefinedItemPosition = ECLFSortingStyleUndefinedEnd;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::AddFieldL
+// -----------------------------------------------------------------------------
+//
+void CCLFSortingStyleImpl::AddFieldL( TCLFFieldId aFieldId )
+    {
+    iFieldIDArray.AppendL( aFieldId );
+    }
+    
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::GetFieldsL
+// -----------------------------------------------------------------------------
+//
+void CCLFSortingStyleImpl::GetFieldsL( RArray<TCLFFieldId>& aArray ) const
+    {
+    const TInt count( iFieldIDArray.Count() );
+    for( TInt i = 0 ; i < count ; ++i )
+        {
+        aArray.AppendL( iFieldIDArray[i] );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::SetOrdering
+// -----------------------------------------------------------------------------
+//
+void CCLFSortingStyleImpl::SetOrdering( TCLFSortingStyleOrdering aOrdering )
+    {
+    iOrdering = aOrdering;
+    }
+    
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::Ordering
+// -----------------------------------------------------------------------------
+//
+TCLFSortingStyleOrdering CCLFSortingStyleImpl::Ordering() const
+    {
+    return iOrdering;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::SetSortingDataType
+// -----------------------------------------------------------------------------
+//
+void CCLFSortingStyleImpl::SetSortingDataType( TCLFItemDataType aDataType )
+    {
+    iDataType = aDataType;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::SortingDataType
+// -----------------------------------------------------------------------------
+//
+TCLFItemDataType CCLFSortingStyleImpl::SortingDataType() const
+    {
+    return iDataType;
+    }
+
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::SetUndefinedItemPosition
+// -----------------------------------------------------------------------------
+//
+void CCLFSortingStyleImpl::SetUndefinedItemPosition(
+                            TCLFUndefinedItemPosition aUndefinedItemPosition )
+    {
+    iUndefinedItemPosition = aUndefinedItemPosition;
+    }
+// -----------------------------------------------------------------------------
+// CCLFSortingStyleImpl::UndefinedItemPosition
+// -----------------------------------------------------------------------------
+//
+TCLFUndefinedItemPosition CCLFSortingStyleImpl::UndefinedItemPosition() const
+    {
+    return iUndefinedItemPosition;
+    }
+    
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CCLFSortingStyleimpl.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,132 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+
+#ifndef CCLFSORTINGSTYLEIMPL_H
+#define CCLFSORTINGSTYLEIMPL_H
+
+//  INCLUDES
+#include <MCLFSortingStyle.h>
+#include <e32base.h>
+
+class TResourceReader;
+
+// CLASS DECLARATION
+
+/**
+*  This class implements MCLFSortingStyle interface.
+*
+*  @lib ContentListingFramework.lib
+*  @since S60 3.0
+*/
+NONSHARABLE_CLASS( CCLFSortingStyleImpl ) : public CBase,
+                                            public MCLFSortingStyle
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCLFSortingStyleImpl* NewLC();
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCLFSortingStyleImpl* NewLC( TResourceReader& aResource );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCLFSortingStyleImpl();
+
+    protected:  // Functions from base classes
+
+        /**
+        * From MCLFSortingStyle
+        */
+        void ResetL();
+
+        /**
+        * From MCLFSortingStyle
+        */
+        void AddFieldL( TCLFFieldId aFieldId );
+
+        /**
+        * From MCLFSortingStyle
+        */
+        void GetFieldsL( RArray<TCLFFieldId>& aArray ) const;
+
+        /**
+        * From MCLFSortingStyle
+        */
+        void SetOrdering( TCLFSortingStyleOrdering aOrdering );
+
+        /**
+        * From MCLFSortingStyle
+        */
+        TCLFSortingStyleOrdering Ordering() const;
+
+        /**
+        * From MCLFSortingStyle
+        */
+        void SetSortingDataType( TCLFItemDataType aDataType );
+
+        /**
+        * From MCLFSortingStyle
+        */
+        TCLFItemDataType SortingDataType() const;
+
+        /**
+        * From MCLFSortingStyle
+        */
+        void SetUndefinedItemPosition(
+                    TCLFUndefinedItemPosition aUndefinedItemPosition );
+
+        /**
+        * From MCLFSortingStyle
+        */
+        TCLFUndefinedItemPosition UndefinedItemPosition() const;
+
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CCLFSortingStyleImpl();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL( TResourceReader& aResource );
+
+    private:    // Data
+        // Own: field ID array
+        RArray<TCLFFieldId> iFieldIDArray;
+        // Own: data type
+        TCLFItemDataType iDataType;
+        // Own: sorting ordering
+        TCLFSortingStyleOrdering iOrdering;
+        // Own:
+        TCLFUndefinedItemPosition iUndefinedItemPosition;
+
+    };
+
+#endif      // CCLFSORTINGSTYLEIMPL_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CLF2MdEConsts.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+#ifndef CLF2MDECONSTS_H
+#define CLF2MDECONSTS_H
+
+//  INCLUDES
+#include <e32def.h>
+
+// CONSTANTS
+
+// Literals for music file mappings
+_LIT( KCLFWrapperMusicTypeMpeg, "audio/mpeg" );
+_LIT( KCLFWrapperMusicTypeAac, "audio/aac" );
+_LIT( KCLFWrapperMusicTypeMp3, "audio/mp3" );
+_LIT( KCLFWrapperMusicTypeX_Mp3, "audio/x-mp3" );
+_LIT( KCLFWrapperMusicTypeMp4, "audio/mp4" );
+_LIT( KCLFWrapperMusicType3gpp, "audio/3gpp" );
+_LIT( KCLFWrapperMusicTypeM4a, "audio/m4a" );
+_LIT( KCLFWrapperMusicType3gpp2, "audio/3gpp2" );
+_LIT( KCLFWrapperMusicTypeMpeg4, "audio/mpeg4" );
+_LIT( KCLFWrapperMusicTypeX_Pn_RealAudio, "audio/x-pn-realaudio" );
+_LIT( KCLFWrapperMusicTypeX_Ms_Wma, "audio/x-ms-wma" );
+
+#endif      // CLF2MDECONSTS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CLFUtils.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+// Includes
+#include <e32base.h>
+#include <CLFContentListing.hrh>
+#include <mdeconstants.h>
+#include "CLFConsts.h"
+#include "CLFUtils.h"
+#include "MGDebugPrint.h"
+
+// ---------------------------------------------------------------------------
+// Maps CLF mediatype to MdE object class
+// ---------------------------------------------------------------------------
+//
+const TDesC& CLFUtils::MapClfType( const TInt aType )
+    {
+    MG_DEBUG2( MCT, "[CLF]\t CCLFQueryAdapter::MapClfType %d", aType );
+    const TDesC* ret = &KNullDesC;
+
+    switch ( aType )
+        {
+        /// Music media type
+        case ECLFMediaTypeMusic:
+            {
+            ret = &MdeConstants::Audio::KAudioObject;
+            break;
+            }
+        /// Sound media type
+        case ECLFMediaTypeSound:
+            {
+            ret = &MdeConstants::Audio::KAudioObject;
+            break;
+            }
+        /// Image media type
+        case ECLFMediaTypeImage:
+            {
+            ret = &MdeConstants::Image::KImageObject;
+            break;
+            }
+        /// Video media type
+        case ECLFMediaTypeVideo:
+            {
+            ret = &MdeConstants::Video::KVideoObject;
+            break;
+            }
+        /// Map ECLFMediaTypeUnknown, ECLFMediaTypeStreamingURL, ECLFMediaTypePlaylist and
+        /// ECLFMediaTypePresentations to KBaseObject.
+        case ECLFMediaTypeUnknown:
+        case ECLFMediaTypeStreamingURL:
+        case ECLFMediaTypePlaylist:
+        case ECLFMediaTypePresentations:
+        default:
+            {
+            MG_DEBUG1( MCT3, "[CLF]\t MapClfType reached default, returning KBaseObject" );   
+            ret = &MdeConstants::Object::KBaseObject;
+            break;
+            }
+        }
+    return *ret;
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/CLFUtils.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Common utility methods.
+*
+*/
+
+
+#ifndef CLFUTILS_H
+#define CLFUTILS_H
+
+namespace CLFUtils
+    {
+    
+    /**
+     * Maps CLF mediatype to MdE object class
+     *
+     */
+    const TDesC& MapClfType( TInt aType );
+    }
+
+#endif // CLFUTILS_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/ContentListingFactory.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,68 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    <ContentListingFactory.h>
+#include    "CCLFEngineImpl.h"
+#include    "CCLFSortingStyleimpl.h"
+#include    "CCLFItemImpl.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// ContentListingFactory::NewContentListingEngineLC
+// -----------------------------------------------------------------------------
+//
+EXPORT_C MCLFContentListingEngine*
+                        ContentListingFactory::NewContentListingEngineLC()
+    {
+    return CCLFEngineImpl::NewLC();
+    }
+
+// -----------------------------------------------------------------------------
+// ContentListingFactory::NewModifiableItemLC
+// -----------------------------------------------------------------------------
+//
+EXPORT_C MCLFModifiableItem* ContentListingFactory::NewModifiableItemLC()
+    {
+    CCLFModifiableItemImpl* item = CCLFModifiableItemImpl::NewL();
+    CleanupStack::PushL( item );
+    return item;
+    }
+
+// -----------------------------------------------------------------------------
+// ContentListingFactory::NewSortingStyleLC
+// -----------------------------------------------------------------------------
+//
+EXPORT_C MCLFSortingStyle* ContentListingFactory::NewSortingStyleLC()
+    {
+    return CCLFSortingStyleImpl::NewLC();
+    }
+
+// -----------------------------------------------------------------------------
+// ContentListingFactory::NewSortingStyleLC
+// -----------------------------------------------------------------------------
+//
+EXPORT_C MCLFSortingStyle* ContentListingFactory::NewSortingStyleLC(
+                                        TResourceReader& aResource )
+    {
+    return CCLFSortingStyleImpl::NewLC( aResource );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/MCLFChangedItemProvider.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,77 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+#ifndef MCLFCHANGEDITEMPROVIDER_H
+#define MCLFCHANGEDITEMPROVIDER_H
+
+//  INCLUDES
+#include <CLFContentListing.h>
+#include <bamdesca.h>
+
+// CLASS DECLARATION
+
+/**
+*  .
+*  @lib ContentListingFramework.lib
+*  @since Series 60 3.1
+*/
+class MCLFChangedItemProviderObserver
+    {
+    public:
+    
+        /**
+        * Two-phased constructor.
+        */
+        virtual void NewChangedItemsL() = 0;
+
+    protected:
+
+        /**
+        * Destructor.
+        */
+        virtual ~MCLFChangedItemProviderObserver() {}
+
+    };
+
+class MCLFChangedItemProvider
+    {
+
+    public:
+    
+        virtual TBool IsItemsForModel( const MDesCArray& aMimeTypes,
+                                       const TArray<TInt>& aMediaTypes,
+                                       const TArray<TCLFItemId>& aModelItemIds ) = 0;
+
+        virtual void RemoveChangedItemProviderObserver( 
+                                    MCLFChangedItemProviderObserver* aObserver ) = 0;
+
+
+    protected:
+
+        /**
+        * Destructor.
+        */    
+        virtual ~MCLFChangedItemProvider() {}
+
+    };
+
+
+#endif      // MCLFCHANGEDITEMPROVIDER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/MCLFEventHandlerObserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+
+#ifndef MCLFEVENTHANDLEROBSERVER_H
+#define MCLFEVENTHANDLEROBSERVER_H
+
+//  INCLUDES
+#include <e32std.h>
+
+// CLASS DECLARATION
+
+/**
+*  Event handler observer interface.
+*
+*  @lib ContentListingFramework.lib
+*  @since Series 60 3.0
+*/
+class MCLFEventHandlerObserver
+    {
+    public: // New functions
+    
+        /**
+        *  Handle event.
+        *  @param aError system-wide error code
+        */
+        virtual void HandleUpdateEndEventL( TInt aError ) = 0;
+
+        virtual void HandleUpdateStartEventL( TInt aError ) = 0;
+
+        
+    protected:
+        
+        // Destructor
+        virtual ~MCLFEventHandlerObserver() {}
+    };
+
+#endif      // MCLFEVENTHANDLEROBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/ClientSrc/MCLFItemProviderObserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+#ifndef MCLFITEMPROVIDEROBSERVER_H
+#define MCLFITEMPROVIDEROBSERVER_H
+
+//  INCLUDES
+#include <e32std.h>
+
+// CLASS DECLARATION
+
+/**
+*  Item provider observer.
+*
+*  @lib ContentListingFramework.lib
+*  @since Series 60 3.0
+*/
+class MCLFItemProviderObserver
+    {
+    public:
+
+        /**
+        *  Item provider operation is completed.
+        *  @param aError system-wide error code
+        */
+        virtual void OperationCompleteL( TInt aError ) = 0;
+
+    protected:
+
+        // Destructor
+        virtual ~MCLFItemProviderObserver() {}
+
+    };
+
+#endif      // MCLFITEMPROVIDEROBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/CommonInc/CLFConsts.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,186 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+#ifndef CLFCONSTS_H
+#define CLFCONSTS_H
+
+//  INCLUDES
+#include <e32def.h>
+#include <e32cmn.h>
+
+// CONSTANTS
+// Server version number
+const TInt KCLFServerMajor( 1 );
+const TInt KCLFServerCollectionManagerMajor( 2 );
+const TInt KCLFServerMinor( 1 );
+const TInt KCLFServerBuild( 1 );
+_LIT( KCLFServerName, "ContentListingFrameworkServer" );
+_LIT( KCLFServerExe, "ContentListingServer.exe" );
+
+// Message slots
+// RCLFDatabase::PrepareItemIds
+const TInt KCLFPrepareItemIdsMimeTypeSlot( 0 );
+const TInt KCLFPrepareItemIdsMediaTypeSlot( 1 );
+const TInt KCLFPrepareItemIdsDataSizeSlot( 2 );
+
+// RCLFDatabase::FetchItemIds
+// RCLFDatabase::FetchItemData
+const TInt KCLFFetchDataSlot( 0 );
+
+// RCLFDatabase::PrepareItems
+const TInt KCLFPrepareItemsIdDataSlot( 0 );
+const TInt KCLFPrepareItemsDataSizeSlot( 1 );
+
+// RCLFEventHandler::GetUpdateEndEvent
+const TInt KCLFGetUpdateEventDataSizeSlot( 0 );
+
+// RCLFEventHandler::FetchItemListData
+const TInt KCLFFetchItemListIdArraySlot( 0 );
+
+// RCLFEventHandler::UpdateItems (id list)
+const TInt KCLFUpdateItemsIdArraySlot( 0 );
+
+// RCLFEventHandler::UpdateItems (opaque data)
+const TInt KCLFUpdateItemsSemanticIdSlot( 0 );
+const TInt KCLFUpdateItemsOpaqueDataSlot( 1 );
+
+// Collection manager message slots
+// RCLFCollectionManagerServer::PrepareCollectionInfoArray
+const TInt KCLFPrepareCollectionInfoArrayDataSizePckg( 0 );
+
+// RCLFCollectionManagerServer::FetchCollectionInfoArray
+const TInt KCLFFetchCollectionInfoArraySlot( 0 );
+
+// RCLFCollectionManagerServer::PrepareCollectionInfoById
+const TInt KCLFPrepareCollectionInfoByIdSlot( 0 );
+const TInt KCLFPrepareCollectionInfoByIdDataSizePckgSlot( 1 );
+
+// RCLFCollectionManagerServer::FetchCollectionInfo
+const TInt KCLFFetchCollectionInfoSlot( 0 );
+
+// RCLFCollectionManagerServer::CreateCollection
+const TInt KCLFCreateCollectionNameSlot( 0 );
+const TInt KCLFCreateCollectionTypesSlot( 1 );
+const TInt KCLFCreateCollectionPropertiesSlot( 2 );
+const TInt KCLFCreateCollectionIdPckgSlot( 3 );
+
+// RCLFCollectionManagerServer::DeleteCollection
+const TInt KCLFDeleteCollectionIdSlot( 0 );
+
+// RCLFCollectionManagerServer::AddToCollection
+const TInt KCLFAddToCollectionIdSlot( 0 );
+const TInt KCLFAddToCollectionItemArraySlot( 1 );
+const TInt KCLFAddToCollectionRemoveFromOtherCollectionsSlot( 2 );
+
+// RCLFCollectionManagerServer::RemoveFromCollection
+const TInt KCLFRemoveFromCollectionIdSlot( 0 );
+const TInt KCLFRemoveFromCollectionItemArraySlot( 1 );
+
+// RCLFCollectionManagerServer::PrepareCollectionItemArray
+const TInt KCLFPrepareCollectionItemArrayIdSlot( 0 );
+const TInt KCLFPrepareCollectionDataSizePckgSlot( 1 );
+
+// RCLFCollectionManagerServer::FetchCollectionItemArray
+const TInt KCLFFetchCollectionItemArrayItemsSlot( 0 );
+
+// RCLFCollectionManagerServer::PrepareCollectionIdByItem
+const TInt KCLFPrepareCollectionIdByItemNameSlot( 0 );
+const TInt KCLFPrepareCollectionIdByItemDataSizePckgSlot( 1 );
+
+// RCLFCollectionManagerServer::FetchCollectionIdByItem
+const TInt KCLFFetchCollectionIdByItemCollectionIdsSlot( 0 );
+
+// RCLFCollectionManagerServer::GetCollectionManagerChangeEvent
+const TInt KCLFGetCollectionManagerChangeEventParameterPckgSlot( 0 );
+const TInt KCLFGetCollectionManagerChangeEventChangeEventPckgSlot( 1 );
+
+// RCLFCollectionManagerServer::FetchChangedIds
+const TInt KCLFFetchChangedCollectinIdsSlot( 0 );
+
+// RCLFCollectionManagerServer::RenameCollection
+const TInt KCLFRenameCollectionIdSlot( 0 );
+const TInt KCLFRenameCollectionNewNameSlot( 1 );
+
+// RCLFCollectionManagerServer::RemoveFromAllCollections
+const TInt KCLFRemoveFromAllCollectionsItemArraySlot( 0 );
+
+// RCLFCollectionManagerServer::GetDriveById
+const TInt KCLFGetDriveIdSlot( 0 );
+const TInt KCLFGetDriveCollectionDriveSlot( 1 );
+
+// DATA TYPES
+enum TCLFServerOpCodes
+    {
+    ECLFCancelPrepare       = 0x0, // RCLFDatabase::CancelPrepareItems
+    ECLFCancelEvent         = 0x1, // RCLFEventHandler::CancelGetEvent
+    ECLFPrepareItems        = 0x2, // RCLFDatabase::PrepareItems
+    ECLFFetchItems          = 0x3, // RCLFDatabase::FetchItemData
+    ECLFFetchChangedItems   = 0x4, // RCLFEventHandler::FetchItemListData
+    ECLFUpdateItems         = 0x5, // RCLFEventHandler::UpdateItems
+    ECLFUpdateAllItems      = 0x6, // RCLFEventHandler::UpdateAllItems
+    ECLFGetUpdateEvent      = 0x7, // RCLFEventHandler::GetUpdateEndEvent
+    ECLFUpdateItemsOpaqueData   = 0x8, // RCLFEventHandler::UpdateItems
+    ECLFProcessStartEvent   = 0x9, // RCLFEventHandler::GetUpdateStartEvent
+    ECLFCancelStartEvent    = 0xA, // RCLFEventHandler::CancelGetUpdateStartEvent
+    ECLFFetchItemIds        = 0xB, // RCLFDatabase::FetchItemIds
+    ECLFPrepareItemIds      = 0xC, // RCLFDatabase::PrepareItemIds
+    ECLFCancelPrepareIds    = 0xD, // RCLFDatabase::CancelPrepareItemIds
+
+    //Collection manager op codes
+    ECLFPrepareCollectionById   = 0xE,
+    ECLFFetchPreparedCollection = 0xF,
+    ECLFPrepareCollectionInfoArray = 0x10,
+    ECLFFetchCollectionInfoArray = 0x11,
+    ECLFCreateCollection        = 0x12,
+    ECLFDeleteCollection        = 0x13,
+    ECLFRenameCollection        = 0x14,
+    ECLFAddToCollection         = 0x15,
+    ECLFRemoveFromCollection    = 0x16,
+    ECLFPrepareCollectionItems  = 0x17,
+    ECLFFetchCollectionItems    = 0x18,
+    ECLFPrepareCollectionIdByItem = 0x19,
+    ECLFFetchCollectionIdByItem = 0x1A,
+    ECLFGetCollectionChangeEvent = 0x1B,
+    ECLFFetchChangedCollectionIds = 0x1C,
+    ECLFCancelCollectionEvent   = 0x1D,
+    ECLFRemoveFromAllCollections = 0x1E,
+    ECLFGetDriveById = 0x1F
+
+    };
+
+const TInt KCLFCheck( -43464 ); //Security check
+
+enum TCMChangeEventParameters
+    {
+    ECLFCollectionDataChanged = 0x1,
+    ECLFCollectionManagerError = 0x2
+    };
+
+// MACROS
+#define IS_FLAG( flags, flag ) ( flags & flag )
+#define SET_FLAG( flags, flag ) ( flags |= flag )
+#define REMOVE_FLAG( flags, flag ) ( flags &= ~flag )
+
+const TInt KCLFUpdateFoldersSemanticId = 0x1000;
+const TInt KCLFUpdateCollectionsSemanticId = 0x1001;
+const TInt KCLFItemsDeletedSemanticId = 0x1002;
+
+#endif      // CLFCONSTS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/CommonInc/CLFPanics.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,44 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+#ifndef CLFPANICS_H
+#define CLFPANICS_H
+
+//  INCLUDES
+#include <e32std.h>
+
+// CONSTANTS
+_LIT( KCLFPanicText, "ContentListingFramework" );
+
+enum TCLFPanicCodes
+    {
+    ECLFNullPointer         = 0x1,
+    ECLFIncorrectCommand    = 0x2,
+    ECLFNoSourcePlugins     = 0x3,
+    ECLFDbWorkThreadRunning = 0x4,
+    ECLFInvalidDbItem       = 0x5,
+    ECLFDbInvalidCommand    = 0x6,
+    ECLFDbDatabaseCorrupt   = 0x7,
+    ECLFInvalidFieldType    = 0x8,
+    ECLFNotReady            = 0x9
+    };
+
+#endif      // CLFPANICS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/CommonInc/CLFUID.hrh	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef CLFUID_HRH
+#define CLFUID_HRH
+
+// CONSTANTS
+#define CLF_FRAMEWORK_UID3 0x101F8858
+#define CLF_MEDIA_COLLECTION_MANAGER_IMPL 0x1028283D
+
+#define CLF_DRM_PLAY_SERVER_SID 0x1020381D
+
+#endif  // CLFUID_HRH
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/CommonInc/MGDebugPrint.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,150 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Debug macros
+*
+*/
+
+
+#ifndef __MGDEBUGPRINT_H__
+#define __MGDEBUGPRINT_H__
+
+#include "harvesterlog.h"
+
+#ifdef _DEBUG
+#define MG_ENABLE_DEBUG_PRINT
+#endif
+
+// Debug logging is enabled, you may enable debug printing in release builds also
+#ifdef MG_ENABLE_DEBUG_PRINT
+
+    // warn if this is a release build!!
+    #ifndef __WINSCW__
+    #ifndef _DEBUG
+        #if defined(__VC32__)
+            #pragma message( "Warning: MG debug printing is on in release build!" )     // CSI: 68 #  68:use of #pragma message
+        #else // __GCC32__
+            #warning "MG debug printing is on in release build!"
+        #endif // __VC32__
+    #endif
+    #endif // __WINSCW__
+
+// no include files if no debug printing --> faster compile time
+// INCLUDES
+#include <e32std.h>
+#include <e32svr.h>
+
+    /**
+     * Helper macro for defining debug strings with just the debug text.
+     */
+    #define MG_DEBUG_STRING(name,s) _LIT(name,s)
+
+    /**
+     * Output to debugger output
+     */
+    #define MG_DEBUG_PRINT RDebug::Print
+
+#else   // MG_ENABLE_DEBUG_PRINT
+
+    /**
+     * Dummy struct for checking that all MG_DEBUG_PRINT's define string
+     * literals using space-saving MG_DEBUG_STRING.
+     */
+    struct TMGEmptyDebugString { };     // CSI: 80 #  80:use of struct
+
+    /**
+     * Macro for defining debug-only literal strings (empty release version)
+     */
+    #define MG_DEBUG_STRING(name, s) const TMGEmptyDebugString name
+
+    /**
+     * Output to debugger output (empty)
+     */
+    #define MG_DEBUG_PRINT MG_EmptyPrint
+
+    /// Empty debug print function for release builds.
+    inline void MG_EmptyPrint(TMGEmptyDebugString)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1>
+    inline void MG_EmptyPrint(TMGEmptyDebugString,T1)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2>
+    inline void MG_EmptyPrint(TMGEmptyDebugString,T1,T2)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3>
+    inline void MG_EmptyPrint(TMGEmptyDebugString,T1,T2,T3)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4>
+    inline void MG_EmptyPrint(TMGEmptyDebugString,T1,T2,T3,T4)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4,class T5>
+    inline void MG_EmptyPrint(TMGEmptyDebugString,T1,T2,T3,T4,T5)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4,class T5,class T6>
+    inline void MG_EmptyPrint(TMGEmptyDebugString,T1,T2,T3,T4,T5,T6)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4,class T5,class T6,class T7>
+    inline void MG_EmptyPrint(TMGEmptyDebugString,T1,T2,T3,T4,T5,T6,T7)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4,class T5,class T6,class T7,class T8>
+    inline void MG_EmptyPrint(TMGEmptyDebugString,T1,T2,T3,T4,T5,T6,T7,T8)
+        {
+        }
+
+
+#endif  // MG_ENABLE_DEBUG_PRINT
+
+/**
+ * Short variant for easier basic usage.
+ */
+#define MG_DEBUG1( name, s ) MG_DEBUG_STRING( name, s ); MG_DEBUG_PRINT( name );
+
+#ifdef MG_ENABLE_DEBUG_PRINT
+#define MG_DEBUG2( name, s, i ) MG_DEBUG_STRING( name, s ); MG_DEBUG_PRINT( name, i );
+#define MG_DEBUG3( name, s, i, j ) MG_DEBUG_STRING( name, s ); MG_DEBUG_PRINT( name, i, j );
+#define MG_DEBUG4( name, s, i, j, k ) MG_DEBUG_STRING( name, s ); MG_DEBUG_PRINT( name, i, j, k );
+#define MG_DEBUG5( name, s, i, j, k, l ) MG_DEBUG_STRING( name, s ); MG_DEBUG_PRINT( name, i, j, k, l );
+#else
+// If debug printing is not enabled, strip other parameters than the string
+// away to prevent unwanted function calls in release build.
+#define MG_DEBUG2( name, s, i ) MG_DEBUG1( name, s )
+#define MG_DEBUG3( name, s, i, j ) MG_DEBUG1( name, s )
+#define MG_DEBUG4( name, s, i, j, k ) MG_DEBUG1( name, s )
+#define MG_DEBUG5( name, s, i, j, k, l ) MG_DEBUG1( name, s )
+#endif
+
+#endif //  __MGDEBUGPRINT_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/CommonInc/MGTracePrint.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,151 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Trace macros
+*
+*/
+
+
+#ifndef MGTRACEPRINT_H
+#define MGTRACEPRINT_H
+
+#include "harvesterlog.h"
+
+#ifdef _DEBUG
+#define MG_ENABLE_TRACE_PRINT
+#endif
+
+// Debug logging is enabled, you may enable debug printing in release builds also
+#ifdef MG_ENABLE_TRACE_PRINT
+
+    // warn if this is a release build!!
+    #ifndef __WINSCW__
+    #ifndef _DEBUG
+        #if defined(__VC32__)
+            #pragma message( "Warning: MG trace printing is on in release build!" )     // CSI: 68 #  68:use of #pragma message
+        #else // __GCC32__
+            #warning "MG trace printing is on in release build!"
+        #endif // __VC32__
+    #endif
+    #endif // __WINSCW__
+
+// no include files if no debug printing --> faster compile time
+// INCLUDES
+#include <e32std.h>
+#include <e32svr.h>
+
+    /**
+     * Helper macro for defining debug strings with just the debug text.
+     */
+    #define MG_TRACE_STRING(name,s) _LIT(name,s)
+
+    /**
+     * Output to debugger output
+     */
+    #define MG_TRACE_PRINT RDebug::Print
+
+#else   // MG_ENABLE_TRACE_PRINT
+
+    /**
+     * Dummy struct for checking that all MG_TRACE_PRINT's define string
+     * literals using space-saving MG_TRACE_STRING.
+     */
+    struct TMGEmptyTraceString { };     // CSI: 80 #  80:use of struct
+
+    /**
+     * Macro for defining debug-only literal strings (empty release version)
+     */
+    #define MG_TRACE_STRING(name, s) const TMGEmptyTraceString name
+
+    /**
+     * Output to debugger output (empty)
+     */
+    #define MG_TRACE_PRINT MG_EmptyTracePrint
+
+
+    /// Empty debug print function for release builds.
+    inline void MG_EmptyTracePrint(TMGEmptyTraceString)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1>
+    inline void MG_EmptyTracePrint(TMGEmptyTraceString,T1)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2>
+    inline void MG_EmptyTracePrint(TMGEmptyTraceString,T1,T2)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3>
+    inline void MG_EmptyTracePrint(TMGEmptyTraceString,T1,T2,T3)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4>
+    inline void MG_EmptyTracePrint(TMGEmptyTraceString,T1,T2,T3,T4)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4,class T5>
+    inline void MG_EmptyTracePrint(TMGEmptyTraceString,T1,T2,T3,T4,T5)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4,class T5,class T6>
+    inline void MG_EmptyTracePrint(TMGEmptyTraceString,T1,T2,T3,T4,T5,T6)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4,class T5,class T6,class T7>
+    inline void MG_EmptyTracePrint(TMGEmptyTraceString,T1,T2,T3,T4,T5,T6,T7)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4,class T5,class T6,class T7,class T8>
+    inline void MG_EmptyTracePrint(TMGEmptyTraceString,T1,T2,T3,T4,T5,T6,T7,T8)
+        {
+        }
+
+
+#endif  // MG_ENABLE_TRACE_PRINT
+
+/**
+ * Short variant for easier basic usage.
+ */
+#define MG_TRACE1( name, s ) MG_TRACE_STRING( name, s ); MG_TRACE_PRINT( name );
+
+#ifdef MG_ENABLE_TRACE_PRINT
+#define MG_TRACE2( name, s, i ) MG_TRACE_STRING( name, s ); MG_TRACE_PRINT( name, i );
+#define MG_TRACE3( name, s, i, j ) MG_TRACE_STRING( name, s ); MG_TRACE_PRINT( name, i, j );
+#define MG_TRACE4( name, s, i, j, k ) MG_TRACE_STRING( name, s ); MG_TRACE_PRINT( name, i, j, k );
+#define MG_TRACE5( name, s, i, j, k, l ) MG_TRACE_STRING( name, s ); MG_TRACE_PRINT( name, i, j, k, l );
+#else  // MG_ENABLE_DEBUG_PRINT
+// If debug printing is not enabled, strip other parameters than the string
+// away to prevent unwanted function calls in release build.
+#define MG_TRACE2( name, s, i ) MG_TRACE1( name, s )
+#define MG_TRACE3( name, s, i, j ) MG_TRACE1( name, s )
+#define MG_TRACE4( name, s, i, j, k ) MG_TRACE1( name, s )
+#define MG_TRACE5( name, s, i, j, k, l ) MG_TRACE1( name, s )
+#endif  // MG_ENABLE_DEBUG_PRINT
+
+#endif //  MGTRACEPRINT_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/CommonInc/clfvariant.hrh	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*      This file contains all the declarations to variate locally
+*      Content Listing Framework
+*
+*
+*/
+
+
+#ifndef CLFVARIANT_HRH
+#define CLFVARIANT_HRH
+
+// CLFVariant related values are in CenRep under
+// KCRUidContentListingFramework key KCLFLocalVariation
+
+// Flag to enable parsing meta data from music files. If feature is enabled then
+// CLF returns possible meta data from music files.
+// This feature has effect to performance of the CLF, if feature is enabled
+// then CLF might be slow if there are lots of music files.
+// By default this feature is enabled.
+#define KCLFMusicMetadata      0x01
+
+// Flag to enable parsing meta data from video files. If feature is enabled then
+// CLF returns possible meta data from video files.
+// This feature has effect to performance of the CLF, if feature is enabled
+// then CLF might be slow if there are lots of video files.
+// By default this feature is disabled.
+#define KCLFVideoMetadata      0x02
+
+
+#endif // CLFVARIANT_HRH
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/CommonInc/contentlistingframeworkprivatecrkeys.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Private Central Repository keys.*
+*/
+
+
+
+#ifndef CONTENTLISTINGFRAMEWORKPRIVATECRKEYS_H
+#define CONTENTLISTINGFRAMEWORKPRIVATECRKEYS_H
+
+//  INCLUDES
+#include <e32std.h>
+
+const TUid KCRUidContentListingFramework = {0x102828AC};
+
+const TUint32 KCLFLocalVariation = 0x00000000;
+
+const TUint32 KPhoneSkippedFolders          = 0x00000001;
+const TUint32 KOtherMemorySkippedFolders    = 0x00000002;
+
+#endif      // CONTENTLISTINGFRAMEWORKPRIVATECRKEYS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/EABI/ContentListingFrameworkU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,6 @@
+EXPORTS
+	_ZN21ContentListingFactory17NewSortingStyleLCER15TResourceReader @ 1 NONAME
+	_ZN21ContentListingFactory17NewSortingStyleLCEv @ 2 NONAME
+	_ZN21ContentListingFactory19NewModifiableItemLCEv @ 3 NONAME
+	_ZN21ContentListingFactory25NewContentListingEngineLCEv @ 4 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/EABI/MediaCollectionManagerU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	_ZN29MediaCollectionManagerFactory24CreateCollectionManagerLEv @ 1 NONAME
+
Binary file clfwrapper/cenrep/keys_s60contentlistingframework.xls has changed
Binary file clfwrapper/conf/102828AC.txt has changed
Binary file clfwrapper/conf/s60contentlistingframework.confml has changed
Binary file clfwrapper/conf/s60contentlistingframework_102828AC.crml has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file for project contentlistingframework
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+../conf/s60contentlistingframework.confml        MW_LAYER_CONFML(s60contentlistingframework.confml)
+../conf/s60contentlistingframework_102828AC.crml MW_LAYER_CRML(s60contentlistingframework_102828AC.crml)
+
+//Stubs
+../sis/contentlistingframework_stub.sis  /epoc32/data/z/system/install/contentlistingframework_stub.sis
+
+PRJ_MMPFILES
+// Client side APIs
+    mediacollectionmanager.mmp
+    contentlistingframework.mmp
+
+//  End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/group/contentlistingframework.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,63 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file for project contentlistingframework
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+#include <../CommonInc/CLFUID.hrh>
+
+VERSION         10.0
+TARGET          ContentListingFramework.dll
+TARGETTYPE      DLL
+UID             0x1000008d CLF_FRAMEWORK_UID3
+VENDORID        VID_DEFAULT
+CAPABILITY      CAP_CLIENT_DLL
+
+SOURCEPATH      ../ClientSrc
+SOURCE          CCLFDbItemContainer.cpp
+SOURCE          CCLFDbItemProvider.cpp
+SOURCE          CCLFDefaultOperation.cpp
+SOURCE          CCLFEngineImpl.cpp
+SOURCE          CCLFItemImpl.cpp
+SOURCE          CCLFItemListModelImpl.cpp
+SOURCE          CCLFSortingStyleImpl.cpp
+SOURCE          ContentListingFactory.cpp
+SOURCE          CCLFQueryAdapter.cpp
+SOURCE          CCLFEventHandler.cpp
+SOURCE          CCLFServerProxy.cpp
+SOURCE          CLFUtils.cpp
+
+// Default system include paths for application layer modules.
+MW_LAYER_SYSTEMINCLUDE
+USERINCLUDE     ../ClientSrc
+USERINCLUDE     ../CommonInc
+USERINCLUDE     ../../inc
+
+LIBRARY         euser.lib
+LIBRARY         estor.lib
+LIBRARY         efsrv.lib
+LIBRARY         bafl.lib
+LIBRARY         platformenv.lib
+LIBRARY         mdeclient.lib
+LIBRARY         harvesterclient.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/group/mediacollectionmanager.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file for project contentlistingframework
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+#include <../commoninc/clfuid.hrh>
+
+VERSION         10.0
+TARGET          MediaCollectionManager.dll
+TARGETTYPE      DLL
+UID             0x1000008d CLF_FRAMEWORK_UID3
+VENDORID        VID_DEFAULT
+CAPABILITY      CAP_GENERAL_DLL
+
+SOURCEPATH      ../mediacollectionmanagersrc
+
+SOURCE          mediacollectionmanagerfactory.cpp
+SOURCE          mediacollectionmanagerimpl.cpp
+
+// Default system include paths for application layer modules.
+MW_LAYER_SYSTEMINCLUDE
+USERINCLUDE     ../CommonInc
+SYSTEMINCLUDE   /epoc32/include/ecom
+
+LIBRARY         euser.lib
+LIBRARY         estor.lib
+LIBRARY         efsrv.lib
+LIBRARY         bafl.lib
+
+BYTEPAIRCOMPRESSTARGET
+PAGED
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/mediacollectionmanagersrc/mediacollectionmanagerfactory.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#include "mediacollectionmanagerimpl.h"
+
+// ======== MEMBER FUNCTIONS ========
+
+EXPORT_C MMediaCollectionManager*
+            MediaCollectionManagerFactory::CreateCollectionManagerL()
+    {
+    return CMediaCollectionManagerImpl::NewL();
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/mediacollectionmanagersrc/mediacollectionmanagerimpl.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,227 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#include "mediacollectionmanagerimpl.h"
+#include "CLFConsts.h"
+#include "CLFPanics.h"
+
+const TInt KCLFMCMObserverArrayGranularity( 2 );
+
+// ======== MEMBER FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::CMediaCollectionManagerImpl
+// -----------------------------------------------------------------------------
+//
+CMediaCollectionManagerImpl::CMediaCollectionManagerImpl()
+    : iObserverArray( KCLFMCMObserverArrayGranularity )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CMediaCollectionManagerImpl::ConstructL()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::NewL
+// -----------------------------------------------------------------------------
+//
+CMediaCollectionManagerImpl* CMediaCollectionManagerImpl::NewL()
+    {
+    CMediaCollectionManagerImpl* self =
+                        new (ELeave) CMediaCollectionManagerImpl;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::~CMediaCollectionManagerImpl
+// -----------------------------------------------------------------------------
+//
+CMediaCollectionManagerImpl::~CMediaCollectionManagerImpl()
+    {
+    iObserverArray.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::GetCollectionInfosL
+// -----------------------------------------------------------------------------
+//
+void CMediaCollectionManagerImpl::GetCollectionInfosL(
+			RPointerArray<MMediaCollectionInfo>& /* aCollectionInfoArray */ ) const
+    {
+    User::Leave( KErrNotSupported );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::CollectionInfoByIdLC
+// -----------------------------------------------------------------------------
+//
+MMediaCollectionInfo* CMediaCollectionManagerImpl::CollectionInfoByIdLC(
+                TInt /* aId */ ) const
+    {
+    User::Leave( KErrNotSupported );
+
+    MMediaCollectionInfo* info = NULL;
+    return info;
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::CreateCollectionL
+// -----------------------------------------------------------------------------
+//
+TInt CMediaCollectionManagerImpl::CreateCollectionL(
+                const TDesC& /* aName */,
+                const TArray<TInt>& /* aCollectionItemTypes */,
+                TInt32 /* aCollectionProperties */ )
+    {
+    User::Leave( KErrNotSupported );
+
+    TInt collectionID( 0 );
+    return collectionID;
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::DeleteCollectionL
+// -----------------------------------------------------------------------------
+//
+void CMediaCollectionManagerImpl::DeleteCollectionL(
+                TInt /* aId */ )
+    {
+    User::Leave( KErrNotSupported );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::RenameCollectionL
+// -----------------------------------------------------------------------------
+//
+void CMediaCollectionManagerImpl::RenameCollectionL(
+                TInt /* aId */,
+                const TDesC& /* aNewName */ )
+    {
+    User::Leave( KErrNotSupported );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::AddToCollectionL
+// -----------------------------------------------------------------------------
+//
+void CMediaCollectionManagerImpl::AddToCollectionL(
+                TInt /* aId */,
+                const MDesCArray& /* aItemArray */,
+                TBool /* aRemoveFromOtherCollections */ )
+    {
+    User::Leave( KErrNotSupported );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::RemoveFromCollectionL
+// -----------------------------------------------------------------------------
+//
+void CMediaCollectionManagerImpl::RemoveFromCollectionL(
+                TInt /* aId */,
+                const MDesCArray& /* aItemArray */ )
+    {
+    User::Leave( KErrNotSupported );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::RemoveFromAllCollectionsL
+// -----------------------------------------------------------------------------
+//
+void CMediaCollectionManagerImpl::RemoveFromAllCollectionsL(
+                    const MDesCArray& /* aItemArray */ )
+    {
+#if ( 0 )
+    User::Leave( KErrNotSupported );
+#endif
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::GetCollectionItemArrayL
+// -----------------------------------------------------------------------------
+//
+void CMediaCollectionManagerImpl::GetCollectionItemArrayL(
+                TInt /* aId */,
+                CDesCArray& /* aItemArray */ ) const
+    {
+    User::Leave( KErrNotSupported );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::GetCollectionIdByItemL
+// -----------------------------------------------------------------------------
+//
+void CMediaCollectionManagerImpl::GetCollectionIdByItemL(
+                const TDesC& /* aItem */,
+                RArray<TInt>& /* aIdArray */ ) const
+    {
+#if (0)
+    User::Leave( KErrNotSupported );
+#endif
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::AddCollectionObserverL
+// -----------------------------------------------------------------------------
+//
+void CMediaCollectionManagerImpl::AddCollectionObserverL(
+                MMediaCollectionObserver& aObserver )
+    {
+    iObserverArray.AppendL( &aObserver );
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::RemoveCollectionObserverL
+// -----------------------------------------------------------------------------
+//
+void CMediaCollectionManagerImpl::RemoveCollectionObserverL(
+                MMediaCollectionObserver& aObserver )
+    {
+    const TInt index( iObserverArray.Find( &aObserver ) );
+    if( index >= 0 )
+        {
+        iObserverArray.Remove( index );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CMediaCollectionManagerImpl::GetDriveById
+// -----------------------------------------------------------------------------
+//
+TInt32 CMediaCollectionManagerImpl::GetDriveByIdL( TInt /* aId */ )
+    {
+    User::Leave( KErrNotSupported );
+    
+    TInt drive( 0 );
+    return drive;
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/mediacollectionmanagersrc/mediacollectionmanagerimpl.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,111 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef MMEDIACOLLECTIONMANAGERIMPL_H
+#define MMEDIACOLLECTIONMANAGERIMPL_H
+
+#include <mediacollectionmanager.h>
+
+/**
+ *  This class implements Media Collection Manager functionality
+ *
+ *  @lib MediaCollectionManager.lib
+ *  @since S60 3.2
+ */
+NONSHARABLE_CLASS( CMediaCollectionManagerImpl ) :
+                            public CBase,
+                            public MMediaCollectionManager
+    {
+    public:
+    
+        static CMediaCollectionManagerImpl* NewL();
+
+        virtual ~CMediaCollectionManagerImpl();
+
+    protected:
+
+		/// From MMediaCollectionManager
+        void GetCollectionInfosL(
+                    RPointerArray<MMediaCollectionInfo>& aCollectionInfoArray ) const;
+
+		/// From MMediaCollectionManager
+        MMediaCollectionInfo* CollectionInfoByIdLC(
+                    TInt aId ) const;
+
+		/// From MMediaCollectionManager
+        TInt CreateCollectionL(
+                    const TDesC& aName,
+                    const TArray<TInt>& aCollectionItemTypes,
+                    TInt32 aCollectionProperties );
+
+		/// From MMediaCollectionManager
+        void DeleteCollectionL(
+                    TInt aId );
+
+		/// From MMediaCollectionManager
+        void RenameCollectionL(
+                    TInt aId,
+                    const TDesC& aNewName );
+
+		/// From MMediaCollectionManager
+        void AddToCollectionL(
+                    TInt aId,
+                    const MDesCArray& aItemArray,
+                    TBool aRemoveFromOtherCollections = ETrue );
+
+		/// From MMediaCollectionManager
+        void RemoveFromCollectionL(
+                    TInt aId,
+                    const MDesCArray& aItemArray );
+
+		/// From MMediaCollectionManager
+        void RemoveFromAllCollectionsL(
+                    const MDesCArray& aItemArray );
+
+		/// From MMediaCollectionManager
+        void GetCollectionItemArrayL(
+                    TInt aId,
+                    CDesCArray& aItemArray ) const;
+
+		/// From MMediaCollectionManager
+        void GetCollectionIdByItemL(
+                    const TDesC& aItem,
+                    RArray<TInt>& aIdArray ) const;
+
+		/// From MMediaCollectionManager
+        void AddCollectionObserverL(
+                    MMediaCollectionObserver& aObserver );
+
+		/// From MMediaCollectionManager
+        void RemoveCollectionObserverL(
+                    MMediaCollectionObserver& aObserver );
+        
+        /// From MMediaCollectionManager            
+        TInt32 GetDriveByIdL( TInt aId );
+    private:
+    
+        CMediaCollectionManagerImpl();
+        void ConstructL();
+
+    private:
+        /// Ref list to observers
+        RPointerArray<MMediaCollectionObserver> iObserverArray;
+    };
+
+
+#endif // MMEDIACOLLECTIONMANAGER_H
Binary file clfwrapper/sis/contentlistingframework_stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/sis/depends.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ad:metadata xmlns="http://nokia.com/arrow/repository/ia_component"
+  xmlns:ad="http://nokia.com/arrow/application_metadata">
+  <appResources>
+     <appResource>
+        <language>1</language>
+        <iacName>ContentListingFramework</iacName>
+        <iacDescription>Upgrade package for ContentListingFramework</iacDescription>
+     </appResource>
+  </appResources>
+  <swPlatformDep>
+     <platform>S60</platform>
+     <versionFrom>
+        <major>5</major>
+        <minor>0</minor>
+        <date>
+           <year>2009</year>
+           <week>16</week>
+        </date>
+     </versionFrom>
+  </swPlatformDep>
+  <interDeps>
+  </interDeps>
+</ad:metadata>
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/sis/package.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,34 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"ContentListingFramework Patch"},(0x101F8858), 2, 0, 0, TYPE=SA, RU
+
+; Localised vendor name
+%{"Nokia"}
+
+; Unique vendor name
+:"Nokia"
+
+;Files
+
+
+"\EPOC32\RELEASE\ARMV5\UREL\MediaCollectionManager.dll" -"c:\sys\bin\MediaCollectionManager.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\ContentListingFramework.dll" -"c:\sys\bin\ContentListingFramework.dll"
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/clfwrapper/sis/stub.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+; Languages
+&EN
+
+; Header
+#{"ContentListingFramework"}, (0x101F8858), 1, 0, 0, TYPE=SA
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+;Files
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/bwincw/contextenginewinscw.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,9 @@
+EXPORTS
+	?ContextSnapshot@CContextEngine@@QAEXAAVMContextSnapshotObserver@@AAV?$RPointerArray@VCHarvesterData@@@@@Z @ 1 NONAME ; void CContextEngine::ContextSnapshot(class MContextSnapshotObserver &, class RPointerArray<class CHarvesterData> &)
+	?ContextSnapshot@CContextEngine@@QAEXAAVMContextSnapshotObserver@@AAVCHarvesterData@@@Z @ 2 NONAME ; void CContextEngine::ContextSnapshot(class MContextSnapshotObserver &, class CHarvesterData &)
+	?Destroy@CContextEngine@@QAEXXZ @ 3 NONAME ; void CContextEngine::Destroy(void)
+	?GetInstanceL@CContextEngine@@SAPAV1@PAVMContextInitializationObserver@@@Z @ 4 NONAME ; class CContextEngine * CContextEngine::GetInstanceL(class MContextInitializationObserver *)
+	?PluginCount@CContextEngine@@QAEHXZ @ 5 NONAME ; int CContextEngine::PluginCount(void)
+	?ReleaseInstance@CContextEngine@@QAEXXZ @ 6 NONAME ; void CContextEngine::ReleaseInstance(void)
+	?SetMdeSession@CContextEngine@@QAEXPAVCMdESession@@@Z @ 7 NONAME ; void CContextEngine::SetMdeSession(class CMdESession *)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/data/ContextEngine_Stub.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,38 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Language
+&en
+
+;Header
+# {"ContextEngine"}, (0x200009F6), 1, 0, 0, TYPE=SA
+
+;Localised Vendor name
+%{"Nokia"}
+
+;Unique Vendor name
+:"Nokia"
+
+;Files to install
+""-"z:\sys\bin\contextengine.dll"
+""-"z:\sys\bin\contextplugininterface.dll"
+
+""-"z:\sys\bin\calendarcontextplugin.dll"
+""-"z:\resource\plugins\calendarcontextplugin.rsc"
+
+""-"z:\sys\bin\locationcontextplugin.dll"
+""-"z:\resource\plugins\locationcontextplugin.rsc"
+
+
Binary file contextengine/data/ContextEngine_Stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/data/Create_STUB_SIS.bat	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,17 @@
+rem
+rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+rem All rights reserved.
+rem This component and the accompanying materials are made available
+rem under the terms of "Eclipse Public License v1.0"
+rem which accompanies this distribution, and is available
+rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+rem
+rem Initial Contributors:
+rem Nokia Corporation - initial contribution.
+rem
+rem Contributors:
+rem
+rem Description:
+rem
+
+makesis -s ContextEngine_Stub.pkg ContextEngine_Stub.sis
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/data/contextengine.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,36 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Context Enginw"},(0x200009F6),1,0,0, TYPE=SA, RU
+
+; Localised vendor name
+%{"Nokia"}
+
+; Unique vendor name
+:"Nokia"
+
+;Files
+"\EPOC32\RELEASE\ARMV5\UREL\contextengine.dll" -"!:\sys\bin\contextengine.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\contextplugininterface.dll" -"!:\sys\bin\contextplugininterface.dll"
+
+"\EPOC32\RELEASE\ARMV5\UREL\calendarcontextplugin.dll" -"!:\sys\bin\calendarcontextplugin.dll"
+"\epoc32\data\z\resource\plugins\calendarcontextplugin.rsc" -"!:\resource\plugins\calendarcontextplugin.rsc"
+
+"\EPOC32\RELEASE\ARMV5\UREL\locationcontextplugin.dll" -"!:\sys\bin\locationcontextplugin.dll"
+"\epoc32\data\z\resource\plugins\locationcontextplugin.rsc" -"!:\resource\plugins\locationcontextplugin.rsc"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/data/rd-key.pem	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICXAIBAAKBgQDLRF+r1FGGkCwTrb420kbnAps7gi1yYUcXYUdWeFTuBeQe5eW4
+6Y+LWaA8HMlDdoHRB0FgASisYcFagwno9+oFf4AJka4H1gWEs5XTGwAA1s0d8XGh
+7W7Dt9F5FZij8F7/9Pi6+FhhxZFIf1DD+yry9D7+Sp+BgdNALe4XOpf25QIBAwKB
+gQCHgupyjYuvCsgNHn7PNtnvVxInrB5MQNoPli+O+uNJWUK/Q+57Rl+yO8AoEzDX
+pFaLWiuVVhsdloDnAgabT/FXzYncs6uOHyEUV+dSXb78vtLPJqAX+Fg2i3hOXreB
+yskcZ13/OsKVOu5wgrJkx2baZufkqMwOSytf5y9nwjEIKwJBAP+inobagVNrN62j
+KQva3cC+UN/6XnKdTc0CA6bHyLOaJoH1xiMwG/VS2PGjHI0tiSMNtLn/QPpHJ003
+iabGhdUCQQDLjp/9UjFT6K6CF66Chqf30pZXhx+GTSQZmv/gvZiMly7X9fX9BGX3
+2MbJohBC4yI21XKTbisWywkF73Hwh+TRAkEAqmxprzxWN5zPyRdwspHpKymLP/w+
+9xOJM1atGdqFzRFvAU6EF3Vn+OHl9my9s3OwwgkjJqorUYTE3iUGby8D4wJBAIe0
+aqjhdjfwdFa6dFcEb/qMZDpaFQQzbWZnVUB+ZbMPdI/5TqitmU/l2dvBYCyXbCSO
+TGJJcg8yBgP09qBamIsCQFL7j1tM0XPVQJQ89WpKCld7O9ORxRGVj1eG0tWijrH8
+mGbYh8SGCVoWV3vrKSS8GBrFVgQnqUaHuEdtM7tpCAQ=
+-----END RSA PRIVATE KEY-----
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/data/rd.cer	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIICzDCCAjWgAwIBAgIBADANBgkqhkiG9w0BAQUFADArMRAwDgYDVQQKEwdSRCBD
+ZXJ0MRcwFQYDVQQDEw5SRCBDZXJ0aWZpY2F0ZTAeFw0wNDExMTUxMjQyMDZaFw0z
+NzA5MjMxMjQyMDZaMCsxEDAOBgNVBAoTB1JEIENlcnQxFzAVBgNVBAMTDlJEIENl
+cnRpZmljYXRlMIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDLRF+r1FGGkCwT
+rb420kbnAps7gi1yYUcXYUdWeFTuBeQe5eW46Y+LWaA8HMlDdoHRB0FgASisYcFa
+gwno9+oFf4AJka4H1gWEs5XTGwAA1s0d8XGh7W7Dt9F5FZij8F7/9Pi6+FhhxZFI
+f1DD+yry9D7+Sp+BgdNALe4XOpf25QIBA6OCAQAwgf0wDAYDVR0TBAUwAwEB/zAL
+BgNVHQ8EBAMCAoQwHQYDVR0OBBYEFFi/kuGzxhVpjGxe9ZwlxC3fH9jFMFMGA1Ud
+IwRMMEqAFFi/kuGzxhVpjGxe9ZwlxC3fH9jFoS+kLTArMRAwDgYDVQQKEwdSRCBD
+ZXJ0MRcwFQYDVQQDEw5SRCBDZXJ0aWZpY2F0ZYIBADBsBgNVHSAEZTBjMGEGBFUd
+IAAwWTATBggrBgEFBQcCARYHaHR0cDovLzBCBggrBgEFBQcCAjA2GjRGb3IgUiZE
+IHVzYWdlIG9ubHkuIFRoaXMgY2VydGlmaWNhdGUgaXMgbm90IHRydXN0ZWQuMA0G
+CSqGSIb3DQEBBQUAA4GBAHGB4RQMAgBdeT2hxfOr6f2nA/dZm+M5yX5daUtZnET9
+Ed0A9sazLawfN2G1KFQT9kxEParAyoAkpbMAsRrnRz/9cM3OHgFm/NiKRnf50DpT
+7oCx0I/65mVD2kt+xXE62/Ii5KPnTufIkPi2uLvURCia1tTS8JmJ8dtxDGyQt8BR
+-----END CERTIFICATE-----
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/eabi/contextenginearm.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,11 @@
+EXPORTS
+	_ZN14CContextEngine11PluginCountEv @ 1 NONAME
+	_ZN14CContextEngine12GetInstanceLEP30MContextInitializationObserver @ 2 NONAME
+	_ZN14CContextEngine13SetMdeSessionEP11CMdESession @ 3 NONAME
+	_ZN14CContextEngine15ContextSnapshotER24MContextSnapshotObserverR13RPointerArrayI14CHarvesterDataE @ 4 NONAME
+	_ZN14CContextEngine15ContextSnapshotER24MContextSnapshotObserverR14CHarvesterData @ 5 NONAME
+	_ZN14CContextEngine15ReleaseInstanceEv @ 6 NONAME
+	_ZN14CContextEngine7DestroyEv @ 7 NONAME
+	_ZTI14CContextEngine @ 8 NONAME ABSENT; #<TI>#
+	_ZTV14CContextEngine @ 9 NONAME ABSENT; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+#include "../plugins/group/bld.inf"
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+../sis/contextengine_stub.sis  /epoc32/data/z/system/install/contextengine_stub.sis
+
+PRJ_MMPFILES
+contextengine.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/group/contextengine.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        contextengine.dll
+TARGETTYPE    dll
+UID           0x1000008d 0x200009F6
+
+CAPABILITY    CAP_GENERAL_DLL
+VENDORID      VID_DEFAULT
+
+SYSTEMINCLUDE /epoc32/include/ecom
+SYSTEMINCLUDE /epoc32/include/connect
+USERINCLUDE   ../inc
+USERINCLUDE   ../../inc
+USERINCLUDE   ../../harvester/common/inc
+
+SOURCEPATH   ../src
+SOURCE        contextengine.cpp
+SOURCE        contextengineao.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       ecom.lib
+LIBRARY       contextplugininterface.lib
+LIBRARY	  	  harvesterdata.lib
+LIBRARY	  	  harvestercommon.lib
+
+#if defined(WINS)
+deffile ../bwincw/contextenginewinscw.def
+#elif defined(ARMCC)
+deffile ../eabi/contextenginearm.def
+#endif
+nostrictdef
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/inc/contextengineao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,247 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef CONTEXTENGINEAO_H
+#define CONTEXTENGINEAO_H
+
+// system include
+#include <e32base.h>
+
+// user include
+#include "contextplugin.h"
+#include "mpropertyobserver.h"
+
+// forward declarations
+class CContextSnapshotItem;
+class MContextInitializationObserver;
+class MContextSnapshotObserver;
+class CMdESession;
+class CPropertyWatcher;
+
+/**
+* This class implements an active object for collecting context metadata
+* asyncronously from the context plugins.
+*/
+NONSHARABLE_CLASS( CContextEngineAO ) : public CActive, 
+									    public MContextPluginObserver,
+										public MKeyObserver
+  	{
+public:
+
+	/**
+	 * State for context engine (=this active object).
+	 * Possible states: Ready for snapshot, initializing plugins or taking a snapshot.
+	 */
+	enum TContextEngineState { EReady = 0, EInitialization, ESnapshot };
+
+	/**
+	 * Creates and constructs a new instance of CContextEngineAO.
+	 *
+	 * @return A pointer to the new instance.
+	 */
+	static CContextEngineAO* NewL( MContextInitializationObserver* aInitObserver,
+		MContextSnapshotObserver* aSnapshotObserver );
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CContextEngineAO();
+
+public:
+	/**
+	 * Set a pointer to MdESession. The pointer is given forward to context plugins.
+	 * Session must be set in order to successfully harvest context data.
+	 *
+	 * @param aSession Session pointer to set.
+	 */
+	void SetMdeSession( CMdESession* aSession );
+
+	/**
+	 * Start taking a context snapshot (for multiple objects).
+	 *
+	 * @param aItem  Observer to inform about snapshot completion
+	 *               and MdE objects the snapshot is taken to.
+	 */
+	void StartSnapshot( CContextSnapshotItem* aItem );
+
+	/**
+	 * Method used to clarify how many plug-ins are loaded.
+	 *
+	 * @return Amount of plug-ins loaded.
+	 */
+	TInt PluginCount();
+
+public:   // from base class CActive
+
+	/**
+	 * From CActive.
+	 * Every call takes a context snapshot from one plug-in.
+	 */
+	void RunL();
+
+	/**
+	 * From CActive.
+	 * Handles a leave occurring in the request completion event handler RunL().
+	 *
+	 * @param aError  An error code.
+	 * @return An error code.
+	 */
+	TInt RunError( TInt aError );
+
+	/**
+	 * From CActive.
+	 * Cancels ????.
+	 */
+	void DoCancel();
+
+public:   // from MContextPluginObserver
+
+	/**
+	 * From MContextPluginObserver.
+	 * This is derived from MContextPluginObserver and it is called
+	 * by each plug-in when they have initialized.
+	 * Error code for the first encountered error is returned as a parameter.
+	 *
+	 * @param aErrorCode  Error code for the first error occurred during initialization.
+	 */
+	void PluginInitializationStatus( TInt aErrorCode );
+	
+	/**
+	 * From MContextPluginObserver.
+	 * This is derived from MContextPluginObserver and it is called
+	 * by each plug-in when they have taken the context snapshot.
+	 * Error code for the first encountered error is returned as a parameter.
+	 *
+	 * @param aErrorCode  Error code for the first error occurred while taking the snapshot.
+	 */
+	void PluginSnapshotStatus( CHarvesterData* aHD );
+        
+public: // From MKeyObserver.   	
+
+	/**
+	 * Method NotifyKeyL from MKeyObserver get notifications when
+	 * property key has changed.
+	 */
+	void NotifyKeyL( 
+			const TInt aKeyValue,
+			const TUid aPropertyCategory,
+			const TUint aKey );     
+
+private:
+
+	/**
+	 * Default constructor, implicitly called by NewL().
+	 */
+	CContextEngineAO( MContextInitializationObserver* aInitObserver,
+		MContextSnapshotObserver* aSnapshotObserver );
+
+	/**
+	 * 2nd phase construction, called by NewL().
+	 */
+	void ConstructL();
+
+	/**
+	 * Load context plugins.
+	 */
+	void LoadPluginsL();
+
+	/**
+	 * Initialize this object. Thus load and initialize context plugins.
+	 */
+	void InitializeL();
+
+	/**
+	  * Called when
+	  * Backup&Restore is backing up or restoring.
+	  */
+	 void BackupRestoreStart();
+
+	 /**
+	  * Called when
+	  * Backup&Restore has finished backup or restore.
+	  */
+	 void BackupRestoreReady();
+
+	/**
+	 * Method HandleBackupRestoreKeyActionL.
+	 * If user make full restore sets restore flag on.
+	 */
+	void HandleBackupRestoreKeyAction( const TUint aKeyValue );
+    
+private: // data
+
+	/**
+	 * This observer is used to inform the client application about
+	 * finishing plug-in initializations.
+	 */
+	MContextInitializationObserver* iInitializationObserver;
+	
+	/**
+	 * This observer is used to inform Context Engine about
+	 * finishing a context snapshot.
+	 */
+	MContextSnapshotObserver* iContextSnapshotObserver;
+
+	/**
+	 * Plug-in array contains the plug-ins.
+	 */
+	RPointerArray<CContextPlugin> iPlugins;
+
+	/**
+	 * Number of plug-ins currently not being initialized yet.
+	 */
+	TInt iUninitializedPluginsCount;
+	
+	/**
+	 * Number of HDs currently not completed the snapshot yet.
+	 */
+	TInt iPluginSnapshotsLacking;
+	
+	/**
+	 * Item to which we are currently doing a snapshot for.
+	 */
+	CContextSnapshotItem* iItem;
+	
+	/**
+	 * State of this active object.
+	 */
+	TContextEngineState iState;
+	
+	/** First error code encountered in initialization is cached here and returned later. */
+	TInt iInitializationError;
+	
+	/** First error code encountered in snapshot is cached here and returned later. */
+	TInt iSnapshotError;
+	
+	/**
+	  * iMdESession - MDE session.
+	  */
+	CMdESession* iMdESession;
+
+	/**
+	 * iPropertyWatcher - constains observed key's, owned by this class.
+	 */
+	CPropertyWatcher* iPropertyWatcher;
+	
+    /**
+     * iPropertyWatcher - used to check if only one plugin has not finished work.
+     */
+    TBool iLastPlugin;
+    };
+
+#endif // CONTEXTENGINEAO_H 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/inc/contextsnapshotitem.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,79 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A simple class to store context observers and related
+*                metadata objects.
+*
+*/
+
+
+#ifndef CCONTEXTSNAPSHOTITEM_H
+#define CCONTEXTSNAPSHOTITEM_H
+
+#include <e32base.h>
+
+class CHarvesterData;
+
+/**
+* A simple storage class used to store queued context observers and their objects.
+*/
+class CContextSnapshotItem : public CBase
+    {
+    public:
+
+        /** NewL for creating new initialized CContextSnapshotItem. */
+        static CContextSnapshotItem* NewL( MContextSnapshotObserver* aObserver,
+            CHarvesterData* aHD );
+
+        /** NewL for creating new initialized CContextSnapshotItem for multiple items. */
+        static CContextSnapshotItem* NewL( MContextSnapshotObserver* aObserver,
+            RPointerArray<CHarvesterData>* aObjects );
+
+        /** Destructor */
+        virtual ~CContextSnapshotItem();
+
+        /** Sets observer for this item */
+        void SetObserver( MContextSnapshotObserver* aObserver );
+
+        /** Gets observer from this item */
+        MContextSnapshotObserver* GetObserver();
+
+        /** Sets item pointer for this item */
+        void SetItem( CHarvesterData* aHD );
+
+        /** Gets item pointer for this item */
+        CHarvesterData* GetItem();
+
+        /** Sets item array pointer for this item */
+        void SetItemArray( RPointerArray<CHarvesterData>* aObjects );
+
+        /** Gets item array pointer for this item */
+        RPointerArray<CHarvesterData>* GetItemArray();
+
+    private:
+
+        /** Default constructor */
+        CContextSnapshotItem();
+
+    private: // data
+
+        MContextSnapshotObserver* iObserver;
+        CHarvesterData* iHD;
+        RPointerArray<CHarvesterData>* iHDArray;
+    };
+
+
+#include "contextsnapshotitem.inl"
+
+
+#endif // CCONTEXTSNAPSHOTITEM_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/inc/contextsnapshotitem.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,81 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Inline implementations CContextSnapshotItem.
+*
+*/
+
+
+#ifndef CCONTEXTSNAPSHOTITEM_INL
+#define CCONTEXTSNAPSHOTITEM_INL
+
+inline CContextSnapshotItem::CContextSnapshotItem()
+    : iObserver( NULL ), iHD( NULL ), iHDArray( NULL )
+    {
+    }
+
+inline CContextSnapshotItem::~CContextSnapshotItem() // notice that objects are not destroyed
+    {
+    } 
+
+inline CContextSnapshotItem* CContextSnapshotItem::NewL(
+    MContextSnapshotObserver* aObserver, CHarvesterData* aHD )
+    {
+    CContextSnapshotItem* self = new (ELeave) CContextSnapshotItem();
+    self->SetObserver( aObserver );
+    self->SetItem( aHD );
+    return self;
+    }
+
+inline CContextSnapshotItem* CContextSnapshotItem::NewL(
+    MContextSnapshotObserver* aObserver, RPointerArray<CHarvesterData>* aHDArray )
+    {
+    CContextSnapshotItem* self = new (ELeave) CContextSnapshotItem();
+    self->SetObserver( aObserver );
+    self->SetItemArray( aHDArray );
+    return self;
+    }
+
+inline void CContextSnapshotItem::SetObserver( MContextSnapshotObserver* aObserver )
+    {
+    iObserver = aObserver;
+    }
+
+inline MContextSnapshotObserver* CContextSnapshotItem::GetObserver()
+    {
+    return iObserver;
+    }
+
+inline void CContextSnapshotItem::SetItem( CHarvesterData* aHD )
+    {
+    iHD = aHD;
+    iHDArray = NULL;
+    }
+
+inline CHarvesterData* CContextSnapshotItem::GetItem()
+    {
+    return iHD;
+    }
+
+inline void CContextSnapshotItem::SetItemArray( RPointerArray<CHarvesterData>* aHDArray )
+    {
+    iHDArray = aHDArray;
+    iHD = NULL;
+    }
+
+inline RPointerArray<CHarvesterData>* CContextSnapshotItem::GetItemArray()
+    {
+    return iHDArray;
+    }
+
+#endif // CCONTEXTSNAPSHOTITEM_INL
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/calendarplugin/data/102823CA.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#include "registryinfov2.rh"
+
+
+// Declares info for one test implementation
+RESOURCE REGISTRY_INFO theInfo
+    {
+    // resource_format_version must always be set as follows
+    resource_format_version = RESOURCE_FORMAT_VERSION_2;
+    
+    // UID for the DLL
+    dll_uid = 0x102823CA; //was: ...E
+    // Declare array of interface info
+    interfaces = 
+        {
+        INTERFACE_INFO
+            {
+            // UID of interface that is implemented
+            interface_uid = 0x200009F7; //Context Framework
+            implementations = 
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = 0x102823CB;    
+                    version_no = 1;
+                    display_name = "Calendar Context Plugin";
+                    default_data = "Calendar";
+                    opaque_data = "";
+                    rom_only = 0;
+                    }
+                };
+            }
+        };
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/calendarplugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+calendarcontextplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/calendarplugin/group/calendarcontextplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,64 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        calendarcontextplugin.dll
+TARGETTYPE    PLUGIN
+UID           0x10009D8D 0x102823CA
+
+CAPABILITY 	  CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+SYSTEMINCLUDE /epoc32/include/ecom
+
+USERINCLUDE   ../../../../inc
+USERINCLUDE   ../inc
+
+SOURCEPATH    ../src
+SOURCE        CalendarContextPlugin.cpp
+SOURCE        proxy.cpp
+
+SOURCEPATH    ../data
+start RESOURCE 102823CA.rss
+target calendarcontextplugin.rsc
+end
+
+APP_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       ECom.lib
+LIBRARY       inetprotutil.lib
+LIBRARY       contextplugininterface.lib
+LIBRARY       mdeclient.lib
+LIBRARY       calinterimapi.lib
+LIBRARY	  estor.lib 
+LIBRARY	  harvesterdata.lib
+
+MACRO CALCON_LOGGING_ON
+#define CALCON_LOGGING_ON
+
+#ifdef CALCON_LOGGING_ON
+LIBRARY		efsrv.lib
+#endif
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/calendarplugin/inc/CalendarContextLogger.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Logging support for R&D purposes
+*
+*
+*/
+
+
+#ifndef CALENDARCONTEXTLOGGER_H_INCLUDED
+#define CALENDARCONTEXTLOGGER_H_INCLUDED
+
+// ========== INCLUDE FILES ================================
+
+#include <eikenv.h>
+
+// ========== CONSTANTS ====================================
+
+#ifdef CALCON_LOGGING_ON
+
+_LIT( KLBENGLogDir,               "CALCON");
+_LIT( KLBENGLogFile,              "CALCON.txt");
+_LIT( KLBENGLogBanner,            "CALCON 0.1.0");
+_LIT( KLBENGLogEnterFn,           "CALCON: -> %S");
+_LIT( KLBENGLogLeaveFn,           "CALCON: <- %S");
+_LIT( KLBENGLogExit,              "CALCON: Application exit");
+_LIT( KLBENGLogTimeFormatString,  "%H:%T:%S:%*C2");
+
+// ========== MACROS =======================================
+
+#define CALCONLOGGER_CREATE
+#define CALCONLOGGER_DELETE
+#define CALCONLOGGER_ENTERFN(a)         {_LIT(temp, a); RDebug::Print( KLBENGLogEnterFn, &temp);}
+#define CALCONLOGGER_LEAVEFN(a)         {_LIT(temp, a); RDebug::Print( KLBENGLogLeaveFn, &temp);}
+#define CALCONLOGGER_WRITE(a)           {_LIT(temp, a); RDebug::Print( temp);}
+#define CALCONLOGGER_WRITE_TIMESTAMP(a) {_LIT(temp, a); TTime time; time.HomeTime(); TBuf<256> buffer; time.FormatL( buffer, KLBENGLogTimeFormatString ); buffer.Insert(0, temp); RDebug::Print( buffer); }
+#define CALCONLOGGER_WRITEF             RDebug::Print
+
+/**
+ * 
+ */
+inline void FPrint( const TRefByValue<const TDesC> aFmt, ... );
+
+/**
+ * 
+ */
+inline void FPrint( const TDesC& aDes );
+
+/**
+ * 
+ */
+inline void FHex( const TUint8* aPtr, TInt aLen );
+
+/**
+ * 
+ */
+inline void FHex( const TDesC8& aDes );
+
+/**
+ * 
+ */
+inline void FCreate();
+
+#include "CalendarContextLogger.inl"
+
+
+#else // CALCON_LOGGING_ON
+
+inline void FPrint( const TRefByValue<const TDesC> /*aFmt*/, ... ) { };
+
+#define CALCONLOGGER_CREATE
+#define CALCONLOGGER_DELETE
+#define CALCONLOGGER_ENTERFN(a)
+#define CALCONLOGGER_LEAVEFN(a)
+#define CALCONLOGGER_WRITE(a)
+#define CALCONLOGGER_WRITEF   1 ? ((void)0) : FPrint
+#define CALCONLOGGER_WRITE_TIMESTAMP(a)
+
+#endif // CALCON_LOGGING_ON
+
+// ========== DATA TYPES ===================================
+
+// ========== FUNCTION PROTOTYPES ==========================
+
+// ========== FORWARD DECLARATIONS =========================
+
+// ========== CLASS DECLARATION ============================
+
+#endif // CALENDARCONTEXTLOGGER_H_INCLUDED
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/calendarplugin/inc/CalendarContextLogger.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,68 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Logging support for R&D purposes
+*
+*/
+
+
+/**
+ * 
+ */
+inline void FPrint( const TRefByValue<const TDesC> aFmt, ... )
+    {
+    VA_LIST list;
+    VA_START( list,aFmt );
+    RFileLogger::WriteFormat( KLBENGLogDir, KLBENGLogFile, EFileLoggingModeAppend, aFmt, list );
+    }
+
+/**
+ * 
+ */
+inline void FPrint( const TDesC& aDes )
+    {
+    RFileLogger::WriteFormat( KLBENGLogDir, KLBENGLogFile, EFileLoggingModeAppend, aDes );
+    }
+
+/**
+ * 
+ */
+inline void FHex( const TUint8* aPtr, TInt aLen )
+    {
+    RFileLogger::HexDump( KLBENGLogDir, KLBENGLogFile, EFileLoggingModeAppend, 0, 0, aPtr, aLen );
+    }
+
+/**
+ * 
+ */
+inline void FHex( const TDesC8& aDes )
+    {
+    FHex( aDes.Ptr(), aDes.Length() );
+    }
+
+/**
+ * 
+ */
+inline void FCreate()
+    {
+    _LIT( KLogPath, "c:\\logs\\" );
+    _LIT( KRootPath, "\\" );
+    TFileName path( KLogPath );
+    path.Append( KLBENGLogDir );
+    path.Append( KRootPath );
+    RFs fs;
+    fs.Connect();
+    fs.MkDirAll( path );
+    fs.Close();
+    RFileLogger::WriteFormat( KLBENGLogDir, KLBENGLogFile, EFileLoggingModeOverwrite, KLBENGLogBanner );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/calendarplugin/inc/CalendarContextPlugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,150 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#ifndef __CCALENDARCONTEXTPLUGIN_H__
+#define __CCALENDARCONTEXTPLUGIN_H__
+
+//  INCLUDES 
+#include <contextplugin.h>
+#include <calprogresscallback.h>
+
+#include <mdesession.h>
+#include "mdeharvestersession.h"
+
+// CONSTANTS
+
+
+// FORWARD DECLARATIONS
+class CCalInstanceView;
+class CCalEntry;
+class CCalSession;
+
+const TInt KInitRetryTimeout = 5000000; //5 sec
+const TInt KMaxRetryCount = 6; // retry for up to 30 sec
+
+// CLASS DECLARATION ===========================================================
+
+/**
+*  Main class of the plugin.
+*/
+class CCalendarContextPlugin : public CContextPlugin,
+                               public MMdESessionObserver,
+                               public MCalProgressCallBack
+      {
+    public:
+    	/** 
+    	* Static constructor
+        * @return           - pointer to the new object
+    	*/
+        static CCalendarContextPlugin* NewL();
+
+    	/** 
+    	* Destructor
+    	*/
+        virtual ~CCalendarContextPlugin();
+        
+    // CContextPlugin functions
+        void Init( MContextPluginObserver& aObserver );
+        void ContextSnapshot( MContextPluginObserver& aObserver,
+                               CHarvesterData& aHD );
+        void ContextSnapshot( MContextPluginObserver&    aObserver,
+                               RPointerArray<CHarvesterData>& aHDArray );
+                               
+    	void SetMdeSession( CMdESession& aSession );                           
+
+    // MMdESessionObserver functions, not used
+        virtual void HandleSessionOpened( CMdESession& aSession, TInt aError );
+        virtual void HandleSessionError( CMdESession& aSession, TInt aError );
+        
+    // MCalProgressCallBack functions, not used
+        virtual void Progress( TInt aPercentageCompleted );
+        virtual void Completed( TInt aError );
+        virtual TBool NotifyProgress();
+
+    private:
+    	/** 
+    	* C++ constructor
+    	*/
+        CCalendarContextPlugin();
+
+    	/** 
+    	* 2nd phase construction
+    	*/
+        void ConstructL(); // second-phase constructor
+
+    	/** 
+    	* Adds the calendar metadata to the MdEObject
+    	* @param aMdEObject - the CMdEObject to add the metadata to
+    	*/
+        void AddMetaDataL( CMdEObject& aMdEObject ) const;
+            
+
+    	/** 
+    	* Gets a time property value from MDS
+    	* @param aNameSpace - reference to the namespace
+    	* @param aProp      - reference to the property name
+    	* @param aMdEObject - reference to the CMdEObject to be examined
+        * @return           - value of the property, leaves if it does not exist
+    	*/
+        TTime GetTimeMdEPropL( const TDesC& aNameSpace,
+                               const TDesC& aProp,
+                               CMdEObject&  aMdEObject ) const;
+
+    	/** 
+    	* Gets a text property value from MDS
+    	* @param aNameSpace - reference to the namespace
+    	* @param aProp      - reference to the property name
+    	* @param aMdEObject - reference to the CMdEObject to be examined
+        * @return           - value of the property, NULL if it does not exist
+    	*/
+        HBufC* GetTextMdEPropLC( const TDesC& aNameSpace,
+                                 const TDesC& aProp,
+                                 CMdEObject&  aMdEObject ) const;
+
+        
+        /**
+         * Initialise calendar serve instance
+         *
+         * @since S60 v5.0
+         * @param aRetry - is retry initialisation
+         */
+        void OpenViewL(TBool aRetry = EFalse);
+        
+        /**
+         * Callback for initialisation retry
+         *
+         * @since S60 v5.0
+         */
+        static TInt InitRetryCallback(TAny* aAny);
+        
+		 /**
+         * Starts initialisation retry
+         *
+         * @since S60 v5.0
+         */
+        void StartRetryL();
+		
+    private:
+        
+        CCalInstanceView* iCalInstanceView;    ///< owned
+        CMdESession* iMdeSession;            ///< NOT owned
+        CCalSession* iCalSession; ///< owned
+        TBool iCalInstanceViewCompleted;
+        CPeriodic* iInitTimer;
+        TInt iRetryCount;
+    };
+#endif // __CCALENDARCONTEXTPLUGIN_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/calendarplugin/src/CalendarContextPlugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,561 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+ *
+*/
+
+
+// INCLUDE FILES
+#include <mdeobject.h>
+
+#include <calinstance.h>
+#include <calinstanceview.h>
+#include <calsession.h>
+#include <caldataexchange.h>
+#include <caldataformat.h>
+
+#include <s32mem.h>
+
+#include "CalendarContextPlugin.h"
+#include "harvesterlog.h"
+#include "mdeconstants.h"
+#include "mdenamespacedef.h"
+#include "mdeobjectdef.h"
+#include "harvesterdata.h"
+#include "mdsutils.h"
+
+using namespace MdeConstants;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::NewL
+// -----------------------------------------------------------------------------
+//
+CCalendarContextPlugin* CCalendarContextPlugin::NewL()
+	{
+	WRITELOG( "CCalendarContextPlugin::NewL -- ENTER" );
+
+	CCalendarContextPlugin* self = new(ELeave) CCalendarContextPlugin();
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+
+	WRITELOG( "CCalendarContextPlugin::NewL -- RETURN" );
+
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::CCalendarContextPlugin
+// -----------------------------------------------------------------------------
+//
+CCalendarContextPlugin::CCalendarContextPlugin() :
+    iCalInstanceView( NULL ), iMdeSession( NULL ),
+    iCalSession( NULL ), iCalInstanceViewCompleted( EFalse ), 
+    iRetryCount( 0 )
+	{
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CCalendarContextPlugin::ConstructL() // second-phase constructor
+	{
+	WRITELOG( "CCalendarContextPlugin::ConstructL -- ENTER" );
+
+	OpenViewL();
+	
+	WRITELOG( "CCalendarContextPlugin::ConstructL  -- RETURN" );
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::~CCalendarContextPlugin
+// -----------------------------------------------------------------------------
+//
+CCalendarContextPlugin::~CCalendarContextPlugin() // destruct
+	{
+	WRITELOG( "CCalendarContextPlugin::~CCalendarContextPlugin -- ENTER" );
+	delete iCalInstanceView;
+	delete iCalSession;
+	
+	if( iInitTimer )
+	    {
+	    iInitTimer->Cancel();
+	    delete iInitTimer;
+	    }
+		
+	WRITELOG( "CCalendarContextPlugin::~CCalendarContextPlugin -- RETURN" );
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::InitL
+// -----------------------------------------------------------------------------
+//
+void CCalendarContextPlugin::Init( MContextPluginObserver& aObserver )
+	{
+	WRITELOG( "CCalendarContextPlugin::InitL  -- ENTER" );
+
+	// Notification to context framework
+	aObserver.PluginInitializationStatus( KErrNone );
+
+	WRITELOG( "CCalendarContextPlugin::InitL -- RETURN" );
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::ContextSnapshot
+// -----------------------------------------------------------------------------
+//
+void CCalendarContextPlugin::ContextSnapshot( MContextPluginObserver& aObserver,
+		CHarvesterData& aHD )
+	{
+	WRITELOG( "CCalendarContextPlugin::ContextSnapshotL, 1 obj. --ENTER" );
+
+	CMdEObject& mdeObject = aHD.MdeObject();
+	TRAPD( error, AddMetaDataL( mdeObject ) )	;
+	// Notification to context framework
+	aHD.SetErrorCode( error );
+	aObserver.PluginSnapshotStatus( &aHD );
+
+	WRITELOG( "CCalendarContextPlugin::ContextSnapshotL, 1 obj. --RETURN" );
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::ContextSnapshot
+// -----------------------------------------------------------------------------
+//
+void CCalendarContextPlugin::ContextSnapshot(MContextPluginObserver& aObserver,
+		RPointerArray< CHarvesterData >& aHDArray)
+	{
+#ifdef _DEBUG
+	WRITELOG( "CCalendarContextPlugin::ContextSnapshotL, array -- ENTER" );
+	WRITELOG1("Size of array: %d", aHDArray.Count() );
+#endif
+	
+	TInt err = KErrNone;
+	const TInt count( aHDArray.Count() );
+	for( TInt i = 0; i < count; ++i )
+		{
+		CHarvesterData* hd = aHDArray[i];
+		CMdEObject& mdeObject = hd->MdeObject();
+		TRAP( err,AddMetaDataL( mdeObject ) );
+		hd->SetErrorCode( err );
+		// Notification to context framework
+		aObserver.PluginSnapshotStatus( hd );
+		}
+
+	WRITELOG( "CCalendarContextPlugin::ContextSnapshotL, array -- RETURN" );
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::GetTimeMdEPropL
+// -----------------------------------------------------------------------------
+//
+#ifdef _DEBUG
+TTime CCalendarContextPlugin::GetTimeMdEPropL( const TDesC& aNameSpace,
+    const TDesC& aProp, CMdEObject& aMdEObject) const
+#else
+TTime CCalendarContextPlugin::GetTimeMdEPropL( const TDesC&,
+    const TDesC& aProp, CMdEObject& aMdEObject) const
+#endif
+	{
+	WRITELOG( "CCalendarContextPlugin::GetTimeMdEPropL -- ENTER" );
+	WRITELOG1("aNameSpace: %S", &aNameSpace );
+	WRITELOG1("aProp: %S", &aProp );
+
+	CMdEPropertyDef& timeDef = aMdEObject.Def().GetPropertyDefL( aProp );
+
+	CMdEProperty* timeProp = NULL;
+	aMdEObject.Property( timeDef, timeProp );
+
+	if ( !timeProp )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	WRITELOG( "CCalendarContextPlugin::GetTimeMdEPropL  -- RETURN" );
+
+	return timeProp->TimeValueL();
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::AddMetaDataL
+// -----------------------------------------------------------------------------
+//
+void CCalendarContextPlugin::AddMetaDataL( CMdEObject& aMdEObject ) const
+	{
+	if ( aMdEObject.Id() == KNoId )
+		return;
+
+	WRITELOG( "CCalendarContextPlugin::AddMetaDataL -- ENTER" );
+
+	if ( !iCalInstanceViewCompleted )
+		{
+		// The CalendarInstanceView has not yet reported completion by calling
+		// the callback routine, so no calendar information can be looked up.
+		WRITELOG( "iCalInstanceViewCompleted==EFalse, returning." );
+		WRITELOG( "CCalendarContextPlugin::AddMetaDataL -- RETURN" );
+		return;
+		}
+
+	RPointerArray<CCalInstance> instances;
+	TCleanupItem cleanupItem( MdsUtils::CleanupPtrArray<CCalInstance>, &instances );
+	CleanupStack::PushL( cleanupItem );
+
+	// From the mdsAddTime find the start of the day and the end of the day
+	// in order to set the time range for the search in the calendar database
+	TTime mdsAddTime = GetTimeMdEPropL(
+		KMdEDefaultNameSpace, Object::KCreationDateProperty, aMdEObject );
+
+	TDateTime dateTime = mdsAddTime.DateTime();
+	dateTime.SetHour( 0 );
+	dateTime.SetMinute( 0 );
+	dateTime.SetSecond( 0 );
+	dateTime.SetMicroSecond( 0 );
+	TTime dayBeginTime( dateTime );
+	TCalTime startCalTime;
+	TCalTime stopCalTime;
+	startCalTime.SetTimeLocalL( dayBeginTime );
+	stopCalTime.SetTimeLocalL( dayBeginTime + 
+			TTimeIntervalDays ( 1 ) - TTimeIntervalMicroSeconds( 1 ) );
+
+	// Get a list of the all instances in the calendar database associated
+	// with this day
+	iCalInstanceView->FindInstanceL( instances, CalCommon::EIncludeAll,
+									 CalCommon::TCalTimeRange( startCalTime, stopCalTime) );
+
+	const TInt instanceCount = instances.Count();
+
+	WRITELOG1( "CCalendarContextPlugin::AddMetaDataL -- instanceCount: %d", instanceCount );
+
+	// required object properties
+	WRITELOG( "CCalendarContextPlugin::AddMetaDataL" );
+	User::LeaveIfNull( iMdeSession );
+	CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+	WRITELOG( "CCalendarContextPlugin::AddMetaDataL" );
+
+	CMdERelationDef& containsRelDef = namespaceDef.GetRelationDefL(
+		Relations::KContains );
+	CMdEObjectDef& calendarObjectDef = namespaceDef.GetObjectDefL(
+		Calendar::KCalendarObject );
+
+	CMdEPropertyDef& creationDef = calendarObjectDef.GetPropertyDefL(
+		Object::KCreationDateProperty );
+	CMdEPropertyDef& modifiedDef = calendarObjectDef.GetPropertyDefL(
+		Object::KLastModifiedDateProperty );
+	CMdEPropertyDef& sizeDef = calendarObjectDef.GetPropertyDefL(
+		Object::KSizeProperty );
+	CMdEPropertyDef& itemTypeDef = calendarObjectDef.GetPropertyDefL(
+		Object::KItemTypeProperty );
+	CMdEPropertyDef& titleDef = calendarObjectDef.GetPropertyDefL(
+			Object::KTitleProperty );
+	CMdEPropertyDef& offSetDef = calendarObjectDef.GetPropertyDefL( 
+			Object::KTimeOffsetProperty );
+
+	// calendar properties
+	CMdEPropertyDef& startDef    = calendarObjectDef.GetPropertyDefL(
+		Calendar::KStartTimeProperty );
+	CMdEPropertyDef& endDef      = calendarObjectDef.GetPropertyDefL(
+		Calendar::KEndTimeProperty );
+	CMdEPropertyDef& caltypeDef  = calendarObjectDef.GetPropertyDefL(
+		Calendar::KCalendarTypeProperty );
+	CMdEPropertyDef& locationDef = calendarObjectDef.GetPropertyDefL(
+		Calendar::KLocationProperty );
+	CMdEPropertyDef& localUidDef = calendarObjectDef.GetPropertyDefL(
+			Calendar::KLocalUidProperty );
+
+	TTime curtime( 0 );
+	curtime.UniversalTime();
+
+	const TTimeIntervalSeconds timeOffsetSeconds = User::UTCOffset();
+	TTime localTime = curtime + timeOffsetSeconds;
+
+	TInt timeOffset = timeOffsetSeconds.Int() / 60;
+
+	for ( TInt i = 0; i < instanceCount; ++i )
+		{
+		WRITELOG1( "CCalendarContextPlugin::AddMetaDataL - loop index: %d", i );
+
+		CCalInstance* instance = instances[i];
+		CCalEntry& entry = instance->Entry();
+
+		const TDesC& location = entry.LocationL();
+		const TDesC& title = entry.SummaryL();
+		TTime beginTime = entry.StartTimeL().TimeLocalL();
+		TTime endTime = entry.EndTimeL().TimeLocalL();
+		TUint32 localUid = entry.LocalUidL();
+
+		CCalEntry::TType type = entry.EntryTypeL();
+
+		// Anniversaries and such are whole day events
+		if ( type == CCalEntry::EAnniv || type == CCalEntry::ETodo )
+			{
+			// Set end time to the end of the day
+			endTime += TTimeIntervalDays ( 1 );
+			endTime -= TTimeIntervalMicroSeconds( 1 );
+			}
+		// Other type entry must be currently active
+		else if ( ( mdsAddTime < beginTime ) || ( endTime < mdsAddTime ) )
+			{
+			WRITELOG( "CCalendarContextPlugin::AddMetaDataL - Calendar event not active - SKIP" );
+			continue;
+			}
+
+		WRITELOG( "CCalendarContextPlugin::AddMetaDataL - Create calendar item" );
+		CMdEObject* calendarObject=  NULL;
+		calendarObject = iMdeSession->NewObjectLC(
+			calendarObjectDef, Object::KAutomaticUri );
+		calendarObject->AddTimePropertyL( creationDef, localTime );
+		calendarObject->AddTimePropertyL( modifiedDef, curtime );
+		calendarObject->AddUint32PropertyL( sizeDef, 0 ); // always zero size for calendar objects
+		calendarObject->AddTextPropertyL( itemTypeDef, Calendar::KCalendarItemType );
+		calendarObject->AddInt16PropertyL( offSetDef, timeOffset );
+
+		//Calendar properties
+		calendarObject->AddTimePropertyL( startDef, beginTime );
+		calendarObject->AddTimePropertyL( endDef, endTime );
+		calendarObject->AddUint8PropertyL( caltypeDef, type );
+		calendarObject->AddUint32PropertyL( localUidDef, localUid );
+		if ( location.Length() > 0 )
+			{
+			calendarObject->AddTextPropertyL( locationDef, location );
+			}
+		if ( title.Length() > 0 )
+			{
+			calendarObject->AddTextPropertyL( titleDef, title );
+			}
+
+		WRITELOG( "CCalendarContextPlugin::AddMetaDataL - Add calendar item to MDE" );
+		TRAPD( addError, iMdeSession->AddObjectL( *calendarObject ) );
+		if ( addError != KErrNone )
+			{
+			WRITELOG1( "CCalendarContextPlugin::AddMetaDataL - Add calendar item to MDE error: %d", addError );
+			CleanupStack::PopAndDestroy( calendarObject );
+			continue;
+			}
+
+		const TItemId calid = calendarObject->Id();
+		const TItemId objid = aMdEObject.Id();
+
+		CMdERelation* relationObject = iMdeSession->NewRelationLC(
+			containsRelDef, objid, calid, 0 );
+		if ( !relationObject )
+			{
+			WRITELOG( "CCalendarContextPlugin::AddMetaDataL - Couldn't create relation object!" );
+			User::Leave( KErrBadHandle );
+			}
+
+		WRITELOG( "CCalendarContextPlugin::AddMetaDataL - Add calendar relation to MDE" );
+		TRAP( addError, iMdeSession->AddRelationL( *relationObject ) );
+		if ( addError != KErrNone)
+			{
+			WRITELOG1( "CCalendarContextPlugin::AddMetaDataL - Add calendar relation to MDE error: %d", addError );
+			}
+
+		CleanupStack::PopAndDestroy( relationObject );
+		CleanupStack::PopAndDestroy( calendarObject );
+		}
+
+	CleanupStack::PopAndDestroy( &instances );
+
+	WRITELOG( "CCalendarContextPlugin::AddMetaDataL -- RETURN" );
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::HandleSessionOpened
+// -----------------------------------------------------------------------------
+//
+void CCalendarContextPlugin::HandleSessionOpened( CMdESession& /*aSession*/,
+		TInt /*aError*/ )
+	{
+	WRITELOG( "CCalendarContextPlugin::HandleSessionOpened -- ENTER" );
+	WRITELOG( "CCalendarContextPlugin::HandleSessionOpened -- RETURN" );
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::HandleSessionError
+// -----------------------------------------------------------------------------
+//
+void CCalendarContextPlugin::HandleSessionError( CMdESession& /*aSession*/,
+	TInt /*aError*/ )
+	{
+	WRITELOG( "CCalendarContextPlugin::HandleSessionError -- ENTER" );
+	WRITELOG( "CCalendarContextPlugin::HandleSessionError -- RETURN" );
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::Progress
+// -----------------------------------------------------------------------------
+//
+void CCalendarContextPlugin::Progress( TInt /*aPercentageCompleted*/ )
+	{
+	WRITELOG( "CCalendarContextPlugin::Progress -- ENTER" );
+	WRITELOG( "CCalendarContextPlugin::Progress -- RETURN" );
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::Completed
+// -----------------------------------------------------------------------------
+//
+void CCalendarContextPlugin::Completed( TInt aError )
+	{
+	WRITELOG( "CCalendarContextPlugin::Completed -- ENTER" );
+
+	if ( aError != KErrNone )
+		{
+		iCalInstanceViewCompleted = EFalse;
+		WRITELOG1( "aError: %d", aError );
+		TRAP_IGNORE( StartRetryL() );
+		}
+	else
+		{
+		iCalInstanceViewCompleted = ETrue;
+		}
+
+	WRITELOG( "CCalendarContextPlugin::Completed -- RETURN" );
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::NotifyProgress
+// -----------------------------------------------------------------------------
+//
+TBool CCalendarContextPlugin::NotifyProgress()
+	{
+	WRITELOG( "CCalendarContextPlugin::NotifyProgress -- ENTER" );
+	WRITELOG( "CCalendarContextPlugin::NotifyProgress -- RETURN" );
+
+	return EFalse;
+	}
+
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::SetMdeSession
+// -----------------------------------------------------------------------------
+//
+void CCalendarContextPlugin::SetMdeSession( CMdESession& aSession )
+	{
+	iMdeSession = &aSession;
+	}
+
+// -----------------------------------------------------------------------------
+// CCalendarContextPlugin::OpenView
+// -----------------------------------------------------------------------------
+//
+void CCalendarContextPlugin::OpenViewL(TBool aRetry)
+    {
+    WRITELOG( "CCalendarContextPlugin::OpenViewL() ENTER" );
+    TInt err(KErrNone);
+    
+    if(aRetry)
+        {
+        WRITELOG( "CCalendarContextPlugin::OpenViewL() retry" );
+        iInitTimer->Cancel();
+        delete iInitTimer;
+        iInitTimer = NULL;
+        }
+    
+    if(!iCalSession)
+        {
+        WRITELOG( "CCalendarContextPlugin::OpenViewL() new calsession");
+        TRAP(err, iCalSession = CCalSession::NewL());
+        
+        if( err != KErrNone)
+            {
+            WRITELOG1( "CCalendarContextPlugin::OpenViewL() CCalSession::NewL() err = %d", err );
+            iCalSession = NULL;
+            StartRetryL();
+            return;
+            }
+        }
+
+    WRITELOG( "CCalendarContextPlugin::OpenViewL() open calsession");
+    TRAP(err, iCalSession->OpenL( KNullDesC ));
+
+    if(err != KErrNone )
+        {
+        WRITELOG1( "CCalendarContextPlugin::OpenViewL() iCalSession->OpenL() err = %d", err );
+        StartRetryL();
+        return;
+        }
+
+    WRITELOG( "CCalendarContextPlugin::OpenViewL() open view");
+    TRAP( err, iCalInstanceView = CCalInstanceView::NewL( *iCalSession, *this ) );
+        
+    if(err != KErrNone )
+        {
+        WRITELOG1( "CCalendarContextPlugin::OpenViewL() CCalInstanceView::NewL() err = %d", err );
+        iCalInstanceView = NULL;
+        StartRetryL();
+        return;
+        }
+
+    WRITELOG( "CCalendarContextPlugin::OpenViewL() RETURN" );
+    }
+
+
+void CCalendarContextPlugin::StartRetryL()
+    {
+    WRITELOG( "CCalendarContextPlugin::StartRetryL() ENTER" );
+    TInt err(KErrNone);
+    
+    if(iRetryCount++ > KMaxRetryCount)
+        {
+        delete iCalInstanceView;
+        iCalInstanceView = NULL;
+        delete iCalSession;
+        iCalSession = NULL;
+        
+        if( iInitTimer )
+            {
+            iInitTimer->Cancel();
+            delete iInitTimer;
+            iInitTimer = NULL;
+            }
+        
+		return; 
+        }
+    
+    
+    if(!iInitTimer)
+        {
+        TRAP(err, iInitTimer = CPeriodic::NewL(CActive::EPriorityStandard) );
+        }
+                
+    if( err != KErrNone )
+        {
+        WRITELOG1( "CCalendarContextPlugin::OpenViewL() iInitTimer->Start failed %d", err );
+        User::Leave( err );
+        }
+        
+    WRITELOG( "CCalendarContextPlugin::OpenViewL() iInitTimer->Start" );
+    iInitTimer->Start( KInitRetryTimeout, KInitRetryTimeout, TCallBack(InitRetryCallback, this));
+    WRITELOG( "CCalendarContextPlugin::StartRetryL() RETURN" );
+    }
+	
+// ---------------------------------------------------------------------------
+// CCalendarContextPlugin::InitRetryCallback()
+// ---------------------------------------------------------------------------
+//
+TInt CCalendarContextPlugin::InitRetryCallback(TAny* aAny)
+    {
+    WRITELOG( "CCalendarContextPlugin::InitRetryCallback() ENTER");
+    CCalendarContextPlugin* self = static_cast<CCalendarContextPlugin*>( aAny );
+
+    TRAP_IGNORE( self->OpenViewL(ETrue) );
+    
+    WRITELOG( "CCalendarContextPlugin::InitRetryCallback() RETURN");
+    return KErrNone;
+    }
+	
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/calendarplugin/src/proxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation proxy
+*
+*/
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include "CalendarContextPlugin.h"
+
+// Map the interface UIDs to implementation factory functions
+const TImplementationProxy KImplementationTable[] = 
+    {
+    { { 0x102823CB }, (TProxyNewLPtr)CCalendarContextPlugin::NewL }
+    };
+
+// Exported proxy for instantiation method resolution
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt&
+    aTableCount )
+    {
+    aTableCount = sizeof( KImplementationTable ) / sizeof( TImplementationProxy );
+    return KImplementationTable;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/contextplugininterface/bwincw/contextplugininterfacewinscw.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	??1CContextPlugin@@UAE@XZ @ 1 NONAME ; CContextPlugin::~CContextPlugin(void)
+	?ListImplementationsL@CContextPlugin@@SAXAAV?$RPointerArray@VCImplementationInformation@@@@@Z @ 2 NONAME ; void CContextPlugin::ListImplementationsL(class RPointerArray<class CImplementationInformation> &)
+	?NewL@CContextPlugin@@SAPAV1@ABVTUid@@@Z @ 3 NONAME ; class CContextPlugin * CContextPlugin::NewL(class TUid const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/contextplugininterface/eabi/contextplugininterfacearm.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,9 @@
+EXPORTS
+	_ZN14CContextPlugin20ListImplementationsLER13RPointerArrayI26CImplementationInformationE @ 1 NONAME
+	_ZN14CContextPlugin4NewLERK4TUid @ 2 NONAME
+	_ZN14CContextPluginD0Ev @ 3 NONAME
+	_ZN14CContextPluginD1Ev @ 4 NONAME
+	_ZN14CContextPluginD2Ev @ 5 NONAME
+	_ZTI14CContextPlugin @ 6 NONAME ; #<TI>#
+	_ZTV14CContextPlugin @ 7 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/contextplugininterface/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+contextplugininterface.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/contextplugininterface/group/contextplugininterface.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        contextplugininterface.dll
+TARGETTYPE    dll
+UID           0x1000008D 0x200009F7
+
+CAPABILITY    CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+SYSTEMINCLUDE /epoc32/include/ecom
+
+SOURCEPATH    ../src
+SOURCE        contextplugin.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       ecom.lib
+
+#if defined(WINS)
+    deffile ../bwincw/contextplugininterfacewinscw.def
+#elif defined(ARMCC)
+    deffile ../eabi/contextplugininterfacearm.def
+#endif
+nostrictdef
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/contextplugininterface/src/contextplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,61 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#include <ecom.h>
+#include "contextplugin.h"
+	
+// ---------------------------------------------------------------------------
+// 
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CContextPlugin* CContextPlugin::NewL( const TUid& aUid )
+	{
+	TAny* contextPlugin = REComSession::CreateImplementationL(
+		aUid, _FOFF( CContextPlugin, iDtor_ID_Key ) );
+	return ( reinterpret_cast<CContextPlugin*>(contextPlugin) );
+	}
+
+// ---------------------------------------------------------------------------
+// 
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CContextPlugin::ListImplementationsL( RImplInfoPtrArray& aImplInfoArray )
+	{
+	REComSession::ListImplementationsL( KCContextPluginInterfaceUid, aImplInfoArray );
+	}
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CContextPlugin::~CContextPlugin()
+	{
+	// Destroy any instance variables and then
+	// inform the framework that this specific
+	// instance of the interface has been destroyed.
+	REComSession::DestroyedImplementation( iDtor_ID_Key );
+	}
+
+// ---------------------------------------------------------------------------
+// Main function of the DLL.
+// ---------------------------------------------------------------------------
+//
+GLDEF_C TInt E32Dll()
+	{
+	return( KErrNone );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+#include "../contextplugininterface/group/bld.inf"
+#include "../calendarplugin/group/bld.inf"
+#include "../locationplugin/group/bld.inf"
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/locationplugin/data/200071cf.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2000-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource file for Location Context Plug-in*
+*/
+
+
+#include "registryinfov2.rh"
+
+// Declares info for one plugin implementation
+RESOURCE REGISTRY_INFO theInfo
+	{
+	// resource_format_version must always be set as follows
+	resource_format_version = RESOURCE_FORMAT_VERSION_2;
+	
+	// UID for the DLL
+	dll_uid = 0x200071cf;
+	// Declare array of interface info
+	interfaces = 
+		{
+		INTERFACE_INFO
+			{
+			// UID of interface that is implemented
+			interface_uid = 0x200009F7;
+			implementations = 
+				{
+				// Info for CLocationContextPlugin
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x200071D0;
+					version_no = 1;
+					display_name = "Location Context Plugin";
+					default_data = "Location";
+					opaque_data = "";
+					rom_only = 0;
+					}
+				};
+			}
+		};
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/locationplugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+locationcontextplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/locationplugin/group/locationcontextplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,61 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        locationcontextplugin.dll
+TARGETTYPE    PLUGIN
+UID           0x10009D8D 0x200071CF
+
+CAPABILITY 	  CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+SYSTEMINCLUDE /epoc32/include/ecom
+
+USERINCLUDE   ../../../../inc
+USERINCLUDE   ../inc
+
+SOURCEPATH    ../src
+SOURCE        locationcontextplugin.cpp
+SOURCE        locationpluginproxy.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       ecom.lib
+LIBRARY       inetprotutil.lib
+LIBRARY       contextplugininterface.lib
+LIBRARY       mdeclient.lib
+LIBRARY       lbs.lib
+
+LIBRARY       locationmanager.lib
+LIBRARY       locationtrail.lib
+LIBRARY	  harvesterdata.lib
+LIBRARY	  etel3rdparty.lib
+
+SOURCEPATH    ../data
+start RESOURCE 200071cf.rss
+target locationcontextplugin.rsc
+end
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/locationplugin/inc/locationcontextplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,135 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A Context Engine Plug-in to get location context information.
+*
+*/
+
+
+#ifndef CLOCATIONCONTEXTPLUGIN_H
+#define CLOCATIONCONTEXTPLUGIN_H
+
+#include <e32def.h>
+
+#include "contextplugin.h"
+#include "rlocationtrail.h"
+#include "rlocationobjectmanipulator.h"
+#include "locationdatatype.h"
+
+// forward declarations
+class TLocality;
+class CMdESession;
+class CHarvesterData;
+class CMdEProperty;
+
+/**
+* This class implements the context plugin interface for GPS
+* location information.
+*
+*/
+class CLocationContextPlugin : public CContextPlugin
+    {
+public:
+
+    /**
+     * Creates and constructs a new instance of CLocationContextPlugin.
+     *
+     * @return A pointer to the created instance.
+     */
+    static CLocationContextPlugin* NewL();
+
+    /**
+     * Destructor.
+     */
+    virtual ~CLocationContextPlugin();
+
+// from base class CContextPlugin
+
+    /**
+     * From CContextPlugin.
+     * Initialization of Location Context Plugin.
+     *
+     * @param An observer to notify the completion of initialization to.
+     */
+    void Init( MContextPluginObserver& aObserver );
+
+    /**
+     * Set a pointer to MdESession.
+     * Session is used to store harvested context data.
+     *
+     * @param aSession Session pointer to set.
+     */
+    void SetMdeSession( CMdESession& aSession );
+
+    /**
+     * From CContextPlugin.
+     * This method takes a location context snapshot for one metadata object
+     * and writes the information to the object received as parameter.
+     * The observer will be informed about the status of the operation.
+     *
+     * @param aObserver  An interface class to inform about finishing context snapshot.
+     * @param aMetadataObject An object to take the snapshot for.
+     */
+    void ContextSnapshot( MContextPluginObserver& aObserver, CHarvesterData& aHD );
+
+    /**
+     * From CContextPlugin.
+     * This method takes a location context snapshot for several metadata objects
+     * and writes the information to the all the objects received as parameter.
+     * The observer will be informed about the status of the operation.
+     *
+     * @param aObserver  An interface class to inform about finishing context snapshot.
+     * @param aMetadataObjectArray Array of objects to take the snapshot for.
+     */
+    void ContextSnapshot( MContextPluginObserver& aObserver,
+                          RPointerArray<CHarvesterData>& aHDArray );
+
+private:
+
+    /**
+     * Constructor, called by NewL() only.
+     */
+    CLocationContextPlugin();
+
+    /**
+     * Second phase constructor called by NewL.
+     */
+    void ConstructL();
+
+    /**
+     * A simple method to get creation date/time from a mde object.
+     *
+     * @param aObject        A metadata object to get the date/time from.
+     * @param aTimeProperty  A property to store the time information to.
+     */    
+    void GetMdeObjectCreationTimeL( CMdEObject& aObject, CMdEProperty*& aProperty );
+
+private: // data
+
+    /** @var Observer to notify about finishing status of the context snapshot. */
+    MContextPluginObserver* iObserver;
+    
+    /** @var Service to get GPS location information. */
+    RLocationTrail iLocationTrail;
+    
+    /** @var Pointer to Mde session which is used to store context data. */
+    CMdESession* iMdeSession;
+    
+    /** @var Location trail status flag to signal if Connect() was successful. */
+    TBool iLocationTrailConnected;
+    
+    /** @var Service to modify location context objects. */
+    RLocationObjectManipulator iManipulator;
+    };
+
+#endif // CLOCATIONCONTEXTPLUGIN_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/locationplugin/src/locationcontextplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,265 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A Context Engine Plug-in to get location context information.
+*
+*/
+
+
+#include <e32std.h>
+#include <uri16.h>
+#include <e32math.h>
+#include <LbsPosition.h> 
+#include <etel3rdparty.h>
+
+#include "locationcontextplugin.h"
+#include "mdenamespacedef.h"
+#include "mdeobject.h"
+#include "mdeharvestersession.h"
+#include "mdeproperty.h"
+#include "harvesterlog.h"
+#include "mdsutils.h"
+#include "mdeconstants.h"
+#include "mdeobjectdef.h"
+#include "harvesterdata.h"
+
+using namespace MdeConstants;
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// Default constructor for first phase construction.
+// Don't export these - used only by functions in this DLL, eg our NewL().
+// ---------------------------------------------------------------------------
+//
+CLocationContextPlugin::CLocationContextPlugin() :
+    iObserver( NULL ), iMdeSession( NULL ), iLocationTrailConnected( EFalse )
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// Second phase construction
+// ---------------------------------------------------------------------------
+//
+void CLocationContextPlugin::ConstructL() // second-phase constructor
+    {
+    // No implementation required
+    }
+
+
+// ---------------------------------------------------------------------------
+// The usual NewL()
+// ---------------------------------------------------------------------------
+//
+CLocationContextPlugin* CLocationContextPlugin::NewL()
+    {
+    CLocationContextPlugin* self = new (ELeave) CLocationContextPlugin();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+    
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CLocationContextPlugin::~CLocationContextPlugin()
+    {
+    iLocationTrail.Close();
+    iManipulator.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// From CContextPlugin.
+// Initialization of Location Context Plugin.
+// ---------------------------------------------------------------------------
+//
+void CLocationContextPlugin::Init( MContextPluginObserver& aObserver )
+    {
+    WRITELOG("CLocationContextPlugin::Init()");
+    
+    TInt err = iLocationTrail.Connect();
+    if ( err == KErrNone )
+    	{
+    	err = iManipulator.Connect();
+    	if (err == KErrNone)
+    		{
+    		iLocationTrailConnected = ETrue;
+    		}
+    	}
+    else
+    	{
+    	iLocationTrailConnected = EFalse;
+    	}
+    aObserver.PluginInitializationStatus( KErrNone ); // notify the context framework
+    }
+
+// ---------------------------------------------------------------------------
+// Set a pointer to MdESession.
+// Session is used to store harvested context data.
+// ---------------------------------------------------------------------------
+//
+void CLocationContextPlugin::SetMdeSession( CMdESession& aSession )
+    {
+    iMdeSession = &aSession;
+    }
+
+// ---------------------------------------------------------------------------
+// From CContextPlugin.
+// This method takes a location context snapshot for one metadata object
+// and writes the information to the object received as parameter.
+// The observer will be informed about the status of the operation.
+// ---------------------------------------------------------------------------
+//
+void CLocationContextPlugin::ContextSnapshot( MContextPluginObserver& aObserver,
+	CHarvesterData& aHD )
+    {
+    WRITELOG( "CLocationContextPlugin::ContextSnapshot()" );
+    
+    if( !aHD.AddLocation() )
+    	{
+        WRITELOG( "CLocationContextPlugin::ContextSnapshot() - aHd.AddLocation returned false" );
+    	aHD.SetErrorCode( KErrNone );
+        aObserver.PluginSnapshotStatus( &aHD );
+    	return;
+    	}
+    
+    if ( !iLocationTrailConnected ) // no trail, no snapshot
+    	{
+    	aHD.SetErrorCode( KErrDisconnected );
+        aObserver.PluginSnapshotStatus( &aHD );
+    	return;
+    	}
+    
+    TInt ret = KErrNone;
+    
+    ret = iManipulator.LocationSnapshot( aHD.MdeObject().Id() );
+    
+    aHD.SetErrorCode( ret );
+    aObserver.PluginSnapshotStatus( &aHD );
+    }
+
+// ---------------------------------------------------------------------------
+// From CContextPlugin.
+// This method takes a location context snapshot for several metadata objects
+// and writes the information to the all the objects received as parameter.
+// The observer will be informed about the status of the operation.
+// ---------------------------------------------------------------------------
+//
+void CLocationContextPlugin::ContextSnapshot( MContextPluginObserver& aObserver,
+    RPointerArray<CHarvesterData>& aHDArray )
+    {
+	const TInt count( aHDArray.Count() );
+    WRITELOG( "CLocationContextPlugin::ContextSnapshot()" );
+
+    if ( !iLocationTrailConnected ) // no trail, no snapshot
+    	{
+    	for(TInt i = 0; i < count; i++)
+    		{
+    		CHarvesterData* hd = aHDArray[i];
+    		hd->SetErrorCode( KErrDisconnected );
+    		aObserver.PluginSnapshotStatus( hd );
+    		}
+    	return;
+    	}
+
+    TLocationData data;
+    RLocationTrail::TTrailState state;
+    CMdEProperty* timeProp = NULL;
+    TInt ret = KErrNone;
+    iLocationTrail.GetLocationTrailState( state );
+
+    if ( state != RLocationTrail::ETrailStopped && state != RLocationTrail::ETrailStopping )
+    	{
+    	for (TInt i = 0; i < aHDArray.Count(); ++i)
+    		{
+    		CMdEObject& mdeObject = ((CHarvesterData*)aHDArray[i])->MdeObject();
+    		TRAP( ret, GetMdeObjectCreationTimeL( mdeObject, timeProp ) );
+    		if ( ret != KErrNone )
+    			{
+    			continue;
+    			}
+#ifdef _DEBUG
+    		TRAP_IGNORE(
+    		WRITELOG1( "CLocationContextPlugin::ContextSnapshot() - timeProp: %Ld", 
+    				timeProp->TimeValueL().Int64() ) );
+    		WRITELOG1( "CLocationContextPlugin::ContextSnapshot() - Location trail state: %d", 
+    				state );
+#endif
+    				
+    		TRAP_IGNORE(ret = iLocationTrail.RetrieveLocation( timeProp->TimeValueL(), data, state ));
+
+#ifdef _DEBUG
+    		WRITELOG1( "CLocationContextPlugin::ContextSnapshot() - Retrieve location returned: %d", ret );
+    		WRITELOG1( "CLocationContextPlugin::ContextSnapshot() - Latitude was: %f", data.iPosition.Latitude() );
+    		WRITELOG1( "CLocationContextPlugin::ContextSnapshot() - Longitude was: %f", data.iPosition.Longitude() );
+    		WRITELOG1( "CLocationContextPlugin::ContextSnapshot() - Altitude was: %f", data.iPosition.Altitude() );
+#endif
+        
+    		if (ret == KErrNone)
+    			{
+    			if ( !Math::IsNaN(data.iPosition.Latitude() ) ||
+   	        		 !Math::IsNaN(data.iPosition.Longitude() ) || 
+   	        		 !Math::IsNaN(data.iPosition.Altitude() ) ||
+   	        		 data.iNetworkInfo.iCellId > 0 || data.iNetworkInfo.iLocationAreaCode > 0 ||
+   	        		 data.iNetworkInfo.iCountryCode.Length() > 0 ||
+   	        		 data.iCountry.Length() > 0 || data.iNetworkInfo.iNetworkId.Length() > 0 )
+   	        		{
+#ifdef _DEBUG
+	    			WRITELOG1( "CLocationContextPlugin::ContextSnapshot() Create location object for id: %d", mdeObject.Id());
+#endif
+	    			ret = iManipulator.CreateLocationObject(data, mdeObject.Id());
+	    			WRITELOG1( "CLocationContextPlugin::ContextSnapshot() Create location object returned: %d", ret);
+   	        		}
+    			}
+	        else
+	        	{
+	        	ret = KErrNone;
+	        	}
+
+    		}
+        }
+
+    // Notify to context framework
+    for(TInt i = 0; i < count; i++)
+        {
+        CHarvesterData* hd = aHDArray[i];
+        hd->SetErrorCode( KErrNone );
+        aObserver.PluginSnapshotStatus( hd );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Get mde object creation date/time.
+// ---------------------------------------------------------------------------
+//
+void CLocationContextPlugin::GetMdeObjectCreationTimeL( CMdEObject& aObject, 
+	CMdEProperty*& aProperty )
+    {
+    CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+
+    CMdEObjectDef& objectDef = namespaceDef.GetObjectDefL( Object::KBaseObject );
+    CMdEPropertyDef& creationDef = objectDef.GetPropertyDefL( Object::KLastModifiedDateProperty );
+
+    CMdEProperty* property = NULL;
+    aObject.Property( creationDef, property, 0 );
+    if ( !property )
+        {
+        User::Leave( KErrNotFound );
+        }
+    aProperty = property;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/plugins/locationplugin/src/locationpluginproxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A Context Engine Plug-in to get location context information.
+*
+*/
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include "locationcontextplugin.h"
+
+// Map the interface UIDs to implementation factory functions
+const TImplementationProxy KImplementationTable[] = 
+    {
+        {{0x200071D0},	(TProxyNewLPtr)CLocationContextPlugin::NewL}
+    };
+
+// Exported proxy for instantiation method resolution
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    aTableCount = sizeof(KImplementationTable) / sizeof(TImplementationProxy);
+    return KImplementationTable;
+    }
Binary file contextengine/sis/contextengine_stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/sis/depends.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ad:metadata xmlns="http://nokia.com/arrow/repository/ia_component"
+  xmlns:ad="http://nokia.com/arrow/application_metadata">
+  <appResources>
+     <appResource>
+        <language>1</language>
+        <iacName>Context Engine</iacName>
+        <iacDescription>Upgrade package for Context Engine</iacDescription>
+     </appResource>
+  </appResources>
+  <swPlatformDep>
+     <platform>S60</platform>
+     <versionFrom>
+        <major>5</major>
+        <minor>0</minor>
+        <date>
+           <year>2009</year>
+           <week>16</week>
+        </date>
+     </versionFrom>
+  </swPlatformDep>
+  <interDeps>
+  </interDeps>
+</ad:metadata>
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/sis/package.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,36 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Context Engine Patch"},(0x200009F6), 2, 0, 0, TYPE=SA, RU
+
+; Localised vendor name
+%{"Nokia"}
+
+; Unique vendor name
+:"Nokia"
+
+;Files
+"\EPOC32\RELEASE\ARMV5\UREL\contextengine.dll" -"c:\sys\bin\contextengine.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\contextplugininterface.dll" -"c:\sys\bin\contextplugininterface.dll"
+
+"\EPOC32\RELEASE\ARMV5\UREL\calendarcontextplugin.dll" -"c:\sys\bin\calendarcontextplugin.dll"
+"\epoc32\data\z\resource\plugins\calendarcontextplugin.rsc" -"c:\resource\plugins\calendarcontextplugin.rsc"
+
+"\EPOC32\RELEASE\ARMV5\UREL\locationcontextplugin.dll" -"c:\sys\bin\locationcontextplugin.dll"
+"\epoc32\data\z\resource\plugins\locationcontextplugin.rsc" -"c:\resource\plugins\locationcontextplugin.rsc"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/sis/stub.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,30 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;Header
+# {"Context Engine"}, (0x200009F6), 1, 0, 0, TYPE=SA
+
+;Localised Vendor name
+%{"Nokia"}
+
+;Unique Vendor name
+:"Nokia"
+
+;Files
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/src/contextengine.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,291 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An engine to collect context related metadata.
+*
+*/
+
+
+// this class contains use of memory allocation and release not
+// conforming to RAII principles
+
+#include <e32uid.h>
+#include <ecom.h>
+#include <e32svr.h>
+
+#include "contextengine.h"
+#include "contextengineao.h"
+#include "contextsnapshotitem.h"
+#include "mdsutils.h"
+#include "harvesterlog.h"
+#include "harvesterdata.h"
+
+/// Key for thread-local storage used by this singleton.
+const TInt KContextEngineTLSKey = 0x200009f6;
+
+// construct/destruct
+
+// ---------------------------------------------------------------------------
+// 1st phase C++ construction.
+// Don't export these, because used only by our NewLC() and the like.
+// ---------------------------------------------------------------------------
+//
+CContextEngine::CContextEngine( ) :
+    iContextEngineAO( NULL ), iArrayCount( 0 ), iProcessedArrayCount( 0 )
+    {
+    WRITELOG( "CContextEngine::CContextEngine" ); // DEBUG INFO
+    }
+
+// ---------------------------------------------------------------------------
+// 2nd phase construction
+// ---------------------------------------------------------------------------
+//
+void CContextEngine::ConstructL( MContextInitializationObserver* aObserver )
+    {
+    WRITELOG( "CContextEngine::ConstructL" ); // DEBUG INFO
+    iContextEngineAO = CContextEngineAO::NewL( aObserver, this );
+    }
+
+// ---------------------------------------------------------------------------
+// Get a reference to this singleton. A new object is created if needed.
+// If an observer object to notify is given, context plugins are initialized
+// asyncronously and observer is notified when ready.
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CContextEngine* CContextEngine::GetInstanceL(
+	MContextInitializationObserver* aObserver )
+    {
+    WRITELOG( "CContextEngine::GetInstanceL" ); // DEBUG INFO
+    CContextEngineStaticData* data = static_cast<CContextEngineStaticData*>(
+        UserSvr::DllTls(KContextEngineTLSKey) );
+    CContextEngine* instance = NULL;
+    if ( !data )
+        {
+        instance = new (ELeave) CContextEngine();
+        CleanupStack::PushL( instance );
+        instance->ConstructL( aObserver );
+
+        UserSvr::DllSetTls( KContextEngineTLSKey,
+        	new (ELeave) CContextEngineStaticData(instance) );
+
+        CleanupStack::Pop( instance );
+        }
+    else
+        {
+        instance = data->iContextEngine;
+        data->iRefCount++;
+        if ( aObserver )
+            {
+            aObserver->ContextInitializationStatus( KErrNone );
+            }
+        }
+
+    return instance;
+    }
+
+// ---------------------------------------------------------------------------
+// Release a reference to this singleton.
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CContextEngine::ReleaseInstance()
+    {
+    WRITELOG( "CContextEngine::ReleaseInstance" ); // DEBUG INFO
+    CContextEngineStaticData* data =
+        static_cast<CContextEngineStaticData*>( UserSvr::DllTls(KContextEngineTLSKey) );
+    if ( data )
+        {
+        data->iRefCount--;
+        if ( data->iRefCount <= 0 )
+            {
+            // destroy the singleton and free TLS
+            delete data;
+            UserSvr::DllFreeTls( KContextEngineTLSKey );
+            }
+        }
+    }
+
+/* ---------------------------------------------------------------------------
+ * Ignores the reference count and destroys this singleton.            .   .
+ * Should be used only if client code is not using ReleaseInstance()  /|\ /|\
+ * to release their handles to this singleton.                         |   |
+ *                                                                     |   |
+ *                                                        			  -------
+ *                                                                	  -------
+ * ---------------------------------------------------------------------------
+*/
+EXPORT_C void CContextEngine::Destroy()
+    {
+    WRITELOG( "CContextEngine::Destroy" ); // DEBUG INFO
+    CContextEngineStaticData* data =
+        static_cast<CContextEngineStaticData*>( UserSvr::DllTls(KContextEngineTLSKey) );
+    if ( data )
+        {
+        // destroy the singleton and free TLS
+        delete data;
+        UserSvr::DllFreeTls( KContextEngineTLSKey );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor.
+// ---------------------------------------------------------------------------
+//
+CContextEngine::~CContextEngine()
+    {
+    WRITELOG( "CContextEngine::~CContextEngine" ); // DEBUG INFO
+    delete iContextEngineAO;
+
+    MdsUtils::CleanupPtrArray<CContextSnapshotItem>( &iSnapshotQueue );
+    REComSession::FinalClose(); // we are done
+    }
+
+// ---------------------------------------------------------------------------
+// Set MdeSession to context engine and it's plugins.
+// Session must be set in order to successfully harvest context data.
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CContextEngine::SetMdeSession( CMdESession* aSession )
+    {
+    iContextEngineAO->SetMdeSession( aSession );
+    }
+
+// ---------------------------------------------------------------------------
+// Takes a context snapshot including all initialized plugins.
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CContextEngine::ContextSnapshot( MContextSnapshotObserver& aObserver,
+    CHarvesterData& aHD )
+    {
+    WRITELOG( "CContextEngine::ContextSnapshot (single)" ); // DEBUG INFO
+    
+    // if any plug-in hasn't been found...
+    if ( iContextEngineAO->PluginCount() <= 0 )
+        {
+        aHD.SetErrorCode( KErrNone );
+        aObserver.ContextSnapshotStatus( &aHD );
+        return;
+        }
+
+    // queue item for taking a snapshot
+    CContextSnapshotItem* item = NULL;
+    TRAPD( err, item = CContextSnapshotItem::NewL( &aObserver, &aHD ) );
+    iArrayCount = 0;
+    iProcessedArrayCount = 0;
+    if ( err == KErrNone ) QueueSnapshotItem( item );
+    }
+
+// ---------------------------------------------------------------------------
+// Takes a context snapshot including all initialized plugins
+// for multiple objects.
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CContextEngine::ContextSnapshot( MContextSnapshotObserver& aObserver,
+    RPointerArray<CHarvesterData>& aHDArray )
+    {
+    WRITELOG( "CContextEngine::ContextSnapshot (array)" ); // DEBUG INFO
+    
+    // if any plug-in hasn't been found...
+    if ( iContextEngineAO->PluginCount() <= 0 )
+        {
+        aObserver.ContextSnapshotStatus( NULL );
+        return;
+        }
+
+    // queue items for taking a snapshot
+    CContextSnapshotItem* item = NULL;
+    TRAPD( err, item = CContextSnapshotItem::NewL( &aObserver, &aHDArray ) );
+    iArrayCount = aHDArray.Count();
+    iProcessedArrayCount = 0;
+    if ( err == KErrNone ) QueueSnapshotItem( item );
+    }
+
+// ---------------------------------------------------------------------------
+// Number of context plug-ins loaded. For testing purposes only.
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt CContextEngine::PluginCount()
+    {
+    return iContextEngineAO->PluginCount();
+    }
+
+// ---------------------------------------------------------------------------
+// From MContextEngineObserver.
+// Method is called by CContextEngineAO when a context snapshot is finished
+// or an error has occured.
+// ---------------------------------------------------------------------------
+//
+void CContextEngine::ContextSnapshotStatus( CHarvesterData* aHD )
+    {
+    if( iSnapshotQueue.Count() == 0 )
+        {
+        return;
+        }
+    
+    if( iArrayCount > 0 )
+        {
+        iProcessedArrayCount++;
+        }
+    
+    // notify the client application by using MContextSnapshotObserver's
+    // method ContextSnapshotStatus()
+    iSnapshotQueue[0]->GetObserver()->ContextSnapshotStatus( aHD );
+
+    // remove handled item from queue
+    if( iProcessedArrayCount == iArrayCount )
+        {
+        delete iSnapshotQueue[0];
+        iSnapshotQueue[0] = NULL;
+        iSnapshotQueue.Remove( 0 );
+        iArrayCount = 0;
+        iProcessedArrayCount = 0;
+        }
+
+    // ask a new snapshot if there is stuff in the queue
+    if( iArrayCount == 0 && iSnapshotQueue.Count() > 0 )
+        {
+        RPointerArray<CHarvesterData>* tempArray = iSnapshotQueue[0]->GetItemArray();
+        if( tempArray )
+            {
+            iArrayCount = tempArray->Count();
+            }
+        iContextEngineAO->StartSnapshot( iSnapshotQueue[0] );
+        }
+    else if( iSnapshotQueue.Count() == 0 )
+    	{
+    	iSnapshotQueue.Compress();
+    	}
+    }
+
+// ---------------------------------------------------------------------------
+// Add a new item to the snapshot item queue.
+// Item contains an observer that needs to be informed when a snapshot is ready
+// and items that need a context snapshot.
+// If the queue was empty before adding the item, it's handling is started.
+// ---------------------------------------------------------------------------
+//
+void CContextEngine::QueueSnapshotItem( CContextSnapshotItem* aItem )
+    {
+    // add a new object
+    if ( iSnapshotQueue.Append( aItem ) != KErrNone )
+        {
+        delete aItem;
+        return;
+        }
+
+    // the queue was empty, start ContextEngineAO
+    if ( iSnapshotQueue.Count() == 1 )  // if the queue _was_ empty
+        {
+        iContextEngineAO->StartSnapshot( iSnapshotQueue[0] );
+        }
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contextengine/src/contextengineao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,467 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#include <sbdefs.h>
+#include <e32property.h>
+
+#include "contextengineao.h"
+#include "contextengine.h"
+#include "contextsnapshotitem.h"
+#include "harvesterlog.h"
+#include "mdsutils.h"
+#include "harvesterdata.h"
+#include "propertywatcher.h" 
+#include "harvestercommon.h"
+
+// ---------------------------------------------------------------------------
+// Default constructor for first phase construction.
+// ---------------------------------------------------------------------------
+//
+CContextEngineAO::CContextEngineAO( 
+		MContextInitializationObserver* aInitObserver,
+		MContextSnapshotObserver* aSnapshotObserver ) : 
+		CActive( KHarvesterPriorityContextEngine ), 
+		iInitializationObserver( aInitObserver ), 
+		iContextSnapshotObserver ( aSnapshotObserver ),
+		iUninitializedPluginsCount( 0 ),
+		iPluginSnapshotsLacking( 0 ),
+		iItem( NULL ),
+	    iState( EInitialization ),
+	    iInitializationError( KErrNone ),
+	    iSnapshotError( KErrNone ),
+	    iMdESession( NULL ),
+	    iPropertyWatcher( NULL ),
+	    iLastPlugin( EFalse )
+    {
+    WRITELOG( "CContextEngineAO::CContextEngineAO" ); // DEBUG INFO
+    }
+
+// ---------------------------------------------------------------------------
+// Standard NewL.
+// ---------------------------------------------------------------------------
+//
+CContextEngineAO* CContextEngineAO::NewL(
+    MContextInitializationObserver* aInitObserver,
+    MContextSnapshotObserver* aSnapshotObserver )
+    {
+    WRITELOG( "CContextEngineAO::NewL" ); // DEBUG INFO
+
+    CContextEngineAO* self = new (ELeave) CContextEngineAO( aInitObserver, aSnapshotObserver );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// 2nd phase construction.
+// ---------------------------------------------------------------------------
+//
+void CContextEngineAO::ConstructL()
+    {
+    WRITELOG( "CContextEngineAO::ConstructL" ); // DEBUG INFO
+
+    CActiveScheduler::Add( this );
+
+    iPropertyWatcher = CPropertyWatcher::GetInstanceL();
+      
+  	// Want to listen when backup/restore starts.
+  	// Calls NotifyKeyL when key's state has changed. 
+  	iPropertyWatcher->ListenKeyChangesL( 
+  			KUidSystemCategory,
+  			conn::KUidBackupRestoreKey, this );
+      
+    
+    if ( !iInitializationObserver )
+        {
+        InitializeL();
+        iState = EReady;
+        }
+    else  // same thing asyncronously
+        {
+        iState = EInitialization;
+        SetActive();
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone ); // "kick-start" this AO
+        }
+    }
+// ---------------------------------------------------------------------------
+// Destructor.
+// ---------------------------------------------------------------------------
+//
+CContextEngineAO::~CContextEngineAO()
+    {
+    WRITELOG( "CContextEngineAO::~CContextEngineAO" ); // DEBUG INFO
+
+    Cancel();
+
+    MdsUtils::CleanupPtrArray<CContextPlugin>( &iPlugins );
+	
+    if( iPropertyWatcher )
+		{
+		
+	 	iPropertyWatcher->StopListeningKeyChanges( 
+	  			KUidSystemCategory,
+	  			conn::KUidBackupRestoreKey, this );
+		
+		iPropertyWatcher->Delete(); // Release connection to TLS object.
+		}
+    }
+
+// ---------------------------------------------------------------------------
+// Set MdeSession for context engine plugins.
+// ---------------------------------------------------------------------------
+//
+void CContextEngineAO::SetMdeSession( CMdESession* aSession )
+    {
+    iMdESession = aSession;
+
+    for ( TInt i = 0; i < iPlugins.Count(); ++i )
+        {
+        iPlugins[i]->SetMdeSession( *aSession );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Start taking a context snapshot (for multiple objects).
+// ---------------------------------------------------------------------------
+//
+void CContextEngineAO::StartSnapshot( CContextSnapshotItem* aItem )
+    {
+    WRITELOG( "CContextEngineAO::StartSnapshot" ); // DEBUG INFO
+    iItem = aItem;
+    if ( !aItem ) return;
+    if ( !aItem->GetItem() && !aItem->GetItemArray() )
+        {
+        // no items to do the snapshot for... stop.
+        aItem->GetObserver()->ContextSnapshotStatus( KErrNone );
+        }
+
+    iSnapshotError = KErrNone;
+    iPluginSnapshotsLacking = iPlugins.Count(); // reset, no snapshots taken yet
+
+    if ( iPluginSnapshotsLacking <= 0 )
+    	{
+    	iState = EReady;
+    	iContextSnapshotObserver->ContextSnapshotStatus( KErrNone );    
+    	}
+    iLastPlugin = EFalse;
+    
+    iState = ESnapshot;
+    SetActive();
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone ); // "kick-start" this AO
+    }
+
+// ---------------------------------------------------------------------------
+// Return loaded plugin count.
+// ---------------------------------------------------------------------------
+//
+TInt CContextEngineAO::PluginCount()
+    {
+    return iPlugins.Count();
+    }
+
+// ---------------------------------------------------------------------------
+// From CActive.
+// Start/continue taking a context snapshot (for multiple objects).
+// Ask a snapshot from one plugin at a time.
+// ---------------------------------------------------------------------------
+//
+void CContextEngineAO::RunL()
+	{
+#ifdef _DEBUG
+    WRITELOG1( "CContextEngineAO::RunL iStatus: %d", iStatus.Int() ); // DEBUG INFO
+#endif
+
+    if ( iState == EInitialization )
+        {
+        InitializeL();
+        }
+    else if ( iState == ESnapshot )
+        {
+        if ( iStatus.Int() != KErrNone )
+            {
+            return;
+            }
+
+        if ( iPluginSnapshotsLacking > 0 )
+            {
+            TInt i = iPlugins.Count() - iPluginSnapshotsLacking;
+            if( iPluginSnapshotsLacking == 1 )
+                {
+                iLastPlugin = ETrue;
+                }
+            if ( iItem->GetItemArray() ) 
+                {
+                iPlugins[i]->ContextSnapshot( *this, *iItem->GetItemArray() );  
+                }                               // CContextEngineAO is instance of
+            else                                // MContextPluginObserver
+                {
+                iPlugins[i]->ContextSnapshot( *this, *iItem->GetItem() );
+                }
+            iPluginSnapshotsLacking--;
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// From CActive.
+// ---------------------------------------------------------------------------
+//
+#ifdef _DEBUG
+TInt CContextEngineAO::RunError( TInt aError )
+#else
+TInt CContextEngineAO::RunError( TInt )
+#endif
+    {
+    WRITELOG1( "CContextEngineAO::RunError with error code: %d", aError ); // DEBUG INFO
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// From CActive. 
+// ---------------------------------------------------------------------------
+//
+void CContextEngineAO::DoCancel()
+    {
+    WRITELOG( "CContextEngineAO::DoCancel" ); // DEBUG INFO
+
+    iPluginSnapshotsLacking = 0;
+    iState = EReady;
+    }
+
+// ---------------------------------------------------------------------------
+// From MContextPluginObserver.
+// ---------------------------------------------------------------------------
+//
+void CContextEngineAO::PluginInitializationStatus( TInt aErrorCode )
+    {
+    WRITELOG1( "CContextEngineAO::PluginInitializationStatus with error code: %d", aErrorCode ); // DEBUG INFO
+
+    if ( aErrorCode != KErrNone && iInitializationError != KErrNone )
+        {
+        iInitializationError = aErrorCode;
+        }
+
+    iUninitializedPluginsCount--;
+    if ( iUninitializedPluginsCount <= 0 )
+        {
+        iState = EReady;
+        // notify the client application by using MContextSnapshotObserver's
+        // method ContextInitializationStatus()
+        // Notice! Error code of the last plugin is returned...
+        if ( iInitializationObserver )
+            {
+            iInitializationObserver->ContextInitializationStatus( iInitializationError );
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// From MContextPluginObserver.
+// ---------------------------------------------------------------------------
+//
+void CContextEngineAO::PluginSnapshotStatus( CHarvesterData* aHD )
+    {
+    TInt errorCode = aHD->ErrorCode();
+    WRITELOG1( "CContextEngineAO::PluginSnapshotStatus with error code: %d", errorCode ); // DEBUG INFO
+
+    if ( errorCode != KErrNone && iSnapshotError != KErrNone )
+        {
+        aHD->SetErrorCode( errorCode );
+        }
+    
+    if( iLastPlugin )
+        {
+        // Notice! Error code of the last plugin is returned...
+        iContextSnapshotObserver->ContextSnapshotStatus( aHD );
+        }
+
+    if ( iPluginSnapshotsLacking <= 0 )
+        {
+        iState = EReady;
+        }
+    else 
+        {  // do this again for the next plugin/harvest data object
+        if( !IsActive() )
+            {
+            SetActive();
+            TRequestStatus* status = &iStatus;
+            User::RequestComplete( status, KErrNone ); // "kick-start" this AO
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Called by CBlacklistBackupSubscriberAO when
+// Backup&Restore is backing up or restoring.
+// ---------------------------------------------------------------------------
+//
+void CContextEngineAO::BackupRestoreStart()
+    {
+    // stop context plugins
+    WRITELOG( "CContextEngineAO::BackupRestoreStart" );
+ 
+    iPlugins.ResetAndDestroy(); // remove any existing plugins, just in case
+    }
+
+// ---------------------------------------------------------------------------
+// Called by CBlacklistBackupSubscriberAO when
+// Backup&Restore has finished backup or restore.
+// ---------------------------------------------------------------------------
+//
+void CContextEngineAO::BackupRestoreReady()
+    {
+    // restart plugins
+    WRITELOG( "CContextEngineAO::BackupRestoreReady" );
+    
+    TRAP_IGNORE( InitializeL() );
+    
+    if ( iMdESession )
+    	{
+    	SetMdeSession( iMdESession );
+    	}
+    
+    iState = EReady;
+    
+    }
+
+// private methods
+
+// ---------------------------------------------------------------------------
+// Load context plugins to the "iPlugins" array.
+// ---------------------------------------------------------------------------
+//
+void CContextEngineAO::LoadPluginsL()
+    {
+    WRITELOG( "CContextEngineAO::LoadPluginsL" ); // DEBUG INFO
+
+    if ( iPlugins.Count() > 0 )
+        {
+        iPlugins.ResetAndDestroy(); // remove any existing plugins, just in case
+        }
+
+    // read info about all implementations into infoArray
+    RImplInfoPtrArray infoArray;
+    TCleanupItem cleanupItem( MdsUtils::CleanupEComArray, &infoArray );
+    CleanupStack::PushL( cleanupItem );
+    
+    CContextPlugin::ListImplementationsL( infoArray );
+
+    CContextPlugin* plugin = NULL;
+    TInt err = KErrNone;
+    for ( TInt i = 0; i < infoArray.Count(); i++ )
+        {
+        TUid uid = infoArray[i]->ImplementationUid(); 
+        TRAP( err, plugin = CContextPlugin::NewL( uid ) ); // create the plug-ins
+        if ( err == KErrNone && plugin )
+            {
+            CleanupStack::PushL( plugin );
+            iPlugins.AppendL( plugin );        // and add them to an array
+            CleanupStack::Pop( plugin );
+            }
+        }
+
+	CleanupStack::PopAndDestroy( &infoArray ); // infoArray, results in a call to CleanupEComArray		
+    }
+
+// ---------------------------------------------------------------------------
+// Initialize this object. Thus load and initialize plugins.
+// ---------------------------------------------------------------------------
+//
+void CContextEngineAO::InitializeL()
+    {
+    WRITELOG( "CContextEngineAO::InitializeL" ); // DEBUG INFO
+
+    iInitializationError = KErrNone;
+    LoadPluginsL();
+    iUninitializedPluginsCount = iPlugins.Count(); // set this so we can later be sure that all
+                                                   // plug-ins are initialized.
+    if ( iUninitializedPluginsCount <= 0 ) // if no plugins were loaded
+        {
+        if ( iInitializationObserver )
+            {
+            iInitializationObserver->ContextInitializationStatus( KErrNone );
+            }
+        }
+
+    const TInt KCount = iUninitializedPluginsCount;
+    for ( TInt i = 0; i < KCount; i++ )
+        {
+        iPlugins[i]->Init( *this ); // CContextEngineAO is instance of MContextPluginObserver
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CRestoreWatcher::NotifyKeyL
+// CPropertyWatcher's callback. From 
+// -----------------------------------------------------------------------------
+//
+void CContextEngineAO::NotifyKeyL( 
+		const TInt aKeyValue,
+		const TUid aPropertyCategory,
+		const TUint aKey )
+	{
+	WRITELOG("CContextEngineAO::NotifyKeyL() - begin");
+	
+	if( aPropertyCategory == KUidSystemCategory &&
+			aKey == conn::KUidBackupRestoreKey ) 
+		{
+		HandleBackupRestoreKeyAction( aKeyValue );
+		}
+	
+	
+	WRITELOG("CContextEngineAO::NotifyKeyL() - end");
+	}
+
+// -----------------------------------------------------------------------------
+// CContextEngineAO::HandleBackupKeyAction
+// When user starts restore sets flag on.
+// -----------------------------------------------------------------------------
+//
+void CContextEngineAO::HandleBackupRestoreKeyAction( const TUint aKeyValue )
+	{	
+	WRITELOG("CRestoreWatcher::HandleBackupKeyAction() - begin");
+	
+	TInt backupStateValue = aKeyValue;
+	backupStateValue &= conn::KBURPartTypeMask;
+	
+	switch ( backupStateValue )
+		{
+		case conn::EBURBackupFull:
+		case conn::EBURBackupPartial:
+		case conn::EBURRestoreFull:
+		case conn::EBURRestorePartial:
+			{
+			BackupRestoreStart();
+			break;
+			}
+		
+		case conn::EBURNormal:
+		case conn::EBURUnset:
+		default:
+			{
+			// backup or restore is completed, so resume normal operation.
+       		BackupRestoreReady();
+			}
+		}	
+	
+	WRITELOG("CRestoreWatcher::HandleBackupKeyAction() - end");
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+#include "../metadataengine/group/bld.inf"
+#include "../locationmanager/group/bld.inf"
+#include "../contextengine/group/bld.inf"
+#include "../harvester/group/bld.inf"
+#include "../mds_plat/group/bld.inf"
+#include "../mds_pub/group/bld.inf"
+#include "../watchdog/group/bld.inf"
+
+#ifdef RD_MDS_2_5 
+#include "../clfwrapper/group/bld.inf"
+#endif
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+../rom/mds.iby	CORE_MW_LAYER_IBY_EXPORT_PATH(mds.iby)
+
+#ifdef RD_MDS_2_5
+../rom/ContentListingFramework.iby	CORE_MW_LAYER_IBY_EXPORT_PATH( ContentListingFramework.iby )
+#endif
+
+//Stubs
+../sis/mds/mds_stub.sis  /epoc32/data/z/system/install/mds_stub.sis
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+../rom/mds_testers.iby	CORE_MW_LAYER_IBY_EXPORT_PATH(mds_testers.iby)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistclient/bwincw/blacklistclientwinscw.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,10 @@
+EXPORTS
+	??0RBlacklistClient@@QAE@XZ @ 1 NONAME ; RBlacklistClient::RBlacklistClient(void)
+	??1RBlacklistClient@@QAE@XZ @ 2 NONAME ; RBlacklistClient::~RBlacklistClient(void)
+	?AddL@RBlacklistClient@@QBEXABVTDesC16@@KVTTime@@@Z @ 3 NONAME ; void RBlacklistClient::AddL(class TDesC16 const &, unsigned long, class TTime) const
+	?CloseDBL@RBlacklistClient@@QAEXXZ @ 4 NONAME ; void RBlacklistClient::CloseDBL(void)
+	?Connect@RBlacklistClient@@QAEHXZ @ 5 NONAME ; int RBlacklistClient::Connect(void)
+	?IsBlacklistedL@RBlacklistClient@@QAEHABVTDesC16@@KVTTime@@@Z @ 6 NONAME ; int RBlacklistClient::IsBlacklistedL(class TDesC16 const &, unsigned long, class TTime)
+	?LoadBlacklistL@RBlacklistClient@@QAEXXZ @ 7 NONAME ; void RBlacklistClient::LoadBlacklistL(void)
+	?RemoveL@RBlacklistClient@@QBEXABVTDesC16@@K@Z @ 8 NONAME ; void RBlacklistClient::RemoveL(class TDesC16 const &, unsigned long) const
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistclient/eabi/blacklistclient.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,14 @@
+EXPORTS
+	_ZN16RBlacklistClient14IsBlacklistedLERK7TDesC16m5TTime @ 1 NONAME
+	_ZN16RBlacklistClient14LoadBlacklistLEv @ 2 NONAME
+	_ZN16RBlacklistClient7ConnectEv @ 3 NONAME
+	_ZN16RBlacklistClient8CloseDBLEv @ 4 NONAME
+	_ZN16RBlacklistClientC1Ev @ 5 NONAME
+	_ZN16RBlacklistClientC2Ev @ 6 NONAME
+	_ZN16RBlacklistClientD1Ev @ 7 NONAME
+	_ZN16RBlacklistClientD2Ev @ 8 NONAME
+	_ZNK16RBlacklistClient4AddLERK7TDesC16m5TTime @ 9 NONAME
+	_ZNK16RBlacklistClient7RemoveLERK7TDesC16m @ 10 NONAME
+	_ZTI14CBlacklistItem @ 11 NONAME ; #<TI>#
+	_ZTV14CBlacklistItem @ 12 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistclient/eabi/blacklistclientarm.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,14 @@
+EXPORTS
+	_ZN16RBlacklistClient14IsBlacklistedLERK7TDesC16m5TTime @ 1 NONAME
+	_ZN16RBlacklistClient14LoadBlacklistLEv @ 2 NONAME
+	_ZN16RBlacklistClient7ConnectEv @ 3 NONAME
+	_ZN16RBlacklistClient8CloseDBLEv @ 4 NONAME
+	_ZN16RBlacklistClientC1Ev @ 5 NONAME
+	_ZN16RBlacklistClientC2Ev @ 6 NONAME
+	_ZN16RBlacklistClientD1Ev @ 7 NONAME
+	_ZN16RBlacklistClientD2Ev @ 8 NONAME
+	_ZNK16RBlacklistClient4AddLERK7TDesC16m5TTime @ 9 NONAME
+	_ZNK16RBlacklistClient7RemoveLERK7TDesC16m @ 10 NONAME
+	_ZTI14CBlacklistItem @ 11 NONAME ABSENT; #<TI>#
+	_ZTV14CBlacklistItem @ 12 NONAME ABSENT; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistclient/group/blacklistclient.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  MMP file
+*/
+
+#include <platform_paths.hrh>
+VERSION           10.0
+TARGET            blacklistclient.dll
+TARGETTYPE        dll
+UID               0x1000008D  0x2001B2ED  
+
+CAPABILITY        CAP_CLIENT_DLL
+
+MW_LAYER_SYSTEMINCLUDE
+
+USERINCLUDE       ../inc
+USERINCLUDE       ../../blacklistserver/inc
+USERINCLUDE       ../../common/inc
+USERINCLUDE       ../../../inc
+
+SOURCEPATH        ../src
+SOURCE		      blacklistclient.cpp
+
+SOURCEPATH        ../../common/src
+SOURCE            blacklistitem.cpp
+
+LIBRARY        	  euser.lib
+LIBRARY           mdccommon.lib
+
+#if defined(WINSCW)
+deffile ../bwincw/blacklistclientwinscw.def
+#else 
+
+#if defined(ARMCC)
+deffile ../eabi/blacklistclientarm.def
+#endif
+
+#endif
+nostrictdef
+
+BYTEPAIRCOMPRESSTARGET
+PAGED
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistclient/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+blacklistclient.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistclient/inc/blacklistclient.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,163 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef _RBLACKLISTCLIENT_H_
+#define _RBLACKLISTCLIENT_H_
+
+// SYSTEM INCLUDE
+#include <e32base.h>
+#include <e32std.h>
+#include <f32file.h>
+
+// FORWARD DECLERATIONS
+class CBlacklistItem;
+
+/*!
+  @class RBlacklistClient
+  @discussion An instance of the RBlacklistClient object 
+  */
+NONSHARABLE_CLASS( RBlacklistClient ) : public RSessionBase
+    {
+    public:
+        /*!
+        @function RBlacklistClient
+        @discussion standard C++ constructor
+        */
+        IMPORT_C RBlacklistClient();
+        
+        /*!
+        @function ~RBlacklistClient
+        @discussion Destroy the object and release all memory objects
+        */
+        IMPORT_C ~RBlacklistClient();
+            
+    public: // Exported public functions
+
+        /*!
+        @function Connect
+        @discussion Create connection to server
+        @result KErrNone if connected succesfully
+        */
+        IMPORT_C TInt Connect();
+        
+        /*!
+        @function IsBlacklistedL
+        @discussion Destroy the object and release all memory objects.
+        @result ETrue if object is blaklisted, EFalse otherwise.
+        @param aUri - object uri.
+        @param aMediaId - drive id where object is located (E,C ...).
+        @param aLastModifiedTime - time when object is modified.
+        */
+        IMPORT_C TBool IsBlacklistedL( const TDesC& aUri, TUint32 aMediaId, TTime aLastModifiedTime );
+        
+        /*!
+        @function AddL
+        @discussion Add object to blacklist.
+        @param aUri - object uri.
+        @param aMediaId - drive id where object is located (E,C ...).
+        @param aLastModifiedTime - time when object is modified.
+        */
+        IMPORT_C void AddL( const TDesC& aUri, TUint32 aMediaId, TTime aLastModifiedTime ) const;
+        
+        /*!
+        @function RemoveL
+        @discussion Remove object from blacklist.
+        */
+        IMPORT_C void RemoveL( const TDesC& aUri, TUint32 aMediaId ) const;
+        
+        /*!
+        @function LoadBlacklistL
+        @discussion Load blacklist from server.
+        */
+        IMPORT_C void LoadBlacklistL();
+        
+        /*!
+        @function CloseDBL
+        @discussion Closes server database. 
+        */
+        IMPORT_C void CloseDBL();
+
+    private: // private functions
+    
+        /*!
+        @function Version
+        @discussion Returns version
+        @result TVersion - Returns version of the server.
+        */
+        TVersion Version() const;
+        
+        /*!
+        @function DoLoadBlacklistL
+        @discussion sends request load blacklist to server.  
+        @param aHandle memory handle, used to create memory chunk.
+        */
+        void DoLoadBlacklistL( TInt& aHandle ) const;
+        
+        /*!
+        @function AddToMemoryTableL
+        @discussion Add object to client list (not actually a memory table).
+        @param aLastModifiedTime - time when object is modified.
+        @param aUri - object uri.
+        @param aMediaId - drive id where object is located (E,C ...).
+        */
+        void AddToMemoryTableL( const TInt64& aModified, const TDesC& aUri,
+            const TUint32 aMediaId );
+        
+        /*!
+        @function RemoveFromMemoryTableL
+        @discussion Remove object from client list (not actually a memory table).
+        @param aUri - object uri.
+        @param aMediaId - drive id where object is located (E,C ...).
+        */
+        void RemoveFromMemoryTableL( const TDesC& aUri, const TUint32 aMediaId );
+        
+        /*!
+        @function GetListIndex NOTE: WRONG NAMING NOT BASED S60 CODING CONVENTIONS!!!
+        @discussion Returns list index.
+        */
+        TInt GetListIndex( const TDesC& aUri, TUint32 aMediaId );
+          
+        /*!
+        @function RemoveFromDBL
+        @discussion removes object from server's database.
+        @param aUri - object uri.
+        @param aMediaId - drive id where object is located (E,C ...).
+        */
+        void RemoveFromDBL( const TDesC& aUri, TUint32 aMediaId ) const;  
+
+        /*!
+        @function StartServer
+        @discussion starts server.
+        @result KErrNone if succesfully created.
+        */
+        TInt StartServer();
+  
+    private: // private data
+       
+        /*! @var iSessionOk flag to indicate if session is ok or not.*/
+        TBool iSessionOk;
+       
+       	/*! @var iBlacklistChunk used to create global memory area.*/
+       	RChunk iBlacklistChunk;
+       
+        /*! @var iBlacklistMemoryTable used to keep blacklisted items.*/
+        RPointerArray<CBlacklistItem> iBlacklistMemoryTable;
+
+    };
+
+#endif      // _RBLACKLISTCLIENT_H_   
+            
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistclient/src/blacklistclient.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,414 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// USER INCLUDE
+#include "blacklistclient.h"
+#include "blacklistcommon.h"
+#include "mdcserializationbuffer.h"
+#include "blacklistitem.h"
+#include "harvesterlog.h"
+
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::RBlacklistClient()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C RBlacklistClient::RBlacklistClient() : RSessionBase (),
+    iSessionOk( EFalse )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::~RBlacklistClient()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C RBlacklistClient::~RBlacklistClient()
+    {
+    WRITELOG( "CBlacklistServer::~RBlacklistClient - begin" );
+    
+    RSessionBase::Close(); 
+    iBlacklistMemoryTable.ResetAndDestroy();
+    iBlacklistMemoryTable.Close();
+	iBlacklistChunk.Close();
+
+    WRITELOG( "CBlacklistServer::~RBlacklistClient - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::Connect()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt RBlacklistClient::Connect()
+    {
+    WRITELOG( "CBlacklistServer::Connect - begin" );
+
+    TInt retryCount = 2;
+    TInt error = KErrNone;
+    
+    iSessionOk = EFalse;
+    
+    while ( retryCount )
+        {
+        // try create session, if ok, then break out and return KErrNone
+        error = CreateSession( KBlacklistServerName, Version() );
+        if( error != KErrNotFound && error != KErrServerTerminated )
+            {
+            iSessionOk = ETrue;
+            break;
+            }
+        
+        // Cannot create session, start server
+        error = StartServer();
+        
+        if ( error != KErrNone && error != KErrAlreadyExists )
+            {
+            break;
+            }
+       
+        --retryCount;
+        }
+    
+    WRITELOG( "CBlacklistServer::Connect - end" );
+
+    return error;
+    }
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::Version()
+// ---------------------------------------------------------------------------
+//
+TVersion RBlacklistClient::Version() const
+    {
+    WRITELOG( "CBlacklistServer::Version - begin" );
+
+    return TVersion( KBlacklistServerMajorVersion, KBlacklistServerMinorVersion,
+    	KBlacklistServerBuildVersion );
+
+    }
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::StartServer()
+// ---------------------------------------------------------------------------
+//
+TInt RBlacklistClient::StartServer()
+    {
+    WRITELOG( "CBlacklistServer::CustomSecurityCheckL - begin" );
+
+    const TUidType serverUid = ( KNullUid, KNullUid, KUidKBlacklistServer );
+
+    RProcess server;
+    TInt error = server.Create( KBlacklistServerExe, KNullDesC );
+    if( error != KErrNone )
+        {
+        return error;
+        }
+    
+    // start server and wait for signal before proceeding    
+    TRequestStatus status;
+    server.Rendezvous( status );
+    if ( status.Int() != KRequestPending )
+        {
+        server.Kill( 0 );
+        }
+    else
+        {
+        server.Resume();
+        }
+
+    User::WaitForRequest( status );
+    error = server.ExitType() == EExitPanic ? KErrGeneral : status.Int();
+    server.Close();
+
+    WRITELOG( "CBlacklistServer::Version - end" );
+
+    return error;
+    }
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::RemoveFromDBL()
+// ---------------------------------------------------------------------------
+//
+void RBlacklistClient::RemoveFromDBL( const TDesC& aUri, TUint32 aMediaId ) const
+    {
+    WRITELOG( "CBlacklistServer::RemoveFromDBL - begin" );
+
+    TPckgBuf<TUint32> mediaIdPckg( aMediaId );
+    
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 1, &aUri );
+    ipcArgs.Set( 2, &mediaIdPckg );
+ 
+    TInt err = SendReceive( EBlacklistRemoveFromDB, ipcArgs );
+    User::LeaveIfError( err );
+
+    WRITELOG( "CBlacklistServer::RemoveFromDBL - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::DoLoadBlacklistL()
+// ---------------------------------------------------------------------------
+//
+void RBlacklistClient::DoLoadBlacklistL( TInt& aHandle ) const
+    {
+    WRITELOG( "CBlacklistServer::DoLoadBlacklistL - begin" );
+
+    TPckgBuf<TInt> handleBuf;
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 1, &handleBuf );
+    TInt err = SendReceive( EGetBlacklistData, ipcArgs );
+    User::LeaveIfError( err );
+    aHandle = handleBuf();
+
+    WRITELOG( "CBlacklistServer::DoLoadBlacklistL - end" );
+    } 
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::LoadBlacklistL()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void RBlacklistClient::LoadBlacklistL()
+    {
+    WRITELOG( "CBlacklistServer::LoadBlacklistL - begin" );
+
+    if ( !iSessionOk )
+        {
+        return;
+        }
+
+    // delete old data
+    if( iBlacklistMemoryTable.Count() > 0 )
+        {
+        iBlacklistMemoryTable.ResetAndDestroy();
+        }
+    
+    // Get handle to data
+    TInt handle( 0 );
+    DoLoadBlacklistL( handle );
+    
+   	// create memory chunk
+   	HBufC*  name = HBufC::NewLC( 32 );
+	*name = KBlacklistChunkName;
+	name->Des().AppendNum( handle );
+	iBlacklistChunk.Close();
+
+	User::LeaveIfError ( iBlacklistChunk.OpenGlobal( *name, ETrue ) );
+
+	CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( iBlacklistChunk.Base(), iBlacklistChunk.Size() );
+
+	if ( buffer->Size() == 0 )
+	    {
+	    User::Leave( KErrNotFound );
+	    }
+	
+	// First get list count
+	TUint32 listCount ( 0 );
+	buffer->ReceiveL( listCount );
+	
+	TInt64 modified ( 0 );
+	TUint32 mediaId ( 0 );
+    HBufC* uri = NULL;
+    
+    for( TInt i( 0 ); i < listCount; i++ )
+        {
+        // get modified and media id
+	    buffer->ReceiveL( modified );
+	    buffer->ReceiveL( mediaId );
+        
+        //Get uri
+        uri = buffer->ReceiveDes16L();
+       	CleanupStack::PushL( uri );
+       	AddToMemoryTableL( modified, *uri, mediaId );
+       	CleanupStack::PopAndDestroy( uri );
+       	uri = NULL;
+        }
+	
+	CleanupStack::PopAndDestroy( buffer );
+	CleanupStack::PopAndDestroy( name );
+
+    WRITELOG( "CBlacklistServer::LoadBlacklistL - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::AddToMemoryTableL()
+// ---------------------------------------------------------------------------
+//
+void RBlacklistClient::AddToMemoryTableL( const TInt64& aModified,
+        const TDesC& aUri, const TUint32 aMediaId )
+    {
+    WRITELOG( "CBlacklistServer::AddToMemoryTableL - begin" );
+
+    CBlacklistItem* item = CBlacklistItem::NewL( aModified, aUri, aMediaId );
+    
+    const TInt err = iBlacklistMemoryTable.Append( item ); // ownership is transferred
+    if ( err != KErrNone )
+        {
+        delete item;
+        }
+
+
+    WRITELOG( "CBlacklistServer::AddToMemoryTableL - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::RemoveFromMemoryTableL()
+// ---------------------------------------------------------------------------
+//
+void RBlacklistClient::RemoveFromMemoryTableL( const TDesC& aUri, const TUint32 aMediaId )
+    {
+    WRITELOG( "CBlacklistServer::RemoveFromMemoryTableL - begin" );
+
+    TInt index = GetListIndex( aUri, aMediaId );
+    if ( index >= 0 )
+        {
+        CBlacklistItem* item = iBlacklistMemoryTable[index];
+        delete item;
+        iBlacklistMemoryTable.Remove( index );
+        }
+
+    WRITELOG( "CBlacklistServer::RemoveFromMemoryTableL - end" );
+    }
+ 
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::IsBlacklistedL()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TBool RBlacklistClient::IsBlacklistedL( const TDesC& aUri, TUint32 aMediaId, TTime aLastModifiedTime )
+    {
+    WRITELOG( "CBlacklistServer::IsBlacklistedL - begin" );
+
+    TInt index = GetListIndex( aUri, aMediaId );
+    if ( index >= 0 )
+        {
+        TInt64 modified( 0 );
+        modified = iBlacklistMemoryTable[index]->Modified();
+        
+        if( modified > 0 )
+            {
+            if ( modified == aLastModifiedTime.Int64() )
+                {
+                WRITELOG( "CBlacklistServer::IsBlacklistedL - file is blacklisted, modification time is different" );
+                return ETrue;
+                }
+            else
+                {
+                // file might be different, so remove from blacklist
+                // and act like it wasn't found
+                RemoveFromMemoryTableL( aUri, aMediaId );
+                
+                // Remove from server DB
+                RemoveFromDBL( aUri, aMediaId );
+                }
+            }
+        else
+            {
+            WRITELOG( "CBlacklistServer::IsBlacklistedL - file is blacklisted, no modification time found" );
+            return ETrue;
+            }
+        
+        }
+   
+    WRITELOG( "CBlacklistServer::IsBlacklistedL - end" );
+    return EFalse;
+    }
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::GetListIndex()
+// ---------------------------------------------------------------------------
+//
+TInt RBlacklistClient::GetListIndex( const TDesC& aUri, TUint32 aMediaId )
+    {
+    WRITELOG( "CBlacklistServer::GetListIndex - begin" );
+
+    for ( TInt i( 0 ); i < iBlacklistMemoryTable.Count(); ++i )
+        {
+        if ( iBlacklistMemoryTable[i]->Compare( aUri, aMediaId ) )
+            {
+            return i;
+            }
+        }
+
+    WRITELOG( "CBlacklistServer::GetListIndex - end" );
+
+    return KErrNotFound;
+    }
+
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::AddL()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void RBlacklistClient::AddL( const TDesC& aUri, TUint32 aMediaId, TTime aLastModifiedTime ) const
+    {
+    WRITELOG( "CBlacklistServer::AddL - begin" );
+
+    TPckgC<TUint32> mediaIdPckg( aMediaId );
+    TPckgC<TTime> lastModifiedTimePckg( aLastModifiedTime );
+
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &mediaIdPckg );
+    ipcArgs.Set( 1, &aUri );
+    ipcArgs.Set( 2, &lastModifiedTimePckg );
+ 
+    const TInt err = SendReceive( EBlacklistAdd, ipcArgs );
+    User::LeaveIfError( err );
+
+    WRITELOG( "CBlacklistServer::AddL - end" );
+    }
+
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::RemoveL()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void RBlacklistClient::RemoveL( const TDesC& aUri, TUint32 aMediaId ) const
+    {
+    WRITELOG( "CBlacklistServer::RemoveL - begin" );
+
+    TPckgBuf<TUint32> mediaIdPckg( aMediaId );
+    
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 1, &aUri );
+    ipcArgs.Set( 2, &mediaIdPckg );
+ 
+    const TInt err = SendReceive( EBlacklistRemove, ipcArgs );
+    User::LeaveIfError( err );
+
+    WRITELOG( "CBlacklistServer::RemoveL - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// RBlacklistClient::CloseDBL()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void RBlacklistClient::CloseDBL()
+    {
+    WRITELOG( "CBlacklistServer::CloseDBL - begin" );
+
+    if ( !iSessionOk )
+        {
+        User::Leave( KErrDisconnected );
+        }
+    else
+        {
+        Send( EBlacklistCloseDB );
+        }
+
+    WRITELOG( "CBlacklistServer::CloseDBL - end" );
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistserver/group/blacklistserver.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  MMP file
+*/
+
+#include <platform_paths.hrh>
+VERSION					  10.0
+TARGET            blacklistserver.exe
+TARGETTYPE        exe
+UID               0x0 0x2001B2EB 
+
+VENDORID          VID_DEFAULT
+
+CAPABILITY        CAP_SERVER 
+
+MW_LAYER_SYSTEMINCLUDE
+SYSTEMINCLUDE	  /epoc32/include/connect
+
+USERINCLUDE       ../inc
+USERINCLUDE       ../../common/inc
+USERINCLUDE       ../../../metadataengine/server/inc
+USERINCLUDE       ../../../inc
+
+SOURCEPATH        ../src
+SOURCE		      blacklistserver.cpp
+SOURCE		      blacklistsession.cpp
+ 
+SOURCEPATH        ../../../metadataengine/server/src
+SOURCE            mdssqliteconnection.cpp
+
+SOURCEPATH        ../../common/src
+SOURCE            blacklistitem.cpp
+
+LIBRARY     	  euser.lib
+LIBRARY           mdccommon.lib
+LIBRARY           sqldb.lib
+LIBRARY           platformenv.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+
+EPOCPROCESSPRIORITY background
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistserver/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+blacklistserver.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistserver/inc/blacklistcommon.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef COMMON_H
+#define COMMON_H
+
+#include <e32base.h>
+
+_LIT( KBlacklistServerName, "BlacklistServer" );
+_LIT( KBlacklistServerExe,  "BlacklistServer.exe" ); // 0x0 2001B2EB = server uid
+_LIT( KBlacklistChunkName,  "BlacklistServerChunk" );
+
+const TUid KUidKBlacklistServer = { 0x2001B2EB };  
+
+const TUint KBlacklistServerMajorVersion = 0;
+const TUint KBlacklistServerMinorVersion = 1;
+const TUint KBlacklistServerBuildVersion = 1;
+
+enum TService
+{
+    EBlacklistAdd,
+    EBlacklistRemove,
+    EBlacklistRemoveFromDB,
+    EGetBlacklistData,
+    EBlacklistCloseDB,
+    EMaxService     // Not an actual service
+};
+
+// SQL clauses for server
+_LIT( KDefaultBlacklistDatabaseFile, "C:[200009fe]blacklistdb.sq" );
+_LIT( KMdsBlacklistInsert, "INSERT INTO Blacklist(Modified, Uri, MediaId) VALUES(?, ?, ?);" );
+_LIT( KMdsBlacklistUpdate, "UPDATE Blacklist SET Modified = ? WHERE Uri = ? AND MediaId = ?;" );
+_LIT( KMdsBlacklistDelete, "DELETE FROM Blacklist WHERE Uri = ? AND MediaId = ?;" );
+_LIT( KMdsBlacklistCheck, "SELECT Modified FROM Blacklist WHERE Uri = ? AND MediaId = ?;" );
+_LIT( KMdsBlacklistCheckTableExistence, "SELECT COUNT(*) FROM Blacklist;" );
+_LIT( KDropBlacklistTable, "DROP TABLE IF EXISTS Blacklist;" );
+_LIT( KCreateBlacklistTable, "CREATE TABLE Blacklist(Uri TEXT NOT NULL, MediaId INTEGER NOT NULL, Modified INTEGER NOT NULL, PRIMARY KEY(Uri,MediaId));" );
+_LIT( KMdsBlacklistCache, "SELECT Uri, MediaId, Modified FROM Blacklist;" );
+
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistserver/inc/blacklistserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,273 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef __BLACKLISTSERVER_H__
+#define __BLACKLISTSERVER_H__
+
+// SYSTEM INCLUDE
+#include <e32base.h>    // CTrapCleanup
+#include <f32file.h>
+
+// FORWARD DECLERATIONS
+class CMdSSqLiteConnection;
+class CBlacklistItem;
+class RRowData;
+
+/*!
+  @class CBlacklistServer
+  @discussion An instance of the CBlacklistServer object 
+  */
+class CBlacklistServer : public CPolicyServer
+    {
+    public:
+         /*!
+        @function NewL
+        @discussion factory function.
+        */
+        static CBlacklistServer* NewL();
+
+        /*!
+        @function NewLC
+        @discussion factory function, pointer is in cleanupstack.
+        */
+        static CBlacklistServer* NewLC();      
+
+        /*!
+        @function ~CBlacklistServer
+        @discussion standard C++ destructor.
+        */
+        virtual ~CBlacklistServer();
+
+        /*!
+        @function AddSession
+        @discussion adds new session.
+        */
+        void AddSession();
+        /*!
+        @function RemoveSession
+        @discussion removes session.
+        */
+        void RemoveSession();
+
+        /*!
+        @function MemoryHandle
+        @discussion returns memory handle.
+        @result integer value to indicate memory handle.
+        */
+        TInt MemoryHandle();
+
+        /*!
+        @function OpenDatabaseL
+        @discussion Opens server database.
+        */
+        void OpenDatabaseL();
+ 
+        /*!
+        @function AddL
+        @discussion Add object to server's list.
+        @param aMediaId - drive id where object is located (E,C ...).
+        @param aUri - object uri.
+        @param aLastModifiedTime - time when object is modified.
+        */
+        void AddL( const TUint32& mediaId, const TDesC& aUri, const TTime& aLastModifiedTime );
+
+        /*!
+        @function RemoveL
+        @discussion Removes object from server's list.
+        @param aUri - object uri.
+        @param aMediaId - drive id where object is located (E,C ...).
+        */
+        void RemoveL( const TUint32& mediaId, const TDesC& aUri );
+
+        /*!
+        @function RemoveFromDBL
+        @discussion removes object from server's database.
+        @param aUri - object uri.
+        @param aMediaId - drive id where object is located (E,C ...).
+        */
+        void RemoveFromDBL( const TDesC& aUri, const TUint32 aMediaId );
+
+        /*!
+        @function AddToDBL
+        @discussion Adds object to server's database.
+        @param aUri - object uri.
+        @param aMediaId - drive id where object is located (E,C ...).
+        @param aLastModifiedTime - time when object is modified.
+        */
+        void AddToDBL( const TDesC& aUri, const TUint32 aMediaId, const TInt64& aLastModifiedTime );
+
+        /*!
+        @function CloseDB
+        @discussion closes server's database.
+        */
+        void CloseDB();
+
+        /*!
+        @function ExeMainL
+        @discussion creates server. 
+        */
+        static void ExeMainL(); 
+    
+    protected: // Functions from base classes
+
+        /*!
+        @function CustomSecurityCheckL
+        @discussion check if service is allowed.
+        */
+        CPolicyServer::TCustomResult CustomSecurityCheckL( 
+            const RMessage2 &aMsg, TInt &aAction, TSecurityInfo &aMissing );
+
+        /*!
+        @function CustomFailureActionL
+        @discussion not used.
+        */
+        CPolicyServer::TCustomResult CustomFailureActionL(
+            const RMessage2 &aMsg, TInt aAction, const TSecurityInfo &aMissing );   
+    private:
+
+        /*!
+        @function CBlacklistServer
+        @discussion standard C++ constructor
+        */
+        CBlacklistServer();
+
+        /*!
+        @function RBlacklistClient
+        @discussion two phase constructor
+        */
+        void ConstructL();
+
+        /*!
+        @function NewSessionL
+        @discussion creates new session
+        @param aVersion, server version.
+        @param aMessage, not used.
+        @result return blacklist session.
+        */
+        CSession2* NewSessionL( const TVersion& aVersion, const RMessage2& aMessage ) const;
+        
+        /*!
+        @function NewSessionL
+        @discussion creates new session
+        @param aVersion, server version.
+        @result KErrNone or error if server RunL fails. 
+        */
+        TInt RunError( TInt aError );
+
+    private:
+
+          /*!
+        @function CloseDatabase
+        @discussion closes server database.
+        */
+        void CloseDatabase();
+
+        /*!
+        @function LoadDatabaseToMemoryL
+        @discussion load database to server's list
+        */
+        void LoadDatabaseToMemoryL();
+     
+        /*!
+        @function CreateBlacklistTableL
+        @discussion Creates blacklist table.
+        */
+        void CreateBlacklistTableL();
+     
+        /*!
+        @function AddToMemoryTableL
+        @discussion adds object to server's list.
+        @param aLastModifiedTime - time when object is modified.
+        @param aUri - object uri.
+        @param aMediaId - drive id where object is located (E,C ...).
+        */
+        void AddToMemoryTableL( const TInt64& aModified, const TDesC& aUri,
+            const TUint32 aMediaId );
+     
+        /*!
+        @function RemoveFromMemoryTable
+        @discussion removes object from server's list 
+        @param aUri - object uri.
+        @param aMediaId - drive id where object is located (E,C ...).
+        */
+        void RemoveFromMemoryTable( const TDesC& aUri,
+            const TUint32 aMediaId );
+     
+        /*!
+        @function GetMemoryTableIndex
+        @discussion returns list index. 
+        @param aUri - object uri.
+        @param aMediaId - drive id where object is located (E,C ...).
+        @result returns list index.        
+        */
+        TInt GetMemoryTableIndex( const TDesC& aUri, TUint32 aMediaId );
+
+        /*!
+        @function TableExistsL
+        @discussion 
+        @result ETrue if table exists, EFalse otherwise. 
+        */
+        TBool TableExistsL();
+        
+        /*!
+        @function SerializeToSharedMemoryL
+        @discussion creates serialized buffer.
+        */
+        void SerializeToSharedMemoryL();
+        
+        /*!
+        @function WriteAllDataToDBL
+        @discussion write all data to server's database.
+        */
+        void WriteAllDataToDBL();
+        
+        /*!
+        @function CommitBufferedItemsL
+        @discussion commits buffered items to server's database.
+        */
+        void CommitBufferedItemsL();
+
+    private: // private data
+    
+        /*! @var iSessionCount to indicate session count.*/
+        TInt iSessionCount;
+    	
+        /*! @var iBlacklistServerChunk global memory chunk.*/
+    	RChunk iBlacklistServerChunk;
+        
+        /*! @var iSqLiteConnection to handle database connections.*/
+        CMdSSqLiteConnection* iSqLiteConnection;
+        
+        /*! @var iDatabaseOpen flag to indicate if database is open or not.*/
+        TBool iDatabaseOpen;
+        
+        /*! @var iDBUpdateNeeded flag to indicate if databse need updating.*/
+        TBool iDBUpdateNeeded;
+        
+        /*! @var iBlacklistMemoryTable contains objects which are serialized to client.*/
+        RPointerArray<CBlacklistItem> iBlacklistMemoryTable;
+
+        /*! @var iBufferedRemoveItems contains all buferred removed items.*/
+        RPointerArray<RRowData> iBufferedRemoveItems;
+
+        /*! @var iBufferedAddedItems contains all buferred added items.*/
+        RPointerArray<RRowData> iBufferedAddedItems;
+
+        /*! @var iHandle server handle.*/
+        TInt iHandle;
+    };
+
+#endif // __BLACKLISTSERVER_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistserver/inc/blacklistsession.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,104 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef __SESSION_H__
+#define __SESSION_H__
+
+// SYSTEM INCLUDE
+#include <e32base.h>
+
+// FORWARD DECLERATIONS
+class CBlacklistServer;
+
+/*!
+  @class CBlacklistSession
+  @discussion An instance of the CBlacklistSession object 
+  */
+class CBlacklistSession : public CSession2
+    {
+    public:
+
+        /*!
+        @function CBlacklistSession
+        @discussion standard C++ constructor.
+        */
+        CBlacklistSession();
+        
+        /*!
+        @function CreateL
+        @discussion Adds session to server.
+        */
+        void CreateL();
+
+    private: // private functions
+ 
+         /*!
+        @function LoadBlacklistDataL
+        @discussion forward request to server to load blacklist.
+        @param aMessage, contains service request.
+        */
+        void LoadBlacklistDataL( const RMessage2& aMessage ); 
+        
+         /*!
+        @function AddL
+        @discussion forward request to server to add item to blacklist.
+        @param aMessage, contains added item's data.
+        */
+        void AddL( const RMessage2& aMessage );
+        
+         /*!
+        @function RemoveL
+        @discussion forward request to server to remove item from blacklist.
+        @param aMessage, contains removed item's data.
+        */
+        void RemoveL( const RMessage2& aMessage );  
+        
+         /*!
+        @function RemoveFromDBL
+        @discussion forward request to server to remove item from database.
+        @param aMessage, contains removed item's data.
+        */
+        void RemoveFromDBL( const RMessage2& aMessage );
+        
+         /*!
+        @function CloseDB
+        @discussion forward request to server to close database.
+        @param aMessage, empty, not used.
+        */
+        void CloseDB( const RMessage2& aMessage );  
+        
+         /*!
+        @function ~CBlacklistSession
+        @discussion standard C++ destructor. Send request to server to remove session.
+        */
+        ~CBlacklistSession();
+
+         /*!
+        @function Server
+        @discussion factory function.
+        @result returns reference to server.
+        */
+        CBlacklistServer& Server();
+        
+         /*!
+        @function ServiceL
+        @discussion handles service requests.
+        @param aMessage, contains service request.
+        */
+        void ServiceL( const RMessage2& aMessage );
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistserver/src/blacklistserver.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,766 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// USER INCLUDE
+#include "blacklistserver.h"
+#include "blacklistcommon.h"
+#include "blacklistsession.h"
+#include "blacklistitem.h"
+#include "harvesterlog.h"
+#include "mdssqliteconnection.h"
+#include "mdcserializationbuffer.h"
+
+#include <PathInfo.h>
+
+// Security policy
+const TUint KServerPolicyRangeCount = 6;
+// Database file without the drive letter
+_LIT( KBlacklistDatabaseFile, ":[2001B2EB]blacklistdb.sq" );
+
+const TInt KServerPolicyRanges[KServerPolicyRangeCount] =
+    {
+    EBlacklistAdd,
+    EBlacklistRemove,
+    EBlacklistRemoveFromDB,
+    EGetBlacklistData,
+    EBlacklistCloseDB,
+    EMaxService    
+    };
+
+const TUint8 KServerPolicyElementsIndex[KServerPolicyRangeCount] =
+    {
+    CPolicyServer::ECustomCheck, // EBlacklistAdd   
+    CPolicyServer::ECustomCheck, // EBlacklistRemove
+    CPolicyServer::ECustomCheck, // EBlacklistRemoveFromDB   
+    CPolicyServer::ECustomCheck, // EGetBlacklistData   
+    CPolicyServer::ECustomCheck, // EBlacklistCloseDB
+    CPolicyServer::ECustomCheck  // EMaxService  
+    };
+
+const CPolicyServer::TPolicy KServerPolicy =
+    {
+    CPolicyServer::EAlwaysPass, // specifies all connect attempts should pass
+    KServerPolicyRangeCount,                   
+    KServerPolicyRanges,
+    KServerPolicyElementsIndex,
+    NULL
+    };
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::CustomSecurityCheckL()
+// ---------------------------------------------------------------------------
+//
+CPolicyServer::TCustomResult CBlacklistServer::CustomSecurityCheckL(
+        const RMessage2& aMsg, TInt& /*aAction*/, TSecurityInfo& /*aMissing*/ )
+	{
+    WRITELOG( "CBlacklistServer::CustomSecurityCheckL - begin" );
+    
+    CPolicyServer::TCustomResult securityCheckResult = EFail;
+    
+    switch ( aMsg.Function() )
+    	{
+    	case EBlacklistAdd:
+    	case EBlacklistRemove:
+    	case EBlacklistRemoveFromDB:
+    	case EGetBlacklistData:
+    	case EBlacklistCloseDB:
+    	case EMaxService:
+		    {
+            if( aMsg.HasCapability( ECapabilityWriteDeviceData ) )
+                {
+                securityCheckResult = EPass;
+                }
+    		}
+            break;
+        default:
+            {
+            securityCheckResult = EFail;
+            }
+   	    }
+    
+    WRITELOG( "CBlacklistServer::CustomSecurityCheckL - end" );
+
+    return securityCheckResult;
+	}
+
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::CustomFailureActionL()
+// ---------------------------------------------------------------------------
+//
+CPolicyServer::TCustomResult CBlacklistServer::CustomFailureActionL(
+        const RMessage2& /*aMsg*/, TInt /*aAction*/, const TSecurityInfo& /*aMissing*/ )
+	{
+    WRITELOG( "CBlacklistServer::CustomFailureActionL" );
+
+    // Not used
+    return EFail;
+	}
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::NewL()
+// ---------------------------------------------------------------------------
+//
+CBlacklistServer* CBlacklistServer::NewL()
+    {
+    WRITELOG( "CBlacklistServer::NewL - begin" );
+
+    CBlacklistServer* self = NewLC();
+    CleanupStack::Pop( self );
+
+    WRITELOG( "CBlacklistServer::NewL - end" );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::NewLC()
+// ---------------------------------------------------------------------------
+//
+CBlacklistServer* CBlacklistServer::NewLC()
+    {
+    WRITELOG( "CBlacklistServer::NewLC - begin" );
+
+    CBlacklistServer* self = new( ELeave ) CBlacklistServer();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+
+    WRITELOG( "CBlacklistServer::NewLC - end" );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::CBlacklistServer()
+// ---------------------------------------------------------------------------
+//
+CBlacklistServer::CBlacklistServer() : 
+    CPolicyServer( CActive::EPriorityStandard, KServerPolicy, ESharableSessions )
+    {
+    }
+
+void CBlacklistServer::ConstructL()
+    {
+    WRITELOG( "CBlacklistServer::ConstructL - begin" );
+
+    TInt error = Start( KBlacklistServerName );
+
+    if ( error != KErrNone )
+        {
+        __ASSERT_DEBUG( EFalse, User::Panic( KBlacklistServerName, error ));
+        }
+    
+    iSqLiteConnection = CMdSSqLiteConnection::NewL();
+    
+    WRITELOG( "CBlacklistServer::ConstructL - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::~CBlacklistServer()
+// ---------------------------------------------------------------------------
+//
+CBlacklistServer::~CBlacklistServer()
+    {
+    WRITELOG( "CBlacklistServer::~CBlacklistServer - begin" );
+
+    if ( iDatabaseOpen )
+        {
+        if( iSqLiteConnection )
+            {
+            iSqLiteConnection->CloseDb();
+            }
+        }
+ 
+    iBlacklistMemoryTable.ResetAndDestroy();
+    iBlacklistMemoryTable.Close();
+   	
+   	
+    const TInt KRowCountRemovedItems = iBufferedRemoveItems.Count();
+
+    for( TInt i = 0; i < KRowCountRemovedItems; i++ )
+    	{
+    	iBufferedRemoveItems[i]->Close();
+    	}
+
+    iBufferedRemoveItems.ResetAndDestroy();
+    iBufferedRemoveItems.Close();  	
+   	
+    const TInt KRowCountAddedItems = iBufferedAddedItems.Count();
+
+    for( TInt i = 0; i < KRowCountAddedItems; i++ )
+    	{
+    	iBufferedAddedItems[i]->Close();
+    	}
+
+   	iBufferedAddedItems.ResetAndDestroy();
+    iBufferedAddedItems.Close();  	
+   	
+   	iBlacklistServerChunk.Close();
+ 
+    delete iSqLiteConnection;
+
+    WRITELOG( "CBlacklistServer::~CBlacklistServer - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// Closes database connection.
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::CloseDB()
+    {
+    WRITELOG( "CBlacklistServer::CloseDB - begin" );
+
+    if ( iDatabaseOpen )
+        {
+        iSqLiteConnection->CloseDb();
+        iDatabaseOpen = EFalse;
+        }
+
+    WRITELOG( "CBlacklistServer::CloseDB - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::ExeMainL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::ExeMainL()
+    {
+    WRITELOG( "CBlacklistServer::ExeMainL - begin" );
+
+    // Install active scheduler
+    CActiveScheduler* scheduler = new( ELeave ) CActiveScheduler;
+    CleanupStack::PushL( scheduler );
+    CActiveScheduler::Install( scheduler );
+
+    CBlacklistServer::NewLC();
+
+    User::LeaveIfError( User::RenameThread( KBlacklistServerName ) );
+    RProcess::Rendezvous( KErrNone );
+
+    CActiveScheduler::Start();
+
+    CleanupStack::PopAndDestroy( 2, scheduler );  
+
+    WRITELOG( "CBlacklistServer::ExeMainL - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// TInt E32Main()
+// ---------------------------------------------------------------------------
+//
+TInt E32Main()
+    {
+    WRITELOG( "CBlacklistServer::E32Main - begin" );
+ 
+    __UHEAP_MARK;
+
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    
+    TRAPD( error, CBlacklistServer::ExeMainL() );
+    __ASSERT_ALWAYS( !error, User::Panic( KBlacklistServerName, error ) );
+
+    delete cleanup;
+    __UHEAP_MARKEND;
+
+    WRITELOG( "CBlacklistServer::E32Main - end" );
+
+    return 0;
+    }
+
+
+// ---------------------------------------------------------------------------
+//  CBlacklistServer::OpenDatabaseL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::OpenDatabaseL()
+    {
+    WRITELOG( "CBlacklistServer::OpenDatabaseL - begin" );
+    
+    if ( iDatabaseOpen )
+        {
+        return; 
+        }
+    HBufC* databasePath = HBufC::NewLC( KMaxFileName );
+    TPtr pathPtr = databasePath->Des();
+    pathPtr.Append( PathInfo::PhoneMemoryRootPath()[0] );
+    pathPtr.Append( KBlacklistDatabaseFile );
+    iSqLiteConnection->OpenDbL( pathPtr );
+    iDatabaseOpen = ETrue; 
+    CleanupStack::PopAndDestroy( databasePath );
+
+    // Add or remove operations when DB connection was off  
+    if ( iDBUpdateNeeded )
+        {
+        CommitBufferedItemsL();        
+        }
+
+    if ( !TableExistsL() )
+        {
+        CreateBlacklistTableL();
+        }
+    
+    LoadDatabaseToMemoryL();
+    
+    // serialize it for client
+    SerializeToSharedMemoryL();
+
+    WRITELOG( "CBlacklistServer::OpenDatabaseL - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::SerializeToSharedMemoryL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::SerializeToSharedMemoryL()
+	{
+    WRITELOG( "CBlacklistServer::SerializeToSharedMemoryL - begin" );
+
+	TUint32 bufferSize = 0;
+	TUint32 blacklistMemoryTableCount = iBlacklistMemoryTable.Count();
+
+    // First add size for item count
+    bufferSize += CMdCSerializationBuffer::KRequiredSizeForTUint32;
+	
+    // Add size for items
+	for ( TInt i = 0; i < blacklistMemoryTableCount; ++i )
+		{
+		bufferSize += iBlacklistMemoryTable[i]->RequiredBufferSize();
+		}
+	
+	// create chunk
+	iBlacklistServerChunk.Close();
+	iHandle++;
+	HBufC* name = HBufC::NewLC( KBlacklistChunkName.iTypeLength + KMaxUintValueLength );
+   	*name = KBlacklistChunkName;
+	name->Des().AppendNum( iHandle );
+	User::LeaveIfError( iBlacklistServerChunk.CreateGlobal( *name, bufferSize, bufferSize ) );
+	
+	CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( iBlacklistServerChunk.Base(), bufferSize );
+	
+	// first inser table count
+	buffer->InsertL( blacklistMemoryTableCount );
+
+	// then items
+	
+	for ( TInt i = 0; i < blacklistMemoryTableCount; ++i )
+	    {
+   	    // add modified and media id field
+   	    buffer->InsertL( iBlacklistMemoryTable[i]->Modified() );
+   	    buffer->InsertL( iBlacklistMemoryTable[i]->MediaId() );
+   	    
+		// add uri
+       	const TDesC& uri =  *iBlacklistMemoryTable[i]->Uri();
+	    HBufC* lcUri = HBufC::NewLC( uri.Length() );
+		lcUri->Des().Append( uri );
+		buffer->InsertL( *lcUri );
+		CleanupStack::PopAndDestroy( lcUri ); 
+        lcUri = NULL;
+        }
+	
+	CleanupStack::PopAndDestroy( 2, name );
+    
+	// No need to keep these items anymore
+	iBlacklistMemoryTable.ResetAndDestroy();
+
+    WRITELOG( "CBlacklistServer::SerializeToSharedMemoryL - end" );
+	}
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::Handle() 
+// ---------------------------------------------------------------------------
+//
+TInt CBlacklistServer::MemoryHandle()
+    {
+    WRITELOG( "CBlacklistServer::MemoryHandle" );
+    return iHandle;
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::LoadDatabaseToMemoryL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::LoadDatabaseToMemoryL()
+    {
+    WRITELOG( "CBlacklistServer::LoadDatabaseToMemoryL - begin" );
+
+    iBlacklistMemoryTable.ResetAndDestroy();
+    RMdsStatement statement;
+    CleanupClosePushL( statement );
+    RRowData emptyRowData;
+    CleanupClosePushL( emptyRowData );
+
+    iSqLiteConnection->ExecuteQueryL( KMdsBlacklistCache, statement, emptyRowData );
+
+    TPtrC ptr = TPtrC( (TUint16*)0, 0 );
+    TInt64 modified = 0;
+    TUint32 mediaId = 0;
+    RRowData result;
+    CleanupClosePushL( result );
+    result.AppendL( TColumn( ptr ) );
+    result.AppendL( TColumn( mediaId ) );
+    result.AppendL( TColumn( modified ) );
+    while ( iSqLiteConnection->NextRowL( statement, result ) )
+        {
+        result.Column( 0 ).Get( ptr );      
+        result.Column( 1 ).Get( mediaId );
+        result.Column( 2 ).Get( modified );
+        AddToMemoryTableL( modified, ptr, mediaId );
+        result.Column( 0 ).Free();
+        }
+    
+    CleanupStack::PopAndDestroy( &result );        
+    CleanupStack::PopAndDestroy( &emptyRowData ); 
+    CleanupStack::PopAndDestroy( &statement ); 
+
+    WRITELOG( "CBlacklistServer::LoadDatabaseToMemoryL - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::CreateBlacklistTableL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::CreateBlacklistTableL()
+    {
+    WRITELOG( "CBlacklistServer::CreateBlacklistTableL - begin" );
+
+    RRowData emptyRowData;
+    CleanupClosePushL( emptyRowData );
+    iSqLiteConnection->ExecuteL( KDropBlacklistTable, emptyRowData );
+    iSqLiteConnection->ExecuteL( KCreateBlacklistTable, emptyRowData );
+	CleanupStack::PopAndDestroy( &emptyRowData );
+
+    WRITELOG( "CBlacklistServer::CreateBlacklistTableL - end" );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::AddToMemoryTableL
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::AddToMemoryTableL( const TInt64& aModified,
+        const TDesC& aUri, const TUint32 aMediaId )
+    {
+
+    WRITELOG( "CBlacklistServer::AddToMemoryTableL - begin" );
+
+    CBlacklistItem* item = CBlacklistItem::NewL( aModified, aUri, aMediaId );
+    const TInt err = iBlacklistMemoryTable.Append( item ); // ownership is transferred
+    if ( err != KErrNone )
+        {
+        delete item;
+        }
+
+    WRITELOG( "CBlacklistServer::AddToMemoryTableL - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::RemoveFromMemoryTable()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::RemoveFromMemoryTable( const TDesC& aUri,
+        const TUint32 aMediaId )
+    {
+
+    WRITELOG( "CBlacklistServer::RemoveFromMemoryTable - begin" );
+
+    TInt index = GetMemoryTableIndex( aUri, aMediaId );
+    if ( index >= 0 )
+        {
+        CBlacklistItem * item = iBlacklistMemoryTable[index];
+        delete item;
+        iBlacklistMemoryTable.Remove( index );
+        }
+
+    WRITELOG( "CBlacklistServer::RemoveFromMemoryTable - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::GetMemoryTableIndex()
+// ---------------------------------------------------------------------------
+//
+TInt CBlacklistServer::GetMemoryTableIndex( const TDesC& aUri, TUint32 aMediaId )
+    {
+    WRITELOG( "CBlacklistServer::GetMemoryTableIndex - begin" );
+
+    for ( TInt i( 0 ); i < iBlacklistMemoryTable.Count(); ++i )
+        {
+        if ( iBlacklistMemoryTable[i]->Compare( aUri, aMediaId ) )
+            {
+            return i;
+            }
+        }
+
+    WRITELOG( "CBlacklistServer::GetMemoryTableIndex - end" );
+    return KErrNotFound;
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::TableExistsL()
+// ---------------------------------------------------------------------------
+//
+TBool CBlacklistServer::TableExistsL()
+    {
+    WRITELOG( "CBlacklistServer::TableExistsL - begin" );
+
+    RMdsStatement validationQuery;
+    CleanupClosePushL( validationQuery );
+    RRowData emptyRowData;
+    CleanupClosePushL( emptyRowData );
+    TRAPD( err, iSqLiteConnection->ExecuteQueryL(
+    		KMdsBlacklistCheckTableExistence, validationQuery, emptyRowData ) );
+	validationQuery.Close();
+	CleanupStack::PopAndDestroy( &emptyRowData ); // emptyRowData
+	CleanupStack::PopAndDestroy( &validationQuery ); // validationQuery
+
+    WRITELOG( "CBlacklistServer::TableExistsL - end" );
+
+    return ( err == KErrNone );
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::NewSessionL()
+// ---------------------------------------------------------------------------
+//
+CSession2* CBlacklistServer::NewSessionL( const TVersion& aVersion, const RMessage2& /*aMessage*/ ) const
+    {
+    WRITELOG( "CBlacklistServer::NewSessionL - begin" );
+
+    // Check we are the right version
+    if ( !User::QueryVersionSupported( TVersion( KBlacklistServerMajorVersion,
+                                                 KBlacklistServerMinorVersion,
+                                                 KBlacklistServerBuildVersion ),
+                                       aVersion ) )
+    	{
+        User::Leave( KErrNotSupported );
+    	}
+    
+    WRITELOG( "CBlacklistServer::NewSessionL - end" );
+
+    return new( ELeave ) CBlacklistSession;
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::RunError()
+// ---------------------------------------------------------------------------
+//
+TInt CBlacklistServer::RunError( TInt aError )
+    {
+    WRITELOG1( "CBlacklistServer::RunError - begin, error %d", aError );
+
+    // Bad descriptor implies bad client
+    if ( aError == KErrBadDescriptor )
+        {
+        Message().Panic( KBlacklistServerName, aError );
+        }
+    else
+        {
+        Message().Complete( aError );
+        }
+
+    // Continue handling requests
+    ReStart();
+
+    WRITELOG( "CBlacklistServer::RunError - end" );
+
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::AddSession()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::AddSession()
+    {
+    WRITELOG( "CBlacklistServer::AddSession" );
+    ++iSessionCount;
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::RemoveSession()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::RemoveSession()
+    {
+    WRITELOG( "CBlacklistServer::RemoveSession - begin" );
+
+    --iSessionCount;
+    
+#ifdef _DEBUG
+    TRAPD ( err, WriteAllDataToDBL() );
+#else
+    TRAP_IGNORE ( WriteAllDataToDBL() );
+#endif
+    WRITELOG1( "CBlacklistServer::RemoveSession - err %d", err  );
+    
+    if ( iSessionCount == 0 )
+        {
+        CActiveScheduler::Stop();
+        }
+
+    WRITELOG( "CBlacklistServer::RemoveSession - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::AddL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::AddL( const TUint32& mediaId, const TDesC& aUri, const TTime& aLastModifiedTime ) 
+    {
+    WRITELOG( "CBlacklistServer::AddL - begin" );
+
+    AddToMemoryTableL( aLastModifiedTime.Int64(), aUri, mediaId );
+
+    WRITELOG( "CBlacklistServer::AddL - end" );
+    } 
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::RemoveL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::RemoveL( const TUint32& mediaId, const TDesC& aUri ) 
+    {
+    WRITELOG( "CBlacklistServer::RemoveL - begin" );
+
+    RemoveFromMemoryTable( aUri, mediaId );
+
+    WRITELOG( "CBlacklistServer::RemoveL - end" );
+    } 
+ 
+// ---------------------------------------------------------------------------
+// CBlacklistServer::RemoveFromDBL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::RemoveFromDBL( const TDesC& aUri, const TUint32 aMediaId )
+    {
+    WRITELOG( "CBlacklistServer::RemoveFromDBL - begin" );
+    
+    RRowData* variables = new ( ELeave ) RRowData();        
+    CleanupStack::PushL( variables );
+    CleanupClosePushL( *variables );
+ 
+    if ( !iDatabaseOpen )
+        {
+        // Add it to buffer, delete from database when DB connection opens
+        
+        HBufC* lcBuf = aUri.AllocLC();
+    
+        variables->AppendL( TColumn( lcBuf ) );     
+        variables->AppendL( TColumn( aMediaId ) );    
+ 
+        iBufferedRemoveItems.Append( variables ); // transfer ownership
+        iDBUpdateNeeded = ETrue;
+        CleanupStack::Pop( lcBuf );
+        CleanupStack::Pop( 2, variables );
+        }
+    else
+        {
+        // Database open, commit to DB
+        
+        variables->AppendL( TColumn( aUri ) );     
+        variables->AppendL( TColumn( aMediaId ) );    
+        
+        iSqLiteConnection->ExecuteL( KMdsBlacklistDelete, *variables );
+        CleanupStack::PopAndDestroy( 2, variables );
+        }
+    
+    WRITELOG( "CBlacklistServer::RemoveFromDBL - end" );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::AddDBL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::AddToDBL( const TDesC& aUri, const TUint32 aMediaId,
+    const TInt64& aLastModifiedTime ) 
+    {
+    WRITELOG( "CBlacklistServer::AddToDBL - begin" );
+  
+    RRowData* rowData = new ( ELeave ) RRowData();        
+    CleanupStack::PushL( rowData );
+    CleanupClosePushL( *rowData );
+    
+    if ( !iDatabaseOpen )
+        {
+        // Add it to buffer, add to database when DB connection opens
+        HBufC* lcBuf = aUri.AllocLC();
+
+        rowData->AppendL( TColumn( aLastModifiedTime ) );
+        rowData->AppendL( TColumn( lcBuf ) );     
+        rowData->AppendL( TColumn( aMediaId ) );    
+
+        iBufferedAddedItems.Append( rowData ); // transfer ownership
+        iDBUpdateNeeded = ETrue;
+        CleanupStack::Pop( lcBuf );
+        CleanupStack::Pop( 2, rowData );
+        }
+    else
+        {
+        rowData->AppendL( TColumn( aLastModifiedTime ) );
+        rowData->AppendL( TColumn( aUri ) );     
+        rowData->AppendL( TColumn( aMediaId ) );    
+       
+        TRAPD( err, iSqLiteConnection->ExecuteL( KMdsBlacklistInsert, *rowData ) );
+        if ( err == KSqlErrConstraint ) // is the file already blacklisted...
+            {
+            iSqLiteConnection->ExecuteL( KMdsBlacklistUpdate, *rowData );
+            }
+        CleanupStack::PopAndDestroy( 2, rowData );
+        }
+
+    WRITELOG( "CBlacklistServer::AddToDBL - end" );
+    } 
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::WriteAllDataToDBL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::WriteAllDataToDBL()
+    {
+    WRITELOG( "CBlacklistServer::WriteAllDataToDBL - begin" );
+
+    for ( TInt i( 0 ); i < iBlacklistMemoryTable.Count(); ++i )
+        {
+        AddToDBL(  *iBlacklistMemoryTable[i]->Uri(),  iBlacklistMemoryTable[i]->MediaId(), iBlacklistMemoryTable[i]->Modified() );
+        }
+
+    WRITELOG( "CBlacklistServer::WriteAllDataToDBL - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// CBlacklistServer::WriteAllDataToDBL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistServer::CommitBufferedItemsL()
+    {
+    WRITELOG( "CBlacklistServer::CommitBufferedItemsL - begin" );
+   
+    // First, removed items
+    for ( TInt i( 0 ); i < iBufferedRemoveItems.Count(); ++i )
+        {
+        iSqLiteConnection->ExecuteL( KMdsBlacklistDelete, *iBufferedRemoveItems[i] );
+        iBufferedRemoveItems[i]->Column( 0 ).Free();      
+        }
+   
+    // Second, added items
+    for ( TInt i( 0 ); i < iBufferedAddedItems.Count(); ++i )
+        {
+        iSqLiteConnection->ExecuteL( KMdsBlacklistUpdate, *iBufferedAddedItems[i] );
+        iBufferedAddedItems[i]->Column( 0 ).Free();  
+        }
+
+    WRITELOG( "CBlacklistServer::CommitBufferedItemsL - end" );
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/blacklistserver/src/blacklistsession.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,193 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// USER INCLUDE
+#include "blacklistsession.h"
+#include "blacklistserver.h"
+#include "blacklistcommon.h"
+
+// ---------------------------------------------------------------------------
+//  CBlacklistSession::CBlacklistSession()
+// ---------------------------------------------------------------------------
+//
+CBlacklistSession::CBlacklistSession()
+    {
+    }
+
+// ---------------------------------------------------------------------------
+//  CBlacklistSession::CreateL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistSession::CreateL()
+    {
+    Server().AddSession();
+    }
+
+// ---------------------------------------------------------------------------
+//  CBlacklistSession::~CBlacklistSession()
+// ---------------------------------------------------------------------------
+//
+CBlacklistSession::~CBlacklistSession()
+    {
+    Server().RemoveSession();
+    }
+
+// ---------------------------------------------------------------------------
+//  CBlacklistSession::Server()
+// ---------------------------------------------------------------------------
+//
+CBlacklistServer& CBlacklistSession::Server()
+    {
+    return *static_cast<CBlacklistServer*>( const_cast<CServer2*>(CSession2::Server()) );
+    }
+
+// ---------------------------------------------------------------------------
+//  CBlacklistSession::ServiceL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistSession::ServiceL( const RMessage2& aMessage )
+    {
+     switch ( aMessage.Function() )
+        {
+        case EGetBlacklistData:
+            {
+            LoadBlacklistDataL( aMessage );
+            break;
+            }    
+        case EBlacklistAdd:
+            {
+            AddL( aMessage );
+            break;
+            }    
+        case EBlacklistRemove:
+            {
+            RemoveL( aMessage );
+            break;
+            }    
+        case EBlacklistRemoveFromDB:
+            {
+            RemoveFromDBL( aMessage );
+            break;
+            }
+        case EBlacklistCloseDB:
+            {
+            CloseDB( aMessage );
+            break;
+            }
+        default:
+            {
+            aMessage.Complete( KErrNotSupported );
+            break;
+            }    
+        }
+    }
+
+// ---------------------------------------------------------------------------
+//  CBlacklistSession::LoadBlacklistDataL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistSession::LoadBlacklistDataL( const RMessage2& aMessage ) 
+    {
+    Server().OpenDatabaseL();
+    TPckgBuf<TInt> handleBuf( Server().MemoryHandle() );
+    aMessage.WriteL( 1, handleBuf );
+    aMessage.Complete( KErrNone );
+    }
+
+// ---------------------------------------------------------------------------
+//  CBlacklistSession::AddL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistSession::AddL( const RMessage2& aMessage ) 
+    {
+    TUint32 mediaId ( 0 );
+    TPckg<TUint32> mediaIdPckg( mediaId );
+    aMessage.ReadL( 0, mediaIdPckg );
+ 
+ 	RBuf uri;
+    uri.Create( aMessage.GetDesLength( 1 ) );
+    CleanupClosePushL( uri );
+    aMessage.ReadL( 1, uri );
+   	
+   	TTime lastModifiedTime ( 0 );
+    TPckg<TTime> lastModifiedTimePckg( lastModifiedTime );
+    aMessage.ReadL( 2, lastModifiedTimePckg );
+
+    Server().AddL( mediaId, uri, lastModifiedTime );
+
+    CleanupStack::PopAndDestroy( &uri );
+
+    aMessage.Complete( KErrNone );
+    }
+
+// ---------------------------------------------------------------------------
+//  CBlacklistSession::RemoveL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistSession::RemoveL( const RMessage2& aMessage ) 
+    {
+ 	RBuf uri;
+    uri.Create( aMessage.GetDesLength( 1 ) );
+    CleanupClosePushL( uri );
+    aMessage.ReadL( 1, uri );
+
+    TUint32 mediaId ( 0 );
+    TPckg<TUint32> mediaIdPckg( mediaId );
+    aMessage.ReadL( 2, mediaIdPckg );
+ 
+    Server().RemoveL( mediaId, uri );
+
+    CleanupStack::PopAndDestroy( &uri );
+   
+    aMessage.Complete( KErrNone );
+    }
+
+// ---------------------------------------------------------------------------
+//  CBlacklistSession::RemoveFromDBL()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistSession::RemoveFromDBL( const RMessage2& aMessage ) 
+    {
+ 	RBuf uri;
+    uri.Create( aMessage.GetDesLength( 1 ) );
+    CleanupClosePushL( uri );
+    aMessage.ReadL( 1, uri );
+
+    TUint32 mediaId ( 0 );
+    TPckg<TUint32> mediaIdPckg( mediaId );
+    aMessage.ReadL( 2, mediaIdPckg );
+
+    Server().RemoveFromDBL( uri, mediaId ); 
+
+    CleanupStack::PopAndDestroy( &uri );  
+
+    aMessage.Complete( KErrNone );
+    }
+
+// ---------------------------------------------------------------------------
+//  CBlacklistSession::CloseDB()
+// ---------------------------------------------------------------------------
+//
+void CBlacklistSession::CloseDB( const RMessage2& aMessage ) 
+    {
+    Server().CloseDB();
+    if( !aMessage.IsNull() )
+        {
+        aMessage.Complete( KErrNone );
+        }
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/bwincw/harvesterclientwinscw.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,15 @@
+EXPORTS
+	??0RHarvesterClient@@QAE@XZ @ 1 NONAME ; RHarvesterClient::RHarvesterClient(void)
+	?AddHarvesterEventObserver@RHarvesterClient@@QAEHAAVMHarvesterEventObserver@@HH@Z @ 2 NONAME ; int RHarvesterClient::AddHarvesterEventObserver(class MHarvesterEventObserver &, int, int)
+	?Close@RHarvesterClient@@QAEXXZ @ 3 NONAME ; void RHarvesterClient::Close(void)
+	?Connect@RHarvesterClient@@QAEHXZ @ 4 NONAME ; int RHarvesterClient::Connect(void)
+	?HarvestFile@RHarvesterClient@@QAEXABVTDesC16@@AAV?$RArray@K@@@Z @ 5 NONAME ABSENT ; void RHarvesterClient::HarvestFile(class TDesC16 const &, class RArray<unsigned long> &)
+	?Pause@RHarvesterClient@@QAEHXZ @ 6 NONAME ; int RHarvesterClient::Pause(void)
+	?RemoveHarvesterEventObserver@RHarvesterClient@@QAEHAAVMHarvesterEventObserver@@@Z @ 7 NONAME ; int RHarvesterClient::RemoveHarvesterEventObserver(class MHarvesterEventObserver &)
+	?RemoveObserver@RHarvesterClient@@QAEXPAVMHarvestObserver@@@Z @ 8 NONAME ; void RHarvesterClient::RemoveObserver(class MHarvestObserver *)
+	?Resume@RHarvesterClient@@QAEHXZ @ 9 NONAME ; int RHarvesterClient::Resume(void)
+	?SetObserver@RHarvesterClient@@QAEXPAVMHarvestObserver@@@Z @ 10 NONAME ; void RHarvesterClient::SetObserver(class MHarvestObserver *)
+	?Stop@RHarvesterClient@@QAEXXZ @ 11 NONAME ABSENT ; void RHarvesterClient::Stop(void)
+	?HarvestFile@RHarvesterClient@@QAEXABVTDesC16@@AAV?$RArray@K@@H@Z @ 12 NONAME ; void RHarvesterClient::HarvestFile(class TDesC16 const &, class RArray<unsigned long> &, int)
+	?HarvestFileWithUID@RHarvesterClient@@QAEXABVTDesC16@@AAV?$RArray@K@@HVTUid@@@Z @ 13 NONAME ; void RHarvesterClient::HarvestFileWithUID(class TDesC16 const &, class RArray<unsigned long> &, int, class TUid)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/eabi/harvesterclientarm.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,21 @@
+EXPORTS
+	_ZN16RHarvesterClient11HarvestFileERK7TDesC16R6RArrayImEi @ 1 NONAME
+	_ZN16RHarvesterClient11SetObserverEP16MHarvestObserver @ 2 NONAME
+	_ZN16RHarvesterClient14RemoveObserverEP16MHarvestObserver @ 3 NONAME
+	_ZN16RHarvesterClient25AddHarvesterEventObserverER23MHarvesterEventObserverii @ 4 NONAME
+	_ZN16RHarvesterClient28RemoveHarvesterEventObserverER23MHarvesterEventObserver @ 5 NONAME
+	_ZN16RHarvesterClient4StopEv @ 6 NONAME ABSENT
+	_ZN16RHarvesterClient5CloseEv @ 7 NONAME
+	_ZN16RHarvesterClient5PauseEv @ 8 NONAME
+	_ZN16RHarvesterClient6ResumeEv @ 9 NONAME
+	_ZN16RHarvesterClient7ConnectEv @ 10 NONAME
+	_ZN16RHarvesterClientC1Ev @ 11 NONAME
+	_ZN16RHarvesterClientC2Ev @ 12 NONAME
+	_ZTI18CHarvesterClientAO @ 13 NONAME ABSENT; #<TI>#
+	_ZTI25CHarvesterEventObserverAO @ 14 NONAME ABSENT; #<TI>#
+	_ZTV18CHarvesterClientAO @ 15 NONAME ABSENT; #<VT>#
+	_ZTV25CHarvesterEventObserverAO @ 16 NONAME ABSENT; #<VT>#
+	_ZN16RHarvesterClient18HarvestFileWithUIDERK7TDesC16R6RArrayImEi4TUid @ 17 NONAME
+	_ZTI22CHarvesterRequestQueue @ 18 NONAME ; #<TI>#
+	_ZTV22CHarvesterRequestQueue @ 19 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+harvesterclient.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/group/harvesterclient.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION           10.0
+TARGET            harvesterclient.dll
+TARGETTYPE        dll
+UID               0x1000008D 0x200009F4
+
+VENDORID        	VID_DEFAULT
+CAPABILITY 		CAP_CLIENT_DLL
+
+#if defined(WINSCW)
+deffile ../bwincw/harvesterclientwinscw.def
+#elif defined(ARMCC)
+deffile ../eabi/harvesterclientarm.def
+#endif
+nostrictdef
+
+USERINCLUDE       ../../../inc
+USERINCLUDE       ../../common/inc
+USERINCLUDE       ../inc
+
+SOURCEPATH        ../src
+SOURCE            harvesterclient.cpp
+SOURCE            harvesterclientao.cpp
+SOURCE            clientharvestitem.cpp
+SOURCE		      harvestereventobserverao.cpp 
+SOURCE            harvesterrequestactive.cpp
+SOURCE            harvesterrequestqueue.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY           euser.lib
+
+OPTION ARMCC -O3 -OTime
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/inc/clientharvestitem.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,72 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Client harvest item
+*
+*/
+
+
+#ifndef __CCLIENTHARVESTITEM_H__
+#define __CCLIENTHARVESTITEM_H__
+
+#include <e32base.h>
+
+#include "mdccommon.h"
+
+NONSHARABLE_CLASS( RClientHarvestItem )
+    {
+    public:
+        /**
+         * Constructor.
+         */
+        RClientHarvestItem();
+
+        /**
+         * Copy constructor.
+         */
+        RClientHarvestItem( const RClientHarvestItem& aItem );
+
+        /**
+         * Initialize with data.
+         */
+        void InitL( const TDesC& aURI, RArray<TItemId>& aAlbumIds );
+
+        /**
+         * Close (release memory).
+         */
+        void Close();
+
+        /**
+         * Resets the item. Releases memory.
+         */
+        void Reset();
+
+    private:
+
+        /** @var 	HBufC16* iUri;
+         *  @brief 	URI to harvest
+         */
+        HBufC16* iUri;
+
+        /** @var 	TTime iTimeStamp;
+         *  @brief  Timestamp for the file
+         */
+        TTime iTimeStamp;
+
+        /** @var 	RArray<TInt> iAlbumIds;
+         *  @brief  Album IDs
+         */
+        RArray<TItemId> iAlbumIds;
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/inc/harvesterclientao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,117 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester client active object
+*
+*/
+
+
+#ifndef __CHARVESTERCLIENTAO_H__
+#define __CHARVESTERCLIENTAO_H__
+
+#include <e32msgqueue.h>
+#include <e32base.h>
+#include <badesca.h>
+
+#include "harvesterclient.h"
+#include "clientharvestitem.h"
+
+class RHarvesterClient;
+class MHarvestObserver;
+
+NONSHARABLE_CLASS( CHarvesterClientAO ) : public CActive
+    {
+    public:
+        /**
+        * Construction.
+        */
+        static CHarvesterClientAO* NewL( RHarvesterClient &aHarvesterClient );
+
+        /**
+        * Destruction.
+        */
+        virtual ~CHarvesterClientAO();
+
+        /**
+        * Method for adding an observer.
+        * @param aObserver  Pointer to observer object.
+        */
+        void SetObserver( MHarvestObserver* aObserver );
+
+        /**
+        * Method for removing an observer.
+        * @param aObserver  Pointer to observer object.
+        */		
+        void RemoveObserver( MHarvestObserver* aObserver );
+        
+        void NotificateObserver( TInt aErr );
+        
+        /**
+         * Set AO to active state. RunL is launched from harvesting complete
+         * request which are subscribed from server.
+         */ 
+        void Active();
+        
+    protected:
+		
+        /**
+         * RunL.
+         * From CActive.
+         */
+        virtual void RunL();
+
+        /**
+         * DoCancel.
+         * From CActive.
+         */
+        virtual void DoCancel();
+
+        /**
+         * RunError for handling leaves occuring in RunL.
+         * From CActive.
+         */
+        virtual TInt RunError( TInt aError );
+
+    private:
+
+        /**
+        * Private constructor
+        * 
+        * @param aHarvesterClient Reference to session class
+        */	
+        CHarvesterClientAO( RHarvesterClient &aHarvesterClient );
+
+        /**
+        * 2nd phase construction
+        */	
+        void ConstructL();        
+		
+    private:
+
+        /**
+        * Observer of the class
+        */ 
+        MHarvestObserver* iObserver;
+
+        /**
+        * Reference to Harvester client session
+        */   	
+        RHarvesterClient& iHarvesterClient;
+
+        /**
+         * Harvester server assigned file name
+         */ 
+        TFileName iURI;
+    };
+
+#endif // __CHARVESTERCLIENTAO_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/inc/harvestereventobserverao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,114 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*/
+
+#ifndef HARVESTEREVENTOBSERVERAO_H
+#define HARVESTEREVENTOBSERVERAO_H
+
+#include <e32base.h>	// For CActive, link against: euser.lib
+#include <e32std.h>		// For RTimer, link against: euser.lib
+#include <e32msgqueue.h>
+
+#include "harvestercommon.h"
+
+class RHarvesterClient;
+class MHarvesterEventObserver;
+
+struct THarvesterEventObserver
+	{
+	MHarvesterEventObserver& iObserver;
+	THarvesterEventObserverInfo iObserverInfo;
+	
+	THarvesterEventObserver(MHarvesterEventObserver& aObserver) : iObserver(aObserver) {}
+	
+	static TInt CompareObserverIds(
+			const THarvesterEventObserver& aFirst, 
+			const THarvesterEventObserver& aSecond)
+		{
+		if( aFirst.iObserverInfo.iObserverId < aSecond.iObserverInfo.iObserverId )
+			{
+			return -1;
+			}
+		else if( aFirst.iObserverInfo.iObserverId > aSecond.iObserverInfo.iObserverId )
+			{
+			return 1;
+			}
+		else
+			{
+			return 0;
+			}
+		}
+	};
+
+NONSHARABLE_CLASS( CHarvesterEventObserverAO ) : public CActive
+	{
+public:
+	// Cancel and destroy
+	~CHarvesterEventObserverAO();
+
+	// Two-phased constructor.
+	static CHarvesterEventObserverAO* NewL( RHarvesterClient& aHC );
+
+	// Two-phased constructor.
+	static CHarvesterEventObserverAO* NewLC( RHarvesterClient& aHC );
+
+public:
+	// New functions
+	// Function for making the initial request
+	void AddHarvesterEventObserverL( 
+			MHarvesterEventObserver& aHarvesterEventObserver, 
+			TInt aHEObserverType,
+    		TInt aEventInterval );
+	
+	void RemoveHarvesterEventObserverL( MHarvesterEventObserver& aHarvesterEventObserver );
+
+private:	
+	// C++ constructor
+	CHarvesterEventObserverAO( RHarvesterClient& aHC );
+
+	// Second-phase constructor
+	void ConstructL();
+	
+	/**
+	 * Get next free observer ID
+	 * @return Observer ID
+	 */
+	TUint NextObserverId();
+
+	/**
+	 * Get handle to event queue. Creates event queue if it doesn't exist. 
+	 * @return Event queue handle
+	 */
+	RHandleBase& GetEventQueueHandleL();
+
+private:
+	// From CActive
+	// Handle completion
+	void RunL();
+
+	// How to cancel me
+	void DoCancel();
+
+	// Override to handle leaves from RunL(). Default implementation causes
+	// the active scheduler to panic.
+	TInt RunError(TInt aError);
+
+private:	
+	RPointerArray<THarvesterEventObserver> iObservers;
+	THarvesterEventQueue iHarvesterEventQueue;
+	RHarvesterClient& iHarvesterClient;
+	};
+
+#endif // HARVESTEREVENTOBSERVERAO_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/inc/harvesterrequestactive.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,187 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Active object for an asynchronous thumbnail request
+ *
+*/
+
+
+#ifndef HARVESTERREQUESTACTIVE_H
+#define HARVESTERREQUESTACTIVE_H
+
+#include <e32base.h>
+
+#include "harvesterclient.h"
+#include "harvestercommon.h"
+
+class CHarvesterRequestQueue;
+
+/**
+ *  Active object for an asynchronous harvest request.
+ *
+ *  @since S60 v5.0
+ */
+NONSHARABLE_CLASS( CHarvesterRequestActive ): public CActive
+    {
+public:
+
+    /**
+     * Destructor
+     *
+     * @since S60 v5.0
+     */
+    virtual ~CHarvesterRequestActive();
+
+    /**
+     * Two-phased constructor
+     *
+     * @since S60 v5.0
+     * @param aClient Session used.
+     * @param aObserver Observer to receive notifications about completed
+     *                  operations.
+     * @param aService service to call for
+     * @param aUri         Uri of the file to be harvested.
+     * @param aAlbumIds  If the harvested file is to be added to some albums, 
+     *                               the IDs of these albums..
+     * @param aAddLocation   Defines if locationdata is to be added to the harvested item.
+     * @param aQueue Queue for harvester calls
+     * @return New CHarvesterRequestActive object.
+     */
+    static CHarvesterRequestActive* NewL( 
+            RHarvesterClient& aClient, MHarvestObserver* aObserver,
+            TInt aService, const TDesC& aUri, 
+            HBufC8* aAlbumIds, TBool& aAddLocation,
+            CHarvesterRequestQueue* aQueue );
+
+    /**
+     * Start harvesting
+     *
+     * @since S60 v5.0
+     */
+    void Start();
+    
+    /**
+     * Forces the harvesting request to be sent to server immidiately
+     *
+     * @since S60 v5.0
+     */
+    void ForceHarvest();
+
+
+    /**
+     * Is request completed
+     *
+     * @since S60 v5.0
+     */
+    TBool RequestCompleted() const;
+
+private:
+
+    /**
+     * C++ default constructor
+     *
+     * @since S60 v5.0
+     * @param aClient Session used.
+     * @param aObserver Observer to receive notifications about completed
+     *                  operations.
+     * @param aService service to call for
+     * @param aUri         Uri of the file to be harvested.
+     * @param aAlbumIds  If the harvested file is to be added to some albums, 
+     *                               the IDs of these albums..
+     * @param aAddLocation   Defines if locationdata is to be added to the harvested item.
+     * @param aQueue Queue for harvester calls
+     * @return New CHarvesterRequestActive object.
+     */
+    CHarvesterRequestActive( RHarvesterClient& aClient,
+            MHarvestObserver* aObserver, TInt aService, const TDesC& aUri, 
+            HBufC8* aAlbumIds, TBool& aAddLocation,
+            CHarvesterRequestQueue* aQueue );
+
+    /**
+     * Handles an active object's request completion event.
+     *
+     * @since S60 v5.0
+     */
+    void RunL();
+
+    /**
+     * Handles a leave occurring in the request completion event handler
+     * RunL().
+     *
+     * @since S60 v5.0
+     * @param aError The leave code.
+     * @return Error code.
+     */
+    TInt RunError( TInt aError );
+
+    /**
+     * Implements cancellation of an outstanding request.
+     *
+     * @since S60 v5.0
+     */
+    void DoCancel();
+
+private:
+    // data
+
+    /**
+     * Session. Ref.
+     */
+    RHarvesterClient& iClient;
+
+    /**
+     * Observer to receive notifications about completed operations. Not owned.
+     */
+    MHarvestObserver* iObserver;
+    
+    TInt iService;
+    
+    /**
+     * Request parameters.
+     */
+    TFileName iUri;
+    
+    // Own.
+    HBufC8* iAlbumIds;
+
+    TBool iAddLocation;
+    
+    // not own
+    CHarvesterRequestQueue* iRequestQueue;
+    
+    TPckg<TBool> iLocation;
+    
+    TIpcArgs iPersistentArgs;
+    
+    /**
+     * Error code.
+     */
+    TInt iError;
+
+    /**
+     * If set, this request object can be deleted.
+     */
+    TBool iRequestCompleted;
+};
+
+#endif // HARVESTERREQUESTACTIVE_H
+
+
+
+// INLINE FUNCTIONS
+
+inline TBool CHarvesterRequestActive::RequestCompleted()const
+    {
+    return iRequestCompleted;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/inc/harvesterrequestqueue.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Processor object for running harvester requests
+*
+*/
+
+
+#ifndef HARVESTERREQUESTQUEUE_H
+#define HARVESTERREQUESTQUEUE_H
+
+#include <e32base.h>
+
+class CHarvesterRequestActive;
+
+/**
+ *  Processor object for running queued tasks.
+ *
+ *  @since S60 v5.0
+ */
+class CHarvesterRequestQueue: public CActive
+    {
+public:
+
+    /**
+     * Two-phased constructor.
+     *
+     * @since S60 v5.0
+     * @return Instance of CHarvesterRequestQueue.
+     */
+    static CHarvesterRequestQueue* NewL();
+
+    /**
+     * Destructor
+     *
+     * @since S60 v5.0
+     */
+    virtual ~CHarvesterRequestQueue();
+
+    /**
+     * Activates next request if possible.
+     *
+     * @since S60 v5.0
+     */
+    void Process();
+    
+    /**
+     * Adds new request to the queue.
+     *
+     * @since S60 v5.0
+     * @param aRequest Request to be added to the queue.
+     */
+    void AddRequestL( CHarvesterRequestActive* aRequest );
+    
+    /**
+     * Marks request completed.
+     *
+     * @since S60 v5.0
+     */
+    void RequestComplete();
+    
+    /**
+     * Force requests
+     *
+     * @since S60 v5.0
+     */
+    void ForceRequests();
+
+protected:
+    // from base class CActive
+
+    /**
+     * Handles an active object's request completion event.
+     *
+     * @since S60 v5.0
+     */
+    void RunL();
+
+    /**
+     * Implements cancellation of an outstanding request.
+     *
+     * @since S60 v5.0
+     */
+    void DoCancel();
+
+    /**
+     * Handles a leave occurring in the request completion event handler
+     * RunL().
+     *
+     * @since S60 v5.0
+     * @return Error code.
+     */
+    TInt RunError( TInt aError );
+
+private:
+
+    /**
+     * C++ default constructor
+     *
+     * @since S60 v5.0
+     * @return Instance of CHarvesterRequestQueue.
+     */
+    CHarvesterRequestQueue();
+
+    /**
+     * Symbian 2nd phase constructor can leave.
+     *
+     * @since S60 v5.0
+     */
+    void ConstructL();
+
+private:
+
+    /**
+     * Array of active objects for each pending harvester request.
+     */
+    RPointerArray <CHarvesterRequestActive> iRequests;
+    
+    // number of currently active requests
+    TInt iActiveRequests;
+    
+    TBool iShutdown;
+
+};
+
+#endif // HARVESTERREQUESTQUEUE_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/src/clientharvestitem.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Client harvest item implementation
+*
+*/
+
+
+#include "clientharvestitem.h"
+#include "harvesterlog.h"
+
+// ---------------------------------------------------------------------------
+// Constructor
+// ---------------------------------------------------------------------------
+//
+RClientHarvestItem::RClientHarvestItem()
+    {
+    WRITELOG( "RClientHarvestItem::RClientHarvestItem()" );
+    iUri = NULL;
+    }
+
+// ---------------------------------------------------------------------------
+// Copy constructor
+// ---------------------------------------------------------------------------
+//
+RClientHarvestItem::RClientHarvestItem( const RClientHarvestItem& aItem )
+    {
+    iUri = aItem.iUri;
+    iTimeStamp = aItem.iTimeStamp;
+    const TInt count = aItem.iAlbumIds.Count();
+    iAlbumIds.Reserve( count );
+    for ( TInt i = 0; i < count; i++ )
+        {
+        iAlbumIds.Append( aItem.iAlbumIds[i] );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// InitL
+// ---------------------------------------------------------------------------
+//
+void RClientHarvestItem::InitL( const TDesC& aUri, RArray<TItemId>& aAlbumIds ) 
+    {
+    if ( aUri.Length() <= 0 || aUri.Length() > KMaxFileName )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    this->Reset();
+
+    iTimeStamp.UniversalTime();
+    iUri = aUri.AllocL();
+    const TInt count = aAlbumIds.Count();
+    
+    iAlbumIds.Reserve( count );
+    for ( TInt i = 0; i < count; i++ )
+        {
+        iAlbumIds.Append( aAlbumIds[i] );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Reset
+// ---------------------------------------------------------------------------
+//
+void RClientHarvestItem::Reset() 
+    {
+    if ( iUri )
+        {
+        delete iUri;
+        iUri = NULL;
+        }
+
+    iAlbumIds.Reset();
+    }
+
+// ---------------------------------------------------------------------------
+// Close
+// ---------------------------------------------------------------------------
+//
+void RClientHarvestItem::Close()
+    {
+    Reset();
+    iAlbumIds.Close();
+    }
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/src/harvesterclient.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,546 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester Client implementation*
+*/
+
+#include <e32property.h> 
+
+#include "harvesterclient.h"
+#include "harvestercommon.h"
+#include "harvesterrequestqueue.h"
+#include "harvestereventobserverao.h"
+#include "harvesterlog.h"
+#include "harvesterclientao.h"
+#include "mdsutils.h"
+#include "harvesterrequestactive.h"
+#include "mdscommoninternal.h"
+
+/** @var Message slots */
+const TInt KDefaultMessageSlots = -1;  // Global pool
+
+/* Server name */
+_LIT( KHarvesterServerName, "HarvesterServer" );
+
+/* Harvester Server process location */
+_LIT( KHarvesterServerExe, "harvesterserver.exe" );
+
+// FUNCTION PROTOTYPES
+static TInt StartServer();
+static TInt CreateServerProcess();
+
+
+// ----------------------------------------------------------------------------------------
+// RHarvesterClient
+// ----------------------------------------------------------------------------------------
+//
+EXPORT_C RHarvesterClient::RHarvesterClient() : RSessionBase() 
+    {
+    WRITELOG( "RHarvesterClient::RHarvesterClient() - Constructor" );
+    iHarvesterClientAO = NULL;
+    iObserver = NULL;
+    iHEO = NULL;
+    iRequestQueue = NULL;
+    }
+
+// ----------------------------------------------------------------------------------------
+// Connect
+// ----------------------------------------------------------------------------------------
+//
+EXPORT_C TInt RHarvesterClient::Connect()
+    {
+    WRITELOG( "RHarvesterClient::Connect()" );
+
+    RProperty property;
+    const TInt error( property.Attach( KHarvesterPSShutdown, KShutdown, EOwnerThread ) );
+    TInt value = 0;
+    property.Get( value );
+    property.Close();
+
+    if ( error != KErrNone || value > KErrNone )
+        {
+        return KErrLocked;
+        }
+    
+    if( iHarvesterClientAO )
+    	{
+    	return KErrAlreadyExists;
+    	}
+    
+    TRAPD( err, iHarvesterClientAO = CHarvesterClientAO::NewL(*this) );
+    if ( err != KErrNone )
+        {
+        WRITELOG( "RHarvesterClient::RHarvesterClient() - Couldn't create active object" );
+        return err;
+        }
+    
+    // request processor
+    TRAP( err, iRequestQueue = CHarvesterRequestQueue::NewL() )
+        {
+        if ( err != KErrNone )
+            {
+            WRITELOG( "RHarvesterClient::RHarvesterClient() - Couldn't create harvester request queue" );
+            delete iHarvesterClientAO;
+            iHarvesterClientAO = NULL;
+            return err;
+            }
+        }
+    
+    err = ::StartServer();
+
+    if ( err == KErrNone || err == KErrAlreadyExists )
+        {
+        WRITELOG( "RHarvesterClient::Connect() - creating session" );
+        err = CreateSession( KHarvesterServerName, Version(), KDefaultMessageSlots );
+        }
+    else
+        {
+        delete iHarvesterClientAO;
+        iHarvesterClientAO = NULL;
+        delete iRequestQueue;
+        iRequestQueue = NULL;
+        }
+
+#ifdef _DEBUG
+    if ( err != KErrNone )
+        {
+        WRITELOG( "RHarvesterClient::Connect() - Server is not running or could not be started" );
+        }
+    else
+        {
+        WRITELOG1( "RHarvesterClient::Connect() - no errors: %d", err );
+        }
+    WRITELOG( "RHarvesterClient::Connect() - end" );
+#endif
+
+    iHEO = NULL;
+    
+    return err;
+    }
+
+// ----------------------------------------------------------------------------------------
+// Pause
+// ----------------------------------------------------------------------------------------
+//
+EXPORT_C TInt RHarvesterClient::Pause()
+    {
+    WRITELOG( "RHarvesterClient::Pause() -  sending command EPauseHarvester" );
+    if( iHandle )
+    	{
+    	return SendReceive( EPauseHarvester );
+       	}
+    return KErrDisconnected;
+    }
+
+// ----------------------------------------------------------------------------------------
+// Resume
+// ----------------------------------------------------------------------------------------
+//
+EXPORT_C TInt RHarvesterClient::Resume()
+    {
+    WRITELOG( "RHarvesterClient::Resume() -  sending command EResumeHarvester" );
+    if( iHandle )
+    	{
+    	return SendReceive( EResumeHarvester );
+    	}
+    return KErrDisconnected;
+    }
+
+// ----------------------------------------------------------------------------------------
+// Close
+// ----------------------------------------------------------------------------------------
+//
+EXPORT_C void RHarvesterClient::Close()
+    {
+    WRITELOG( "RHarvesterClient::Close()" );
+    
+    // cancels Harvest Complete request if it exist at server
+    UnregisterHarvestComplete();
+    
+    WRITELOG( "RHarvesterClient::Close() - UnregisterHarvest done" );
+    
+    iRequestQueue->ForceRequests();
+    
+    delete iRequestQueue;
+    iRequestQueue = NULL;
+    
+    delete iHarvesterClientAO;
+    iHarvesterClientAO = NULL;
+    
+    delete iHEO;
+    iHEO = NULL;
+    
+    WRITELOG( "RHarvesterClient::Close() - Closing session" );
+    
+    RSessionBase::Close();
+    }
+
+// ----------------------------------------------------------------------------------------
+// SetObserver
+// ----------------------------------------------------------------------------------------
+//
+EXPORT_C void RHarvesterClient::SetObserver( MHarvestObserver* aObserver )
+    {
+    WRITELOG( "RHarvesterClient::SetObserver()" );
+
+    if ( iHarvesterClientAO )
+        {
+       iHarvesterClientAO->SetObserver( aObserver );
+       }
+	iObserver = aObserver;
+    }
+
+// ----------------------------------------------------------------------------------------
+// RemoveObserver
+// ----------------------------------------------------------------------------------------
+//
+EXPORT_C void RHarvesterClient::RemoveObserver( MHarvestObserver* aObserver )
+    {
+    WRITELOG( "RHarvesterClient::RemoveObserver()" );
+    
+    if ( iHarvesterClientAO )
+        {
+        iHarvesterClientAO->RemoveObserver( aObserver );
+        }
+    
+	if ( aObserver == iObserver )
+		{
+		if ( iObserver )
+			{
+			WRITELOG( "CHarvesterClientAO::RemoveObserver() - deleting observer" );
+			iObserver = NULL;
+			}
+		}
+    }
+
+// ----------------------------------------------------------------------------------------
+// AddHarvesterEventObserver
+// ----------------------------------------------------------------------------------------
+//
+EXPORT_C TInt RHarvesterClient::AddHarvesterEventObserver( 
+	MHarvesterEventObserver& aHarvesterEventObserver, 
+	TInt aHEObserverType,
+	TInt aEventInterval )
+	{
+	TInt err( 0 );
+	if( !iHEO )
+	    {
+        TRAP( err, iHEO = CHarvesterEventObserverAO::NewL( *this ) );
+        if ( err != KErrNone )
+            {
+            WRITELOG( "RHarvesterClient::RHarvesterClient() - Couldn't create harvester event observer" );
+            return err;
+            }
+	    }
+	
+	TRAP(err, iHEO->AddHarvesterEventObserverL(
+			aHarvesterEventObserver,
+			aHEObserverType,
+			aEventInterval ));
+	
+	return err;
+	}
+
+// ----------------------------------------------------------------------------------------
+// RemoveObserver
+// ----------------------------------------------------------------------------------------
+//
+EXPORT_C TInt RHarvesterClient::RemoveHarvesterEventObserver( MHarvesterEventObserver& aHarvesterEventObserver )
+	{
+	TRAPD( err, iHEO->RemoveHarvesterEventObserverL( aHarvesterEventObserver ) );
+	
+	return err;
+	}
+
+// ----------------------------------------------------------------------------------------
+// HarvestFile
+// ----------------------------------------------------------------------------------------
+//
+EXPORT_C void RHarvesterClient::HarvestFile( const TDesC& aURI, RArray<TItemId>& aAlbumIds, TBool aAddLocation )
+    {
+    WRITELOG1( "RHarvesterClient::HarvestFile() - file %S", &aURI );
+    
+    HBufC8* paramBuf = NULL;
+    TRAPD( err, paramBuf = SerializeArrayL( aAlbumIds ) );
+    if ( err )
+    	{
+        WRITELOG1( "RHarvesterClient::HarvestFile() - cannot create serialized array, error: %d", err );
+        if( iObserver )
+            {
+            iObserver->HarvestingComplete( const_cast<TDesC&>(aURI), err );  
+            }
+    	return;
+    	}
+        
+    CHarvesterRequestActive* harvestFileActive( NULL );
+    TRAP( err, harvestFileActive = CHarvesterRequestActive::NewL( *this, iObserver, (TInt)EHarvestFile, aURI, 
+                                                                                                   paramBuf, aAddLocation, iRequestQueue ) );
+    if( err )
+        {
+        WRITELOG1( "RHarvesterClient::HarvestFile() - cannot create harvesting request, error: %d", err );
+        if( iObserver )
+            {
+            iObserver->HarvestingComplete( const_cast<TDesC&>(aURI), err );  
+            }
+        return;
+        }
+
+    // send actually harvest request to server
+    if( iHandle )
+        {
+        TRAP( err, iRequestQueue->AddRequestL( harvestFileActive ) );
+        if( err && iObserver)
+            {
+            WRITELOG1( "RHarvesterClient::HarvestFile() - cannot not send harvest request to server, error: %d", KErrServerBusy );
+            iObserver->HarvestingComplete( const_cast<TDesC&>(aURI), KErrServerBusy );  
+            delete harvestFileActive;
+            }
+        else if( err )
+            {
+            WRITELOG1( "RHarvesterClient::HarvestFile() - cannot not send harvest request to server, error: %d", KErrServerBusy );
+            delete harvestFileActive;
+            }
+        else
+            {
+            WRITELOG( "RHarvesterClient::HarvestFile() - harvesting request added to queue" );
+            iRequestQueue->Process();
+            }
+        }
+    else if( iObserver )
+        {
+        WRITELOG1( "RHarvesterClient::HarvestFile() - cannot not send harvest request to server, error: %d", KErrDisconnected );
+        iObserver->HarvestingComplete( const_cast<TDesC&>(aURI), KErrDisconnected );  
+        delete harvestFileActive;
+        }
+    else
+        {
+        WRITELOG1( "RHarvesterClient::HarvestFile() - cannot not send harvest request to server, error: %d", KErrDisconnected );
+        delete harvestFileActive;
+        }
+    WRITELOG( "RHarvesterClient::HarvestFile() - end" );
+    }
+
+// ----------------------------------------------------------------------------------------
+// HarvestFileWithUID
+// ----------------------------------------------------------------------------------------
+//
+EXPORT_C void RHarvesterClient::HarvestFileWithUID( const TDesC& aURI, 
+                                                                                         RArray<TItemId>& aAlbumIds, 
+                                                                                         TBool aAddLocation,
+                                                                                         TUid /*aUid*/ )
+    {
+    WRITELOG1( "RHarvesterClient::HarvestFileWithUID() - file %S", &aURI );
+    
+    HBufC8* paramBuf = NULL;
+    TRAPD( err, paramBuf = SerializeArrayL( aAlbumIds ) );
+    if ( err )
+        {
+        WRITELOG1( "RHarvesterClient::HarvestFileWithUID() - cannot create serialized array, error: %d", err );
+        if( iObserver )
+            {
+            iObserver->HarvestingComplete( const_cast<TDesC&>(aURI), err );  
+            }
+        return;
+        }
+
+    CHarvesterRequestActive* harvestFileActive( NULL );
+    TRAP( err, harvestFileActive = CHarvesterRequestActive::NewL( *this, iObserver, (TInt)EHarvestFile, aURI, 
+                                                                                                   paramBuf, aAddLocation, iRequestQueue ) );
+    if( err )
+        {
+        WRITELOG1( "RHarvesterClient::HarvestFile() - cannot create harvesting request, error: %d", err );
+        if( iObserver )
+            {
+            iObserver->HarvestingComplete( const_cast<TDesC&>(aURI), err );  
+            }
+        return;
+        }
+
+    // send actually harvest request to server
+    if( iHandle )
+        {
+        TRAP( err, iRequestQueue->AddRequestL( harvestFileActive ) );
+        if( err && iObserver)
+            {
+            WRITELOG1( "RHarvesterClient::HarvestFile() - cannot not send harvest request to server, error: %d", KErrServerBusy );
+            iObserver->HarvestingComplete( const_cast<TDesC&>(aURI), KErrServerBusy );  
+            delete harvestFileActive;
+            }
+        else if( err )
+            {
+            WRITELOG1( "RHarvesterClient::HarvestFile() - cannot not send harvest request to server, error: %d", KErrServerBusy );
+            delete harvestFileActive;
+            }
+        else
+            {
+            iRequestQueue->Process();
+            }
+        }
+    else if( iObserver )
+        {
+        WRITELOG1( "RHarvesterClient::HarvestFile() - cannot not send harvest request to server, error: %d", KErrDisconnected );
+        iObserver->HarvestingComplete( const_cast<TDesC&>(aURI), KErrDisconnected );  
+        delete harvestFileActive;
+        }
+    else
+        {
+        WRITELOG1( "RHarvesterClient::HarvestFile() - cannot not send harvest request to server, error: %d", KErrDisconnected );
+        delete harvestFileActive;
+        }
+    }
+
+// ----------------------------------------------------------------------------------------
+// RegisterHarvestComplete
+// ----------------------------------------------------------------------------------------
+//
+void RHarvesterClient::RegisterHarvestComplete(TDes& aURI, TRequestStatus& aStatus)
+	{	
+	TIpcArgs ipcArgs( &aURI );
+	
+	if( !iHandle )
+		{
+		return;
+		}
+	SendReceive( ERegisterHarvestComplete, ipcArgs, aStatus);
+	}
+
+
+// ----------------------------------------------------------------------------------------
+// UnregisterHarvestComplete
+// ----------------------------------------------------------------------------------------
+//
+void RHarvesterClient::UnregisterHarvestComplete()
+	{
+	if( !iHandle )
+		{
+		return;
+		}	
+	
+	Send( EUnregisterHarvestComplete );
+	}
+
+// ----------------------------------------------------------------------------------------
+// HarvestFile
+// ----------------------------------------------------------------------------------------
+//
+void RHarvesterClient::HarvestFile( TInt& aService, TIpcArgs& aArgs, TRequestStatus& aStatus )
+    {
+    // send to server harvesting complete observer
+    iHarvesterClientAO->Active();
+    SendReceive( aService, aArgs, aStatus );
+    }
+
+// ----------------------------------------------------------------------------------------
+// ForceHarvestFile
+// ----------------------------------------------------------------------------------------
+//
+void RHarvesterClient::ForceHarvestFile( TInt& aService, TIpcArgs& aArgs )
+    {
+    // send to server harvesting complete observer
+    iHarvesterClientAO->Active();
+    SendReceive( aService, aArgs );
+    }
+
+// ----------------------------------------------------------------------------------------
+// Version
+// ----------------------------------------------------------------------------------------
+//
+TVersion RHarvesterClient::Version() const
+    {
+    WRITELOG( "RHarvesterClient::Version()" );
+        
+    return TVersion( KHarvesterServerMajorVersion, KHarvesterServerMinorVersion,
+    	KHarvesterServerBuildVersion );
+    }
+
+// ----------------------------------------------------------------------------------------
+// StartServer
+// ----------------------------------------------------------------------------------------
+//
+static TInt StartServer()
+    {
+    WRITELOG( "StartServer() - begin" );
+    
+    TFindServer findHarvesterServer( KHarvesterServerName );
+    TFullName name;
+
+    TInt result = findHarvesterServer.Next( name );
+    if ( result == KErrNone )
+        {
+        WRITELOG( "StartServer() - Server allready running" );
+        
+        // Server already running
+        return KErrNone;
+        }
+    else
+        {
+        WRITELOG1( "StartServer() error - error code: %d", result );
+        }
+    
+    result = CreateServerProcess();
+    if ( result != KErrNone )
+        {
+        WRITELOG1( "StartServer() - creating process failed, error: %d", result );
+        }
+    
+    WRITELOG( "StartServer() - end" ); 
+    return result;
+    }
+
+// ----------------------------------------------------------------------------------------
+// CreateServerProcess
+// ----------------------------------------------------------------------------------------
+//
+static TInt CreateServerProcess()
+    {
+    WRITELOG( "CreateServerProcess() - begin" );
+    RProcess server;
+    TInt result = server.Create( KHarvesterServerExe, KNullDesC );
+
+    if( result == KErrAlreadyExists )
+    	{
+    	return KErrNone;
+    	}
+    
+    if ( result != KErrNone )
+        {
+        WRITELOG1( "CreateServerProcess() - failed to create server process, error: %d", result );
+        return result;
+        }
+ 
+    TRequestStatus stat( 0 );
+    server.Rendezvous( stat );
+    
+    if ( stat != KRequestPending )
+        {
+        server.Kill( 0 );     // abort startup
+        }
+    else
+        {
+        server.Resume();    // logon OK - start the server
+        }        
+    
+    User::WaitForRequest( stat ); // wait for start or death
+    // we can't use the 'exit reason' if the server panicked as this
+    // is the panic 'reason' and may be '0' wehich cannot be distinguished
+    // from KErrNone
+    result = ( server.ExitType() == EExitPanic ) ? KErrCommsBreak : stat.Int();
+    server.Close();
+    
+    WRITELOG( "CreateServerProcess() - end" );
+    
+    return result;
+    }
+
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/src/harvesterclientao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,163 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester client active object
+*
+*/
+
+
+#include "harvesterclientao.h"
+#include "harvestercommon.h"
+#include "harvesterlog.h"
+#include "mdsutils.h"
+
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CHarvesterClientAO* CHarvesterClientAO::NewL( RHarvesterClient& aHarvesterClient )
+	{
+    WRITELOG( "CHarvesterClientAO::NewL()" );
+	CHarvesterClientAO* self = new (ELeave) CHarvesterClientAO( aHarvesterClient );
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// ~CHarvesterClientAO
+// ---------------------------------------------------------------------------
+//
+CHarvesterClientAO::~CHarvesterClientAO() // destruct
+	{   
+    WRITELOG( "CHarvesterClientAO::~CHarvesterClientAO()" );
+    Cancel();
+ 	}
+
+// ---------------------------------------------------------------------------
+// CHarvesterClientAO
+// First-phase C++ constructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterClientAO::CHarvesterClientAO( RHarvesterClient& aHarvesterClient )
+    : CActive( CActive::EPriorityStandard ), 
+    iObserver( NULL ),
+    iHarvesterClient( aHarvesterClient )
+  	{
+    WRITELOG( "CHarvesterClientAO::CHarvesterClientAO()" );
+	}
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterClientAO::ConstructL() // second-phase constructor
+	{
+    WRITELOG( "CHarvesterClientAO::ConstructL()" );    
+    CActiveScheduler::Add( this );
+	}
+
+// ---------------------------------------------------------------------------
+// SetObserver
+// ---------------------------------------------------------------------------
+//
+void CHarvesterClientAO::SetObserver( MHarvestObserver* aObserver )
+	{
+	WRITELOG( "CHarvesterClientAO::SetObserver()" );
+	iObserver = aObserver;
+	}
+
+// ---------------------------------------------------------------------------
+// RemoveObserver
+// ---------------------------------------------------------------------------
+//	
+void CHarvesterClientAO::RemoveObserver( MHarvestObserver* aObserver )
+	{
+	WRITELOG( "CHarvesterClientAO::RemoveObserver()" );
+	if ( aObserver == iObserver )
+		{
+		if ( iObserver )
+			{
+			WRITELOG( "CHarvesterClientAO::RemoveObserver() - deleting observer" );
+			iObserver = NULL;
+			}
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// DoCancel
+// ---------------------------------------------------------------------------
+//
+void CHarvesterClientAO::DoCancel()
+	{
+	WRITELOG( "CHarvesterClientAO::DoCancel()" );
+	}
+	
+// ---------------------------------------------------------------------------
+// Active
+// ---------------------------------------------------------------------------
+//
+void CHarvesterClientAO::Active()
+	{	
+	if (!IsActive())
+		{
+		iHarvesterClient.RegisterHarvestComplete(iURI, iStatus);
+		SetActive();
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// RunL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterClientAO::RunL()
+	{
+	WRITELOG( "CHarvesterClientAO::RunL()" );
+
+	const TInt status = iStatus.Int();
+	
+    if ( status < KErrNone )
+        {
+        WRITELOG1( "CHarvesterClientAO::RunL() - Error occured while harvesting, error:%d", status );
+        }
+
+	// Callback to client process
+	if ( iObserver )
+		{
+		WRITELOG( "CHarvesterClientAO::RunL() - ECompleteRequest - calling callback" );
+		iObserver->HarvestingComplete( iURI, status );
+		}
+	
+	// if the request was not canceled or server is not terminated, Activating AO again
+	if ( status != KErrCancel && status != KErrServerTerminated )
+		{
+		Active();
+		}
+	}
+	
+// ---------------------------------------------------------------------------
+// RunError
+// ---------------------------------------------------------------------------
+//	
+#ifdef _DEBUG
+TInt CHarvesterClientAO::RunError( TInt aError )
+#else
+TInt CHarvesterClientAO::RunError( TInt )
+#endif
+    {
+    WRITELOG1( "CHarvesterClientAO::RunError(), errorcode: %d", aError );
+    
+    return KErrNone;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/src/harvestereventobserverao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,207 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+#include <e32svr.h>
+#include <harvestereventenum.h>
+
+#include "harvestereventobserverao.h"
+#include "harvesterclient.h"
+
+const TInt KHarverterEventQueueSize = 32;
+
+CHarvesterEventObserverAO::CHarvesterEventObserverAO( 
+		RHarvesterClient& aHarvesterClient ) :
+	CActive(CActive::EPriorityStandard), // Standard priority
+	iHarvesterClient( aHarvesterClient )
+	{
+	}
+
+CHarvesterEventObserverAO* CHarvesterEventObserverAO::NewLC( 
+		RHarvesterClient& aHarvesterClient )
+	{
+	CHarvesterEventObserverAO* self = 
+		new ( ELeave ) CHarvesterEventObserverAO( aHarvesterClient );
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+	}
+
+CHarvesterEventObserverAO* CHarvesterEventObserverAO::NewL( 
+		RHarvesterClient& aHarvesterClient )
+	{
+	CHarvesterEventObserverAO* self = 
+		CHarvesterEventObserverAO::NewLC( aHarvesterClient );
+	CleanupStack::Pop( self ); // self;
+	return self;
+	}
+
+void CHarvesterEventObserverAO::ConstructL()
+	{
+	CActiveScheduler::Add( this ); // Add to scheduler
+	}
+
+CHarvesterEventObserverAO::~CHarvesterEventObserverAO()
+	{
+	Cancel(); // Cancel any request, if outstanding
+
+	for(TInt i = iObservers.Count(); --i >= 0;)
+		{
+		THarvesterEventObserver& observer = *(iObservers[i]);
+
+		TIpcArgs ipcArgs( observer.iObserverInfo.iObserverId, 
+				iHarvesterEventQueue.Handle() );
+
+		iHarvesterClient.Send( EUnregisterHarvesterEvent, ipcArgs );
+		}
+
+	iHarvesterEventQueue.Close();
+	
+	iObservers.ResetAndDestroy();
+	}
+
+void CHarvesterEventObserverAO::DoCancel()
+	{
+	iHarvesterEventQueue.CancelDataAvailable();
+	}
+
+void CHarvesterEventObserverAO::AddHarvesterEventObserverL( 
+			MHarvesterEventObserver& aHarvesterEventObserver, 
+			TInt aHEObserverType,
+    		TInt aNotificationInterval )
+	{
+	RHandleBase& queueHandle = GetEventQueueHandleL();
+
+	THarvesterEventObserver* observer = 
+			new (ELeave) THarvesterEventObserver( aHarvesterEventObserver );
+	CleanupStack::PushL( observer );
+
+	// Init client side values
+	observer->iObserverInfo.iQueueHandle = queueHandle.Handle();
+	observer->iObserverInfo.iObserverId = NextObserverId();
+	observer->iObserverInfo.iObserverType = aHEObserverType;
+	observer->iObserverInfo.iNotificationInterval = aNotificationInterval;
+
+	iObservers.AppendL( observer );
+
+	CleanupStack::Pop( observer );
+
+	TPckg<THarvesterEventObserverInfo> pckgObserverInfo( observer->iObserverInfo );
+	TIpcArgs ipcArgs( &pckgObserverInfo, queueHandle );
+
+	TInt err = iHarvesterClient.SendReceive( ERegisterHarvesterEvent, ipcArgs );
+
+	User::LeaveIfError( err );
+
+	if( !IsActive() )
+		{
+		iHarvesterEventQueue.NotifyDataAvailable( iStatus );
+		SetActive(); // Tell scheduler a request is active
+		}
+	}
+
+void CHarvesterEventObserverAO::RemoveHarvesterEventObserverL( 
+		MHarvesterEventObserver& aHarvesterEventObserver )
+	{
+	// clear all observers which match to callback instance
+	for(TInt i = iObservers.Count(); --i >= 0;)
+		{
+		THarvesterEventObserver* observer = iObservers[i];
+		if( &observer->iObserver == &aHarvesterEventObserver )
+			{
+			TIpcArgs ipcArgs( observer->iObserverInfo.iObserverId, 
+							iHarvesterEventQueue.Handle() );
+			iHarvesterClient.Send( EUnregisterHarvesterEvent, ipcArgs );
+			iObservers.Remove( i );
+			delete observer;
+			}
+		}
+
+	// close event queue if all observers are removed
+	if( iObservers.Count() == 0 )
+		{
+		Cancel();
+		iHarvesterEventQueue.Close();
+		}
+	}
+
+void CHarvesterEventObserverAO::RunL()
+	{
+	User::LeaveIfError( iStatus.Int() );
+
+	THarvesterEventNotification received;
+	while( iHarvesterEventQueue.Receive( received ) != KErrUnderflow )
+		{
+		for(TInt i = iObservers.Count(); --i >= 0;)
+			{
+			THarvesterEventObserver& observer = *(iObservers[i]);
+			if( observer.iObserverInfo.iObserverId == received.iObserverId )
+				{
+				observer.iObserver.HarvestingUpdated( received.iObserverType,  
+						received.iCurrentState, received.iItemsLeft );
+				break;
+				}
+			}
+		}
+
+	if( iObservers.Count() > 0 )
+		{
+		SetActive();
+		iHarvesterEventQueue.NotifyDataAvailable( iStatus );
+		}
+	}
+
+TInt CHarvesterEventObserverAO::RunError(TInt /*aError*/)
+	{
+	return KErrNone;
+	}
+
+TUint CHarvesterEventObserverAO::NextObserverId()
+	{
+	// Sort by observer IDs
+	iObservers.Sort( TLinearOrder<THarvesterEventObserver>(
+			THarvesterEventObserver::CompareObserverIds ) );
+
+	// Find smallest unused observer ID 
+	const TUint count = iObservers.Count();
+	for( TUint i = 0; i < count; i++ )
+		{
+		// Return first free observer ID 
+		if( iObservers[i]->iObserverInfo.iObserverId != i )
+			{
+			return i;
+			}
+		}
+
+	if( count )
+	    {
+	    // No free observer ID found, so return largest observer ID + 1 
+	    return iObservers[count - 1]->iObserverInfo.iObserverId + 1;
+	    }
+	// No observer IDs assigned
+	return 0;
+	}
+
+RHandleBase& CHarvesterEventObserverAO::GetEventQueueHandleL()
+	{
+	// create new message queue
+	if( KNullHandle == iHarvesterEventQueue.Handle() )
+		{
+		TInt err = iHarvesterEventQueue.CreateGlobal( KNullDesC, KHarverterEventQueueSize );
+		User::LeaveIfError( err );
+		}
+
+	return iHarvesterEventQueue;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/src/harvesterrequestactive.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,154 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Active object for an asynchronous harvesrt request
+ *
+*/
+
+#include <e32base.h>
+
+#include "harvesterrequestactive.h"
+#include "harvesterrequestqueue.h"
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestActive::~CHarvesterRequestActive()
+// Destructor.
+// ---------------------------------------------------------------------------
+//
+CHarvesterRequestActive::~CHarvesterRequestActive()
+    {
+    if( IsActive() )
+        {
+        Cancel();
+        if( iObserver )
+            {
+            iObserver->HarvestingComplete( iUri, KErrCancel );
+            }    
+        iRequestCompleted = ETrue;
+        }
+    
+    delete iAlbumIds;
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestActive::NewL
+// Two-phased constructor.
+// --------------------------------------------------------------------------- 
+//
+CHarvesterRequestActive* CHarvesterRequestActive::NewL(
+        RHarvesterClient& aClient, MHarvestObserver* aObserver,
+        TInt aService, const TDesC& aUri, 
+        HBufC8* aAlbumIds, TBool& aAddLocation,
+        CHarvesterRequestQueue* aQueue )
+    {
+    CHarvesterRequestActive* self = new( ELeave )CHarvesterRequestActive( aClient, aObserver,
+            aService, aUri, aAlbumIds, aAddLocation, aQueue );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestActive::CHarvesterRequestActive()
+// C++ default constructor can NOT contain any code, that might leave.
+// ---------------------------------------------------------------------------
+//
+CHarvesterRequestActive::CHarvesterRequestActive( RHarvesterClient& aClient,
+    MHarvestObserver* aObserver, TInt aService, const TDesC& aUri, 
+    HBufC8* aAlbumIds, TBool& aAddLocation, CHarvesterRequestQueue* aQueue )
+    : CActive( CActive::EPriorityStandard ), iClient( aClient ), iObserver( aObserver ), 
+    iService( aService ), iUri( aUri ), iAlbumIds( aAlbumIds ), iAddLocation( aAddLocation ),
+    iRequestQueue( aQueue ), iLocation( EFalse )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestActive::RunL()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRequestActive::RunL()
+    {
+    if( iStatus.Int() && iObserver )
+        {
+        iObserver->HarvestingComplete( iUri, iStatus.Int() );
+        }       
+    iRequestCompleted = ETrue;
+    if( iRequestQueue )
+        {
+        iRequestQueue->RequestComplete();
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestActive::RunError()
+// ---------------------------------------------------------------------------
+//
+TInt CHarvesterRequestActive::RunError( TInt aError )
+    {
+    if( aError == KErrCancel )
+        {
+        return KErrNone;
+        }
+    
+    if( iObserver )
+        {
+        iObserver->HarvestingComplete( iUri, aError );
+        }    
+    iRequestCompleted = ETrue;
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestActive::DoCancel()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRequestActive::DoCancel()
+    {
+    // Nothing to do here
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestActive::Start()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRequestActive::Start()
+    {
+    TPckg<TBool> location( iAddLocation );
+    iLocation.Set( location );
+    
+    TIpcArgs ipcArgs( &iUri, iAlbumIds, &iLocation );
+    iPersistentArgs = ipcArgs;
+    
+    iClient.HarvestFile( iService, iPersistentArgs, iStatus );
+    SetActive();
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestActive::ForceHarvest()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRequestActive::ForceHarvest()
+    {
+    iObserver = NULL;
+    
+    TPckg<TBool> location( iAddLocation );
+    iLocation.Set( location );
+    
+    TIpcArgs ipcArgs( &iUri, iAlbumIds, &iLocation );
+    iPersistentArgs = ipcArgs;
+    
+    iClient.ForceHarvestFile( iService, iPersistentArgs );
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/client/src/harvesterrequestqueue.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,276 @@
+/*
+* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Processor object for running harvester requests
+*
+*/
+
+
+#include "harvesterrequestqueue.h"
+#include "harvesterrequestactive.h"
+#include "harvesterlog.h"
+
+// maximum number of active client requests ( 18 burst images + 1 video )
+const TUint KMaxClientRequests = 19;
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestQueue::NewL()
+// Two-phased constructor.
+// ---------------------------------------------------------------------------
+//
+CHarvesterRequestQueue* CHarvesterRequestQueue::NewL()
+    {
+    CHarvesterRequestQueue* self = new( ELeave )CHarvesterRequestQueue();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestQueue::CHarvesterRequestQueue()
+// C++ default constructor can NOT contain any code, that might leave.
+// ---------------------------------------------------------------------------
+//
+CHarvesterRequestQueue::CHarvesterRequestQueue(): CActive( CActive::EPriorityStandard )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestQueue::ConstructL()
+// Symbian 2nd phase constructor can leave.
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRequestQueue::ConstructL()
+    {
+    iActiveRequests = 0;
+    iShutdown = EFalse;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestQueue::~CHarvesterRequestQueue()
+// Destructor.
+// ---------------------------------------------------------------------------
+//
+CHarvesterRequestQueue::~CHarvesterRequestQueue()
+    {
+    WRITELOG( "CHarvesterRequestQueue::~CHarvesterRequestQueue()");
+    
+    Cancel();
+    iRequests.ResetAndDestroy();
+    
+    WRITELOG( "CHarvesterRequestQueue::~CHarvesterRequestQueue() - All requests deleted");
+    }
+
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestQueue::Process()
+// Activates next request if possible.
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRequestQueue::Process()
+    {
+    WRITELOG( "CHarvesterRequestQueue::Process()");
+
+    if ( !IsActive() && !iShutdown && (iActiveRequests < KMaxClientRequests) )
+        {  
+        SetActive();
+        TRequestStatus* statusPtr = &iStatus;
+        User::RequestComplete( statusPtr, KErrNone );
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestQueue::AddRequestL()
+// Adds new request to the queue.
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRequestQueue::AddRequestL( CHarvesterRequestActive* aRequest )
+    {
+    WRITELOG( "CHarvesterRequestQueue::AddRequestL()");
+    
+    iRequests.AppendL( aRequest );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestQueue::RunL()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRequestQueue::RunL()
+    {
+    WRITELOG2( "CHarvesterRequestQueue::RunL() begin - requests: %d, active requests: %d",
+               iRequests.Count(), iActiveRequests );
+    
+    CHarvesterRequestActive* selectedRequest = NULL;
+    
+    for ( TInt i = 0; i < iRequests.Count(); i++ )
+        {
+        CHarvesterRequestActive* request = iRequests[i];
+        
+        // remove completed tasks    
+        if ( request->RequestCompleted() && !request->IsActive() )
+            {
+            // delete completed task
+            delete request;
+            iRequests.Remove( i );
+            
+            // correct the index so that no tasks are skipped
+            i--;
+            if(i <= -1)
+                {
+                i = -1;
+                }
+            
+            WRITELOG( "CHarvesterRequestQueue::RunL() - removing completed request");
+            }
+        // select priorised task
+        else
+            {
+            // not yet activated
+            if( !request->IsActive() )
+                {
+                selectedRequest = request;
+                }
+            }
+        }
+
+    // activate selected
+    if ( selectedRequest )
+        {
+        iActiveRequests++;
+        selectedRequest->Start();
+        }
+    
+    WRITELOG2( "CHarvesterRequestQueue::RunL() end - requests: %d, active requests: %d",
+            iRequests.Count(), iActiveRequests );
+    
+    // continue processing if needed
+    if ( !iShutdown && (iActiveRequests < KMaxClientRequests)  && 
+            (iRequests.Count() > iActiveRequests))
+        {  
+        SetActive();
+        TRequestStatus* statusPtr = &iStatus;
+        User::RequestComplete( statusPtr, KErrNone );
+        }
+    else
+    	{
+    	iRequests.Compress();
+    	}
+    }
+
+// ---------------------------------------------------------------------------
+// Handle any error from RunL
+// ---------------------------------------------------------------------------
+//
+TInt CHarvesterRequestQueue::RunError( TInt aError )
+    {
+    WRITELOG1( "CHarvesterRequestQueue::RunError() - %d", aError);
+    
+    if (aError)
+        {
+        iActiveRequests--;
+        if(iActiveRequests <= -1)
+            {
+            iActiveRequests = 0;
+            }
+        }
+    
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestQueue::DoCancel()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRequestQueue::DoCancel()
+    {
+    WRITELOG( "CHarvesterRequestQueue::DoCancel()");
+    
+    for( TInt i(0); i < iRequests.Count(); i++ )
+        {
+        iRequests[i]->Cancel();
+        }
+    
+    iShutdown = ETrue;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestQueue::RequestComplete()
+// Completes the request
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRequestQueue::RequestComplete()
+    {
+    WRITELOG( "CHarvesterRequestQueue::RequestComplete()");
+ 
+    iActiveRequests--;
+    if(iActiveRequests <= -1)
+        {
+        iActiveRequests = 0;
+        }
+    
+    WRITELOG1( "CHarvesterRequestQueue::RequestComplete() - active requests: %d", iActiveRequests );
+    
+    // clean completed request and possibly process next
+    if ( !IsActive() && !iShutdown )
+        {  
+        SetActive();
+        TRequestStatus* statusPtr = &iStatus;
+        User::RequestComplete( statusPtr, KErrNone );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterRequestQueue::ForceRequests()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRequestQueue::ForceRequests()
+    {
+    WRITELOG( "CHarvesterRequestQueue::ForceRequests()");
+    
+    Cancel();
+    
+    for ( TInt i = 0; i < iRequests.Count(); i++ )
+        {
+        CHarvesterRequestActive* request = iRequests[i];
+        // remove completed tasks    
+        if ( request->RequestCompleted() )
+            {
+            // delete completed task
+            delete request;
+            iRequests.Remove( i );
+        
+            // correct the index so that no tasks are skipped
+            i--;
+            if(i <= -1)
+                {
+                i = -1;
+                }
+            }
+        else
+            {
+            iRequests[i]->ForceHarvest();
+            }
+        }
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/bwincw/harvestercommonwinscw.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,67 @@
+EXPORTS
+	??1CHarvesterBlacklist@@UAE@XZ @ 1 NONAME ; CHarvesterBlacklist::~CHarvesterBlacklist(void)
+	??1CHarvesterCenRepUtil@@UAE@XZ @ 2 NONAME ; CHarvesterCenRepUtil::~CHarvesterCenRepUtil(void)
+	??1CHarvesterExifUtil@@UAE@XZ @ 3 NONAME ; CHarvesterExifUtil::~CHarvesterExifUtil(void)
+	?AddFile@CHarvesterBlacklist@@QAEHABVTDesC16@@KVTTime@@@Z @ 4 NONAME ; int CHarvesterBlacklist::AddFile(class TDesC16 const &, unsigned long, class TTime)
+	?AddIgnorePathsToFspL@CHarvesterCenRepUtil@@QAEXABVTDesC16@@0@Z @ 5 NONAME ; void CHarvesterCenRepUtil::AddIgnorePathsToFspL(class TDesC16 const &, class TDesC16 const &)
+	?AddIgnorePathsToFspL@CHarvesterCenRepUtil@@QAEXABVTDesC16@@@Z @ 6 NONAME ; void CHarvesterCenRepUtil::AddIgnorePathsToFspL(class TDesC16 const &)
+	?CloseDatabase@CHarvesterBlacklist@@QAEXXZ @ 7 NONAME ; void CHarvesterBlacklist::CloseDatabase(void)
+	?ComposeExifDataL@CHarvesterExifUtil@@QAEHAAVCMdEObject@@VTPtr8@@AAPAVHBufC8@@@Z @ 8 NONAME ; int CHarvesterExifUtil::ComposeExifDataL(class CMdEObject &, class TPtr8, class HBufC8 * &)
+	?ComposeLocationL@CHarvesterExifUtil@@QAEXPAVCMdEObject@@VTPtr8@@AAPAVHBufC8@@@Z @ 9 NONAME ; void CHarvesterExifUtil::ComposeLocationL(class CMdEObject *, class TPtr8, class HBufC8 * &)
+	?ConvertExifDateTimeToSymbianTimeL@CHarvesterExifUtil@@SA?AVTTime@@ABVTDesC8@@@Z @ 10 NONAME ; class TTime CHarvesterExifUtil::ConvertExifDateTimeToSymbianTimeL(class TDesC8 const &)
+	?CurrentState@CHarvesterEventManager@@QAE?AW4HarvesterEventState@@W4HarvesterEventObserverType@@@Z @ 11 NONAME ; enum HarvesterEventState CHarvesterEventManager::CurrentState(enum HarvesterEventObserverType)
+	?DecreaseItemCountL@CHarvesterEventManager@@QAEHW4HarvesterEventObserverType@@I@Z @ 12 NONAME ; int CHarvesterEventManager::DecreaseItemCountL(enum HarvesterEventObserverType, unsigned int)
+	?Delete@CPropertyWatcher@@QAEXXZ @ 13 NONAME ; void CPropertyWatcher::Delete(void)
+	?FspEngine@CHarvesterCenRepUtil@@QAEAAVRMdsFSPEngine@@XZ @ 14 NONAME ; class RMdsFSPEngine & CHarvesterCenRepUtil::FspEngine(void)
+	?GetIgnorePathL@CHarvesterCenRepUtil@@SAXAAV?$RPointerArray@VHBufC16@@@@@Z @ 15 NONAME ; void CHarvesterCenRepUtil::GetIgnorePathL(class RPointerArray<class HBufC16> &)
+	?GetIgnoredPartialRestorePathsL@CHarvesterCenRepUtil@@SAXAAV?$RPointerArray@VHBufC16@@@@@Z @ 16 NONAME ; void CHarvesterCenRepUtil::GetIgnoredPartialRestorePathsL(class RPointerArray<class HBufC16> &)
+	?GetIgnoredScanPathsL@CHarvesterCenRepUtil@@SAXAAV?$RPointerArray@VHBufC16@@@@@Z @ 17 NONAME ; void CHarvesterCenRepUtil::GetIgnoredScanPathsL(class RPointerArray<class HBufC16> &)
+	?GetInstanceL@CHarvesterEventManager@@SAPAV1@XZ @ 18 NONAME ; class CHarvesterEventManager * CHarvesterEventManager::GetInstanceL(void)
+	?GetInstanceL@CPropertyWatcher@@SAPAV1@XZ @ 19 NONAME ; class CPropertyWatcher * CPropertyWatcher::GetInstanceL(void)
+	?GetLastClientId@CHarvesterEventManager@@QAEIXZ @ 20 NONAME ; unsigned int CHarvesterEventManager::GetLastClientId(void)
+	?GetMimeType@CHarvesterPluginFactory@@QAEXABVTDesC16@@AAVTDes16@@@Z @ 21 NONAME ; void CHarvesterPluginFactory::GetMimeType(class TDesC16 const &, class TDes16 &)
+	?GetObjectDefL@CHarvesterPluginFactory@@QAEXAAVCHarvesterData@@AAVTDes16@@@Z @ 22 NONAME ; void CHarvesterPluginFactory::GetObjectDefL(class CHarvesterData &, class TDes16 &)
+	?GetPartialRestorePathsL@CHarvesterCenRepUtil@@SAXAAV?$RPointerArray@UTScanItem@@@@@Z @ 23 NONAME ; void CHarvesterCenRepUtil::GetPartialRestorePathsL(class RPointerArray<struct TScanItem> &)
+	?GetPluginInfos@CHarvesterPluginFactory@@QAEAAV?$RPointerArray@VCHarvesterPluginInfo@@@@XZ @ 24 NONAME ; class RPointerArray<class CHarvesterPluginInfo> & CHarvesterPluginFactory::GetPluginInfos(void)
+	?GetScanItemsL@CHarvesterCenRepUtil@@SAXAAV?$RPointerArray@UTScanItem@@@@@Z @ 25 NONAME ; void CHarvesterCenRepUtil::GetScanItemsL(class RPointerArray<struct TScanItem> &)
+	?HandleObjectPropertyL@CMdeObjectWrapper@@QAEXAAVCMdEObject@@ABVTDesC16@@PAXH@Z @ 26 NONAME ; void CMdeObjectWrapper::HandleObjectPropertyL(class CMdEObject &, class TDesC16 const &, void *, int)
+	?HarvestL@CHarvesterPluginFactory@@QAEHPAVCHarvesterData@@@Z @ 27 NONAME ; int CHarvesterPluginFactory::HarvestL(class CHarvesterData *)
+	?IncreaseItemCount@CHarvesterEventManager@@QAEXW4HarvesterEventObserverType@@I@Z @ 28 NONAME ; void CHarvesterEventManager::IncreaseItemCount(enum HarvesterEventObserverType, unsigned int)
+	?IsBlacklisted@CHarvesterBlacklist@@QAEHABVTDesC16@@KVTTime@@@Z @ 29 NONAME ; int CHarvesterBlacklist::IsBlacklisted(class TDesC16 const &, unsigned long, class TTime)
+	?IsContainerFileL@CHarvesterPluginFactory@@QAEHABVTDesC16@@@Z @ 30 NONAME ; int CHarvesterPluginFactory::IsContainerFileL(class TDesC16 const &)
+	?IsSupportedFileExtension@CHarvesterPluginFactory@@QAEHABVTDesC16@@@Z @ 31 NONAME ; int CHarvesterPluginFactory::IsSupportedFileExtension(class TDesC16 const &)
+	?IsValidExifData@CHarvesterExifUtil@@SAHVTPtr8@@@Z @ 32 NONAME ; int CHarvesterExifUtil::IsValidExifData(class TPtr8)
+	?ItemCount@CHarvesterEventManager@@QAEIW4HarvesterEventObserverType@@@Z @ 33 NONAME ; unsigned int CHarvesterEventManager::ItemCount(enum HarvesterEventObserverType)
+	?ListenKeyAndStatusChangesL@CPropertyWatcher@@QAEXVTUid@@IPBVMKeyAndStatusObserver@@@Z @ 34 NONAME ; void CPropertyWatcher::ListenKeyAndStatusChangesL(class TUid, unsigned int, class MKeyAndStatusObserver const *)
+	?ListenKeyChangesL@CPropertyWatcher@@QAEXVTUid@@IPBVMKeyObserver@@@Z @ 35 NONAME ; void CPropertyWatcher::ListenKeyChangesL(class TUid, unsigned int, class MKeyObserver const *)
+	?NewL@CHarvesterBlacklist@@SAPAV1@XZ @ 36 NONAME ; class CHarvesterBlacklist * CHarvesterBlacklist::NewL(void)
+	?NewL@CHarvesterCenRepUtil@@SAPAV1@XZ @ 37 NONAME ; class CHarvesterCenRepUtil * CHarvesterCenRepUtil::NewL(void)
+	?NewL@CHarvesterExifUtil@@SAPAV1@XZ @ 38 NONAME ; class CHarvesterExifUtil * CHarvesterExifUtil::NewL(void)
+	?NewL@CHarvesterPluginFactory@@SAPAV1@XZ @ 39 NONAME ; class CHarvesterPluginFactory * CHarvesterPluginFactory::NewL(void)
+	?NewL@CMdeObjectWrapper@@SAPAV1@XZ @ 40 NONAME ; class CMdeObjectWrapper * CMdeObjectWrapper::NewL(void)
+	?NewLC@CHarvesterCenRepUtil@@SAPAV1@XZ @ 41 NONAME ; class CHarvesterCenRepUtil * CHarvesterCenRepUtil::NewLC(void)
+	?NewLC@CHarvesterExifUtil@@SAPAV1@XZ @ 42 NONAME ; class CHarvesterExifUtil * CHarvesterExifUtil::NewLC(void)
+	?NewLC@CMdeObjectWrapper@@SAPAV1@XZ @ 43 NONAME ; class CMdeObjectWrapper * CMdeObjectWrapper::NewLC(void)
+	?OpenDatabase@CHarvesterBlacklist@@QAEXXZ @ 44 NONAME ; void CHarvesterBlacklist::OpenDatabase(void)
+	?ReadExifDataL@CHarvesterExifUtil@@SAHAAVCHarvestData@@AAVCFileData@@@Z @ 45 NONAME ; int CHarvesterExifUtil::ReadExifDataL(class CHarvestData &, class CFileData &)
+	?RegisterHEClientInfo@CHarvesterEventManager@@QAEHABVRMessage2@@@Z @ 46 NONAME ABSENT ; int CHarvesterEventManager::RegisterHEClientInfo(class RMessage2 const &)
+	?ReleaseInstance@CHarvesterEventManager@@QAEXXZ @ 47 NONAME ; void CHarvesterEventManager::ReleaseInstance(void)
+	?RemoveFile@CHarvesterBlacklist@@QAEHABVTDesC16@@K@Z @ 48 NONAME ; int CHarvesterBlacklist::RemoveFile(class TDesC16 const &, unsigned long)
+	?RemoveIgnorePathsFromFspL@CHarvesterCenRepUtil@@QAEXABVTDesC16@@@Z @ 49 NONAME ; void CHarvesterCenRepUtil::RemoveIgnorePathsFromFspL(class TDesC16 const &)
+	?SendEventL@CHarvesterEventManager@@QAEHW4HarvesterEventObserverType@@W4HarvesterEventState@@I@Z @ 50 NONAME ; int CHarvesterEventManager::SendEventL(enum HarvesterEventObserverType, enum HarvesterEventState, unsigned int)
+	?SetBlacklist@CHarvesterPluginFactory@@QAEXAAVCHarvesterBlacklist@@@Z @ 51 NONAME ; void CHarvesterPluginFactory::SetBlacklist(class CHarvesterBlacklist &)
+	?SetSession@CHarvesterExifUtil@@QAEXPAVCMdESession@@@Z @ 52 NONAME ; void CHarvesterExifUtil::SetSession(class CMdESession *)
+	?StopListeningKeyAndStatusChanges@CPropertyWatcher@@QAEXVTUid@@IPAVMKeyAndStatusObserver@@@Z @ 53 NONAME ; void CPropertyWatcher::StopListeningKeyAndStatusChanges(class TUid, unsigned int, class MKeyAndStatusObserver *)
+	?StopListeningKeyChanges@CPropertyWatcher@@QAEXVTUid@@IPBVMKeyObserver@@@Z @ 54 NONAME ; void CPropertyWatcher::StopListeningKeyChanges(class TUid, unsigned int, class MKeyObserver const *)
+	?UnregisterHEClientInfo@CHarvesterEventManager@@QAEHH@Z @ 55 NONAME ABSENT ; int CHarvesterEventManager::UnregisterHEClientInfo(int)
+	?GetDriveLetter@CHarvesterMediaIdUtil@@QAEHKAAVTChar@@@Z @ 56 NONAME ; int CHarvesterMediaIdUtil::GetDriveLetter(unsigned long, class TChar &)
+	?GetMediaId@CHarvesterMediaIdUtil@@QAEHABVTDesC16@@AAK@Z @ 57 NONAME ; int CHarvesterMediaIdUtil::GetMediaId(class TDesC16 const &, unsigned long &)
+	?RemoveMediaId@CHarvesterMediaIdUtil@@QAEXK@Z @ 58 NONAME ; void CHarvesterMediaIdUtil::RemoveMediaId(unsigned long)
+	?GetInstanceL@RMediaIdUtil@@SAAAVCHarvesterMediaIdUtil@@XZ @ 59 NONAME ; class CHarvesterMediaIdUtil & RMediaIdUtil::GetInstanceL(void)
+	?ReleaseInstance@RMediaIdUtil@@SAXXZ @ 60 NONAME ; void RMediaIdUtil::ReleaseInstance(void)
+	?IsRomScanEnabledL@CHarvesterCenRepUtil@@SAXAAH@Z @ 61 NONAME ; void CHarvesterCenRepUtil::IsRomScanEnabledL(int &)
+	?IsThumbnailDaemonEnabledL@CHarvesterCenRepUtil@@SAXAAH@Z @ 62 NONAME ; void CHarvesterCenRepUtil::IsThumbnailDaemonEnabledL(int &)
+	?RegisterEventObserverL@CHarvesterEventManager@@QAEXABVRMessage2@@@Z @ 63 NONAME ; void CHarvesterEventManager::RegisterEventObserverL(class RMessage2 const &)
+	?UnregisterEventObserver@CHarvesterEventManager@@QAEHABVRMessage2@@@Z @ 64 NONAME ; int CHarvesterEventManager::UnregisterEventObserver(class RMessage2 const &)
+	?HandleObjectPropertyL@CMdeObjectWrapper@@SAXAAVCMdEObject@@AAVCMdEPropertyDef@@PAXH@Z @ 65 NONAME ; void CMdeObjectWrapper::HandleObjectPropertyL(class CMdEObject &, class CMdEPropertyDef &, void *, int)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/bwincw/harvesterdatawinscw.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,47 @@
+EXPORTS
+	?AddLocation@CHarvesterData@@QAEHXZ @ 1 NONAME ; int CHarvesterData::AddLocation(void)
+	?ClientData@CHarvesterData@@QAEPAVCBase@@XZ @ 2 NONAME ; class CBase * CHarvesterData::ClientData(void)
+	?ClientId@CHarvesterData@@QAE?AVTUid@@XZ @ 3 NONAME ; class TUid CHarvesterData::ClientId(void)
+	?ErrorCode@CHarvesterData@@QAEHXZ @ 4 NONAME ; int CHarvesterData::ErrorCode(void)
+	?EventType@CHarvesterData@@QAE?AW4THarvesterEventType@@XZ @ 5 NONAME ; enum THarvesterEventType CHarvesterData::EventType(void)
+	?FileSize@CPlaceholderData@@QAEKXZ @ 6 NONAME ; unsigned long CPlaceholderData::FileSize(void)
+	?HarvesterPluginInfo@CHarvesterData@@QAEPAVCHarvesterPluginInfo@@XZ @ 7 NONAME ; class CHarvesterPluginInfo * CHarvesterData::HarvesterPluginInfo(void)
+	?LocationData@CHarvesterData@@QAEPAUTLocationData@@XZ @ 8 NONAME ; struct TLocationData * CHarvesterData::LocationData(void)
+	?MdeObject@CHarvesterData@@QAEAAVCMdEObject@@XZ @ 9 NONAME ; class CMdEObject & CHarvesterData::MdeObject(void)
+	?MediaId@CPlaceholderData@@QAEIXZ @ 10 NONAME ; unsigned int CPlaceholderData::MediaId(void)
+	?Modified@CPlaceholderData@@QAE?AVTTime@@XZ @ 11 NONAME ; class TTime CPlaceholderData::Modified(void)
+	?New@CHarvestClientData@@SAPAV1@XZ @ 12 NONAME ; class CHarvestClientData * CHarvestClientData::New(void)
+	?NewL@CHarvestClientData@@SAPAV1@XZ @ 13 NONAME ; class CHarvestClientData * CHarvestClientData::NewL(void)
+	?NewL@CHarvesterData@@SAPAV1@PBVHBufC16@@@Z @ 14 NONAME ; class CHarvesterData * CHarvesterData::NewL(class HBufC16 const *)
+	?NewL@CPlaceholderData@@SAPAV1@XZ @ 15 NONAME ; class CPlaceholderData * CPlaceholderData::NewL(void)
+	?NewLC@CHarvesterData@@SAPAV1@PBVHBufC16@@@Z @ 16 NONAME ; class CHarvesterData * CHarvesterData::NewLC(class HBufC16 const *)
+	?ObjectType@CHarvesterData@@QAE?AW4THarvesterObjectType@@XZ @ 17 NONAME ; enum THarvesterObjectType CHarvesterData::ObjectType(void)
+	?Origin@CHarvesterData@@QAE?AW4TOrigin@Object@MdeConstants@@XZ @ 18 NONAME ; enum MdeConstants::Object::TOrigin CHarvesterData::Origin(void)
+	?PluginObserver@CHarvesterData@@QAEPAVMHarvesterPluginObserver@@XZ @ 19 NONAME ; class MHarvesterPluginObserver * CHarvesterData::PluginObserver(void)
+	?PresentState@CPlaceholderData@@QAEHXZ @ 20 NONAME ; int CPlaceholderData::PresentState(void)
+	?SetAddLocation@CHarvesterData@@QAEXH@Z @ 21 NONAME ; void CHarvesterData::SetAddLocation(int)
+	?SetAlbumIds@CHarvestClientData@@QAEXABV?$RArray@K@@@Z @ 22 NONAME ; void CHarvestClientData::SetAlbumIds(class RArray<unsigned long> const &)
+	?SetClientData@CHarvesterData@@QAEXPAVCBase@@@Z @ 23 NONAME ; void CHarvesterData::SetClientData(class CBase *)
+	?SetClientId@CHarvesterData@@QAEXVTUid@@@Z @ 24 NONAME ; void CHarvesterData::SetClientId(class TUid)
+	?SetErrorCode@CHarvesterData@@QAEXH@Z @ 25 NONAME ; void CHarvesterData::SetErrorCode(int)
+	?SetEventType@CHarvesterData@@QAEXW4THarvesterEventType@@@Z @ 26 NONAME ; void CHarvesterData::SetEventType(enum THarvesterEventType)
+	?SetFileSize@CPlaceholderData@@QAEXK@Z @ 27 NONAME ; void CPlaceholderData::SetFileSize(unsigned long)
+	?SetHarvesterPluginInfo@CHarvesterData@@QAEXPAVCHarvesterPluginInfo@@@Z @ 28 NONAME ; void CHarvesterData::SetHarvesterPluginInfo(class CHarvesterPluginInfo *)
+	?SetLocationData@CHarvesterData@@QAEXPAUTLocationData@@@Z @ 29 NONAME ; void CHarvesterData::SetLocationData(struct TLocationData *)
+	?SetMdeObject@CHarvesterData@@QAEXPAVCMdEObject@@@Z @ 30 NONAME ; void CHarvesterData::SetMdeObject(class CMdEObject *)
+	?SetMediaId@CPlaceholderData@@QAEXI@Z @ 31 NONAME ; void CPlaceholderData::SetMediaId(unsigned int)
+	?SetModified@CPlaceholderData@@QAEXVTTime@@@Z @ 32 NONAME ; void CPlaceholderData::SetModified(class TTime)
+	?SetObjectType@CHarvesterData@@QAEXW4THarvesterObjectType@@@Z @ 33 NONAME ; void CHarvesterData::SetObjectType(enum THarvesterObjectType)
+	?SetOrigin@CHarvesterData@@QAEXW4TOrigin@Object@MdeConstants@@@Z @ 34 NONAME ; void CHarvesterData::SetOrigin(enum MdeConstants::Object::TOrigin)
+	?SetPluginObserver@CHarvesterData@@QAEXAAVMHarvesterPluginObserver@@@Z @ 35 NONAME ; void CHarvesterData::SetPluginObserver(class MHarvesterPluginObserver &)
+	?SetPresentState@CPlaceholderData@@QAEXH@Z @ 36 NONAME ; void CPlaceholderData::SetPresentState(int)
+	?SetTakeSnapshot@CHarvesterData@@QAEXH@Z @ 37 NONAME ; void CHarvesterData::SetTakeSnapshot(int)
+	?SetUri@CPlaceholderData@@QAEXABVTDesC16@@@Z @ 38 NONAME ; void CPlaceholderData::SetUri(class TDesC16 const &)
+	?TakeSnapshot@CHarvesterData@@QAEHXZ @ 39 NONAME ; int CHarvesterData::TakeSnapshot(void)
+	?Uri@CHarvesterData@@QAEABVTDesC16@@XZ @ 40 NONAME ; class TDesC16 const & CHarvesterData::Uri(void)
+	?Uri@CPlaceholderData@@QAE?AVTPtr16@@XZ @ 41 NONAME ; class TPtr16 CPlaceholderData::Uri(void)
+	?Preinstalled@CPlaceholderData@@QAEHXZ @ 42 NONAME ; int CPlaceholderData::Preinstalled(void)
+	?SetPreinstalled@CPlaceholderData@@QAEXH@Z @ 43 NONAME ; void CPlaceholderData::SetPreinstalled(int)
+	?IsBinary@CHarvesterData@@QAEHXZ @ 44 NONAME ; int CHarvesterData::IsBinary(void)
+	?SetBinary@CHarvesterData@@QAEXH@Z @ 45 NONAME ; void CHarvesterData::SetBinary(int)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/bwincw/harvesterplugininterfacewinscw.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,13 @@
+EXPORTS
+	??0CHarvesterPlugin@@IAE@XZ @ 1 NONAME ; CHarvesterPlugin::CHarvesterPlugin(void)
+	??1CHarvesterPlugin@@UAE@XZ @ 2 NONAME ; CHarvesterPlugin::~CHarvesterPlugin(void)
+	?DoCancel@CHarvesterPlugin@@MAEXXZ @ 3 NONAME ; void CHarvesterPlugin::DoCancel(void)
+	?GetObjectType@CHarvesterPlugin@@UAEXABVTDesC16@@AAVTDes16@@@Z @ 4 NONAME ; void CHarvesterPlugin::GetObjectType(class TDesC16 const &, class TDes16 &)
+	?ListImplementationsL@CHarvesterPlugin@@SAXAAV?$RPointerArray@VCImplementationInformation@@@@@Z @ 5 NONAME ; void CHarvesterPlugin::ListImplementationsL(class RPointerArray<class CImplementationInformation> &)
+	?NewL@CHarvesterPlugin@@SAPAV1@ABVTUid@@@Z @ 6 NONAME ; class CHarvesterPlugin * CHarvesterPlugin::NewL(class TUid const &)
+	?RunError@CHarvesterPlugin@@MAEHH@Z @ 7 NONAME ; int CHarvesterPlugin::RunError(int)
+	?RunL@CHarvesterPlugin@@MAEXXZ @ 8 NONAME ; void CHarvesterPlugin::RunL(void)
+	?SetQueue@CHarvesterPlugin@@UAEXAAV?$RPointerArray@VCHarvesterData@@@@@Z @ 9 NONAME ; void CHarvesterPlugin::SetQueue(class RPointerArray<class CHarvesterData> &)
+	?StartHarvest@CHarvesterPlugin@@UAEXXZ @ 10 NONAME ; void CHarvesterPlugin::StartHarvest(void)
+	?SetBlacklist@CHarvesterPlugin@@UAEXAAVCHarvesterBlacklist@@@Z @ 11 NONAME ; void CHarvesterPlugin::SetBlacklist(class CHarvesterBlacklist &)
+
Binary file harvester/common/data/200009FE.txt has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/data/harvester_settings.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,13 @@
+<!DOCTYPE Feature SYSTEM "CT_XMLData.dtd">
+<Feature Name="Harvester settings" Plugin="CRPlugin" Group="Harvester" Desc="">
+	<Settings>
+		<Setting Name="Ignore directory private" Key="0x1" Type="string" ref="Variant/Harvester/IgnorePrivate" Desc="Directory which is ignored by Harvester">\private\</Setting>
+		<Setting Name="Ignore directory system" Key="0x2" Type="string" ref="Variant/Harvester/IgnoreSystem" Desc="Directory which is ignored by Harvester">\system\</Setting>
+		<Setting Name="Ignore directory activenotes" Key="0x3" Type="string" ref="Variant/Harvester/IgnoreActiveNotes" Desc="Directory which is ignored by Harvester">\activenotes\</Setting>
+		<Setting Name="Ignore directory data\activenotes" Key="0x4" Type="string" ref="Variant/Harvester/IgnoreDataActiveNotes" Desc="Directory which is ignored by Harvester">\Data\activenotes\</Setting>
+	</Settings>
+	<Rules>
+		<CenRepfile Name1="\epoc32\data\z\private\10202BE9\200009FE.txt">1</CenRepfile>
+		<Ibyfile Name1="\epoc32\rom\include\S60Cenrep_variant.iby">1</Ibyfile>
+	</Rules>
+</Feature>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/eabi/harvestercommonarm.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,84 @@
+EXPORTS
+	_ZN16CPropertyWatcher12GetInstanceLEv @ 1 NONAME
+	_ZN16CPropertyWatcher17ListenKeyChangesLE4TUidjPK12MKeyObserver @ 2 NONAME
+	_ZN16CPropertyWatcher23StopListeningKeyChangesE4TUidjPK12MKeyObserver @ 3 NONAME
+	_ZN16CPropertyWatcher26ListenKeyAndStatusChangesLE4TUidjPK21MKeyAndStatusObserver @ 4 NONAME
+	_ZN16CPropertyWatcher32StopListeningKeyAndStatusChangesE4TUidjP21MKeyAndStatusObserver @ 5 NONAME
+	_ZN16CPropertyWatcher6DeleteEv @ 6 NONAME
+	_ZN17CMdeObjectWrapper21HandleObjectPropertyLER10CMdEObjectRK7TDesC16Pvi @ 7 NONAME
+	_ZN17CMdeObjectWrapper4NewLEv @ 8 NONAME
+	_ZN17CMdeObjectWrapper5NewLCEv @ 9 NONAME
+	_ZN18CHarvesterExifUtil10SetSessionEP11CMdESession @ 10 NONAME
+	_ZN18CHarvesterExifUtil13ReadExifDataLER12CHarvestDataR9CFileData @ 11 NONAME
+	_ZN18CHarvesterExifUtil15IsValidExifDataE5TPtr8 @ 12 NONAME
+	_ZN18CHarvesterExifUtil16ComposeExifDataLER10CMdEObject5TPtr8RP6HBufC8 @ 13 NONAME
+	_ZN18CHarvesterExifUtil16ComposeLocationLEP10CMdEObject5TPtr8RP6HBufC8 @ 14 NONAME
+	_ZN18CHarvesterExifUtil33ConvertExifDateTimeToSymbianTimeLERK6TDesC8 @ 15 NONAME
+	_ZN18CHarvesterExifUtil4NewLEv @ 16 NONAME
+	_ZN18CHarvesterExifUtil5NewLCEv @ 17 NONAME
+	_ZN19CHarvesterBlacklist10RemoveFileERK7TDesC16m @ 18 NONAME
+	_ZN19CHarvesterBlacklist12OpenDatabaseEv @ 19 NONAME
+	_ZN19CHarvesterBlacklist13CloseDatabaseEv @ 20 NONAME
+	_ZN19CHarvesterBlacklist13IsBlacklistedERK7TDesC16m5TTime @ 21 NONAME
+	_ZN19CHarvesterBlacklist4NewLEv @ 22 NONAME
+	_ZN19CHarvesterBlacklist7AddFileERK7TDesC16m5TTime @ 23 NONAME
+	_ZN19CHarvesterBlacklistD0Ev @ 24 NONAME
+	_ZN19CHarvesterBlacklistD1Ev @ 25 NONAME
+	_ZN19CHarvesterBlacklistD2Ev @ 26 NONAME
+	_ZN20CHarvesterCenRepUtil13GetScanItemsLER13RPointerArrayI9TScanItemE @ 27 NONAME
+	_ZN20CHarvesterCenRepUtil14GetIgnorePathLER13RPointerArrayI7HBufC16E @ 28 NONAME
+	_ZN20CHarvesterCenRepUtil20AddIgnorePathsToFspLERK7TDesC16 @ 29 NONAME
+	_ZN20CHarvesterCenRepUtil20AddIgnorePathsToFspLERK7TDesC16S2_ @ 30 NONAME
+	_ZN20CHarvesterCenRepUtil20GetIgnoredScanPathsLER13RPointerArrayI7HBufC16E @ 31 NONAME
+	_ZN20CHarvesterCenRepUtil23GetPartialRestorePathsLER13RPointerArrayI9TScanItemE @ 32 NONAME
+	_ZN20CHarvesterCenRepUtil25RemoveIgnorePathsFromFspLERK7TDesC16 @ 33 NONAME
+	_ZN20CHarvesterCenRepUtil30GetIgnoredPartialRestorePathsLER13RPointerArrayI7HBufC16E @ 34 NONAME
+	_ZN20CHarvesterCenRepUtil4NewLEv @ 35 NONAME
+	_ZN20CHarvesterCenRepUtil5NewLCEv @ 36 NONAME
+	_ZN20CHarvesterCenRepUtil9FspEngineEv @ 37 NONAME
+	_ZN20CHarvesterCenRepUtilD0Ev @ 38 NONAME
+	_ZN20CHarvesterCenRepUtilD1Ev @ 39 NONAME
+	_ZN20CHarvesterCenRepUtilD2Ev @ 40 NONAME
+	_ZN22CHarvesterEventManager10SendEventLE26HarvesterEventObserverType19HarvesterEventStatej @ 41 NONAME
+	_ZN22CHarvesterEventManager12CurrentStateE26HarvesterEventObserverType @ 42 NONAME
+	_ZN22CHarvesterEventManager12GetInstanceLEv @ 43 NONAME
+	_ZN22CHarvesterEventManager15GetLastClientIdEv @ 44 NONAME
+	_ZN22CHarvesterEventManager15ReleaseInstanceEv @ 45 NONAME
+	_ZN22CHarvesterEventManager17IncreaseItemCountE26HarvesterEventObserverTypej @ 46 NONAME
+	_ZN22CHarvesterEventManager18DecreaseItemCountLE26HarvesterEventObserverTypej @ 47 NONAME
+	_ZN22CHarvesterEventManager20RegisterHEClientInfoERK9RMessage2 @ 48 NONAME ABSENT
+	_ZN22CHarvesterEventManager22UnregisterHEClientInfoEi @ 49 NONAME ABSENT
+	_ZN22CHarvesterEventManager9ItemCountE26HarvesterEventObserverType @ 50 NONAME
+	_ZN23CHarvesterPluginFactory11GetMimeTypeERK7TDesC16R6TDes16 @ 51 NONAME
+	_ZN23CHarvesterPluginFactory12SetBlacklistER19CHarvesterBlacklist @ 52 NONAME
+	_ZN23CHarvesterPluginFactory13GetObjectDefLER14CHarvesterDataR6TDes16 @ 53 NONAME
+	_ZN23CHarvesterPluginFactory14GetPluginInfosEv @ 54 NONAME
+	_ZN23CHarvesterPluginFactory16IsContainerFileLERK7TDesC16 @ 55 NONAME
+	_ZN23CHarvesterPluginFactory24IsSupportedFileExtensionERK7TDesC16 @ 56 NONAME
+	_ZN23CHarvesterPluginFactory4NewLEv @ 57 NONAME
+	_ZN23CHarvesterPluginFactory8HarvestLEP14CHarvesterData @ 58 NONAME
+	_ZTI17CMdeObjectWrapper @ 59 NONAME ABSENT ; #<TI>#
+	_ZTI18CHarvesterExifUtil @ 60 NONAME ABSENT ; #<TI>#
+	_ZTI19CHarvesterBlacklist @ 61 NONAME ABSENT ; #<TI>#
+	_ZTI20CHarvesterCenRepUtil @ 62 NONAME ABSENT ; #<TI>#
+	_ZTI22CHarvesterEventManager @ 63 NONAME ABSENT ; #<TI>#
+	_ZTI23CHarvesterPluginFactory @ 64 NONAME ABSENT ; #<TI>#
+	_ZTV17CMdeObjectWrapper @ 65 NONAME ABSENT ; #<VT>#
+	_ZTV18CHarvesterExifUtil @ 66 NONAME ABSENT ; #<VT>#
+	_ZTV19CHarvesterBlacklist @ 67 NONAME ABSENT ; #<VT>#
+	_ZTV20CHarvesterCenRepUtil @ 68 NONAME ABSENT ; #<VT>#
+	_ZTV22CHarvesterEventManager @ 69 NONAME ABSENT ; #<VT>#
+	_ZTV23CHarvesterPluginFactory @ 70 NONAME ABSENT ; #<VT>#
+	_ZN12RMediaIdUtil12GetInstanceLEv @ 71 NONAME
+	_ZN12RMediaIdUtil15ReleaseInstanceEv @ 72 NONAME
+	_ZN21CHarvesterMediaIdUtil10GetMediaIdERK7TDesC16Rm @ 73 NONAME
+	_ZN21CHarvesterMediaIdUtil13RemoveMediaIdEm @ 74 NONAME
+	_ZN21CHarvesterMediaIdUtil14GetDriveLetterEmR5TChar @ 75 NONAME
+	_ZTI21CHarvesterMediaIdUtil @ 76 NONAME ; #<TI>#
+	_ZTV21CHarvesterMediaIdUtil @ 77 NONAME ; #<VT>#
+	_ZN20CHarvesterCenRepUtil17IsRomScanEnabledLERi @ 78 NONAME
+	_ZN20CHarvesterCenRepUtil25IsThumbnailDaemonEnabledLERi @ 79 NONAME
+	_ZN22CHarvesterEventManager22RegisterEventObserverLERK9RMessage2 @ 80 NONAME
+	_ZN22CHarvesterEventManager23UnregisterEventObserverERK9RMessage2 @ 81 NONAME
+	_ZN17CMdeObjectWrapper21HandleObjectPropertyLER10CMdEObjectR15CMdEPropertyDefPvi @ 82 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/eabi/harvesterdataarm.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,53 @@
+EXPORTS
+	_ZN14CHarvesterData10ClientDataEv @ 1 NONAME
+	_ZN14CHarvesterData10ObjectTypeEv @ 2 NONAME
+	_ZN14CHarvesterData11SetClientIdE4TUid @ 3 NONAME
+	_ZN14CHarvesterData12LocationDataEv @ 4 NONAME
+	_ZN14CHarvesterData12SetErrorCodeEi @ 5 NONAME
+	_ZN14CHarvesterData12SetEventTypeE19THarvesterEventType @ 6 NONAME
+	_ZN14CHarvesterData12SetMdeObjectEP10CMdEObject @ 7 NONAME
+	_ZN14CHarvesterData12TakeSnapshotEv @ 8 NONAME
+	_ZN14CHarvesterData13SetClientDataEP5CBase @ 9 NONAME
+	_ZN14CHarvesterData13SetObjectTypeE20THarvesterObjectType @ 10 NONAME
+	_ZN14CHarvesterData14PluginObserverEv @ 11 NONAME
+	_ZN14CHarvesterData15SetLocationDataEP13TLocationData @ 12 NONAME
+	_ZN14CHarvesterData15SetTakeSnapshotEi @ 13 NONAME
+	_ZN14CHarvesterData17SetPluginObserverER24MHarvesterPluginObserver @ 14 NONAME
+	_ZN14CHarvesterData3UriEv @ 15 NONAME
+	_ZN14CHarvesterData4NewLEPK7HBufC16 @ 16 NONAME
+	_ZN14CHarvesterData5NewLCEPK7HBufC16 @ 17 NONAME
+	_ZN14CHarvesterData6OriginEv @ 18 NONAME
+	_ZN14CHarvesterData8ClientIdEv @ 19 NONAME
+	_ZN14CHarvesterData9ErrorCodeEv @ 20 NONAME
+	_ZN14CHarvesterData9EventTypeEv @ 21 NONAME
+	_ZN14CHarvesterData9MdeObjectEv @ 22 NONAME
+	_ZN14CHarvesterData9SetOriginEN12MdeConstants6Object7TOriginE @ 23 NONAME
+	_ZN16CPlaceholderData10SetMediaIdEj @ 24 NONAME
+	_ZN16CPlaceholderData11SetFileSizeEm @ 25 NONAME
+	_ZN16CPlaceholderData11SetModifiedE5TTime @ 26 NONAME
+	_ZN16CPlaceholderData12PresentStateEv @ 27 NONAME
+	_ZN16CPlaceholderData15SetPresentStateEi @ 28 NONAME
+	_ZN16CPlaceholderData3UriEv @ 29 NONAME
+	_ZN16CPlaceholderData4NewLEv @ 30 NONAME
+	_ZN16CPlaceholderData6SetUriERK7TDesC16 @ 31 NONAME
+	_ZN16CPlaceholderData7MediaIdEv @ 32 NONAME
+	_ZN16CPlaceholderData8FileSizeEv @ 33 NONAME
+	_ZN16CPlaceholderData8ModifiedEv @ 34 NONAME
+	_ZN18CHarvestClientData11SetAlbumIdsERK6RArrayImE @ 35 NONAME
+	_ZN18CHarvestClientData3NewEv @ 36 NONAME
+	_ZN18CHarvestClientData4NewLEv @ 37 NONAME
+	_ZTI14CHarvesterData @ 38 NONAME ABSENT; #<TI>#
+	_ZTI16CPlaceholderData @ 39 NONAME ABSENT; #<TI>#
+	_ZTI18CHarvestClientData @ 40 NONAME ABSENT; #<TI>#
+	_ZTV14CHarvesterData @ 41 NONAME ABSENT; #<VT>#
+	_ZTV16CPlaceholderData @ 42 NONAME ABSENT; #<VT>#
+	_ZTV18CHarvestClientData @ 43 NONAME ABSENT; #<VT>#
+	_ZN14CHarvesterData11AddLocationEv @ 44 NONAME
+	_ZN14CHarvesterData14SetAddLocationEi @ 45 NONAME
+	_ZN14CHarvesterData19HarvesterPluginInfoEv @ 46 NONAME
+	_ZN14CHarvesterData22SetHarvesterPluginInfoEP20CHarvesterPluginInfo @ 47 NONAME
+	_ZN16CPlaceholderData12PreinstalledEv @ 48 NONAME
+	_ZN16CPlaceholderData15SetPreinstalledEi @ 49 NONAME
+	_ZN14CHarvesterData8IsBinaryEv @ 50 NONAME
+	_ZN14CHarvesterData9SetBinaryEi @ 51 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/eabi/harvesterplugininterfacearm.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,17 @@
+EXPORTS
+	_ZN16CHarvesterPlugin12StartHarvestEv @ 1 NONAME
+	_ZN16CHarvesterPlugin13GetObjectTypeERK7TDesC16R6TDes16 @ 2 NONAME
+	_ZN16CHarvesterPlugin20ListImplementationsLER13RPointerArrayI26CImplementationInformationE @ 3 NONAME
+	_ZN16CHarvesterPlugin4NewLERK4TUid @ 4 NONAME
+	_ZN16CHarvesterPlugin4RunLEv @ 5 NONAME
+	_ZN16CHarvesterPlugin8DoCancelEv @ 6 NONAME
+	_ZN16CHarvesterPlugin8RunErrorEi @ 7 NONAME
+	_ZN16CHarvesterPlugin8SetQueueER13RPointerArrayI14CHarvesterDataE @ 8 NONAME
+	_ZN16CHarvesterPluginC2Ev @ 9 NONAME
+	_ZN16CHarvesterPluginD0Ev @ 10 NONAME
+	_ZN16CHarvesterPluginD1Ev @ 11 NONAME
+	_ZN16CHarvesterPluginD2Ev @ 12 NONAME
+	_ZTI16CHarvesterPlugin @ 13 NONAME ; #<TI>#
+	_ZTV16CHarvesterPlugin @ 14 NONAME ; #<VT>#
+	_ZN16CHarvesterPlugin12SetBlacklistER19CHarvesterBlacklist @ 15 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+../data/200009FE.txt /epoc32/data/z/private/10202BE9/200009FE.txt
+../data/200009FE.txt /epoc32/WINSCW/C/private/10202BE9/200009FE.txt
+
+PRJ_MMPFILES
+harvesterdata.mmp
+harvestercommon.mmp
+harvesterplugininterface.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/group/harvestercommon.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,72 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION           10.0
+TARGET            harvestercommon.dll
+TARGETTYPE        dll
+UID               0x1000008D 0x200009FE
+
+VENDORID        	VID_DEFAULT
+CAPABILITY 		CAP_GENERAL_DLL
+
+#if defined(WINSCW)
+deffile ../bwincw/harvestercommonwinscw.def
+#elif defined(ARMCC)
+deffile ../eabi/harvestercommonarm.def
+#endif
+nostrictdef
+
+SYSTEMINCLUDE     /epoc32/include/ecom
+SYSTEMINCLUDE     /epoc32/include/connect
+
+USERINCLUDE       ../../../inc
+USERINCLUDE       ../inc
+USERINCLUDE       ../../monitorplugins/inc
+
+SOURCEPATH        ../src
+SOURCE            harvesterblacklist.cpp
+SOURCE			  harvesterpluginfactory.cpp
+SOURCE            harvesterexifutil.cpp
+SOURCE            mdeobjectwrapper.cpp
+SOURCE            harvestercenreputil.cpp
+SOURCE            harvestereventmanager.cpp
+SOURCE            propertywatcher.cpp
+SOURCE  		  listener.cpp
+SOURCE            harvestermediaidutil.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY           euser.lib
+LIBRARY           efsrv.lib 
+LIBRARY           mdeclient.lib
+LIBRARY			  ecom.lib
+LIBRARY			  harvesterdata.lib
+LIBRARY			  harvesterplugininterface.lib
+LIBRARY           ExifLib.lib
+LIBRARY           charconv.lib 
+LIBRARY           tzclient.lib
+LIBRARY           centralrepository.lib 
+LIBRARY           blacklistclient.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/group/harvesterdata.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION           10.0
+TARGET            harvesterdata.dll
+TARGETTYPE        dll
+UID               0x1000008D 0x200104D9
+
+VENDORID        	VID_DEFAULT
+CAPABILITY 		CAP_GENERAL_DLL
+
+#if defined(WINSCW)
+    deffile ../bwincw/harvesterdatawinscw.def
+#elif defined(ARMCC)
+    deffile ../eabi/harvesterdataarm.def
+#endif
+nostrictdef
+
+USERINCLUDE       ../inc
+
+SOURCEPATH        ../src
+SOURCE		harvesterclientdata.cpp
+SOURCE		placeholderdata.cpp
+SOURCE		harvesterdata.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY           euser.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/group/harvesterplugininterface.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        harvesterplugininterface.dll
+TARGETTYPE    dll
+UID           0x1000008D 0x200009F8
+
+CAPABILITY 	  CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+SYSTEMINCLUDE /epoc32/include/ecom
+
+USERINCLUDE   ../inc
+USERINCLUDE	  ../../../inc
+
+SOURCEPATH    ../src
+SOURCE        harvesterplugin.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       efsrv.lib
+LIBRARY       ecom.lib
+LIBRARY       harvesterdata.lib
+LIBRARY       harvestercommon.lib
+LIBRARY	      mdeclient.lib
+
+#if defined(WINS)
+    deffile ../bwincw/harvesterplugininterfacewinscw.def
+#elif defined(ARMCC)
+    deffile ../eabi/harvesterplugininterfacearm.def
+#endif
+nostrictdef
+
+BYTEPAIRCOMPRESSTARGET
+PAGED
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/blacklistitem.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,105 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef __BLACKLISTITEM_H__
+#define __BLACKLISTITEM_H__
+
+// SYSTEM INCLUDE
+#include <e32base.h>
+
+
+/**
+* A helper class (DTO) for data stored to the blacklist database and cache.
+*/
+NONSHARABLE_CLASS( CBlacklistItem ) : public CBase
+    {
+    public:
+        /**
+         * Standard NewL().
+         * @param aModified  Item's last modification time.
+         * @param aUri  Item's URI.
+         * @param aMediaId  Item's media id.
+         * @return  New item
+         */
+        static CBlacklistItem* NewL( const TInt64& aModified,
+                const TDesC& aUri, const TUint32 aMediaId );
+        
+        /** Destructor. */
+        virtual ~CBlacklistItem();
+
+        /**
+         * Check if given item matches given data.
+         * @param aUri  Item's URI.
+         * @param aMediaId  Item's media id.
+         * @return ETrue, if matches.
+         */
+        TBool Compare( const TDesC& aUri, const TUint32 aMediaId );
+        
+        /**
+         * Return item's last modification time.
+         * @return Item's last modification time.
+         */
+        const TInt64& Modified();
+    
+        /**
+         * Return item's MediaId.
+         * @return item's MediaId.
+         */
+        const TUint32& MediaId();
+ 
+ 
+        /**
+         * Return item's Uri.
+         * @return item's Uri.
+         */
+        const HBufC* Uri();
+        
+        /**
+         * Return item's size for serialization.
+         * @return item's size for serialization.
+         */
+        TInt RequiredBufferSize();
+ 
+    private:
+
+        /**
+         * 2nd phase construction.
+         * @param aUri  Item's URI.
+         */
+        void ConstructL( const TDesC& aUri );
+        
+        /**
+         * Constructor.
+         * @param aModified  Item's last modification time.
+         * @param aMediaId  Item's media id.
+         */
+        CBlacklistItem( const TInt64& aModified,
+                const TUint32 aMediaId );
+
+    private: // data
+    
+        /** @var Item modification time */
+        TInt64 iModified;
+        
+        /** @var Item URI */
+        HBufC* iUri;
+        
+        /** Media Id of the item's location */
+        TUint32 iMediaId;
+    };
+
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/clientkeywatcherkeys.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition of clinet keys. Used by restore watcher and*
+*/
+
+
+#ifndef CLIENTKEYWATCHERKEYS_H
+#define CLIENTKEYWATCHERKEYS_H
+
+// SYSTEM INCLUDE
+#include <e32def.h>
+#include <e32cmn.h>
+
+const TUid KPSRestoreWatcherCategory = { 0x200009F5 }; // Gategory
+const TUint KPSRestoreWatcherClientsKey = 0x00000001;  // Observed key
+
+_LIT( KRestoreFile, ":\\private\\200009F5\\restoredone" ); // HARCODED PATH!
+
+#endif /*CLIENTKEYWATCHERKEYS_H*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/harvestdata.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,308 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester image plugin data transfer objects
+*
+*/
+
+
+
+#ifndef HARVESTDATA_H
+#define HARVESTDATA_H
+
+#include "mdeobject.h"
+#include "mdequery.h"
+#include "f32file.h"
+
+
+/**
+* Class used to store gps location data to an array.
+* A data transfer object.
+*/
+class CLocationData : public CBase
+    {
+    public:
+        /** Standard NewL */
+        inline static CLocationData* NewL( TReal64 aGpsLatitude, TReal64 aGpsLongitude,
+            TReal64 aGpsAltitude, TBool aGpsLaLExists, TBool aGpsAExists );
+        
+    private:
+        /** Constructor. */
+        inline CLocationData( TReal64 aGpsLatitude, TReal64 aGpsLongitude,
+            TReal64 aGpsAltitude, TBool aGpsLaLExists, TBool aGpsAExists );
+
+    public:
+
+        /** GPS latitude */
+        TReal64 iGpsLatitude;
+
+        /** GPS longitude */
+        TReal64 iGpsLongitude;
+
+        /** GPS altitude */
+        TReal64 iGpsAltitude;
+
+        /** GPS latitude and longitude exists */
+        TBool   iGpsLatAndLongExists;
+
+        /** GPS altitude exists */
+        TBool   iGpsAltitudeExists;
+    };
+
+/**
+* This class is used to match corresponding mde object and location data (if any) with two arrays.
+* Arrays are (and must be) always be of same size.
+*/
+class CObjectDataArray : public CBase
+    {
+    public:
+
+        /** Standard NewL */
+        inline static CObjectDataArray* NewL();
+        
+        /**
+        * Virtual destructor.
+        */
+        inline virtual ~CObjectDataArray();
+        
+        /**
+        * Appends a new entry to the array.
+        * @param aMdeObject  A mde object pointer
+        * @param aLocationData  Related location data
+        * @param aQuery  Location query pointer for prepared queries
+        */
+        inline void Append( CMdEObject* aMdeObject,
+        		CLocationData* aLocationData, CMdEQuery* aQuery = NULL );
+
+        /**
+        * Removes an entry from the array.
+        */
+        inline void Remove( TInt aIndex );
+
+        /**
+        * Returns how many entries there are in the array.
+        * @return Count on entries.
+        */
+        inline TInt Count();
+        
+        /**
+        * Destroys the array. Frees memory.
+        */
+        inline void ResetAndDestroy();
+        
+        /**
+        * Closes the array.
+        */
+        inline void Close();
+        
+        /**
+        * Returns a mde object by index.
+        * Leaves if index is out of bounds.
+        * @return A pointer to mde object in the array.
+        */
+        inline CMdEObject* ObjectL( const TInt aIndex );
+
+        /**
+        * Returns a location data object by index.
+        * Leaves if index is out of bounds.
+        * @return A location data object in the array.
+        */
+        inline CLocationData* LocationDataL( const TInt aIndex );
+        
+        /**
+        * Returns a query pointer by index.
+        * Might be NULL.
+        * Leaves if index is out of bounds.
+        * @return A mde query pointer in the array.
+        */
+        inline CMdEQuery* QueryL( const TInt aIndex );
+
+        /**
+        * Sets a query pointer by index in the array to the given value.
+        * @param aIndex  Array index. Leaves if out of bounds.
+        * @param aQuery  Mde query pointer to set.
+        */
+        inline void SetQuery( const TInt aIndex, CMdEQuery* aQuery );
+        
+        /**
+        * Return a reference to the mde object array used by this array.
+        * Useful as a parameter to Mde API.
+        * @return RPointerArray reference to an array used by this array.
+        */
+        inline RPointerArray<CMdEObject>& MdeObjectArray();
+
+    private:
+    
+        /** Private constructor */
+        inline CObjectDataArray();
+    
+    private:
+
+        /** Array of mde objects. */
+        RPointerArray<CMdEObject> iMdeObjectArray;
+
+        /** Array of location data objects. */
+        RPointerArray<CLocationData> iLocationArray;
+
+        /** Array of (prepared) mde query objects. */
+        RPointerArray<CMdEQuery> iQueryArray;
+    };
+
+
+/**
+* Class used to store harvested file information.
+*/
+class CFileData : public CBase
+    {
+    public:
+        TBuf16<KMaxDataTypeLength> iMime16;
+        TBuf8<KMaxDataTypeLength> iMime8;
+        TInt64 iImageDataSize;
+        TBool iJpeg;
+        TTime iModified;
+        TInt64 iFileSize;
+        TInt iImageWidth;
+        TInt iImageHeight;
+        TInt iBitsPerPixel;
+        TInt iFrameCount;
+        TBool iExifSupported;
+        TBool iDrmProtected;
+        
+        // no ownership to these
+        CMdEObjectDef* iImageDef;
+        TDesC* iUri;
+        
+        // ownership data
+        HBufC8* iImageData;
+    
+    public:
+        inline virtual ~CFileData();
+        
+        /** Standard NewL */
+        inline static CFileData* NewL();
+
+    private:
+    
+        /** Private constructor */
+        inline CFileData();
+    };
+
+/**
+* Class used to store harvested image data.
+*/    
+class CHarvestData : public CBase
+    {
+    public:
+    
+        TUint16 iWhiteBalance;
+        TUint32 iImageWidthExif; 
+        TUint32 iImageHeightExif; 
+        TUint16 iFlash;
+        TUint16 iExposureProgram;
+        TUint16 iOrientation;
+        TUint16 iYCbCrPositioning;
+        TUint16 iResolutionUnit;
+        TUint16 iIsoSpeedRating;
+        TReal32 iExposureTime;
+        TUint16 iColourSpace;
+        TReal32 iAperture;
+        TReal32 iExposureBias;
+        TUint16 iMeteringMode;
+        TUint32 iExifVersion;
+        TUint32 iFlashPixVersion;
+        TUint32 iThumbXResolution;
+        TUint32 iThumbYResolution;
+        TUint16 iThumbResolutionUnit;
+        TUint16 iThumbCompression;
+        TReal32 iShutterSpeed;
+        TUint32 iComponentsConfiguration;
+        
+        TReal32 iXResolution;
+        TReal32 iYResolution;
+        
+        TReal32 iFocalPlaneXResolution;
+        TReal32 iFocalPlaneYResolution;
+        TUint16 iFocalPlaneResolutionUnit;
+        
+        TReal32 iFNumber;
+        TReal32 iFocalLength;
+        TUint16 iFocalLengthIn35mm;
+        
+        // We must not try to store these unless they can be found in exif
+        TBool iStoreWhiteBalance;
+        TBool iStoreExposureProgram;
+        TBool iStoreExposureBias;
+        TBool iStoreOrientation;
+        TBool iStoreYCbCrPositioning;
+        TBool iStoreExifVersion;
+        TBool iStoreFlashPixVersion;
+        TBool iStoreShutterSpeed;
+        TBool iStoreAperture;
+        TBool iStoreColourSpace;
+        TBool iStoreXResolution;
+        TBool iStoreYResolution;
+        TBool iStoreExposureTime;
+        TBool iStoreThumbCompression;
+        TBool iStoreThumbResolutionUnit;
+        TBool iStoreFNumber;
+        TBool iStoreFocalLength;
+        TBool iStoreComponentsConfig;
+        TBool iStoreSamplesPerPixel;
+        TBool iStoreThumbXResolution;
+        TBool iStoreThumbYResolution;
+        TBool iStoreFocalLengthIn35;
+        TBool iStoreIsoSpeedRating;
+        TBool iStoreMeteringMode;
+        TBool iStoreFlash;
+        TBool iStoreFocalPlaneResolutionUnit;
+        TBool iStoreFocalPlaneXResolution;
+        TBool iStoreFocalPlaneYResolution;
+        
+        // bits per sample and samples per pixel not recorded in JPEG exif
+        TUint16 iSamplesPerPixel;
+        
+        HBufC16* iDescription16;
+        HBufC16* iComment16;
+        HBufC16* iCopyright16;
+        HBufC8* iDateModified8;
+        HBufC8* iDateOriginal8;
+        HBufC8* iDateDigitized8;
+        HBufC16* iMake;
+        HBufC16* iModel;
+        HBufC16* iArtist;
+        HBufC16* iRelatedSoundFile;
+        
+        // location
+        TReal64 iGpsLatitude;
+        TReal64 iGpsLongitude;
+        TReal64 iGpsAltitude;
+
+        TBool iStoreGpsLatitudeAndLongitude;
+        TBool iStoreGpsAltitude;
+    
+    public:
+        /** Virtual destructor. */
+        inline virtual ~CHarvestData();
+
+        /** Standard NewL */
+        inline static CHarvestData* NewL();
+        
+    private:
+    
+        /** Private constructor */
+        inline CHarvestData();
+    };
+
+#include "harvestdata.inl"
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/harvestdata.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,323 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester image plugin data transfer objects
+*
+*/
+
+
+
+
+
+// ---------------------------------------------------------------------------
+// Constructor for CLocationData.
+// ---------------------------------------------------------------------------
+//
+CLocationData::CLocationData( TReal64 aGpsLatitude, TReal64 aGpsLongitude,
+    TReal64 aGpsAltitude, TBool aGpsLaLExists, TBool aGpsAExists )
+    : iGpsLatitude(aGpsLatitude), iGpsLongitude(aGpsLongitude), iGpsAltitude(aGpsAltitude)
+    , iGpsLatAndLongExists(aGpsLaLExists), iGpsAltitudeExists(aGpsAExists)
+    {
+    // initializers are enough
+    }
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CLocationData* CLocationData::NewL( TReal64 aGpsLatitude, TReal64 aGpsLongitude,
+    TReal64 aGpsAltitude, TBool aGpsLaLExists, TBool aGpsAExists )
+    {
+    CLocationData* self = new (ELeave) CLocationData( aGpsLatitude,
+        aGpsLongitude, aGpsAltitude, aGpsLaLExists, aGpsAExists );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Constructor
+// ---------------------------------------------------------------------------
+//
+CObjectDataArray::CObjectDataArray()
+    {
+    // no implementation required
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor for CObjectDataArray.
+// ---------------------------------------------------------------------------
+//
+CObjectDataArray::~CObjectDataArray()
+    {
+    ResetAndDestroy();
+    Close();
+    }
+
+// CObjectDataArray
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CObjectDataArray* CObjectDataArray::NewL()
+    {
+    CObjectDataArray* self = new (ELeave) CObjectDataArray();
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Appends a new entry to a CObjectDataArray.
+// ---------------------------------------------------------------------------
+//
+void CObjectDataArray::Append( CMdEObject* aMdeObject, CLocationData* aLocationData, CMdEQuery* aQuery )
+    {
+    iMdeObjectArray.Append( aMdeObject );
+    iLocationArray.Append( aLocationData );
+    iQueryArray.Append( aQuery );
+    }
+
+// ---------------------------------------------------------------------------
+// Removes an entry from the array.
+// ---------------------------------------------------------------------------
+//
+void CObjectDataArray::Remove( TInt aIndex )
+    {
+    if ( aIndex < 0 || aIndex >= iMdeObjectArray.Count() )
+        {
+        return;
+        }
+    delete iMdeObjectArray[aIndex];
+    delete iLocationArray[aIndex];
+    delete iQueryArray[aIndex];
+    iMdeObjectArray.Remove( aIndex );
+    iLocationArray.Remove( aIndex );
+    iQueryArray.Remove( aIndex );
+    }
+
+// ---------------------------------------------------------------------------
+// Returns the count of objects in the array.
+// ---------------------------------------------------------------------------
+//
+TInt CObjectDataArray::Count()
+    {
+    return iMdeObjectArray.Count();
+    }
+
+// ---------------------------------------------------------------------------
+// ResetAndDestroy()
+// ---------------------------------------------------------------------------
+//
+void CObjectDataArray::ResetAndDestroy()
+    {
+    iMdeObjectArray.ResetAndDestroy();
+    iLocationArray.ResetAndDestroy();
+    iQueryArray.ResetAndDestroy();
+    }
+
+// ---------------------------------------------------------------------------
+// Close()
+// ---------------------------------------------------------------------------
+//
+void CObjectDataArray::Close()
+    {
+    iMdeObjectArray.Close();
+    iLocationArray.Close();
+    iQueryArray.Close();
+    }
+
+// ---------------------------------------------------------------------------
+// ObjectL()
+// ---------------------------------------------------------------------------
+//
+CMdEObject* CObjectDataArray::ObjectL( const TInt aIndex ) 
+    {
+    if ( aIndex < 0 || aIndex >= iMdeObjectArray.Count() )
+        {
+        User::Leave( KErrArgument );
+        }
+    return iMdeObjectArray[aIndex];
+    }
+
+// ---------------------------------------------------------------------------
+// LocationDataL
+// ---------------------------------------------------------------------------
+//
+CLocationData* CObjectDataArray::LocationDataL( const TInt aIndex )
+    {
+    if ( aIndex < 0 || aIndex >= iLocationArray.Count() )
+        {
+        User::Leave( KErrArgument );
+        }
+    return iLocationArray[aIndex];
+    }
+
+// ---------------------------------------------------------------------------
+// QueryL
+// ---------------------------------------------------------------------------
+//
+CMdEQuery* CObjectDataArray::QueryL( const TInt aIndex )
+    {
+    if ( aIndex < 0 || aIndex >= iQueryArray.Count() )
+        {
+        User::Leave( KErrArgument );
+        }
+    return iQueryArray[aIndex];
+    }
+
+// ---------------------------------------------------------------------------
+// SetQuery
+// ---------------------------------------------------------------------------
+//
+void CObjectDataArray::SetQuery( const TInt aIndex, CMdEQuery* aQuery )
+    {
+    if ( aIndex < 0 || aIndex >= iQueryArray.Count() )
+        {
+        return;
+        }
+    iQueryArray[aIndex] = aQuery;
+    }
+
+// ---------------------------------------------------------------------------
+// MdeObjectArray
+// ---------------------------------------------------------------------------
+//
+RPointerArray<CMdEObject>& CObjectDataArray::MdeObjectArray()
+    {
+    return iMdeObjectArray;
+    }
+
+
+// CFileData
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CFileData* CFileData::NewL()
+    {
+    CFileData* self = new (ELeave) CFileData;
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Constructor
+// ---------------------------------------------------------------------------
+//
+CFileData::CFileData()
+    {
+    // no implementation needed
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CFileData::~CFileData()
+    {
+    if ( iImageData )
+        {
+        delete iImageData;
+        iImageData = NULL;
+        }
+    iImageDef = NULL;
+    iUri = NULL;
+    }
+
+    
+// CHarvestData
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CHarvestData* CHarvestData::NewL()
+    {
+    CHarvestData* self = new (ELeave) CHarvestData;
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Constructor
+// ---------------------------------------------------------------------------
+//
+CHarvestData::CHarvestData()
+    {
+    // no implementation needed
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CHarvestData::~CHarvestData()
+    {
+    if ( iDescription16 )
+        {
+        delete iDescription16;
+        iDescription16 = NULL;
+        }
+        
+    if ( iComment16 )
+        {
+        delete iComment16;
+        iComment16 = NULL;
+        }
+        
+    if ( iCopyright16 )
+        {
+        delete iCopyright16;
+        iCopyright16 = NULL;
+        }
+        
+    if ( iDateModified8 )
+        {
+        delete iDateModified8;
+        iDateModified8 = NULL;
+        }
+        
+    if ( iDateOriginal8 )
+        {
+        delete iDateOriginal8;
+        iDateOriginal8 = NULL;
+        }
+        
+    if ( iDateDigitized8 )
+        {
+        delete iDateDigitized8;
+        iDateDigitized8 = NULL;
+        }
+        
+    if ( iMake )
+        {
+        delete iMake;
+        iMake = NULL;
+        }
+        
+    if ( iModel )
+        {
+        delete iModel;
+        iModel = NULL;
+        }
+        
+    if ( iArtist )
+        {
+        delete iArtist;
+        iArtist = NULL;
+        }
+        
+    if ( iRelatedSoundFile )
+        {
+        delete iRelatedSoundFile;
+        iRelatedSoundFile = NULL;
+        }
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/harvesterblacklist.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,107 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Blacklisting of files that fail harvesting.
+*
+*/
+
+
+#ifndef CHARVESTERBLACKLIST_H
+#define CHARVESTERBLACKLIST_H
+
+#include <e32def.h>
+
+#include "../harvester/blacklistclient/inc/blacklistclient.h"
+/**
+* This class implements blacklisting of files that
+* have failed harvesting.
+* All files should be added to blacklist while harvesting
+* and removed when harvesting is successful.
+* If harvesting fails, file is left blacklisted.
+*/
+NONSHARABLE_CLASS( CHarvesterBlacklist ) : public CBase
+    {
+    public:
+
+        /**
+         * Creates and constructs a new instance of CMdsBlacklist.
+         *
+         * @return A pointer to the created instance.
+         */
+        IMPORT_C static CHarvesterBlacklist* NewL();
+
+        /**
+         * Destructor.
+         */
+        IMPORT_C virtual ~CHarvesterBlacklist();
+
+        /**
+         * Adds a file to blacklist with it's URI.
+         * 
+         * @param aUri  URI to a file.
+         * @param aMediaId  Media Id of the media where file is located.
+         * @return KErrNone or a system wide error code.
+         */
+        IMPORT_C TInt AddFile( const TDesC& aUri, TUint32 aMediaId, TTime aLastModifiedTime  );
+
+        /**
+         * Removes a file from the blacklist.
+         * 
+         * @param aUri  URI to a file.
+         * @param aMediaId  Media Id of the media where file is located.
+         * @return KErrNone or a system wide error code.
+         */
+        IMPORT_C TInt RemoveFile( const TDesC& aUri, TUint32 aMediaId );
+
+        /**
+         * Checks if a given file is blacklisted.
+         * 
+         * @param aUri      URI to a file.
+         * @param aMediaId  Media id of the file.
+         * @return ETrue, if the file is blacklisted, otherwise EFalse.
+         */
+        IMPORT_C TBool IsBlacklisted( const TDesC& aUri, TUint32 aMediaId,  TTime aLastModifiedTime );
+        
+         /**
+         * Closes database connection through CMdSSqLiteConnection.
+         */
+         IMPORT_C void CloseDatabase();
+         
+         /**
+         * Opens database connection and load blacklist.
+         */
+         IMPORT_C void OpenDatabase();
+
+    private:
+
+        /**
+         * Constructor, called by NewL() only.
+         */
+        CHarvesterBlacklist();
+
+        /**
+         * Second phase constructor called by NewL.
+         */
+        void ConstructL();
+
+        /**
+         * Connect to blacklist client
+         */
+        void ConnectToBlackListServerL();
+
+    private: // data
+    
+        RBlacklistClient iBlacklistClient;
+    };
+
+#endif // CHARVESTERBLACKLIST_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/harvestercenreputil.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,117 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester Central Repository utility class
+*
+*/
+
+#ifndef HARVESTERCENREPUTIL_H
+#define HARVESTERCENREPUTIL_H
+
+// INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <f32file.h>
+#include "mdsfileserverpluginclient.h"
+
+struct TScanItem
+{
+	TUint32 iPreinstalled;
+	HBufC* iPath;
+	~TScanItem() { delete iPath; }
+};
+// CLASS DECLARATION
+
+/**
+*  CHarvesterCenRepUtil
+* 
+*/
+NONSHARABLE_CLASS( CHarvesterCenRepUtil ) : public CBase
+{
+public: // Constructors and destructor
+	IMPORT_C ~CHarvesterCenRepUtil();
+	IMPORT_C static CHarvesterCenRepUtil* NewL();
+	IMPORT_C static CHarvesterCenRepUtil* NewLC();
+
+public: // new functions
+    IMPORT_C void AddIgnorePathsToFspL( const TDesC& aDrivePrefix );
+    IMPORT_C void AddIgnorePathsToFspL( const TDesC& aDrivePrefix, const TDesC& aFilterPrefix );
+    IMPORT_C void RemoveIgnorePathsFromFspL( const TDesC& aDrivePrefix );
+    IMPORT_C RMdsFSPEngine& FspEngine();
+    
+    /**
+     * Append ignore paths to given array
+     * 
+     * @param aIgnorePaths ignore paths
+     */
+    IMPORT_C static void GetIgnorePathL( RPointerArray<HBufC>& aIgnorePaths );
+    
+    /**
+     * Append first boot scan paths to given array
+     * 
+     * @param aPaths scan paths
+     */
+    IMPORT_C static void GetScanItemsL( RPointerArray<TScanItem>& aItems );
+    
+    /**
+     * Append ignored first boot scan paths to given array
+     * 
+     * @param aIngorePaths ignored scan paths
+     */
+    IMPORT_C static void GetIgnoredScanPathsL( RPointerArray<HBufC>& aIngorePaths );
+
+    /**
+     * Append partial restore scan paths to given array
+     * 
+     * @param aPaths scan paths
+     */
+    IMPORT_C static void GetPartialRestorePathsL( RPointerArray<TScanItem>& aPaths );
+    
+    /**
+     * Append ignored partial restore scan paths to given array
+     * 
+     * @param aIngorePaths ignored scan paths
+     */
+    IMPORT_C static void GetIgnoredPartialRestorePathsL( RPointerArray<HBufC>& aIngorePaths );
+    
+    /**
+     * Check if ROM scanning is enabled
+     * 
+     * @param aEnabled is rom scan enabled
+     */
+    IMPORT_C static void IsRomScanEnabledL( TBool& aEnabled );
+    
+    /**
+     * Check if automatic thumbnail generation is enabled
+     * 
+     * @param aEnabled is rom scan enabled
+     */
+    IMPORT_C static void IsThumbnailDaemonEnabledL( TBool& aEnabled );
+    
+private:
+	CHarvesterCenRepUtil();
+	void ConstructL();
+
+	static void GetPathsL( TUint32 aPartialKey, RPointerArray<HBufC>& aPaths );
+	
+	static void GetItemsL( TUint32 aPartialKey, RPointerArray<TScanItem>& aPaths );
+	
+	void AddOrRemoveIgnorePathsL( const TDesC& aDrivePrefix, TBool aAdd, const TDesC& aFilterPrefix );
+	
+private: // member variables
+	RFs iFs;
+	RMdsFSPEngine iFspEngine;
+};
+
+#endif // HARVESTERCENREPUTIL_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/harvestercommon.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,105 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester server commands*
+*/
+
+
+#ifndef __HARVESTERCOMMON_H__
+#define __HARVESTERCOMMON_H__
+
+#include <harvestereventenum.h>
+#include <e32msgqueue.h>
+#include <f32file.h>
+
+enum THarvesterService
+{
+    EResumeHarvester,
+    EPauseHarvester,
+    EHarvestFile,
+    ERegisterProcessOrigin,
+    EUnregisterProcessOrigin,
+	ERegisterHarvestComplete,
+    EUnregisterHarvestComplete,
+    ERegisterHarvesterEvent,
+    EUnregisterHarvesterEvent,
+    EGetLastObserverId,
+
+#ifdef _DEBUG
+    EStopHarvester,
+#endif
+
+    EHarvestFileWithUID
+};
+
+/* Server version */
+const TUint KHarvesterServerMajorVersion = 0;
+const TUint KHarvesterServerMinorVersion = 1;
+const TUint KHarvesterServerBuildVersion = 1;
+
+/**
+ * Harvester event status which is sent from 
+ * harvester server to harvester client.
+ */
+struct THarvesterEventNotification
+	{
+	TUint iObserverId;
+	HarvesterEventObserverType iObserverType;
+	HarvesterEventState iCurrentState;
+	TUint iItemsLeft;
+	};
+
+typedef RMsgQueue<THarvesterEventNotification> THarvesterEventQueue;
+
+/**
+ * Common harvester event observer infomation.
+ * 
+ * Used for deliver client side information to server side during 
+ * registering observers and store observer information in server side.
+ */
+struct THarvesterEventObserverInfo
+	{
+	// client fills
+	TInt iQueueHandle;
+	TUint iObserverId;
+	TInt iObserverType;
+	TInt iNotificationInterval;
+
+	// server fills
+	TUint iProcessUid;
+	THarvesterEventQueue* iQueuePtr; // not owned
+	TUint iDelta;
+	};
+
+	
+_LIT(KHarvesterOomQueue, "mdsoommsgqueue");
+
+enum TMdsOomStatus
+	{
+	TMdsOomFreeRam,
+	TMdsOomMemoryGood
+	};
+
+const TInt KHarvesterGetDirFlags = ESortByDate | EDescending | EDirsFirst;
+
+const TInt KOriginIgnored = 255;
+const TInt KOriginFastHarvest = 254;
+
+const CActive::TPriority KHarvesterPriorityContextEngine = CActive::EPriorityUserInput;
+const CActive::TPriority KHarvesterPriorityMonitorPlugin = CActive::EPriorityUserInput;
+const CActive::TPriority KHarvesterPriorityComposerPlugin = CActive::EPriorityStandard;
+const CActive::TPriority KHarvesterPriorityHarvestingPlugin = CActive::EPriorityStandard;
+
+#endif
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/harvestereventmanager.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,163 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*/
+
+#ifndef HARVESTEREVENTMANAGER_H
+#define HARVESTEREVENTMANAGER_H
+
+#include <e32base.h>	// For CActive, link against: euser.lib
+#include <e32msgqueue.h>
+
+#include "harvestercommon.h"
+
+NONSHARABLE_CLASS( CHarvesterEventManager ) : public CBase
+	{
+public:
+	virtual ~CHarvesterEventManager();
+	
+	IMPORT_C static CHarvesterEventManager* GetInstanceL();	
+	IMPORT_C void ReleaseInstance();
+
+	/*
+	 * Increase event's item count
+	 * @param aHEObserverType Event type
+	 * @param aCount Increase to event's items
+	 */
+	IMPORT_C void IncreaseItemCount( HarvesterEventObserverType aHEObserverType, TUint aCount = 1 );
+
+	/*
+	 * Decrease event's item count
+	 * @param aHEObserverType Event type
+	 * @param aCount Decrease to event's items
+	 */
+	IMPORT_C TBool DecreaseItemCountL( HarvesterEventObserverType aHEObserverType, TUint aCount = 1 );
+	
+	/*
+	 * Get event's item count
+	 * @param aHEObserverType Event type
+	 * @return Event's item count
+	 */
+	IMPORT_C TUint ItemCount( HarvesterEventObserverType aHEObserverType );
+
+	/**
+	 * Send event to all matching observers.
+	 * @param aHEObserverType Event type
+	 * @param aHEState Event state
+	 * @param aItemsLeft Items left
+	 * @return Event sending error code
+	 */
+	IMPORT_C TInt SendEventL( HarvesterEventObserverType aHEObserverType, 
+			HarvesterEventState aHEState, TUint aItemsLeft = 0 );
+
+	/*
+	 * Register event observer. Leaves if registering fails.
+	 * @param aMessage Event observer's client side information
+	 */
+	IMPORT_C void RegisterEventObserverL( const RMessage2& aMessage );
+
+	/*
+	 * Unregister event observer. Returns error code if unregistering fails.
+	 * @param aMessage Event observer's client side information
+	 */
+	IMPORT_C TInt UnregisterEventObserver( const RMessage2& aMessage );
+	
+	/**
+	 * Get current state of event by event type
+	 * @param Event type
+	 * @return Currect state of event
+	 */
+	IMPORT_C HarvesterEventState CurrentState( HarvesterEventObserverType aHEObserverType );
+
+	/**
+	 * @deprecated Client generates own "Harvester Event Observer IDs"
+	 */
+	IMPORT_C TUint GetLastClientId();
+
+private:
+	/**
+	 * Server side event status.
+	 */
+	struct TEventStatus
+		{
+		HarvesterEventObserverType iObserverType;
+		HarvesterEventState iCurrentState;
+		TUint iItemsLeft;
+		};
+	
+	// C++ constructor
+	CHarvesterEventManager();
+
+	// Second-phase constructor
+	void ConstructL();
+
+	/**
+	 * Check if observer type contain wanted event type.
+	 * @param aObserverType Observer type
+	 * @param aEventType Event type
+	 * @return Does observer type contain wanted event type
+	 */
+	TBool CheckObserverType( TInt aObserverType, TInt aEventType );
+	
+	/**
+	 * Get wanted event by event type
+	 * @param aHEObserverType Wanted event type
+	 * @return Requested event or NULL
+	 */
+	TEventStatus* GetEventStatus( HarvesterEventObserverType aHEObserverType );
+	
+	/**
+	 * Send event to single observer.
+	 * @param aEventObserverInfo Observer to receive event
+	 * @param aHEObserverType Event type
+	 * @param aHEState Event state
+	 * @param aItemsLeft Items left
+	 * @return Event sending error code
+	 */
+	TInt SendSingleEvent( THarvesterEventObserverInfo& aEventObserverInfo, 
+			HarvesterEventObserverType aObserverType, 
+			HarvesterEventState aEventState, TUint aItemsLeft );
+
+private:
+
+	RArray<TEventStatus> iEventStatuses;
+	RPointerArray<THarvesterEventQueue> iEventQueues;
+	RPointerArray<THarvesterEventObserverInfo> iRegisteredObservers;
+	};
+
+/**
+* A helper class to store this singleton's static data.
+*/
+class CHarvesterEventManagerStaticData : public CBase
+    {
+    friend class CHarvesterEventManager;
+        
+    public:
+
+    	CHarvesterEventManagerStaticData( CHarvesterEventManager* aHEM ) : iHEM(aHEM), iRefCount(1)
+            {
+            }
+
+        virtual ~CHarvesterEventManagerStaticData()
+            {
+            delete iHEM;
+            }
+
+    protected:
+
+    	CHarvesterEventManager* iHEM;
+        TInt iRefCount;
+    };
+
+#endif // HARVESTEREVENTMANAGER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/harvesterexifutil.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,148 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Common Exif-utilities for harvester
+*
+*/
+
+
+#ifndef HARVESTEREXIFUTIL_H
+#define HARVESTEREXIFUTIL_H
+
+// INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <ExifRead.h>
+#include <ExifTag.h>
+#include <apmstd.h>
+#include "harvesterlog.h"
+#include "harvestdata.h"
+#include "mdeobject.h"
+#include "mdesession.h"
+
+class CExifModify;
+
+// CLASS DECLARATION
+
+/**
+*  CHarvesterExifUtil
+* 
+*/
+NONSHARABLE_CLASS( CHarvesterExifUtil ) : public CBase
+{
+public: // Constructors and destructor
+
+	/**
+		* Destructor.
+		*/
+	IMPORT_C ~CHarvesterExifUtil();
+
+		/**
+		* Two-phased constructor.
+		*/
+	IMPORT_C static CHarvesterExifUtil* NewL();
+
+		/**
+		* Two-phased constructor.
+		*/
+	IMPORT_C static CHarvesterExifUtil* NewLC();
+	
+
+	IMPORT_C void SetSession( CMdESession* aSession );
+		/**
+		* 
+		*/
+	IMPORT_C static TBool IsValidExifData(TPtr8 aData);
+
+	IMPORT_C static TInt ReadExifDataL( CHarvestData& aHd, CFileData& aFileData );
+	
+	IMPORT_C static TTime ConvertExifDateTimeToSymbianTimeL( const TDesC8& aDateTime );
+	
+	IMPORT_C TInt ComposeExifDataL( CMdEObject& aObject, TPtr8 aImagePtr, HBufC8*& aModified );
+
+	IMPORT_C void ComposeLocationL( CMdEObject* aLocation, TPtr8 aImagePtr, HBufC8*& aModified );
+	
+protected:
+	void SetExifDefaultsL( CMdEObject& aMdeObject, CExifModify& aExifModify );
+	void AddPropertyL( CMdEObjectDef& aObjectDef, CMdEObject& aMdeObject,
+			const TDesC& aProperty, TUint32 aValue );
+	void AddPropertyL( CMdEObjectDef& aObjectDef, CMdEObject& aMdeObject,
+			const TDesC& aProperty, TUint16 aValue );
+	TBool ModifyExifTagL( CMdEObject& aMdeObject, CExifModify& aExifModify,
+			const TDesC& aProperty, TExifIfdType aIFD, TUint16 aTagID, TBool aRemove = EFalse );
+	HBufC8* GetPropertyValueLC( const CMdEPropertyDef& aPropDef,
+			const CMdEProperty& aProperty );
+	CExifTag::TExifTagDataType ExifTagDataType( TUint16 aTagID, const CMdEPropertyDef& aPropDef );
+	
+	TBool CompareTag( TPtrC8 aMdeData, const CExifTag* aTag );
+	
+	static HBufC16* ReadExifTagL( const CExifRead& aReader, TExifIfdType aIFD, TUint16 aTagID );
+
+	static void StripNulls( HBufC& aString );
+
+private:
+
+	/**
+		* Constructor for performing 1st stage construction
+		*/
+	CHarvesterExifUtil();
+
+	/**
+		* default constructor for performing 2nd stage construction
+		*/
+	void ConstructL();
+	
+	static void ReadUserCommentL( CHarvestData& aHd, CExifRead* aReader );
+	
+	static void ReadXResolutionL( CHarvestData& aHd, CExifRead* aReader );
+	
+	static void ReadYResolutionL( CHarvestData& aHd, CExifRead* aReader );
+	
+	static void ReadExposureBiasL( CHarvestData& aHd, CExifRead* aReader );
+	
+	static void ReadExposureTimeL( CHarvestData& aHd, CExifRead* aReader );
+	
+	static void ReadFNumberL( CHarvestData& aHd, CExifRead* aReader );
+	
+	static void ReadShutterSpeedL( CHarvestData& aHd, CExifRead* aReader );
+	
+	static void ReadApertureValueL( CHarvestData& aHd, CExifRead* aReader );
+	
+	static void ReadFocalLengthL( CHarvestData& aHd, CExifRead* aReader );
+	
+	static void ReadFocalLength35mmL( CHarvestData& aHd, CExifRead* aReader );
+	
+	static void ReadFocalXPlaneResolutionL( CHarvestData& aHd, CExifRead* aReader );
+	
+	static void ReadFocalYPlaneResolutionL( CHarvestData& aHd, CExifRead* aReader );
+	
+	static void ReadGPSLatitudeL( CHarvestData& aHd, CExifRead* aReader, TBool& aLatitude );
+	
+	static void ReadGPSLongitudeL( CHarvestData& aHd, CExifRead* aReader, TBool& aLatitude );
+	
+	static void ReadGPSAltitudeL( CHarvestData& aHd, CExifRead* aReader );
+	
+private:
+	
+	/** Pointer to mde session to use */
+    CMdESession* iSession;
+    
+    /** Mde default namespace. NOT OWN. */
+    CMdENamespaceDef* iDefaultNamespace;
+    
+    
+
+};
+
+#endif // HARVESTEREXIFUTIL_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/harvestermediaidutil.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,69 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Utility class to keep a list of mediaid's
+*/
+
+#ifndef HARVESTERMEDIAIDUTIL_H
+#define HARVESTERMEDIAIDUTIL_H
+
+#include <e32base.h>
+#include <f32file.h>
+
+const TInt KHarvesterMediaIdTLSKey = 0x200009FE;
+
+class CHarvesterMediaIdUtil : public CBase
+	{
+	friend class RMediaIdUtil;
+	
+public: 
+	
+	IMPORT_C TInt GetMediaId( const TDesC& aUri, TUint32& aMediaId );
+	
+	IMPORT_C TInt GetDriveLetter( TUint32 aMediaId, TChar& aChar );
+	
+	IMPORT_C void RemoveMediaId( TUint32 aMediaId );
+	
+private:
+	
+	static CHarvesterMediaIdUtil* NewL();
+		
+	~CHarvesterMediaIdUtil();
+		
+	CHarvesterMediaIdUtil();
+	
+	void ConstructL();
+	
+private:
+    TUint32 iMediaId[KMaxDrives];
+	RFs iFs;
+	TVolumeInfo iVolumeInfo;
+	
+	};
+
+struct TMediaIdUtilInfo
+	{
+	CHarvesterMediaIdUtil* iMediaIdUtil;
+    TInt iRefCount;
+	};
+
+
+class RMediaIdUtil 
+    {
+public:
+   	IMPORT_C static CHarvesterMediaIdUtil& GetInstanceL();
+
+   	IMPORT_C static void ReleaseInstance();
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/harvesterpluginfactory.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#ifndef __CHARVESTERPLUGINFACTORY_H__
+#define __CHARVESTERPLUGINFACTORY_H__
+
+#include <e32base.h>
+
+// FORWARD DECLARATION 
+class CHarvesterPluginInfo;
+class CHarvesterPlugin;
+class CHarvesterData;
+class CHarvesterBlacklist;
+
+NONSHARABLE_CLASS( CHarvesterPluginFactory ) : public CBase
+	{
+	public:
+
+		IMPORT_C static CHarvesterPluginFactory* NewL();
+		virtual ~CHarvesterPluginFactory();
+		
+		IMPORT_C void GetObjectDefL( CHarvesterData& aHD, TDes& aObjectDef );
+		IMPORT_C void GetMimeType(const TDesC& aUri, TDes& aMimeType);
+		IMPORT_C TInt HarvestL( CHarvesterData* aHD );
+		IMPORT_C RPointerArray<CHarvesterPluginInfo>& GetPluginInfos();
+		IMPORT_C void SetBlacklist( CHarvesterBlacklist& aBlacklist );
+		IMPORT_C TBool IsSupportedFileExtension( const TDesC& aFileName );
+		IMPORT_C TBool IsContainerFileL( const TDesC& aURI );
+
+	private:
+		CHarvesterPluginFactory();
+		void ConstructL();
+		void SetupHarvesterPluginInfoL();
+		void AddNewPluginL( const TDesC8& aType, const TDesC8& aOpaque, TUid aPluginUid );
+		void GetSupportedPluginsL( RPointerArray<CHarvesterPluginInfo>& aSupportedPlugins, const TDesC& aExt );
+		
+	private:
+		RPointerArray<CHarvesterPluginInfo> iHarvesterPluginInfoArray;
+		CHarvesterBlacklist* iBlacklist;
+	};
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/harvesterplugininfo.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,65 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester plugin information struct*
+*/
+
+#ifndef __HARVESTERPLUGININFO_H__
+#define __HARVESTERPLUGININFO_H__
+
+#include "harvesterplugin.h"
+
+class CHarvesterData;
+
+class CHarvesterPluginInfo : public CBase
+	{
+public:
+	virtual ~CHarvesterPluginInfo()
+	{
+		delete iPlugin;
+		iExtensions.ResetAndDestroy();
+		iExtensions.Close();
+		iObjectTypes.ResetAndDestroy();
+		iObjectTypes.Close();
+		iQueue.ResetAndDestroy();
+		iQueue.Close();
+	}
+	
+	CHarvesterPluginInfo() : CBase(), iPlugin( NULL ), iPluginUid( KNullUid )
+	{
+	}
+	
+	/** @var 	CHarvesterPlugin Plugin
+	 *  @brief 	Pointer to the loaded plugin. */
+	CHarvesterPlugin* iPlugin;
+
+	/** @var 	RPointerArray<TDesC> iExtensions
+	 *  @brief 	Supported extensions of the plugin. */
+    RPointerArray<TDesC> iExtensions;
+    
+    /** @var 	RPointerArray<TDesC> iObjectTypes
+	 *  @brief 	Describes plugin - returned by CImplementationInformation->DataType(). */
+    RPointerArray<TDesC> iObjectTypes;
+
+    /** @var 	TUid iPluginUid;
+	 *  @brief 	Harvester plugin UID */	    
+    TUid iPluginUid;
+
+	/** */	
+	RPointerArray<CHarvesterData> iQueue;
+	
+private:
+	};
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/listener.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,187 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition of CListener class. Observers RProperty changes.
+*
+*/
+
+
+#ifndef LISTENER_H
+#define LISTENER_H
+
+// SYSTEM INCLUDES
+#include <aknappui.h> 
+#include <aknViewAppUi.h>
+#include <e32property.h>
+#include <e32def.h>
+
+// FORWARD DECLARATIONS
+class MKeyObserver;
+class MKeyAndStatusObserver;
+
+// CLASS DECLARATION
+/**
+ *  Property listener class.
+ *  Observes property keys for key values and status changes.
+ *
+ *  @code
+ *  // Create new listener.
+ *	CListener* listener = CListener::NewL( 
+ *			 aPropertyCategory,
+ *			 aKey
+ *			 ); 
+ *	 
+ *	listener->RegisterNewClientForKeyValueL( aKeyObserver );
+ *  @endcode
+ *
+ *  @lib common.lib
+ *  @since -
+ */
+NONSHARABLE_CLASS( CListener )  : public CActive
+    {
+public: 
+
+    /**
+     * Factory method NewL
+     * @param aPropertyCategory The property's category.   
+     * @param aKey       		The P&S key to be watched. 
+     * @return           		The new watcher object. 
+     */
+    static CListener* NewL( const TUid aPropertyCategory,
+    			const TUint aKey );
+    
+    /**
+     * Factory method NewLC
+     * @param aPropertyCategory The property's category.   
+     * @param aKey       		The P&S key to be watched. 
+     * @return           		The new watcher object on the cleanupstack. 
+      */
+     static CListener* NewLC( const TUid aPropertyCategory,
+     			const TUint aKey );
+     
+    /**
+     * Destructor. Make public to clean it via CPropertyWatcher. 
+     */
+    virtual ~CListener();
+    
+public: // New functions
+	        
+    /**
+     * Returns observed key.
+     * @return The key value.          		
+     */
+    TUint ObservedKey () const;
+    
+    /**
+     * Returns observed category.
+     * @return The category's uid.          		
+     */
+    TUid ObservedCategory () const;
+    
+    /**
+     * Removes watcher client. 
+     * @param aKeyObserver    Pointer to caller's adress.   
+     */
+    void RegisterNewClientForKeyValueL ( const MKeyObserver* aKeyObserver );
+    
+    /**
+     * Adds new watcher client. Listens key and status changes.
+     * @param aKeyAndStatusObserver    Pointer to caller's adress.   
+     */
+    void RegisterNewClientForKeyAndStatusL ( const MKeyAndStatusObserver* aKeyAndStatusObserver );
+    
+     /**
+      * Removes watcher client. 
+      * @param aKeyObserver    Pointer to caller's adress.   
+      */
+    void UnregisterKeyClient( const MKeyObserver* aKeyObserver );
+    	
+     /**
+      * Removes watcher client. 
+      * @param aKeyAndStatusObserver    Pointer to caller's adress.   
+      */
+   	void UnregisterKeyAndStatusClient( 
+    			const MKeyAndStatusObserver* aKeyAndStatusObserver );
+ 
+private: // Construction and destruction.	
+
+    /**
+     * Constructor.
+     * @param aPropertyCategory The property's category.   
+     * @param aKey       		The P&S key to be watched. 
+	 */
+   	CListener::CListener( const TUid aPropertyCategory,
+    			const TUint aKey ); 
+    	
+   	/**
+	 * Symbian 2nd phase constructor.
+	 */
+    void ConstructL();
+	
+private: // Functions from CActive
+    /**
+     *	Implements CActive
+     */
+    void RunL();
+ 
+    /**
+     *	Implements CActive
+     *	@param aError the error returned
+     *	@return error
+     */
+    TInt RunError( TInt aError );
+
+    /**
+     *	Implements CActive
+     */
+    void DoCancel();
+            
+private:
+    	
+    /**
+     *	Starts active object - listen key changes.
+     */
+	void StartListening();
+ 
+	/**
+     *	Send notifications to registered clients.
+     *	@param aKeyValue - observed key's value.
+     *	@return aStatus - reference to iStatus.
+     */
+	void SendNotificationsL( const TUint aKeyValue,
+			TRequestStatus& aStatus ) const; 
+    
+private: // Data
+    
+    /*iArrayForKeyValue - all registered clients for value
+     * owned by this class.*/
+    RPointerArray<MKeyObserver> iArrayForKeyValue;    
+
+	/*iArrayForKeyAndStatus - all registered clients for status
+     * owned by this class*/
+    RPointerArray<MKeyAndStatusObserver> iArrayForKeyAndStatus;  
+ 
+    /*iPropertyCategory; - property's gategory.
+     * owned by this class*/
+    TUid iPropertyCategory;
+	
+	/*iKey - observed key, owned by this class*/
+    TUint iKey;
+    
+	/*iProperty - owned by this class*/
+    RProperty iProperty;
+    };
+
+#endif // LISTENER_H
+
+// End of File.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/mdeobjectwrapper.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,71 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#ifndef MDEOBJECTWRAPPER_H
+#define MDEOBJECTWRAPPER_H
+
+// INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+// CLASS DECLARATION
+class CMdEObject;
+class CMdEPropertyDef;
+
+/**
+*  CMdeObjectWrapper
+* 
+*/
+NONSHARABLE_CLASS( CMdeObjectWrapper ) : public CBase
+{
+public: // Constructors and destructor
+
+	/**
+		* Destructor.
+		*/
+	~CMdeObjectWrapper();
+
+		/**
+		* Two-phased constructor.
+		*/
+	IMPORT_C static CMdeObjectWrapper* NewL();
+
+		/**
+		* Two-phased constructor.
+		*/
+	IMPORT_C static CMdeObjectWrapper* NewLC();
+	
+	IMPORT_C void HandleObjectPropertyL(CMdEObject& aMdeObject, const TDesC& aPropertyType, TAny* aData, TBool aIsAdd = ETrue);
+
+	IMPORT_C static void HandleObjectPropertyL(CMdEObject& aMdeObject, CMdEPropertyDef& aPropertyDef, TAny* aData, TBool aIsAdd = ETrue);
+	
+private:
+
+	/**
+		* Constructor for performing 1st stage construction
+		*/
+	CMdeObjectWrapper();
+
+	/**
+		* default constructor for performing 2nd stage construction
+		*/
+	void ConstructL();
+
+};
+
+#endif // MDEOBJECTWRAPPER_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/mimetypemapping.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef MIMETYPEMAPPING_H_
+#define MIMETYPEMAPPING_H_
+
+//
+// TMimeTypeMapping
+// 
+// Helper class for mapping file extensions 
+// to MIME types and harvesting method.
+//
+template <typename T> class TMimeTypeMapping
+	{
+	public:
+		TPtrC iExt;
+		TPtrC iMimeType;
+		T iHandler;
+		
+		TMimeTypeMapping(TPtrC aExt);
+
+		TMimeTypeMapping(TPtrC aExt, TPtrC aMimeType, const T& aHandler);
+		
+		static TInt CompareFunction(const TMimeTypeMapping& aKey, 
+				const TMimeTypeMapping& aItem);
+	};
+
+#include "mimetypemapping.inl"
+
+#endif /*MIMETYPEMAPPING_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/mimetypemapping.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+
+template <typename T> TMimeTypeMapping<T>::TMimeTypeMapping(TPtrC aExt)
+	{
+	iExt.Set( aExt.Ptr(), aExt.Length() );
+	}
+
+template <typename T> TMimeTypeMapping<T>::TMimeTypeMapping(TPtrC aExt, TPtrC aMimeType, const T& aHandler) :
+	iHandler( aHandler )
+	{
+	iExt.Set( aExt.Ptr(), aExt.Length() );
+	iMimeType.Set( aMimeType.Ptr(), aMimeType.Length() );
+	}
+
+template <typename T> TInt TMimeTypeMapping<T>::CompareFunction(
+		const TMimeTypeMapping<T>& aKey,
+		const TMimeTypeMapping<T>& aItem)
+	{
+	return aKey.iExt.CompareF( aItem.iExt );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/mpropertyobserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface class.
+*
+*/
+
+
+#ifndef MPROPERTYWATCHER_H
+#define MPROPERTYWATCHER_H
+
+// SYSTEM INCLUDE
+#include <e32base.h>
+
+// CLASS DECLARATION 
+class MKeyObserver
+	{
+public:
+
+
+	/**
+	 * Factory method NotifyKeyAndStatusL
+	 * @param aKeyValue - observed key's value.
+	 * @param aPropertyCategory observed key's category.
+	 * @param aKey The P&S key to be watched.
+	 */
+	virtual void NotifyKeyL( 
+					const TInt aKeyValue,
+					const TUid aPropertyCategory,
+					const TUint aKey ) = 0;
+		};
+	
+// CLASS DECLARATION
+class MKeyAndStatusObserver
+	{
+public:
+
+    /**
+     * Factory method NotifyKeyAndStatusL
+     * @param aKeyValue - observed key's value.
+     * @param aStatus - reference to iStatus.
+     * @param aPropertyCategory observed key's category.
+     * @param aKey he P&S key to be watched.
+     */
+	virtual void NotifyKeyAndStatusL( 
+				const TInt aKeyValue,
+				TRequestStatus& aStatus,
+				const TUid aPropertyCategory,
+				const TUint aKey ) = 0;
+	};
+	
+#endif // MPROPERTYWATCHER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/processoriginmapperinterface.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface for mds item origin mappers.*
+*/
+
+#ifndef PROCESSORIGINMAPPERINTERFACE_H
+#define PROCESSORIGINMAPPERINTERFACE_H
+
+/**
+ * Interface for component that maps mds origin values
+ * based on process id that created the file.
+ */
+class MProcessOriginMapperInterface
+    {
+    public:
+    
+        /**
+         * Add a process to the list.
+         * @param aProcessUid  Uid of the process to add.
+         * @param aOrigin      Origin to which this process will mapped to.
+         */
+        virtual void RegisterProcessL( const TUid& aProcessId,
+                               const TOrigin& aOrigin ) = 0;
+        
+        /**
+         * Remove a process from the list.
+         * @param aProcessId  Uid of the process to remove.
+         */
+        virtual void UnregisterProcessL( const TUid& aProcessId ) = 0;
+    };
+
+#endif // PROCESSORIGINMAPPERINTERFACE_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/inc/propertywatcher.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,175 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition of CPropertyWatcher class.*
+*/
+
+
+#ifndef PROPERTYWATCHER_H
+#define PROPERTYWATCHER_H
+
+// SYSTEM INCLUDE
+#include <e32base.h>
+
+// FORWARD DECLARATIONS
+class CListener;
+class MKeyObserver;
+class MKeyAndStatusObserver;
+
+// CLASS DECLARATION
+/**
+ *  An instance of the CPropertyWatcher object - singleton.
+ *  Create listeners for RProperty key changes. This class
+ *  uses TLS implementation. 
+ *
+ *  @code
+ *	
+ * // Get instance
+ * iPropertyWatcher = CPropertyWatcher::GetInstanceL();
+ *	
+ * // Set wanted key, give gategory's uid, observed key and this pointer.
+ * iPropertyWatcher->ListenKeyChangesL( KUidSystemCategory,
+ *  	conn::KUidBackupRestoreKey, this );
+ *	iPropertyWatcher->ListenKeyChangesL( KPSUidScreenSaver,
+ *  	KScreenSaverOn, this );
+ *
+ * ...
+ *  // Implement NotifyKeyL for key canges or NotifyKeyAndStatusL for
+ *  // key and status changes. 
+ *  void CRestoreWatcher::NotifyKeyL( 
+ *		const TInt aKeyValue,
+ *		const TUid aPropertyCategory,
+ *		const TUint aKey)
+ *	{
+ *	
+ *	// In interface check key's category. 
+ *	if( aPropertyCategory == KUidSystemCategory &&
+ *		aKey == conn::KUidBackupRestoreKey )
+ *		{
+ *		TInt backupStateValue = aKeyValue;
+ *		backupStateValue &= conn::KBURPartTypeMask;
+ *		
+ *		if ( backupStateValue >= conn::EBURRestoreFull )
+ *			{
+ *			// Handle backup here
+ *			}
+ *		}
+ *	
+ *	if( aPropertyCategory == KPSUidScreenSaver && aKey == KScreenSaverOn )
+ *		{
+ *		//Handle screensaver activity here 
+ *		}	
+ *	}
+ * 
+ *  // Destruction
+ * 
+ * 	if( iPropertyWatcher )
+ *		{
+ *		iPropertyWatcher->StopListeningKeyChanges( 
+			KUidSystemCategory,
+			conn::KUidBackupRestoreKey, this );
+ *		
+ *		iPropertyWatcher->Delete(); // Release connection to TLS object.
+ *		} 
+ * 
+ * @endcode
+ */
+NONSHARABLE_CLASS( CPropertyWatcher ) : public CBase
+    {
+ public: // Exported.
+		
+	/*!
+	@function GetInstanceL
+	@Create a CPropertyWatcher object, 
+	@result a pointer to the created instance of CPropertyWatcher.
+	*/
+	IMPORT_C static CPropertyWatcher* GetInstanceL();
+	
+	/*!
+	@function Delete
+	@Release an instance of this singleton.
+	*/
+	IMPORT_C void Delete();
+		
+	/*!
+	@function ListenKeyChanges
+	@Registers to watcher and get events from watcher via MKeyObserver interface.
+	@param aPropertyCategory observed key's category.       
+	@param aKey observed key.
+	@aValueObserver client's pointer. Notive that this is not taking ownership.
+	*/
+	IMPORT_C void ListenKeyChangesL( const TUid aPropertyCategory,
+			 const TUint aKey,
+			 const MKeyObserver* aValueObserver
+			);
+   /*
+	@function ListenKeyAndStatusChangesL
+	@Registers to watcher and get events from watcher via MKeyAndStatusObserver interface.
+	@param aPropertyCategory observed key's category.       
+	@param aKey observed key.
+	@aStatusObserver client's pointer. Notive that this is not taking ownership.
+	*/
+   IMPORT_C void ListenKeyAndStatusChangesL( const TUid aPropertyCategory,
+			const TUint aKey,
+			const MKeyAndStatusObserver* aStatusObserver );
+
+   /*
+	@function StopListeningKeyChanges
+	@Stops listening key changes. 
+	@param aPropertyCategory observed key's category.       
+	@param aKey observed key.
+	@aValueObserver client's pointer.
+	*/
+   IMPORT_C void StopListeningKeyChanges( 
+			const TUid aPropertyCategory,
+			const TUint aKey,
+			const MKeyObserver* aKeyObserver );
+   
+   /*
+	@function StopListeningKeyAndStatusChanges
+	@Stops listening key and status changes. MDS need this to stop Active sheduler during restore.
+	@param aPropertyCategory observed key's category.       
+	@param aKey observed key.
+	@aValueObserver client's pointer.
+	*/
+    IMPORT_C void StopListeningKeyAndStatusChanges( 
+			const TUid aPropertyCategory,
+			const TUint aKey,
+			MKeyAndStatusObserver* aStatusObserver );
+ 
+private:  
+   /*!
+	@function ~CPropertyWatcher
+	@Destroy the object and release all memory objects.
+	*/
+	~CPropertyWatcher();  
+
+private:
+	/*!
+	@function FindListener
+	@Find if there is allredy listener which matches
+	@aPropertyCategory and aKey.
+	@return listener index, KErrNotFound if not exists.
+	*/    	
+	TInt FindListener( const TUid aPropertyCategory, const TUint aKey ) const;
+  
+private:
+  
+	/*!@iListenersArray - all listeners for different key values.
+	 * Owned by this class.
+	 */
+	RPointerArray<CListener> iListenersArray;    
+    };
+
+#endif // PROPERTYWATCHER
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/blacklistitem.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,116 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// CBlacklistItem
+
+#include "blacklistitem.h"
+#include "mdsutils.h"
+#include "mdcserializationbuffer.h"
+
+// ---------------------------------------------------------------------------
+// Standard NewL for CBlacklistItem
+// ---------------------------------------------------------------------------
+//
+CBlacklistItem* CBlacklistItem::NewL( const TInt64& aModified, const TDesC& aUri,
+    const TUint32 aMediaId )
+    {
+    CBlacklistItem* self = new (ELeave) CBlacklistItem( aModified, aMediaId );
+    CleanupStack::PushL( self );
+    self->ConstructL( aUri );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// ConstructL()
+// 2nd phase construction.
+// ---------------------------------------------------------------------------
+//
+void CBlacklistItem::ConstructL( const TDesC& aUri )
+    {
+    iUri = aUri.AllocL();
+    }
+
+// ---------------------------------------------------------------------------
+// 
+// ---------------------------------------------------------------------------
+//
+CBlacklistItem::~CBlacklistItem()
+    {
+    delete iUri;
+    }
+
+// ---------------------------------------------------------------------------
+// Constructor for CBlacklistItem
+// ---------------------------------------------------------------------------
+//
+CBlacklistItem::CBlacklistItem( const TInt64& aModified,
+    const TUint32 aMediaId )
+    : iModified( aModified ), iUri( NULL ), iMediaId( aMediaId )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// Search a file from blacklist cache.
+// ---------------------------------------------------------------------------
+//
+TBool CBlacklistItem::Compare( const TDesC& aUri, const TUint32 aMediaId )
+    {
+    if ( iUri && MdsUtils::Compare( *iUri, aUri ) == 0 && iMediaId == aMediaId )
+        {
+        return ETrue;
+        }
+    return EFalse;
+    }
+
+// ---------------------------------------------------------------------------
+// Returns item's last modification time.
+// ---------------------------------------------------------------------------
+//
+const TInt64& CBlacklistItem::Modified()
+    {
+    return iModified;
+    }
+
+// ---------------------------------------------------------------------------
+// Returns item's MediaId.
+// ---------------------------------------------------------------------------
+//
+const TUint32& CBlacklistItem::MediaId()
+    {
+    return iMediaId;
+    }
+
+// ---------------------------------------------------------------------------
+// Returns item's Uri.
+// ---------------------------------------------------------------------------
+//
+const HBufC* CBlacklistItem::Uri()
+    {
+    return iUri;
+    }
+    // ---------------------------------------------------------------------------
+// Returns item's Uri.
+// ---------------------------------------------------------------------------
+//
+TInt CBlacklistItem::RequiredBufferSize()
+    {
+    return ( CMdCSerializationBuffer::KRequiredSizeForTInt64 +
+        CMdCSerializationBuffer::KRequiredSizeForTUint32 + 
+        CMdCSerializationBuffer::RequiredSize( *iUri ) );
+    }
+    
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/harvesterblacklist.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,125 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Keeps a list of files that should not be harvested.
+*
+*/
+
+
+#include <f32file.h>
+
+#include "harvesterlog.h"
+#include "harvesterblacklist.h"
+
+// CHarvesterBlacklist
+
+// ---------------------------------------------------------------------------
+// Default constructor for first phase construction.
+// ---------------------------------------------------------------------------
+//
+CHarvesterBlacklist::CHarvesterBlacklist() 
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// Second phase construction
+// ---------------------------------------------------------------------------
+//
+void CHarvesterBlacklist::ConstructL() // second-phase constructor
+    {
+    ConnectToBlackListServerL();
+    }
+
+// ---------------------------------------------------------------------------
+// ConnectToBlackListServerL()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterBlacklist::ConnectToBlackListServerL()
+    {
+    User::LeaveIfError( iBlacklistClient.Connect() );
+    }
+
+// ---------------------------------------------------------------------------
+// The usual NewL()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CHarvesterBlacklist* CHarvesterBlacklist::NewL()
+    {
+    CHarvesterBlacklist* self = new (ELeave) CHarvesterBlacklist();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+    
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CHarvesterBlacklist::~CHarvesterBlacklist()
+    {
+    // close connection
+    iBlacklistClient.Close();
+    }
+
+// ---------------------------------------------------------------------------
+// Adds a file to blacklist with it's URI. Doesn't leave.
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt CHarvesterBlacklist::AddFile( const TDesC& aUri, TUint32 aMediaId, TTime aLastModifiedTime )
+    {
+    TRAPD( err, iBlacklistClient.AddL( aUri, aMediaId, aLastModifiedTime ) );
+    return err;
+    }
+
+// ---------------------------------------------------------------------------
+// Removes a file from the blacklist. Doesn't leave.
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt CHarvesterBlacklist::RemoveFile( const TDesC& aUri, TUint32 aMediaId )
+    {
+    TRAPD( err, iBlacklistClient.RemoveL( aUri, aMediaId ) );
+    return err;
+    }
+
+
+// ---------------------------------------------------------------------------
+// Checks if a given file is blacklisted. And doesn't leave.
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TBool CHarvesterBlacklist::IsBlacklisted( const TDesC& aUri, TUint32 aMediaId, TTime aLastModifiedTime )
+    {
+    TBool isBlacklisted( EFalse );
+    TRAP_IGNORE( isBlacklisted = iBlacklistClient.IsBlacklistedL( aUri, aMediaId, aLastModifiedTime ) );
+    return isBlacklisted;
+    }
+ 
+// ---------------------------------------------------------------------------
+// Closes database connection.
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CHarvesterBlacklist::CloseDatabase()
+    {
+    TRAP_IGNORE( iBlacklistClient.CloseDBL() );
+    }
+    
+// ---------------------------------------------------------------------------
+// Closes database connection.
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CHarvesterBlacklist::OpenDatabase()
+    {
+    TRAP_IGNORE( iBlacklistClient.LoadBlacklistL() );
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/harvestercenreputil.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,244 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester Central Repository utility class*
+*/
+
+
+#include "harvestercenreputil.h"
+#include "centralrepository.h"
+#include "mdsutils.h"
+#include "mdeconstants.h"
+
+const TUid KHarvesterRepoUid = { 0x200009FE };
+const TUint32 KSearchMask                     = 0xFFFF0000;
+const TUint32 KIgnorePathPartialKey           = 0x00010000;
+const TUint32 KBootScanPartialKey             = 0x00020000;
+const TUint32 KBootIgnorePartialKey           = 0x00030000;
+const TUint32 KPartialRestorePartialKey       = 0x00040000;
+const TUint32 KPartialRestoreIgnorePartialKey = 0x00050000;
+
+const TUint32 KRomScanEnabledKey              = 0x00090000;
+
+const TInt32 KThumbnailManagerCenrepUID = 0x102830B0; // TNM cenrep uid
+const TUint32 KEnableDaemon = 0x300; // from TNM
+
+CHarvesterCenRepUtil::CHarvesterCenRepUtil()
+	{
+	// No implementation required
+	}
+
+
+EXPORT_C CHarvesterCenRepUtil::~CHarvesterCenRepUtil()
+	{
+	iFspEngine.Close();
+	iFs.Close();
+	}
+
+EXPORT_C CHarvesterCenRepUtil* CHarvesterCenRepUtil::NewLC()
+	{
+	CHarvesterCenRepUtil* self = new (ELeave)CHarvesterCenRepUtil();
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+	}
+
+EXPORT_C CHarvesterCenRepUtil* CHarvesterCenRepUtil::NewL()
+	{
+	CHarvesterCenRepUtil* self=CHarvesterCenRepUtil::NewLC();
+	CleanupStack::Pop(); // self;
+	return self;
+	}
+
+void CHarvesterCenRepUtil::ConstructL()
+	{
+	User::LeaveIfError( iFs.Connect() );
+	User::LeaveIfError( iFspEngine.Open( iFs, KMdsFSPluginPosition ) );
+	}
+
+EXPORT_C RMdsFSPEngine& CHarvesterCenRepUtil::FspEngine()
+	{
+	return iFspEngine;
+	}
+
+EXPORT_C void CHarvesterCenRepUtil::AddIgnorePathsToFspL( const TDesC& aDrivePrefix )
+	{
+	AddOrRemoveIgnorePathsL( aDrivePrefix, ETrue, KNullDesC );
+	}
+
+EXPORT_C void CHarvesterCenRepUtil::AddIgnorePathsToFspL( const TDesC& aDrivePrefix,
+														  const TDesC& aFilterPrefix )
+	{
+	AddOrRemoveIgnorePathsL( aDrivePrefix, ETrue, aFilterPrefix);
+	}
+
+EXPORT_C void CHarvesterCenRepUtil::RemoveIgnorePathsFromFspL( const TDesC& aDrivePrefix )
+	{
+	AddOrRemoveIgnorePathsL( aDrivePrefix, EFalse, KNullDesC );
+	}
+
+void CHarvesterCenRepUtil::AddOrRemoveIgnorePathsL( const TDesC& aDrivePrefix,
+													TBool aAdd,
+													const TDesC& aFilterPrefix )
+	{
+	CRepository* repo = CRepository::NewLC( KHarvesterRepoUid ); 
+	RArray<TUint32> ignoredKeys;
+	CleanupClosePushL( ignoredKeys );
+	TInt ret = repo->FindL( KIgnorePathPartialKey, KSearchMask, ignoredKeys );
+	
+	TBuf<KMaxFileName> path;
+	const TInt count = ignoredKeys.Count();
+	for( TInt i=0;i<count;i++ )
+		{
+		const TInt error( repo->Get( ignoredKeys[i], path ) );
+		if( error != KErrNone )
+		    {
+		    continue;
+		    }
+		if( aFilterPrefix != KNullDesC )
+			{
+			TPtrC pathStart = path.Left( aFilterPrefix.Length() );
+			if( MdsUtils::Compare( pathStart, aFilterPrefix ) != 0 )
+				{
+				continue;
+				}
+			}
+		HBufC* ignorePath = HBufC::NewL( aDrivePrefix.Length() + path.Length() );
+		TPtr ptr = ignorePath->Des();
+		ptr.Append( aDrivePrefix );
+		ptr.Append( path );
+		if( aAdd )
+			{
+			iFspEngine.AddIgnorePath( *ignorePath );
+			}
+		else
+			{
+			iFspEngine.RemoveIgnorePath( *ignorePath );
+			}
+		delete ignorePath;
+		ignorePath = NULL;
+		}
+	CleanupStack::PopAndDestroy( &ignoredKeys );
+	CleanupStack::PopAndDestroy( repo );	
+	}
+
+EXPORT_C void CHarvesterCenRepUtil::GetIgnorePathL( 
+		RPointerArray<HBufC>& aIgnorePaths )
+	{
+	GetPathsL( KIgnorePathPartialKey, aIgnorePaths );
+	}
+
+EXPORT_C void CHarvesterCenRepUtil::GetScanItemsL(
+		RPointerArray<TScanItem>& aItems )
+	{
+	GetItemsL( KBootScanPartialKey, aItems );
+	}
+
+EXPORT_C void CHarvesterCenRepUtil::GetIgnoredScanPathsL( 
+		RPointerArray<HBufC>& aIngorePaths )
+	{
+	GetPathsL( KBootIgnorePartialKey, aIngorePaths );
+	}
+
+EXPORT_C void CHarvesterCenRepUtil::GetPartialRestorePathsL( 
+		RPointerArray<TScanItem>& aPaths )
+	{
+	GetItemsL( KPartialRestorePartialKey, aPaths );
+	}
+
+EXPORT_C void CHarvesterCenRepUtil::GetIgnoredPartialRestorePathsL( 
+		RPointerArray<HBufC>& aIngorePaths )
+	{
+	GetPathsL( KPartialRestoreIgnorePartialKey, aIngorePaths );
+	}
+	
+EXPORT_C void CHarvesterCenRepUtil::IsRomScanEnabledL( TBool& aEnabled )
+    {
+    CRepository* rep = CRepository::NewLC( KHarvesterRepoUid );
+    
+    rep->Get( KRomScanEnabledKey, aEnabled );
+    
+    CleanupStack::PopAndDestroy( rep );    
+    }
+
+EXPORT_C void CHarvesterCenRepUtil::IsThumbnailDaemonEnabledL( TBool& aEnabled )
+    {
+    CRepository* rep = CRepository::NewLC( TUid::Uid( KThumbnailManagerCenrepUID ) );
+    
+    rep->Get( KEnableDaemon, aEnabled );
+    
+    CleanupStack::PopAndDestroy( rep );    
+    }
+
+void CHarvesterCenRepUtil::GetPathsL( TUint32 aPartialKey, RPointerArray<HBufC>& aPaths )
+	{
+	CRepository* repo = CRepository::NewLC( KHarvesterRepoUid ); 
+	RArray<TUint32> scanPathKeys;
+	CleanupClosePushL( scanPathKeys );
+
+	repo->FindL( aPartialKey, KSearchMask, scanPathKeys );
+
+	TBuf<KMaxFileName> path;
+	const TInt count = scanPathKeys.Count();
+	aPaths.ReserveL( count );
+	for( TInt i = 0; i < count; i++ )
+		{
+	    const TInt error( repo->Get( scanPathKeys[i], path ) );
+	    if( error != KErrNone )
+	        {
+	        continue;
+	        }
+		HBufC* pathBuf = path.AllocL();
+		aPaths.Append( pathBuf );
+		}
+
+	CleanupStack::PopAndDestroy( &scanPathKeys );
+	CleanupStack::PopAndDestroy( repo );
+	}
+
+void CHarvesterCenRepUtil::GetItemsL( TUint32 aPartialKey, RPointerArray<TScanItem>& aItems )
+	{
+	CRepository* repo = CRepository::NewLC( KHarvesterRepoUid ); 
+	RArray<TUint32> scanPathKeys;
+	CleanupClosePushL( scanPathKeys );
+
+	repo->FindL( aPartialKey, KSearchMask, scanPathKeys );
+
+	TBuf<KMaxFileName> path;
+	const TInt count = scanPathKeys.Count();
+	for( TInt i = 0; i < count; i++ )
+		{
+	    const TInt error( repo->Get( scanPathKeys[i], path ) );
+	    if( error != KErrNone )
+	        {
+	        continue;
+	        }
+		TUint32 preinstalled = MdeConstants::MediaObject::ENotPreinstalled;
+		if( path[ path.Length() - 1 ] != TChar('\\') )
+			{
+			User::LeaveIfError( repo->GetMeta( scanPathKeys[i], preinstalled ) );
+			}
+		TScanItem* item = new (ELeave) TScanItem();
+		CleanupStack::PushL( item );
+		item->iPath = path.AllocL();
+		item->iPreinstalled = preinstalled;
+		CleanupStack::Pop( item );
+		aItems.Append( item ); // ownership is transferred
+		}
+
+	CleanupStack::PopAndDestroy( &scanPathKeys );
+	CleanupStack::PopAndDestroy( repo );	
+	}
+
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/harvesterclientdata.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Data transfer object for harvest client data
+*
+*/
+
+#include <harvesterclientdata.h>
+
+// CHarvestClientData implementation
+
+//==========================================================================
+// Constructor
+//==========================================================================
+//
+CHarvestClientData::CHarvestClientData()
+    {
+    // no implementation needed
+    }
+
+//==========================================================================
+// Destructor
+//==========================================================================
+//
+CHarvestClientData::~CHarvestClientData()
+    {
+    iAlbumIds.Close();
+    }
+
+//==========================================================================
+// New
+//==========================================================================
+//
+EXPORT_C CHarvestClientData* CHarvestClientData::New()
+    {
+    CHarvestClientData* self = NULL;
+    TRAPD( err, self = NewL() );
+    if ( err != KErrNone )
+        {
+        return NULL;
+        }
+    return self;
+    }
+
+//==========================================================================
+// NewL
+//==========================================================================
+//
+EXPORT_C CHarvestClientData* CHarvestClientData::NewL()
+    {
+    CHarvestClientData* self = new (ELeave) CHarvestClientData();
+    return self;
+    }
+
+//==========================================================================
+// SetAlbumIds
+//==========================================================================
+//
+EXPORT_C void CHarvestClientData::SetAlbumIds( const RArray<TItemId>& aAlbumIds )
+    {
+    iAlbumIds.Reset();
+    const TInt count = aAlbumIds.Count();
+    iAlbumIds.Reserve( count );
+    for ( TInt i = 0; i < count; i++ )
+        {
+        iAlbumIds.Append( aAlbumIds[i] );
+        }
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/harvesterdata.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,319 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Data transfer object for harvest data
+ *
+*/
+
+
+#include <harvesterdata.h>
+#include <mdeobject.h>
+#include <locationdatatype.h>
+
+// CHarvestData implementation
+
+//==========================================================================
+// Constructor
+//==========================================================================
+//
+CHarvesterData::CHarvesterData( const HBufC* aUri )
+	{
+	iUri = aUri;
+	iIsBinary = ETrue;
+	}
+
+//==========================================================================
+// Destructor
+//==========================================================================
+//
+CHarvesterData::~CHarvesterData()
+	{
+	delete iUri;
+	delete iClientData;
+	delete iMdeObject;
+	delete iLocationData;
+	}
+
+//==========================================================================
+// NewLC
+//==========================================================================
+//
+EXPORT_C CHarvesterData* CHarvesterData::NewLC( const HBufC* aUri )
+	{
+	CHarvesterData* self = new (ELeave)CHarvesterData( aUri );
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+	}
+
+//==========================================================================
+// NewL
+//==========================================================================
+//
+EXPORT_C CHarvesterData* CHarvesterData::NewL( const HBufC* aUri )
+	{
+	CHarvesterData* self=CHarvesterData::NewLC( aUri );
+	CleanupStack::Pop(); // self;
+	return self;
+	}
+
+//==========================================================================
+// ConstructL
+//==========================================================================
+//
+void CHarvesterData::ConstructL()
+	{
+	}
+
+//==========================================================================
+// Uri
+//==========================================================================
+//
+EXPORT_C const TDesC& CHarvesterData::Uri()
+	{
+	return *iUri;
+	}
+
+//==========================================================================
+// SetEventType
+//==========================================================================
+//
+EXPORT_C void CHarvesterData::SetEventType( THarvesterEventType aEventType )
+	{
+	iEventType = aEventType;
+	}
+
+//==========================================================================
+// EventType
+//==========================================================================
+//
+EXPORT_C THarvesterEventType CHarvesterData::EventType()
+	{
+	return iEventType;
+	}
+
+//==========================================================================
+// SetPluginObserver
+//==========================================================================
+//
+EXPORT_C void CHarvesterData::SetPluginObserver( MHarvesterPluginObserver& aObserver )
+	{
+	iObserver = &aObserver;
+	}
+
+//==========================================================================
+// PluginObserver
+//==========================================================================
+//
+EXPORT_C MHarvesterPluginObserver* CHarvesterData::PluginObserver()
+	{
+	return iObserver;
+	}
+
+//==========================================================================
+// SetOrigin
+//==========================================================================
+//
+EXPORT_C void CHarvesterData::SetOrigin( TOrigin aOrigin )
+	{
+	iOrigin = aOrigin;
+	}
+
+//==========================================================================
+// Origin
+//==========================================================================
+//
+EXPORT_C TOrigin CHarvesterData::Origin()
+	{
+	return iOrigin;
+	}
+
+//==========================================================================
+// SetTakeSnapshot
+//==========================================================================
+//
+EXPORT_C void CHarvesterData::SetTakeSnapshot( TBool aTakeSnapshot )
+	{
+	iTakeSnapshot = aTakeSnapshot;
+	}
+
+//==========================================================================
+// TakeSnapshot
+//==========================================================================
+//
+EXPORT_C TBool CHarvesterData::TakeSnapshot()
+	{
+	return iTakeSnapshot;
+	}
+
+//==========================================================================
+// SetObjectType
+//==========================================================================
+//
+EXPORT_C void CHarvesterData::SetObjectType( THarvesterObjectType aObjectType )
+	{
+	iObjectType = aObjectType;
+	}
+
+//==========================================================================
+// ObjectType
+//==========================================================================
+//
+EXPORT_C THarvesterObjectType CHarvesterData::ObjectType()
+	{
+	return iObjectType;
+	}
+
+//==========================================================================
+// SetClientData
+//==========================================================================
+//
+EXPORT_C void CHarvesterData::SetClientData( CBase* aClientData )
+	{
+	iClientData = aClientData;
+	}
+
+//==========================================================================
+// ClientData
+//==========================================================================
+//
+EXPORT_C CBase* CHarvesterData::ClientData()
+	{
+	return iClientData;
+	}
+
+//==========================================================================
+// ErrorCode
+//==========================================================================
+//
+EXPORT_C TInt CHarvesterData::ErrorCode()
+	{
+	return iErrorCode;
+	}
+
+//==========================================================================
+// SetErrorCode
+//==========================================================================
+//
+EXPORT_C void CHarvesterData::SetErrorCode( TInt aErrorCode )
+	{
+	iErrorCode = aErrorCode;
+	}
+
+//==========================================================================
+// MdeObject
+//==========================================================================
+//
+EXPORT_C CMdEObject& CHarvesterData::MdeObject()
+	{
+	return *iMdeObject;
+	}
+
+//==========================================================================
+// SetMdeObject
+//==========================================================================
+//
+EXPORT_C void CHarvesterData::SetMdeObject( CMdEObject* aMdeObject )
+	{
+	iMdeObject = aMdeObject;
+	}
+
+//==========================================================================
+// SetLocationData
+//==========================================================================
+//
+EXPORT_C void CHarvesterData::SetLocationData( TLocationData* aLD )
+	{
+	iLocationData = aLD;
+	}
+
+//==========================================================================
+// LocationData
+//==========================================================================
+//
+EXPORT_C TLocationData* CHarvesterData::LocationData()
+	{
+	return iLocationData;
+	}
+
+//==========================================================================
+// SetClientId
+//==========================================================================
+//
+EXPORT_C void CHarvesterData::SetClientId( TUid aClientId )
+	{
+	iClientId = aClientId;
+	}
+
+//==========================================================================
+// ClientId
+//==========================================================================
+//
+EXPORT_C TUid CHarvesterData::ClientId()
+	{
+	return iClientId;
+	}
+
+//==========================================================================
+// AddLocation
+//==========================================================================
+//
+EXPORT_C TBool CHarvesterData::AddLocation()
+	{
+	return iAddLocation;
+	}
+
+//==========================================================================
+// SetAddLocation
+//==========================================================================
+//
+EXPORT_C void CHarvesterData::SetAddLocation( TBool aAdd )
+	{
+	iAddLocation = aAdd;
+	}
+
+//==========================================================================
+// SetHarvesterPluginInfo
+//==========================================================================
+//
+EXPORT_C void CHarvesterData::SetHarvesterPluginInfo( CHarvesterPluginInfo* aPluginInfo )
+	{
+	iPluginInfo = aPluginInfo;
+	}
+
+//==========================================================================
+// IsBinary
+//==========================================================================
+//
+EXPORT_C TBool CHarvesterData::IsBinary()
+	{
+	return iIsBinary;
+	}
+
+//==========================================================================
+// SetBinary
+//==========================================================================
+//
+EXPORT_C void CHarvesterData::SetBinary( TBool aValue )
+	{
+	iIsBinary = aValue;
+	}
+
+//==========================================================================
+// HarvesterPluginInfo
+//==========================================================================
+//
+EXPORT_C CHarvesterPluginInfo* CHarvesterData::HarvesterPluginInfo()
+	{
+	return iPluginInfo;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/harvestereventmanager.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,460 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+ *
+*/
+#include <e32svr.h>
+
+#include "harvestereventmanager.h"
+#include "harvesterlog.h"
+
+const TInt KHarvesterEventManagerTLSKey = 0x200104D9;
+
+CHarvesterEventManager::CHarvesterEventManager()
+	{
+	}
+
+void CHarvesterEventManager::ConstructL()
+	{
+	}
+
+CHarvesterEventManager::~CHarvesterEventManager()
+	{
+	for ( TInt i = 0; i < iEventQueues.Count(); i++)
+		{
+		iEventQueues[i]->Close();
+		}
+	iEventQueues.ResetAndDestroy();
+	iEventQueues.Close();
+	
+	iRegisteredObservers.ResetAndDestroy();
+	iRegisteredObservers.Close();
+	
+	iEventStatuses.Close();
+	}
+
+EXPORT_C CHarvesterEventManager* CHarvesterEventManager::GetInstanceL()
+	{
+	WRITELOG( "CHarvesterEventManager::GetInstanceL" );
+
+	CHarvesterEventManagerStaticData* data = 
+		static_cast<CHarvesterEventManagerStaticData*>( 
+				UserSvr::DllTls( KHarvesterEventManagerTLSKey ) );
+
+	CHarvesterEventManager* instance = NULL;
+
+	if ( !data )
+        {
+        instance = new (ELeave) CHarvesterEventManager();
+        CleanupStack::PushL( instance );
+        instance->ConstructL();
+        UserSvr::DllSetTls( KHarvesterEventManagerTLSKey,
+        	new (ELeave) CHarvesterEventManagerStaticData(instance) );
+        CleanupStack::Pop( instance );
+        }
+    else
+        {
+        instance = data->iHEM;
+        data->iRefCount++;
+        }
+
+    return instance;
+	}
+
+EXPORT_C void CHarvesterEventManager::ReleaseInstance()
+    {
+    WRITELOG( "CHarvesterEventManager::ReleaseInstance" );
+    CHarvesterEventManagerStaticData* data =
+        static_cast<CHarvesterEventManagerStaticData*>( 
+        		UserSvr::DllTls( KHarvesterEventManagerTLSKey ) );
+    if ( data )
+        {
+        data->iRefCount--;
+        if ( data->iRefCount <= 0 )
+            {
+            // destroy the singleton and free TLS
+            delete data;
+            UserSvr::DllFreeTls( KHarvesterEventManagerTLSKey );
+            }
+        }
+    }
+
+EXPORT_C void CHarvesterEventManager::IncreaseItemCount( 
+		HarvesterEventObserverType aHEObserverType, TUint aCount )
+	{
+	TEventStatus* eventStatus = GetEventStatus( aHEObserverType );
+	WRITELOG2( "CHarvesterEventManager::IncreaseItemCount(%d) type = %d", aCount, aHEObserverType); 
+	
+#ifdef _DEBUG
+	switch(aHEObserverType)
+	    {
+	    case EHEObserverTypePlaceholder:
+	        WRITELOG( "CHarvesterEventManager::IncreaseItemCount() EHEObserverTypePlaceholder");
+	        break;
+	    case EHEObserverTypeMMC:
+	        WRITELOG( "CHarvesterEventManager::IncreaseItemCount() EHEObserverTypeMMC");
+	        break;
+	    case EHEObserverTypeOverall:
+	        WRITELOG( "CHarvesterEventManager::IncreaseItemCount() EHEObserverTypeOverall");
+	        break;
+	    default:
+	        WRITELOG( "CHarvesterEventManager::IncreaseItemCount() Unknown type!");
+	    };
+#endif
+	
+	if( eventStatus )
+		{
+		WRITELOG1( "CHarvesterEventManager::IncreaseItemCount() itemsleft = %d old ", eventStatus->iItemsLeft);
+		eventStatus->iItemsLeft += aCount;
+		WRITELOG1( "CHarvesterEventManager::IncreaseItemCount() itemsleft = %d ", eventStatus->iItemsLeft);
+		}
+	else
+		{
+		TEventStatus eventStatus;
+		eventStatus.iCurrentState = EHEStateStarted;
+		WRITELOG1( "CHarvesterEventManager::IncreaseItemCount() itemsleft = %d old", aCount);
+		eventStatus.iItemsLeft = aCount;
+		WRITELOG1( "CHarvesterEventManager::IncreaseItemCount() itemsleft = %d ", aCount);
+		eventStatus.iObserverType = aHEObserverType;
+		iEventStatuses.Append( eventStatus );
+		}
+	}
+
+EXPORT_C TBool CHarvesterEventManager::DecreaseItemCountL( 
+		HarvesterEventObserverType aHEObserverType, TUint aCount )
+	{
+	TEventStatus* eventStatus = GetEventStatus( aHEObserverType );
+	WRITELOG2( "CHarvesterEventManager::DecreaseItemCountL(%d) type = %d ", aCount, aHEObserverType);
+	
+#ifdef _DEBUG
+    switch(aHEObserverType)
+        {
+        case EHEObserverTypePlaceholder:
+            WRITELOG( "CHarvesterEventManager::DecreaseItemCountL() EHEObserverTypePlaceholder");
+            break;
+        case EHEObserverTypeMMC:
+            WRITELOG( "CHarvesterEventManager::DecreaseItemCountL() EHEObserverTypeMMC");
+            break;
+        case EHEObserverTypeOverall:
+            WRITELOG( "CHarvesterEventManager::DecreaseItemCountL() EHEObserverTypeOverall");
+            break;
+        default:
+            WRITELOG( "CHarvesterEventManager::DecreaseItemCountL() Unknown type!");
+        };
+#endif
+	
+	if( eventStatus )
+		{
+		WRITELOG1( "CHarvesterEventManager::DecreaseItemCountL() iItemsLeft = %d old", eventStatus->iItemsLeft);
+		TUint newCount = eventStatus->iItemsLeft - aCount;
+
+		// check for wrap
+		if( newCount > eventStatus->iItemsLeft )
+			{
+			newCount = 0;
+			}
+
+		// event doesn't need to be sent, if count hasn't changed 
+		if( newCount == eventStatus->iItemsLeft )
+			{
+			return EFalse;
+			}
+
+		eventStatus->iItemsLeft = newCount;
+		}
+	else
+		{
+		return EFalse;
+		}
+
+	WRITELOG1( "CHarvesterEventManager::DecreaseItemCountL() iItemsLeft = %d", eventStatus->iItemsLeft );
+	
+	// send finished event to all matching observers
+	if ( eventStatus->iItemsLeft <= 0 )
+		{
+		eventStatus->iItemsLeft = 0;
+		eventStatus->iCurrentState = EHEStateFinished;
+
+		// EHEObserverTypeOverall state is handled directly in harvesterao during harvesting
+        if( aHEObserverType != EHEObserverTypeOverall )
+		    {
+		    const TInt err = SendEventL( aHEObserverType, eventStatus->iCurrentState, eventStatus->iItemsLeft );
+		    return err == KErrNone;
+		    }
+		}
+
+	// still harvesting
+	eventStatus->iCurrentState = EHEStateHarvesting;
+	
+	// send harvesting event to all matching observers
+	TBool wasSent = EFalse;
+	TInt count = iRegisteredObservers.Count();
+	for ( TInt i = count; --i >= 0; )
+		{
+		THarvesterEventObserverInfo& observer = *(iRegisteredObservers[i]);
+
+		if( CheckObserverType( observer.iObserverType, aHEObserverType ) )
+			{
+			observer.iDelta += aCount;
+
+			// observers interval full
+			if ( observer.iDelta >= observer.iNotificationInterval )
+				{
+				TInt err = SendSingleEvent( observer, aHEObserverType, 
+						eventStatus->iCurrentState, eventStatus->iItemsLeft );
+				if ( err == KErrNone )
+					{
+					wasSent = ETrue;
+					}
+				}
+			}
+		}
+
+	return wasSent;
+	}
+
+TInt CHarvesterEventManager::SendSingleEvent( 
+		THarvesterEventObserverInfo& aEventObserverInfo, 
+		HarvesterEventObserverType aObserverType, 
+		HarvesterEventState aEventState, TUint aItemsLeft )
+	{
+	aEventObserverInfo.iDelta = 0;
+
+	THarvesterEventNotification notification;
+	notification.iObserverId = aEventObserverInfo.iObserverId;
+	notification.iObserverType = aObserverType;
+	notification.iCurrentState = aEventState;
+	notification.iItemsLeft = aItemsLeft;
+
+	THarvesterEventQueue& eventQueue = *(aEventObserverInfo.iQueuePtr);
+	TInt err = eventQueue.Send( notification );
+	return err;
+	}
+
+EXPORT_C TUint CHarvesterEventManager::ItemCount( 
+		HarvesterEventObserverType aHEObserverType )
+	{
+	TEventStatus* eventStatus = GetEventStatus( aHEObserverType );
+	if( eventStatus )
+		{
+		return eventStatus->iItemsLeft;
+		}
+	
+	return 0;
+	}
+
+EXPORT_C TInt CHarvesterEventManager::SendEventL( 
+		HarvesterEventObserverType aHEObserverType,
+		HarvesterEventState aHEState, TUint aItemsLeft )
+	{
+	TEventStatus* eventStatus = GetEventStatus( aHEObserverType );
+	if( eventStatus )
+		{
+		eventStatus->iCurrentState = aHEState;
+		}
+
+	THarvesterEventNotification notification;
+	notification.iObserverType = aHEObserverType;
+	notification.iCurrentState = aHEState;
+	notification.iItemsLeft = aItemsLeft;
+
+	TInt err = KErrNone;
+	TInt count = iRegisteredObservers.Count();
+	for ( TInt i = count; --i >= 0; )
+		{
+		THarvesterEventObserverInfo& observer = *(iRegisteredObservers[i]);
+
+		if( CheckObserverType( observer.iObserverType, aHEObserverType ) )
+			{
+			notification.iObserverId = observer.iObserverId;
+
+			THarvesterEventQueue& eventQueue = *(observer.iQueuePtr);
+			TInt sendErr = eventQueue.Send( notification );
+			// Take first error
+			if( err == KErrNone )
+				{
+				err = sendErr;
+				}
+			}
+		}
+	return err;
+	}
+
+EXPORT_C void CHarvesterEventManager::RegisterEventObserverL( const RMessage2& aMessage )
+	{
+	THarvesterEventObserverInfo* observerInfo = new (ELeave) THarvesterEventObserverInfo;
+	CleanupStack::PushL( observerInfo );
+
+    TPckg<THarvesterEventObserverInfo> pckgObserverInfo( *observerInfo );
+    TInt err = aMessage.Read( 0, pckgObserverInfo );
+
+    // Init server side values
+    observerInfo->iQueuePtr = NULL;
+    observerInfo->iDelta = 0;
+    observerInfo->iProcessUid = aMessage.Identity().iUid;
+
+    // Check if observer ID is not yet used
+    // and if event queue already exists
+    TBool found = EFalse;
+	for(TInt i = iRegisteredObservers.Count(); --i >= 0;)
+		{
+		THarvesterEventObserverInfo* info = iRegisteredObservers[i];
+		if( info->iProcessUid == observerInfo->iProcessUid && 
+			info->iQueueHandle == observerInfo->iQueueHandle )
+			{
+			if( info->iObserverId == observerInfo->iObserverId )
+				{
+				User::Leave( KErrAlreadyExists );
+				}
+
+			observerInfo->iQueuePtr = info->iQueuePtr;
+			found = ETrue;
+			}
+		}
+
+	// create new event queue if no match was found 
+	if ( !found )
+		{
+		THarvesterEventQueue* msgQueue = new (ELeave) THarvesterEventQueue;
+		CleanupStack::PushL( msgQueue );
+
+		TInt err = msgQueue->Open( aMessage, 1 );
+
+		User::LeaveIfError( err );
+
+		iEventQueues.AppendL( msgQueue );
+		observerInfo->iQueuePtr = msgQueue;
+		
+		CleanupStack::Pop( msgQueue );
+		}	
+
+	iRegisteredObservers.AppendL( observerInfo );
+
+	CleanupStack::Pop( observerInfo );
+	
+	// send event if register is coming in the middle of harvesting
+	for( TInt i = iEventStatuses.Count(); --i >= 0; )
+		{
+		TEventStatus& eventStatus = iEventStatuses[i];
+		if( CheckObserverType( observerInfo->iObserverType, 
+				eventStatus.iObserverType) )
+			{
+			if( eventStatus.iItemsLeft > 0 )
+				{
+				TRAP_IGNORE( SendEventL( eventStatus.iObserverType, 
+						eventStatus.iCurrentState, eventStatus.iItemsLeft ) );
+				}
+			}
+		}
+	}
+
+EXPORT_C TInt CHarvesterEventManager::UnregisterEventObserver( const RMessage2& aMessage )
+	{
+	TUint observerId = (TUint)aMessage.Int0();
+	TInt queueHandle = aMessage.Int1();
+
+	TInt serverQueueHandle = KNullHandle;
+	TUint processUid = aMessage.Identity().iUid;
+	
+	TBool otherObserverFound = EFalse;
+	for(TInt i = iRegisteredObservers.Count(); --i >= 0;)
+		{
+		THarvesterEventObserverInfo* observer = iRegisteredObservers[i];
+		if( observer->iProcessUid == processUid && 
+			observer->iQueueHandle == queueHandle )
+			{
+			// Remove registered observer
+			if( observer->iObserverId == observerId )
+				{
+				serverQueueHandle = observer->iQueuePtr->Handle();
+				
+				iRegisteredObservers.Remove( i );
+				delete observer;
+				}
+			// Find if any other observer is using the same queue
+			else
+				{
+				otherObserverFound = ETrue;
+				}
+			}
+		}
+
+	if( serverQueueHandle )
+		{
+		// Remove the queue if removed observer 
+		// was the last observer which used it
+		if( !otherObserverFound )
+			{
+			for(TInt i = iEventQueues.Count(); --i >= 0;)
+				{
+				THarvesterEventQueue* queue = iEventQueues[i];
+				if( queue->Handle() == serverQueueHandle )
+					{
+					iEventQueues.Remove( i );
+					queue->Close();
+					delete queue;
+					break;
+					}
+				}
+			}
+
+		return KErrNone;
+		}
+	else
+		{
+		return KErrNotFound;
+		}
+	}
+
+EXPORT_C HarvesterEventState CHarvesterEventManager::CurrentState( 
+		HarvesterEventObserverType aHEObserverType )
+	{
+	TInt count = iEventStatuses.Count();
+	for( TInt i = count; --i >= 0; )
+		{
+		TEventStatus& eventStatus = iEventStatuses[i];
+		if( eventStatus.iObserverType == aHEObserverType )
+			{
+			return eventStatus.iCurrentState;
+			}
+		}
+	return EHEStateUninitialized;
+	}
+
+TBool CHarvesterEventManager::CheckObserverType( TInt aObserverType, TInt aEventType )
+	{
+	return aObserverType & aEventType;
+	}
+
+CHarvesterEventManager::TEventStatus* CHarvesterEventManager::GetEventStatus( 
+		HarvesterEventObserverType aHEObserverType )
+	{
+	TInt count = iEventStatuses.Count();
+	for(TInt i = count; --i >= 0; )
+		{
+		TEventStatus& eventStatus = iEventStatuses[i];
+		if( eventStatus.iObserverType == aHEObserverType )
+			{
+			return &eventStatus;
+			}
+		}
+
+	return NULL;
+	}
+
+EXPORT_C TUint CHarvesterEventManager::GetLastClientId()
+	{
+	// deprecated method, just return something
+	return 0;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/harvesterexifutil.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1847 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Exif-utilities for harvester
+*
+*/
+
+#include "harvesterexifutil.h"
+
+#include "mdsutils.h"
+#include "mdeobjectdef.h"
+#include "mdeconstants.h"
+#include "mdeproperty.h"
+#include "tz.h"
+#include <ExifModify.h>
+
+
+
+using namespace MdeConstants;
+
+const TUint16 KIdColorSpace = 0xA001;
+const TUint16 KIdResolutionUnit = 0x0128;
+const TUint16 KIdYbCrPositioning = 0x0213;
+const TUint16 KIdImageDescription = 0x010E;
+const TUint16 KIdCopyright = 0x8298;
+const TUint16 KIdUserComment = 0x9286;
+const TUint16 KIdDateTime = 0x0132;
+const TUint16 KIdDateTimeOriginal = 0x9003;
+const TUint16 KIdDateTimeDigitized = 0x9004;
+const TUint16 KIdDateTimeModified = 0x132;
+const TUint16 KIdFNumber = 0x829D;
+const TUint16 KIdMake = 0x010F;
+const TUint16 KIdModel = 0x0110;
+const TUint16 KIdFocalLength = 0x920A;
+const TUint16 KIdFocalLengthIn35mm = 0xA405;
+const TUint16 KIdSamplesPerPixel = 0x0115;
+const TUint16 KIdISOSpeedRatings = 0x8827;
+const TUint16 KIdComponentsConfig = 0x9101;
+const TUint16 KIdArtist = 0x013B;
+const TUint16 KIdPixelXDimension = 0xA002;
+const TUint16 KIdPixelYDimension = 0xA003;
+const TUint16 KIdRelatedSoundFile = 0xA004;
+const TUint16 KIdFocalPlaneResolutionUnit = 0xA210;
+const TUint16 KIdFocalPlaneXResolution = 0xA20E;
+const TUint16 KIdFocalPlaneYResolution = 0xA20F;
+
+const TUint16 KIdExposureTime = 0x829A;
+const TUint16 KIdApertureValue = 0x9202;
+const TUint16 KIdExposureBias = 0x9204;
+const TUint16 KIdMeteringMode = 0x9207;
+const TUint16 KIdShutterSpeed = 0x9201;
+const TUint16 KIdXResolution = 0x011A;
+const TUint16 KIdYResolution = 0x011B;
+const TUint16 KIdWhiteBalance = 0xA403;
+const TUint16 KIdExposureProgram = 0x8822;
+const TUint16 KIdFlash = 0x9209;
+const TUint16 KIdOrientation = 0x112;
+
+const TUint16 KIdGpsLatitudeRef = 0x1;
+const TUint16 KIdGpsLatitude = 0x2;
+const TUint16 KIdGpsLongitudeRef = 0x3;
+const TUint16 KIdGpsLongitude = 0x4;
+const TUint16 KIdGpsAltitudeRef = 0x5;
+const TUint16 KIdGpsAltitude = 0x6;
+const TUint16 KIdGpsMeasureMode = 0xA;
+const TUint16 KIdGpsDop = 0xB;
+const TUint16 KIdGpsMapDatum = 0x12;
+
+_LIT( KExifDateTimeFormat, "%F%Y:%M:%D %H:%T:%S\0" );
+const TInt KDateBufferSize = 20;
+const TInt KCoordinateBufferSize = 24;
+
+// This is needed for exif description field
+_LIT8( KAsciiCodeDesignation,     "\x41\x53\x43\x49\x49\x00\x00\x00");
+_LIT8( KJisCodeDesignation,     "\x4A\x49\x53\x00\x00\x00\x00\x00");
+_LIT8( KUnicodeCodeDesignation, "\x55\x4E\x49\x43\x4F\x44\x45\x00");
+_LIT8( KUnknownCodeDesignation, "\x00\x00\x00\x00\x00\x00\x00\x00");
+
+_LIT8( KNorth, "N\0" );
+_LIT8( KSouth, "S\0" );
+_LIT8( KEast, "E\0" );
+_LIT8( KWest, "W\0" );
+_LIT8( KMeasureMode2, "2\0" );
+_LIT8( KMeasureMode3, "3\0" );
+_LIT8( KMapDatum, "WGS-84\0");
+
+CHarvesterExifUtil::CHarvesterExifUtil() :
+    iSession( NULL ), iDefaultNamespace( NULL )
+{
+}
+
+
+CHarvesterExifUtil::~CHarvesterExifUtil()
+{
+}
+
+EXPORT_C CHarvesterExifUtil* CHarvesterExifUtil::NewLC()
+{
+	CHarvesterExifUtil* self = new (ELeave)CHarvesterExifUtil();
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+}
+
+EXPORT_C CHarvesterExifUtil* CHarvesterExifUtil::NewL()
+{
+	CHarvesterExifUtil* self=CHarvesterExifUtil::NewLC();
+	CleanupStack::Pop( self ); // self;
+	return self;
+}
+
+void CHarvesterExifUtil::ConstructL()
+{
+
+}
+
+EXPORT_C void CHarvesterExifUtil::SetSession( CMdESession* aSession )
+	{
+	iSession = aSession;
+	if ( !iDefaultNamespace && aSession )
+		{
+    	TRAP_IGNORE( iDefaultNamespace = &iSession->GetDefaultNamespaceDefL() );
+		}
+	}
+
+
+EXPORT_C TBool CHarvesterExifUtil::IsValidExifData(TPtr8 aPtr)
+	{
+	WRITELOG( "CHarvesterExifUtil::IsValidExifData start" );
+	
+	CExifRead* reader = NULL;
+	
+	TRAPD(err, reader = CExifRead::NewL(aPtr, CExifRead::ENoJpeg | CExifRead::ENoTagChecking));
+	if (err != KErrNone || !reader )
+		{
+		WRITELOG1( "CHarvesterExifUtil::IsValidExifData - error code: %d", err );
+	
+		return EFalse;
+		}
+	
+	delete reader;
+	
+	WRITELOG( "CHarvesterExifUtil::IsValidExifData end" );	
+	
+	return ETrue;
+	}
+
+void CHarvesterExifUtil::StripNulls( HBufC& aString )
+	{
+	_LIT( KNull, "\0" );
+	_LIT( KSpace, " " );
+	
+	TInt pos( 0 );
+    while( (pos = aString.Find( KNull ) ) != KErrNotFound )
+    	{
+    	aString.Des().Replace( pos, 1, KSpace );
+    	}
+    aString.Des().TrimAll();
+	}
+
+HBufC16* CHarvesterExifUtil::ReadExifTagL( const CExifRead& aReader, TExifIfdType aIFD, TUint16 aTagID )
+	{
+	HBufC16* destination = NULL;
+    if( aReader.TagExists( aTagID, aIFD ) )
+    	{
+        const CExifTag* tag = aReader.GetTagL( aIFD, aTagID );
+    	destination = CnvUtfConverter::ConvertToUnicodeFromUtf8L( tag->Data() );
+    	StripNulls( *destination );    	
+    	}	
+    return destination;
+	}
+
+EXPORT_C TInt CHarvesterExifUtil::ReadExifDataL( CHarvestData& aHd, CFileData& aFileData )
+    {
+    WRITELOG( "CHarvesterExifUtil::ReadExifDataL()" );
+
+    CExifRead* reader = CExifRead::NewL(
+    		aFileData.iImageData->Des(), CExifRead::ENoJpeg | CExifRead::ENoTagChecking);
+    CleanupStack::PushL(reader);
+    
+    // Getting description
+    aHd.iDescription16 = ReadExifTagL( *reader, EIfd0, KIdImageDescription );
+
+    // Getting UserComment
+    ReadUserCommentL( aHd, reader ); 
+          
+    // Getting copyright
+    aHd.iCopyright16 = ReadExifTagL( *reader, EIfd0, KIdCopyright );
+    
+    // Artist
+    aHd.iArtist = ReadExifTagL( *reader, EIfd0, KIdArtist );
+    
+    // Getting whitebalance
+    aHd.iStoreWhiteBalance = reader->GetWhiteBalance( aHd.iWhiteBalance ) == KErrNone;
+ 
+    // Getting aHd.iFlash    
+    aHd.iStoreFlash = reader->GetFlash( aHd.iFlash ) == KErrNone;
+    
+    // Getting exposure
+    aHd.iStoreExposureProgram = reader->GetExposureProgram( aHd.iExposureProgram ) == KErrNone;
+                
+    // Getting width
+    if ( reader->TagExists( KIdPixelXDimension, EIfdExif ) )
+        {
+        // PixelXDimension tag should be found in EXIF according to the standard.
+        reader->GetPixelXDimension(aHd.iImageWidthExif);
+        }
+    
+    // Getting height
+    if ( reader->TagExists( KIdPixelYDimension, EIfdExif ) )
+        {
+        // PixelYDimension tag should be found in EXIF according to the standard.
+        reader->GetPixelYDimension(aHd.iImageHeightExif);
+        }
+    
+    // Getting aFileData.iModified date
+    if ( reader->TagExists(KIdDateTime, EIfd0) )
+        {
+        WRITELOG( "CHarvesterExifUtil::ReadExifDataL() - getting last aFileData.iModified date (exif)" );
+        aHd.iDateModified8 = reader->GetDateTimeL();
+        }
+    
+    // Getting original date
+    if ( reader->TagExists(KIdDateTimeOriginal, EIfdExif) )
+        {
+        WRITELOG( "CHarvesterExifUtil::ReadExifDataL() - getting original date (exif)" );
+        aHd.iDateOriginal8 = reader->GetDateTimeOriginalL();
+        }
+        
+    // Getting date & time digitized
+    if ( reader->TagExists(KIdDateTimeDigitized, EIfdExif) )
+        {
+        WRITELOG( "CHarvesterExifUtil::ReadExifDataL() - getting digitized date (exif)" );
+        aHd.iDateDigitized8 = reader->GetDateTimeDigitizedL();
+        }            
+    
+    //Getting camera maker
+    aHd.iMake = ReadExifTagL( *reader, EIfd0, KIdMake );
+    
+    //Getting camera aHd.iModel
+    aHd.iModel = ReadExifTagL( *reader, EIfd0, KIdModel );
+    
+    //Getting aHd.iOrientation
+    aHd.iStoreOrientation = reader->GetOrientation( aHd.iOrientation ) == KErrNone;
+    
+    //Getting X Resolution
+    ReadXResolutionL( aHd, reader ); 
+    
+    //Getting Y Resolution
+    ReadXResolutionL( aHd, reader ); 
+    
+    //Getting resolution unit (mandatory tag)
+    reader->GetResolutionUnit( aHd.iResolutionUnit );
+    
+    //Getting YCbCr Positioning
+    aHd.iStoreYCbCrPositioning = reader->GetYCbCrPositioning( aHd.iYCbCrPositioning ) == KErrNone;
+        
+    //Getting exposure bias value
+    ReadExposureBiasL( aHd, reader ); 
+    
+    //Getting exposure time
+    ReadExposureTimeL( aHd, reader ); 
+        
+    //Getting FNumber
+    ReadFNumberL( aHd, reader );
+    
+    //Getting Exif version
+    aHd.iStoreExifVersion = reader->GetExifVersion( aHd.iExifVersion ) == KErrNone;           
+        
+    //Getting FlashPix version
+    aHd.iStoreFlashPixVersion = reader->GetFlashPixVersion( aHd.iFlashPixVersion ) == KErrNone;
+    
+    // Shutter speed
+    ReadShutterSpeedL( aHd, reader );
+        
+    //Getting aHd.iAperture
+    ReadApertureValueL( aHd, reader );
+    
+    //Getting focal length
+    ReadFocalLengthL( aHd, reader );
+    
+    // Getting focal length in 35 mm
+    ReadFocalLength35mmL( aHd, reader );
+        
+    aHd.iStoreColourSpace = reader->GetColorSpace( aHd.iColourSpace ) == KErrNone;
+    
+    aHd.iStoreThumbCompression = reader->GetThumbnailCompression( aHd.iThumbCompression ) == KErrNone;
+    
+	TUint32 numerator = 0;
+    TUint32 denominator = 0;
+	
+    //Getting thumbnail X resolution    
+    TInt error = reader->GetThumbnailXResolution( numerator, denominator );
+    if ( error == KErrNone )
+        {
+        aHd.iStoreThumbXResolution = ETrue;
+        aHd.iThumbXResolution = 0.0f;
+        if ( denominator > 0)
+            {
+            aHd.iThumbXResolution = numerator / denominator;
+            }
+        }
+    
+    //Getting thumbnail Y resolution
+    error = reader->GetThumbnailYResolution( numerator, denominator );
+    if ( error == KErrNone )
+        {
+        aHd.iStoreThumbYResolution = ETrue;
+        aHd.iThumbYResolution = 0.0f;
+        if ( denominator > 0 )
+            {
+            aHd.iThumbYResolution = numerator / denominator;
+            }
+        }
+        
+    aHd.iStoreThumbResolutionUnit =
+    	reader->GetThumbnailResolutionUnit( aHd.iThumbResolutionUnit ) == KErrNone;
+       
+    // Bits per sample and Samples per pixel not recorded in JPEG Exif.
+    if ( reader->TagExists( KIdSamplesPerPixel, EIfd0 ) )
+        {
+        const CExifTag* tag = reader->GetTagL( EIfd0, KIdSamplesPerPixel );
+        TPtrC8 tagData = tag->Data();
+        
+        aHd.iSamplesPerPixel = MdsUtils::ToUInt16L( CONST_CAST( TUint8*, tagData.Ptr() ) );
+        aHd.iStoreSamplesPerPixel = ETrue;
+        
+        WRITELOG1( "CHarvesterExifUtil::ReadExifDataL() - samples per pixel: %d", aHd.iSamplesPerPixel );
+        }
+    
+    //Getting ISO speed rating.
+    if ( reader->TagExists(KIdISOSpeedRatings, EIfdExif) )
+        {
+        HBufC8* iso8 = reader->GetIsoSpeedRatingsL();
+        
+        if ( iso8 )
+            {
+            aHd.iStoreIsoSpeedRating = ETrue;
+            aHd.iIsoSpeedRating = iso8->Des()[0];
+            delete iso8;
+            iso8 = NULL;
+            }    
+        }
+    
+    //Getting components configuration
+    if ( reader->TagExists( KIdComponentsConfig, EIfdExif ) )
+        {
+        const CExifTag* tag = reader->GetTagL(
+        		EIfdExif, KIdComponentsConfig );
+        TPtrC8 tagData = tag->Data();
+        
+        aHd.iComponentsConfiguration = MdsUtils::ToUInt32L( CONST_CAST( TUint8*, tagData.Ptr() ) );
+        aHd.iStoreComponentsConfig = ETrue;
+        }
+    
+    // Getting thumbnail compression
+    aHd.iStoreThumbCompression =
+    	reader->GetThumbnailCompression( aHd.iThumbCompression ) == KErrNone;
+        
+    // Getting metering mode
+    aHd.iStoreMeteringMode = reader->GetMeteringMode( aHd.iMeteringMode ) ==KErrNone;
+    
+    // Getting related soundfile
+    aHd.iRelatedSoundFile = ReadExifTagL( *reader, EIfdExif, KIdRelatedSoundFile );
+        
+    // Getting focal plane resolution unit
+    if ( reader->TagExists(KIdFocalPlaneResolutionUnit, EIfdExif) )
+        {
+        const CExifTag* tag = reader->GetTagL(
+        		EIfdExif, KIdFocalPlaneResolutionUnit );
+        TPtrC8 tagData = tag->Data();
+        
+        aHd.iFocalPlaneResolutionUnit = MdsUtils::ToUInt16L( CONST_CAST( TUint8*, tagData.Ptr() ) );
+        aHd.iStoreFocalPlaneResolutionUnit = ETrue;
+        }
+    
+    // Getting focal plane X resolution
+    ReadFocalXPlaneResolutionL( aHd, reader );
+
+        
+    // Getting focal plane Y resolution
+    ReadFocalYPlaneResolutionL( aHd, reader );
+
+    // Get GPS tags
+    TBool latitudeExists = EFalse;
+    
+    // latitude
+    ReadGPSLatitudeL( aHd, reader, latitudeExists );
+
+    // longitude
+    ReadGPSLongitudeL( aHd, reader, latitudeExists );
+    
+    // altitude
+    ReadGPSAltitudeL( aHd, reader );
+        
+    CleanupStack::PopAndDestroy( reader );
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// Time converting
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TTime CHarvesterExifUtil::ConvertExifDateTimeToSymbianTimeL(
+		const TDesC8& aDateTime )
+    {
+    WRITELOG( "CHarvesterImagePluginAO::ConvertExifDateTimeToSymbianTimeL()" );
+    
+    TDateTime datetime( 0, EJanuary, 0, 0, 0, 0, 0 );
+    TBuf<4> text;
+    
+    // Year
+    TPtrC8 textPart = aDateTime.Left(4);
+    TLex8 lex( textPart );
+    TInt number = 0;
+    TInt error = lex.Val( number );
+    if ( error != KErrNone )
+        {
+        WRITELOG( "CHarvesterImagePluginAO::ConvertExifDateTimeToSymbianTimeL() - couldn't get year" );
+        User::Leave( error );
+        }
+    datetime.SetYear( number );
+    
+    // Month
+    TPtrC8 textPart2 = aDateTime.Mid( 5,2 );
+    lex.Assign( textPart2 );
+    error = lex.Val( number );
+    if ( error != KErrNone )
+        {
+        WRITELOG( "CHarvesterImagePluginAO::ConvertExifDateTimeToSymbianTimeL() - couldn't get month" );
+        User::Leave( error );
+        }        
+    number--;
+    TMonth month = (TMonth) number;
+    datetime.SetMonth( month );
+    
+    // Day
+    TPtrC8 textPart3 = aDateTime.Mid( 8,2 );
+    lex.Assign( textPart3 );
+    error = lex.Val( number );
+    if ( error != KErrNone )
+        {
+        WRITELOG( "CHarvesterImagePluginAO::ConvertExifDateTimeToSymbianTimeL() - couldn't get date" );
+        User::Leave( error );
+        }
+    datetime.SetDay( number - 1 );
+    
+    // Hours
+    TPtrC8 textPart4 = aDateTime.Mid( 11,2 );
+    lex.Assign( textPart4 );
+    error = lex.Val( number );
+    if ( error != KErrNone )
+        {
+        WRITELOG( "CHarvesterImagePluginAO::ConvertExifDateTimeToSymbianTimeL() - couldn't get hours" );
+        User::Leave( error );
+        }    
+    datetime.SetHour( number );
+    
+    // Minutes
+    TPtrC8 textPart5 = aDateTime.Mid( 14,2 );
+    lex.Assign( textPart5 );
+    error = lex.Val( number );
+    if ( error != KErrNone )
+        {
+        WRITELOG( "CHarvesterImagePluginAO::ConvertExifDateTimeToSymbianTimeL() - couldn't get minutes" );
+        User::Leave( error );
+        }
+    datetime.SetMinute( number );
+    
+    // Seconds
+    TPtrC8 textPart6 = aDateTime.Mid( 17,2 );
+    lex.Assign( textPart6 );
+    error = lex.Val( number );
+    if ( error != KErrNone )
+        {
+        WRITELOG( "CHarvesterImagePluginAO::ConvertExifDateTimeToSymbianTimeL() - couldn't get seconds" );
+        User::Leave( error );
+        }
+    datetime.SetSecond( number );
+    
+    TTime time( datetime );
+
+    return time;
+    }
+
+void CHarvesterExifUtil::AddPropertyL( CMdEObjectDef& aObjectDef, CMdEObject& aMdeObject,
+		const TDesC& aProperty, TUint16 aValue )
+	{
+	CMdEPropertyDef& propDef = aObjectDef.GetPropertyDefL( aProperty );    
+	CMdEProperty* mdeProp = NULL;
+	
+	aMdeObject.Property( propDef, mdeProp, 0 );
+    if ( !mdeProp )
+        {
+        aMdeObject.AddUint16PropertyL( propDef, aValue );
+        }	
+	}
+
+void CHarvesterExifUtil::AddPropertyL( CMdEObjectDef& aObjectDef, CMdEObject& aMdeObject,
+		   const TDesC& aProperty, TUint32 aValue )
+{
+	CMdEPropertyDef& propDef = aObjectDef.GetPropertyDefL( aProperty );    
+	CMdEProperty* mdeProp = NULL;
+	
+	aMdeObject.Property( propDef, mdeProp, 0 );
+	if ( !mdeProp )
+		{
+		aMdeObject.AddUint32PropertyL( propDef, aValue );
+		}	
+}
+
+void CHarvesterExifUtil::SetExifDefaultsL( CMdEObject& aMdeObject, CExifModify& aExifModify )
+	{
+    const TUint32 KPixPerResolution = 72;
+    const TUint32 KPixPerResDenm = 1;
+    const TUint16 KResUnitInch = 2;
+    const TUint16 KYCbCrPositioning = 1;
+    const TUint8  KCompConf1st = 1;
+    const TUint8  KCompConf2nd = 2;
+    const TUint8  KCompConf3rd = 3;
+    const TUint8  KCompConf4rd = 0;
+    const TUint16 KColorSpaceRGB = 1;
+
+    CMdEObjectDef& imageDef = iDefaultNamespace->GetObjectDefL( Image::KImageObject );
+    
+    aExifModify.SetXResolutionL( KPixPerResolution, KPixPerResDenm );
+    aExifModify.SetYResolutionL( KPixPerResolution, KPixPerResDenm );
+
+    AddPropertyL( imageDef, aMdeObject, MediaObject::KResolutionUnitProperty,
+    		      KResUnitInch );
+    aExifModify.SetResolutionUnitL( KResUnitInch );
+
+    AddPropertyL( imageDef, aMdeObject, Image::KYCbCrPositioningProperty,
+    		      KYCbCrPositioning );
+    aExifModify.SetYCbCrPositioningL( KYCbCrPositioning );
+
+    TUint32 compUint32( 0 );
+    TUint8* components = (TUint8*) &compUint32;
+    *(components + 3) = KCompConf4rd;
+    *(components + 2) = KCompConf3rd;
+    *(components + 1) = KCompConf2nd;
+          *components = KCompConf1st;
+    
+    AddPropertyL( imageDef, aMdeObject, Image::KComponentsConfigurationProperty,
+    		      compUint32 );
+    aExifModify.SetComponentsConfigurationL( KCompConf1st, KCompConf2nd,
+    										 KCompConf3rd, KCompConf4rd );
+
+    AddPropertyL( imageDef, aMdeObject, Image::KColourSpaceProperty, KColorSpaceRGB );
+    aExifModify.SetColorSpaceL( KColorSpaceRGB );
+	}
+
+HBufC8* CHarvesterExifUtil::GetPropertyValueLC( const CMdEPropertyDef& aPropDef,
+		const CMdEProperty& aProperty )
+	{
+	switch( aPropDef.PropertyType() )
+		{
+		case EPropertyReal32:
+			{
+			TUint32 denominator = 1; 
+			if( aPropDef.Name().CompareF( Image::KExposureTimeProperty ) == 0 )
+				{
+				denominator = 1000000;
+				}
+			else if( aPropDef.Name().CompareF( Image::KApertureValueProperty ) == 0 )
+				{
+				denominator = 100;
+				}
+			else if( aPropDef.Name().CompareF( Image::KExposureBiasValueProperty ) == 0 )
+				{
+				denominator = 100;
+				}
+			else if( aPropDef.Name().CompareF( Image::KShutterSpeedValueProperty ) == 0 )
+				{
+				denominator = 1000;
+				}
+			else if( aPropDef.Name().CompareF( Image::KFNumberProperty ) == 0 )
+				{
+				denominator = 10;
+				}			
+			TUint32 value = TUint32( aProperty.Real32ValueL() * (TReal32)denominator );
+
+			HBufC8* buf8 = HBufC8::NewLC( 2 * sizeof(TUint32) );
+			TPtr8 ptr = buf8->Des();
+			ptr.Append( (TUint8*)&value, sizeof(TUint32) );
+			ptr.Append( (TUint8*)&denominator, sizeof(TUint32) );
+			
+			return buf8;
+			}
+		case EPropertyTime:
+			{
+	        TTime time = aProperty.TimeValueL();
+	        if( aPropDef.Name().CompareF( Image::KDateTimeProperty ) == 0 )
+	        	{
+	        	RTz timezone;
+	        	CleanupClosePushL( timezone );
+	        	User::LeaveIfError( timezone.Connect() );
+	        	timezone.ConvertToLocalTime( time );
+	        	CleanupStack::PopAndDestroy( &timezone );
+	        	}
+	        HBufC* buf = HBufC::NewLC( KDateBufferSize );
+	        TPtr ptr = buf->Des();
+	        time.FormatL( ptr, KExifDateTimeFormat );
+	        HBufC8* buf8 = CnvUtfConverter::ConvertFromUnicodeToUtf8L( ptr );
+	        CleanupStack::PopAndDestroy( buf );
+	        CleanupStack::PushL( buf8 );
+	        return buf8;
+			}
+		case EPropertyText:
+			{
+			TPtrC text = aProperty.TextValueL();
+			if( aPropDef.Name().CompareF( MediaObject::KCommentProperty ) == 0 )
+				{
+		        const TUint16 bufLength = KUnicodeCodeDesignation.iTypeLength + text.Size();
+		        HBufC8* commentBuf = HBufC8::NewLC( bufLength );
+		        TPtr8 commentPtr = commentBuf->Des();
+		        commentPtr.Append( KUnicodeCodeDesignation );
+		        commentPtr.Append( (TUint8*)text.Ptr(), text.Size() );
+		        return commentBuf;
+				}
+			HBufC8* buf = CnvUtfConverter::ConvertFromUnicodeToUtf8L( text );
+			CleanupStack::PushL( buf );
+	        return buf;
+			}
+		case EPropertyUint16:
+			{
+        	TUint16 value = aProperty.Uint16ValueL();
+        	HBufC8* buf = HBufC8::NewLC( sizeof(value) );
+        	TPtr8 ptr = buf->Des();
+        	ptr.Copy( (TUint8*)(&value), sizeof(value) );
+			return buf;
+			}
+		default:
+			User::Leave( KErrGeneral );
+		}
+	    return NULL;
+	}
+
+CExifTag::TExifTagDataType CHarvesterExifUtil::ExifTagDataType( TUint16 aTagID, const CMdEPropertyDef& aPropDef )
+	{
+	if( aTagID == KIdUserComment )
+		{
+		return CExifTag::ETagUndefined;   		
+		}
+	if( aTagID == KIdShutterSpeed || aTagID == KIdExposureBias )
+		{
+		return CExifTag::ETagSrational;
+		}
+	switch( aPropDef.PropertyType() )
+		{
+		case EPropertyBool:
+		case EPropertyInt8:
+		case EPropertyUint8:
+			return CExifTag::ETagByte;
+		case EPropertyInt16:
+		case EPropertyUint16:
+			return CExifTag::ETagShort;
+		case EPropertyUint32:
+			return CExifTag::ETagLong;
+		case EPropertyInt32:
+			return CExifTag::ETagSlong;
+		case EPropertyReal32:
+			return CExifTag::ETagRational;
+		case EPropertyTime:
+			return CExifTag::ETagAscii;
+		case EPropertyText:
+			return CExifTag::ETagAscii;
+		default:
+			return CExifTag::ETagUndefined;
+		}
+	}
+
+TBool CHarvesterExifUtil::CompareTag( TPtrC8 aMdeData, const CExifTag* aTag )
+	{
+	if( aTag->TagInfo().iDataType == CExifTag::ETagRational )
+		{
+		TUint32 denominator;
+		TUint32 value;
+        TPtrC8 ptr( aTag->Data() );
+        memcpy( &value, ptr.Ptr(), sizeof(value) );
+        memcpy( &denominator, ptr.Ptr()+sizeof(value), sizeof(denominator) );
+
+    	TReal32 tagValue = 0.0f;
+    	if ( denominator != 0 )
+    		{
+    		tagValue = (TReal32)value / (TReal32)denominator;
+    		}
+        ptr.Set( aMdeData );
+        memcpy( &value, ptr.Ptr(), sizeof(value) );
+        memcpy( &denominator, ptr.Ptr()+sizeof(value), sizeof(denominator) );
+
+    	TReal32 mdeValue = 0.0f;
+    	if ( denominator != 0 )
+    		{
+    		mdeValue = (TReal32)value / (TReal32)denominator;
+    		}
+    	return Abs( tagValue - mdeValue ) > 0.01f;
+		}
+	else
+		{
+		return aMdeData.CompareF( aTag->Data() ) != 0; 
+		}
+	}
+
+TBool CHarvesterExifUtil::ModifyExifTagL( CMdEObject& aMdeObject, CExifModify& aExifModify,
+		const TDesC& aProperty, TExifIfdType aIFD, TUint16 aTagID, TBool aRemove )
+	{
+	CMdEObjectDef& imageDef = iDefaultNamespace->GetObjectDefL( Image::KImageObject );
+	CMdEPropertyDef& propDef = imageDef.GetPropertyDefL( aProperty );    
+	CMdEProperty* mdeProp = NULL;
+	TBool exifChanged = EFalse;
+	
+	aMdeObject.Property( propDef, mdeProp, 0 );
+	TBool tagExists = EFalse;
+	if( aRemove )
+		{
+		tagExists = aExifModify.Reader()->TagExists( aTagID, aIFD );
+		}
+	if ( mdeProp )
+        {
+        HBufC8* mdedata = GetPropertyValueLC( propDef, *mdeProp );
+        TPtrC8 ptr = mdedata->Des();
+        TBool change = EFalse;
+        const CExifTag* tag = NULL;
+        TRAP_IGNORE( tag = aExifModify.Reader()->GetTagL( aIFD, aTagID ) );
+        if( !tag ) //create new exif tag
+        	{
+        	change = ETrue;
+        	}
+        else if( CompareTag( ptr, tag ) )
+            {
+            change = ETrue;
+            }
+        if( change )
+        	{
+        	CExifTag::TExifTagDataType type = ExifTagDataType( aTagID, propDef );
+        	TInt len = 1;
+        	if( type == CExifTag::ETagUndefined || type == CExifTag::ETagAscii  )
+        		{
+        		len = ptr.Length();
+        		}
+        	TExifTagInfo info( aTagID, type, len  );
+            aExifModify.SetTagL( aIFD, info, ptr );
+            exifChanged = ETrue;        	
+        	}
+        CleanupStack::PopAndDestroy( mdedata );
+        }
+	else if( tagExists ) // remove from exif
+        {
+        aExifModify.DeleteTag( aIFD, aTagID );
+        exifChanged = ETrue;
+        }
+    return exifChanged;
+	}
+
+// ---------------------------------------------------------------------------
+// ComposeExifData
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt CHarvesterExifUtil::ComposeExifDataL( CMdEObject& aMdeObject, TPtr8 aImagePtr, HBufC8*& aModified )
+	{
+
+	if ( !iSession )
+		{
+		User::Leave( KErrSessionClosed );
+		}
+	
+    WRITELOG1( "CHarvesterExifUtil::ComposeExifData() - Compose Start Object ID: %d", aMdeObject.Id() );
+    TBool exifChanged = EFalse;
+
+    // 2. try to init EXIF data from image file's data
+    CExifModify* modifyExif = NULL;
+    TInt exifError = KErrNone;
+    TRAP( exifError, modifyExif = CExifModify::NewL( aImagePtr, 
+    		CExifModify::EModify, CExifModify::ENoJpegParsing ) );
+
+    // 3. Is this image format supported?
+    if ( exifError == KErrNotSupported )
+        {
+        WRITELOG( "CHarvesterExifUtil::ComposeExifData() - Image format not supported (!jpeg)" );
+        User::Leave( exifError );
+        }
+
+    // 4. if image does not contain EXIF data try to create it
+    if ( exifError != KErrNone )
+        {
+        WRITELOG( "CHarvesterExifUtil::ComposeExifData() - Image doesn't contain EXIF data" );
+        modifyExif = CExifModify::NewL( aImagePtr, 
+        		CExifModify::ECreate, CExifModify::ENoJpegParsing );
+        SetExifDefaultsL( aMdeObject, *modifyExif );
+        exifChanged = ETrue;
+        }
+    CleanupStack::PushL( modifyExif );
+    const CExifRead* readExif = modifyExif->Reader();
+    CMdEObjectDef& imageDef = iDefaultNamespace->GetObjectDefL( Image::KImageObject );
+    
+    // Set pixel X dimension tag (mandatory)
+    TBool changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		MediaObject::KWidthProperty, EIfdExif, KIdPixelXDimension);
+    exifChanged = (exifChanged | changed);
+
+    // Set pixel Y dimension tag (mandatory)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		MediaObject::KHeightProperty, EIfdExif, KIdPixelYDimension);
+    exifChanged = (exifChanged | changed);
+
+    // Set white balance tag (recommended)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KWhiteBalanceProperty, EIfdExif, KIdWhiteBalance, ETrue );
+    exifChanged = (exifChanged | changed);
+    
+    // Set flash tag (recommended)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KFlashProperty, EIfdExif, KIdFlash, ETrue );
+    exifChanged = (exifChanged | changed);
+    
+    // Set exposure program tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KExposureProgramProperty, EIfdExif, KIdExposureProgram, ETrue );
+    exifChanged = (exifChanged | changed);
+
+    // Set description tag (recommended)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		MediaObject::KDescriptionProperty, EIfd0, KIdImageDescription, ETrue );
+    exifChanged = (exifChanged | changed);
+    
+    // Set user comment tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		MediaObject::KCommentProperty, EIfdExif, KIdUserComment, ETrue );
+    exifChanged = (exifChanged | changed);
+    
+    // Set copyright tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		MediaObject::KCopyrightProperty, EIfd0, KIdCopyright, ETrue );
+    exifChanged = (exifChanged | changed);
+
+    // Set DateTimeOriginal tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KDateTimeOriginalProperty, EIfdExif, KIdDateTimeOriginal, ETrue );
+    exifChanged = (exifChanged | changed);
+    
+    // Set DateTimeDigitized tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KDateTimeDigitizedProperty, EIfdExif, KIdDateTimeDigitized, ETrue );
+    exifChanged = (exifChanged | changed);
+    
+    // Set DateTime (_image_ modified) tag (recommended)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KDateTimeProperty, EIfd0, KIdDateTimeModified, ETrue );
+    exifChanged = (exifChanged | changed);
+    
+    // Set maker tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KMakeProperty, EIfd1, KIdMake, ETrue );
+    exifChanged = (exifChanged | changed);
+    
+    // Set model tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KModelProperty, EIfd1, KIdModel, ETrue );
+    exifChanged = (exifChanged | changed);
+    
+    // Set orientation tag (recommended)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KOrientationProperty, EIfd0, KIdOrientation , ETrue );
+    exifChanged = (exifChanged | changed);
+
+    // Set YCbCrPositioning tag (mandatory)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KYCbCrPositioningProperty, EIfd1, KIdYbCrPositioning, EFalse );
+    exifChanged = (exifChanged | changed);
+    
+    // Set resolution unit tag (mandatory)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		MediaObject::KResolutionUnitProperty, EIfd1, KIdResolutionUnit, EFalse );
+    exifChanged = (exifChanged | changed);
+    
+    // Set ISO speed tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KISOSpeedRatingsProperty, EIfdExif, KIdISOSpeedRatings, ETrue );
+    exifChanged = (exifChanged | changed);
+
+    // Set related soundfile tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KRelatedSoundFileProperty, EIfdExif, KIdRelatedSoundFile, ETrue );
+    exifChanged = (exifChanged | changed);    
+    
+    // Set exposure time tag (recommended)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KExposureTimeProperty, EIfdExif, KIdExposureTime, ETrue );
+    exifChanged = (exifChanged | changed);   
+        
+    // Set aperture value tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KApertureValueProperty, EIfdExif, KIdApertureValue, ETrue );
+    exifChanged = (exifChanged | changed);  
+    
+    // Set colour space tag (mandatory)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+		Image::KColourSpaceProperty, EIfdExif, KIdColorSpace , EFalse );
+    exifChanged = (exifChanged | changed);
+        
+    // Set exposure bias tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KExposureBiasValueProperty, EIfdExif, KIdExposureBias, ETrue );
+    exifChanged = (exifChanged | changed);
+    
+    // Set metering mode tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KMeteringModeProperty, EIfdExif, KIdMeteringMode, ETrue );
+    exifChanged = (exifChanged | changed);
+
+    // Set shutter speed tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KShutterSpeedValueProperty, EIfdExif, KIdShutterSpeed, ETrue );
+    exifChanged = (exifChanged | changed);
+
+    // Set X resolution tag (mandatory)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KXResolutionProperty, EIfd0, KIdXResolution, EFalse );
+    exifChanged = (exifChanged | changed); 
+
+    // Set Y resolution tag (mandatory)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KYResolutionProperty, EIfd0, KIdYResolution, EFalse );
+    exifChanged = (exifChanged | changed); 
+    
+    // Set F number tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KFNumberProperty, EIfdExif, KIdFNumber, ETrue );
+    exifChanged = (exifChanged | changed);     
+    
+    // Set focal length tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KFocalLengthProperty, EIfdExif, KIdFocalLength, ETrue );
+    exifChanged = (exifChanged | changed);  
+    
+    // Set focal length in 35 mm film tag (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KFocalLengthIn35mmFilmProperty, EIfdExif, KIdFocalLengthIn35mm, ETrue );
+    exifChanged = (exifChanged | changed);   
+
+    // Set focal plane resolution unit (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KFocalPlaneResolutionUnitProperty, EIfdExif, KIdFocalPlaneResolutionUnit, ETrue );
+    exifChanged = (exifChanged | changed);   
+
+    // Set focal plane X resolution (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KFocalPlaneXResolutionProperty, EIfdExif, KIdFocalPlaneXResolution, ETrue );
+    exifChanged = (exifChanged | changed);
+    
+    // Set focal plane Y resolution (optional)
+    changed = ModifyExifTagL( aMdeObject, *modifyExif,
+    		Image::KFocalPlaneYResolutionProperty, EIfdExif, KIdFocalPlaneYResolution, ETrue );
+    exifChanged = (exifChanged | changed);
+    
+    TUint16 uint16Value( 0 );
+    TUint32 uint32Value( 0 );
+    
+    // Set components configuration tag (mandatory)
+    const CMdEPropertyDef& componentsDef = imageDef.GetPropertyDefL(
+     		Image::KComponentsConfigurationProperty );
+        {
+        CMdEProperty* componentsProp = NULL;
+        aMdeObject.Property( componentsDef, componentsProp, 0 );
+
+        if ( componentsProp )
+            {
+            TUint32 componentsValue = componentsProp->Uint32ValueL();
+            TUint8* components = (TUint8*) &componentsValue;
+            const TUint8 KComponent4th = *(components + 3);
+            const TUint8 KComponent3rd = *(components + 2);
+            const TUint8 KComponent2nd = *(components + 1);
+            const TUint8 KComponent1st = *components;
+            
+            TUint8 exifComponent4th( 0 );
+            TUint8 exifComponent3rd( 0 );
+            TUint8 exifComponent2nd( 0 );
+            TUint8 exifComponent1st( 0 );
+            
+            exifError = readExif->GetComponentsConfiguration(
+              	exifComponent1st, exifComponent2nd, exifComponent3rd, exifComponent4th );
+            if ( exifError != KErrNone || 
+                 exifComponent1st != KComponent1st || exifComponent2nd != KComponent2nd ||
+                 exifComponent3rd != KComponent3rd || exifComponent4th != KComponent4th )
+                {
+                modifyExif->SetComponentsConfigurationL(
+                		KComponent1st, KComponent2nd, KComponent3rd, KComponent4th );
+                exifChanged = ETrue;
+                }
+            }
+        }        
+        
+	// Set thumbnail X resolution tag (mandatory)
+    const CMdEPropertyDef& thumbXDef = imageDef.GetPropertyDefL(
+        Image::KThumbXResolutionProperty );
+        {
+        CMdEProperty* thumbXProp = NULL;
+        aMdeObject.Property( thumbXDef, thumbXProp, 0 );
+
+        if ( thumbXProp )
+            {
+            const TUint32 thumbX = thumbXProp->Uint32ValueL();
+
+            TUint32 exifDenominator = 0;
+            exifError = readExif->GetThumbnailXResolution( uint32Value, exifDenominator );
+            TUint32 exifThumbXResol = 0;
+            if ( exifDenominator > 0 )
+                {
+                exifThumbXResol = uint32Value / exifDenominator;
+                }
+
+            if ( exifError != KErrNone || exifThumbXResol != thumbX )
+                {
+                const TUint32 KDenominator = 1;
+                modifyExif->SetThumbnailXResolutionL( thumbX, KDenominator );
+                exifChanged = ETrue;
+                }
+            }
+        }
+
+	// Set thumbnail Y resolution tag (mandatory)
+    const CMdEPropertyDef& thumbYDef = imageDef.GetPropertyDefL(
+      		Image::KThumbYResolutionProperty );
+        {
+        CMdEProperty* thumbYProp = NULL;
+        aMdeObject.Property( thumbYDef, thumbYProp, 0 );
+
+        if ( thumbYProp )
+            {
+            TUint32 thumbY = TUint32( thumbYProp->Uint32ValueL() );
+            TUint32 exifDenominator = 0;
+            exifError = readExif->GetThumbnailYResolution( uint32Value, exifDenominator );
+            TUint32 exifThumbYResol = 0;
+            if ( exifDenominator > 0 )
+                {
+                exifThumbYResol = uint32Value / exifDenominator;
+                }
+            
+            if ( exifError != KErrNone || exifThumbYResol != thumbY )
+                {
+                const TUint32 KDenominator = 1;
+                modifyExif->SetThumbnailYResolutionL( thumbY, KDenominator );
+                exifChanged = ETrue;
+                }
+            }
+        }
+
+	// Set thumbnail resolution unit tag (mandatory)
+    const CMdEPropertyDef& thumbResolutionUnitDef = imageDef.GetPropertyDefL(
+        	Image::KThumbResolutionUnitProperty );
+        {
+        CMdEProperty* thumbResolutionUnitProp = NULL;            
+        aMdeObject.Property( thumbResolutionUnitDef, thumbResolutionUnitProp, 0 );
+
+        if ( thumbResolutionUnitProp )
+            {
+            exifError = readExif->GetThumbnailResolutionUnit( uint16Value );
+            const TUint16 thumbnailResolutionUnitValue =
+             	thumbResolutionUnitProp->Uint16ValueL();
+            if ( exifError != KErrNone || uint16Value != thumbnailResolutionUnitValue )
+                {
+                modifyExif->SetThumbnailResolutionUnitL( thumbnailResolutionUnitValue );
+                exifChanged = ETrue;
+                }
+            }
+        }
+        
+    if ( exifChanged )
+        {
+        WRITELOG( "CHarvesterExifUtil::ComposeExifData() - write exif to buffer" );
+        aModified = modifyExif->WriteDataL( aImagePtr );
+        }
+    CleanupStack::PopAndDestroy( modifyExif );
+
+    WRITELOG1( "CHarvesterExifUtil::ComposeExifData() - Compose End Object ID: %d", aMdeObject.Id() );
+
+	return KErrNone;
+	}
+
+// ---------------------------------------------------------------------------
+// ComposeLocation
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CHarvesterExifUtil::ComposeLocationL( CMdEObject* aLocation, TPtr8 aImagePtr, HBufC8*& aModified )
+    {
+    CMdEProperty* latitudeProperty = NULL;
+    CMdEProperty* longitudeProperty = NULL;
+    CMdEProperty* altitudeProperty = NULL;
+    CMdEProperty* qualityProperty = NULL;
+    
+    CMdEObjectDef& locationDef = iDefaultNamespace->GetObjectDefL( Location::KLocationObject );
+
+    aLocation->Property( locationDef.GetPropertyDefL(
+    		Location::KLatitudeProperty ), latitudeProperty, 0 );
+    aLocation->Property( locationDef.GetPropertyDefL(
+    		Location::KLongitudeProperty ), longitudeProperty, 0 );
+    aLocation->Property( locationDef.GetPropertyDefL(
+    		Location::KAltitudeProperty ), altitudeProperty, 0 );
+    aLocation->Property( locationDef.GetPropertyDefL(
+    		Location::KQualityProperty ), qualityProperty, 0 );
+
+    CExifModify* exifWriter = CExifModify::NewL( aImagePtr, 
+    		CExifModify::EModify, CExifModify::ENoJpegParsing );
+    CleanupStack::PushL( exifWriter );
+    const CExifRead* exifReader = exifWriter->Reader();
+
+    TBool exifChanged = EFalse;
+    TBool changed = EFalse;
+    const TReal KAngleSecond = 1.0 / 3600.0;
+    TInt exifError( 0 );
+    // location data (all fields are optional)
+    // latitude
+    const CExifTag* exifLatitudeRefTag = NULL;
+    TRAP( exifError, exifLatitudeRefTag = exifReader->GetTagL( EIfdGps, KIdGpsLatitudeRef ) );
+    if ( latitudeProperty )
+        {
+        TBuf8<2> south( KSouth );
+        TBuf8<2> north( KNorth );
+        TReal64 latitude = latitudeProperty->Real64ValueL();
+
+        TReal64 exifLatitude( 0.0 );
+        TBuf8<2> exifLatitudeRef;
+        if ( exifError == KErrNone )
+            {
+            TPtrC8 exifLatitudeRefBuf( exifLatitudeRefTag->Data() );
+            exifLatitudeRef.Append( exifLatitudeRefBuf.Ptr(), 2 );
+
+            if ( latitude < 0 )
+                {
+                if ( south.Compare(exifLatitudeRef) )
+                    {
+                    changed = ETrue;
+                    }
+                }
+            else
+                {
+                if ( north.Compare(exifLatitudeRef) )
+                    {
+                    changed = ETrue;
+                    }
+                }
+
+            if ( !changed )
+                {
+                TBuf8<KCoordinateBufferSize> exifLatitudeBuf;
+                const CExifTag* exifLatitudeTag = NULL;
+                TRAPD( err, exifLatitudeTag = exifReader->GetTagL( EIfdGps, KIdGpsLatitude ) );
+                if ( err == KErrNone )
+                    {
+                    TPtrC8 exifLatitudeTagBuf( exifLatitudeTag->Data() );
+                    exifLatitudeBuf.Append( exifLatitudeTagBuf.Ptr(), KCoordinateBufferSize );
+                    MdsUtils::ConvertFromDegreesToDecimalL( exifLatitudeBuf, exifLatitude );
+                    }
+                else
+                    {
+                    exifError = err;
+                    }
+                }
+            }
+
+        if ( exifError != KErrNone || changed || Abs(exifLatitude - latitude) > KAngleSecond )
+            {
+            // latitude ref (N/S)
+            if ( latitude < 0 )
+                {
+                exifWriter->SetTagL( EIfdGps, TExifTagInfo(
+                		KIdGpsLatitudeRef, CExifTag::ETagAscii, 2 ), south );
+                latitude = -latitude;
+                }
+            else
+                {
+                exifWriter->SetTagL( EIfdGps, TExifTagInfo(
+                		KIdGpsLatitudeRef, CExifTag::ETagAscii, 2 ), north );
+                }
+
+            TBuf8<KCoordinateBufferSize> latitudeBuf;
+            MdsUtils::ConvertFromDecimalToDegreesL( latitude, latitudeBuf );
+            exifWriter->SetTagL( EIfdGps, TExifTagInfo(
+            		KIdGpsLatitude, CExifTag::ETagRational, 3 ), latitudeBuf );
+            exifChanged = ETrue;
+            }
+        }
+    else if ( exifError == KErrNone )
+        {
+        exifWriter->DeleteTag( EIfdGps, KIdGpsLatitudeRef );
+        exifWriter->DeleteTag( EIfdGps, KIdGpsLatitude );
+        exifChanged = ETrue;
+        }
+
+    changed = EFalse;
+    
+    // longitude
+    const CExifTag* exifLongitudeRefTag = NULL;
+    TRAP( exifError, exifLongitudeRefTag = exifReader->GetTagL(
+    		EIfdGps, KIdGpsLongitudeRef ) );
+    if ( longitudeProperty )
+        {
+        TBuf8<2> west( KWest );
+        TBuf8<2> east( KEast );        
+        TReal64 longitude = longitudeProperty->Real64ValueL();
+        
+        TReal64 exifLongitude( 0.0 );
+        TBuf8<2> exifLongitudeRef;
+        if ( exifError == KErrNone )
+            {
+            TPtrC8 exifLongitudeRefBuf( exifLongitudeRefTag->Data() );
+            exifLongitudeRef.Append( exifLongitudeRefBuf.Ptr(), 2 );
+
+            if ( longitude < 0 )
+                {
+                if ( west.Compare(exifLongitudeRef) )
+                    {
+                    changed = ETrue;
+                    }
+                }
+            else
+                {
+                if ( east.Compare(exifLongitudeRef) )
+                    {
+                    changed = ETrue;
+                    }
+                }
+
+            if ( !changed )
+                {
+                TBuf8<KCoordinateBufferSize> exifLongitudeBuf;
+                const CExifTag* exifLongitudeTag = NULL;
+                TRAPD( err, exifLongitudeTag = exifReader->GetTagL( EIfdGps, KIdGpsLongitude ) );
+                if ( err == KErrNone )
+                    {
+                    TPtrC8 exifLongitudeTagBuf( exifLongitudeTag->Data() );
+                    exifLongitudeBuf.Append( exifLongitudeTagBuf.Ptr(), KCoordinateBufferSize );
+                    MdsUtils::ConvertFromDegreesToDecimalL( exifLongitudeBuf, exifLongitude );
+                    if ( exifLongitudeRef.Compare( KWest ) == 0 )
+                        {
+                        exifLongitude = -exifLongitude;
+                        }
+                    }
+                else
+                    {
+                    exifError = err;
+                    }
+                }
+            }
+
+        if ( exifError != KErrNone || changed || Abs(exifLongitude - longitude) > KAngleSecond )
+            {
+            // longitude ref (E/W)
+            if ( longitude < 0 )
+                {
+                exifWriter->SetTagL( EIfdGps,
+                		TExifTagInfo( KIdGpsLongitudeRef, CExifTag::ETagAscii, 2 ), west );
+                longitude = -longitude;
+                }
+            else
+                {
+                exifWriter->SetTagL( EIfdGps,
+                		TExifTagInfo( KIdGpsLongitudeRef, CExifTag::ETagAscii, 2 ), east );
+                }
+            
+            TBuf8<KCoordinateBufferSize> longitudeBuf;
+            MdsUtils::ConvertFromDecimalToDegreesL( longitude, longitudeBuf );
+            exifWriter->SetTagL( EIfdGps,
+            		TExifTagInfo( KIdGpsLongitude, CExifTag::ETagRational, 3 ), longitudeBuf );
+            exifChanged = ETrue;
+            }
+        }
+    else if ( exifError == KErrNone )
+        {
+        exifWriter->DeleteTag( EIfdGps, KIdGpsLongitudeRef );
+        exifWriter->DeleteTag( EIfdGps, KIdGpsLongitude  );
+        exifChanged = ETrue;
+        }
+
+    changed = EFalse;
+    
+    // altitude
+    const CExifTag* exifAltitudeRefTag = NULL;
+    TRAP( exifError, exifAltitudeRefTag = exifReader->GetTagL( EIfdGps, KIdGpsAltitudeRef ) );
+    if ( altitudeProperty )
+        {
+        TReal64 altitude = altitudeProperty->Real64ValueL();
+
+        TBuf8<8> altitudeBuf;
+        const TInt32 KAltDenominator = 100;
+        altitude *= KAltDenominator;
+
+        TUint8 altitudeRef = 0;
+        TBuf8<1> altRefBuf;
+        
+        if ( altitude < 0 )
+            {
+            altitudeRef = 1;
+            altitude = -altitude;
+            }        	
+        
+        altRefBuf.Append( &altitudeRef, 1 );
+
+        TInt32 exifAltitudeValue( 0 );
+        TInt32 exifAltDenominator( 0 );
+        TReal64 exifAltitude = 0.0f;
+        TBuf8<1> exifAltitudeRef;
+        if ( exifError == KErrNone )
+            {
+            TPtrC8 exifAltitudeRefBuf( exifAltitudeRefTag->Data() );
+            exifAltitudeRef.Append( exifAltitudeRefBuf.Ptr(), 1 );
+            const CExifTag* exifAltitudeTag = NULL;
+            TRAPD( err, exifAltitudeTag = exifReader->GetTagL( EIfdGps, KIdGpsAltitude ) );
+            if ( err == KErrNone )
+                {
+                TPtrC8 exifAltitudeTagBuf( exifAltitudeTag->Data() );
+                memcpy( &exifAltitudeValue, exifAltitudeTagBuf.Ptr(),
+                		sizeof(exifAltitudeValue) );
+                memcpy( &exifAltDenominator,
+                		exifAltitudeTagBuf.Ptr()+sizeof(exifAltitudeValue),
+                		sizeof(exifAltDenominator) );
+                }
+            else
+                {
+                exifError = err;
+                }
+            exifAltitude = (TReal64)exifAltitudeValue;
+            }
+
+        if ( exifError != KErrNone || exifAltitudeRef.Compare(altRefBuf) ||
+        		Abs(altitude - exifAltitude) > KAngleSecond )
+            {
+            exifWriter->SetTagL( EIfdGps, TExifTagInfo(
+            		KIdGpsAltitudeRef, CExifTag::ETagByte, 1 ), altRefBuf );
+
+            TInt32 tmpAlt = (TInt32) altitude;
+            altitudeBuf.Append( (TUint8*) &tmpAlt, 4 );
+            altitudeBuf.Append( (TUint8*) &KAltDenominator, 4 );
+            exifWriter->SetTagL( EIfdGps, TExifTagInfo(
+            		KIdGpsAltitude, CExifTag::ETagRational, 1 ), altitudeBuf );
+            exifChanged = ETrue;
+
+            changed = EFalse;            
+            }
+        // measure mode
+        const CExifTag* exifMeasureModeTag = NULL;
+        TRAPD( err, exifMeasureModeTag = exifReader->GetTagL( EIfdGps, KIdGpsMeasureMode ) );
+        if ( err == KErrNone )
+        	{
+        	
+        	TBuf8<2> exifMeasureMode;
+            TPtrC8 exifMeasureModeBuf( exifMeasureModeTag->Data() );
+            exifMeasureMode.Append( exifMeasureModeBuf.Ptr(), 2 );
+        	
+            if (altitude == 0)
+            	{
+            	if (exifMeasureMode.Compare(KMeasureMode3))
+            		{
+            		changed = ETrue;
+            		}
+            	}
+            else
+            	{
+            	if (exifMeasureMode.Compare(KMeasureMode2))
+            		{
+            		changed = ETrue;
+            		}
+            	}
+        	}
+        else
+            {
+            exifError = err;
+            }
+        
+        if (err != KErrNone || changed)
+        	{
+        	if (altitude == 0)
+            	{
+            	exifWriter->SetTagL( EIfdGps, TExifTagInfo(
+            		KIdGpsMeasureMode, CExifTag::ETagAscii, 2 ), KMeasureMode2 );
+            	}
+        	else
+        		{
+        		exifWriter->SetTagL( EIfdGps, TExifTagInfo(
+                		KIdGpsMeasureMode, CExifTag::ETagAscii, 2 ), KMeasureMode3 );
+        		}
+        	}
+        }
+    else if ( exifError == KErrNone )
+        {
+        exifWriter->DeleteTag( EIfdGps, KIdGpsAltitudeRef  );
+        exifWriter->DeleteTag( EIfdGps, KIdGpsAltitude  );
+        exifWriter->DeleteTag( EIfdGps, KIdGpsMeasureMode  );
+        exifChanged = ETrue;
+        } 
+    
+    changed = EFalse;
+    
+    // quality, DOP value
+    const CExifTag* exifQualityTag = NULL;
+    TRAPD( err, exifQualityTag = exifReader->GetTagL( EIfdGps, KIdGpsDop ) );
+    if (qualityProperty)
+    	{
+        CMdEReal32Property* qualityReal = static_cast<CMdEReal32Property*>(qualityProperty);
+        TReal32 quality = qualityReal->Value();
+        const TInt32 KQualityDenominator = 10;
+        TBuf8<8> qualityBuf;
+        TInt32 exifQualityValue( 0 );
+        TInt32 exifQualityDenominator( 0 );  
+        TReal32 exifQuality (0.0f);
+        quality = quality * KQualityDenominator;
+        
+	    if ( err == KErrNone )
+	        {
+                TPtrC8 exifQualityTagBuf( exifQualityTag->Data() );
+                memcpy( &exifQualityValue, exifQualityTagBuf.Ptr(),
+                		sizeof(exifQualityValue) );
+                memcpy( &exifQualityDenominator,
+                		exifQualityTagBuf.Ptr()+sizeof(exifQualityValue),
+                		sizeof(exifQualityDenominator) );
+	        }
+        else
+            {
+            exifError = err;
+            }
+	    
+	    if (exifQualityDenominator > 0)
+	    	{
+	    	exifQuality = (TReal32)exifQualityValue;
+	    	}
+	    
+	    if (exifError != KErrNone || Abs(quality - exifQuality) > 0.1f)
+	    	{
+	    	
+	    	TInt32 tmpQuality = (TInt32) quality;
+	    	qualityBuf.Append( (TUint8*) &tmpQuality, 4 );
+	    	qualityBuf.Append( (TUint8*) &KQualityDenominator, 4 );
+            exifWriter->SetTagL( EIfdGps, TExifTagInfo(
+            		KIdGpsDop, CExifTag::ETagRational, 1 ), qualityBuf );
+            exifChanged = ETrue;	    	
+	    	}	    
+    	}
+    
+    const CExifTag* exifDatumTag = NULL;
+    TRAP( err, exifDatumTag = exifReader->GetTagL( EIfdGps, KIdGpsMapDatum ) );
+    TBuf8<7> mapdatum( KMapDatum );
+
+    
+    if ( err == KErrNone )
+        {        
+        if (exifDatumTag->Data().Compare(mapdatum))
+    		{
+    		changed = ETrue;
+    		}        	
+        }
+    else
+        {
+        exifError = err;
+        }
+    
+    if (exifError != KErrNone || changed)
+    	{        		
+		exifWriter->SetTagL( EIfdGps, TExifTagInfo(
+			KIdGpsMapDatum, CExifTag::ETagAscii, 7 ), mapdatum );
+    	}
+    
+    // write the EXIF data to the image
+    if ( exifChanged )
+        {
+        aModified = exifWriter->WriteDataL( aImagePtr );
+        }
+    CleanupStack::PopAndDestroy( exifWriter );
+    }
+
+void CHarvesterExifUtil::ReadUserCommentL( CHarvestData& aHd, CExifRead* aReader )
+    {
+    // Getting UserComment
+    if ( aReader->TagExists(KIdUserComment, EIfdExif ) )
+        {
+        TUint16 KMaxCommentLength = 256;
+        
+        HBufC8* comment = aReader->GetUserCommentL();
+        CleanupStack::PushL( comment );
+        if( comment->Length() >= 8 )
+            {
+            TBuf8<8> commentFormat = comment->Mid( 0,8 );
+            
+            TUint16 commentLength = comment->Length();
+            
+            TPtrC8 userPtr = comment->Mid( 8, commentLength > KMaxCommentLength ?
+                    KMaxCommentLength - 8 : commentLength - 8 );
+            
+            if ( commentFormat.Compare(KUnicodeCodeDesignation) == 0 )
+                {
+                WRITELOG( "CHarvesterExifUtil::ReadUserCommentL() - comment, Unicode encoding" );
+                aHd.iComment16 = HBufC::NewL( userPtr.Length() );
+                TPtr ptr = aHd.iComment16->Des();
+                TPtrC16 ptr16( (TUint16*)(userPtr.Ptr()), (userPtr.Size()/2) );
+                ptr.Copy( ptr16 );
+                }
+            else if ( commentFormat.Compare(KAsciiCodeDesignation) == 0 ||
+                      commentFormat.Compare(KUnknownCodeDesignation) == 0 ||
+                      commentFormat.Compare(KJisCodeDesignation) == 0 )
+                {
+                aHd.iComment16 = CnvUtfConverter::ConvertToUnicodeFromUtf8L( userPtr ); 
+                }
+            else
+                {
+                WRITELOG( "CHarvesterExifUtil::ReadUserCommentL() - unknown comment encoding" );    
+                }
+            if( aHd.iComment16 )
+                {
+                StripNulls( *(aHd.iComment16) );
+                }
+            }
+        CleanupStack::PopAndDestroy( comment );
+        comment = NULL;
+        }
+    }
+
+void CHarvesterExifUtil::ReadXResolutionL( CHarvestData& aHd, CExifRead* aReader )
+    {
+    //Getting X Resolution
+    TUint32 numerator = 0;
+    TUint32 denominator = 0;
+    const TInt error = aReader->GetXResolution( numerator, denominator );
+    if ( error == KErrNone )
+        {
+        aHd.iStoreXResolution = ETrue;
+        aHd.iXResolution = 0.0f;
+        if ( denominator > 0 )
+            {
+            aHd.iXResolution = (TReal32) numerator / (TReal32) denominator;
+            }
+        }
+    }
+
+void CHarvesterExifUtil::ReadYResolutionL( CHarvestData& aHd, CExifRead* aReader )
+    {
+    //Getting Y Resolution
+    TUint32 numerator = 0;
+    TUint32 denominator = 0;
+    const TInt error = aReader->GetYResolution( numerator, denominator );
+    if ( error == KErrNone )
+        {
+        aHd.iStoreYResolution = ETrue;
+        aHd.iYResolution = 0.0f;
+        if ( denominator > 0 )
+            {
+            aHd.iYResolution = (TReal32) numerator / (TReal32) denominator;
+            }
+        }
+    }
+
+void CHarvesterExifUtil::ReadExposureBiasL( CHarvestData& aHd, CExifRead* aReader )
+    {
+    // Getting exposure bias
+    TInt32 num( 0 );
+    TInt32 deno( 0 );
+    const TInt error = aReader->GetExposureBiasValue( num, deno );
+    if ( error == KErrNone )
+        {
+        aHd.iStoreExposureBias = ETrue;
+        aHd.iExposureBias = 0.0f;
+        if ( deno != 0 )
+            {
+            aHd.iExposureBias = (TReal32) num / (TReal32) deno;    
+            }
+        }
+    }
+
+void CHarvesterExifUtil::ReadExposureTimeL( CHarvestData& aHd, CExifRead* aReader )
+    {
+    // Getting exposure time
+    TUint32 numerator = 0;
+    TUint32 denominator = 0;
+    const TInt error = aReader->GetExposureTime( numerator, denominator );
+    if ( error == KErrNone )
+        {
+        aHd.iStoreExposureTime = ETrue;
+        aHd.iExposureTime = 0.0f;
+        if ( denominator > 0 )
+            {
+            aHd.iExposureTime = (TReal32) numerator / (TReal32) denominator;
+            }
+        }
+    }
+
+void CHarvesterExifUtil::ReadFNumberL( CHarvestData& aHd, CExifRead* aReader )
+    {
+    //Getting FNumber
+    if ( aReader->TagExists(KIdFNumber, EIfdExif) )
+        {
+        const CExifTag* tag = aReader->GetTagL( EIfdExif, KIdFNumber );
+        TPtrC8 tagData = tag->Data();
+        
+        TUint32 numerator = MdsUtils::ToUInt32L( CONST_CAST( TUint8*, tagData.Ptr() ) );
+        TUint32 denominator = MdsUtils::ToUInt32L( CONST_CAST( TUint8*, tagData.Ptr() + 4 ) );
+        if ( denominator == 0 )
+            {
+            denominator = 1;
+            }
+        
+        aHd.iFNumber = (TReal32) numerator / (TReal32) denominator;
+        aHd.iStoreFNumber = ETrue;
+        WRITELOG1( "CHarvesterExifUtil::ReadFNumberL() - fnumber %f", aHd.iFNumber );
+        }
+    }
+
+void CHarvesterExifUtil::ReadShutterSpeedL( CHarvestData& aHd, CExifRead* aReader )
+    {
+    //Getting shutter speed value
+    TInt32 num( 0 );
+    TInt32 deno( 0 );
+    const TInt error = aReader->GetShutterSpeedValue( num, deno );
+    if ( error == KErrNone )
+        {
+        aHd.iStoreShutterSpeed = ETrue;
+        aHd.iShutterSpeed = 0.0f;
+        if ( deno != 0 )
+            {
+            aHd.iShutterSpeed = (TReal32) num / (TReal32) deno;
+            }
+        
+        WRITELOG1( "CHarvesterExifUtil::ReadExifDataL() - shutter speed %f", aHd.iShutterSpeed );
+        }
+    }
+
+void CHarvesterExifUtil::ReadApertureValueL( CHarvestData& aHd, CExifRead* aReader )
+    {
+    //Getting aHd.iAperture
+    TUint32 numerator = 0;
+    TUint32 denominator = 0;
+    const TInt error = aReader->GetApertureValue( numerator, denominator );
+    if ( error == KErrNone )
+        {
+        aHd.iStoreAperture = ETrue;
+        aHd.iAperture = 0.0f;
+        if ( denominator > 0 )
+            {
+            aHd.iAperture = (TReal32) numerator / (TReal32) denominator;
+            }
+      
+        WRITELOG1( "CHarvesterExifUtil::ReadExifDataL() - aHd.iAperture %f", aHd.iAperture );
+        }
+    }
+
+void CHarvesterExifUtil::ReadFocalLengthL( CHarvestData& aHd, CExifRead* aReader )
+    {
+    //Getting focal length
+    TUint32 numerator = 0;
+    TUint32 denominator = 0;
+    if ( aReader->TagExists(KIdFocalLength, EIfdExif) )
+        {                
+        const CExifTag* tag = aReader->GetTagL( EIfdExif, KIdFocalLength );
+        TPtrC8 tagData = tag->Data();
+        
+        numerator = MdsUtils::ToUInt32L( CONST_CAST( TUint8*, tagData.Ptr() ) );
+        denominator = MdsUtils::ToUInt32L( CONST_CAST( TUint8*, tagData.Ptr() + 4 ) );
+        
+        if ( denominator == 0 )
+            {
+            denominator = 1;
+            }
+        
+        aHd.iFocalLength = (TReal32) numerator / (TReal32) denominator;
+        aHd.iStoreFocalLength = ETrue;
+        
+        WRITELOG1( "CHarvesterExifUtil::ReadExifDataL() - focal length %f", aHd.iFocalLength );
+        }
+    }
+
+void CHarvesterExifUtil::ReadFocalLength35mmL( CHarvestData& aHd, CExifRead* aReader )
+    {
+    // Getting focal length in 35 mm
+    if ( aReader->TagExists(KIdFocalLengthIn35mm, EIfdExif) )
+        {
+        const CExifTag* tag = aReader->GetTagL( EIfdExif, KIdFocalLengthIn35mm );
+        TPtrC8 tagData = tag->Data();
+        
+        aHd.iFocalLengthIn35mm = MdsUtils::ToUInt16L( CONST_CAST( TUint8*, tagData.Ptr() ) );
+        
+        aHd.iStoreFocalLengthIn35 = ETrue;
+        
+        WRITELOG1( "CHarvesterExifUtil::ReadExifDataL() - focal length in 35 mm: %f", aHd.iFocalLengthIn35mm );
+        }
+    }
+
+void CHarvesterExifUtil::ReadFocalXPlaneResolutionL( CHarvestData& aHd, CExifRead* aReader )
+    {
+    // Getting focal plane X resolution
+    if ( aReader->TagExists(KIdFocalPlaneXResolution, EIfdExif) )
+        {
+        const CExifTag* tag = aReader->GetTagL(
+                EIfdExif, KIdFocalPlaneXResolution );
+        TPtrC8 tagData = tag->Data();
+        
+        TUint32 numerator = MdsUtils::ToUInt32L( CONST_CAST( TUint8*, tagData.Ptr() ) );
+        TUint32 denominator = MdsUtils::ToUInt32L( CONST_CAST( TUint8*, tagData.Ptr() + 4 ) );
+        if ( denominator == 0 )
+            {
+            denominator = 1;
+            }
+        
+        aHd.iFocalPlaneXResolution = (TReal32) numerator / (TReal32) denominator;
+        aHd.iStoreFocalPlaneXResolution = ETrue;
+        }
+    }
+
+void CHarvesterExifUtil::ReadFocalYPlaneResolutionL( CHarvestData& aHd, CExifRead* aReader )
+    {
+    // Getting focal plane Y resolution
+    if ( aReader->TagExists(KIdFocalPlaneYResolution, EIfdExif) )
+        {
+        const CExifTag* tag = aReader->GetTagL(
+                EIfdExif, KIdFocalPlaneYResolution );
+        TPtrC8 tagData = tag->Data();
+        
+        TUint32 numerator = MdsUtils::ToUInt32L( CONST_CAST( TUint8*, tagData.Ptr() ) );
+        TUint32 denominator = MdsUtils::ToUInt32L( CONST_CAST( TUint8*, tagData.Ptr() + 4 ) );
+        if ( denominator == 0 )
+            {
+            denominator = 1;
+            }
+        
+        aHd.iFocalPlaneYResolution = (TReal32) numerator / (TReal32) denominator;
+        aHd.iStoreFocalPlaneYResolution = ETrue;
+        }
+    }
+
+void CHarvesterExifUtil::ReadGPSLatitudeL( CHarvestData& aHd, 
+                                                                       CExifRead* aReader, 
+                                                                       TBool& aLatitude )
+    {
+    const TInt KCoordinateBufferSize = 24;
+    
+    WRITELOG( "CHarvesterExifUtil::ReadGPSLatitudeL() - trying to read GPS Latitude" );
+    
+    // Getting GPS latitude   
+    if ( aReader->TagExists(KIdGpsLatitudeRef, EIfdGps) &&
+            aReader->TagExists(KIdGpsLatitude, EIfdGps) )
+        {
+        WRITELOG( "CHarvesterExifUtil::ReadGPSLatitudeL() - GPS Latitude found" );
+        
+        TReal64 latitude = 0.0;
+        const CExifTag* refTag = aReader->GetTagL(
+                EIfdGps, KIdGpsLatitudeRef );
+        TBuf8<2> latitudeRef = refTag->Data();
+        const CExifTag* latitudeTag = aReader->GetTagL(
+                EIfdGps, KIdGpsLatitude );
+        TBuf8<KCoordinateBufferSize> latitudeBuf = latitudeTag->Data();
+        MdsUtils::ConvertFromDegreesToDecimalL( latitudeBuf, latitude );
+        if ( latitudeRef == KSouth )
+            {
+            latitude = -latitude;
+            }
+        aHd.iGpsLatitude = latitude;
+        aLatitude = ETrue;
+        }
+    
+    WRITELOG( "CHarvesterExifUtil::ReadGPSLatitudeL() - trying to read GPS Latitude - end" );
+    }
+
+void CHarvesterExifUtil::ReadGPSLongitudeL( CHarvestData& aHd, 
+                                                                          CExifRead* aReader, 
+                                                                          TBool& aLatitude )
+    {
+    const TInt KCoordinateBufferSize = 24;
+    
+    WRITELOG( "CHarvesterExifUtil::ReadGPSLongitudeL() - trying to read GPS Longitude" );
+    
+    // Getting GPS longitude
+    if ( aReader->TagExists(KIdGpsLongitudeRef, EIfdGps) &&
+            aReader->TagExists(KIdGpsLongitude, EIfdGps) )
+        {
+        WRITELOG( "CHarvesterExifUtil::ReadGPSLatitudeL() - GPS Longitude found" );
+    
+        TReal64 longitude = 0.0;
+        const CExifTag* refTag = aReader->GetTagL(
+                EIfdGps, KIdGpsLongitudeRef );
+        TBuf8<2> longitudeRef = refTag->Data();
+        const CExifTag* longitudeTag = aReader->GetTagL(
+                EIfdGps, KIdGpsLongitude );
+        TBuf8<KCoordinateBufferSize> longitudeBuf = longitudeTag->Data();
+        MdsUtils::ConvertFromDegreesToDecimalL( longitudeBuf, longitude );
+        if ( longitudeRef == KWest )
+            {
+            longitude = -longitude;
+            }
+        aHd.iGpsLongitude = longitude;
+        if ( aLatitude )
+            {
+            aHd.iStoreGpsLatitudeAndLongitude = ETrue;
+            }
+        }
+    
+    WRITELOG( "CHarvesterExifUtil::ReadGPSLongitudeL() - trying to read GPS Longitude - end" );
+    }
+
+void CHarvesterExifUtil::ReadGPSAltitudeL( CHarvestData& aHd, CExifRead* aReader )
+    {
+    const TInt KAltitudeBufferSize = 8;
+    
+    WRITELOG( "CHarvesterExifUtil::ReadGPSLongitudeL() - trying to read GPS Altitude" );
+    
+    // Getting GPS altitude
+    if ( aReader->TagExists(KIdGpsAltitudeRef, EIfdGps) &&
+            aReader->TagExists(KIdGpsAltitude, EIfdGps) )
+        {
+        WRITELOG( "CHarvesterExifUtil::ReadGPSLatitudeL() - GPS Altitude found" );
+    
+        const CExifTag* refTag = aReader->GetTagL(
+                EIfdGps, KIdGpsAltitudeRef );
+        TBuf8<1> altitudeRef = refTag->Data();
+        const CExifTag* altitudeTag = aReader->GetTagL(
+                EIfdGps, KIdGpsAltitude );
+        TBuf8<KAltitudeBufferSize> altitudeBuf = altitudeTag->Data();
+        TInt32 altitude = MdsUtils::ToUInt32L(
+                CONST_CAST( TUint8*, altitudeBuf.Left(4).Ptr() ) );
+        TInt32 denominator =  MdsUtils::ToUInt32L(
+                CONST_CAST( TUint8*, altitudeBuf.Right(4).Ptr() ) );
+        TInt8 ref = *((TUint8*) altitudeRef.Ptr());
+
+        if ( ref == 1 )
+            {
+            altitude = -altitude;
+            }
+
+        aHd.iGpsAltitude = 0.0f;
+        if ( denominator != 0 )
+            {
+            aHd.iGpsAltitude = (TReal64)altitude / (TReal64)denominator;
+            }
+
+        aHd.iStoreGpsAltitude = ETrue;
+        }
+    
+    WRITELOG( "CHarvesterExifUtil::ReadGPSLongitudeL() - trying to read GPS Altitude - end" );
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/harvestermediaidutil.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,144 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Utility class to keep a list of mediaid's
+*/
+
+#include "harvestermediaidutil.h"
+#include "mdsutils.h"
+
+
+CHarvesterMediaIdUtil* CHarvesterMediaIdUtil::NewL()
+	{
+	CHarvesterMediaIdUtil* self = new (ELeave) CHarvesterMediaIdUtil;
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+
+CHarvesterMediaIdUtil::CHarvesterMediaIdUtil()
+	{
+	// no implementation needed
+	}
+
+CHarvesterMediaIdUtil::~CHarvesterMediaIdUtil()
+	{
+	iFs.Close();
+	}
+
+void CHarvesterMediaIdUtil::ConstructL()
+	{
+	for ( TInt i = 0; i < KMaxDrives; i++ )
+		{
+		iMediaId[i] = 0;
+		}
+	User::LeaveIfError( iFs.Connect() );
+	}
+
+EXPORT_C TInt CHarvesterMediaIdUtil::GetMediaId( const TDesC& aUri, TUint32& aMediaId )
+	{
+    TChar ch = aUri[0];
+    TInt drive( 0 );
+    TInt err = RFs::CharToDrive( ch, drive );
+    if ( err == KErrNone )
+    	{
+    	// return mediaid if already in array
+    	if( iMediaId[drive] > 0 )
+    		{
+    		aMediaId = iMediaId[drive];
+    		return KErrNone;
+    		}
+    	
+    	// resolve mediaid and save into array
+	    err = MdsUtils::GetVolumeInfo( iFs, aUri, iVolumeInfo );
+	    if ( err == KErrNone )
+	    	{
+	    	iMediaId[drive] = iVolumeInfo.iUniqueID;
+	    	aMediaId = iVolumeInfo.iUniqueID;
+	    	return KErrNone;
+	    	}
+    	}
+    return err;
+	}
+
+EXPORT_C TInt CHarvesterMediaIdUtil::GetDriveLetter( TUint32 aMediaId, TChar& aChar )
+	{
+	for ( TInt i = 0; i < KMaxDrives; i++ )
+		{
+		if ( iMediaId[i] == aMediaId )
+			{
+			TInt err = RFs::DriveToChar( i, aChar );
+			return err;
+			}
+		}
+	return KErrNotFound;
+	}
+
+EXPORT_C void CHarvesterMediaIdUtil::RemoveMediaId( TUint32 aMediaId )
+	{
+	for ( TInt i = 0; i < KMaxDrives; i++ )
+		{
+		if ( iMediaId[i] == aMediaId )
+			{
+			iMediaId[i] = 0;
+			break;
+			}
+		}
+	}
+
+EXPORT_C CHarvesterMediaIdUtil& RMediaIdUtil::GetInstanceL()
+	{
+    TMediaIdUtilInfo* data =
+        static_cast<TMediaIdUtilInfo*>( 
+        		UserSvr::DllTls( KHarvesterMediaIdTLSKey ) );
+
+        CHarvesterMediaIdUtil* instance = NULL;
+
+    	if ( data )
+            {
+            instance = data->iMediaIdUtil;
+            data->iRefCount++;
+            }
+    	else
+    		{
+            instance = CHarvesterMediaIdUtil::NewL();
+            CleanupStack::PushL(instance);
+            TMediaIdUtilInfo* tmp = new (ELeave) TMediaIdUtilInfo;
+            tmp->iMediaIdUtil = instance;
+            tmp->iRefCount = 1;
+            UserSvr::DllSetTls( KHarvesterMediaIdTLSKey, tmp );
+            	
+            CleanupStack::Pop(instance);
+            }
+    	
+    	return *instance;
+	}
+
+EXPORT_C void RMediaIdUtil::ReleaseInstance()
+	{
+	TMediaIdUtilInfo* data = static_cast<TMediaIdUtilInfo*> (UserSvr::DllTls(
+			KHarvesterMediaIdTLSKey));
+	if (data)
+		{
+		data->iRefCount--;
+		if (data->iRefCount <= 0)
+			{
+			delete data->iMediaIdUtil;
+
+			delete data;
+			UserSvr::DllFreeTls(KHarvesterMediaIdTLSKey);
+			}
+		}
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/harvesterplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,301 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Base class for harvester plug-ins*
+*/
+
+
+#include <harvesterplugin.h>
+#include <harvesterdata.h>
+#include <mdeconstants.h>
+#include <mdepropertydef.h>
+#include <mdeobjectdef.h>
+#include <mdeobject.h>
+#include "harvesterlog.h"
+#include "harvestercommon.h"
+#include "harvesterblacklist.h"
+#include "mdsutils.h"
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CHarvesterPlugin* CHarvesterPlugin::NewL(const TUid& aUid)
+	{
+	TAny* harvesterPlugin = REComSession::CreateImplementationL(
+			aUid, _FOFF( CHarvesterPlugin, iDtor_ID_Key ) );
+	CHarvesterPlugin* self = reinterpret_cast<CHarvesterPlugin*>(harvesterPlugin);
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterPlugin::ConstructL()
+	{
+	User::LeaveIfError( iFs.Connect() );
+	iState = EHarvesterIdle;
+	CActiveScheduler::Add( this );
+	}
+
+// ---------------------------------------------------------------------------
+// Constructor
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CHarvesterPlugin::CHarvesterPlugin() : 
+	CActive( KHarvesterPriorityHarvestingPlugin ),
+	iState( EHarvesterIdle ),
+	iQueue( NULL ),
+	iBlacklist( NULL ),
+    iDtor_ID_Key( KNullUid ),
+    iOriginPropertyDef( NULL ),
+    iTitlePropertyDef( NULL )
+	{
+	
+	}
+
+// ---------------------------------------------------------------------------
+// ListImplementationsL
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CHarvesterPlugin::ListImplementationsL(
+		RImplInfoPtrArray& aImplInfoArray)
+	{
+	REComSession::ListImplementationsL(
+			KCHarvesterPluginInterfaceUid, aImplInfoArray );
+	}
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CHarvesterPlugin::~CHarvesterPlugin() // destruct - virtual
+	{
+	Cancel();
+	
+	iFs.Close();
+	REComSession::DestroyedImplementation( iDtor_ID_Key );
+	}
+
+// ---------------------------------------------------------------------------
+// AddQueue
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CHarvesterPlugin::SetQueue( RPointerArray<CHarvesterData>& aQueue )
+	{
+	iQueue = &aQueue;
+	}
+
+// ---------------------------------------------------------------------------
+// StartHarvest
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CHarvesterPlugin::StartHarvest()
+	{
+	if( iState == EHarvesterIdle )
+		{
+		SetNextRequest( EHarvesterGathering );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// GetObjectType
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CHarvesterPlugin::GetObjectType( const TDesC& /*aUri*/, TDes& aObjectType )
+	{
+	aObjectType.Zero();
+	}
+
+// ---------------------------------------------------------------------------
+// RunL
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CHarvesterPlugin::RunL()
+    {
+    switch( iState )
+        {
+        case EHarvesterIdle:
+            {
+            }
+            break;
+            
+        case EHarvesterGathering:
+            {
+            if( iQueue->Count() == 0 )
+                {
+                SetNextRequest( EHarvesterIdle );
+                iQueue->Compress();
+                }
+            else
+            	{
+            	CHarvesterData* hd = (*iQueue)[0];
+            	iQueue->Remove( 0 );
+            	const TDesC& uri = hd->Uri();
+            	TUint32 mediaId = hd->MdeObject().MediaId();
+            	
+				if( iBlacklist )
+					{
+					WRITELOG( "CHarvesterPlugin::RunL - Adding URI to blacklist" );
+					TTime modified ( 0 );
+					
+					if( hd->IsBinary() )
+						{
+						TInt err = iFs.Modified( hd->Uri(), modified );
+						if ( err != KErrNone )
+							{
+							modified = 0;
+							}
+						}
+					iBlacklist->AddFile( uri, mediaId, modified );
+					}
+				
+				TRAP_IGNORE( SetDefaultPropertiesL( *hd ) );
+				
+				WRITELOG1("CHarvesterPlugin::RunL - Calling HarvestL for file: %S", &uri);  
+                TRAPD(err, HarvestL( hd ) );
+                
+                if ( iBlacklist )
+                    {
+                    WRITELOG( "CHarvesterPlugin::RunL - Removing URI from blacklist" );
+                    iBlacklist->RemoveFile( uri, mediaId );
+                    }
+                
+                if( err )
+                	{
+                	WRITELOG1("CHarvesterPlugin::RunL - ERROR: harvesting failed: %d", err); 
+                	hd->SetErrorCode( err );
+                	}
+                
+	            hd->PluginObserver()->HarvestingCompleted( hd );
+                SetNextRequest( EHarvesterGathering );
+            	}
+            }
+            break;
+
+        default:
+            break;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// DoCancel
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CHarvesterPlugin::DoCancel()
+    {
+    
+    }
+
+// ---------------------------------------------------------------------------
+// RunError
+// ---------------------------------------------------------------------------
+//
+EXPORT_C  TInt CHarvesterPlugin::RunError( TInt /*aError*/ )
+	{
+	SetNextRequest( EHarvesterGathering );
+	return KErrNone;
+	}
+
+// ---------------------------------------------------------------------------
+// SetNextRequest
+// ---------------------------------------------------------------------------
+//
+void CHarvesterPlugin::SetNextRequest( THarvesterState aState )
+    {
+    if ( ! IsActive() )
+        {
+        iState = aState;
+        SetActive();
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// SetDefaultProperties
+// ---------------------------------------------------------------------------
+//
+void CHarvesterPlugin::SetDefaultPropertiesL(CHarvesterData& aData)
+	{
+	CMdEObject& mdeObject = aData.MdeObject();
+	
+	if( !iOriginPropertyDef )
+		{
+		CMdEObjectDef& objDef = mdeObject.Def();
+		iOriginPropertyDef = &objDef.GetPropertyDefL( MdeConstants::Object::KOriginProperty );
+		}
+
+	CMdEProperty* prop = NULL;
+	mdeObject.Property( *iOriginPropertyDef, prop );
+    if ( prop )
+    	{
+    	TUint8 val = prop->Uint8ValueL();
+    	if ( val == MdeConstants::Object::EOther )
+    		{
+#ifdef _DEBUG
+    		WRITELOG2("CHarvesterPlugin::SetDefaultPropertiesL - URI: %S SET Origin: %d", &aData.Uri(), aData.Origin() );
+#endif
+    		prop->SetUint8ValueL( (TUint8) aData.Origin() );
+    		}
+    	}
+    else
+    	{
+#ifdef _DEBUG
+		WRITELOG2("CHarvesterPlugin::SetDefaultPropertiesL - URI: %S ADD Origin: %d", &aData.Uri(), aData.Origin() );
+#endif
+    	mdeObject.AddUint8PropertyL( *iOriginPropertyDef, (TUint8) aData.Origin() );
+    	}
+    
+	if( !iTitlePropertyDef )
+		{
+		CMdEObjectDef& objDef = mdeObject.Def();
+		iTitlePropertyDef = &objDef.GetPropertyDefL( MdeConstants::Object::KTitleProperty );
+		}
+    
+    prop = NULL;
+    mdeObject.Property( *iTitlePropertyDef, prop );
+    if ( !prop )
+    	{
+    	TPtrC name;
+    	TBool nameFound = MdsUtils::GetName( aData.Uri(), name );
+
+     	if ( nameFound )
+     		{
+     		mdeObject.AddTextPropertyL( *iTitlePropertyDef, name );
+     		}
+    	}
+	}
+
+// ---------------------------------------------------------------------------
+// SetBlacklist
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CHarvesterPlugin::SetBlacklist( CHarvesterBlacklist& aBlacklist )
+	{
+	iBlacklist = &aBlacklist;
+	}
+
+// ---------------------------------------------------------------------------
+// E32Dll
+// ---------------------------------------------------------------------------
+//
+GLDEF_C TInt E32Dll()
+	{
+	return(KErrNone);
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/harvesterpluginfactory.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,353 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester plugin factory
+ *
+*/
+
+
+#include <e32base.h>
+#include <e32std.h>
+#include <apmrec.h>
+#include <harvesterplugin.h>
+#include <mdeobject.h>
+#include <harvesterdata.h>
+
+#include "harvesterpluginfactory.h"
+#include "harvesterplugininfo.h"
+#include "mdsutils.h"
+#include "harvesterlog.h"
+
+// ---------------------------------------------------------------------------
+// Constructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterPluginFactory::CHarvesterPluginFactory() :
+    iBlacklist( NULL )
+	{
+	WRITELOG( "CHarvesterPluginFactory::CHarvesterPluginFactory()" );
+	}
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CHarvesterPluginFactory* CHarvesterPluginFactory::NewL()
+	{
+	WRITELOG( "CHarvesterPluginFactory::NewL()" );
+	CHarvesterPluginFactory* self = new (ELeave) CHarvesterPluginFactory();
+	CleanupStack::PushL ( self);
+	self->ConstructL ();
+	CleanupStack::Pop ( self);
+
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterPluginFactory::~CHarvesterPluginFactory()
+	{
+	WRITELOG( "CHarvesterPluginFactory::~CHarvesterPluginFactory()" );
+	iHarvesterPluginInfoArray.ResetAndDestroy();
+	iHarvesterPluginInfoArray.Close();
+	REComSession::FinalClose();
+	}
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterPluginFactory::ConstructL()
+	{
+	WRITELOG( "CHarvesterPluginFactory::ConstructL()" );
+	SetupHarvesterPluginInfoL();
+	}
+
+// ---------------------------------------------------------------------------
+// GetObjectDef
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CHarvesterPluginFactory::GetObjectDefL( CHarvesterData& aHD, TDes& aObjectDef )
+	{
+	TPtrC extPtr;
+	if( MdsUtils::GetExt( aHD.Uri(), extPtr ) )
+		{
+		RPointerArray<CHarvesterPluginInfo> supportedPlugins;
+		CleanupClosePushL( supportedPlugins );
+		GetSupportedPluginsL( supportedPlugins, extPtr );
+		
+		const TInt sCount = supportedPlugins.Count();
+		if( sCount == 1 )
+			{
+			CHarvesterPluginInfo* info = supportedPlugins[0];
+			if( info->iObjectTypes.Count() == 1 )
+				{
+				aObjectDef.Copy( *(info->iObjectTypes[0]) );
+				aHD.SetHarvesterPluginInfo( info );
+				CleanupStack::PopAndDestroy( &supportedPlugins );
+				return;
+				}
+			}
+		for( TInt i = 0; i < sCount; i++ )
+			{
+			CHarvesterPluginInfo* info = supportedPlugins[i];
+			if ( !(info->iPlugin) )
+				{
+				info->iPlugin = CHarvesterPlugin::NewL( info->iPluginUid );
+				info->iPlugin->SetQueue( info->iQueue );
+				}
+			info->iPlugin->GetObjectType( aHD.Uri(), aObjectDef );
+			if( aObjectDef.Length() > 0 )
+				{
+				aHD.SetHarvesterPluginInfo( info );
+				break;
+				}
+			}
+		CleanupStack::PopAndDestroy( &supportedPlugins );
+		}
+	else
+		{
+		aObjectDef.Zero();
+		}
+	}
+	
+// ---------------------------------------------------------------------------
+// GetMimeType
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CHarvesterPluginFactory::GetMimeType(const TDesC& /*aUri*/, TDes& aMimeType)
+	{
+	_LIT( KJPGMimeType, "image/jpeg" );
+	aMimeType.Copy( KJPGMimeType );
+	}
+
+// ---------------------------------------------------------------------------
+// HarvestL
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt CHarvesterPluginFactory::HarvestL( CHarvesterData* aHD )
+	{
+#ifdef _DEBUG
+	WRITELOG1("CHarvesterPluginFactory::HarvestL - aHD->Uri: %S", &aHD->Uri() );
+#endif
+	CHarvesterPluginInfo* hpi = aHD->HarvesterPluginInfo();
+		
+	if ( hpi )
+		{
+		if ( ! hpi->iPlugin )
+	   		{
+	   		hpi->iPlugin = CHarvesterPlugin::NewL( hpi->iPluginUid );
+	   		hpi->iPlugin->SetQueue( hpi->iQueue );
+	   		hpi->iPlugin->SetBlacklist( *iBlacklist );
+	   		}
+			
+		if( aHD->ObjectType() == EFastHarvest || aHD->Origin() == MdeConstants::Object::ECamera )
+		   	{
+		   	hpi->iQueue.Insert( aHD, 0 );
+		    	}
+	    else
+			{
+			hpi->iQueue.AppendL( aHD );
+			}
+		    
+		hpi->iPlugin->StartHarvest();
+			
+		return KErrNone;
+		}
+		
+	return KErrNotFound;
+	}
+
+// ---------------------------------------------------------------------------
+// GetPluginInfos
+// ---------------------------------------------------------------------------
+//
+EXPORT_C RPointerArray<CHarvesterPluginInfo>& CHarvesterPluginFactory::GetPluginInfos()
+	{
+	return iHarvesterPluginInfoArray;
+	}
+
+// ---------------------------------------------------------------------------
+// SetBlacklist
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CHarvesterPluginFactory::SetBlacklist( CHarvesterBlacklist& aBlacklist )
+	{
+	WRITELOG( "CHarvesterPluginFactory::SetBlacklist()" );
+	iBlacklist = &aBlacklist;
+	
+	TInt count = iHarvesterPluginInfoArray.Count();
+	for ( TInt i = 0; i < count; i++ )
+		{
+		iHarvesterPluginInfoArray[i]->iPlugin->SetBlacklist( *iBlacklist );
+		}
+	
+	}
+
+// ---------------------------------------------------------------------------
+// SetupHarvesterPluginInfoL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterPluginFactory::SetupHarvesterPluginInfoL()
+    {
+    WRITELOG( "CHarvesterPluginFactory::SetupHarvesterPluginInfo()" );
+    
+    RImplInfoPtrArray infoArray;
+    TCleanupItem cleanupItem( MdsUtils::CleanupEComArray, &infoArray );
+    CleanupStack::PushL( cleanupItem );
+ 
+    CHarvesterPlugin::ListImplementationsL( infoArray );
+
+    for ( TInt i = infoArray.Count(); --i >= 0; )
+        {
+        // Parse the MIME types and resolve plug-in's uids from infoArray to iDataTypeArray
+        CImplementationInformation* info = infoArray[i];
+        const TBufC8<KMaxFileName>& type = info->DataType();
+        const TBufC8<KMaxFileName>& opaque = info->OpaqueData();
+        TUid implUID = info->ImplementationUid(); 
+                
+        AddNewPluginL( type, opaque, implUID );   
+        }
+    
+    CleanupStack::PopAndDestroy( &infoArray );
+    }
+
+// ---------------------------------------------------------------------------
+// AddNewPluginL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterPluginFactory::AddNewPluginL( const TDesC8& aType,
+		const TDesC8& aOpaque, TUid aPluginUid )
+    {      
+    WRITELOG( "CHarvesterPluginFactory::AddNewPluginL" );
+
+    CHarvesterPluginInfo* pluginInfo = new (ELeave) CHarvesterPluginInfo;
+    CleanupStack::PushL( pluginInfo );
+
+    // get file extensions
+    TLex8 lex( aOpaque );
+    while ( !lex.Eos() )
+        {
+        /* Tokenizing file extensions using TLex8 */
+        lex.SkipSpaceAndMark();
+
+        TPtrC8 extToken = lex.NextToken();
+
+        HBufC* str = HBufC::NewLC( extToken.Length() );
+        str->Des().Copy( extToken );
+        pluginInfo->iExtensions.AppendL( str );
+        CleanupStack::Pop( str );
+        }
+
+    // get object types
+    TLex8 lexObjectTypes( aType );
+    while ( !lexObjectTypes.Eos() )
+        {
+        /* Tokenizing object types using TLex8 */
+        lexObjectTypes.SkipSpaceAndMark();
+        
+        TPtrC8 objectTypeToken = lexObjectTypes.NextToken();
+
+        HBufC* str = HBufC::NewLC( objectTypeToken.Length() );
+        str->Des().Copy( objectTypeToken );
+        pluginInfo->iObjectTypes.AppendL( str );
+        CleanupStack::Pop( str );
+        }
+    
+    pluginInfo->iPluginUid = aPluginUid;
+    
+    // Load plugin
+    pluginInfo->iPlugin = CHarvesterPlugin::NewL( pluginInfo->iPluginUid );
+    pluginInfo->iPlugin->SetQueue( pluginInfo->iQueue );    
+    
+    iHarvesterPluginInfoArray.AppendL( pluginInfo );
+    CleanupStack::Pop( pluginInfo );
+    }
+
+void CHarvesterPluginFactory::GetSupportedPluginsL(
+		RPointerArray<CHarvesterPluginInfo>& aSupportedPlugins, const TDesC& aExt )
+	{
+	TInt pluginInfoCount = iHarvesterPluginInfoArray.Count();
+	TInt extCount = 0;
+	for ( TInt i = pluginInfoCount; --i >= 0; )
+        {
+        CHarvesterPluginInfo* info = iHarvesterPluginInfoArray[i];
+        
+        extCount = info->iExtensions.Count();
+        for ( TInt k = extCount; --k >= 0; )
+            {
+            TDesC* ext = info->iExtensions[k];
+            
+            // checking against supported plugin file extensions
+            const TInt result = ext->CompareF( aExt );
+            if ( result == 0 )
+                {
+                aSupportedPlugins.AppendL( info );
+                break;
+                }
+            }
+        }	
+	}
+
+EXPORT_C TBool CHarvesterPluginFactory::IsSupportedFileExtension( const TDesC& aFileName )
+	{
+	TPtrC extPtr;
+	if( MdsUtils::GetExt( aFileName, extPtr ) )
+		{
+		TInt pluginInfoCount = iHarvesterPluginInfoArray.Count();
+		TInt extCount = 0;
+		for ( TInt i = pluginInfoCount; --i >= 0; )
+			{
+			CHarvesterPluginInfo* info = iHarvesterPluginInfoArray[i];
+			extCount = info->iExtensions.Count();
+			for ( TInt k = extCount; --k >= 0; )
+				{
+				TDesC* ext = info->iExtensions[k];
+				// checking against supported plugin file extensions
+				TInt result = MdsUtils::Compare( *ext, extPtr );
+				if ( result == 0 )
+					{
+					return ETrue;
+					}
+				}
+			}
+		}
+	return EFalse;
+	}
+
+EXPORT_C TBool CHarvesterPluginFactory::IsContainerFileL( const TDesC& aURI )
+	{
+	TBool isContainerFile = EFalse;
+	TPtrC extPtr;
+	
+	if( MdsUtils::GetExt( aURI, extPtr ) )
+		{
+		RPointerArray<CHarvesterPluginInfo> supportedPlugins;
+		CleanupClosePushL( supportedPlugins );
+		GetSupportedPluginsL( supportedPlugins, extPtr );
+		const TInt sCount = supportedPlugins.Count();
+		for( TInt i = 0; i < sCount; i++ )
+			{
+			CHarvesterPluginInfo* info = supportedPlugins[i];
+			if( info->iObjectTypes.Count() >  1 )
+				{
+				isContainerFile = ETrue;
+				break;
+				}
+			}
+		CleanupStack::PopAndDestroy( &supportedPlugins );
+		}
+	return isContainerFile;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/listener.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,313 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This implements CListener class.
+*
+*/
+
+
+// INCLUDE FILES
+#include "listener.h"
+#include "mpropertyobserver.h"
+#include "harvesterlog.h" // For debugging.
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CListener::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CListener* CListener::NewL( const TUid aPropertyCategory,
+		const TUint aKey )
+    {
+    WRITELOG( "CListener::NewL() - begin" );
+    
+    CListener* self = CListener::NewLC( aPropertyCategory, aKey );
+    CleanupStack::Pop( self );
+    
+    WRITELOG( "CListener::NewL() - end" );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CListener::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CListener* CListener::NewLC( const TUid aPropertyCategory,
+		const TUint aKey )
+    {
+    WRITELOG( "CHarvesterAO::NewLC() - begin" );
+    
+    CListener* self = new ( ELeave ) CListener( aPropertyCategory, aKey );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    
+    WRITELOG( "CListener::NewLC - end" );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CListener::~CListener
+// C++ default destructor
+// -----------------------------------------------------------------------------
+//    
+CListener::~CListener()
+    {
+    WRITELOG( "CListener::~CListener - begin" );
+    
+    Cancel(); // Cancels any existing active object orders for iStatus.
+    
+    iProperty.Close();
+    
+    iArrayForKeyValue.Reset();
+    iArrayForKeyValue.Close();
+    
+    iArrayForKeyAndStatus.Reset();
+    iArrayForKeyAndStatus.Close();
+
+    WRITELOG( "CListener::~CListener - end" );   
+    }
+
+// -----------------------------------------------------------------------------
+// CListener::ObservedKey
+// Returns observed key.
+// -----------------------------------------------------------------------------
+//
+TUint CListener::ObservedKey() const
+    {
+    WRITELOG( "CListener::ObservedKey" );
+    
+    return iKey; 
+    }
+
+// -----------------------------------------------------------------------------
+// CListener::ObservedCategory
+// Returns observed key's Category.
+// -----------------------------------------------------------------------------
+//
+TUid CListener::ObservedCategory() const
+    {
+    WRITELOG( "CListener::ObservedCategory" );
+    
+    return iPropertyCategory; 
+    }
+
+// -----------------------------------------------------------------------------
+// CListener::RegisterNewClientForKeyValueL
+// 
+// -----------------------------------------------------------------------------
+//
+void CListener::RegisterNewClientForKeyValueL( const MKeyObserver* aKeyObserver )
+    {
+    WRITELOG( "CListener::RegisterNewClientForKeyValue" );
+    
+    User::LeaveIfError( iArrayForKeyValue.Append( aKeyObserver ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CListener::RegisterNewClientForKeyAndStatusL
+// 
+// -----------------------------------------------------------------------------
+//
+void CListener::RegisterNewClientForKeyAndStatusL( 
+		const MKeyAndStatusObserver* aKeyAndStatusObserver )
+    {
+    WRITELOG( "CListener::RegisterNewClientForKeyAndStatus" );
+    
+    User::LeaveIfError( iArrayForKeyAndStatus.Append( aKeyAndStatusObserver ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CListener::UnregisterKeyClient
+//
+// -----------------------------------------------------------------------------
+//
+void CListener::UnregisterKeyClient( const MKeyObserver* aKeyObserver )
+    {
+    WRITELOG( "CListener::RemoveClient - begin" ); 
+    
+    const TInt listIndex = iArrayForKeyValue.Find( aKeyObserver );
+    if( listIndex != KErrNotFound )
+    	{
+    	iArrayForKeyValue.Remove( listIndex );
+    	}
+ 
+    WRITELOG( "CListener::RemoveClient - end" );   
+    }
+
+// -----------------------------------------------------------------------------
+// CListener::UnregisterKeyAndStatusClient
+//
+// -----------------------------------------------------------------------------
+//
+void CListener::UnregisterKeyAndStatusClient( const MKeyAndStatusObserver* aKeyAndStatusObserver )
+    {
+    WRITELOG( "CListener::UnregisterKeyAndStatusClient - begin" ); 
+    
+    const TInt listIndex = iArrayForKeyAndStatus.Find( aKeyAndStatusObserver );
+    if( listIndex != KErrNotFound )
+    	{
+    	iArrayForKeyAndStatus.Remove( listIndex );
+    	}
+ 
+    WRITELOG( "CListener::UnregisterKeyAndStatusClient - end" );   
+    }
+
+// -----------------------------------------------------------------------------
+// CListener::CListener
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CListener::CListener( const TUid aPropertyCategory, const TUint aKey ) :
+		CActive( CActive::EPriorityUserInput ),
+		iPropertyCategory( aPropertyCategory ),
+		iKey( aKey )
+ 	{
+ 	// No implementation required.
+ 	}
+
+// -----------------------------------------------------------------------------
+// CListener::ConstructL
+// Construct member variable that is to access the
+// kernel. 
+// -----------------------------------------------------------------------------
+//
+void CListener::ConstructL()
+    {
+    WRITELOG( "CListener::ConstructL - begin" );
+    
+    CActiveScheduler::Add( this );
+    
+	// Attach to key.
+ 	User::LeaveIfError( iProperty.Attach( 
+ 			iPropertyCategory,
+ 			iKey,
+ 			EOwnerThread ) );
+ 	
+ 	// Sets object active.
+	StartListening();
+    
+    WRITELOG( "CListener::ConstructL - end" );
+    }
+
+// -----------------------------------------------------------------------------
+// CListener::RunL
+// This function will be called upon a change in the watched key.
+// From class CActive.
+// -----------------------------------------------------------------------------
+//
+void CListener::RunL()
+    {
+#ifdef _DEBUG
+    WRITELOG1( "CListener::RunL - begin, iStatus: %d",  iStatus.Int() ); 
+#endif
+    
+    if( iStatus.Int() == KErrNone )
+    	{
+    	TInt keyValue( KErrNone );
+    	User::LeaveIfError( iProperty.Get( keyValue ) );
+    	SendNotificationsL( keyValue, iStatus );
+    	}
+    
+    // Start listening again.
+    StartListening();
+    
+    WRITELOG( "CListener::RunL - end" );
+    }
+
+// -----------------------------------------------------------------------------
+// CListener::RunError
+// Standard active object error function. From class CActive.
+// -----------------------------------------------------------------------------
+//
+#ifdef _DEBUG
+TInt CListener::RunError( TInt aError )
+#else
+TInt CListener::RunError( TInt /*aError*/ )
+#endif
+    {
+    WRITELOG1( "CListener::RunError, aError: %d",  aError );
+    
+    Cancel();
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CListener::DoCancel
+// Standard active object cancellation function. From class CActive.
+// -----------------------------------------------------------------------------
+//
+void CListener::DoCancel()
+    {
+    WRITELOG( "CListener::DoCancel" );
+    
+    iProperty.Cancel();	
+    }
+
+// -----------------------------------------------------------------------------
+// CListener::StartListeningL
+// Then start listening of the changes in the key.
+// -----------------------------------------------------------------------------
+//
+void CListener::StartListening()
+    {
+    WRITELOG( "CListener::StartListeningL - begin" ); 
+    
+    if( IsActive() )
+        {
+        return;   
+        }
+
+	iProperty.Subscribe( iStatus );
+	SetActive();
+ 
+   WRITELOG( "CListener::StartListeningL - end" );   
+   }
+
+// -----------------------------------------------------------------------------
+// CListener::SendNotificationsL
+// Send notifications to clients.
+// -----------------------------------------------------------------------------
+//
+void CListener::SendNotificationsL( const TUint aKeyValue,
+		TRequestStatus& aStatus ) const 
+    {
+    WRITELOG( "CListener::SendNotifications - begin" ); 
+    
+    // For value only.
+    for ( TInt i = iArrayForKeyValue.Count(); --i >= 0; ) 
+    	{
+        iArrayForKeyValue[i]->NotifyKeyL(
+        		aKeyValue,
+        		iPropertyCategory,
+        		iKey );
+        }
+    
+    // For status and value.
+    for ( TInt i = iArrayForKeyAndStatus.Count(); --i >= 0; ) 
+    	{
+        iArrayForKeyAndStatus[i]->NotifyKeyAndStatusL( 
+        		aKeyValue,
+        		aStatus,
+        		iPropertyCategory,
+        		iKey );
+        }
+
+    WRITELOG( "CListener::SendNotifications - end" );   
+    }
+
+// End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/mdeobjectwrapper.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,318 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#include "mdeobjectwrapper.h"
+#include "harvesterlog.h"
+#include "mdeobjectdef.h"
+#include "mdepropertydef.h"
+#include "mdeobject.h"
+#include "mdetextproperty.h"
+
+CMdeObjectWrapper::CMdeObjectWrapper()
+    {
+	// No implementation required
+    }
+
+
+CMdeObjectWrapper::~CMdeObjectWrapper()
+    {
+    }
+
+EXPORT_C CMdeObjectWrapper* CMdeObjectWrapper::NewLC()
+    {
+	CMdeObjectWrapper* self = new (ELeave)CMdeObjectWrapper();
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+    }
+
+EXPORT_C CMdeObjectWrapper* CMdeObjectWrapper::NewL()
+    {
+	CMdeObjectWrapper* self=CMdeObjectWrapper::NewLC();
+	CleanupStack::Pop( self ); // self;
+	return self;
+    }
+
+void CMdeObjectWrapper::ConstructL()
+    {
+
+    }
+
+EXPORT_C void CMdeObjectWrapper::HandleObjectPropertyL(CMdEObject& aMdeObject, const TDesC& aPropertyType, TAny* aData, TBool aIsAdd )
+	{
+	CMdEObjectDef& mdoDef = aMdeObject.Def();
+    CMdEPropertyDef& propertyDef = mdoDef.GetPropertyDefL( aPropertyType );
+    
+    HandleObjectPropertyL( aMdeObject, propertyDef, aData, aIsAdd );
+	}
+
+EXPORT_C void CMdeObjectWrapper::HandleObjectPropertyL(CMdEObject& aMdeObject, CMdEPropertyDef& aPropertyDef, TAny* aData, TBool aIsAdd )
+	{
+	if( ! aData )
+		{
+#ifdef _DEBUG
+		WRITELOG1("CMdeObjectWrapper::HandleObjectPropertyL - aData is null for property: %S", &aPropertyDef.Name() );
+#endif
+		return;
+		}
+	
+    TPropertyType pt = aPropertyDef.PropertyType();
+    
+    // check if edit and readonly property then do nothing
+    if( ! aIsAdd )
+    	{
+    	if ( aPropertyDef.ReadOnly() != 0 )
+    		{
+#ifdef _DEBUG
+    		WRITELOG1("CMdeObjectWrapper::HandleObjectPropertyL - property: %S is readonly", &aPropertyDef.Name() );
+#endif
+    		return;
+    		}
+ 
+	    CMdEProperty* property = NULL;
+	    const TInt error = aMdeObject.Property( aPropertyDef, property );
+
+	    if ( error >= KErrNone && property )
+	        {
+	        switch ( pt )
+		        {
+				case EPropertyBool:
+					{
+					TBool* value = static_cast<TBool*>( aData );
+					WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Edit property: %S with value %d", &aPropertyDef.Name(), *value );
+					property->SetBoolValueL( *value );
+					}
+				break;
+				
+				case EPropertyInt8:
+					{
+					TInt8* value = static_cast<TInt8*>( aData );
+					WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Edit property: %S with value %d", &aPropertyDef.Name(), *value );
+					property->SetInt8ValueL( *value );
+					}
+				break;
+				
+				case EPropertyUint8:
+					{
+					TUint8* value = static_cast<TUint8*>( aData );
+					WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Edit property: %S with value %d", &aPropertyDef.Name(), *value );
+					property->SetUint8ValueL( *value );
+					}
+				break;
+				
+				case EPropertyInt16:
+					{
+					TInt16* value = static_cast<TInt16*>( aData );
+					WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Edit property: %S with value %d", &aPropertyDef.Name(), *value );
+					property->SetInt16ValueL( *value );
+					}
+				break;
+				
+				case EPropertyUint16:
+					{
+					TUint16* value = static_cast<TUint16*>( aData );
+					WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Edit property: %S with value %d", &aPropertyDef.Name(), *value );
+					property->SetUint16ValueL( *value );
+					}
+				break;
+				
+				case EPropertyInt32:
+					{
+					TInt32* value = static_cast<TInt32*>( aData );
+					WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Edit property: %S with value %d", &aPropertyDef.Name(), *value );
+					property->SetInt32ValueL( *value );
+					}
+				break;
+				
+				case EPropertyUint32:
+					{
+					TUint32* value = static_cast<TUint32*>( aData );
+					WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Edit property: %S with value %d", &aPropertyDef.Name(), *value );
+					property->SetUint32ValueL( *value );
+					}
+				break;
+				
+				case EPropertyInt64:
+					{
+					TInt64* value = static_cast<TInt64*>( aData );
+					WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Edit property: %S with value %d", &aPropertyDef.Name(), *value );
+					property->SetInt64ValueL( *value );
+					}
+				break;
+				
+				case EPropertyReal32:
+					{
+					TReal32* value = static_cast<TReal32*>( aData );
+					WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Edit property: %S with value %d", &aPropertyDef.Name(), *value );
+					property->SetReal32ValueL( *value );
+					}
+				break;
+				
+				case EPropertyReal64:
+					{
+					TReal64* value = static_cast<TReal64*>( aData );
+					WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Edit property: %S with value %d", &aPropertyDef.Name(), *value );
+					property->SetReal64ValueL( *value );
+					}
+				break;
+				
+				case EPropertyTime:
+					{
+					TTime* value = static_cast<TTime*>( aData );
+#ifdef _DEBUG
+					WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Edit property: %S with value %d", &aPropertyDef.Name(), value->Int64() );
+#endif
+					property->SetTimeValueL( *value );
+					}
+				break;
+				
+				case EPropertyText:
+					{
+					const TDesC16* value = static_cast<const TDesC16*>( aData );
+					if( value->Length() > 0 )
+						{
+						WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Edit property: %S with value %S", &aPropertyDef.Name(), value );
+						property->SetTextValueL( *value );
+						}
+					else
+						{
+#ifdef _DEBUG
+						WRITELOG1("CMdeObjectWrapper::HandleObjectPropertyL - property: %S was empty and not edited", &aPropertyDef.Name() );
+#endif
+						}
+					}
+				break;
+				
+				default:
+				break;
+				}
+	        
+	        return;
+	        }
+    	}
+   
+    switch ( pt )
+        {
+		case EPropertyBool:
+			{
+			TBool* value = static_cast<TBool*>( aData );
+			WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Add property: %S with value %d", &aPropertyDef.Name(), *value );
+			aMdeObject.AddBoolPropertyL( aPropertyDef, *value );
+			}
+		break;
+
+		case EPropertyInt8:
+			{
+			TInt8* value = static_cast<TInt8*>( aData );
+			WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Add property: %S with value %d", &aPropertyDef.Name(), *value );
+			aMdeObject.AddInt8PropertyL( aPropertyDef, *value );
+			}
+		break;
+
+		case EPropertyUint8:
+			{
+			TUint8* value = static_cast<TUint8*>( aData );
+			WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Add property: %S with value %d", &aPropertyDef.Name(), *value );
+			aMdeObject.AddUint8PropertyL( aPropertyDef, *value );
+			}
+		break;
+		
+		case EPropertyInt16:
+			{
+			TInt16* value = static_cast<TInt16*>( aData );
+			WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Add property: %S with value %d", &aPropertyDef.Name(), *value );
+			aMdeObject.AddInt16PropertyL( aPropertyDef, *value );
+			}
+		break;
+		
+		case EPropertyUint16:
+			{
+			TUint16* value = static_cast<TUint16*>( aData );
+			WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Add property: %S with value %d", &aPropertyDef.Name(), *value );
+			aMdeObject.AddUint16PropertyL( aPropertyDef, *value );
+			}
+		break;
+		
+		case EPropertyInt32:
+			{
+			TInt32* value = static_cast<TInt32*>( aData );
+			WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Add property: %S with value %d", &aPropertyDef.Name(), *value );
+			aMdeObject.AddInt32PropertyL( aPropertyDef, *value );
+			}
+		break;
+		
+		case EPropertyUint32:
+			{
+			TUint32* value = static_cast<TUint32*>( aData );
+			WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Add property: %S with value %d", &aPropertyDef.Name(), *value );
+			aMdeObject.AddUint32PropertyL( aPropertyDef, *value );
+			}
+		break;
+		
+		case EPropertyInt64:
+			{
+			TInt64* value = static_cast<TInt64*>( aData );
+			WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Add property: %S with value %d", &aPropertyDef.Name(), *value );
+			aMdeObject.AddInt64PropertyL( aPropertyDef, *value );
+			}
+		break;
+		
+		case EPropertyReal32:
+			{
+			TReal32* value = static_cast<TReal32*>( aData );
+			WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Add property: %S with value %d", &aPropertyDef.Name(), *value );
+			aMdeObject.AddReal32PropertyL( aPropertyDef, *value );
+			}
+		break;
+		
+		case EPropertyReal64:
+			{
+			TReal64* value = static_cast<TReal64*>( aData );
+			WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Add property: %S with value %d", &aPropertyDef.Name(), *value );
+			aMdeObject.AddReal64PropertyL( aPropertyDef, *value );
+			}
+		break;
+		
+		case EPropertyTime:
+			{
+			TTime* value = static_cast<TTime*>( aData );
+			WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Add property: %S with value %d", &aPropertyDef.Name(), value->Int64() );
+			aMdeObject.AddTimePropertyL( aPropertyDef, *value );
+			}
+		break;
+		
+		case EPropertyText:
+			{
+			const TDesC16* value = static_cast<const TDesC16*>( aData );
+			if( value->Length() > 0 )
+				{
+				WRITELOG2("CMdeObjectWrapper::HandleObjectPropertyL - Add property: %S with value %S", &aPropertyDef.Name(), value );
+				aMdeObject.AddTextPropertyL( aPropertyDef, *value );
+				}
+			else
+				{
+#ifdef _DEBUG
+				WRITELOG1("CMdeObjectWrapper::HandleObjectPropertyL - property: %S was empty and not added", &aPropertyDef.Name() );
+#endif
+				}
+			}
+		break;
+		
+		default:
+		break;
+		}
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/placeholderdata.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,162 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Data transfer object for placeholder data
+*
+*/
+
+#include <placeholderdata.h>
+
+// CPlaceholderData implementation
+
+//==========================================================================
+// NewL
+//==========================================================================
+//
+EXPORT_C CPlaceholderData* CPlaceholderData::NewL()
+	{
+	CPlaceholderData* self = new (ELeave) CPlaceholderData;
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+
+	return self;
+	}
+
+//==========================================================================
+// ConstructL
+//==========================================================================
+//
+void CPlaceholderData::ConstructL()
+	{
+	iUri = HBufC::New( 1 );
+	iMediaId = 0;
+	}
+
+//==========================================================================
+// Destructor
+//==========================================================================
+//
+CPlaceholderData::~CPlaceholderData()
+	{
+		delete iUri;
+	}
+
+//==========================================================================
+// Modified
+//==========================================================================
+//
+EXPORT_C TTime CPlaceholderData::Modified()
+	{
+	return iModified;
+	}
+
+//==========================================================================
+// SetModified
+//==========================================================================
+//
+EXPORT_C void CPlaceholderData::SetModified( TTime aModified )
+	{
+	iModified = aModified;
+	}
+
+//==========================================================================
+// Uri
+//==========================================================================
+//
+EXPORT_C TPtr16 CPlaceholderData::Uri()
+	{
+	return iUri->Des();
+	}
+
+//==========================================================================
+// SetUri
+//==========================================================================
+//
+EXPORT_C void CPlaceholderData::SetUri( const TDesC& aUri )
+	{
+	delete iUri;
+	iUri = aUri.Alloc();
+	}
+
+//==========================================================================
+// FileSize
+//==========================================================================
+//
+EXPORT_C TUint32 CPlaceholderData::FileSize()
+	{
+	return iFileSize;
+	}
+
+//==========================================================================
+// SetFileSize
+//==========================================================================
+//
+EXPORT_C void CPlaceholderData::SetFileSize( TUint32 aFileSize )
+	{
+	iFileSize = aFileSize;
+	}
+
+//==========================================================================
+// MediaId
+//==========================================================================
+//
+EXPORT_C TUint CPlaceholderData::MediaId()
+	{
+	return (TUint)iMediaId;
+	}
+
+//==========================================================================
+// SetMediaId
+//==========================================================================
+//
+EXPORT_C void CPlaceholderData::SetMediaId( TUint aMediaId )
+	{
+	iMediaId = aMediaId;
+	}
+
+//==========================================================================
+// PresentState
+//==========================================================================
+//
+EXPORT_C TInt CPlaceholderData::PresentState()
+	{
+	return iPresentState;
+	}
+
+//==========================================================================
+// SetPresentState
+//==========================================================================
+//
+EXPORT_C void CPlaceholderData::SetPresentState( TInt aState )
+	{
+	iPresentState = aState;
+	}
+
+//==========================================================================
+// Preinstalled
+//==========================================================================
+//
+EXPORT_C TInt CPlaceholderData::Preinstalled()
+	{
+	return iPreinstalled;
+	}
+
+//==========================================================================
+// SetPreinstalled
+//==========================================================================
+//
+EXPORT_C void CPlaceholderData::SetPreinstalled( TInt aValue )
+	{
+	iPreinstalled = aValue;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/common/src/propertywatcher.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,221 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This implements CPropertyWatcher class.
+*
+*/
+
+
+// SYSTEM INCLUDE
+#include <e32base.h>
+#include <e32std.h>  // For DLL.
+
+// USER INCLUDE
+#include "propertywatcher.h"
+#include "harvesterlog.h" // For debugging.
+#include "listener.h" 
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// ---------------------------------------------------------------------------
+// CPropertyWatcher::GetInstanceL
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CPropertyWatcher* CPropertyWatcher::GetInstanceL() 
+    {
+    WRITELOG( "CPropertyWatcher::GetInstanceL() - begin" ); 
+  
+    CPropertyWatcher* me = NULL;
+    me = static_cast<CPropertyWatcher*>( Dll::Tls() );
+    if ( !me )
+        {
+        CPropertyWatcher* self = new( ELeave ) CPropertyWatcher();
+        User::LeaveIfError( Dll::SetTls( self ) );
+    
+        WRITELOG( "CPropertyWatcher::GetInstanceL() - end returning self" ); 
+        return self;	
+        }
+    else
+        {
+        WRITELOG( "CPropertyWatcher::GetInstanceL() - end returning me" ); 
+        return me;	
+        }			    
+    }
+
+// ---------------------------------------------------------------------------
+// CPropertyWatcher::Delete
+// ---------------------------------------------------------------------------
+//	
+EXPORT_C void CPropertyWatcher::Delete()
+    {
+    WRITELOG( "CPropertyWatcher::Delete() - begin" ); 
+    
+    CPropertyWatcher *me = NULL;
+    me = static_cast<CPropertyWatcher*>( Dll::Tls() );
+    
+    if ( me )
+        {
+        delete me; 
+        Dll::SetTls( NULL ); // Free TLS.
+        }
+    
+    WRITELOG( "CPropertyWatcher::Delete() - end" ); 
+    }
+
+// ---------------------------------------------------------------------------
+// CPropertyWatcher::ListenKeyChangesL
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CPropertyWatcher::ListenKeyChangesL( 
+		const TUid aPropertyCategory,
+		const TUint aKey,
+		const MKeyObserver* aValueObserver )
+    {
+	WRITELOG( "CPropertyWatcher::ListenKeyChanges() - begin" ); 
+
+	const TInt listenerIndex = FindListener ( aPropertyCategory, aKey ); // Finds listener.
+	if ( listenerIndex >=  0 )
+		{
+		iListenersArray[listenerIndex]->RegisterNewClientForKeyValueL( aValueObserver );
+		return;
+		}
+    
+	// Create new listener.
+	CListener* listener = CListener::NewLC( 
+			 aPropertyCategory,
+			 aKey
+			 ); 
+	 
+	listener->RegisterNewClientForKeyValueL( aValueObserver );
+	
+	// Add creted listener to array.
+	User::LeaveIfError( iListenersArray.Append( listener ) ); // Transfer ownership.
+	
+	CleanupStack::Pop( listener );
+
+	WRITELOG( "CPropertyWatcher::ListenKeyChanges() - end" ); 
+    }
+
+// ---------------------------------------------------------------------------
+// CPropertyWatcher::ListenKeyAndStatusChanges
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CPropertyWatcher::ListenKeyAndStatusChangesL( 
+		const TUid aPropertyCategory,
+		const TUint aKey,
+		const MKeyAndStatusObserver* aStatusObserver )
+    {
+	WRITELOG( "CPropertyWatcher::ListenKeyAndStatusChanges - begin" ); 
+
+	const TInt listenerIndex = FindListener ( aPropertyCategory, aKey ); // Finds listener.
+	if ( listenerIndex >= 0 )
+		{
+		iListenersArray[listenerIndex]->RegisterNewClientForKeyAndStatusL( aStatusObserver );
+		return;
+		}
+    
+	// Create new listener.
+	CListener* listener = CListener::NewLC( 
+			 aPropertyCategory,
+			 aKey
+			 ); 
+	 
+	listener->RegisterNewClientForKeyAndStatusL( aStatusObserver );
+	
+	// Add created listener to array.
+	User::LeaveIfError( iListenersArray.Append( listener ) ); // Transfer ownership.
+	
+	CleanupStack::Pop( listener );
+	
+	WRITELOG( "CPropertyWatcher::ListenKeyChanges() - end" ); 
+    }
+
+// ---------------------------------------------------------------------------
+// CPropertyWatcher::StopListeningKeyChanges
+// ---------------------------------------------------------------------------
+//	
+EXPORT_C void CPropertyWatcher::StopListeningKeyChanges( 
+		const TUid aPropertyCategory,
+		const TUint aKey,
+		const MKeyObserver* aKeyObserver )
+    {
+    WRITELOG( "CPropertyWatcher::StopListeningKeyChangesL() - begin" ); 
+	
+	const TInt listenerIndex = FindListener ( aPropertyCategory, aKey ); // Finds listener.
+	if ( listenerIndex >= 0 )
+		{
+		iListenersArray[listenerIndex]->UnregisterKeyClient( aKeyObserver );
+		}
+	
+	WRITELOG( "CPropertyWatcher::StopListeningKeyChangesL() - end" ); 
+    }
+
+// ---------------------------------------------------------------------------
+// CPropertyWatcher::StopListeningKeyAndStatusChanges
+// ---------------------------------------------------------------------------
+//	
+EXPORT_C void CPropertyWatcher::StopListeningKeyAndStatusChanges( 
+		const TUid aPropertyCategory,
+		const TUint aKey,
+		MKeyAndStatusObserver* aStatusObserver )
+    {
+    WRITELOG( "CPropertyWatcher::StopListeningKeyAndStatusChanges() - begin" ); 
+	
+	const TInt listenerIndex = FindListener ( aPropertyCategory, aKey ); // Finds listener.
+	if ( listenerIndex >= 0 )
+		{
+		iListenersArray[listenerIndex]->UnregisterKeyAndStatusClient( aStatusObserver );
+		}
+	
+	WRITELOG( "CPropertyWatcher::StopListeningKeyAndStatusChanges() - end" ); 
+    }
+
+// ---------------------------------------------------------------------------
+// CPropertyWatcher::~CPropertyWatcher
+// ---------------------------------------------------------------------------
+//	
+CPropertyWatcher::~CPropertyWatcher()
+	{
+	WRITELOG( "CPropertyWatcher::~CPropertyWatcher() - begin" ); 
+	
+	iListenersArray.ResetAndDestroy(); // Clean array and objects.
+	
+	WRITELOG( "CPropertyWatcher::~CPropertyWatcher() - end" ); 
+	}
+
+// ---------------------------------------------------------------------------
+// CPropertyWatcher::FindListener
+// ---------------------------------------------------------------------------
+//	
+TInt CPropertyWatcher::FindListener( const TUid aPropertyCategory, const TUint aKey )	const
+    {
+    WRITELOG( "CPropertyWatcher::FindListener() - begin" ); 
+	
+    TInt listenerIndex ( KErrNotFound );
+    
+    for ( TInt i = iListenersArray.Count(); --i >= 0; )
+    	{
+    	CListener& listenerItem = *iListenersArray[i];
+    	
+    	if ( aKey == listenerItem.ObservedKey() &&
+			aPropertyCategory == listenerItem.ObservedCategory() ) 
+			{
+			listenerIndex =  i; 
+			}
+		}
+	
+	WRITELOG( "CPropertyWatcher::FindListener() - end" ); 
+	return listenerIndex;
+    }
+
+// End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/composerplugininterface/bwincw/composerplugininterfacewinscw.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,7 @@
+EXPORTS
+	??1CComposerPlugin@@UAE@XZ @ 1 NONAME ; CComposerPlugin::~CComposerPlugin(void)
+	?ListImplementationsL@CComposerPlugin@@SAXAAV?$RPointerArray@VCImplementationInformation@@@@@Z @ 2 NONAME ; void CComposerPlugin::ListImplementationsL(class RPointerArray<class CImplementationInformation> &)
+	?NewL@CComposerPlugin@@SAPAV1@ABVTUid@@@Z @ 3 NONAME ; class CComposerPlugin * CComposerPlugin::NewL(class TUid const &)
+	?RemoveSession@CComposerPlugin@@QAEXXZ @ 4 NONAME ; void CComposerPlugin::RemoveSession(void)
+	?SetSession@CComposerPlugin@@QAEXAAVCMdESession@@@Z @ 5 NONAME ; void CComposerPlugin::SetSession(class CMdESession &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/composerplugininterface/eabi/composerplugininterfacearm.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,11 @@
+EXPORTS
+	_ZN15CComposerPlugin10SetSessionER11CMdESession @ 1 NONAME
+	_ZN15CComposerPlugin13RemoveSessionEv @ 2 NONAME
+	_ZN15CComposerPlugin20ListImplementationsLER13RPointerArrayI26CImplementationInformationE @ 3 NONAME
+	_ZN15CComposerPlugin4NewLERK4TUid @ 4 NONAME
+	_ZN15CComposerPluginD0Ev @ 5 NONAME
+	_ZN15CComposerPluginD1Ev @ 6 NONAME
+	_ZN15CComposerPluginD2Ev @ 7 NONAME
+	_ZTI15CComposerPlugin @ 8 NONAME ; #<TI>#
+	_ZTV15CComposerPlugin @ 9 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/composerplugininterface/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+composerplugininterface.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/composerplugininterface/group/composerplugininterface.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        composerplugininterface.dll
+TARGETTYPE    dll
+UID           0x1000008D 0x2000717E
+
+CAPABILITY    CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+SYSTEMINCLUDE /epoc32/include/ecom
+
+SOURCEPATH    ../src
+SOURCE        composerplugin.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       ECOM.LIB
+
+#if defined(WINS)
+    deffile ../bwincw/composerplugininterfacewinscw.def
+#elif defined(ARMCC)
+    deffile ../eabi/composerplugininterfacearm.def
+#endif
+nostrictdef
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/composerplugininterface/src/composerplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,80 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Composer Plug-in ECom interface
+*
+*/
+
+
+#include "composerplugin.h"
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CComposerPlugin* CComposerPlugin::NewL( const TUid& aUid )
+	{
+	TAny* composerPlugin = REComSession::CreateImplementationL(
+			aUid, _FOFF( CComposerPlugin, iDtor_ID_Key ) );
+	return ( reinterpret_cast<CComposerPlugin*>(composerPlugin) );
+	}
+
+// ---------------------------------------------------------------------------
+// ListImplementationsL
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CComposerPlugin::ListImplementationsL( RImplInfoPtrArray& aImplInfoArray )
+	{
+	REComSession::ListImplementationsL(
+			KCComposerPluginInterfaceUid, aImplInfoArray );
+	}
+
+// ---------------------------------------------------------------------------
+// Destructor, virtual
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CComposerPlugin::~CComposerPlugin()
+	{
+	REComSession::DestroyedImplementation( iDtor_ID_Key );
+	}
+
+// ---------------------------------------------------------------------------
+// SetSession
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CComposerPlugin::SetSession( CMdESession& aSession )
+	{
+	iSession = &aSession;
+	
+	SetObservers();
+	}
+
+// ---------------------------------------------------------------------------
+// RemoveSession
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CComposerPlugin::RemoveSession()
+	{
+	RemoveObservers();
+	
+	iSession = NULL;
+	}
+
+// ---------------------------------------------------------------------------
+// E32Dll
+// ---------------------------------------------------------------------------
+//
+GLDEF_C TInt E32Dll()
+	{
+	return KErrNone;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+#include "../composerplugininterface/group/bld.inf"
+#include "../imagecomposer/group/bld.inf"
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/imagecomposer/data/20007180.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// 1CA037F6.RSS
+
+#include "registryinfov2.rh"
+
+// Declares info for one test implementation
+RESOURCE REGISTRY_INFO theInfo
+	{
+  // resource_format_version must always be set as follows
+  resource_format_version = RESOURCE_FORMAT_VERSION_2;
+	
+	// UID for the DLL
+	dll_uid = 0x20007180;
+	// Declare array of interface info
+	interfaces = 
+		{
+		INTERFACE_INFO
+			{
+			// UID of interface that is implemented
+			interface_uid = 0x2000717E;
+			implementations = 
+				{
+				// Info for CComposerImagePlugin
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x20007185;
+					version_no = 1;
+					display_name = "Composer image plugin";
+					default_data = "ComposerImage";
+                              		// We for now use just extension - now way to convert MIME-type to file extensio
+                              		opaque_data = "jpg";
+          rom_only = 0;
+					}
+				};
+			}
+		};
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/imagecomposer/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+composerimageplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/imagecomposer/group/composerimageplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        composerimageplugin.dll
+TARGETTYPE    PLUGIN
+UID           0x10009D8D 0x20007180
+
+CAPABILITY    CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+start RESOURCE ../data/20007180.rss
+target composerimageplugin.rsc
+end
+
+SYSTEMINCLUDE /epoc32/include/ecom
+USERINCLUDE   ../inc
+USERINCLUDE   ../../../common/inc
+USERINCLUDE   ../../../../inc
+
+SOURCEPATH    ../src
+SOURCE        composerimageplugin.cpp
+SOURCE        proxy.cpp
+SOURCE        imagecomposerao.cpp
+SOURCE        locationrelationobserver.cpp 
+SOURCE        imagepresentobserver.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       efsrv.lib
+LIBRARY       composerplugininterface.lib
+LIBRARY       mdeclient.lib
+LIBRARY       harvestercommon.lib
+LIBRARY       mdccommon.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/imagecomposer/inc/composerimageplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,115 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Composer image plug-in
+*
+*/
+
+
+#include <mdeobject.h>
+
+#include "composerplugin.h"
+#include "imagecomposerao.h"
+#include "locationrelationobserver.h"
+#include "imagepresentobserver.h"
+#include "mdeharvestersession.h"
+
+#ifndef __CCOMPOSERIMAGEPLUGIN_H__
+#define __CCOMPOSERIMAGEPLUGIN_H__
+
+/**
+* Composer image plugin.
+* This class implements the composer plugin interface.
+* Actual composing is done in class CComposerImagePluginAO.
+*/
+class CComposerImagePlugin : public CComposerPlugin
+    {
+    friend class CLocationRelationObserver;
+    friend class CImagePresentObserver;
+    
+    public:
+
+        /**
+         * Construction.
+         */
+        static CComposerImagePlugin* NewL();
+
+        /**
+         * Destruction.
+         */
+        virtual ~CComposerImagePlugin();
+
+        /**
+         * Checks if composing is complete.
+         */
+        TBool IsComposingComplete();
+
+    protected:
+
+        /**
+         * Set observers that will be notified of composing events.
+         */
+        void SetObservers();
+
+        /**
+         * Remove observers.
+         */
+        void RemoveObservers();
+
+        /** 
+         * Handle object modifications
+         */
+        void HandleObjectNotification(CMdESession& aSession, 
+				TObserverNotificationType aType,
+				const RArray<TItemId>& aObjectIdArray);
+        
+        void WriteGPSTagsL( TItemId aObjectId, TItemId locationId );
+        
+        void HandlePendingObjects( const RArray<TItemId>& aObjectIdArray );
+        
+    private:
+
+        /**
+         * Private constructor.
+         */    
+        CComposerImagePlugin();
+        
+        /**
+         * 2nd phase construction.
+         */    
+        void ConstructL();
+
+        /**
+         * Private, leaving set observers method that is called by the public version of this method.
+         */
+        void SetObserversL();
+
+    private:
+
+        /**
+         * Pointer to the active object that implements the asyncronous functionality
+         * of this plug-in.
+         */
+        CImageComposerAO* iImageComposerAO;
+
+        /**
+         * Pointer to the observer listening for location relation changes in Mde.
+         */
+        CLocationRelationObserver* iLocationRelationObserver;
+        
+        CImagePresentObserver* iImagePresentObserver;
+        
+        CMdEHarvesterSession* iMdEHarvesterSession;
+    };
+
+#endif // __CCOMPOSERIMAGEPLUGIN_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/imagecomposer/inc/imagecomposerao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,272 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Composer image active object
+*
+*/
+
+
+#include <e32msgqueue.h>
+
+#include "mdeobject.h"
+#include "mdeobjectquery.h"
+#include "harvesterexifutil.h"
+#include "mdeharvestersession.h"
+
+#ifndef __CIMAGECOMPOSERAO_H__
+#define __CIMAGECOMPOSERAO_H__
+
+_LIT( KImageComposerPanic, "CImageComposerAO" );
+
+class CMdERelationQuery;
+
+class CImageComposerAO : public CActive, public MMdEQueryObserver
+    {
+    public:
+    
+        enum TRequestType
+            {
+            ERequestReady = 0,
+            ERequestGetObject,
+            ERequestCompose
+            };
+
+        /**
+        * Construction
+        */
+        static CImageComposerAO* NewL();
+
+        /**
+        * Destruction
+        */
+        virtual ~CImageComposerAO();
+        
+        /**
+         * Adds new item to composing queue.
+         * @param aItems  Items to add to the queue.
+         * @param aForce  Force composing to items in aItems array
+         */
+        void AddToQueue( const RArray<TItemId>& aItems, TBool aForce );
+
+        /**
+         * Checks if composing is completed.
+         * @return ETrue, if complete.
+         */
+        TBool IsComposingComplete();
+
+        /**
+         * Sets mde client session to be used by this composer.
+         * @param aSession  Mde client session.
+         */
+        void SetSession( CMdESession* aSession );
+        
+        /**
+         * Remove MdE client session used by this composer.
+         */
+        void RemoveSession();
+        
+        /**
+         * Writes location data to Exif.
+         * @param aMdeObject  Mde object of the image.
+         * @param aLocationObject  Related mde location object.
+         */
+        void DoWriteExifL( CMdEObject* aMdEObject, CMdEObject* aLocationObject );
+        
+        
+        
+        
+        
+    public: // from MMdEQueryObserver
+
+	    /**
+	     * Callback to handle new results received from a query.
+	     * From MMdEQueryObserver.
+	     */
+        virtual void HandleQueryNewResults( CMdEQuery& aQuery, TInt aFirstNewItemIndex,
+            TInt aNewItemCount );
+
+	    /**
+	     * Callback to handle new results received from a query.
+	     * From MMdEQueryObserver.
+	     */
+        virtual void HandleQueryNewResults( CMdEQuery& aQuery, TInt aNewObjectItemCount, 
+            TInt aNewRelationItemCount, TInt aNewEventItemCount );
+
+	    /**
+	     * Callback to handle all results of a completed query.
+	     * From MMdEQueryObserver.
+	     * @param aQuery  Completed query
+	     * @param aError  Error code, KErrNone on success.
+	     */
+        virtual void HandleQueryCompleted( CMdEQuery& aQuery, TInt aError );
+
+    protected:
+
+    	/**
+    	 * RunL
+    	 * From CActive.
+    	 */
+        virtual void RunL();
+
+    	/**
+    	 * DoCancel
+    	 * From CActive.
+    	 */
+        virtual void DoCancel();
+
+    	/**
+    	 * RunError. Error handler in case RunL() leaves.
+    	 * From CActive.
+    	 * @param aError  Leave code from RunL.
+    	 * @return  Error code. KErrNone if error was handled.
+    	 */
+        virtual TInt RunError( TInt aError );
+
+    private:
+
+        /**
+        * Private constructor
+        */    
+        CImageComposerAO();
+        
+        /**
+        * 2nd phase construction
+        */    
+        void ConstructL(); // second-phase constructor
+        
+        /**
+         * Gets an object from MdE DB.
+         * Leave on queue errors.
+         * Leaves with KErrNotFound, if object is not found.
+         * 
+         * @param Returned value of current composing request's object ID. 
+         *        Value is changed when item is read from composing queue.
+         */
+        void GetObjectFromMdeL(TItemId& aMdEObjectId);
+        
+        /**
+         * Writes (=composes) new metadata to a image file.
+         */
+        void ComposeL();
+        
+        /**
+         * SetNextRequest
+         * Sets next state for this active object's RunL.
+         * @param aNextRequest  State to set.
+         */
+        void SetNextRequest( TRequestType aNextRequest );
+        
+        /**
+         * @brief Starts the write of GPS tags to a image file.
+         * 
+         * Starts a query to search for related location data in mde.
+         * If found, HandleQueryCompleted will start adding found info
+         * to image file.
+         * 
+         * @param aObjectId  Object to whichs add GPS tags.
+         * 
+         * @see HandleQueryCompleted
+         * @see StartWritingGPSTagsL
+         * @see DoWriteExifL
+         */
+        void WriteGPSTagsL( TItemId aObjectId );
+        
+        /**
+         * Checks if given mime type is JPEG image.
+         * @param aMimeType  a mime type string.
+         * @return ETrue if mime type is image/jpeg.
+         */
+        static TBool IsJpeg( const TDesC& aMimeType );
+        
+        
+        /**
+         * Starts writing GPS tags to image file.
+         * @param aQuery  Mde query which contains results for related
+         *                location object query.
+         */
+        void StartWritingGPSTagsL( CMdEQuery& aQuery );
+
+        /**
+         * Converts a TDateTime object's date to a Exif GPS date string.
+         *
+         * @param aTime  TDateTime object to extract the date from.
+         * @param aTgtDes  Target descriptor for the string.
+         */
+        void TimeToGpsDateStringL( TTime aTime, TDes& aTgtDes );
+
+        /**
+         * Converts a TTime object's time to a Exif GPS time string.
+         *
+         * @param aTime  TDateTime object to extract the time from.
+         * @param aTgtDes  Target descriptor for the string.
+         */
+        void TimeToGpsTimeStringL( TDateTime aTime, TDes8& aTgtDes );
+
+
+        /**
+         * CompareItemIds
+         */
+		static TInt CompareTItemIds( const TItemId& aLeft, const TItemId& aRight )
+			{
+			return aLeft - aRight;
+			}
+
+    private:
+
+    	/** Pointer to a mde object */
+        CMdEObject* iMdeObject;
+        
+        /** Pointer to mde session to use */
+        CMdESession* iSession;
+        
+        CMdEHarvesterSession* iMdEHarvesterSession;
+        
+        /** Next state of this active object's RunL() */
+        TRequestType iNextRequest;
+        
+        /** Queue of items to compose */
+        RArray<TItemId> iItemQueue;
+        
+        /** A relation query used to seach for related location objects */
+        CMdERelationQuery* iRelationQuery;
+        
+        /** Mde default namespace. NOT OWN. */
+        CMdENamespaceDef* iDefaultNamespace;
+        
+        /** Image Object Def. NOT OWN. */
+        CMdEObjectDef* iImageObjectDef;
+
+        /** "Base" Object Def. NOT OWN. */
+        CMdEObjectDef* iObjectDef;
+
+        /** Location Object Def. NOT OWN. */
+        CMdEObjectDef* iLocationObjectDef;
+        
+        /**
+         * Array used to skip new coming id after explicit change of
+         * MdE object in composer.
+         */
+        RArray<TItemId> iNextItemsSkip;
+        
+        /**
+         * Array of item id's which will be forced to be composed
+         * No timestamp checking will be done for these objects
+         */
+        RArray<TItemId> iForceObjectIds;
+        
+        CHarvesterExifUtil* iExifUtil;
+        
+        RFs iFs;
+    };
+
+#endif // __CIMAGECOMPOSERAO_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/imagecomposer/inc/imagepresentobserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,144 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  image composer listener for setting pending image objects present
+ *
+*/
+
+
+#ifndef IMAGEPRESENTOBSERVER_H_
+#define IMAGEPRESENTOBSERVER_H_
+
+#include "mdeharvestersession.h"
+
+// forward declarations
+class CMdENamespaceDef;
+class CComposerImagePlugin;
+
+/**
+ *  CImagePresentObserver
+ * 
+ */
+class CImagePresentObserver : public CActive, public MMdEObjectPresentObserver
+	{
+public:
+
+	enum TRequest
+		{
+		ERequestIdle,
+		ERequestWaitPendingCount,
+		ERequestWaitPending,
+		ERequestProcess
+		} 
+	;
+	/**
+	 * Destructor.
+	 */
+	~CImagePresentObserver();
+
+	/**
+	 * Two-phased constructor.
+	 */
+	static CImagePresentObserver* NewL( CMdESession* aSession, CComposerImagePlugin* aComposer, 
+			CMdEHarvesterSession* aMdEHarvesterSession );
+
+    /**
+     * Set next request (=state) of this active object.
+     * @param aRequest  State enumeration.
+     */       
+    void SetNextRequest( TRequest aRequest );	
+	
+    /**
+     * Standard RunL-method.
+     * From CActive.
+     */       
+    void RunL();
+
+    /**
+     * From CActive.
+     */       
+    void DoCancel();
+
+    /**
+     * From CActive.
+     * @param aError  Leave error code.
+     * @return Always KErrNone.
+     */       
+    TInt RunError( TInt aError );
+		
+	
+protected:
+
+	/**
+	 * Called to notify the observer that objects has been set
+	 * to present or not present state in the metadata engine database.
+	 *
+	 * @param aSession session
+	 * @param aPresent state: ETrue - present or  EFales - not present
+	 * @param aObjectIdArray object IDs which are set to present state
+	 */
+	void HandleObjectPresentNotification(CMdESession& aSession, 
+			TBool aPresent, const RArray<TItemId>& aObjectIdArray);
+	
+private:
+
+	/**
+	 * Constructor for performing 1st stage construction
+	 */
+	CImagePresentObserver();
+
+	/**
+	 * EPOC default constructor for performing 2nd stage construction
+	 */
+	void ConstructL( CMdESession* aSession, CComposerImagePlugin* aComposer, CMdEHarvesterSession* aMdEHarvesterSession );
+	
+	void CleanUp();
+	
+
+	
+private:
+
+	/**
+	 * Pointer to default Mde namespace.
+	 */
+	CMdENamespaceDef* iDefaultNamespace;
+
+	/**
+	 * Pointer to Mde session.
+	 */
+	CMdESession* iSession;
+	
+	CMdEHarvesterSession* iMdEHarvesterSession;
+
+	/**
+	 * Pointer to a composer.
+	 */
+	CComposerImagePlugin* iComposer;	
+	
+	TGetPendingPgckWrapper* iPendingPckWrapper;
+	
+	RArray<TItemId> iPresentObjectIds;
+	RArray<TItemId> iPendingObjectIds;
+	RArray<TItemId> iComposeObjectIds;
+	
+    TRequest iNextRequest;
+    
+    TInt iPendingCount;
+    
+    CMdCSerializationBuffer* iPendingBuffer;
+    TBool iStarted;
+	
+	};
+
+#endif /*IMAGEPRESENTOBSERVER_H_*/
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/imagecomposer/inc/locationrelationobserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Image Composer's listener for changes in db location relations
+ *
+*/
+
+
+#ifndef LOCATIONRELATIONOBSERVER_H
+#define LOCATIONRELATIONOBSERVER_H
+
+#include "mdeharvestersession.h"
+#include "mdequery.h"
+
+// forward declarations
+class CMdENamespaceDef;
+class CComposerImagePlugin;
+
+/**
+ *  CLocationRelationObserver
+ * 
+ */
+class CLocationRelationObserver : public CBase, public MMdERelationObserver, public MMdEQueryObserver
+	{
+public:
+	// Constructors and destructor
+
+	/**
+	 * Destructor.
+	 */
+	~CLocationRelationObserver();
+
+	/**
+	 * Two-phased constructor.
+	 */
+	static CLocationRelationObserver* NewL( CMdESession* aSession, CComposerImagePlugin* aComposer );
+
+protected:
+
+	/**
+	 * Called to notify the observer that new relations has been
+	 * added/modified/removed in the metadata engine database.
+	 *
+	 * @param aSession session
+	 * @param aType defines if relation was added/modified/remove
+	 * @param aRelationIdArray IDs of relations
+	 */
+
+	void HandleRelationNotification(CMdESession& aSession,
+			TObserverNotificationType aType,
+			const RArray<TItemId>& aRelationIdArray);
+	
+    /**
+     * Called to notify the observer that new results have been received 
+     * in the query.
+     * From MMdEQueryObserver.
+     *
+     * @param aQuery              Query instance that received new results.
+     * @param aFirstNewItemIndex  Index of the first new item that was added
+     *                            to the result item array.
+     * @param aNewItemCount       Number of items added to the result item 
+     *                            array.
+     *
+     * No implementation needed!
+     */
+    void HandleQueryNewResults( CMdEQuery& /*aQuery*/,
+        TInt /*aFirstNewItemIndex*/, TInt /*aNewItemCount*/ );
+
+    /**
+     * Handle query results.
+     * From MMdEQueryObserver.
+     *
+     * @param aQuery   Query instance that received new results.
+     * @param aError   Error code.
+     */
+    void HandleQueryCompleted( CMdEQuery& aQuery, TInt aError );
+	
+private:
+
+	/**
+	 * Constructor for performing 1st stage construction
+	 */
+	CLocationRelationObserver();
+
+	/**
+	 * EPOC default constructor for performing 2nd stage construction
+	 */
+	void ConstructL( CMdESession* aSession, CComposerImagePlugin* aComposer );
+	
+    /**
+     * Query the related image object ids from MdE database.
+     * @param aObjectIdArray  Array of Location object database ids.
+     */
+    void QueryRelationItemsL( );
+	
+	
+private:
+
+	/**
+	 * Pointer to default Mde namespace.
+	 */
+	CMdENamespaceDef* iDefaultNamespace;
+
+	/**
+	 * Pointer to Mde session.
+	 */
+	CMdESession* iSession;
+
+	/**
+	 * Pointer to a composer.
+	 */
+	CComposerImagePlugin* iComposer;	
+	
+    /**
+     * MdE query object to use for querying relations
+     */
+    CMdERelationQuery* iQuery;	
+    
+    TBool iQueryStarted;
+    
+    RArray<TItemId> iRelationIdArray;
+
+	};
+
+#endif // LOCATIONRELATIONOBSERVER_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/imagecomposer/src/composerimageplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,217 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Composer Image Plug-in
+*
+*/
+
+
+#include <e32base.h>
+
+#include "mdelogiccondition.h"
+#include "mdenamespacedef.h"
+#include "composerimageplugin.h"
+#include "harvesterlog.h"
+#include "mdeconstants.h"
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CComposerImagePlugin* CComposerImagePlugin::NewL()
+    {
+    WRITELOG( "CComposerImagePlugin::NewL()" );
+
+    CComposerImagePlugin* self = new (ELeave) CComposerImagePlugin();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// ~CComposerImagePlugin
+// ---------------------------------------------------------------------------
+//
+CComposerImagePlugin::~CComposerImagePlugin() // destruct
+    {   
+    WRITELOG( "CComposerImagePlugin::~CComposerImagePlugin()" );
+
+    delete iImageComposerAO;
+    delete iLocationRelationObserver;
+    delete iImagePresentObserver;
+    
+    delete iMdEHarvesterSession;
+    }
+
+// ---------------------------------------------------------------------------
+// CComposerImagePlugin
+// ---------------------------------------------------------------------------
+//
+CComposerImagePlugin::CComposerImagePlugin() : // first-phase C++ constructor
+    iImageComposerAO( NULL ), iLocationRelationObserver( NULL ),
+    iImagePresentObserver( NULL ), iMdEHarvesterSession( NULL )
+    {
+    WRITELOG( "CComposerImagePlugin::CComposerImagePlugin()" );
+    }
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CComposerImagePlugin::ConstructL() // second-phase constructor
+    {
+    WRITELOG( "CComposerImagePlugin::ConstructL()" );
+    iImageComposerAO = CImageComposerAO::NewL();
+    iLocationRelationObserver = NULL;
+
+    }
+
+// ---------------------------------------------------------------------------
+// SetObservers
+// ---------------------------------------------------------------------------
+//
+void CComposerImagePlugin::SetObservers()
+    {
+    WRITELOG( "CComposerImagePlugin::SetObservers()" );
+
+    TRAPD( err, SetObserversL() );
+    if ( err != KErrNone )
+        {
+        WRITELOG1( "CComposerImagePlugin::SetObservers Error: %d", err );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// SetObserversL
+// ---------------------------------------------------------------------------
+//
+void CComposerImagePlugin::SetObserversL()
+    {
+    if ( iSession )
+        {
+        iImageComposerAO->SetSession( iSession );
+
+        CMdELogicCondition* condition = CMdELogicCondition::NewL( ELogicConditionOperatorAnd );
+        CleanupStack::PushL( condition );
+
+        CMdENamespaceDef& defaultNamespace = iSession->GetDefaultNamespaceDefL();
+        CMdEObjectDef& imageDef = 
+        	defaultNamespace.GetObjectDefL( MdeConstants::Image::KImageObject );
+        condition->AddObjectConditionL( imageDef );
+
+        CleanupStack::Pop( condition );
+        iSession->AddObjectObserverL( *this, condition, ENotifyModify, &defaultNamespace );
+
+        if ( iLocationRelationObserver )
+            {
+            delete iLocationRelationObserver;
+            iLocationRelationObserver = NULL;
+            }
+
+        iLocationRelationObserver = CLocationRelationObserver::NewL( iSession, this );
+        
+        if ( iMdEHarvesterSession )
+        	{
+        	delete iMdEHarvesterSession;
+        	iMdEHarvesterSession = NULL;
+        	}
+        iMdEHarvesterSession = CMdEHarvesterSession::NewL ( *iSession );
+
+        if ( iImagePresentObserver )
+        	{
+        	delete iImagePresentObserver;
+        	iImagePresentObserver = NULL;
+        	}
+        
+        iImagePresentObserver = CImagePresentObserver::NewL( iSession, this, iMdEHarvesterSession );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// RemoveObservers
+// ---------------------------------------------------------------------------
+//
+void CComposerImagePlugin::RemoveObservers()
+    {
+    if ( iSession )
+        {
+        TRAP_IGNORE( iSession->RemoveObjectObserverL( *this ) );
+
+        iImageComposerAO->RemoveSession();
+        
+        delete iImagePresentObserver;
+        iImagePresentObserver = NULL;
+        
+        delete iLocationRelationObserver;
+        iLocationRelationObserver = NULL;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// IsComposingComplete
+// ---------------------------------------------------------------------------
+//
+TBool CComposerImagePlugin::IsComposingComplete()
+    {
+    WRITELOG( "CComposerImagePlugin::IsComposingComplete()" );
+    
+    return iImageComposerAO->IsComposingComplete();
+    }
+
+/** 
+ * Handle object modifications
+ */
+void CComposerImagePlugin::HandleObjectNotification(CMdESession& /*aSession*/, 
+		TObserverNotificationType aType,
+		const RArray<TItemId>& aObjectIdArray)
+	{
+    if ( aType == ENotifyModify )
+    	{
+#ifdef _DEBUG
+        WRITELOG1( "CComposerImagePlugin::HandleObjectNotification() objects: %d", aObjectIdArray.Count() );
+#endif
+        TRAP_IGNORE( iMdEHarvesterSession->SetPendingL( aObjectIdArray ) );
+    	iImageComposerAO->AddToQueue( aObjectIdArray, EFalse );
+    	}
+	}
+
+void CComposerImagePlugin::WriteGPSTagsL( TItemId aObjectId, TItemId locationId )
+	{
+	RArray<TItemId> objectId;
+	CleanupClosePushL( objectId );
+	objectId.Append( aObjectId );
+	iMdEHarvesterSession->SetPendingL( objectId );
+	
+	CMdENamespaceDef& defaultNamespace = iSession->GetDefaultNamespaceDefL();
+    CMdEObjectDef& imageObjDef = defaultNamespace.GetObjectDefL( MdeConstants::Image::KImageObject );
+    CMdEObjectDef& locationObjDef = defaultNamespace.GetObjectDefL( MdeConstants::Location::KLocationObject );
+	CMdEObject* object = iSession->GetObjectL( aObjectId, imageObjDef );
+	CMdEObject* location = iSession->GetObjectL( locationId, locationObjDef );
+	
+	if( object && location )
+		{
+		TRAPD( err, iImageComposerAO->DoWriteExifL( object, location ) );
+	
+		if ( err == KErrNone )
+			{
+			iMdEHarvesterSession->ResetPendingL( objectId );
+			}
+		}
+	CleanupStack::PopAndDestroy( &objectId );
+	}
+
+void CComposerImagePlugin::HandlePendingObjects( const RArray<TItemId>& aObjectIdArray )
+	{
+	iImageComposerAO->AddToQueue( aObjectIdArray, ETrue);
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/imagecomposer/src/imagecomposerao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,903 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Composer image active object
+*
+*/
+
+
+#include <e32base.h>
+#include <e32debug.h>
+
+#include <mderelation.h>
+#include <mderelationquery.h>
+#include <mdelogiccondition.h>
+
+#include "mdeharvestersession.h"
+#include "mdeproperty.h"
+#include "mdenamespacedef.h"
+#include "imagecomposerao.h"
+#include "harvesterlog.h"
+#include "mdeconstants.h"
+#include "mdsutils.h"
+#include "mderelationcondition.h"
+#include "mdeobjectdef.h"
+#include "harvestercommon.h"
+
+using namespace MdeConstants;
+
+_LIT( KJpegMimeType, "image/jpeg" );
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CImageComposerAO* CImageComposerAO::NewL()
+    {
+    WRITELOG( "CImageComposerAO::NewL()" );
+
+    CImageComposerAO* self = new (ELeave) CImageComposerAO();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// ~CImageComposerAO
+// ---------------------------------------------------------------------------
+//
+CImageComposerAO::~CImageComposerAO() // destruct
+    {   
+    WRITELOG( "CImageComposerAO::~CImageComposerAO()" );
+    
+    Cancel();
+    
+    iItemQueue.Close();
+    
+    iForceObjectIds.Close();
+    iNextItemsSkip.Close();
+    
+    if ( iMdeObject )
+        {
+        delete iMdeObject;
+        }
+    if ( iExifUtil )
+    	{
+    	delete iExifUtil;
+    	}
+
+    delete iRelationQuery;
+    iFs.Close();
+    
+    delete iMdEHarvesterSession;
+    }
+
+// ---------------------------------------------------------------------------
+// CComposerImagePlugin
+// ---------------------------------------------------------------------------
+//
+CImageComposerAO::CImageComposerAO() : // first-phase C++ constructor
+		CActive( KHarvesterPriorityComposerPlugin )
+    {
+    WRITELOG( "CImageComposerAO::CImageComposerAO()" );
+    }
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::ConstructL() // second-phase constructor
+    {
+    WRITELOG( "CImageComposerAO::ConstructL()" );
+    iMdeObject = NULL;
+    iNextRequest = ERequestReady;
+    iDefaultNamespace = NULL;
+    iImageObjectDef = NULL;
+    iObjectDef = NULL;
+    iLocationObjectDef = NULL;
+
+    CActiveScheduler::Add( this );
+    
+    iExifUtil = CHarvesterExifUtil::NewL();
+    User::LeaveIfError( iFs.Connect() );
+    }
+    
+// ---------------------------------------------------------------------------
+// DoCancel
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::DoCancel()
+    {
+    WRITELOG( "CImageComposerAO::DoCancel()" );
+    }
+    
+// ---------------------------------------------------------------------------
+// AddToQueue
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::AddToQueue( const RArray<TItemId>& aItems, TBool aForce )
+    {
+    WRITELOG( "CImageComposerAO::AddToQueue()" );
+    
+    // check if we should skip some items
+    const TInt itemsCount = aItems.Count();
+    for ( TInt i = 0; i < itemsCount; ++i )
+        {
+        TInt res = iNextItemsSkip.FindInOrder( aItems[i],
+        		TLinearOrder<TItemId>( CImageComposerAO::CompareTItemIds ) );
+        if ( res != KErrNotFound && res >= 0 )
+            {
+            RArray<TItemId> objectId;
+            objectId.Append( aItems[i] );
+            TRAP_IGNORE( iMdEHarvesterSession->ResetPendingL( objectId ) );
+            iNextItemsSkip.Remove( res );
+            
+            if( iNextItemsSkip.Count() == 0 )
+            	{
+            	iNextItemsSkip.Compress();
+            	}
+            objectId.Close();
+            }
+        else
+            {
+            iItemQueue.Append( aItems[i] );
+            if ( aForce )
+            	{
+            	iForceObjectIds.Append( aItems[i] );
+            	}
+            }
+        }
+    if ( iNextRequest == ERequestReady )
+    	{
+    	SetNextRequest( ERequestGetObject );
+    	}
+    }
+    
+// ---------------------------------------------------------------------------
+// IsComposingComplete()
+// ---------------------------------------------------------------------------
+//
+TBool CImageComposerAO::IsComposingComplete()
+    {
+    WRITELOG( "CImageComposerAO::IsComposingComplete()" );
+    return iNextRequest == ERequestReady;
+    }
+
+// ---------------------------------------------------------------------------
+// SetSession
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::SetSession( CMdESession* aSession )
+    {
+    WRITELOG( "CImageComposerAO::SetSession()" );
+    iSession = aSession;
+    iExifUtil->SetSession(iSession);
+    if( iSession )
+    	{
+    	iDefaultNamespace = NULL;
+    	TRAP_IGNORE( iDefaultNamespace = &iSession->GetDefaultNamespaceDefL() );
+    	
+    	TRAP_IGNORE( iImageObjectDef = &iDefaultNamespace->GetObjectDefL( 
+    			Image::KImageObject ) );
+    	TRAP_IGNORE( iObjectDef = &iDefaultNamespace->GetObjectDefL( 
+    			Object::KBaseObject ) );
+    	TRAP_IGNORE( iLocationObjectDef = &iDefaultNamespace->GetObjectDefL( 
+    			Location::KLocationObject ) );
+    	
+    	
+		iMdEHarvesterSession = NULL;
+    	TRAP_IGNORE( iMdEHarvesterSession 
+    	        = CMdEHarvesterSession::NewL ( *iSession ));
+    	}
+    }
+
+// ---------------------------------------------------------------------------
+// RemoveSession
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::RemoveSession()
+    {
+    iSession = NULL;
+    iExifUtil->SetSession( NULL );
+
+    delete iMdEHarvesterSession;
+    iMdEHarvesterSession = NULL;
+    
+    iDefaultNamespace = NULL;
+    iImageObjectDef = NULL;
+    iObjectDef = NULL;
+    iLocationObjectDef = NULL;
+    }
+
+// ---------------------------------------------------------------------------
+// RunL
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::RunL()
+    {
+    WRITELOG( "CImageComposerAO::RunL()" );
+    User::LeaveIfError( iStatus.Int() );
+    
+    if ( !iDefaultNamespace && iSession )
+        {
+        iDefaultNamespace = &iSession->GetDefaultNamespaceDefL();
+        }
+    
+    switch ( iNextRequest )
+        {
+        case ERequestGetObject:
+            {
+            if( iItemQueue.Count() <= 0 )
+            	{
+            	SetNextRequest( ERequestReady );
+            	}
+            else
+            	{
+            	TItemId mdeObjectId = KNoId;
+	            TRAPD( err, GetObjectFromMdeL( mdeObjectId ) );
+	            
+	            if ( err == KErrNone )
+	                {    
+	                SetNextRequest( ERequestCompose );
+	                }
+	            // if object does not exists, find next
+	            else if ( err == KErrNotFound || err == KErrAbort )
+	                 {
+	                 if ( err == KErrAbort && mdeObjectId != KNoId )
+	                	 {
+		                 RArray<TItemId> objectId;
+		                 objectId.Append( mdeObjectId );
+		                 CleanupClosePushL( objectId );
+		                 iMdEHarvesterSession->ResetPendingL( objectId );
+		                 CleanupStack::PopAndDestroy( &objectId );
+	                	 }
+	                 SetNextRequest( ERequestGetObject );
+	                 }
+	                 
+	            // something goes really wrong
+	            else
+	                 {
+	                 User::Leave( err );
+	                 }
+            	}
+
+            }
+            break;
+            
+        case ERequestCompose:
+            {
+            ComposeL();
+
+            if ( iMdeObject )
+                {
+                RArray<TItemId> objectId;
+                objectId.Append( iMdeObject->Id() );
+                TRAP_IGNORE( iMdEHarvesterSession->ResetPendingL( objectId ) );
+                objectId.Close();
+
+                delete iMdeObject;
+                iMdeObject = NULL;
+                }
+            }
+            break;
+            
+        case ERequestReady:
+            {
+            }
+            break;
+            
+        default:
+            {
+            User::Leave( KErrUnknown );
+            }
+            break;
+        }
+    }
+    
+// ---------------------------------------------------------------------------
+// RunError
+// ---------------------------------------------------------------------------
+//
+#ifdef _DEBUG
+TInt CImageComposerAO::RunError( TInt aError )
+#else
+TInt CImageComposerAO::RunError( TInt )
+#endif
+    {
+    WRITELOG1( "CImageComposerAO::RunError() - error code: %d", aError );
+    if ( iMdeObject && iSession )
+    	{
+    	TRAP_IGNORE( iSession->CancelObjectL( *iMdeObject ) );
+    	}
+    SetNextRequest( ERequestGetObject );
+
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// GetObjectFromMde
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::GetObjectFromMdeL(TItemId& aMdEObjectId)
+    {
+#ifdef _DEBUG
+    _LIT( KPanicCategoryNsd, "NSD=NULL" );
+    _LIT( KPanicCategoryOd,  "OD=NULL" );
+    _LIT( KPanicCategoryId,  "ID=NULL" );
+    _LIT( KPanicCategoryLd,  "LD=NULL" );
+    __ASSERT_DEBUG( iDefaultNamespace, User::Panic( KPanicCategoryNsd, KErrBadHandle ) );
+    __ASSERT_DEBUG( iObjectDef, User::Panic( KPanicCategoryOd,  KErrBadHandle ) );
+    __ASSERT_DEBUG( iImageObjectDef, User::Panic( KPanicCategoryId,  KErrBadHandle ) );
+    __ASSERT_DEBUG( iLocationObjectDef, User::Panic( KPanicCategoryLd,  KErrBadHandle ) );
+#endif    
+    
+    WRITELOG( "CImageComposerAO::GetObjectFromMdeL() - start" );
+    
+    if ( !iSession )
+    	{
+    	WRITELOG( "CImageComposerAO::GetObjectFromMdeL() - iSession is NULL" );
+    	User::Leave( KErrSessionClosed );
+    	}
+
+    TItemId objectId = KNoId;
+    
+    // get the object id from queue
+    if( iItemQueue.Count() > 0 )
+    	{
+    	objectId = iItemQueue[0];
+    	aMdEObjectId = objectId;
+    	iItemQueue.Remove( 0 );
+    	}
+    else
+    	{
+    	iItemQueue.Compress();
+    	}
+    
+    // get object from db (NULL if not found)
+    CMdEObject* mdeObject = iSession->GetObjectL( objectId, *iImageObjectDef );
+
+    CleanupStack::PushL( mdeObject );
+    
+    if ( !mdeObject )
+        {
+        WRITELOG1( "CImageComposerAO::GetObjectFromMdeL() - could not find object id %d", objectId );
+        User::Leave( KErrNotFound );
+        }
+
+    TInt force;
+    force = iForceObjectIds.Find( objectId );
+    if ( force != KErrNotFound )
+    	{
+    	iForceObjectIds.Remove( force );
+    	
+    	if( iForceObjectIds.Count() == 0 )
+    		{
+    		iForceObjectIds.Compress();
+    		}
+    	}
+    else
+    	{
+	    // check if file's and object's last modified dates are equal
+	    CMdEPropertyDef& lastModifiedDatePropDef = mdeObject->Def().GetPropertyDefL( 
+	    		Object::KLastModifiedDateProperty );
+	    CMdEProperty* lastModifiedDateProp = NULL;
+	    mdeObject->Property( lastModifiedDatePropDef, lastModifiedDateProp );
+	    if( lastModifiedDateProp )
+	    	{
+	    	TTime time = ((CMdETimeProperty*)lastModifiedDateProp)->Value();
+	
+	    	TEntry entry;
+	    	TInt error = iFs.Entry( mdeObject->Uri(), entry );
+	
+	    	if( error != KErrNone || entry.iModified == time )
+	    		{
+	    		User::Leave( KErrAbort );
+	    		}
+	    	}
+	    else
+	    	{
+	    	User::Leave( KErrNotFound );
+	    	}   
+    	}
+    
+    CleanupStack::Pop( mdeObject );
+    iMdeObject = mdeObject;
+    
+    WRITELOG( "CImageComposerAO::GetObjectFromMdeL() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// ComposeL
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::ComposeL()
+    {
+#ifdef _DEBUG
+    _LIT( KPanicCategoryNsd, "NSD=NULL" );
+    _LIT( KPanicCategoryOd,  "OD=NULL" );
+    _LIT( KPanicCategoryId,  "ID=NULL" );
+    _LIT( KPanicCategoryLd,  "LD=NULL" );
+    __ASSERT_DEBUG( iDefaultNamespace, User::Panic( KPanicCategoryNsd, KErrBadHandle ) );
+    __ASSERT_DEBUG( iObjectDef, User::Panic( KPanicCategoryOd,  KErrBadHandle ) );
+    __ASSERT_DEBUG( iImageObjectDef, User::Panic( KPanicCategoryId,  KErrBadHandle ) );
+    __ASSERT_DEBUG( iLocationObjectDef, User::Panic( KPanicCategoryLd,  KErrBadHandle ) );
+#endif    
+    
+#ifdef _DEBUG    
+    WRITELOG( "CImageComposerAO::ComposeL()" );
+    WRITELOG1( "CImageComposerAO::ComposeL() - Compose Start Object ID: %d", iMdeObject->Id() );
+#endif
+
+    if ( !iSession )
+    	{
+    	WRITELOG( "CImageComposerAO::ComposeL() - iSession is NULL!" );
+    	User::Leave( KErrSessionClosed );
+    	}
+
+    // 1. Read Exif image from the file to a buffer...
+    RFile64 file;
+    CleanupClosePushL( file );
+    WRITELOG( "CImageComposerAO::ComposeL() - open file for reading" );
+    User::LeaveIfError( file.Open( iFs, iMdeObject->Uri(), EFileRead ) );
+
+    TInt64 dataSize = 0;
+    file.Size( dataSize );
+    HBufC8* exif = HBufC8::NewL( dataSize );
+    CleanupStack::PushL( exif );
+    TPtr8 exifPtr = exif->Des();
+    User::LeaveIfError( file.Read( exifPtr ) );
+    CleanupStack::Pop( exif );             // exif needs to be popped and pushed again
+    CleanupStack::PopAndDestroy( &file );  // to get file out of CleanupStack
+    CleanupStack::PushL( exif );
+    
+    HBufC8* modifiedExif = NULL;
+    
+    iExifUtil->ComposeExifDataL(*iMdeObject, exifPtr, modifiedExif);
+   
+    // modifiedExif is NULL if no changes were made
+    if ( modifiedExif )
+        {
+        CleanupStack::PushL( modifiedExif );
+        
+        if ( !iMdeObject->OpenForModifications() )
+            {
+            // we have get version
+            const TItemId objectId = iMdeObject->Id();
+            delete iMdeObject;
+            iMdeObject = NULL;
+            iMdeObject = iSession->OpenObjectL( objectId, *iImageObjectDef );
+            if ( !iMdeObject )
+                {
+                User::Leave( KErrAccessDenied );
+                }
+            }
+
+    	// set position to begin of file
+        WRITELOG( "CImageComposerAO::ComposeL() - open file for writing" );
+        User::LeaveIfError( file.Open( iFs, iMdeObject->Uri(), EFileWrite ) );
+        CleanupClosePushL( file );
+
+        TInt64 pos = 0;
+        WRITELOG( "CImageComposerAO::ComposeL() - seek to position 0" );
+        User::LeaveIfError( file.Seek( ESeekStart, pos ) );
+
+        WRITELOG( "CImageComposerAO::ComposeL() - write buffer (exif) to file" );
+        User::LeaveIfError( file.Write( modifiedExif->Des(), modifiedExif->Des().Length() ) );
+
+        CleanupStack::PopAndDestroy( 2, modifiedExif ); // file, modifiedExif
+        TEntry fileEntry;
+        iFs.Entry( iMdeObject->Uri(), fileEntry );
+
+        WRITELOG( "CImageComposerAO::ComposeL() - store Size and LastModifiedDate properties to MDE" );
+        CMdEPropertyDef& sizePropDef = iImageObjectDef->GetPropertyDefL( Object::KSizeProperty );
+            {
+            CMdEProperty* sizeProp = NULL;
+            iMdeObject->Property( sizePropDef, sizeProp, 0 );
+
+            if ( sizeProp )
+                {
+                sizeProp->SetUint32ValueL( fileEntry.iSize );
+                }
+            else
+                {
+                iMdeObject->AddUint32PropertyL( sizePropDef, fileEntry.iSize );
+                }
+            }
+
+        CMdEPropertyDef& lastModDatePropDef = iImageObjectDef->GetPropertyDefL(
+        		Object::KLastModifiedDateProperty );
+            {
+            CMdEProperty* lastModDateProp = NULL;
+            iMdeObject->Property( lastModDatePropDef, lastModDateProp, 0 );
+
+            if ( lastModDateProp )
+                {
+                lastModDateProp->SetTimeValueL( fileEntry.iModified );
+                }
+            else
+                {
+                iMdeObject->AddTimePropertyL( lastModDatePropDef, fileEntry.iModified );
+                }
+            }
+        iSession->CommitObjectL( *iMdeObject );
+        iNextItemsSkip.InsertInOrder( iMdeObject->Id(),
+        		TLinearOrder<TItemId>( CImageComposerAO::CompareTItemIds ) );
+        }
+
+    CleanupStack::PopAndDestroy( exif );
+
+    WRITELOG( "CImageComposerAO::ComposeL() - Start writing GPS tags" );
+    
+    WriteGPSTagsL( iMdeObject->Id() );
+
+#ifdef _DEBUG
+    WRITELOG1( "CImageComposerAO::ComposeL() - Compose End Object ID: %d", iMdeObject->Id() );
+#endif
+    }
+
+// ---------------------------------------------------------------------------
+// WriteGPSTagsL
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::WriteGPSTagsL( TItemId aObjectId )
+    {
+#ifdef _DEBUG
+    _LIT( KPanicCategoryNsd, "NSD=NULL" );
+    _LIT( KPanicCategoryOd,  "OD=NULL" );
+    _LIT( KPanicCategoryId,  "ID=NULL" );
+    _LIT( KPanicCategoryLd,  "LD=NULL" );
+    __ASSERT_DEBUG( iDefaultNamespace, User::Panic( KPanicCategoryNsd, KErrBadHandle ) );
+    __ASSERT_DEBUG( iObjectDef, User::Panic( KPanicCategoryOd,  KErrBadHandle ) );
+    __ASSERT_DEBUG( iImageObjectDef, User::Panic( KPanicCategoryId,  KErrBadHandle ) );
+    __ASSERT_DEBUG( iLocationObjectDef, User::Panic( KPanicCategoryLd,  KErrBadHandle ) );
+#endif    
+    
+    delete iRelationQuery;
+    iRelationQuery = NULL;
+    
+    if ( !iSession )
+    	{
+    	User::Leave( KErrSessionClosed );
+    	}
+    
+    iRelationQuery = iSession->NewRelationQueryL( *iDefaultNamespace, this );
+    
+    iRelationQuery->SetResultMode( EQueryResultModeItem );
+    iRelationQuery->Conditions().SetOperator( ELogicConditionOperatorAnd );
+    
+    CMdERelationCondition& filterCond = iRelationQuery->Conditions().
+    		AddRelationConditionL( ERelationConditionSideRight );
+    
+    // Left object in relation must have this ID.
+    filterCond.LeftL().AddObjectConditionL( aObjectId );
+    
+    // Right object in relation must be a location object.
+    filterCond.RightL().AddObjectConditionL( *iLocationObjectDef );
+    
+    iRelationQuery->FindL( 1, 1 ); // results to a call to HandleQueryCompleted()
+    }
+    
+// ---------------------------------------------------------------------------
+// SetNextRequest
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::SetNextRequest( TRequestType aNextRequest )
+    {
+    iNextRequest = aNextRequest;
+    
+    if ( !IsActive() )
+        {
+        iStatus = KRequestPending;
+        SetActive();
+        TRequestStatus* ptrStatus = &iStatus;
+        User::RequestComplete( ptrStatus, KErrNone );
+        }
+    }
+    
+// ---------------------------------------------------------------------------
+// HandleQueryNewResults
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::HandleQueryNewResults( CMdEQuery& /*aQuery*/,
+	TInt /*aFirstNewItemIndex*/, TInt /*aNewItemCount*/ )
+    {
+    }
+    
+// ---------------------------------------------------------------------------
+// HandleQueryNewResults
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::HandleQueryNewResults( CMdEQuery& /*aQuery*/,
+	TInt /*aNewObjectItemCount*/, TInt /*aNewRelationItemCount*/,
+	TInt /*aNewEventItemCount*/ )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// HandleQueryCompleted
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::HandleQueryCompleted( CMdEQuery& aQuery, TInt aError )
+    {
+    if ( aError != KErrNone )
+    	{
+    	WRITELOG1( "CImageComposerAO::HandleQueryCompleted() - query error: %d", aError );
+    	SetNextRequest( ERequestGetObject );
+    	return;
+    	}
+    if ( aQuery.Count() == 0 )
+        {
+        WRITELOG( "CImageComposerAO::HandleQueryCompleted() - no gps items found" );
+        SetNextRequest( ERequestGetObject );
+        return;
+        }
+
+#ifdef _DEBUG        
+    TRAPD( error, StartWritingGPSTagsL( aQuery ) );
+    WRITELOG1( "CImageComposerAO::HandleQueryCompleted() - error code from StartWritingGPSTagsL: %d", error );
+#else
+    TRAP_IGNORE( StartWritingGPSTagsL( aQuery ) );
+#endif
+    
+    SetNextRequest( ERequestGetObject );
+    }
+
+// ---------------------------------------------------------------------------
+// StartWritingGPSTagsL
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::StartWritingGPSTagsL( CMdEQuery& aQuery )
+    {
+#ifdef _DEBUG
+    _LIT( KPanicCategoryNsd, "NSD=NULL" );
+    _LIT( KPanicCategoryOd,  "OD=NULL" );
+    _LIT( KPanicCategoryId,  "ID=NULL" );
+    _LIT( KPanicCategoryLd,  "LD=NULL" );
+    __ASSERT_DEBUG( iDefaultNamespace, User::Panic( KPanicCategoryNsd, KErrBadHandle ) );
+    __ASSERT_DEBUG( iObjectDef, User::Panic( KPanicCategoryOd,  KErrBadHandle ) );
+    __ASSERT_DEBUG( iImageObjectDef, User::Panic( KPanicCategoryId,  KErrBadHandle ) );
+    __ASSERT_DEBUG( iLocationObjectDef, User::Panic( KPanicCategoryLd,  KErrBadHandle ) );
+#endif    
+    
+    if ( !iSession )
+    	{
+    	WRITELOG( "CImageComposerAO::StartWritingGPSTagsL - iSession is NULL!" );
+    	User::Leave( KErrSessionClosed );
+    	}
+    
+    CMdERelation& result = static_cast<CMdERelation&>( aQuery.ResultItem( 0 ) );
+    TItemId rightId = result.RightObjectId();
+    CMdEObject* location = iSession->GetObjectL( rightId, *iLocationObjectDef );
+    CleanupStack::PushL( location );
+    
+    TItemId leftId = result.LeftObjectId();
+    CMdEObject* mdeObject = iSession->GetObjectL( leftId, *iObjectDef );
+    CleanupStack::PushL( mdeObject );
+    
+    DoWriteExifL( mdeObject, location );
+    
+    CleanupStack::PopAndDestroy( mdeObject );
+    CleanupStack::PopAndDestroy( location );
+    }
+
+
+// ---------------------------------------------------------------------------
+// DoWriteExifL
+// ---------------------------------------------------------------------------
+//
+void CImageComposerAO::DoWriteExifL( CMdEObject* aMdEObject, CMdEObject* aLocationObject )
+    {
+#ifdef _DEBUG
+    _LIT( KPanicCategoryNsd, "NSD=NULL" );
+    _LIT( KPanicCategoryOd,  "OD=NULL" );
+    _LIT( KPanicCategoryId,  "ID=NULL" );
+    _LIT( KPanicCategoryLd,  "LD=NULL" );
+    __ASSERT_DEBUG( iDefaultNamespace, User::Panic( KPanicCategoryNsd, KErrBadHandle ) );
+    __ASSERT_DEBUG( iObjectDef, User::Panic( KPanicCategoryOd,  KErrBadHandle ) );
+    __ASSERT_DEBUG( iImageObjectDef, User::Panic( KPanicCategoryId,  KErrBadHandle ) );
+    __ASSERT_DEBUG( iLocationObjectDef, User::Panic( KPanicCategoryLd,  KErrBadHandle ) );
+#endif
+    
+    WRITELOG( "CImageComposerAO::DoWriteExifL()" );
+    if ( !aMdEObject || !aLocationObject )
+        {
+        WRITELOG( "CImageComposerAO::DoWriteExifL() - null parameter(s)!" );
+        User::Leave( KErrArgument );
+        }
+
+    CMdEProperty* itemTypeProperty = NULL;
+    CMdEProperty* latitudeProperty = NULL;
+    CMdEProperty* longitudeProperty = NULL;
+    CMdEProperty* altitudeProperty = NULL;
+    CMdEProperty* qualityProperty = NULL;
+
+    aMdEObject->Property( iObjectDef->GetPropertyDefL(
+    		Object::KItemTypeProperty ), itemTypeProperty, 0 );
+    aLocationObject->Property( iLocationObjectDef->GetPropertyDefL(
+    		Location::KLatitudeProperty ), latitudeProperty, 0 );
+    aLocationObject->Property( iLocationObjectDef->GetPropertyDefL(
+    		Location::KLongitudeProperty ), longitudeProperty, 0 );
+    aLocationObject->Property( iLocationObjectDef->GetPropertyDefL(
+    		Location::KAltitudeProperty ), altitudeProperty, 0 );
+    aLocationObject->Property( iLocationObjectDef->GetPropertyDefL(
+    		Location::KQualityProperty ), qualityProperty, 0 );
+
+    if ( !itemTypeProperty )
+        {
+        WRITELOG( "CImageComposerAO::DoWriteExifL() - NULL item type property!" );
+        User::Leave( KErrBadHandle );
+        }
+    const TDesC& uri = aMdEObject->Uri();
+
+    const TDesC& mimeType = itemTypeProperty->TextValueL();
+
+    if ( !IsJpeg( const_cast<TDesC&>(mimeType) ) )
+        {
+        WRITELOG( "CImageComposerAO::DoWriteExifL() - object mimetype is not image/jpeg!" );
+        User::Leave( KErrNotSupported );
+        }
+
+    // Check whether the file is open
+    TBool isOpen( EFalse );
+    iFs.IsFileOpen( uri, isOpen );
+    if ( isOpen )
+        {
+        WRITELOG( "CImageComposerAO::DoWriteExifL() - file handle is open!" );
+        User::Leave( KErrInUse );
+        }
+
+    TInt64 imageFileSize = 0;
+    RFile64 file;
+    User::LeaveIfError( file.Open( iFs, uri, EFileRead ) );
+    CleanupClosePushL( file );
+
+    User::LeaveIfError( file.Size( imageFileSize ) );
+    HBufC8* imageData = HBufC8::NewL( imageFileSize );
+    CleanupStack::PushL( imageData );
+    TPtr8 myImagePtr = imageData->Des();
+
+    WRITELOG( "CImageComposerAO::DoWriteExifL() - reading IMAGE file" );
+    const TInt readError = file.Read( myImagePtr ) ;
+    if ( readError != KErrNone )
+        {
+        WRITELOG( "CImageComposerAO::DoWriteExifL() - error while reading image file!" );
+        User::Leave( KErrGeneral );
+        }
+
+    WRITELOG( "CImageComposerAO::DoWriteExifL() - reading IMAGE file - DONE! - closing file" );
+    CleanupStack::Pop( imageData );
+    CleanupStack::PopAndDestroy( &file );
+    CleanupStack::PushL( imageData );
+
+    HBufC8* modifiedExif = NULL;
+    iExifUtil->ComposeLocationL( aLocationObject, myImagePtr, modifiedExif );
+
+    // write the EXIF data to the image
+
+    if ( modifiedExif )
+        {
+        CleanupStack::PushL( modifiedExif );
+
+        CMdEObject* mdeObject = iSession->OpenObjectL( aMdEObject->Id(), 
+        		*iImageObjectDef );
+        if ( !mdeObject )
+            {
+            User::Leave( KErrAccessDenied );
+            }
+        CleanupStack::PushL( mdeObject );
+
+        User::LeaveIfError( file.Open( iFs, mdeObject->Uri(), EFileWrite ) );
+        CleanupClosePushL( file );
+
+        // set position to begin of file
+        TInt64 pos = 0;
+        User::LeaveIfError( file.Seek( ESeekStart, pos ) );
+
+        User::LeaveIfError( file.Write( modifiedExif->Des(), modifiedExif->Des().Length() ) );
+
+        CleanupStack::PopAndDestroy( &file );
+        TEntry fileEntry;
+        iFs.Entry( mdeObject->Uri(), fileEntry );
+
+        CMdEPropertyDef& sizePropDef = iImageObjectDef->GetPropertyDefL( Object::KSizeProperty );
+        CMdEProperty* sizeProp = NULL;
+        mdeObject->Property( sizePropDef, sizeProp, 0 );
+
+        if ( sizeProp )
+            {
+            sizeProp->SetUint32ValueL( fileEntry.iSize );
+            }
+        else
+            {
+            mdeObject->AddUint32PropertyL( sizePropDef, fileEntry.iSize );
+            }
+
+        CMdEPropertyDef& lastModDatePropDef = iImageObjectDef->GetPropertyDefL(
+        		Object::KLastModifiedDateProperty );
+        CMdEProperty* lastModDateProp = NULL;
+        mdeObject->Property( lastModDatePropDef, lastModDateProp, 0 );
+
+        if ( lastModDateProp )
+            {
+            lastModDateProp->SetTimeValueL( fileEntry.iModified );
+            }
+        else
+            {
+            mdeObject->AddTimePropertyL( lastModDatePropDef, fileEntry.iModified );
+            }
+
+        iSession->CommitObjectL( *mdeObject );
+        iNextItemsSkip.InsertInOrder( mdeObject->Id(),
+        		TLinearOrder<TItemId>( CImageComposerAO::CompareTItemIds ) );
+        CleanupStack::PopAndDestroy( mdeObject );
+        CleanupStack::PopAndDestroy( modifiedExif );
+        }
+
+    // remove empty (=unneeded) location objects
+    if ( !latitudeProperty && !longitudeProperty && !altitudeProperty ) // && !satellitesProperty ) // check these first...
+        {
+        // get the rest of the properties
+        CMdEProperty* cellIdProperty = NULL;
+        CMdEProperty* countryCodeProperty = NULL;
+        CMdEProperty* networkCodeProperty = NULL;
+        CMdEProperty* locationAreaCodeProperty = NULL;
+        CMdEProperty* speedProperty = NULL;
+        CMdEProperty* directionProperty = NULL;
+        CMdEProperty* qualityProperty = NULL;
+
+        aLocationObject->Property( iLocationObjectDef->GetPropertyDefL(
+        		Location::KCellIdProperty ), cellIdProperty, 0 );
+        aLocationObject->Property( iLocationObjectDef->GetPropertyDefL(
+        		Location::KCountryCodeProperty ), countryCodeProperty, 0 );
+        aLocationObject->Property( iLocationObjectDef->GetPropertyDefL(
+        		Location::KNetworkCodeProperty ), networkCodeProperty, 0 );
+        aLocationObject->Property( iLocationObjectDef->GetPropertyDefL(
+        		Location::KLocationAreaCodeProperty ), locationAreaCodeProperty, 0 );
+        aLocationObject->Property( iLocationObjectDef->GetPropertyDefL(
+        		Location::KSpeedProperty ), speedProperty, 0 );
+        aLocationObject->Property( iLocationObjectDef->GetPropertyDefL(
+        		Location::KDirectionProperty ), directionProperty, 0 );
+        aLocationObject->Property( iLocationObjectDef->GetPropertyDefL(
+        		Location::KQualityProperty ), qualityProperty, 0 );
+
+        // if object doesn't contain any properties, remove it
+        if ( !cellIdProperty && !countryCodeProperty && !networkCodeProperty
+            && !locationAreaCodeProperty && !speedProperty && !directionProperty && !qualityProperty )
+            {
+            iSession->RemoveObjectL( aLocationObject->Id(), iDefaultNamespace );
+            }
+        }
+    
+    CleanupStack::PopAndDestroy( imageData );
+
+    }
+
+// ---------------------------------------------------------------------------
+// IsJpeg
+// ---------------------------------------------------------------------------
+//
+TBool CImageComposerAO::IsJpeg( const TDesC& aMimeType )
+    {
+    WRITELOG( "CImageComposerAO::IsJpeg()" );
+
+    if ( MdsUtils::Compare( KJpegMimeType, aMimeType ) == 0 )
+        {
+        WRITELOG( "CImageComposerAO::IsJpeg() - image is Jpeg" );
+        return ETrue;        
+        }
+
+    return EFalse;
+    }
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/imagecomposer/src/imagepresentobserver.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,235 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  image composer listener for setting pending image objects present
+*
+*/
+
+
+#include "imagepresentobserver.h"
+#include "harvesterlog.h"
+#include "mdeconstants.h"
+#include "composerimageplugin.h"
+#include "mdcserializationbuffer.h"
+#include "mdsutils.h"
+#include "harvestercommon.h"
+
+using namespace MdeConstants;
+
+const TInt KBatchSize = 100;
+
+CImagePresentObserver::CImagePresentObserver() : 
+		CActive( KHarvesterPriorityComposerPlugin ),
+		iDefaultNamespace( NULL ),
+		iSession( NULL ),
+		iMdEHarvesterSession( NULL ),
+		iComposer( NULL ),
+		iPendingPckWrapper( NULL ),
+		iNextRequest( ERequestIdle ),
+		iPendingCount( 0 ),
+		iPendingBuffer( NULL ),
+		iStarted( EFalse )
+	{
+	// No implementation required
+	}
+
+CImagePresentObserver::~CImagePresentObserver()
+	{
+	if( iSession )
+	    {
+	    TRAP_IGNORE( iSession->RemoveObjectPresentObserverL( *this ) );
+	    }
+	
+	CleanUp();
+	}
+
+CImagePresentObserver* CImagePresentObserver::NewL( CMdESession* aSession, CComposerImagePlugin* aComposer, 
+		CMdEHarvesterSession* aMdEHarvesterSession )
+	{
+	WRITELOG( "CImagePresentObserver::NewL start" );
+	CImagePresentObserver* self = new (ELeave)CImagePresentObserver();
+	CleanupStack::PushL(self);
+	self->ConstructL( aSession, aComposer, aMdEHarvesterSession );
+	CleanupStack::Pop( self ); 
+	WRITELOG( "CImagePresentObserver::NewL end" );
+	return self;
+	}
+
+void CImagePresentObserver::ConstructL( CMdESession* aSession, CComposerImagePlugin* aComposer, 
+		CMdEHarvesterSession* aMdEHarvesterSession )
+	{
+    WRITELOG( "CImagePresentObserver::ConstructL start" );
+    User::LeaveIfNull( iSession = aSession );
+    User::LeaveIfNull( iComposer = aComposer );
+    
+    iDefaultNamespace = &iSession->GetDefaultNamespaceDefL();
+
+    iSession->AddObjectPresentObserverL( *this );
+    iMdEHarvesterSession = aMdEHarvesterSession;
+    
+    iStarted = EFalse;
+    
+    CActiveScheduler::Add( this );
+
+    WRITELOG( "CImagePresentObserver::ConstructL end" );
+	}
+
+
+void CImagePresentObserver::HandleObjectPresentNotification(CMdESession& /*aSession*/, 
+		TBool aPresent, const RArray<TItemId>& aObjectIdArray)
+	{
+	if ( aPresent )
+		{
+		if ( !iStarted )
+			{
+			CMdEObjectDef* imageObjDef = NULL;
+			TRAP_IGNORE( imageObjDef = &iDefaultNamespace->GetObjectDefL( 
+					MdeConstants::Image::KImageObject ));
+			
+			iPendingCount = iMdEHarvesterSession->GetPendingCount( imageObjDef );
+			SetNextRequest( ERequestWaitPendingCount );
+			iStarted = ETrue;
+			}
+		TInt count = aObjectIdArray.Count();
+		for (TInt i = 0; i < count; i++ )
+			{
+			iPresentObjectIds.Append( aObjectIdArray[i] );
+			}
+		}
+	}
+
+
+void CImagePresentObserver::RunL()
+	{
+	switch ( iNextRequest )
+		{
+		case ERequestIdle:
+			{
+			if( iComposeObjectIds.Count() > 0 )
+				{
+				iComposer->HandlePendingObjects( iComposeObjectIds );			
+				iComposeObjectIds.Reset();
+				}
+			iPendingObjectIds.Reset();
+			iPresentObjectIds.Reset();
+			delete iPendingBuffer;
+			iPendingBuffer = NULL;
+			iStarted = EFalse;
+			break;
+			}
+		
+		case ERequestWaitPendingCount:
+			{
+			if ( iPendingCount > 0 )
+				{
+				CMdEObjectDef& imageObjDef = iDefaultNamespace->GetObjectDefL( 
+						MdeConstants::Image::KImageObject );
+
+				iPendingBuffer = CMdCSerializationBuffer::NewL( iPendingCount * 
+						sizeof(TItemId) );
+			
+				const TInt result = iMdEHarvesterSession->GetPending( &imageObjDef,
+						iPendingCount, *iPendingBuffer );
+				
+				SetNextRequest( ERequestWaitPending );
+				}
+			else
+				{
+				SetNextRequest( ERequestIdle );
+				}
+			break;
+			}
+			
+		case ERequestWaitPending:
+			{
+			if ( iPendingBuffer )
+				{
+				DeserializeArrayL( iPendingBuffer->Buffer(), iPendingObjectIds );
+				}
+			
+			SetNextRequest( ERequestProcess );
+			break;
+			}
+		
+		case ERequestProcess:
+			{
+			if( iPresentObjectIds.Count() > 0 && iPendingObjectIds.Count() > 0 )
+				{
+				TItemId itemId = iPresentObjectIds[0];
+				iPresentObjectIds.Remove( 0 );
+				
+				TInt found = iPendingObjectIds.Find( itemId );
+				if ( found != KErrNotFound )
+					{
+					iPendingObjectIds.Remove( found );
+					iComposeObjectIds.Append( itemId );
+					}
+				}
+			else 
+				{
+				SetNextRequest( ERequestIdle );
+				
+				iPendingObjectIds.Compress();
+				iPresentObjectIds.Compress();
+				
+				break;
+				}
+
+			if( iComposeObjectIds.Count() > KBatchSize )
+				{
+				iComposer->HandlePendingObjects( iComposeObjectIds );		
+				iComposeObjectIds.Reset();
+				}
+			
+			SetNextRequest ( ERequestProcess );	
+			break;
+			}
+		}
+	}
+
+void CImagePresentObserver::DoCancel()
+	{
+	}
+
+TInt CImagePresentObserver::RunError( TInt /*aError*/ )
+	{
+	return KErrNone;
+	}
+
+// ---------------------------------------------------------------------------
+// SetNextRequest
+// ---------------------------------------------------------------------------
+//
+void CImagePresentObserver::SetNextRequest( TRequest aRequest )
+    {
+    iNextRequest = aRequest;
+            
+    if ( !IsActive() )
+        {
+        iStatus = KRequestPending;
+        SetActive();
+        TRequestStatus* ptrStatus = &iStatus;
+        User::RequestComplete( ptrStatus, KErrNone );
+        }
+    }
+
+
+void CImagePresentObserver::CleanUp()
+	{
+	iPendingObjectIds.Close();
+	iPresentObjectIds.Close();
+	iComposeObjectIds.Close();
+	delete iPendingBuffer;
+	iPendingBuffer = NULL;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/imagecomposer/src/locationrelationobserver.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,210 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Image Composer's listener for changes in db location relations
+*
+*/
+
+
+#include <mdelogiccondition.h>
+#include <mdequery.h>
+
+#include "locationrelationobserver.h"
+#include "harvesterlog.h"
+#include "mdeconstants.h"
+#include "composerimageplugin.h"
+
+using namespace MdeConstants;
+
+
+CLocationRelationObserver::CLocationRelationObserver() :
+    iDefaultNamespace( NULL ), iSession( NULL ), iComposer( NULL ),
+    iQuery( NULL ), iQueryStarted( EFalse )
+	{
+	// No implementation required
+	}
+
+CLocationRelationObserver::~CLocationRelationObserver()
+	{
+	iRelationIdArray.Close();
+	
+	if( iSession )
+		{
+		TRAP_IGNORE( iSession->RemoveRelationObserverL( *this ) );
+		}
+	}
+
+CLocationRelationObserver* CLocationRelationObserver::NewL( CMdESession* aSession, CComposerImagePlugin* aComposer )
+	{
+	WRITELOG( "CLocationRelationObserver::NewL start" );
+	CLocationRelationObserver* self = new (ELeave)CLocationRelationObserver();
+	CleanupStack::PushL(self);
+	self->ConstructL( aSession, aComposer );
+	CleanupStack::Pop(); // self;
+	WRITELOG( "CLocationRelationObserver::NewL end" );
+	return self;
+	}
+
+void CLocationRelationObserver::ConstructL( CMdESession* aSession, CComposerImagePlugin* aComposer )
+	{
+    WRITELOG( "CLocationRelationObserver::ConstructL start" );
+    User::LeaveIfNull( iSession = aSession );
+    User::LeaveIfNull( iComposer = aComposer );
+    
+    iDefaultNamespace = &iSession->GetDefaultNamespaceDefL();
+
+    // start listening to mde location object changes
+    CMdELogicCondition* condition = CMdELogicCondition::NewL( ELogicConditionOperatorAnd );
+    CleanupStack::PushL( condition );
+    
+    CMdERelationDef& relationDef = iDefaultNamespace->GetRelationDefL( 
+    		MdeConstants::Relations::KContainsLocation );
+    
+    // Create relation condition
+    CMdERelationCondition* relCond = &condition->AddRelationConditionL( relationDef );
+
+    // Remove relation condition from logic condition
+    condition->Remove( 0 );
+    // and delete logic condition
+    CleanupStack::PopAndDestroy( condition );
+
+    iSession->AddRelationObserverL( *this, relCond, ENotifyAdd | ENotifyModify | ENotifyRemove, iDefaultNamespace );
+
+    WRITELOG( "CLocationRelationObserver::ConstructL end" );
+	}
+
+void CLocationRelationObserver::HandleRelationNotification(
+		CMdESession& /*aSession*/, TObserverNotificationType aType,
+		const RArray<TItemId>& aRelationIdArray)
+	{
+#ifdef _DEBUG
+	WRITELOG2( "CLocationRelationObserver::HandleObjectModified() objects: %d, aType: %d", aRelationIdArray.Count(), aType );
+#endif
+	
+	if ( aType == ENotifyAdd || aType == ENotifyModify )
+    	{
+#ifdef _DEBUG
+        WRITELOG1( "CLocationRelationObserver::HandleObjectModified() objects: %d", aRelationIdArray.Count() );
+#endif
+
+        // get images 
+        const TInt count = aRelationIdArray.Count();
+        for( TInt i = 0; i < count; i ++ )
+        	{
+        	iRelationIdArray.Append( aRelationIdArray[i] );
+        	}
+        
+        if( !iQueryStarted )
+        	{
+        	TRAP_IGNORE( QueryRelationItemsL() );
+        	}
+    	}	
+	}
+
+// ---------------------------------------------------------------------------
+// QueryImageObjectIdsL
+// ---------------------------------------------------------------------------
+//
+void CLocationRelationObserver::QueryRelationItemsL()
+    {
+    if ( iRelationIdArray.Count() > 0 )
+    	{
+    	iQueryStarted = ETrue;
+    	}
+    else
+    	{ 
+    	iQueryStarted = EFalse;
+    	return;
+    	}
+    	
+    delete iQuery; iQuery = NULL;
+    
+    RArray<TItemId> objectIds;
+    CleanupClosePushL( objectIds );
+    const TInt count = iRelationIdArray.Count();
+    for ( TInt i = 0; i < count; i++ )
+    	{
+    	objectIds.Append( iRelationIdArray[i] );
+    	}
+    iRelationIdArray.Reset();
+    
+    iQuery = iSession->NewRelationQueryL( *iDefaultNamespace, this );
+    User::LeaveIfNull( iQuery );
+
+    iQuery->SetResultMode( EQueryResultModeId );
+    iQuery->Conditions().SetOperator( ELogicConditionOperatorAnd );
+    
+    // Relation id must be in array
+    iQuery->Conditions().AddRelationConditionL( objectIds );
+    
+    CMdERelationCondition& filterCondLeft = iQuery->Conditions().
+    		AddRelationConditionL( ERelationConditionSideLeft );
+
+    // Left object in relation must be an image object.
+    CMdEObjectDef& imageObjDef = iDefaultNamespace->GetObjectDefL(
+    		MdeConstants::Image::KImageObject );
+    filterCondLeft.LeftL().AddObjectConditionL( imageObjDef );
+    
+    CMdERelationCondition& filterCondRight = iQuery->Conditions().
+	AddRelationConditionL( ERelationConditionSideRight );
+    
+    // Right object in relation must be a location object.
+    CMdEObjectDef& locationObjDef = iDefaultNamespace->GetObjectDefL(
+    		Location::KLocationObject );
+    filterCondRight.RightL().AddObjectConditionL( locationObjDef );
+    
+    iQuery->FindL(); // results to a call to HandleQueryCompleted()
+    
+    CleanupStack::PopAndDestroy( &objectIds );
+    }
+
+// ---------------------------------------------------------------------------
+// HandleQueryCompleted
+// From MMdEQueryObserver.
+// ---------------------------------------------------------------------------
+//
+void CLocationRelationObserver::HandleQueryNewResults( CMdEQuery& /*aQuery*/,
+    TInt /*aFirstNewItemIndex*/, TInt /*aNewItemCount*/ )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// HandleQueryCompleted
+// From MMdEQueryObserver.
+// ---------------------------------------------------------------------------
+//
+void CLocationRelationObserver::HandleQueryCompleted( CMdEQuery& aQuery, TInt /*aError*/ )
+    {
+    if ( aQuery.Count() == 0 )
+        {
+        WRITELOG( "CLocationObjectObserver::HandleQueryCompleted() - no items found" );
+        }
+    else 
+    	{
+	    TRAP_IGNORE(
+	    const TInt count = aQuery.Count();
+	    for ( TInt i = 0; i < count; i++ )
+	    	{
+	    	CMdERelation* relation = iSession->GetRelationL( aQuery.ResultId(i) );
+	        if ( iComposer && relation )
+	            {
+	            iComposer->WriteGPSTagsL( relation->LeftObjectId(), relation->RightObjectId() );
+	            }
+	    	
+	    	delete relation;
+	    	}
+	    	)
+    	}
+    
+   	TRAP_IGNORE( QueryRelationItemsL() );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/composerplugins/imagecomposer/src/proxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Composer image plugin
+*
+*/
+
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include "composerimageplugin.h"
+
+// Map the interface UIDs to implementation factory functions
+const TImplementationProxy KImplementationTable[] = 
+	{
+		{{0x20007185},	(TProxyNewLPtr)CComposerImagePlugin::NewL}
+	};
+
+// Exported proxy for instantiation method resolution
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+	{
+	aTableCount = sizeof(KImplementationTable) / sizeof(TImplementationProxy);
+	return KImplementationTable;
+	}
+
Binary file harvester/conf/harvester.confml has changed
Binary file harvester/conf/harvester_200009FE.crml has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/data/blacklist_backup_registration.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,4 @@
+<?xml version="1.0" standalone="yes" ?>
+<backup_registration version="1.0">
+  <proxy_data_manager SID="0x10281E17" />
+</backup_registration>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/data/default_origin_mappings.db	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,34 @@
+Process UID / Origin -mapping table
+
+UID         Origin
+200009EE	0
+101FFA91	0
+10208A29	0
+101FD659	1
+101FFA86	1
+2000D16B	1
+10208A6D	1
+101f857a    1
+10003a3f	2
+101f4d90	2
+1028242D	2
+1028242E	2
+10281F1D	2
+101FFB51	2
+101F8839	2
+101FFAAB	2
+200071D8	2
+10008D60	2
+10008d39   	2
+1028190b    2
+100058CA	4
+1028290B	4
+10281FA8	4
+10281FA7	4
+10281FA5	4
+10281FA6	4
+101FFA91  254
+10208A29  254
+200009F5	255
+2000A7AE	255
+200071BE	255
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+#include "../blacklistclient/group/bld.inf"
+#include "../blacklistserver/group/bld.inf"
+#include "../common/group/bld.inf"
+#include "../composerplugins/group/bld.inf"
+#include "../harvesterplugins/group/bld.inf"
+#include "../monitorplugins/group/bld.inf"
+#include "../server/group/bld.inf"
+#include "../client/group/bld.inf"
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+../data/blacklist_backup_registration.xml	/epoc32/winscw/c/private/200009F5/backup_registration.xml
+../data/blacklist_backup_registration.xml   /epoc32/data/z/private/200009F5/backup_registration.xml
+../data/default_origin_mappings.db    /epoc32/winscw/c/private/200009F5/mappings.db
+../data/default_origin_mappings.db    /epoc32/data/z/private/200009F5/mappings.db
+../conf/harvester.confml        MW_LAYER_CONFML(harvester.confml)
+../conf/harvester_200009FE.crml MW_LAYER_CRML(harvester_200009FE.crml)
+
+../sis/blacklistserver/blacklistserver_stub.sis  /epoc32/data/z/system/install/blacklistserver_stub.sis
+../sis/composerplugins/composerplugins_stub.sis  /epoc32/data/z/system/install/composerplugins_stub.sis
+../sis/harvester/harvester_stub.sis  /epoc32/data/z/system/install/harvester_stub.sis
+../sis/harvesterplugins/harvesterplugins_stub.sis  /epoc32/data/z/system/install/harvesterplugins_stub.sis
+../sis/monitorplugins/monitorplugins_stub.sis  /epoc32/data/z/system/install/monitorplugins_stub.sis
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/AudioPlugin/data/2001116A.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// 2001116A.RSS
+
+#include "registryinfov2.rh"
+
+// Declares info for one test implementation
+RESOURCE REGISTRY_INFO theInfo
+	{
+    // resource_format_version must always be set as follows
+    resource_format_version = RESOURCE_FORMAT_VERSION_2;
+    
+	// UID for the DLL
+	dll_uid = 0x2001116A;
+	// Declare array of interface info
+	interfaces = 
+		{
+		INTERFACE_INFO
+			{
+			// UID of interface that is implemented
+			interface_uid = 0x200009F8;
+			implementations = 
+				{
+				// Info for CHarvesterVideoPlugin
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x2001116B;  // dll_uid + 1
+					version_no = 1;
+					display_name = "Harvester audio plugin";
+					default_data = "Audio";
+					opaque_data = "mp3 aac amr awb mid midi mxmf rng spmid wav au wma nrt mka";
+					rom_only = 0;
+					}
+				};
+			}
+		};
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/AudioPlugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build info file for Composer Plugin Interface.*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_MMPFILES
+harvesteraudioplugin.mmp
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/AudioPlugin/group/harvesteraudioplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,67 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester Audio plugin
+*
+*/
+
+
+// To get the MW_LAYER_SYSTEMINCLUDE-definition
+#include <platform_paths.hrh>
+
+CAPABILITY CAP_ECOM_PLUGIN
+
+VERSION       10.0
+TARGET        harvesteraudioplugin.dll
+TARGETTYPE    PLUGIN
+
+// ECom Dll recognition UID followed by the unique UID for this dll
+UID           0x10009D8D 0x2001116A
+
+start RESOURCE ../data/2001116A.rss
+target harvesteraudioplugin.rsc
+end
+
+
+SYSTEMINCLUDE /epoc32/include/ecom
+SYSTEMINCLUDE /epoc32/include/connect
+
+USERINCLUDE   ../../../../inc
+USERINCLUDE   ../../../common/inc
+USERINCLUDE   ../inc
+
+SOURCEPATH    ../src
+SOURCE        harvesteraudioplugin.cpp
+SOURCE        harvesteraudiopluginutils.cpp
+SOURCE        proxy.cpp
+
+// Default system include paths for middleware layer modules.
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY     euser.lib
+LIBRARY     efsrv.lib
+
+LIBRARY     harvesterplugininterface.lib
+LIBRARY     mdeclient.lib
+LIBRARY		harvesterdata.lib
+LIBRARY		harvestercommon.lib
+LIBRARY     metadatautility.lib 
+LIBRARY     thumbnailmanager.lib 
+LIBRARY     centralrepository.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/AudioPlugin/inc/harvesteraudioplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,155 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef HARVESTERAUDIOPLUGIN_H
+#define HARVESTERAUDIOPLUGIN_H
+
+#include <harvesterplugin.h>
+#include <thumbnailmanager.h>
+#include <thumbnailmanagerobserver.h>
+
+#include "harvesteraudiopluginutils.h"
+#include "mdeobjectwrapper.h"
+
+// FORWARD DECLARATION
+class CMdEObjectDef;
+class CHarvestData;
+class MThumbnailData;
+
+/**
+ * Helper class to hold all property definitions 
+ * (pointers are not owned) used in harvester audio plug-in.
+ */
+class CHarvesterAudioPluginPropertyDefs : public CBase
+	{
+	public:
+		// Common property definitions
+		CMdEPropertyDef* iCreationDatePropertyDef;
+		CMdEPropertyDef* iLastModifiedDatePropertyDef;
+		CMdEPropertyDef* iSizePropertyDef;
+		CMdEPropertyDef* iItemTypePropertyDef;
+		CMdEPropertyDef* iTitlePropertyDef;
+
+		// Media property definitions	
+		CMdEPropertyDef* iRatingPropertyDef;
+		CMdEPropertyDef* iGenrePropertyDef;
+		CMdEPropertyDef* iArtistPropertyDef;
+		CMdEPropertyDef* iDurationPropertyDef;
+		CMdEPropertyDef* iCopyrightPropertyDef;
+		CMdEPropertyDef* iThumbnailPropertyDef;
+		CMdEPropertyDef* iDatePropertyDef;
+
+		// Audio property definitions
+		CMdEPropertyDef* iAlbumPropertyDef;
+		CMdEPropertyDef* iComposerPropertyDef;		
+		CMdEPropertyDef* iOriginalArtistPropertyDef;
+		CMdEPropertyDef* iTrackPropertyDef;
+
+	private:
+		CHarvesterAudioPluginPropertyDefs();
+	
+		void ConstructL(CMdEObjectDef& aObjectDef);
+
+	public:	
+		static CHarvesterAudioPluginPropertyDefs* NewL(CMdEObjectDef& aObjectDef);
+	};
+
+class CHarvesterAudioPlugin : public CHarvesterPlugin,
+                                            public MThumbnailManagerObserver
+	{
+	public:
+		/**
+		* Construction
+		* @return Harvester audio plugin
+		*/
+		static CHarvesterAudioPlugin* NewL();
+
+		/**
+		* Destruction
+		*/
+		virtual ~CHarvesterAudioPlugin();
+
+    private:
+		// Default constructor
+		CHarvesterAudioPlugin();
+		
+		// 2nd phase constructor
+		void ConstructL();
+    
+    
+    
+    public: // from CHarvesterPlugin
+    
+		/**
+		* Harvesting multiple files
+		* @param aHarvesterData  CHarvesterData datatype containing needed harvest data
+ 		* @return None
+		*/
+		void HarvestL( CHarvesterData* aHD );
+
+    public: // from Thumbnail Observer
+		
+	    void ThumbnailPreviewReady( MThumbnailData& aThumbnail,
+	        TThumbnailRequestId aId );
+	    
+	    void ThumbnailReady( TInt aError, MThumbnailData& aThumbnail,
+	        TThumbnailRequestId aId );
+		
+	private:
+	     
+		/**
+		* Harvesting multiple files
+		* @param aHarvesterData  CHarvesterData datatype containing needed harvest data
+ 		* 
+		*/
+		void DoHarvestL( CHarvesterData* aHD );
+
+		/**
+		 * Handles creation of new mde objects.
+		 */
+		void GetPropertiesL( CHarvesterData* aHarvesterData, TBool aIsAdd );
+		 		
+		/**
+		 * Get placeholder properties (creation time, modify time and file size).
+		 */
+        void GetPlaceHolderPropertiesL( CHarvesterData* aHD, TBool aIsAdd );
+		
+		/**
+		 * Get media file mime type (eg. "audio/mp3").
+		 */
+        const TMimeTypeMapping<TAudioMetadataHandling>* GetMimeTypePropertyL( 
+        		CHarvesterData* aHD, TBool aIsAdd );
+
+		/**
+		 * Get song name, artist, album, genre and composer from normal music
+         * file (eg. mp3).
+		 */
+        void GetMusicPropertiesL( CHarvesterData* aHD, TBool aIsAdd );
+
+	private:
+		CAudioMDParser* iAudioParser;
+		
+		CHarvesterAudioPluginPropertyDefs* iPropDefs;
+		
+		CThumbnailManager* iTNM;
+		TBool iHarvestAlbumArt;
+	};
+
+
+#endif  // HARVESTERAUDIOPLUGIN_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/AudioPlugin/inc/harvesteraudiopluginutils.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,85 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef __CHARVESTERAUDIOPLUGINUTILS_H__
+#define __CHARVESTERAUDIOPLUGINUTILS_H__
+
+#include <MetaDataUtility.h>
+#include <MetaDataFieldContainer.h>
+
+#include "mimetypemapping.h"
+
+enum TAudioMetadataHandling
+	{
+	EMetaDataUtilityHandling,
+	EFileSystemHandling
+	};
+
+//
+// CAudioMDParser
+//
+class CAudioMDParser : public CBase
+	{
+    public:
+	    enum TAudioMetadataFields
+	        {
+	        EAudioMDFieldSong,
+	        EAudioMDFieldArtist,
+	        EAudioMDFieldAlbum,
+	        EAudioMDFieldGenre,
+	        EAudioMDFieldComposer,
+	        EAudioMDFieldRating,
+	        EAudioMDFieldTrack,
+	        EAudioMDFieldOriginalArtist,
+	        EAudioMDFieldDuration,
+	        EAudioMDFieldCopyright,
+	        EAudioMDFieldDate,
+	        EAudioMDFieldJpeg
+	        };
+	
+	public:
+		static CAudioMDParser* NewL( const TBool aAlbumArt );
+		virtual ~CAudioMDParser();
+
+        TBool ParseL( const TDesC& aFileName );
+        TPtrC MetaDataFieldL( TInt aFieldId );
+        TPtrC8 MetaDataField8L( TInt aFieldId );
+        void ResetL();
+        
+        const TMimeTypeMapping<TAudioMetadataHandling>* ParseMimeType( const TDesC& aFileName );
+		
+	private:
+        CAudioMDParser();
+        void ConstructL( const TBool aAlbumArt );
+		
+        TMetaDataFieldId MapFieldId( TInt aFieldId );
+
+    private:
+        CMetaDataUtility* iMetaDataUtility;
+        
+        RArray<TMetaDataFieldId> iWantedMetadataFields;
+        
+        RArray< TMimeTypeMapping<TAudioMetadataHandling> > iMimeTypeMappings;
+        
+        TInt iLastParsedFileMimeType;
+	};
+
+
+
+#endif  // __CHARVESTERAUDIOPLUGINUTILS_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/AudioPlugin/src/harvesteraudioplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,470 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester audio plugin
+*
+*/
+
+
+#include <e32base.h>
+#include <harvesterdata.h>
+#include <mdenamespacedef.h>
+#include <mdeobjectdef.h>
+#include <mdeobject.h>
+#include <centralrepository.h>
+
+#include "harvesteraudioplugin.h"
+#include "harvesteraudiopluginutils.h"
+
+#include "harvesterlog.h"
+
+const TInt KMimeLength( 10 );
+const TUid KHarvesterRepoUid = { 0x200009FE };
+const TUint32 KEnableAlbumArtHarvest = 0x00090001;
+
+CHarvesterAudioPluginPropertyDefs::CHarvesterAudioPluginPropertyDefs() : CBase()
+	{
+	}
+
+void CHarvesterAudioPluginPropertyDefs::ConstructL(CMdEObjectDef& aObjectDef)
+	{
+	CMdENamespaceDef& nsDef = aObjectDef.NamespaceDef();
+
+	// Image property definitions
+	CMdEObjectDef& objectDef = nsDef.GetObjectDefL( MdeConstants::Object::KBaseObject );
+	iCreationDatePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KCreationDateProperty );
+	iLastModifiedDatePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KLastModifiedDateProperty );
+	iSizePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KSizeProperty );
+	iItemTypePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KItemTypeProperty );
+	iTitlePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KTitleProperty );
+
+	// Media property definitions
+	CMdEObjectDef& mediaDef = nsDef.GetObjectDefL( MdeConstants::MediaObject::KMediaObject );
+	iRatingPropertyDef = &mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KRatingProperty );
+	iGenrePropertyDef = &mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KGenreProperty );
+	iArtistPropertyDef = &mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KArtistProperty );
+	iDurationPropertyDef = &mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KDurationProperty );
+	iCopyrightPropertyDef = &mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KCopyrightProperty );
+	iTrackPropertyDef = &mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KTrackProperty );
+	iThumbnailPropertyDef = &mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KThumbnailPresentProperty );
+	iDatePropertyDef = &mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KReleaseDateProperty );
+
+	// Audio property definitions
+	CMdEObjectDef& audioDef = nsDef.GetObjectDefL( MdeConstants::Audio::KAudioObject );
+	iAlbumPropertyDef = &audioDef.GetPropertyDefL( MdeConstants::Audio::KAlbumProperty );
+	iComposerPropertyDef = &audioDef.GetPropertyDefL( MdeConstants::Audio::KComposerProperty );
+	iOriginalArtistPropertyDef = &audioDef.GetPropertyDefL( MdeConstants::Audio::KOriginalArtistProperty );
+	}
+
+CHarvesterAudioPluginPropertyDefs* CHarvesterAudioPluginPropertyDefs::NewL(CMdEObjectDef& aObjectDef)
+	{
+	CHarvesterAudioPluginPropertyDefs* self = 
+		new (ELeave) CHarvesterAudioPluginPropertyDefs();
+	CleanupStack::PushL( self );
+	self->ConstructL( aObjectDef );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+using namespace MdeConstants;
+
+// ---------------------------------------------------------------------------
+// CHarvesterAudioPlugin::CHarvesterAudioPlugin
+// ---------------------------------------------------------------------------
+//    
+CHarvesterAudioPlugin::CHarvesterAudioPlugin() : CHarvesterPlugin(),
+    iAudioParser( NULL ), iPropDefs( NULL ), iTNM( NULL ), iHarvestAlbumArt( EFalse )
+	{
+	}
+
+// ---------------------------------------------------------------------------
+// CHarvesterAudioPlugin::NewL
+// ---------------------------------------------------------------------------
+//    
+CHarvesterAudioPlugin* CHarvesterAudioPlugin::NewL()
+	{
+	WRITELOG( "CHarvesterAudioPlugin::NewL()" );
+	CHarvesterAudioPlugin* self = new (ELeave) CHarvesterAudioPlugin();
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// CHarvesterAudioPlugin::~CHarvesterAudioPlugin
+// ---------------------------------------------------------------------------
+//    
+CHarvesterAudioPlugin::~CHarvesterAudioPlugin()
+	{
+	WRITELOG( "CHarvesterAudioPlugin::~CHarvesterAudioPlugin()" );
+	
+	delete iAudioParser;
+	delete iPropDefs;
+	delete iTNM;
+	}
+
+// ---------------------------------------------------------------------------
+// CHarvesterAudioPlugin::ConstructL
+// ---------------------------------------------------------------------------
+//    
+void CHarvesterAudioPlugin::ConstructL()
+	{
+	WRITELOG( "CHarvesterAudioPlugin::ConstructL()" );
+	
+    CRepository* rep = CRepository::NewLC( KHarvesterRepoUid );
+    rep->Get( KEnableAlbumArtHarvest, iHarvestAlbumArt );
+    CleanupStack::PopAndDestroy( rep );   
+	
+	iAudioParser = CAudioMDParser::NewL( iHarvestAlbumArt );
+    iAudioParser->ResetL();
+    
+    if( iHarvestAlbumArt )
+        {
+        TRAP_IGNORE( iTNM = CThumbnailManager::NewL( *this ) );
+        }
+	}
+
+// ---------------------------------------------------------------------------
+// CHarvesterAudioPlugin::HarvestL (from CHarvesterPlugin)
+// ---------------------------------------------------------------------------
+//    
+void CHarvesterAudioPlugin::HarvestL( CHarvesterData* aHD )
+	{
+	WRITELOG( "CHarvesterAudioPlugin::HarvestL()" );
+	
+	TInt err = KErrNone;
+	
+	TRAP( err, DoHarvestL( aHD ) );
+	
+	if ( err != KErrNone )
+	    {
+	    aHD->SetErrorCode( err );
+	    }
+	}
+
+// ---------------------------------------------------------------------------
+// CHarvesterAudioPlugin::ThumbnailPreviewReady 
+// ---------------------------------------------------------------------------
+//    
+void CHarvesterAudioPlugin::ThumbnailPreviewReady( MThumbnailData& /*aThumbnail*/,
+    TThumbnailRequestId /*aId*/ )
+    {
+    // Pass through, nothing to do
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterAudioPlugin::HarvestL (from CHarvesterPlugin)
+// ---------------------------------------------------------------------------
+//    
+void CHarvesterAudioPlugin::ThumbnailReady( TInt /*aError*/, 
+    MThumbnailData& /*aThumbnail*/,
+    TThumbnailRequestId /*aId*/ )
+    {
+    // Pass through, nothing to do
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterAudioPlugin::DoHarvestL
+// ---------------------------------------------------------------------------
+//    
+void CHarvesterAudioPlugin::DoHarvestL( CHarvesterData* aHD )
+	{
+	WRITELOG( "CHarvesterAudioPlugin::DoHarvestL()" );
+    CMdEObject& mdeObject = aHD->MdeObject();
+        
+    TBool isAdd = EFalse;
+    if ( mdeObject.Placeholder() || mdeObject.Id() == KNoId ) // is a new object or placeholder
+        {
+        isAdd = ETrue;
+        }
+
+    GetPropertiesL( aHD, isAdd );
+	}
+
+
+// ---------------------------------------------------------------------------
+// CHarvesterAudioPlugin::GetPropertiesL
+// ---------------------------------------------------------------------------
+//    
+void CHarvesterAudioPlugin::GetPropertiesL( CHarvesterData* aHD,
+                                            TBool aIsAdd )
+    {
+    CMdEObject& mdeObject = aHD->MdeObject();
+    
+    // get creation time, modified time and file size
+    if( !mdeObject.Placeholder() )
+        {
+        GetPlaceHolderPropertiesL( aHD, aIsAdd );
+        }
+    
+    const TMimeTypeMapping<TAudioMetadataHandling>* mapping = 
+    	GetMimeTypePropertyL( aHD, aIsAdd );
+
+    if( mapping )
+    	{
+		// get properties for file types supported by CMetaDataUtility.
+    	if( mapping->iHandler == EMetaDataUtilityHandling )
+    		{
+    		GetMusicPropertiesL( aHD, aIsAdd );
+    		}
+    	}
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterAudioPlugin::GetPlaceHolderPropertiesL
+// Get placeholder properties (creation time, modify time and file size).
+// ---------------------------------------------------------------------------
+//    
+void CHarvesterAudioPlugin::GetPlaceHolderPropertiesL( CHarvesterData* aHD,
+                               TBool aIsAdd )
+    {
+    CMdEObject& mdeObject = aHD->MdeObject();
+    
+    const TDesC& uri = mdeObject.Uri();
+    
+    TEntry entry;
+    TInt err = iFs.Entry( uri, entry );
+    
+    if ( err!= KErrNone )
+        {
+        User::Leave( err ); // metadata cannot be gathered!
+        }
+    
+	TTime now;
+	now.HomeTime();
+    
+	if( !iPropDefs )
+		{
+		CMdEObjectDef& objectDef = mdeObject.Def();
+		iPropDefs = CHarvesterAudioPluginPropertyDefs::NewL( objectDef );
+		}
+	
+	CMdeObjectWrapper::HandleObjectPropertyL(
+                 mdeObject, *iPropDefs->iCreationDatePropertyDef, &now, aIsAdd );
+
+	CMdeObjectWrapper::HandleObjectPropertyL(
+             mdeObject, *iPropDefs->iLastModifiedDatePropertyDef, &entry.iModified, aIsAdd );
+
+	CMdeObjectWrapper::HandleObjectPropertyL(
+              mdeObject, *iPropDefs->iSizePropertyDef, &entry.iSize, aIsAdd );
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterAudioPlugin::GetMimeTypePropertyL
+// Get mime type.
+// ---------------------------------------------------------------------------
+//    
+const TMimeTypeMapping<TAudioMetadataHandling>* CHarvesterAudioPlugin::GetMimeTypePropertyL( 
+		CHarvesterData* aHD, TBool aIsAdd )
+    {
+    CMdEObject& mdeObject = aHD->MdeObject();
+ 
+    const TMimeTypeMapping<TAudioMetadataHandling>* mapping = 
+    	iAudioParser->ParseMimeType( mdeObject.Uri() );
+    
+    if ( mapping )
+        {
+    	if( !iPropDefs )
+    		{
+    		CMdEObjectDef& objectDef = mdeObject.Def();
+    		iPropDefs = CHarvesterAudioPluginPropertyDefs::NewL( objectDef );
+    		}
+        
+    	CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+    			*iPropDefs->iItemTypePropertyDef, (TAny*)&(mapping->iMimeType), aIsAdd );
+        }
+    
+    return mapping;
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterAudioPlugin::GetMusicPropertiesL
+// ---------------------------------------------------------------------------
+//    
+void CHarvesterAudioPlugin::GetMusicPropertiesL( CHarvesterData* aHD,
+                                      TBool aIsAdd )
+    {
+#ifdef _DEBUG
+    TTime dStart, dStop;
+    dStart.UniversalTime();
+    dStop.UniversalTime();
+    WRITELOG1( "CHarvesterAudioPlugin::GetMusicPropertiesL start %d us", (TInt)dStop.MicroSecondsFrom(dStart).Int64() );
+#endif
+    
+    CMdEObject& mdeObject = aHD->MdeObject();
+    const TDesC& uri = mdeObject.Uri();
+    
+    TBool parsed( EFalse );
+    TRAPD( parseError, parsed = iAudioParser->ParseL( uri ) );
+
+    if( !parsed || (parseError != KErrNone) )
+    	{
+    	iAudioParser->ResetL();
+    	return;
+    	}
+
+    // We do not want to get all long text fields at this time
+    TPtrC song      = iAudioParser->MetaDataFieldL( CAudioMDParser::EAudioMDFieldSong );
+    TPtrC artist    = iAudioParser->MetaDataFieldL( CAudioMDParser::EAudioMDFieldArtist );
+    TPtrC album     = iAudioParser->MetaDataFieldL( CAudioMDParser::EAudioMDFieldAlbum );
+    TPtrC genre     = iAudioParser->MetaDataFieldL( CAudioMDParser::EAudioMDFieldGenre );
+    TPtrC composer  = iAudioParser->MetaDataFieldL( CAudioMDParser::EAudioMDFieldComposer );
+    TPtrC rating    = iAudioParser->MetaDataFieldL( CAudioMDParser::EAudioMDFieldRating );
+    TPtrC orgArtist = iAudioParser->MetaDataFieldL( CAudioMDParser::EAudioMDFieldOriginalArtist );
+    TPtrC track     = iAudioParser->MetaDataFieldL( CAudioMDParser::EAudioMDFieldTrack );
+    TPtrC duration  = iAudioParser->MetaDataFieldL( CAudioMDParser::EAudioMDFieldDuration );
+    TPtrC copyright     = iAudioParser->MetaDataFieldL( CAudioMDParser::EAudioMDFieldCopyright);
+    TPtrC date     = iAudioParser->MetaDataFieldL( CAudioMDParser::EAudioMDFieldDate );
+    
+    TPtrC8 jpeg = iAudioParser->MetaDataField8L( CAudioMDParser::EAudioMDFieldJpeg );
+    
+	if( !iPropDefs )
+		{
+	    CMdEObjectDef& audioObjectDef = mdeObject.Def();
+		iPropDefs = CHarvesterAudioPluginPropertyDefs::NewL( audioObjectDef );
+		}
+    
+    if ( song.Length() > 0
+        && song.Length() < iPropDefs->iTitlePropertyDef->MaxTextLengthL() )
+        {
+        TRAPD( error, CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+        		*iPropDefs->iTitlePropertyDef, &song, aIsAdd ) );
+        if( error != KErrNone )
+            {
+            CMdEProperty* prop = NULL;
+            const TInt index = mdeObject.Property( *iPropDefs->iTitlePropertyDef, prop );
+            mdeObject.RemoveProperty( index );
+            CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+            		*iPropDefs->iTitlePropertyDef, &song, aIsAdd );
+            }
+        }
+
+    if ( artist.Length() > 0
+        && artist.Length() < iPropDefs->iArtistPropertyDef->MaxTextLengthL() )
+        {
+        CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+        		*iPropDefs->iArtistPropertyDef, &artist, aIsAdd );
+        }
+
+    if ( album.Length() > 0
+        && album.Length() < iPropDefs->iAlbumPropertyDef->MaxTextLengthL() )
+        {
+        CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+        		*iPropDefs->iAlbumPropertyDef, &album, aIsAdd );
+        }
+ 
+    if ( genre.Length() > 0
+        && genre.Length() < iPropDefs->iGenrePropertyDef->MaxTextLengthL() )
+        {
+        CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+        		*iPropDefs->iGenrePropertyDef, &genre, aIsAdd );
+        }
+
+    if ( composer.Length() > 0
+        && composer.Length() < iPropDefs->iComposerPropertyDef->MaxTextLengthL() )
+        {
+        CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+        		*iPropDefs->iComposerPropertyDef, &composer, aIsAdd );
+        }
+
+    if ( rating.Length() > 0 )
+        {
+        TLex ratingLex( rating );
+        TUint8 ratingValue( 0 );
+        const TInt error( ratingLex.Val( ratingValue, EDecimal ) );
+        if( error == KErrNone )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+                *iPropDefs->iRatingPropertyDef, &ratingValue, aIsAdd );        
+            }
+        }
+    
+    if ( orgArtist.Length() > 0
+        && orgArtist.Length() < iPropDefs->iOriginalArtistPropertyDef->MaxTextLengthL() )
+        {
+        CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+        		*iPropDefs->iOriginalArtistPropertyDef, &orgArtist, aIsAdd );
+        }
+    
+    if ( track.Length() > 0 )
+        {
+        TLex trackLex( track );
+        TUint16 trackValue( 0 );
+        trackLex.Val( trackValue, EDecimal );
+        CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+        		*iPropDefs->iTrackPropertyDef, &trackValue, aIsAdd );
+        }
+    
+    if ( duration.Length() > 0 )
+        {
+        TLex durationLex( duration );
+        TReal32 durationValue( 0 );
+        const TInt error( durationLex.Val( durationValue, EDecimal ) );
+        if( error == KErrNone )
+            {
+            if ( durationValue < iPropDefs->iDurationPropertyDef->MaxRealValueL() )
+                {
+                CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+                    *iPropDefs->iDurationPropertyDef, &durationValue, aIsAdd );
+                }
+            }
+        }
+    
+    if ( copyright.Length() > 0
+        && copyright.Length() < iPropDefs->iCopyrightPropertyDef->MaxTextLengthL() )
+        {
+        CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+        		*iPropDefs->iCopyrightPropertyDef, &copyright, aIsAdd );
+        }
+    
+    if ( date.Length() > 0
+        && date.Length() < iPropDefs->iDatePropertyDef->MaxTextLengthL() )
+        {
+        TTime releaseDate( date );
+        CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+                *iPropDefs->iDatePropertyDef, &releaseDate, aIsAdd );
+        }
+    
+    if( iHarvestAlbumArt && iTNM && jpeg.Length() > 0 )
+        {
+        HBufC8* jpegBuf = jpeg.AllocLC();
+        TBuf<KMimeLength> mimeType( KNullDesC );
+        CThumbnailObjectSource* tnmSource = CThumbnailObjectSource::NewL( jpegBuf, mimeType, uri );
+        CleanupStack::Pop(); // jpegBuf
+        // Ownership of buffer is transferred to Thumbnail Manager
+        iTNM->CreateThumbnails( *tnmSource );
+        delete tnmSource;
+        TBool thumbnailPresent( ETrue );
+        CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+                          *iPropDefs->iThumbnailPropertyDef, &thumbnailPresent, aIsAdd );
+        }
+    else if( iHarvestAlbumArt )
+        {
+        TBool thumbnailNotPresent( EFalse );
+        CMdeObjectWrapper::HandleObjectPropertyL( mdeObject, 
+                          *iPropDefs->iThumbnailPropertyDef, &thumbnailNotPresent, aIsAdd );
+        }
+       
+    
+    iAudioParser->ResetL();
+    
+#ifdef _DEBUG
+    dStop.UniversalTime();
+    WRITELOG1( "CHarvesterAudioPlugin::GetMusicPropertiesL start %d us", (TInt)dStop.MicroSecondsFrom(dStart).Int64() );
+#endif   
+    }
+
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/AudioPlugin/src/harvesteraudiopluginutils.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,335 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester audio plugin
+*
+*/
+
+
+#include <e32base.h>
+#include <apgcli.h>  // for RApaLsSession
+
+#include "harvesteraudiopluginutils.h"
+
+#include "mdsutils.h"
+#include "harvesterlog.h"
+
+_LIT( KMimeTypeMpeg,   "audio/mpeg" );
+_LIT( KMimeTypeAac,    "audio/aac" );
+_LIT( KMimeTypeAmr,    "audio/amr" );
+_LIT( KMimeTypeAwb,    "audio/amr-wb" );
+_LIT( KMimeTypeMidi,   "audio/midi" );
+_LIT( KMimeTypeSpMidi, "audio/sp-midi" );
+_LIT( KMimeTypeRng,    "application/vnd.nokia.ringing-tone" );
+_LIT( KMimeTypeMxmf,   "audio/vnd.nokia.mobile-xmf" );
+_LIT( KMimeTypeWav,    "audio/wav" );
+_LIT( KMimeTypeAu,     "audio/au" );
+_LIT( KMimeTypeWma,    "audio/x-ms-wma");
+_LIT( KMimeTypeAudioMatroska, "audio/x-matroska");
+
+_LIT( KExtensionMp3,    "mp3" );
+_LIT( KExtensionAac,    "aac" );
+_LIT( KExtensionAmr,    "amr" );
+_LIT( KExtensionAwb,    "awb" );
+_LIT( KExtensionMid,    "mid" );
+_LIT( KExtensionMidi,   "midi" );
+_LIT( KExtensionSpMid,  "spmid" );
+_LIT( KExtensionRng,    "rng" );
+_LIT( KExtensionMxmf,   "mxmf" );
+_LIT( KExtensionWav,    "wav" );
+_LIT( KExtensionAu,     "au" );
+_LIT( KExtensionWma,    "wma" );
+_LIT( KExtensionNrt,    "nrt" );
+_LIT( KExtensionMka,    "mka" );
+
+// -----------------------------------------------------------------------------
+// CAudioMDParser::NewL
+// 
+// -----------------------------------------------------------------------------
+//
+CAudioMDParser* CAudioMDParser::NewL( const TBool aAlbumArt )
+    {
+    CAudioMDParser* self = new ( ELeave ) CAudioMDParser();
+	CleanupStack::PushL( self );
+	self->ConstructL( aAlbumArt );
+	CleanupStack::Pop( self );
+
+	return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// Destructor
+// 
+// -----------------------------------------------------------------------------
+//
+CAudioMDParser::~CAudioMDParser()
+    {
+    delete iMetaDataUtility;
+    
+    iWantedMetadataFields.Close();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAudioMDParser::CAudioMDParser
+// 
+// -----------------------------------------------------------------------------
+//
+CAudioMDParser::CAudioMDParser() :
+	iMetaDataUtility( NULL ), iLastParsedFileMimeType( 0 )
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAudioMDParser::ConstructL
+// 
+// -----------------------------------------------------------------------------
+//
+void CAudioMDParser::ConstructL( const TBool aAlbumArt )
+    {
+    iMetaDataUtility = CMetaDataUtility::NewL();
+
+    // initialize metadata field list for CMetaDataUtility (iMetaDataUtility)
+    iWantedMetadataFields.AppendL( EMetaDataSongTitle );
+    iWantedMetadataFields.AppendL( EMetaDataArtist );
+    iWantedMetadataFields.AppendL( EMetaDataAlbum );
+    iWantedMetadataFields.AppendL( EMetaDataGenre );
+    iWantedMetadataFields.AppendL( EMetaDataComposer );
+    iWantedMetadataFields.AppendL( EMetaDataRating );
+    iWantedMetadataFields.AppendL( EMetaDataAlbumTrack );
+    iWantedMetadataFields.AppendL( EMetaDataOriginalArtist );
+    iWantedMetadataFields.AppendL( EMetaDataDuration );
+    iWantedMetadataFields.AppendL( EMetaDataCopyright );
+    iWantedMetadataFields.AppendL( EMetaDataDate );
+    
+    if( aAlbumArt )
+        {
+        iWantedMetadataFields.AppendL( EMetaDataJpeg );
+        }
+    
+    TLinearOrder< TMimeTypeMapping<TAudioMetadataHandling> > cmp(
+    		TMimeTypeMapping<TAudioMetadataHandling>::CompareFunction);
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+    		KExtensionMp3(), KMimeTypeMpeg(), 
+    		EMetaDataUtilityHandling ), cmp ) );
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+    		KExtensionAac(), KMimeTypeAac(), 
+    		EMetaDataUtilityHandling ), cmp ) );
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+    		KExtensionAmr(), KMimeTypeAmr(), 
+    		EMetaDataUtilityHandling ), cmp ) );
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+    		KExtensionAwb(), KMimeTypeAwb(), 
+    		EMetaDataUtilityHandling ), cmp ) );
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+        	KExtensionWma(), KMimeTypeWma(), 
+        	EMetaDataUtilityHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+    		KExtensionMid(), KMimeTypeMidi(), 
+    		EFileSystemHandling ), cmp ) );
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+    		KExtensionMidi(), KMimeTypeMidi(), 
+    		EFileSystemHandling ), cmp ) );
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+    		KExtensionSpMid(), KMimeTypeSpMidi(), 
+    		EFileSystemHandling ), cmp ) );
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+    		KExtensionRng(), KMimeTypeRng(), 
+    		EFileSystemHandling ), cmp ) );
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+    		KExtensionMxmf(), KMimeTypeMxmf(), 
+    		EFileSystemHandling ), cmp ) );
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+    		KExtensionWav(), KMimeTypeWav(), 
+    		EFileSystemHandling ), cmp ) );
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+    		KExtensionAu(), KMimeTypeAu(), 
+    		EFileSystemHandling ), cmp ) );
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+    		KExtensionNrt(), KMimeTypeRng(), 
+    		EFileSystemHandling ), cmp ) );
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TAudioMetadataHandling>(
+            KExtensionMka(), KMimeTypeAudioMatroska(), 
+            EMetaDataUtilityHandling ), cmp ) );
+
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAudioMDParser::ParseMimeType
+// 
+// -----------------------------------------------------------------------------
+//
+const TMimeTypeMapping<TAudioMetadataHandling>* CAudioMDParser::ParseMimeType( 
+		const TDesC& aFileName )
+    {
+    TPtrC ext;
+    if( MdsUtils::GetExt( aFileName, ext ) )
+    	{
+    	TMimeTypeMapping<TAudioMetadataHandling> finder(ext);
+    	
+    	TLinearOrder< TMimeTypeMapping<TAudioMetadataHandling> > cmp(
+    			TMimeTypeMapping<TAudioMetadataHandling>::CompareFunction);
+    	
+    	TInt pos = iMimeTypeMappings.FindInOrder( finder, cmp );
+    	
+    	if( KErrNotFound != pos )
+    		{
+    		iLastParsedFileMimeType = pos;
+    		return &iMimeTypeMappings[ pos ];
+    		}
+    	}
+
+    return NULL;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAudioMDParser::ParseL
+// 
+// -----------------------------------------------------------------------------
+//
+TBool CAudioMDParser::ParseL( const TDesC& aFileName )
+    {
+    TBuf8<KMaxDataTypeLength> mime;
+    mime.Copy( iMimeTypeMappings[ iLastParsedFileMimeType ].iMimeType );
+    iMetaDataUtility->OpenFileL( aFileName, iWantedMetadataFields, mime );
+    
+    return iMetaDataUtility->MetaDataCount() > 0;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAudioMDParser::MetaDataFieldL
+// 
+// -----------------------------------------------------------------------------
+//
+TPtrC CAudioMDParser::MetaDataFieldL( TInt aFieldId )
+    {
+    const CMetaDataFieldContainer& metaCont = iMetaDataUtility->MetaDataFieldsL();
+    
+    TMetaDataFieldId id = MapFieldId( aFieldId );
+    return metaCont.Field( id );  // returns KNullDesC if not found
+    }
+
+// -----------------------------------------------------------------------------
+// CAudioMDParser::MetaDataFieldL
+// 
+// -----------------------------------------------------------------------------
+//
+TPtrC8 CAudioMDParser::MetaDataField8L( TInt aFieldId )
+    {
+    const CMetaDataFieldContainer& metaCont = iMetaDataUtility->MetaDataFieldsL();
+    
+    TMetaDataFieldId id = MapFieldId( aFieldId );
+    return metaCont.Field8( id );  // returns KNullDesC if not found
+    }
+
+// -----------------------------------------------------------------------------
+// CAudioMDParser::ResetL
+// 
+// -----------------------------------------------------------------------------
+//
+void CAudioMDParser::ResetL()
+    {
+    iMetaDataUtility->ResetL();
+    }
+
+// -----------------------------------------------------------------------------
+// CAudioMDParser::MapFieldId
+// 
+// -----------------------------------------------------------------------------
+//
+TMetaDataFieldId CAudioMDParser::MapFieldId( TInt aFieldId )
+    {
+    TMetaDataFieldId id = EMetaDataSongTitle;
+    
+    switch ( aFieldId )
+        {
+        case EAudioMDFieldSong:
+            {
+            id = EMetaDataSongTitle;
+            break;
+            }
+        case EAudioMDFieldArtist:
+            {
+            id = EMetaDataArtist;
+            break;
+            }
+        case EAudioMDFieldAlbum:
+            {
+            id = EMetaDataAlbum;
+            break;
+            }
+        case EAudioMDFieldGenre:
+            {
+            id = EMetaDataGenre;
+            break;
+            }
+        case EAudioMDFieldComposer:
+            {
+            id = EMetaDataComposer;
+            break;
+            }
+        case EAudioMDFieldRating:
+            {
+            id = EMetaDataRating;
+            break;
+            }
+        case EAudioMDFieldTrack:
+            {
+            id = EMetaDataAlbumTrack;
+            break;
+            }
+        case EAudioMDFieldOriginalArtist:
+            {
+            id = EMetaDataOriginalArtist;
+            break;
+            }
+        case EAudioMDFieldDuration:
+            {
+            id = EMetaDataDuration;
+            break;
+            }
+        case EAudioMDFieldCopyright:
+            {
+            id = EMetaDataCopyright;
+            break;
+            }
+        case EAudioMDFieldDate:
+            {
+            id = EMetaDataDate;
+            break;
+            }
+        case EAudioMDFieldJpeg:
+            {
+            id = EMetaDataJpeg;
+            break;
+            }
+
+        default:
+            {
+#ifdef _DEBUG
+            _LIT( KPanicCategory,"HarvesterAudioPlugin" );
+            __ASSERT_DEBUG( EFalse, User::Panic( KPanicCategory,  KErrArgument ) );
+#endif
+            break;
+            }
+        }
+        
+    return id;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/AudioPlugin/src/proxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester audio plugin
+*
+*/
+
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include "harvesteraudioplugin.h"
+
+// Map the interface UIDs to implementation factory functions
+const TImplementationProxy KImplementationTable[] = 
+	{
+		{{0x2001116B},	(TProxyNewLPtr)CHarvesterAudioPlugin::NewL}
+	};
+
+// Exported proxy for instantiation method resolution
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+	{
+	aTableCount = sizeof(KImplementationTable) / sizeof(TImplementationProxy);
+	return KImplementationTable;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/ImagePlugin/data/200009fb.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// 1CA032F6.RSS
+
+#include "registryinfov2.rh"
+
+// Declares info for one test implementation
+RESOURCE REGISTRY_INFO theInfo
+	{
+  // resource_format_version must always be set as follows
+  resource_format_version = RESOURCE_FORMAT_VERSION_2;
+    
+	// UID for the DLL
+	dll_uid = 0x200009FB;
+	// Declare array of interface info
+	interfaces = 
+		{
+		INTERFACE_INFO
+			{
+			// UID of interface that is implemented
+			interface_uid = 0x200009F8;
+			implementations = 
+				{
+				// Info for CHarvesterVideoPlugin
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x200009FC;
+					version_no = 1;
+					display_name = "Harvester image plugin";
+					default_data = "Image";
+					opaque_data = "jpg jpeg jp2 j2k jpx jpf mbm ota wbmp wmf png gif bmp tif tiff otb";
+					rom_only = 0;
+					}
+				};
+			}
+		};
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/ImagePlugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+harvesterimageplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/ImagePlugin/group/harvesterimageplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,63 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        harvesterimageplugin.dll
+TARGETTYPE    PLUGIN
+UID           0x10009D8D 0x200009FB
+
+CAPABILITY 	  CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+start RESOURCE ../data/200009fb.rss
+target harvesterimageplugin.rsc
+end
+
+SYSTEMINCLUDE /epoc32/include/ecom
+SYSTEMINCLUDE /epoc32/include/connect
+
+USERINCLUDE   ../../../../inc
+USERINCLUDE   ../../../common/inc
+USERINCLUDE   ../inc
+
+SOURCEPATH    ../src
+SOURCE        harvesterimageplugin.cpp
+SOURCE        proxy.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       efsrv.lib
+LIBRARY       imageconversion.lib
+LIBRARY       fbscli.lib 
+LIBRARY	  lbs.lib
+LIBRARY	  etel3rdparty.lib
+LIBRARY       harvesterplugininterface.lib
+LIBRARY       mdeclient.lib
+LIBRARY	  harvesterdata.lib
+LIBRARY	  harvestercommon.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/ImagePlugin/inc/harvesterimageplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,199 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef __CHARVESTERIMAGEPLUGIN_H__
+#define __CHARVESTERIMAGEPLUGIN_H__
+
+#include <mdeobject.h>
+#include <fbs.h>
+#include <imageconversion.h>
+#include <harvesterplugin.h>
+#include <monitorplugin.h>
+
+#include "mimetypemapping.h"
+
+// FORWARD DECLARATION
+class CFileData;
+class CHarvestData;
+class CHarvesterExifUtil;
+
+/**
+ * Helper class to hold all property definitions 
+ * (pointers are not owned) used in harvester image plug-in.
+ */
+class CHarvesterImagePluginPropertyDefs : public CBase
+	{
+	public:
+		// Common property definitions
+		CMdEPropertyDef* iCreationDatePropertyDef;
+		CMdEPropertyDef* iLastModifiedDatePropertyDef;
+		CMdEPropertyDef* iSizePropertyDef;
+		CMdEPropertyDef* iTimeOffsetPropertyDef;
+		CMdEPropertyDef* iItemTypePropertyDef;
+	
+		// Media property definitions
+		CMdEPropertyDef* iWidthPropertyDef;
+		CMdEPropertyDef* iHeightPropertyDef;
+		CMdEPropertyDef* iDescriptionPropertyDef;
+		CMdEPropertyDef* iCommentPropertyDef;
+		CMdEPropertyDef* iReleaseDatePropertyDef;
+		CMdEPropertyDef* iCopyrightPropertyDef;
+		CMdEPropertyDef* iCaptureDatePropertyDef;
+		CMdEPropertyDef* iResolutionUnitPropertyDef;
+		CMdEPropertyDef* iArtistPropertyDef;
+		
+		// Image property definitions
+		CMdEPropertyDef* iPixelYDimensionPropertyDef;
+		CMdEPropertyDef* iPixelXDimensionPropertyDef;
+		CMdEPropertyDef* iBitsPerSamplePropertyDef;
+		CMdEPropertyDef* iFrameCountPropertyDef;
+		CMdEPropertyDef* iDateTimeOriginalPropertyDef;
+		CMdEPropertyDef* iDateTimeDigitizedPropertyDef;
+		CMdEPropertyDef* iDateTimePropertyDef;
+		CMdEPropertyDef* iWhiteBalancePropertyDef;
+		CMdEPropertyDef* iFlashPropertyDef;
+		CMdEPropertyDef* iExposureProgramPropertyDef;
+		CMdEPropertyDef* iMakePropertyDef;
+		CMdEPropertyDef* iModelPropertyDef;
+		CMdEPropertyDef* iOrientationPropertyDef;
+		CMdEPropertyDef* iXResolutionPropertyDef;
+		CMdEPropertyDef* iYResolutionPropertyDef;
+		CMdEPropertyDef* iYCbCrPositioningPropertyDef;
+		CMdEPropertyDef* iExposureTimePropertyDef;
+		CMdEPropertyDef* iFNumberPropertyDef;
+		CMdEPropertyDef* iExifVersionPropertyDef;
+		CMdEPropertyDef* iShutterSpeedValuePropertyDef;
+		CMdEPropertyDef* iApertureValuePropertyDef;
+		CMdEPropertyDef* iFocalLengthPropertyDef;
+		CMdEPropertyDef* iFlashPixVersionPropertyDef;
+		CMdEPropertyDef* iColourSpacePropertyDef;
+		CMdEPropertyDef* iISOSpeedRatingsPropertyDef;
+		CMdEPropertyDef* iComponentsConfigurationPropertyDef;
+		CMdEPropertyDef* iExposureBiasValuePropertyDef;
+		CMdEPropertyDef* iSamplesPerPixelPropertyDef;
+		CMdEPropertyDef* iThumbCompressionPropertyDef;
+		CMdEPropertyDef* iThumbXResolutionPropertyDef;
+		CMdEPropertyDef* iThumbYResolutionPropertyDef;
+		CMdEPropertyDef* iThumbResolutionUnitPropertyDef;
+		CMdEPropertyDef* iFocalLengthIn35mmFilmPropertyDef;
+		CMdEPropertyDef* iMeteringModePropertyDef;
+		CMdEPropertyDef* iRelatedSoundFilePropertyDef;
+		CMdEPropertyDef* iFocalPlaneResolutionUnitPropertyDef;
+		CMdEPropertyDef* iFocalPlaneXResolutionPropertyDef;
+		CMdEPropertyDef* iFocalPlaneYResolutionPropertyDef;
+        CMdEPropertyDef* iDraftPropertyDef;
+
+	private:
+		CHarvesterImagePluginPropertyDefs();
+	
+		void ConstructL(CMdEObjectDef& aObjectDef);
+
+	public:	
+		static CHarvesterImagePluginPropertyDefs* NewL(CMdEObjectDef& aObjectDef);
+	};
+
+class CHarvesterImagePlugin : public CHarvesterPlugin
+	{
+	public:
+
+		/**
+		* Construction
+		* @return Harvester image plugin
+		*/
+		static CHarvesterImagePlugin* NewL();
+
+		/**
+		* Destruction
+		*/
+		virtual ~CHarvesterImagePlugin();
+
+		/**
+		* Harvesting multiple files
+		* @param aHarvesterData  CHarvesterData datatype containing needed harvest data
+ 		* @param aClientData  TAny* to client specific data
+		*/
+		void HarvestL( CHarvesterData* aHD );
+
+	private:
+	    /**
+	     * The method that actually extracts the metadata.
+	     * @param aMetadataObject  Metadata object which is filled with metadata
+	     * @param aFileData  File data to be filled
+	     * @param aHarvestData  Harvested data to be filled
+	     * @return Error code which indicates status of the operation
+	     */                
+		TInt GatherDataL( CMdEObject& aMetadataObject, CFileData& aFileData,
+				CHarvestData& aHarvestData );
+
+		/**
+		 * Checks if the MIME type of current file is supported.
+		 * @param aMimeBuf mime string
+		 * @return KErrNone if MIME type is supported, KErrNotSupported if not
+		 */
+		TInt CheckIfMimeSupported( const TDesC& aMimeBuf );
+		 
+		/**
+		 * Reads file data from image file.
+		 */
+		void DataFromImageFileL( CFileData& aFileData );
+		
+		/**
+		 * Handles creation of new mde objects.
+		 */
+		void HandleObjectPropertiesL( CHarvestData& aHd, CFileData& aFileData,
+		 		CHarvesterData& aHarvesterData, TBool aIsAdd );
+
+		// Default constructor
+		CHarvesterImagePlugin();
+		
+		// 2nd phase constructor
+		void ConstructL();
+	
+	private:
+	
+		enum TImageMetadataHandling
+			{
+			EJpegHandling,
+			EGifHandling,
+			EOtherHandling
+			};
+		
+		/** */
+        CHarvesterExifUtil* iExifUtil;
+        
+        /**
+         *  Buffered image decoder (so that we don't have to create decoders all the time)
+         */        
+        CBufferedImageDecoder *iDecoder;
+         
+        /**
+         *  Session to Font and Bitmap server. For some reason WMF-harvesting needs this
+         */
+        RFbsSession iFbs;
+        
+        
+        /**
+         *  Mime type mapper for extension/mimetype pairs
+         */
+        RArray< TMimeTypeMapping<TImageMetadataHandling> > iMimeTypeMappings;
+        
+        CHarvesterImagePluginPropertyDefs* iPropDefs;
+	};
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/ImagePlugin/src/harvesterimageplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,954 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester image plugin
+*
+*/
+
+
+#include <e32base.h>
+#include <e32math.h>
+#include <locationdatatype.h>
+#include <harvesterdata.h>
+
+#include "harvesterlog.h"
+#include "mdsutils.h"
+#include "harvesterexifutil.h"
+#include "harvesterimageplugin.h"
+#include "mdeobjectwrapper.h"
+
+using namespace MdeConstants;
+
+// image mime types
+_LIT( KJpegMime, "image/jpeg" );
+_LIT( KJpeg2000Mime, "image/jp2" );
+_LIT( KJpeg2000_2Mime, "image/jpx" );
+_LIT( KTiffMime, "image/tiff" );
+_LIT( KMsmMime, "application/x-msmetafile" );
+_LIT( KGifMime, "image/gif" );
+_LIT( KXbmpMime, "image/x-bmp" );
+_LIT( KBmpMime, "image/bmp" );
+_LIT( KPngMime, "image/png" );
+_LIT( KMbmMime, "image/x-epoc-mbm" );
+_LIT( KOtaMime, "image/vnd.nokia.ota-bitmap" );
+_LIT( KXotaMime, "image/x-ota-bitmap" );
+_LIT( KWbmpMime, "image/vnd.wap.wbmp" );
+_LIT( KWmfMime, "image/x-wmf" );
+_LIT( KOtbMime, "image/vnd.nokia.ota-bitmap" );
+
+_LIT( KExtJpg, "JPG" );
+_LIT( KExtJpeg, "JPEG" );
+_LIT( KExtJp2, "JP2" );
+_LIT( KExtJ2k, "J2K" ); 
+_LIT( KExtJpx, "JPX" ); 
+_LIT( KExtJpf, "JPF" );
+_LIT( KExtMbm, "MBM" ); 
+_LIT( KExtPng, "PNG" );
+_LIT( KExtGif, "GIF" );
+_LIT( KExtBmp, "BMP" );
+_LIT( KExtTif, "TIF" );
+_LIT( KExtTiff, "TIFF" );
+_LIT( KExtOta, "OTA" );
+_LIT( KExtWbmp, "WBMP" );
+_LIT( KExtWmf, "WMF" ); 
+_LIT( KExtOtb, "OTB" ); 
+
+#ifdef MDS_MULTIPLE_STAGE_IMAGE_PROCESSING
+const TUid KBGPSUid = { 0x0ADC2480 };
+#endif
+
+CHarvesterImagePluginPropertyDefs::CHarvesterImagePluginPropertyDefs() : CBase()
+	{
+	}
+
+void CHarvesterImagePluginPropertyDefs::ConstructL(CMdEObjectDef& aObjectDef)
+	{
+	CMdENamespaceDef& nsDef = aObjectDef.NamespaceDef();
+
+	// Image property definitions
+	CMdEObjectDef& objectDef = nsDef.GetObjectDefL( Object::KBaseObject );
+	iCreationDatePropertyDef = &objectDef.GetPropertyDefL( Object::KCreationDateProperty );
+	iLastModifiedDatePropertyDef = &objectDef.GetPropertyDefL( Object::KLastModifiedDateProperty );
+	iSizePropertyDef = &objectDef.GetPropertyDefL( Object::KSizeProperty );
+	iTimeOffsetPropertyDef = &objectDef.GetPropertyDefL( Object::KTimeOffsetProperty );
+	iItemTypePropertyDef = &objectDef.GetPropertyDefL( Object::KItemTypeProperty );
+
+	// Media property definitions
+	CMdEObjectDef& mediaDef = nsDef.GetObjectDefL( MediaObject::KMediaObject );
+	iWidthPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KWidthProperty );
+	iHeightPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KHeightProperty );
+	iDescriptionPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KDescriptionProperty );
+	iCommentPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KCommentProperty );
+	iReleaseDatePropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KReleaseDateProperty );
+	iCopyrightPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KCopyrightProperty );
+	iCaptureDatePropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KCaptureDateProperty );
+	iResolutionUnitPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KResolutionUnitProperty );
+	iArtistPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KArtistProperty );
+
+	// Image property definitions
+	CMdEObjectDef& imageDef = nsDef.GetObjectDefL( Image::KImageObject );
+	iPixelYDimensionPropertyDef = &imageDef.GetPropertyDefL( Image::KPixelYDimensionProperty );
+	iPixelXDimensionPropertyDef = &imageDef.GetPropertyDefL( Image::KPixelXDimensionProperty );
+	iBitsPerSamplePropertyDef = &imageDef.GetPropertyDefL( Image::KBitsPerSampleProperty );
+	iFrameCountPropertyDef = &imageDef.GetPropertyDefL( Image::KFrameCountProperty );
+	iDateTimeOriginalPropertyDef = &imageDef.GetPropertyDefL( Image::KDateTimeOriginalProperty );
+	iDateTimeDigitizedPropertyDef = &imageDef.GetPropertyDefL( Image::KDateTimeDigitizedProperty );
+	iDateTimePropertyDef = &imageDef.GetPropertyDefL( Image::KDateTimeProperty );
+	iWhiteBalancePropertyDef = &imageDef.GetPropertyDefL( Image::KWhiteBalanceProperty );
+	iFlashPropertyDef = &imageDef.GetPropertyDefL( Image::KFlashProperty );
+	iExposureProgramPropertyDef = &imageDef.GetPropertyDefL( Image::KExposureProgramProperty );
+	iMakePropertyDef = &imageDef.GetPropertyDefL( Image::KMakeProperty );
+	iModelPropertyDef = &imageDef.GetPropertyDefL( Image::KModelProperty );
+	iOrientationPropertyDef = &imageDef.GetPropertyDefL( Image::KOrientationProperty );
+	iXResolutionPropertyDef = &imageDef.GetPropertyDefL( Image::KXResolutionProperty );
+	iYResolutionPropertyDef = &imageDef.GetPropertyDefL( Image::KYResolutionProperty );
+	iYCbCrPositioningPropertyDef = &imageDef.GetPropertyDefL( Image::KYCbCrPositioningProperty );
+	iExposureTimePropertyDef = &imageDef.GetPropertyDefL( Image::KExposureTimeProperty );
+	iFNumberPropertyDef = &imageDef.GetPropertyDefL( Image::KFNumberProperty );
+	iExifVersionPropertyDef = &imageDef.GetPropertyDefL( Image::KExifVersionProperty );
+	iShutterSpeedValuePropertyDef = &imageDef.GetPropertyDefL( Image::KShutterSpeedValueProperty );
+	iApertureValuePropertyDef = &imageDef.GetPropertyDefL( Image::KApertureValueProperty );
+	iFocalLengthPropertyDef = &imageDef.GetPropertyDefL( Image::KFocalLengthProperty );
+	iFlashPixVersionPropertyDef = &imageDef.GetPropertyDefL( Image::KFlashPixVersionProperty );
+	iColourSpacePropertyDef = &imageDef.GetPropertyDefL( Image::KColourSpaceProperty );
+	iISOSpeedRatingsPropertyDef = &imageDef.GetPropertyDefL( Image::KISOSpeedRatingsProperty );
+	iComponentsConfigurationPropertyDef = &imageDef.GetPropertyDefL( Image::KComponentsConfigurationProperty );
+	iExposureBiasValuePropertyDef = &imageDef.GetPropertyDefL( Image::KExposureBiasValueProperty );
+	iSamplesPerPixelPropertyDef = &imageDef.GetPropertyDefL( Image::KSamplesPerPixelProperty );
+	iThumbCompressionPropertyDef = &imageDef.GetPropertyDefL( Image::KThumbCompressionProperty );
+	iThumbXResolutionPropertyDef = &imageDef.GetPropertyDefL( Image::KThumbXResolutionProperty );
+	iThumbYResolutionPropertyDef = &imageDef.GetPropertyDefL( Image::KThumbYResolutionProperty );
+	iThumbResolutionUnitPropertyDef = &imageDef.GetPropertyDefL( Image::KThumbResolutionUnitProperty );
+	iFocalLengthIn35mmFilmPropertyDef = &imageDef.GetPropertyDefL( Image::KFocalLengthIn35mmFilmProperty );
+	iMeteringModePropertyDef = &imageDef.GetPropertyDefL( Image::KMeteringModeProperty );
+	iRelatedSoundFilePropertyDef = &imageDef.GetPropertyDefL( Image::KRelatedSoundFileProperty );
+	iFocalPlaneResolutionUnitPropertyDef = &imageDef.GetPropertyDefL( Image::KFocalPlaneResolutionUnitProperty );
+	iFocalPlaneXResolutionPropertyDef = &imageDef.GetPropertyDefL( Image::KFocalPlaneXResolutionProperty );
+	iFocalPlaneYResolutionPropertyDef = &imageDef.GetPropertyDefL( Image::KFocalPlaneYResolutionProperty );
+	iDraftPropertyDef = &imageDef.GetPropertyDefL( Image::KDraftProperty );
+	}
+
+CHarvesterImagePluginPropertyDefs* CHarvesterImagePluginPropertyDefs::NewL(CMdEObjectDef& aObjectDef)
+	{
+	CHarvesterImagePluginPropertyDefs* self = 
+		new (ELeave) CHarvesterImagePluginPropertyDefs();
+	CleanupStack::PushL( self );
+	self->ConstructL( aObjectDef );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+/**
+* Default constructor
+*/
+CHarvesterImagePlugin::CHarvesterImagePlugin() : CHarvesterPlugin(),
+    iExifUtil( NULL ), iDecoder( NULL ), iPropDefs( NULL )
+	{
+	}
+
+/**
+* Construction
+* @return Harvester image plugin
+*/
+CHarvesterImagePlugin* CHarvesterImagePlugin::NewL()
+	{
+	WRITELOG( "CHarvesterImagePlugin::NewL()" );
+	CHarvesterImagePlugin* self = new (ELeave) CHarvesterImagePlugin();
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	
+	return self;
+	}
+
+/**
+* Destruction
+*/
+CHarvesterImagePlugin::~CHarvesterImagePlugin()
+	{
+	WRITELOG( "CHarvesterImagePlugin::~CHarvesterImagePlugin()" );
+	
+	if (iDecoder)
+		{
+		iDecoder->Reset();
+	    delete iDecoder;
+		}   
+    
+    if (iExifUtil)
+		{
+		delete iExifUtil;
+		}
+   	
+    delete iPropDefs;
+    
+    iFbs.Disconnect();
+	}
+
+/**
+* 2nd phase constructor
+*/
+void CHarvesterImagePlugin::ConstructL()
+	{
+	WRITELOG( "CHarvesterImagePlugin::ConstructL()" );
+	iDecoder = CBufferedImageDecoder::NewL( iFs );
+	iExifUtil = CHarvesterExifUtil::NewL();
+    User::LeaveIfError( iFbs.Connect() );
+
+    TLinearOrder< TMimeTypeMapping<TImageMetadataHandling> > cmp(
+    		TMimeTypeMapping<TImageMetadataHandling>::CompareFunction);
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtJpg(), KJpegMime(), EJpegHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtJpeg(), KJpegMime(), EJpegHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtGif(), KGifMime(), EGifHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtBmp(), KBmpMime(), EOtherHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtJpf(), KJpeg2000_2Mime(), EOtherHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtJpx(), KJpeg2000_2Mime(), EOtherHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtJp2(), KJpeg2000Mime(), EOtherHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtJ2k(), KJpeg2000Mime(), EOtherHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtMbm(), KMbmMime(), EOtherHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtOta(), KOtaMime(), EOtherHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtPng(), KPngMime(), EOtherHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtTif(), KTiffMime(), EOtherHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtTiff(), KTiffMime(), EOtherHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtWbmp(), KWbmpMime(), EOtherHandling ), cmp ) );
+
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+    		KExtWmf(), KWmfMime(), EOtherHandling ), cmp ) );
+    
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
+            KExtOtb(), KOtbMime(), EOtherHandling ), cmp ) );
+	}
+
+void CHarvesterImagePlugin::HarvestL( CHarvesterData* aHD )
+	{
+	WRITELOG( "CHarvesterImagePlugin::HarvestL()" );
+    CMdEObject& mdeObject = aHD->MdeObject();
+
+    CFileData* fileData = CFileData::NewL();
+    CleanupStack::PushL( fileData );
+    CHarvestData* harvestData = CHarvestData::NewL();
+    CleanupStack::PushL( harvestData );
+        
+    const TInt errorCode = GatherDataL( mdeObject, *fileData, *harvestData );
+    if ( errorCode == KErrNone || errorCode == KErrCompletion ) // ok, something got harvested
+        {
+        if ( mdeObject.Id() == 0 || mdeObject.Placeholder() ) // is a new object or placeholder
+            {
+            TRAP_IGNORE( HandleObjectPropertiesL( *harvestData, *fileData, *aHD, ETrue ) );
+            }
+        else   // not a new object
+            {
+            TRAP_IGNORE( HandleObjectPropertiesL( *harvestData, *fileData, *aHD, EFalse ) );
+            }
+        
+        if( harvestData->iStoreGpsLatitudeAndLongitude ||
+        	harvestData->iStoreGpsAltitude )
+        	{
+        	TLocationData* locData = new (ELeave) TLocationData();
+
+        	if( harvestData->iStoreGpsAltitude )
+        		{
+        		locData->iPosition.SetCoordinate( 
+        				harvestData->iGpsLatitude, harvestData->iGpsLongitude, 
+        				harvestData->iGpsAltitude);
+        		}
+        	else
+        		{
+        		locData->iPosition.SetCoordinate( 
+        				harvestData->iGpsLatitude, harvestData->iGpsLongitude);
+        		}
+
+        	// remove unnessesary values
+        	locData->iNetworkInfo.iAreaKnown = EFalse;
+        	
+        	TRealX nanX;
+        	nanX.SetNaN();
+        	nanX.GetTReal( locData->iQuality );
+        	
+        	aHD->SetLocationData( locData );
+        	}
+        }
+    else
+        {
+        WRITELOG1( "CHarvesterImagePlugin::HarvestL() - other error: %d", errorCode );
+        TInt convertedError = KErrNone;
+        MdsUtils::ConvertTrapError( errorCode, convertedError );
+        aHD->SetErrorCode( convertedError );
+        WRITELOG1( "CHarvesterImagePlugin::HarvestL() - returning: %d", convertedError );
+        }
+
+    // Delete image data.
+    CleanupStack::PopAndDestroy( 2, fileData );
+	}
+
+// ---------------------------------------------------------------------------
+// GatherData
+// ---------------------------------------------------------------------------
+//    
+TInt CHarvesterImagePlugin::GatherDataL( CMdEObject& aMetadataObject,
+    CFileData& aFileData, CHarvestData& aHarvestData )
+    {
+#ifdef _DEBUG
+    TTime dStart, dStop;
+    dStart.UniversalTime();
+    dStop.UniversalTime();
+    WRITELOG1( "CHarvesterImagePlugin::GatherData() start %d us", (TInt)dStop.MicroSecondsFrom(dStart).Int64() );
+#endif
+    
+    WRITELOG( "CHarvesterImagePlugin::GatherData()" );
+
+    TBool dataExtracted( aMetadataObject.Id() == 0 || aMetadataObject.Placeholder() );
+    aFileData.iImageDef = &aMetadataObject.Def();
+    
+    if( dataExtracted )
+        {
+        CMdEProperty* prop = NULL;
+        CMdEObjectDef& objectDef = *aFileData.iImageDef;
+        
+        if( !iPropDefs )
+        	{
+        	iPropDefs = CHarvesterImagePluginPropertyDefs::NewL( objectDef );
+        	}
+        
+        aMetadataObject.Property( *iPropDefs->iSizePropertyDef, prop );
+        if( prop )
+            {
+            aFileData.iFileSize  = prop->Uint32ValueL();
+            }
+        else
+            {
+            dataExtracted = EFalse;
+            }
+
+        aMetadataObject.Property( *iPropDefs->iLastModifiedDatePropertyDef, prop );
+        if( prop )
+            {
+            aFileData.iModified  = prop->TimeValueL();
+            }
+        else
+            {
+            dataExtracted = EFalse;
+            }
+        }
+
+    const TDesC& uri = aMetadataObject.Uri();
+    
+    if( !dataExtracted )
+        {
+        TEntry entry;
+        const TInt errorcode = iFs.Entry( uri, entry );
+        
+        if ( errorcode != KErrNone )
+            {
+            return errorcode; // metadata cannot be gathered!
+            }
+        
+        aFileData.iModified = entry.iModified;
+        aFileData.iFileSize = (TUint)entry.iSize;
+        }
+
+    TPtrC imageFile = uri;
+
+    aFileData.iUri = &imageFile;
+    aFileData.iFrameCount = 1;
+
+    TRAPD( readError, DataFromImageFileL( aFileData ) );
+
+    if ( readError != KErrNone )
+        {
+        WRITELOG1( "CHarvesterImagePlugin::GatherData() - error reading image data, error: %d", readError );
+        return KErrCompletion; // metadata item still can be created, thus KErrCompletion
+        }
+
+    TInt err = KErrNone;
+    if ( aFileData.iExifSupported )
+        {
+        TRAP( err, iExifUtil->ReadExifDataL( aHarvestData, aFileData ) );
+        }
+    if( !aFileData.iExifSupported || err != KErrNone )
+        {
+        // Exif couldn't be found. Open the image with ICL decoder instead.
+        WRITELOG( "CHarvesterImagePlugin::GatherData() - Exif could not be read. Using ICL." );
+
+        iDecoder->Reset();
+
+        TPtr8 imageDataPtr = aFileData.iImageData->Des();
+        TRAP( err, iDecoder->OpenL(imageDataPtr, aFileData.iMime8,
+                CImageDecoder::TOptions( CImageDecoder::EPreferFastDecode | CImageDecoder::EOptionIgnoreExifMetaData ) ) );
+        WRITELOG( "CHarvesterImagePlugin::GatherData() - Image decoder has opened the file." );
+
+        if ( err != KErrNone )
+            {
+            WRITELOG1( "CHarvesterImagePlugin::GatherData() - ERROR: Decoder could not open image data! Code %d", err );
+            return KErrCompletion; // metadata item still can be created, thus KErrCompletion
+            }
+
+        if ( !iDecoder->ValidDecoder() )
+        	{
+        	// read all remaining data from file
+        	TInt64 additionalDataSize = aFileData.iFileSize - aFileData.iImageDataSize;
+        	if( additionalDataSize < 0 )
+        	    {
+        	    additionalDataSize = 0;
+        	    }
+ 
+            HBufC8* additionalData = HBufC8::NewLC( additionalDataSize );
+			if ( additionalData )
+				{
+				TPtr8 addPtr = additionalData->Des();
+				TInt readStatus = iFs.ReadFileSection(
+						*aFileData.iUri, aFileData.iImageDataSize, addPtr, additionalDataSize );
+				if ( readStatus != KErrNone )
+					{
+					CleanupStack::PopAndDestroy( additionalData );
+					return KErrCompletion;
+					}
+				
+				// append all remaining data to image decoder
+				TRAP( err, iDecoder->AppendDataL( addPtr ) );
+				if ( err == KErrNone )
+					{
+					TRAP( err, iDecoder->ContinueOpenL() );
+					}
+				CleanupStack::PopAndDestroy( additionalData );
+				}
+
+            if ( err || !iDecoder->ValidDecoder() )
+            	{
+            	WRITELOG( "CHarvesterImagePlugin::GatherData() - ERROR: no valid decoder" );
+            	return KErrCompletion; // metadata item still can be created, thus KErrCompletion
+            	}
+            }
+
+        // Get image width, frame count, height and bits per pixel from image decoder.
+        const TFrameInfo info = iDecoder->FrameInfo( 0 );
+        const TSize imageSize = info.iOverallSizeInPixels;
+        const TInt framecount = iDecoder->FrameCount();
+        aFileData.iFrameCount = framecount;
+        aFileData.iImageWidth = imageSize.iWidth;
+        aFileData.iImageHeight = imageSize.iHeight;
+        aFileData.iBitsPerPixel = info.iBitsPerPixel;
+        }
+
+    WRITELOG( "CHarvesterImagePlugin::GatherData() - end" );
+
+#ifdef _DEBUG
+    dStop.UniversalTime();
+    WRITELOG1( "CHarvesterImagePlugin::GatherData() end %d us", (TInt)dStop.MicroSecondsFrom(dStart).Int64() );
+#endif   
+
+    return KErrNone;
+    }
+
+///---------------------------------------------------------------------------
+/// DataFromImageFile
+///---------------------------------------------------------------------------
+void CHarvesterImagePlugin::DataFromImageFileL( CFileData& aFileData )
+    {
+    WRITELOG( "CHarvesterImagePlugin::DataFromImageFileL()" );
+    
+    TPtrC ext;
+    if( !MdsUtils::GetExt( *aFileData.iUri, ext ) )
+    	{
+    	User::Leave( KErrNotSupported );
+    	}
+
+	TMimeTypeMapping<TImageMetadataHandling> finder(ext);
+	TLinearOrder< TMimeTypeMapping<TImageMetadataHandling> > cmp(
+			TMimeTypeMapping<TImageMetadataHandling>::CompareFunction);
+
+	TInt pos = iMimeTypeMappings.FindInOrder( finder, cmp );
+
+	TImageMetadataHandling handler( EOtherHandling ); 
+
+	if ( pos != KErrNotFound )
+		{
+		handler = iMimeTypeMappings[pos].iHandler;
+		}
+
+    switch( handler )
+    	{
+    	case EJpegHandling:
+			{
+			aFileData.iJpeg = ETrue;
+			const TInt K64Kb = 65536;
+			aFileData.iImageDataSize = K64Kb;
+			WRITELOG( "CHarvesterImagePlugin::DataFromImageFileL() - read first 64Kb from JPEG" );
+			break;
+			}
+    	case EGifHandling:
+    		{
+    		aFileData.iJpeg = EFalse;
+    		aFileData.iImageDataSize = aFileData.iFileSize;
+			WRITELOG( "CHarvesterImagePlugin::DataFromImageFileL() - read whole GIF file" );
+    		break;
+    		}
+    	default:
+    		{
+    		aFileData.iJpeg = EFalse;
+			const TInt K4Kb = 4096;
+			aFileData.iImageDataSize = K4Kb; 
+			WRITELOG1( "CHarvesterImagePlugin::DataFromImageFileL() - read first %d bytes from image", aFileData.iImageDataSize );
+    		}
+    	}	
+
+    aFileData.iImageData = HBufC8::NewL( aFileData.iImageDataSize );
+    TPtr8 myImagePtr = aFileData.iImageData->Des();
+
+    const TInt readStatus = iFs.ReadFileSection(
+    		*aFileData.iUri, 0, myImagePtr, aFileData.iImageDataSize );
+    if ( readStatus != KErrNone )
+        {
+        WRITELOG( "CHarvesterImagePlugin::DataFromImageFileL() - ERROR: file could not be read!" );
+        User::Leave( readStatus );
+        }
+
+    // extension was in mapping list, so use that 
+	if ( pos != KErrNotFound )
+		{
+		aFileData.iMime8.Copy( iMimeTypeMappings[pos].iMimeType );
+		aFileData.iMime16.Copy( aFileData.iMime8 );
+		}
+	// otherwise try to recognize using image decoder
+    else
+        {
+        CImageDecoder::GetMimeTypeDataL( myImagePtr, aFileData.iMime8 );
+        aFileData.iMime16.Copy( aFileData.iMime8 );
+
+        // Check if MIME type is supported
+        User::LeaveIfError( CheckIfMimeSupported( aFileData.iMime16 ) );
+        }
+
+    // If is jpeg get EXIF data
+    if ( aFileData.iJpeg )
+        {
+        if( iExifUtil->IsValidExifData(myImagePtr) )
+            {
+            WRITELOG( "CHarvesterImagePlugin::DataFromImageFileL() - exif data found!" );
+            aFileData.iExifSupported = ETrue;
+            }
+        else
+            {
+            WRITELOG( "CHarvesterImagePlugin::DataFromImageFileL() - no exif data!" );
+            aFileData.iImageDataSize = aFileData.iFileSize;
+            aFileData.iExifSupported = EFalse;
+            }
+        }
+    
+    WRITELOG( "CHarvesterImagePlugin::DataFromImageFileL() - reading IMAGE file done!" );
+    }
+
+// ---------------------------------------------------------------------------
+// HandleNewObjectL
+// ---------------------------------------------------------------------------
+//    
+void CHarvesterImagePlugin::HandleObjectPropertiesL(
+		CHarvestData& aHd,
+		CFileData& aFileData,
+		CHarvesterData& aHarvesterData,
+		TBool aIsAdd )
+    {
+    WRITELOG( "CHarvesterImagePlugin::HandleObjectPropertiesL() - New MdE object" );
+    
+    CMdEObject& mdeObject = aHarvesterData.MdeObject();
+    
+    if( !iPropDefs )
+    	{
+    	iPropDefs = CHarvesterImagePluginPropertyDefs::NewL( mdeObject.Def() );
+    	}
+
+    TTimeIntervalSeconds timeOffsetSeconds = User::UTCOffset();
+
+    TTime localModifiedDate = aFileData.iModified + timeOffsetSeconds;
+    
+    // Object - Creation date
+    if( ! mdeObject.Placeholder() )
+    	{
+	    if ( aFileData.iExifSupported && aHd.iDateOriginal8 )
+	        {
+	        TTime originalTime = iExifUtil->ConvertExifDateTimeToSymbianTimeL(
+	        		aHd.iDateOriginal8->Des() );
+	        CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iCreationDatePropertyDef, &originalTime, aIsAdd );
+	        }
+	    else if ( aIsAdd )
+	        {
+	        CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iCreationDatePropertyDef, &localModifiedDate, aIsAdd );
+	        }
+    	}
+
+    // Object - last aFileData.iModified date
+    if( ! mdeObject.Placeholder() )
+    	{
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iLastModifiedDatePropertyDef, &aFileData.iModified, aIsAdd );
+    	}
+
+    if( aFileData.iJpeg )
+    	{
+    	// Time offset
+    	TInt16 timeOffsetMinutes = timeOffsetSeconds.Int() / 60;
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iTimeOffsetPropertyDef, &timeOffsetMinutes, aIsAdd );
+    	}
+
+    // Object - Size
+    if( ! mdeObject.Placeholder() )
+    	{
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iSizePropertyDef, &aFileData.iFileSize, aIsAdd );
+    	}
+    
+    // Item Type
+	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iItemTypePropertyDef, &aFileData.iMime16, aIsAdd );
+    
+    // MediaObject - Width
+    if ( aFileData.iExifSupported )
+        {
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iWidthPropertyDef, &aHd.iImageWidthExif, aIsAdd );
+
+        // If pixelXDimension tag is found, save its value to both Width and PixelXDimension in DB.
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iPixelXDimensionPropertyDef, &aHd.iImageWidthExif, aIsAdd );
+        }
+    else if (aFileData.iImageWidth != 0)
+        {
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iWidthPropertyDef, &aFileData.iImageWidth, aIsAdd );
+        }
+    
+    // MediaObject - Height
+    if ( aFileData.iExifSupported )
+        {
+        CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iHeightPropertyDef, &aHd.iImageHeightExif, aIsAdd );
+        
+        // If pixelYDimension tag is found, save its value to both Height and PixelYDimension in DB.
+        CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iPixelYDimensionPropertyDef, &aHd.iImageHeightExif, aIsAdd );
+        }
+    else if (aFileData.iImageHeight != 0)
+        {
+        CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iHeightPropertyDef, &aFileData.iImageHeight, aIsAdd );
+        } 
+
+#ifdef MDS_MULTIPLE_STAGE_IMAGE_PROCESSING
+    TBool draftVal = ETrue;
+    if( aIsAdd )
+        {
+        if( aHarvesterData.Origin() != MdeConstants::Object::ECamera )
+            {
+            draftVal = EFalse;
+            }
+        CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iDraftPropertyDef, &draftVal, aIsAdd );
+        }
+    else
+        {
+        if( aHarvesterData.ClientId() == KBGPSUid )
+            {
+            draftVal = EFalse;
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iDraftPropertyDef, &draftVal, aIsAdd );
+            }
+        }
+#endif
+    
+    // Image - Bits per Sample
+    if (aFileData.iBitsPerPixel != 0)
+        {
+        CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iBitsPerSamplePropertyDef, &aFileData.iBitsPerPixel, aIsAdd );
+        }
+
+    // Image - Framecount
+    CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iFrameCountPropertyDef, &aFileData.iFrameCount, aIsAdd );
+
+    // If is jpeg write EXIF data
+    if ( aFileData.iExifSupported )
+        {
+       	// MediaObject - Description
+       	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iDescriptionPropertyDef, aHd.iDescription16, aIsAdd );
+
+        // MediaObject - Comment (user comment)
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iCommentPropertyDef, aHd.iComment16, aIsAdd );
+        
+        // MediaObject - Release date
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iReleaseDatePropertyDef, &localModifiedDate, aIsAdd );
+
+        // MediaObject - Copyright
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iCopyrightPropertyDef, aHd.iCopyright16, aIsAdd );
+        
+        // Data & time original
+        if ( aHd.iDateOriginal8 )
+            {
+            TTime originalTime = iExifUtil->ConvertExifDateTimeToSymbianTimeL( aHd.iDateOriginal8->Des() );
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iDateTimeOriginalPropertyDef, &originalTime, aIsAdd );
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iCaptureDatePropertyDef, &originalTime, aIsAdd );
+            if( originalTime.Int64() == 0 )
+                {
+                CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iCreationDatePropertyDef, &localModifiedDate, EFalse );
+                }
+            else
+                {
+                CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iCreationDatePropertyDef, &originalTime, EFalse );
+                }
+            }
+        
+        // Date & time digitized
+        if ( aHd.iDateDigitized8 )
+            {
+            TTime digitizedTime = iExifUtil->ConvertExifDateTimeToSymbianTimeL( aHd.iDateDigitized8->Des() );
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iDateTimeDigitizedPropertyDef, &digitizedTime, aIsAdd );
+            }
+
+        // Date & time aFileData.iModified (DateTime tag)
+        if ( aHd.iDateModified8 )
+            {
+            TTime modifiedTime = iExifUtil->ConvertExifDateTimeToSymbianTimeL(
+            		aHd.iDateModified8->Des() );
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iDateTimePropertyDef, &modifiedTime, aIsAdd );
+            }
+        
+        // Artist    
+        CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iArtistPropertyDef, aHd.iArtist, aIsAdd );
+
+        // Image - White balance
+        if ( aHd.iStoreWhiteBalance )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iWhiteBalancePropertyDef, &aHd.iWhiteBalance, aIsAdd );
+            }
+         
+        // Image - Flash
+        if ( aHd.iStoreFlash )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iFlashPropertyDef, &aHd.iFlash, aIsAdd );
+            }
+        
+        // Image - Exposure program                
+        if ( aHd.iStoreExposureProgram )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iExposureProgramPropertyDef, &aHd.iExposureProgram, aIsAdd );
+            }     
+         
+         // Make string            
+        CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iMakePropertyDef, aHd.iMake, aIsAdd );
+            
+        // Model string
+        CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iModelPropertyDef, aHd.iModel, aIsAdd );
+                    
+        // Orientation
+        if ( aHd.iStoreOrientation )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iOrientationPropertyDef, &aHd.iOrientation, aIsAdd );
+            }
+            
+        // X resolution    
+        if ( aHd.iStoreXResolution )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iXResolutionPropertyDef, &aHd.iXResolution, aIsAdd );
+            }
+            
+        // Y resolution    
+        if ( aHd.iStoreYResolution )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iYResolutionPropertyDef, &aHd.iYResolution, aIsAdd );
+            }
+            
+        // Resolution unit
+        CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iResolutionUnitPropertyDef, &aHd.iResolutionUnit, aIsAdd );
+        
+        // YCbCrPositioning
+        if ( aHd.iStoreYCbCrPositioning )    
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iYCbCrPositioningPropertyDef, &aHd.iYCbCrPositioning, aIsAdd );
+            }
+        
+        // Exposure time                
+        if ( aHd.iStoreExposureTime )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iExposureTimePropertyDef, &aHd.iExposureTime, aIsAdd );
+            }
+            
+        // F number
+        if ( aHd.iStoreFNumber )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iFNumberPropertyDef, &aHd.iFNumber, aIsAdd );
+            }
+            
+        // EXIF version                
+        if ( aHd.iStoreExifVersion )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iExifVersionPropertyDef, &aHd.iExifVersion, aIsAdd );
+            }
+        
+        //     Shutter speed
+        if ( aHd.iStoreShutterSpeed )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iShutterSpeedValuePropertyDef, &aHd.iShutterSpeed, aIsAdd );
+            }
+            
+        // Aperture    
+        if ( aHd.iStoreAperture )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iApertureValuePropertyDef, &aHd.iAperture, aIsAdd );
+            }
+        
+        // Focal length        
+        if ( aHd.iStoreFocalLength )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iFocalLengthPropertyDef, &aHd.iFocalLength, aIsAdd );
+            }
+            
+        // FlashPix version    
+        if ( aHd.iStoreFlashPixVersion )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iFlashPixVersionPropertyDef, &aHd.iFlashPixVersion, aIsAdd );
+            }
+            
+        // Colour space            
+        if ( aHd.iStoreColourSpace )    
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iColourSpacePropertyDef, &aHd.iColourSpace, aIsAdd );
+            }
+            
+        // ISO speed rating            
+        if ( aHd.iStoreIsoSpeedRating )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iISOSpeedRatingsPropertyDef, &aHd.iIsoSpeedRating, aIsAdd );
+            }
+        
+        // Components configuration    
+        if ( aHd.iStoreComponentsConfig )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iComponentsConfigurationPropertyDef, &aHd.iComponentsConfiguration, aIsAdd );
+            }
+        
+        // Exposure bias value        
+        if ( aHd.iStoreExposureBias )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iExposureBiasValuePropertyDef, &aHd.iExposureBias, aIsAdd );
+            }
+            
+        // Samples per pixel    
+        if ( aHd.iStoreSamplesPerPixel )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iSamplesPerPixelPropertyDef, &aHd.iSamplesPerPixel, aIsAdd );
+            }
+            
+        // Thumbnail compression                
+        if ( aHd.iStoreThumbCompression )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iThumbCompressionPropertyDef, &aHd.iThumbCompression, aIsAdd );
+            }
+            
+        // Thumbnail X resolution    
+        if ( aHd.iStoreThumbXResolution )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iThumbXResolutionPropertyDef, &aHd.iThumbXResolution, aIsAdd );
+            }
+            
+        // Thumbnail Y resolution            
+        if ( aHd.iStoreThumbYResolution )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iThumbYResolutionPropertyDef, &aHd.iThumbYResolution, aIsAdd );
+            }
+            
+        // Thumbnail resolution unit    
+        if ( aHd.iStoreThumbResolutionUnit )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iThumbResolutionUnitPropertyDef, &aHd.iThumbResolutionUnit, aIsAdd );
+            }
+        
+        // Focal length in 35 mm    
+        if ( aHd.iStoreFocalLengthIn35 )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iFocalLengthIn35mmFilmPropertyDef, &aHd.iFocalLengthIn35mm, aIsAdd );
+            }
+            
+        // Metering mode                
+        if ( aHd.iStoreMeteringMode )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iMeteringModePropertyDef, &aHd.iMeteringMode, aIsAdd );
+            }
+            
+        // Related soundfile            
+        if ( aHd.iRelatedSoundFile && aHd.iRelatedSoundFile->Length() > 0 )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iRelatedSoundFilePropertyDef, aHd.iRelatedSoundFile, aIsAdd );
+            }
+        
+        // Focal plane resolution unit
+        if ( aHd.iStoreFocalPlaneResolutionUnit )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iFocalPlaneResolutionUnitPropertyDef, &aHd.iFocalPlaneResolutionUnit, aIsAdd );
+            }
+            
+        // Focal plane X resolution
+        if ( aHd.iStoreFocalPlaneXResolution )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iFocalPlaneXResolutionPropertyDef, &aHd.iFocalPlaneXResolution, aIsAdd );
+            }
+            
+        // Focal plane Y resolution
+        if ( aHd.iStoreFocalPlaneYResolution )
+            {
+            CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iFocalPlaneYResolutionPropertyDef, &aHd.iFocalPlaneYResolution, aIsAdd );
+            }
+        WRITELOG( "CHarvesterImagePlugin::HandleObjectPropertiesL() - All EXIF tags added." );
+        }
+    }
+
+//---------------------------------------------------------------------------
+// CheckIfMimeSupported
+//---------------------------------------------------------------------------
+//
+TInt CHarvesterImagePlugin::CheckIfMimeSupported(const TDesC& aMimeBuf)
+    {
+    if ( MdsUtils::Compare(KJpegMime, aMimeBuf) == 0
+            || MdsUtils::Compare(KJpeg2000Mime, aMimeBuf) == 0
+            || MdsUtils::Compare(KJpeg2000_2Mime, aMimeBuf) == 0
+            || MdsUtils::Compare(KPngMime, aMimeBuf) == 0
+            || MdsUtils::Compare(KGifMime, aMimeBuf) == 0
+            || MdsUtils::Compare(KBmpMime, aMimeBuf) == 0
+            || MdsUtils::Compare(KMsmMime, aMimeBuf) == 0
+            || MdsUtils::Compare(KXbmpMime, aMimeBuf) == 0
+            || MdsUtils::Compare(KWbmpMime, aMimeBuf) == 0
+            || MdsUtils::Compare(KMbmMime, aMimeBuf) == 0
+            || MdsUtils::Compare(KTiffMime, aMimeBuf) == 0
+            || MdsUtils::Compare(KOtaMime, aMimeBuf) == 0
+            || MdsUtils::Compare(KXotaMime, aMimeBuf) == 0
+            || MdsUtils::Compare(KWmfMime, aMimeBuf) == 0 )
+
+    	{
+        return KErrNone;
+        }
+    
+    return KErrNotSupported;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/ImagePlugin/src/proxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester image plugin
+*
+*/
+
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include "harvesterimageplugin.h"
+
+// Map the interface UIDs to implementation factory functions
+const TImplementationProxy KImplementationTable[] = 
+	{
+		{{0x200009FC},	(TProxyNewLPtr)CHarvesterImagePlugin::NewL}
+	};
+
+// Exported proxy for instantiation method resolution
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+	{
+	aTableCount = sizeof(KImplementationTable) / sizeof(TImplementationProxy);
+	return KImplementationTable;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/MessagePlugin/data/102823c8.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// 1CA032F6.RSS
+
+#include "registryinfov2.rh"
+	
+// Declares info for one test implementation
+RESOURCE REGISTRY_INFO theInfo
+	{
+  // resource_format_version must always be set as follows
+  resource_format_version = RESOURCE_FORMAT_VERSION_2;
+  
+	// UID for the DLL
+	dll_uid = 0x102823C8;
+	// Declare array of interface info
+	interfaces = 
+		{
+		INTERFACE_INFO
+			{
+			// UID of interface that is implemented
+			interface_uid = 0x200009F8;
+			implementations = 
+				{
+				// Info for CHarvesterMessagePlugin
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x102823C9;
+					version_no = 1;
+					display_name = "Harvester Message plugin";
+					default_data = "Message";
+                    opaque_data = "msg";
+          rom_only = 0;
+					}
+				};
+			}
+		};
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/MessagePlugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+harvestermessageplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/MessagePlugin/group/harvestermessageplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        HarvesterMessagePlugin.dll
+TARGETTYPE    PLUGIN
+UID           0x10009D8D 0x102823C8
+
+CAPABILITY 	  CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+SOURCEPATH    ../src
+SOURCE        harvestermessageplugin.cpp
+SOURCE        proxy.cpp
+
+USERINCLUDE   ../../../../inc
+USERINCLUDE   ../../../common/inc
+USERINCLUDE   ../inc
+
+SYSTEMINCLUDE /epoc32/include/ecom
+
+SOURCEPATH    ../data
+START RESOURCE 102823c8.rss
+target HarvesterMessagePlugin.rsc
+END
+
+APP_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+
+LIBRARY       HarvesterPluginInterface.lib
+LIBRARY       MdEClient.lib
+LIBRARY	  msgs.lib
+LIBRARY	  gsmu.lib
+LIBRARY	  harvesterdata.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/MessagePlugin/inc/harvestermessageplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,169 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvests metadata from sms/mms messages.*
+*/
+
+
+#ifndef __CHARVESTERMESSAGEPLUGIN_H__
+#define __CHARVESTERMESSAGEPLUGIN_H__
+
+#include <mdeobject.h>
+#include <fbs.h>
+#include <msvapi.h>
+
+#include "harvesterplugin.h"
+#include "monitorplugin.h"
+
+// forward declarations
+class CHarvesterMessagePluginAO;
+class CMsvSession;
+class CClientMtmRegistry;
+class CMmsClientMtm;
+class CSmsClientMtm;
+
+/**
+ * Message harvester plug-in.
+ * Harvests metadata from sms/mms messages.
+ * Implements CHarvesterPlugin.
+ */
+class CHarvesterMessagePlugin : public CHarvesterPlugin,
+								public MMsvSessionObserver
+    {
+    public:
+
+        /**
+        * Construction
+        * @return Harvester image plugin
+        */
+        static CHarvesterMessagePlugin* NewL();
+
+        /**
+        * Destruction
+        */
+        virtual ~CHarvesterMessagePlugin();
+
+		/**
+		* @param aHD harvester data type
+		*/
+		void HarvestL( CHarvesterData* aHD );
+		
+		/**
+        * From MMsvSessionObserver
+        */
+        virtual void HandleSessionEventL( TMsvSessionEvent aEvent, 
+                                          TAny* aArg1, 
+                                          TAny* aArg2, 
+                                          TAny* aArg3 );
+		
+    private:
+    
+        /**
+         * Default constructor
+         */
+        CHarvesterMessagePlugin();
+        
+        /**
+         * 2nd phase constructor.
+         */
+        void ConstructL();
+        
+        /**
+         * The method that actually extracts the metadata
+         * @param aMetadataObject  Metadata object which is filled with metadata
+         * @return Error code which indicates status of the operation
+         */                
+         TInt GatherDataL( CMdEObject& aMetadataObject );
+         
+         /**
+         * It takes const ref to two THarvestResult objects and returns zero if 
+         * the iUri of objects are equal, a negative value if aFirst is less than aSecond and 
+         * a positive value if aFirst is greater than aSecond. 
+         * @param aFirst
+         * @param aSecond   
+         * @return returns zero if the objects are equal, a negative value if aFirst 
+         * is less than aSecond and a positive value if aFirst is greater than aSecond. 
+         */   
+         static TInt CompareByUri( const THarvestResult& aFirst, const THarvestResult& aSecond );
+         
+         /**
+         * It takes const ref to two CMdEObject objects and returns zero if 
+         * the id of objects are equal, a negative value if aFirst is less than aSecond and 
+         * a positive value if aFirst is greater than aSecond. 
+         * @param aFirst
+         * @param aSecond   
+         * @return returns zero if the objects are equal, a negative value if aFirst 
+         * is less than aSecond and a positive value if aFirst is greater than aSecond. 
+         */   
+         static TInt CompareById( const CMdEObject& aFirst, const CMdEObject& aSecond );    
+         
+         /**
+          *
+          */
+         void SetPropertiesL(CHarvesterData& aHD);
+    
+    private:
+    	
+		/**
+		 * Session Message server session, own
+		 */
+		 CMsvSession* iMsvSession;
+    
+		 /**
+        * iMTMReg Accesses the MTM on the message server
+        */
+        CClientMtmRegistry* iMtmReg;    
+        
+        /**
+        * iMmsMtm Access MMS messages on the message server
+        */
+        CMmsClientMtm* iMmsMtm;    
+        
+        /**
+        * iSmsMtm Access SMS messages on the message server
+        */
+        CSmsClientMtm* iSmsMtm;
+        
+        /**
+         *
+         */
+        HBufC* iFromOrTo;
+        
+        /**
+         *
+         */
+        TInt64 iSize;
+        
+        /**
+         *
+         */
+        TBool iIncoming;
+        
+        /**
+         *
+         */
+        TTime iDate;
+        
+        /**
+         *
+         */
+        TPtrC iItemType;
+        
+        /**
+         *
+         */
+        TPtrC iSubject;
+    };
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/MessagePlugin/src/harvestermessageplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,430 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester image plugin
+*
+*/
+
+
+#include <e32base.h>
+#include <smsclnt.h>
+#include <smuthdr.h>
+#include <smsclnt.h>
+#include <smut.h>
+#include <gsmuelem.h>
+#include <msventry.h>
+#include <msvuids.h>
+#include <mmsconst.h>
+#include <mtclreg.h>
+#include <mmsclient.h>
+#include <mdetextproperty.h>
+
+#include "harvestermessageplugin.h"
+#include "harvesterlog.h"
+#include "mdsutils.h"
+#include "mdeobjectdef.h"
+
+#ifdef _DEBUG
+_LIT( KMsgHarvesterMsvPanic, "Message harvester: Message server terminated" );
+#endif
+_LIT( KSemicolonSpace, "; " );
+_LIT( KCharSpace, " " );
+_LIT( KCharLeftAddressIterator, "<" );
+_LIT( KCharRightAddressIterator, ">" );
+
+/**
+* Default constructor
+*/
+CHarvesterMessagePlugin::CHarvesterMessagePlugin() : CHarvesterPlugin()
+	, iItemType(NULL, 0)
+	, iSubject(NULL, 0)
+	{
+	}
+
+/**
+* Construction
+* @return Harvester image plugin
+*/
+CHarvesterMessagePlugin* CHarvesterMessagePlugin::NewL()
+	{
+	WRITELOG("CHarvesterMessagePlugin::NewL()");
+	CHarvesterMessagePlugin* self = new(ELeave) CHarvesterMessagePlugin();
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(self);
+	
+	return self;
+	}
+
+/**
+* Destruction
+*/
+CHarvesterMessagePlugin::~CHarvesterMessagePlugin()
+	{
+	WRITELOG("CHarvesterMessagePlugin::~CHarvesterMessagePlugin()");
+	delete iMmsMtm;
+	delete iSmsMtm;
+	delete iMtmReg;
+	delete iMsvSession;  
+	}
+
+/**
+* 2nd phase constructor
+*/
+void CHarvesterMessagePlugin::ConstructL()
+	{
+	WRITELOG("CHarvesterMessagePlugin::ConstructL()");
+	if ( iMsvSession )
+		{
+		delete iMsvSession;
+		iMsvSession = NULL;
+		}
+	iMsvSession = CMsvSession::OpenSyncL( *this ); 
+	
+	iMtmReg = CClientMtmRegistry::NewL( *iMsvSession );
+    iMmsMtm = static_cast<CMmsClientMtm*>
+                ( iMtmReg->NewMtmL( KUidMsgTypeMultimedia ) );
+	iSmsMtm = static_cast<CSmsClientMtm*>
+                ( iMtmReg->NewMtmL( KUidMsgTypeSMS ) );
+
+	}
+
+void CHarvesterMessagePlugin::HarvestL( CHarvesterData* aHD )
+	{
+	CMdEObject& mdeObject = aHD->MdeObject();
+    mdeObject.SetMediaId( 0 );
+
+    TRAPD( error, GatherDataL( mdeObject ) );
+    if ( error != KErrNone )
+        {
+        WRITELOG1( "CHarvesterMessagePlugin::HarvestSingleFileL() - TRAP error: %d", error );
+        TInt convertedError = KErrNone;
+        MdsUtils::ConvertTrapError( error, convertedError );
+        aHD->SetErrorCode( convertedError );
+        return;
+        }
+    
+#ifdef _DEBUG    
+    TRAP(error, SetPropertiesL( *aHD ));
+
+    if ( error != KErrNone )
+        {
+        WRITELOG1( "CHarvesterMessagePlugin::HarvestSingleFileL() - Handling object failed: %d", error );
+        }
+#else
+    TRAP_IGNORE( SetPropertiesL( *aHD ) );
+#endif        
+
+	}
+
+// ---------------------------------------------------------------------------
+// CHarvesterMessagePlugin::GatherDataL
+// ---------------------------------------------------------------------------
+//	
+TInt CHarvesterMessagePlugin::GatherDataL( CMdEObject& aMetadataObject )
+	{
+			
+    WRITELOG( "CHarvesterMessagePlugin::GatherDataL enter" );
+    const TChar KPoint( '.' );
+            
+	const TDesC& uri = aMetadataObject.Uri();
+	const TInt i = uri.Locate( KPoint );
+	TMsvId msgId( 0 );	
+
+    TLex lex( uri.Left( i ) );
+    lex.Val( msgId );
+	WRITELOG1( "msgId: %d", msgId );     	
+    
+	TMsvId service = 0;
+    TMsvEntry tEntry;
+	TInt err = iMsvSession->GetEntry( msgId, service, tEntry );    
+	User::LeaveIfError( err );
+        
+	CBaseMtm* actMtm( iSmsMtm ); 
+	
+	WRITELOG1( "tEntry.iMtm.iUid: %d", tEntry.iMtm.iUid );     	
+	
+	
+	if ( tEntry.iMtm.iUid == KUidMsgTypeMultimedia.iUid )
+		{
+		WRITELOG( "MMS MESSAGE" );
+		actMtm = iMmsMtm;
+		}
+	actMtm->SwitchCurrentEntryL( msgId );
+	actMtm->LoadMessageL();
+	
+	tEntry = actMtm->Entry().Entry();
+	
+	WRITELOG1( "tEntry.iMtm.iUid: %d", tEntry.iMtm.iUid );     		
+	
+	TMsvId parentId = tEntry.Parent();
+	
+	WRITELOG1( "parentId: %d", parentId );     		
+	
+	iSize = (TUint)tEntry.iSize;
+	
+	WRITELOG1( "size: %d", iSize );     			
+	
+	iDate = tEntry.iDate;
+	
+#ifdef _DEBUG
+	WRITELOG1( "date.DaysInMonth: %d", iDate.DaysInMonth() );
+#endif
+	
+	delete iFromOrTo;
+	iFromOrTo = NULL;
+	
+	if ( KMsvSentEntryId == parentId )	// sent
+		{		
+		iIncoming = EFalse;
+        const CDesCArray& array = static_cast<const CDesCArray&>(
+            actMtm->AddresseeList().RecipientList() );
+        TInt count( array.Count() );
+        TInt maxLength( 0 );
+            
+        for ( TInt i( 0 ); i < count; ++i )
+        	{
+        	maxLength += array[i].Length();
+        	}
+		WRITELOG1( "maxLength: %d", maxLength );     		
+        	
+		iFromOrTo = HBufC::NewL( maxLength + 3 * count );
+		TPtr desReceipients( iFromOrTo->Des() ) ;
+		
+        for ( TInt i( 0 ); i < count; ++i )
+        	{
+        	desReceipients.Append( array[i] );
+       		desReceipients.Append( KSemicolonSpace );        		
+        	}	
+        count = desReceipients.Length();
+		WRITELOG1("count: %d", count );     		
+        
+        if ( count )
+        	{        	
+        	desReceipients.Delete( count - 2, 2 );
+        	}
+		}
+	else	// KMsvGlobalInBoxIndexEntryId received
+		{
+		iIncoming = ETrue;
+		WRITELOG( "Got incoming" );
+		
+		HBufC* senderNumber = NULL;
+		if ( tEntry.iMtm.iUid == KUidMsgTypeMultimedia.iUid )
+			{
+			senderNumber = iMmsMtm->Sender().AllocLC();
+			}
+		else
+			{
+			senderNumber= iSmsMtm->SmsHeader().FromAddress().AllocLC();
+			}
+
+        TInt senderLength = senderNumber->Length();
+        if ( senderLength > 0 )
+            {
+            // Check if we have an alias
+            if ( senderNumber->Compare( tEntry.iDetails ) )
+            	{
+                // Additional space for chars: '<' '>' ','
+            	senderLength += KCharSpace.iTypeLength +
+					KCharLeftAddressIterator.iTypeLength +
+					KCharRightAddressIterator.iTypeLength;
+            	
+                iFromOrTo = HBufC::NewL( tEntry.iDetails.Length() + senderLength );
+                TPtr fromTextPtr = iFromOrTo->Des();
+                fromTextPtr.Append( tEntry.iDetails );
+                fromTextPtr.Append( KCharSpace );
+                fromTextPtr.Append( KCharLeftAddressIterator );
+                fromTextPtr.Append( *senderNumber );
+                fromTextPtr.Append( KCharRightAddressIterator );
+            	}
+            else
+                {
+                iFromOrTo = senderNumber->AllocL();
+                }
+            }
+        else
+            {
+            iFromOrTo = senderNumber->AllocL();
+            }
+        
+        CleanupStack::PopAndDestroy( senderNumber );
+		}
+
+	// Set subject - MMS has subject but SMS doesn't have one
+	if ( tEntry.iMtm.iUid == KUidMsgTypeMultimedia.iUid )
+		{
+		iItemType.Set( MdeConstants::Message::KMMSItemType );
+		iSubject.Set( iMmsMtm->SubjectL() );
+		}
+	else
+		{
+		iItemType.Set( MdeConstants::Message::KSMSItemType );
+		iSubject.Set( KNullDesC );
+		}
+		
+	WRITELOG1( "fromOrTo: %S", iFromOrTo );
+	WRITELOG1( "incoming: %b", iIncoming );     		
+	
+	WRITELOG( "CHarvesterMessagePlugin::GatherDataL return" );
+	return KErrNone;	
+	}
+
+void CHarvesterMessagePlugin::SetPropertiesL( CHarvesterData& aHD )
+	{	    
+	WRITELOG( "CHarvesterMessagePlugin::SetPropertiesL enter" );
+	CMdEObject& aMetadataObject = aHD.MdeObject();
+	
+	CMdEObjectDef& messageObjectDef = aMetadataObject.Def();
+	
+	CMdEPropertyDef& creationTimeDef = messageObjectDef.GetPropertyDefL( 									  
+		MdeConstants::Object::KCreationDateProperty ) ;
+	
+	CMdEPropertyDef& lastModTimeDef = messageObjectDef.GetPropertyDefL(
+        MdeConstants::Object::KLastModifiedDateProperty ) ;									  	
+
+	CMdEPropertyDef& sizeDef =  messageObjectDef.GetPropertyDefL(
+        MdeConstants::Object::KSizeProperty ) ;
+
+    CMdEPropertyDef& receivedDef = messageObjectDef.GetPropertyDefL(
+        MdeConstants::Message::KReceivedProperty ) ;
+	
+	CMdEPropertyDef& textDef = iIncoming
+        ? messageObjectDef.GetPropertyDefL( MdeConstants::Message::KSenderProperty )
+		: messageObjectDef.GetPropertyDefL( MdeConstants::Message::KToWhomProperty );
+
+	CMdEPropertyDef& ItemtypeDef = messageObjectDef.GetPropertyDefL(
+			MdeConstants::Object::KItemTypeProperty );
+	
+	CMdEPropertyDef& offSetDef = messageObjectDef.GetPropertyDefL( 
+			MdeConstants::Object::KTimeOffsetProperty );
+	
+	CMdEPropertyDef& titleDef = messageObjectDef.GetPropertyDefL(
+			MdeConstants::Object::KTitleProperty );
+
+	TTimeIntervalSeconds timeOffset = User::UTCOffset();
+	TTime now;
+	now.HomeTime();
+	
+	if ( EHarvesterAdd == aHD.EventType() )
+		{
+		aMetadataObject.AddTimePropertyL( creationTimeDef, now );			
+		aMetadataObject.AddTimePropertyL( lastModTimeDef, iDate );										
+		aMetadataObject.AddBoolPropertyL( receivedDef, iIncoming );
+		if (iFromOrTo && iFromOrTo->Length())
+			{
+			aMetadataObject.AddTextPropertyL( textDef, *iFromOrTo );
+			}
+		aMetadataObject.AddTextPropertyL( ItemtypeDef, iItemType );									
+		aMetadataObject.AddUint32PropertyL( sizeDef, iSize );
+		aMetadataObject.AddInt16PropertyL( offSetDef, timeOffset.Int() / 60 );
+		
+		CMdEProperty* prop = NULL;	
+		TInt index = aMetadataObject.Property( titleDef, prop );
+		
+		if (iSubject.Length())
+			{
+			if( prop )
+				{
+				prop->SetTextValueL( iSubject );
+				}
+			else
+				{
+				aMetadataObject.AddTextPropertyL( titleDef, iSubject );
+				}
+			}
+		else
+			{
+			if (iFromOrTo && iFromOrTo->Length())
+				{
+				if( prop )
+					{
+					prop->SetTextValueL( *iFromOrTo );
+					}
+				else
+					{
+					aMetadataObject.AddTextPropertyL( titleDef, *iFromOrTo );
+					}
+				}
+			}
+		}
+	else
+		{	
+		CMdEProperty* prop = NULL;	
+		TInt index = aMetadataObject.Property( textDef, prop );
+		if (iFromOrTo && iFromOrTo->Length())
+			{
+			if (prop)
+				{
+				prop->SetTextValueL( *iFromOrTo );
+				}
+			else
+				{
+				aMetadataObject.AddTextPropertyL( textDef, *iFromOrTo );
+				}
+			}
+		else if (index >= 0)
+			{
+			aMetadataObject.RemoveProperty(index);
+			}
+		
+		aMetadataObject.Property( sizeDef, prop );
+		static_cast<CMdEUint32Property *>(prop)->SetValueL( iSize );
+		
+		aMetadataObject.Property( lastModTimeDef, prop );
+		static_cast <CMdETimeProperty *>(prop)->SetValueL( iDate );										
+		}
+
+    iStatus = KErrNone;
+	WRITELOG( "CHarvesterMessagePlugin::SetPropertiesL return" );
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterMessagePlugin::HandleSessionEventL
+// -----------------------------------------------------------------------------
+//
+void CHarvesterMessagePlugin::HandleSessionEventL( TMsvSessionEvent aEvent, 
+	TAny* /*aArg1*/, TAny* /*aArg2*/, TAny* /*aArg3*/ )
+	{	
+    WRITELOG( "CHarvesterMessagePlugin::HandleSessionEventL enter" );	
+		
+	switch ( aEvent )
+		{
+		case EMsvGeneralError: // not used after v5		
+		case EMsvServerFailedToStart:			
+		case EMsvServerTerminated:
+			{
+			__ASSERT_DEBUG( EFalse, User::Panic( KMsgHarvesterMsvPanic, KErrServerTerminated ));
+			break;				
+			}					
+		case EMsvEntriesCreated:
+		case EMsvEntriesChanged:
+		case EMsvEntriesDeleted:
+		case EMsvEntriesMoved:
+		case EMsvMtmGroupInstalled:
+		case EMsvMtmGroupDeInstalled:
+		case EMsvServerReady:
+		case EMsvCorruptedIndexRebuilt:
+		case EMsvMediaChanged:
+		case EMsvMediaUnavailable:
+		case EMsvMediaAvailable:
+		case EMsvMediaIncorrect:
+		case EMsvCorruptedIndexRebuilding:
+		case EMsvCloseSession:		
+		default:
+			{
+			break;
+			}							
+		}	
+    WRITELOG( "CHarvesterMessagePlugin::HandleSessionEventL return" );			
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/MessagePlugin/src/proxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester Message plugin
+*
+*/
+
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include "harvestermessageplugin.h"
+
+// Map the interface UIDs to implementation factory functions
+const TImplementationProxy KImplementationTable[] = 
+	{
+		{ {0x102823C9},	( TProxyNewLPtr) CHarvesterMessagePlugin::NewL }
+	};
+
+// Exported proxy for instantiation method resolution
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+	{
+	aTableCount = sizeof( KImplementationTable ) / sizeof( TImplementationProxy );
+	return KImplementationTable;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/OMADRMPlugin/data/20010973.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// 20010973.RSS
+
+#include "registryinfov2.rh"
+
+// Declares info for one test implementation
+RESOURCE REGISTRY_INFO theInfo
+	{
+  // resource_format_version must always be set as follows
+  resource_format_version = RESOURCE_FORMAT_VERSION_2;
+    
+	// UID for the DLL
+	dll_uid = 0x20010973;
+	// Declare array of interface info
+	interfaces = 
+		{
+		INTERFACE_INFO
+			{
+			// UID of interface that is implemented
+			interface_uid = 0x200009F8;
+			implementations = 
+				{
+				// Info for CHarvesterOMADRMPlugin
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x20010974;
+					version_no = 1;
+					display_name = "Harvester OMA DRM plugin";
+					default_data = "Image Video Audio";
+					opaque_data = "dcf odf dm o4a o4v";
+					rom_only = 0;
+					}
+				};
+			}
+		};
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/OMADRMPlugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+harvesteromadrmplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/OMADRMPlugin/group/harvesteromadrmplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,61 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        harvesteromadrmplugin.dll
+TARGETTYPE    PLUGIN
+UID           0x10009D8D 0x20010973
+
+CAPABILITY 	  CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+start RESOURCE ../data/20010973.rss
+target harvesteromadrmplugin.rsc
+end
+
+SYSTEMINCLUDE /epoc32/include/ecom
+SYSTEMINCLUDE /epoc32/include/libc
+SYSTEMINCLUDE /epoc32/include/connect
+
+USERINCLUDE   ../inc
+USERINCLUDE   ../../../common/inc
+USERINCLUDE   ../../../../inc
+
+SOURCEPATH    ../src
+SOURCE        harvesteromadrmplugin.cpp
+SOURCE        proxy.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       efsrv.lib
+LIBRARY       caf.lib
+LIBRARY	  cafutils.lib
+LIBRARY       harvesterplugininterface.lib
+LIBRARY       mdeclient.lib
+LIBRARY	  harvesterdata.lib
+LIBRARY	  harvestercommon.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/OMADRMPlugin/inc/harvesteromadrmplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,154 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvests meta data from oma drm file.*
+*/
+
+
+#ifndef __CHARVESTEROMADRMPLUGIN_H__
+#define __CHARVESTEROMADRMPLUGIN_H__
+
+#include <e32base.h>
+#include <apmstd.h>
+#include "harvesterplugin.h"
+
+// FORWARD DECLARATION
+class CMdEObjectDef;
+class CMdEObject;
+
+/**
+* A data transfer class for harvested drm metadata.
+*/
+class CDRMHarvestData : public CBase
+    {
+    public:
+
+        /** NewL */
+        static CDRMHarvestData* NewL()
+            {
+            CDRMHarvestData* self = new (ELeave) CDRMHarvestData;
+            return self;
+            }
+        
+        /** Destructor */
+        virtual ~CDRMHarvestData()
+            {
+            }
+
+    private:
+        /** Constructor */
+    		CDRMHarvestData() :  iFileSize( 0 ), iDrmProtected( EFalse )
+            {
+            // no implementation required
+            }
+
+    public:
+
+    	TBuf<KMaxDataTypeLength> iMimetype;
+        TBuf<KMaxDataTypeLength> iDescription;
+        TBuf<KMaxDataTypeLength> iTitle;
+        TBuf<KMaxDataTypeLength> iAuthor;
+        TInt64 iFileSize;
+        TTime iModified;
+        TBool iDrmProtected;
+    };
+
+/**
+ * Helper class to hold all property definitions 
+ * (pointers are not owned) used in harvester OMA DRM plug-in.
+ */
+class CHarvesterOmaDrmPluginPropertyDefs : public CBase
+	{
+	public:
+		// Common property definitions
+		CMdEPropertyDef* iCreationDatePropertyDef;
+		CMdEPropertyDef* iLastModifiedDatePropertyDef;
+		CMdEPropertyDef* iSizePropertyDef;
+		CMdEPropertyDef* iItemTypePropertyDef;
+		CMdEPropertyDef* iTitlePropertyDef;
+	
+		// Media property definitions
+		CMdEPropertyDef* iDrmPropertyDef;
+		CMdEPropertyDef* iDescriptionPropertyDef;
+		CMdEPropertyDef* iAuthorPropertyDef;
+	
+	private:
+		CHarvesterOmaDrmPluginPropertyDefs();
+	
+		void ConstructL(CMdEObjectDef& aObjectDef);
+
+	public:	
+		static CHarvesterOmaDrmPluginPropertyDefs* NewL(CMdEObjectDef& aObjectDef);
+	};
+
+class CHarvesterOMADRMPlugin : public CHarvesterPlugin
+  	{
+	public:
+		/**
+		* Constructs a new CHarvesterOMADRMPlugin implementation.
+		*
+		* @return A pointer to the new CHarvesterOMADRMPlugin implementation
+		*/
+		static CHarvesterOMADRMPlugin* NewL();
+		
+		/**
+		* Destructor
+		*/
+		virtual ~CHarvesterOMADRMPlugin();
+		
+		/**
+		* Harvests several files. Inherited from CHarvestPlugin.
+		*
+		* @param aHarvesterData  CHarvesterData datatype containing needed harvest data
+ 		* @param aClientData  TAny* to client specific data
+		*/
+		void HarvestL( CHarvesterData* aHD );
+		
+		/** */
+		void GetObjectType( const TDesC& aUri, TDes& aObjectType );
+		
+	private:
+		/**
+		* C++ constructor - not exported;
+		* implicitly called from NewL()
+		*
+		* @return an instance of CHarvesterOMADRMPlugin.
+		*/
+		CHarvesterOMADRMPlugin();
+		
+		/**
+		* 2nd phase construction, called by NewLC()
+		*/
+		void ConstructL();
+		
+		/**
+        * Gathers data from file to meta data object.
+        *
+        * @param aMetadataObject  A reference to meta data object to gather the data.
+        * @param aHarvestData  An object to store harvested video file data.
+        */
+        void GatherDataL( CMdEObject& aMetadataObject, CDRMHarvestData& aHarvestData );
+		
+        /**
+         * Handle addition of new mde video objects.
+         *
+         * @param aMetadataObject  A reference to meta data object to gather the data.
+         * @param aHarvestData  An object containing harvested video file data.
+         */
+        void HandleObjectPropertiesL( CHarvesterData& aHD, CDRMHarvestData& aVHD, TBool aIsAdd );
+
+	private:
+		CHarvesterOmaDrmPluginPropertyDefs* iPropDefs;
+	};
+
+#endif // __CHarvesterOMADRMPlugin_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/OMADRMPlugin/src/harvesteromadrmplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,359 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvests meta data from oma drm file.*
+*/
+
+
+#include <e32base.h>
+#include <caf/caf.h>
+
+#include "mdsutils.h"
+#include "harvesteromadrmplugin.h"
+#include "harvesterlog.h"
+#include "mdeobjectwrapper.h"
+#include <harvesterdata.h>
+
+#include <mdenamespacedef.h>
+#include <mdeobjectdef.h>
+#include <mdeobject.h>
+#include <mdetextproperty.h>
+#include <mdenamespacedef.h>
+#include <mdeconstants.h>
+
+_LIT(KImage, "Image");
+_LIT(KVideo, "Video");
+_LIT(KAudio, "Audio");
+_LIT(KRmMimetype, "realmedia");
+
+_LIT( KSvgMime, "image/svg+xml" );
+
+CHarvesterOmaDrmPluginPropertyDefs::CHarvesterOmaDrmPluginPropertyDefs() : CBase()
+	{
+	}
+
+void CHarvesterOmaDrmPluginPropertyDefs::ConstructL(CMdEObjectDef& aObjectDef)
+	{
+	CMdENamespaceDef& nsDef = aObjectDef.NamespaceDef();
+	
+	// Common property definitions
+	CMdEObjectDef& objectDef = nsDef.GetObjectDefL( MdeConstants::Object::KBaseObject );
+	iCreationDatePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KCreationDateProperty );
+	iLastModifiedDatePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KLastModifiedDateProperty );
+	iSizePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KSizeProperty );
+	iItemTypePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KItemTypeProperty );
+	iTitlePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KTitleProperty );
+
+	CMdEObjectDef& mediaDef = nsDef.GetObjectDefL( MdeConstants::MediaObject::KMediaObject );
+	iDrmPropertyDef = &mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KDRMProperty );
+	iDescriptionPropertyDef = &mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KDescriptionProperty );
+	iAuthorPropertyDef = &mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KAuthorProperty );
+	}
+
+CHarvesterOmaDrmPluginPropertyDefs* CHarvesterOmaDrmPluginPropertyDefs::NewL(CMdEObjectDef& aObjectDef)
+	{
+	CHarvesterOmaDrmPluginPropertyDefs* self = 
+		new (ELeave) CHarvesterOmaDrmPluginPropertyDefs();
+	CleanupStack::PushL( self );
+	self->ConstructL( aObjectDef );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+/**
+* Default constructor
+*/
+CHarvesterOMADRMPlugin::CHarvesterOMADRMPlugin() : CHarvesterPlugin()
+	{
+	WRITELOG("CHarvesterOMADRMPlugin::CHarvesterOMADRMPlugin()");
+	}
+
+/**
+* Construction
+* @return Harvester image plugin
+*/
+CHarvesterOMADRMPlugin* CHarvesterOMADRMPlugin::NewL()
+	{
+	WRITELOG("CHarvesterOMADRMPlugin::NewL()");
+	CHarvesterOMADRMPlugin* self = new(ELeave) CHarvesterOMADRMPlugin();
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(self);
+	
+	return self;
+	}
+
+/**
+* Destruction
+*/
+CHarvesterOMADRMPlugin::~CHarvesterOMADRMPlugin()
+	{
+	WRITELOG("CHarvesterOMADRMPlugin::~CHarvesterOMADRMPlugin()");
+	
+	delete iPropDefs;
+	}
+
+/**
+* 2nd phase constructor
+*/
+void CHarvesterOMADRMPlugin::ConstructL()
+	{
+	WRITELOG( "CHarvesterOMADRMPlugin::ConstructL()" );
+	}
+
+void CHarvesterOMADRMPlugin::HarvestL( CHarvesterData* aHD )
+	{
+    CMdEObject& mdeObject = aHD->MdeObject();
+    CDRMHarvestData* fileData = CDRMHarvestData::NewL();
+    CleanupStack::PushL( fileData );
+
+    TRAPD( error, GatherDataL( mdeObject, *fileData ) );
+    if ( error == KErrNone || error == KErrCompletion )
+    	{
+        TBool isNewObject( mdeObject.Id() == 0 );
+        
+        if ( isNewObject || mdeObject.Placeholder() )
+            {
+            TRAP( error, HandleObjectPropertiesL( *aHD, *fileData, ETrue ) );
+            mdeObject.SetPlaceholder( EFalse );
+            }
+        else
+            {
+            TRAP( error, HandleObjectPropertiesL( *aHD, *fileData, EFalse ) );
+            }
+
+        if ( error != KErrNone )
+            {
+            WRITELOG1( "CHarvesterOMADRMPlugin::HarvestL() - Handling object failed: ", error );
+            }
+    	}
+    else	
+        {
+        WRITELOG1( "CHarvesterOMADRMPlugin::HarvestL() - TRAP error: %d", error );
+        TInt convertedError = KErrNone;
+        MdsUtils::ConvertTrapError( error, convertedError );
+        aHD->SetErrorCode( convertedError );
+        }
+
+    CleanupStack::PopAndDestroy( fileData );
+	}
+
+// ---------------------------------------------------------------------------
+// GatherDataL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterOMADRMPlugin::GatherDataL( CMdEObject& aMetadataObject,
+		CDRMHarvestData& aVHD )
+    {
+    WRITELOG( "CHarvesterOMADRMPlugin::GatherDataL" );
+    
+    TEntry* entry = new (ELeave) TEntry();
+    CleanupStack::PushL( entry );
+    
+    const TDesC& uri = aMetadataObject.Uri();
+    User::LeaveIfError( iFs.Entry( uri, *entry ) );
+    
+    aVHD.iModified = entry->iModified;
+    aVHD.iFileSize = (TUint)entry->iSize;
+    CleanupStack::PopAndDestroy( entry );
+    
+    ContentAccess::CContent* content = NULL;
+    content = ContentAccess::CContent::NewLC( uri );
+    
+    ContentAccess::RStringAttributeSet attrSet;
+    CleanupClosePushL( attrSet );
+    
+    attrSet.AddL( ContentAccess::EDescription );
+    attrSet.AddL( ContentAccess::EMimeType );
+    attrSet.AddL( ContentAccess::ETitle );
+    attrSet.AddL( ContentAccess::EAuthor );
+    
+    User::LeaveIfError( content->GetStringAttributeSet(attrSet) );
+    
+    TInt err = attrSet.GetValue( ContentAccess::EDescription, aVHD.iDescription );
+    if ( err != KErrNone)
+        {
+        WRITELOG1( "CHarvesterOMADRMPlugin::GatherDataL - ERROR: getting description failed %d", err );
+        }
+        
+    if ( aVHD.iDescription.Length() <= 0 )
+        {
+        WRITELOG( "CHarvesterOMADRMPlugin::GatherDataL - no description" );
+        }
+    
+    err = attrSet.GetValue( ContentAccess::EMimeType, aVHD.iMimetype );
+    if ( err != KErrNone)
+        {
+        WRITELOG1( "CHarvesterOMADRMPlugin::GatherDataL - ERROR: getting mimetype failed %d", err );
+        }
+        
+    if ( aVHD.iMimetype.Length() <= 0 )
+        {
+        WRITELOG( "CHarvesterOMADRMPlugin::GatherDataL - no mimetype" );
+        }
+    
+    err = attrSet.GetValue( ContentAccess::ETitle, aVHD.iTitle );
+    if ( err != KErrNone)
+        {
+        WRITELOG1( "CHarvesterOMADRMPlugin::GatherDataL - ERROR: getting title failed %d", err );
+        }
+        
+    if ( aVHD.iTitle.Length() <= 0 )
+        {
+        WRITELOG( "CHarvesterOMADRMPlugin::GatherDataL - no title" );
+        }
+    
+    err = attrSet.GetValue( ContentAccess::EAuthor, aVHD.iAuthor );
+    if ( err != KErrNone)
+        {
+        WRITELOG1( "CHarvesterOMADRMPlugin::GatherDataL - ERROR: getting author failed %d", err );
+        }
+        
+    if ( aVHD.iAuthor.Length() <= 0 )
+        {
+        WRITELOG( "CHarvesterOMADRMPlugin::GatherDataL - no author" );
+        }
+    
+    err = content->GetAttribute( ContentAccess::EIsProtected, aVHD.iDrmProtected );
+    if ( err != KErrNone)
+        {
+        WRITELOG1( "CHarvesterOMADRMPlugin::GatherDataL - ERROR: getting protection info failed %d", err );
+        }
+        
+    CleanupStack::PopAndDestroy( 2, content );
+    }
+
+// ---------------------------------------------------------------------------
+// HandleNewObjectL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterOMADRMPlugin::HandleObjectPropertiesL(
+		CHarvesterData& aHD,
+		CDRMHarvestData& aVHD,
+		TBool aIsAdd )
+    {
+    WRITELOG("CHarvesterOMADRMPlugin - HandleNewObject ");
+    CMdEObject& mdeObject = aHD.MdeObject();
+
+    if( !iPropDefs )
+    	{
+    	CMdEObjectDef& objectDef = mdeObject.Def();
+    	iPropDefs = CHarvesterOmaDrmPluginPropertyDefs::NewL( objectDef );
+    	}
+    
+    TTimeIntervalSeconds timeOffset = User::UTCOffset();
+    
+    if( ! mdeObject.Placeholder() )
+    	{
+    	// Creation date
+    	TTime localTime = aVHD.iModified + timeOffset;
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    			*iPropDefs->iCreationDatePropertyDef, &localTime, aIsAdd );
+    	// Last modified date
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    			*iPropDefs->iLastModifiedDatePropertyDef, &aVHD.iModified, aIsAdd );
+    	// File size
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    			*iPropDefs->iSizePropertyDef, &aVHD.iFileSize, aIsAdd );
+    	}
+    // DRM protection
+    CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    		*iPropDefs->iDrmPropertyDef, &aVHD.iDrmProtected, aIsAdd );
+    
+    // Item Type
+    if(aVHD.iMimetype.Length() > 0)
+    	{
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    			*iPropDefs->iItemTypePropertyDef, &aVHD.iMimetype, aIsAdd );
+    	}
+    // Title (is set from URI by default)
+    if(aVHD.iTitle.Length() > 0)
+    	{
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    			*iPropDefs->iTitlePropertyDef, &aVHD.iTitle, EFalse );
+    	}
+    // Description
+    if(aVHD.iDescription.Length() > 0)
+    	{
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    			*iPropDefs->iDescriptionPropertyDef, &aVHD.iDescription, aIsAdd );
+    	}   
+    // Author
+    if(aVHD.iAuthor.Length() > 0)
+    	{
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    			*iPropDefs->iAuthorPropertyDef, &aVHD.iAuthor, aIsAdd );
+    	}
+    }
+
+// ---------------------------------------------------------------------------
+// ChangeObjectType
+// ---------------------------------------------------------------------------
+//
+void CHarvesterOMADRMPlugin::GetObjectType( const TDesC& aUri, TDes& aObjectType )
+	{
+	ContentAccess::CContent* content = NULL;
+    TBuf16<KMaxDataTypeLength> mime;
+    
+	TRAPD( err, content = ContentAccess::CContent::NewL( aUri ) );
+	if (err == KErrNone) 
+		{
+		err = content->GetStringAttribute( ContentAccess::EMimeType, mime );
+		delete content;
+		}
+    
+	if( mime == KSvgMime )
+	    {
+	    WRITELOG1( "CHarvesterOMADRMPlugin::GetObjectType - ERROR: mimetype %S. Not supported", &mime );
+	     aObjectType.Zero();
+	     return;
+	    }
+	
+    if( err == KErrNone )
+    	{
+	    TPtrC ptrImage( KImage );
+		if( MdsUtils::Find( mime, ptrImage ) != KErrNotFound )
+			{
+			WRITELOG1( "CHarvesterOMADRMPlugin::GetObjectType - mimetype %S. Object type changed to Image", &mime );
+			aObjectType.Copy( KImage );
+			return;
+			}
+		
+		TPtrC ptrVideo( KVideo );
+		if( MdsUtils::Find( mime, ptrVideo ) != KErrNotFound )
+			{
+			WRITELOG1( "CHarvesterOMADRMPlugin::GetObjectType - mimetype %S. Object type changed to Video", &mime );
+			aObjectType.Copy( KVideo );
+			return;
+			}
+		
+        TPtrC ptrAudio( KAudio );
+        if( MdsUtils::Find( mime, ptrAudio ) != KErrNotFound )
+            {
+            WRITELOG1( "CHarvesterOMADRMPlugin::GetObjectType - mimetype %S. Object type changed to Audio", &mime );
+            aObjectType.Copy( KAudio );
+            return;
+            }		
+		
+		TPtrC ptrRm( KRmMimetype );
+		if( MdsUtils::Find( mime, ptrRm ) != KErrNotFound )
+			{
+			WRITELOG1( "CHarvesterOMADRMPlugin::GetObjectType - mimetype %S. Object type changed to Rm", &mime );
+			aObjectType.Copy( KVideo );
+			return;
+			}
+    	}
+    
+	WRITELOG1( "CHarvesterOMADRMPlugin::GetObjectType - ERROR: mimetype %S. No object type found", &mime );
+	aObjectType.Zero();
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/OMADRMPlugin/src/proxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation proxy*
+*/
+
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include "harvesteromadrmplugin.h"
+
+// Map the interface UIDs to implementation factory functions
+const TImplementationProxy KImplementationTable[] = 
+	{
+		{{0x20010974},	(TProxyNewLPtr)CHarvesterOMADRMPlugin::NewL}
+	};
+
+// Exported proxy for instantiation method resolution
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+	{
+	aTableCount = sizeof( KImplementationTable ) / sizeof( TImplementationProxy );
+	return KImplementationTable;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/RTPPlugin/data/2000B433.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource definitions for project harvesterrtpplugin
+*
+*/
+
+#include "registryinfov2.rh"
+
+// -----------------------------------------------------------------------------
+// registry_info
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE REGISTRY_INFO registry_info
+    {
+    // resource_format_version must always be set as follows
+    resource_format_version = RESOURCE_FORMAT_VERSION_2;
+    
+    dll_uid = 0x2000B433; // UID of the plugin DLL 
+
+    // Declare array of interface info
+    interfaces =
+        {
+        INTERFACE_INFO
+            {
+            // UID of harvester plugin interface that is implemented
+            interface_uid = 0x200009F8;
+            implementations = 
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid  =  0x2000B434;
+                    version_no          =  1;
+                    display_name        =  "Harvester RTP Plugin";
+                    default_data        =  "Video";
+                    opaque_data         =  "rtp";
+                    rom_only = 0;
+                    }
+                };
+            }
+        };
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/RTPPlugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+harvesterrtpplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/RTPPlugin/group/harvesterrtpplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION                 10.0
+TARGET                  harvesterrtpplugin.dll
+TARGETTYPE              PLUGIN
+UID                     0x10009D8D 0x2000B433
+
+CAPABILITY              CAP_ECOM_PLUGIN
+VENDORID                VID_DEFAULT
+
+SOURCEPATH              ../src
+SOURCE                  harvesterrtpproxy.cpp
+SOURCE                  harvesterrtpplugin.cpp
+SOURCE                  harvesterrtpmetadatareader.cpp
+
+START RESOURCE ../data/2000B433.rss
+TARGET harvesterrtpplugin.rsc
+END
+
+USERINCLUDE   ../../../../inc
+USERINCLUDE   ../../../../harvester/server/inc
+USERINCLUDE   ../../../../harvester/common/inc
+USERINCLUDE    ../inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+SYSTEMINCLUDE /epoc32/include/ecom
+
+LIBRARY       euser.lib 
+LIBRARY       efsrv.lib   
+LIBRARY       harvestercommon.lib
+LIBRARY       harvesterplugininterface.lib
+LIBRARY       mdeclient.lib
+LIBRARY       apgrfx.lib
+LIBRARY       apmime.lib
+LIBRARY	  harvesterdata.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/RTPPlugin/inc/harvesterrtpmetadatareader.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,173 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Reads metadata from rtp file meta header
+*
+*/
+
+#ifndef C_HARVESTERRTPMETADATAREADER_H
+#define C_HARVESTERRTPMETADATAREADER_H
+
+#include <e32base.h>
+#include <f32file.h>
+#include <etelmm.h>
+
+// CONSTANTS
+const TInt KIntegerBytes ( 4 );
+const TInt KStringLengthBytes( 1 );
+const TInt KMaxMetaHeaderLength( 2048 );
+const TInt KMetaLengthPoint( 0 );
+const TInt KAttributesPoint( KMetaLengthPoint + KIntegerBytes ); //4
+const TInt KPlayCountPoint( KAttributesPoint + KIntegerBytes );  // 8
+const TInt KPlaySpotPoint( KPlayCountPoint + KIntegerBytes );    // 12
+const TInt KReservedPoint1( KPlaySpotPoint + KIntegerBytes );    // 16
+const TInt KReservedPoint2( KReservedPoint1 + KIntegerBytes );   // 20
+const TInt KReservedPoint3( KReservedPoint2 + KIntegerBytes );   // 24
+const TInt KReservedPoint4( KReservedPoint3 + KIntegerBytes );   // 28
+const TInt KStartTimePoint( KReservedPoint4 + KIntegerBytes );   // 32
+const TInt KEndTimePoint( KStartTimePoint + 2 * KIntegerBytes ); // 40
+const TInt KDurationPoint( KEndTimePoint + 2 * KIntegerBytes );  // 48
+const TInt KSeekArrayPoint( KDurationPoint + KIntegerBytes );    // 52
+const TInt KUserIdPoint( KSeekArrayPoint + KIntegerBytes );      // 56
+const TInt KDeviceInfoPoint( KUserIdPoint + KStringLengthBytes +
+                             RMobilePhone::KIMSISize );          // 72
+
+const TInt KSpaceLength( 1 );
+
+const TInt KContentRightsLockToDevice( 2 );
+const TInt KPartiallyFailedLimit ( 60 );
+
+// Metaheader attributes
+const TInt KOngoingFlagShift( 0 );
+const TInt KCompletedFlagShift( 1 );
+const TInt KProtectedFlagShift( 2 );
+const TInt KFailedFlagShift( 3 );
+const TInt KVersionFieldShift( 4 );
+const TInt KQualityFieldShift( 8 );
+const TInt KPostRuleFieldShift( 16 );
+const TInt KParentalFieldShift( 24 );
+
+//DATA TYPES
+typedef enum // Video flags
+    {
+    //Duplicates in CIptvMyVideosVideoBriefDetails.h:
+    //DO NOT CHANGE
+    EIptvMyVideosVideoTypeRecording      = 0x00000400, // Video type is recording. 
+    EIptvMyVideosVideoIsRecording        = 0x00000800, // Video is being recorded. 
+    EIptvMyVideosVideoRecPartiallyFailed = 0x00020000, // Recording partially failed 
+    EIptvMyVideosVideoRecFailed          = 0x00040000  // Recording failed
+    } TIptvMyVideosVideoFlags;
+
+class CHarvesterRtpClipDetails;
+
+/**
+ *  Rtp Meta data reader class definition
+ *
+ *  @lib harvesterrtpplugin.dll
+ *  @since S60 S60 v3.x
+ */
+class CHarvesterRtpMetaDataReader : public CBase
+    {
+public:
+
+    /**
+     * Constructs a new CHarvesterRTPPlugin implementation.
+     *  
+     * @param aFileBuffer File data buffer
+     * @return A pointer to CHarvesterRtpMetaDataReader
+     */
+    static CHarvesterRtpMetaDataReader* NewL( const TDesC8* aFileBuffer );
+
+    /**
+    * Destructor.
+    */
+    virtual ~CHarvesterRtpMetaDataReader();
+
+    /**
+    * Get metadata of rtp clip
+    * 
+    * @param aDetails Clip metadata from metadata header
+    */
+    void GetClipDetailsL( CHarvesterRtpClipDetails& aDetails );
+
+private:
+
+    /**
+    * C++ constructor
+    * @param aFileBuffer File data buffer
+    */
+    CHarvesterRtpMetaDataReader( const TDesC8* aFileBuffer );
+
+    /**
+    * 2nd phase constructor
+    */
+    void ConstructL();
+
+    /**
+    * Reads any string with one byte len info from meta header.
+    * @since 
+    * @param aPosition a position from to read
+    * @param aData a data to read
+    * @return None.
+    */
+    void ReadStringDataL( const TInt aPosition, TPtrC8& aData );
+
+    /**
+    * Converts bytes to integer.
+    * @since Series 60 3.0
+    * @param aBytes a buffer to convert.
+    * @param aValue a integer converted from bytes.
+    * @return a system wide error code.
+    */
+    TInt GetValue( const TDesC8& aBytes, TUint& aValue );
+
+    /**
+    * Get channel name and program name from meta header. 
+    * Format to one string. Leaves if cannot read 
+    * data from meta header.
+    *
+    * @param aTitle On return, clip title
+    */
+    void GetProgramTitleL( TDes& aTitle );
+
+private: // data
+
+    /**
+    * Meta total length.
+    */
+    TInt iMetaTotal;
+
+    /**
+    * Data buffer.
+    * Own.
+    */
+    HBufC8* iMetaData;
+
+    /**
+    * File data buffer pointer.
+    */
+    TPtr8 iDataPtr;
+    
+    /**
+    * ESG data point.
+    */
+    TInt iEsgDataPoint;
+
+    /**
+    * File data buffer
+    * Not own.
+    */
+    const TDesC8* iFileBuffer;
+    };
+
+#endif // C_HARVESTERRTPMETADATAREADER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/RTPPlugin/inc/harvesterrtpplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,228 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvests metadata for rtp video file
+*
+*/
+
+#ifndef C_HARVESTERRTPPLUGIN_H
+#define C_HARVESTERRTPPLUGIN_H
+
+#include <harvesterplugin.h>
+#include <e32std.h>
+#include <apmstd.h>
+
+// FORWARD DECLARATION 
+class CHarvesterData;
+class CMdEObject;
+class CMdEObjectDef;
+
+const TInt KMaxMimeTypeLength( KMaxDataTypeLength );
+const TInt KMaxProgramTitle( 255 ); //to fit in db
+
+/**
+ * Helper class to hold all property definitions 
+ * (pointers are not owned) used in harvester OMA DRM plug-in.
+ */
+class CHarvesterRtpPluginPropertyDefs : public CBase
+	{
+	public:
+		// Common property definitions
+		CMdEPropertyDef* iCreationDatePropertyDef;
+		CMdEPropertyDef* iLastModifiedDatePropertyDef;
+		CMdEPropertyDef* iSizePropertyDef;
+		CMdEPropertyDef* iItemTypePropertyDef;
+		CMdEPropertyDef* iTitlePropertyDef;
+	
+		// Media property definitions
+		CMdEPropertyDef* iCaptureDatePropertyDef;
+		CMdEPropertyDef* iDurationPropertyDef;
+
+		// Video property definitions
+		CMdEPropertyDef* iAgeProfilePropertyDef;
+		CMdEPropertyDef* iRecordingFlagsPropertyDef;
+		
+	private:
+		CHarvesterRtpPluginPropertyDefs();
+	
+		void ConstructL(CMdEObjectDef& aObjectDef);
+
+	public:	
+		static CHarvesterRtpPluginPropertyDefs* NewL(CMdEObjectDef& aObjectDef);
+	};
+
+/**
+ *  Data class for rtp harvester
+ *
+ *  Includes clip metadata from metaheader
+ *
+ */
+class CHarvesterRtpClipDetails : public CBase
+    {
+public:
+	
+/** NewL */
+static CHarvesterRtpClipDetails* NewL()
+    {
+    CHarvesterRtpClipDetails* self = new (ELeave) CHarvesterRtpClipDetails;
+    return self;
+    }
+
+/** Destructor */
+virtual ~CHarvesterRtpClipDetails()
+    {
+    }
+
+public:
+
+    /**
+     * Mime type
+     */
+     TBuf<KMaxMimeTypeLength> iMimeType;
+
+     /**
+     * Modification date
+     */
+     TTime iModifiedDate;
+
+     /**
+      * File size
+      */
+     TUint32 iFileSize;
+     
+    /**
+    * Program title including service name and program name
+    */
+    TBuf<KMaxProgramTitle> iTitle;       
+    
+    /**
+    * Recording duration.
+    */
+    TReal32 iDuration;
+
+    /**
+    * Clip's quality. 
+    */
+    TUint8 iQuality; 
+
+    /**
+    * Recording currently ongoing state.
+    */
+    TBool iRecOngoing;
+
+    /**
+    * Recording completed status.
+    */
+    TBool iRecCompleted;
+
+    /**
+    * Recording failed status.
+    */
+    TBool iRecFailed;
+    
+    /**
+    * Parental rate
+    */
+    TInt iParental;
+    
+    /**
+    * Post acquisition rule
+    */
+    TBool iPostRule;        
+    
+private:
+
+    /**
+     * Default constructor
+     */
+    CHarvesterRtpClipDetails()
+    {
+    }
+};
+
+/**
+ *  This class implements RTP harvester plugin.
+ *
+ *  @lib harvesterrtpplugin.dll
+ *  @since S60 S60 v3.x
+ */
+class CHarvesterRtpPlugin : public CHarvesterPlugin
+    {
+public:
+
+    /**
+     * Constructs a new CHarvesterRtpPlugin implementation.
+     * 
+     * @return A pointer to the new CHarvesterRtpPlugin implementation
+     */
+    static CHarvesterRtpPlugin* NewL();
+
+    /**
+    * Destructor.
+    */
+    virtual ~CHarvesterRtpPlugin();
+
+    // from base class CHarvesterPlugin
+    
+    /**
+    * Harvest file. 
+    * 
+    * @param aHarvesterData  
+    */
+    void HarvestL( CHarvesterData* aHarvesterData );
+
+private:
+
+    /**
+    * C++ constructor
+    */
+    CHarvesterRtpPlugin();
+
+    /**
+    * 2nd phase constructor
+    */
+    void ConstructL();
+    
+    /**
+     * Gathers data from file to meta data object. 
+     * Leaves if mime type is not supported.
+     *
+     * @param aMetadataObject  A reference to meta data object to gather the data. 
+     */
+     void GatherDataL( CMdEObject& aMetadataObject, CHarvesterRtpClipDetails& aClipDetails );
+     
+     /**
+      * Recognize file mime type
+      *
+      * @param aFilePath File path for recognizer
+      * @param aFileBuffer Data buffer for file recognition
+      * @return KErrNone if file is recognized, otherwise symbian error code.
+      */
+     TInt RecognizeFile( const TDesC& aFilePath, const TDesC8& aFileBuffer, CHarvesterRtpClipDetails& aClipDetails );
+      
+      /**
+       * Check if mime type is supported
+       * @param aMimeBuf Mime type 
+       * @return KErrNone if mime type is supported
+       * @return KErrNotSupported if mime type is not supported
+       */
+     TInt CheckIfMimeSupported( const TDesC& aMimeBuf );
+     
+     /** */
+     void HandleObjectPropertiesL( CHarvesterData& aHD, CHarvesterRtpClipDetails& aClipDetails, TBool aIsAdd);
+
+private: // data
+	CHarvesterRtpPluginPropertyDefs* iPropDefs;
+    };
+
+#endif // C_HARVESTERWMVPLUGIN_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/RTPPlugin/src/harvesterrtpmetadatareader.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,264 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Reads metadata from rtp clip meta header
+*
+*/
+
+#include "harvesterrtpmetadatareader.h"
+#include "harvesterrtpplugin.h"
+#include "harvesterlog.h"
+
+_LIT( KTxtSpace, " ");
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// Constructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterRtpMetaDataReader* CHarvesterRtpMetaDataReader::NewL( 
+    const TDesC8* aFileBuffer  )
+    {
+    CHarvesterRtpMetaDataReader* self =
+        new( ELeave ) CHarvesterRtpMetaDataReader( aFileBuffer );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterRtpMetaDataReader::~CHarvesterRtpMetaDataReader()
+    {
+    WRITELOG( "CHarvesterRtpMetaDataReader::~CHarvesterRtpMetaDataReader()" );
+    delete iMetaData;
+    }
+
+// ---------------------------------------------------------------------------
+// Read details from meta header
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRtpMetaDataReader::GetClipDetailsL( 
+    CHarvesterRtpClipDetails& aDetails )
+    {
+    WRITELOG( "CHarvesterRtpMetaDataReader::GetClipDetailsL()" );
+    
+    // Attributes
+    TPtrC8 bytes( iDataPtr.Mid( KAttributesPoint, KIntegerBytes ) );
+    TUint data( 0 );
+    User::LeaveIfError( GetValue( bytes, data ) );
+
+    // Recording quality 
+    aDetails.iQuality = 
+        ( TUint8 )( ( data >> KQualityFieldShift ) & KMaxTUint8 );
+    //Recording ongoing 
+    aDetails.iRecOngoing = 
+        ( data >> KOngoingFlagShift ) & ETrue;
+    // Recording completed 
+    aDetails.iRecCompleted = 
+        ( data >> KCompletedFlagShift ) & ETrue;
+    //Recording failed 
+    aDetails.iRecFailed = 
+        ( data >> KFailedFlagShift ) & ETrue;
+    //Parental rate
+    aDetails.iParental =
+         ( TUint8 )( ( data >> KParentalFieldShift ) & KMaxTUint8 );
+    // Post rule    
+    TUint8 postRule = 
+        ( TUint8 )( ( data >> KPostRuleFieldShift ) & KMaxTUint8 );
+    
+    if ( postRule == KContentRightsLockToDevice )
+        {
+        aDetails.iPostRule = ETrue;
+        }
+    else
+        {
+        aDetails.iPostRule = EFalse;
+        }
+        
+    // Duration
+    TUint duration( 0 ); 
+    TPtrC8 durationBytes ( iDataPtr.Mid( KDurationPoint, KIntegerBytes ) );
+    User::LeaveIfError( GetValue( durationBytes, duration ) );
+    duration /= 1000; //Convert to seconds 
+    aDetails.iDuration = static_cast<TReal32>( duration );
+    
+    // Title
+    GetProgramTitleL( aDetails.iTitle );
+    }
+
+// ---------------------------------------------------------------------------
+// Default constructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterRtpMetaDataReader::CHarvesterRtpMetaDataReader(
+    const TDesC8* aFileBuffer )
+    : iMetaTotal( KErrNotFound ),
+      iMetaData( NULL ),
+      iDataPtr( 0, 0 ),
+      iEsgDataPoint ( KErrNotFound ),
+      iFileBuffer( aFileBuffer )
+    {
+    // None
+    }
+
+// ---------------------------------------------------------------------------
+// 2nd phase constructor
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRtpMetaDataReader::ConstructL()
+    {
+    WRITELOG( "CHarvesterRtpMetaDataReader::ConstructL()" );
+    TPtrC8 bytes;
+    
+    if ( iFileBuffer 
+        && iFileBuffer->Length() > KIntegerBytes )
+        {
+        // Read whole meta area
+        bytes.Set( iFileBuffer->Mid( KMetaLengthPoint, KIntegerBytes ) );
+        }        
+
+    TUint value ( 0 );
+    User::LeaveIfError( GetValue( bytes, value ) );
+    
+    iMetaTotal = value;
+    
+    if ( iMetaTotal > KMaxMetaHeaderLength || iMetaTotal <= 0 )
+        {
+        //Length not reasonable, metadata corrupted
+        WRITELOG( "CHarvesterRtpMetaDataReader - metadata corrupted, leave!" );
+        User::Leave( KErrCorrupt );
+        }
+
+    iMetaData = HBufC8::NewL( iMetaTotal );
+    *iMetaData = iFileBuffer->Mid( KMetaLengthPoint, iMetaTotal );
+
+    iDataPtr.Set( iMetaData->Des() );
+            
+    // Check that all data exist in meta header
+    if ( iDataPtr.Length() < iMetaTotal )
+        {
+        //Meta header corrupted
+        WRITELOG( "CHarvesterRtpMetaDataReader - metaheader corrupted, leave!" );
+        User::Leave( KErrCorrupt );
+        }
+
+    // ESG data point ( device info point + device info data )
+    iEsgDataPoint = KDeviceInfoPoint + KStringLengthBytes +
+                    iDataPtr[KDeviceInfoPoint];
+
+    }
+
+// -----------------------------------------------------------------------------
+// Reads data with length info of meta header from the clip
+// -----------------------------------------------------------------------------
+//
+void CHarvesterRtpMetaDataReader::ReadStringDataL( 
+    const TInt aPosition, 
+    TPtrC8& aData )
+    {
+    WRITELOG( "CHarvesterRtpMetaDataReader::ReadStringDataL()" );
+
+    if ( aPosition < 0 
+        || aPosition > iDataPtr.Length() )
+        {
+        WRITELOG( "CHarvesterRtpMetaDataReader - KErrArgument, leave!" );
+        User::Leave( KErrArgument );
+        }
+
+    const TInt len( iDataPtr[aPosition] );
+    
+    if ( len < 0 
+        || len > TInt( KMaxTUint8 ) )
+        {
+        WRITELOG( "CHarvesterRtpMetaDataReader - KErrCorrupt, leave!" );
+        User::Leave( KErrCorrupt );
+        }
+        
+    aData.Set( iDataPtr.Mid( aPosition + KStringLengthBytes, len ) );
+    }
+
+// -----------------------------------------------------------------------------
+// Get value
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterRtpMetaDataReader::GetValue( 
+    const TDesC8& aBytes, 
+    TUint& aValue )
+    {
+    WRITELOG( "CHarvesterRtpMetaDataReader::GetValue()" );
+    if ( aBytes.Length() >= KIntegerBytes )
+        {
+        aValue = ( TUint )( aBytes[0] );
+        aValue <<= 8;
+        aValue |= ( TUint )( aBytes[1] );
+        aValue <<= 8;
+        aValue |= ( TUint )( aBytes[2] );
+        aValue <<= 8;
+        aValue |= ( TUint )( aBytes[3] );
+        return KErrNone;
+        }
+
+    WRITELOG( "CHarvesterRtpMetaDataReader::GetValue() : KErrUnderFlow!" );
+    return KErrUnderflow;
+    }
+
+// -----------------------------------------------------------------------------
+// Get and format clip title
+// -----------------------------------------------------------------------------
+//
+void CHarvesterRtpMetaDataReader::GetProgramTitleL( TDes& aTitle )
+    {
+    WRITELOG( "CHarvesterRtpMetaDataReader::GetProgramTitleL()" );
+    
+    User::LeaveIfError( iEsgDataPoint );
+    aTitle.Zero();
+
+    TUint32 totalLength( 0 );
+    TPtrC8 service;
+    TPtrC8 program;
+    
+    ReadStringDataL( iEsgDataPoint, service );
+    
+    totalLength += service.Length();
+    totalLength += KSpaceLength;
+
+    // Program name
+    const TInt progPos( iEsgDataPoint + KStringLengthBytes + service.Length() );
+    ReadStringDataL( progPos, program );
+    
+    totalLength += program.Length();
+
+    HBufC8* title = HBufC8::NewLC( totalLength );
+    title->Des().Append( service.Ptr(), service.Length() );
+    title->Des().Append( KTxtSpace );
+    title->Des().Append( program.Ptr(), program.Length() ); 
+    
+    if ( totalLength > KMaxProgramTitle ) 
+        {
+        //Make title fit in max title length
+        TPtrC8 titlePtr( *title );
+        aTitle.Copy( titlePtr.Mid( 0 , KMaxProgramTitle ) );
+        }
+    else
+        {
+        aTitle.Copy( *title );
+        }
+                
+    CleanupStack::PopAndDestroy( title );
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/RTPPlugin/src/harvesterrtpplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,327 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvests metadata from rtp video file 
+*
+*/
+
+#include <e32std.h>
+#include <apgcli.h> 
+
+#include "harvesterdata.h"
+#include "harvesterrtpplugin.h"
+#include "harvesterlog.h"
+#include "mdeobject.h"
+#include "mdsutils.h"
+#include "mdeobjectwrapper.h"
+#include "harvesterrtpmetadatareader.h"
+#include <mdenamespacedef.h>
+#include <mdeobjectdef.h>
+
+// Supported mime type
+_LIT( KRtpClipMimetype, "application/x-nokia-teh-rtp" );
+
+// Enough size to recognize file and read metaheader
+const TInt KFileBufferSize( KMaxMetaHeaderLength );
+
+CHarvesterRtpPluginPropertyDefs::CHarvesterRtpPluginPropertyDefs() : CBase()
+	{
+	}
+
+void CHarvesterRtpPluginPropertyDefs::ConstructL(CMdEObjectDef& aObjectDef)
+	{
+	CMdENamespaceDef& nsDef = aObjectDef.NamespaceDef();
+	
+	// Common property definitions
+	CMdEObjectDef& objectDef = nsDef.GetObjectDefL( MdeConstants::Object::KBaseObject );
+	iCreationDatePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KCreationDateProperty );
+	iLastModifiedDatePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KLastModifiedDateProperty );
+	iSizePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KSizeProperty );
+	iItemTypePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KItemTypeProperty );
+	iTitlePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KTitleProperty );
+
+	CMdEObjectDef& mediaDef = nsDef.GetObjectDefL( MdeConstants::MediaObject::KMediaObject );
+	iCaptureDatePropertyDef =& mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KCaptureDateProperty );
+	iDurationPropertyDef = &mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KDurationProperty );
+
+	CMdEObjectDef& videoDef = nsDef.GetObjectDefL( MdeConstants::Video::KVideoObject );
+	iAgeProfilePropertyDef = &videoDef.GetPropertyDefL( MdeConstants::Video::KAgeProfileProperty );
+	iRecordingFlagsPropertyDef = &videoDef.GetPropertyDefL( MdeConstants::Video::KRecordingFlagsProperty );
+	}
+
+CHarvesterRtpPluginPropertyDefs* CHarvesterRtpPluginPropertyDefs::NewL(CMdEObjectDef& aObjectDef)
+	{
+	CHarvesterRtpPluginPropertyDefs* self = 
+		new (ELeave) CHarvesterRtpPluginPropertyDefs();
+	CleanupStack::PushL( self );
+	self->ConstructL( aObjectDef );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// Default constructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterRtpPlugin::CHarvesterRtpPlugin() : CHarvesterPlugin(), iPropDefs( NULL )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// 2nd phase constructor
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRtpPlugin::ConstructL()
+    {
+    WRITELOG( "CHarvesterRtpPlugin::ConstructL()" );
+    }
+
+// ---------------------------------------------------------------------------
+// Constructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterRtpPlugin* CHarvesterRtpPlugin::NewL()
+    {
+    CHarvesterRtpPlugin* self = new(ELeave) CHarvesterRtpPlugin();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterRtpPlugin::~CHarvesterRtpPlugin()
+    {
+    WRITELOG( "CHarvesterRtpPlugin::~CHarvesterRtpPlugin()" );
+    }
+
+// ---------------------------------------------------------------------------
+// Harvest file
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRtpPlugin::HarvestL( CHarvesterData* aHD )    
+    {
+    WRITELOG( "CHarvesterRtpPlugin::Harvest()" );
+    CMdEObject& mdeObject = aHD->MdeObject();
+    
+    CHarvesterRtpClipDetails* clipDetails = CHarvesterRtpClipDetails::NewL();
+    CleanupStack::PushL( clipDetails );
+    
+    TRAPD( error, GatherDataL( mdeObject, *clipDetails ) );
+    if ( error == KErrNone || error == KErrCompletion )
+    	{
+    	TBool isNewObject( mdeObject.Id() == 0 );
+        
+        if ( isNewObject || mdeObject.Placeholder() )
+            {
+            TRAP( error, HandleObjectPropertiesL( *aHD, *clipDetails, ETrue ) );
+            mdeObject.SetPlaceholder( EFalse );
+            }
+        else
+            {
+            TRAP( error, HandleObjectPropertiesL( *aHD, *clipDetails, EFalse ) );
+            }
+
+        if ( error != KErrNone )
+            {
+            WRITELOG1( "CHarvesterWMVPlugin::HarvestL() - Handling object failed: ", error );
+            }
+    	}
+    else
+        {
+        TInt convertedError = KErrNone;
+        MdsUtils::ConvertTrapError( error, convertedError );
+        aHD->SetErrorCode( convertedError );
+        }
+    CleanupStack::PopAndDestroy( clipDetails );
+    }
+
+// ---------------------------------------------------------------------------
+// Gather metadata
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRtpPlugin::GatherDataL( CMdEObject& aMetadataObject, CHarvesterRtpClipDetails& aClipDetails )
+    {
+    WRITELOG( "CHarvesterRtpPlugin - GatherDataL()" );
+    
+    const TDesC& uri = aMetadataObject.Uri();
+
+    HBufC8* buffer = HBufC8::NewLC( KFileBufferSize );
+    TPtr8 bufferPtr( buffer->Des() );
+    
+    RFile64 file;
+    CleanupClosePushL( file );
+
+    User::LeaveIfError( file.Open( iFs, uri, EFileShareAny ) );
+    
+    TEntry* entry = new (ELeave) TEntry();
+    CleanupStack::PushL( entry );
+    User::LeaveIfError( iFs.Entry( uri, *entry ) );
+    aClipDetails.iFileSize = (TUint)entry->iSize;
+    aClipDetails.iModifiedDate = entry->iModified;
+    CleanupStack::PopAndDestroy( entry ); // entry
+    
+    User::LeaveIfError( file.Read( bufferPtr, KFileBufferSize ) );
+    User::LeaveIfError( RecognizeFile( uri, *buffer, aClipDetails ) );
+    User::LeaveIfError( CheckIfMimeSupported( aClipDetails.iMimeType ) ); 
+
+    CHarvesterRtpMetaDataReader* mdr = CHarvesterRtpMetaDataReader::NewL( buffer );
+    CleanupStack::PushL( mdr );
+
+    WRITELOG( "CHarvesterRtpPlugin - GatherDataL() ---> found metadata!" );
+    mdr->GetClipDetailsL( aClipDetails );
+
+    CleanupStack::PopAndDestroy( mdr ); // mdr
+    CleanupStack::PopAndDestroy( &file );  // file
+    CleanupStack::PopAndDestroy( buffer ); // buffer
+    }
+
+// -----------------------------------------------------------------------------
+// Runs recognizers on the given file to determine its mime type
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterRtpPlugin::RecognizeFile(
+    const TDesC& aFilePath,
+    const TDesC8& aFileBuffer,
+    CHarvesterRtpClipDetails& aClipDetails )
+    {
+    WRITELOG( "CHarvesterRtpPlugin::RecognizeFile()" );
+    TInt err( KErrNone );
+    
+    RApaLsSession apaSession;
+    err = apaSession.Connect();
+    if ( err == KErrNone )
+        {
+        TDataRecognitionResult result;
+        err = apaSession.RecognizeData( aFilePath, aFileBuffer, result );
+        if ( result.iConfidence >= CApaDataRecognizerType::EProbable )
+            {
+            aClipDetails.iMimeType = result.iDataType.Des();
+            WRITELOG1( "CHarvesterRtpPlugin - Mime type: %S", &aClipDetails.iMimeType );
+            }
+
+        apaSession.Close();
+        }
+    
+    return err;
+    }
+
+///---------------------------------------------------------------------------
+/// Check if mime type is supported
+///---------------------------------------------------------------------------
+//
+TInt CHarvesterRtpPlugin::CheckIfMimeSupported( const TDesC& aMimeBuf )
+    {
+    if ( MdsUtils::Compare( KRtpClipMimetype, aMimeBuf ) == 0 )
+        {
+        WRITELOG( "CHarvesterRtpPlugin - Mime type supported");
+        return KErrNone;
+        }
+    
+    WRITELOG( "CHarvesterRtpPlugin - Mime type not supported");
+    return KErrNotSupported;
+    }
+
+// ---------------------------------------------------------------------------
+// Add object properties
+// ---------------------------------------------------------------------------
+//
+void CHarvesterRtpPlugin::HandleObjectPropertiesL( 
+    CHarvesterData& aHD,
+    CHarvesterRtpClipDetails& aClipDetails,
+    TBool aIsAdd)
+    {
+    WRITELOG( "CHarvesterRtpPlugin::HandleObjectPropertiesL()" );
+
+    CMdEObject& mdeObject = aHD.MdeObject();
+    
+    if( !iPropDefs )
+		{
+		CMdEObjectDef& objectDef = mdeObject.Def();
+		iPropDefs = CHarvesterRtpPluginPropertyDefs::NewL( objectDef );
+		}
+
+    TTimeIntervalSeconds timeOffset = User::UTCOffset();
+    TTime localModifiedTime = aClipDetails.iModifiedDate + timeOffset;
+    
+    if( ! mdeObject.Placeholder() )
+    	{
+    	// Creation date of media file
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    			*iPropDefs->iCreationDatePropertyDef, &localModifiedTime, aIsAdd );
+    	// Last modified date
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    			*iPropDefs->iLastModifiedDatePropertyDef, &aClipDetails.iModifiedDate, aIsAdd );
+    	// File size
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    			*iPropDefs->iSizePropertyDef, &aClipDetails.iFileSize, aIsAdd );
+    	}
+
+    // Title (is set from URI by default)
+    if ( aClipDetails.iTitle.Length() > 0 ) 
+        {
+        CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+        		*iPropDefs->iTitlePropertyDef, &aClipDetails.iTitle, EFalse );
+        }
+
+    // Mime Type
+    CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    		*iPropDefs->iItemTypePropertyDef, &aClipDetails.iMimeType, aIsAdd );
+
+    // Capture date
+    CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    		*iPropDefs->iCaptureDatePropertyDef, &localModifiedTime, aIsAdd );    
+
+   	// Duration
+    CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    		*iPropDefs->iDurationPropertyDef, &aClipDetails.iDuration, aIsAdd );
+
+    //Save these if video center videostorage available
+    //AgeProfile
+    CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    		*iPropDefs->iAgeProfilePropertyDef, &aClipDetails.iParental, aIsAdd );
+    
+    //VideoFlags    
+    TUint32 flags = 0;
+
+    //always set clip type as recording
+    flags |= EIptvMyVideosVideoTypeRecording;
+
+    if ( aClipDetails.iRecOngoing )
+        {
+        //Recording ongoing 
+        //Otherwise assuming that recording has completed
+        flags |= EIptvMyVideosVideoIsRecording;
+        }        
+
+    if ( aClipDetails.iRecFailed )
+        {
+        //Recording failed
+        flags |= EIptvMyVideosVideoRecFailed;
+        }
+
+    if ( aClipDetails.iQuality <= KPartiallyFailedLimit )
+        {
+        //Clip partially failed
+        flags |= EIptvMyVideosVideoRecPartiallyFailed;
+        }
+
+    CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    		*iPropDefs->iRecordingFlagsPropertyDef, &flags, aIsAdd );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/RTPPlugin/src/harvesterrtpproxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,42 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include "harvesterrtpplugin.h"
+
+// --------------------------------------------------------------------------
+// Provide a key pair value table.
+// Used to identify the correct construction function
+// for the requested interface.
+// --------------------------------------------------------------------------
+//
+const TImplementationProxy ImplementationTable[] =
+    {
+    { { 0x2000B434 }, ( TProxyNewLPtr ) CHarvesterRtpPlugin::NewL }
+    };
+
+// --------------------------------------------------------------------------
+// Return an instance of the proxy table.
+// --------------------------------------------------------------------------
+//
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+    {
+    aTableCount = sizeof( ImplementationTable ) / sizeof( TImplementationProxy );
+    return ImplementationTable;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/VideoPlugin/data/200009f9.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// 200009F9.RSS
+
+#include "registryinfov2.rh"
+
+// Declares info for one test implementation
+RESOURCE REGISTRY_INFO theInfo
+	{
+  // resource_format_version must always be set as follows
+  resource_format_version = RESOURCE_FORMAT_VERSION_2;
+
+	// UID for the DLL
+	dll_uid = 0x200009F9;
+	// Declare array of interface info
+	interfaces = 
+		{
+		INTERFACE_INFO
+			{
+			// UID of interface that is implemented
+			interface_uid = 0x200009F8;
+			implementations = 
+				{
+				// Info for CHarvesterVideoPlugin
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x200009FA;
+					version_no = 1;
+					display_name = "Harvester video plugin";
+					default_data = "Video Audio";
+					opaque_data = "mp4 mpg4 mpeg4 m4v m4a 3gp 3gpp rm rv rmvb 3g2 avi mkv ra";
+          rom_only = 0;
+					}
+				};
+			}
+		};
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/VideoPlugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+harvestervideoplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/VideoPlugin/group/harvestervideoplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,64 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        harvestervideoplugin.dll
+TARGETTYPE    PLUGIN
+UID           0x10009D8D 0x200009F9
+
+CAPABILITY 	  CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+start RESOURCE ../data/200009f9.rss
+target HarvesterVideoPlugin.rsc
+end
+
+SYSTEMINCLUDE /epoc32/include/ecom
+SYSTEMINCLUDE /epoc32/include/libc
+SYSTEMINCLUDE /epoc32/include/connect
+SYSTEMINCLUDE /epoc32/include/3gplibrary
+
+USERINCLUDE   ../inc
+USERINCLUDE   ../../../common/inc
+USERINCLUDE   ../../../../inc
+
+SOURCEPATH    ../src
+SOURCE        harvestervideoplugin.cpp
+SOURCE        proxy.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       efsrv.lib
+LIBRARY       3GPMP4Lib.lib
+LIBRARY       harvesterplugininterface.lib
+LIBRARY       mdeclient.lib
+LIBRARY	  harvesterdata.lib
+LIBRARY	  harvestercommon.lib
+
+STATICLIBRARY       hxmetadatautil.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/VideoPlugin/inc/harvestervideoplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,223 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvests meta data from video file.*
+*/
+
+
+#ifndef __CHARVESTERVIDEOPLUGIN_H__
+#define __CHARVESTERVIDEOPLUGIN_H__
+
+#include <e32base.h>
+#include "harvesterplugin.h"
+
+#include "mimetypemapping.h"
+
+// FORWARD DECLARATION
+class CMdEObjectDef;
+class CMdEPropertyDef;
+class CMdEObject;
+class CHarvesterData;
+
+class TVideoMetadataHandling
+	{
+	public:
+		enum TVideoMetadataHandlingLibrary
+			{
+			EMp4LibHandling,
+			EHexilMetadataHandling
+			};
+
+		TVideoMetadataHandlingLibrary iLibrary;
+		TPtrC iObjectDef;
+		TPtrC iVideoMime;
+		TPtrC iAudioMime;
+
+		TVideoMetadataHandling()
+			{		
+			}
+		
+		TVideoMetadataHandling(TVideoMetadataHandlingLibrary aLibrary, 
+				TPtrC aObjectDef, TPtrC aVideoMime, TPtrC aAudioMime) :
+			iLibrary( aLibrary ), iObjectDef( aObjectDef ),
+			iVideoMime( aVideoMime ), iAudioMime( aAudioMime ) 
+			{		
+			}
+		
+		TVideoMetadataHandling(const TVideoMetadataHandling& aHandling) :
+			iLibrary( aHandling.iLibrary ), iObjectDef( aHandling.iObjectDef ),
+			iVideoMime( aHandling.iVideoMime ), iAudioMime( aHandling.iAudioMime )
+			{
+			}
+	};
+
+typedef TMimeTypeMapping<TVideoMetadataHandling> THarvestingHandling;
+	
+/**
+* A data transfer class for harvested video metadata.
+*/
+class CVideoHarvestData : public CBase
+    {
+    public:
+    	TBool iVideoObject; // Is object video or audio
+
+    	TTime iModified;
+    	TInt64 iFileSize; // in bytes
+        TReal32 iDuration; // in seconds
+        TReal32 iFrameRate; // in frames per second
+        TReal32 iSamplingFrequency; // in kHz 
+        TInt iVideoBitrate; // in kbps
+        TInt iAudioBitrate; // in kbps
+        TInt iClipBitrate; // in kbps
+        TInt16 iFrameWidth;
+        TInt16 iFrameHeight;
+        HBufC* iCopyright;
+        HBufC* iAuthor;
+        HBufC* iGenre;
+        HBufC* iPerformer; // Artist
+        HBufC* iDescription;
+
+        HBufC* iMimeBuf;
+        TUint32 iCodec;
+
+        CVideoHarvestData() : CBase()
+        	{
+        	}
+
+        ~CVideoHarvestData()
+        	{
+        	delete iCopyright;
+            delete iAuthor;
+            delete iGenre;
+            delete iPerformer;
+            delete iDescription;
+
+        	delete iMimeBuf;
+        	}
+    };
+
+/**
+ * Helper class to hold all property definitions 
+ * (pointers are not owned) used in harvester video plug-in.
+ */
+class CHarvesterVideoPluginPropertyDefs : public CBase
+	{
+	public:
+		// Common property definitions
+		CMdEPropertyDef* iCreationDatePropertyDef;
+		CMdEPropertyDef* iLastModifiedDatePropertyDef;
+		CMdEPropertyDef* iSizePropertyDef;
+		CMdEPropertyDef* iTimeOffsetPropertyDef;
+		CMdEPropertyDef* iItemTypePropertyDef;
+	
+		// Media property definitions
+		CMdEPropertyDef* iReleaseDatePropertyDef;
+		CMdEPropertyDef* iCaptureDatePropertyDef;
+		CMdEPropertyDef* iDurationPropertyDef;
+		CMdEPropertyDef* iWidthPropertyDef;
+		CMdEPropertyDef* iHeightPropertyDef;
+		CMdEPropertyDef* iBitratePropertyDef;
+		CMdEPropertyDef* iCopyrightPropertyDef;
+		CMdEPropertyDef* iAuthorPropertyDef;
+		CMdEPropertyDef* iGenrePropertyDef;
+		CMdEPropertyDef* iArtistPropertyDef;
+		CMdEPropertyDef* iDescriptionPropertyDef;
+		
+		CMdEPropertyDef* iAudioFourCCDef;
+	
+		// Video property definitions
+		CMdEPropertyDef* iFrameratePropertyDef;
+	
+		// Audio property definitions
+		CMdEPropertyDef* iSamplingFrequencyPropertyDef;
+	
+	private:
+		CHarvesterVideoPluginPropertyDefs();
+	
+		void ConstructL(CMdEObjectDef& aObjectDef);
+
+	public:	
+		static CHarvesterVideoPluginPropertyDefs* NewL(CMdEObjectDef& aObjectDef);
+	};
+
+class CHarvesterVideoPlugin : public CHarvesterPlugin
+  	{
+	public:
+		/**
+		* Constructs a new CHarvesterVideoPlugin implementation.
+		*
+		* @return A pointer to the new CHarvesterVideoPlugin implementation
+		*/
+		static CHarvesterVideoPlugin* NewL();
+		
+		/**
+		* Destructor
+		*/
+		virtual ~CHarvesterVideoPlugin();
+		
+		void GetObjectType( const TDesC& aUri, TDes& aObjectType );
+
+		/**
+		* Harvests several files. Inherited from CHarvestPlugin.
+		*
+		* @param aHarvesterData  CHarvesterData datatype containing needed harvest data
+ 		* @param aClientData  TAny* to client specific data
+		*/
+		void HarvestL( CHarvesterData* aHD );
+				
+	private:
+		/**
+		* C++ constructor - not exported;
+		* implicitly called from NewL()
+		*
+		* @return an instance of CHarvesterVideoPlugin.
+		*/
+		CHarvesterVideoPlugin();
+		
+		/**
+		* 2nd phase construction, called by NewLC()
+		*/
+		void ConstructL();
+		
+		/**
+        * Gathers data from file to meta data object.
+        *
+        * @param aMetadataObject  A reference to meta data object to gather the data.
+        * @param aHarvestData  An object to store harvested video file data.
+        */
+        void GatherDataL( CMdEObject& aMetadataObject, CVideoHarvestData& aHarvestData );
+		
+        /**
+         * Handle addition of new mde video objects.
+         *
+         * @param aMetadataObject  A reference to meta data object to gather the data.
+         * @param aHarvestData  An object containing harvested video file data.
+         */
+        void HandleObjectPropertiesL( CHarvesterData& aHD, CVideoHarvestData& aVHD, TBool aIsAdd );
+          
+	private:
+		void GetMp4Type( RFile64& aFile, TDes& aType );
+		
+		void GetRmTypeL( RFile64& aFile, TDes& aType );
+	
+		const THarvestingHandling* FindHandler( const TDesC& aUri );
+		
+		void CheckForCodecSupport( HBufC* aMimeBuffer, CVideoHarvestData& aVHD );
+		
+	private:
+		RArray<THarvestingHandling> iMimeTypeMappings;
+		
+		CHarvesterVideoPluginPropertyDefs* iPropDefs;
+	};
+
+#endif // __CHARVESTERVIDEOPLUGIN_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/VideoPlugin/src/harvestervideoplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1066 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvests meta data from video file.*
+*/
+
+
+#include <e32base.h>
+#include <e32std.h>
+#include <3gplibrary/mp4lib.h>
+#include <hxmetadatautil.h>
+#include <hxmetadatakeys.h>
+
+#include "mdsutils.h"
+#include "harvestervideoplugin.h"
+#include "harvesterlog.h"
+#include "harvesterblacklist.h"
+#include "mdeobjectwrapper.h"
+
+#include <mdenamespacedef.h>
+#include <mdeobjectdef.h>
+#include <mdepropertydef.h>
+#include <mdeobject.h>
+#include <harvesterdata.h>
+#include <mdeconstants.h>
+
+using namespace MdeConstants;
+
+_LIT( KMimeTypeVideoMp4,  "video/mp4" );
+_LIT( KMimeTypeAudioMp4,  "audio/mp4" );
+_LIT( KMimeTypeVideo3gpp, "video/3gpp" );
+_LIT( KMimeTypeAudio3gpp, "audio/3gpp" );
+_LIT( KMimeTypeRm,        "application/vnd.rn-realmedia" ); // can be audio or video
+_LIT( KMimeTypeRmvb,      "application/vnd.rn-realmedia-vbr" ); // can be audio or video
+_LIT( KMimeTypeRv,        "video/vnd.rn-realvideo" );
+_LIT( KMimeTypeRa,        "audio/vnd.rn-realaudio" );
+_LIT( KMimeTypeAvi,        "video/avi");
+_LIT( KMimeTypeVideoMatroska, "video/x-matroska");
+_LIT( KMimeTypeAudioMatroska, "audio/x-matroska");
+
+_LIT( KExtensionMp4,   "mp4" );
+_LIT( KExtensionMpg4,  "mpg4" );
+_LIT( KExtensionMpeg4, "mpeg4" );
+_LIT( KExtensionM4v,   "m4v" );
+_LIT( KExtensionM4a,   "m4a" );
+_LIT( KExtension3gp,   "3gp" );
+_LIT( KExtension3gpp,  "3gpp" );
+_LIT( KExtension3g2,   "3g2" );
+_LIT( KExtensionRm,    "rm" );
+_LIT( KExtensionRmvb,  "rmvb" );
+_LIT( KExtensionRv,    "rv" );
+_LIT( KExtensionAvi,    "avi" );
+_LIT( KExtensionMkv,    "mkv" );
+_LIT( KExtensionRa,     "ra" );
+
+_LIT(KVideo, "Video");
+_LIT(KAudio, "Audio");
+
+_LIT(KAudioAC3, "audio/AC3");
+_LIT(KAudioEAC3, "audio/EAC3");
+const TUint32 KMDSFourCCCodeAC3 = 0x33434120;       //{' ', 'A', 'C', '3'}
+const TUint32 KMDSFourCCCodeEAC3 = 0x33434145;      //{'E', 'A', 'C', '3'}
+
+_LIT(KInUse, "InUse");
+
+const TInt KKiloBytes = 1024;
+const TReal32 KThousandReal = 1000.0;
+
+CHarvesterVideoPluginPropertyDefs::CHarvesterVideoPluginPropertyDefs() : CBase()
+	{
+	}
+
+void CHarvesterVideoPluginPropertyDefs::ConstructL(CMdEObjectDef& aObjectDef)
+	{
+	CMdENamespaceDef& nsDef = aObjectDef.NamespaceDef();
+	
+	// Common property definitions
+	CMdEObjectDef& objectDef = nsDef.GetObjectDefL( Object::KBaseObject );
+	iCreationDatePropertyDef = &objectDef.GetPropertyDefL( Object::KCreationDateProperty );
+	iLastModifiedDatePropertyDef = &objectDef.GetPropertyDefL( Object::KLastModifiedDateProperty );
+	iSizePropertyDef = &objectDef.GetPropertyDefL( Object::KSizeProperty );
+	iTimeOffsetPropertyDef = &objectDef.GetPropertyDefL( Object::KTimeOffsetProperty );
+	iItemTypePropertyDef = &objectDef.GetPropertyDefL( Object::KItemTypeProperty );
+
+	CMdEObjectDef& mediaDef = nsDef.GetObjectDefL( MediaObject::KMediaObject );
+	iReleaseDatePropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KReleaseDateProperty );
+	iCaptureDatePropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KCaptureDateProperty );
+	iDurationPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KDurationProperty );
+	iWidthPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KWidthProperty );
+	iHeightPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KHeightProperty );
+	iBitratePropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KBitrateProperty );
+	iCopyrightPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KCopyrightProperty );
+	iAuthorPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KAuthorProperty );
+	iGenrePropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KGenreProperty );
+	iArtistPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KArtistProperty );
+	iDescriptionPropertyDef = &mediaDef.GetPropertyDefL( MediaObject::KDescriptionProperty );
+	
+	iAudioFourCCDef = &mediaDef.GetPropertyDefL( MediaObject::KAudioFourCCProperty );
+
+	// Video property definitions
+	CMdEObjectDef& videoDef = nsDef.GetObjectDefL( Video::KVideoObject );
+	iFrameratePropertyDef = &videoDef.GetPropertyDefL( Video::KFramerateProperty );
+
+	// Audio property definitions
+	CMdEObjectDef& audioDef = nsDef.GetObjectDefL( Audio::KAudioObject );
+	iSamplingFrequencyPropertyDef = &audioDef.GetPropertyDefL( Audio::KSamplingFrequencyProperty );
+	}
+
+CHarvesterVideoPluginPropertyDefs* CHarvesterVideoPluginPropertyDefs::NewL(CMdEObjectDef& aObjectDef)
+	{
+	CHarvesterVideoPluginPropertyDefs* self = 
+		new (ELeave) CHarvesterVideoPluginPropertyDefs();
+	CleanupStack::PushL( self );
+	self->ConstructL( aObjectDef );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+/**
+* Default constructor
+*/
+CHarvesterVideoPlugin::CHarvesterVideoPlugin() : CHarvesterPlugin(), iPropDefs( NULL )
+	{
+	}
+
+/**
+* Construction
+* @return Harvester image plugin
+*/
+CHarvesterVideoPlugin* CHarvesterVideoPlugin::NewL()
+	{
+	WRITELOG("CHarvesterVideoPlugin::NewL()");
+	CHarvesterVideoPlugin* self = new(ELeave) CHarvesterVideoPlugin();
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+/**
+* Destruction
+*/
+CHarvesterVideoPlugin::~CHarvesterVideoPlugin()
+	{
+	delete iPropDefs;
+
+	WRITELOG("CHarvesterVideoPlugin::CHarvesterVideoPlugin()");
+	}
+
+/**
+* 2nd phase constructor
+*/
+void CHarvesterVideoPlugin::ConstructL()
+	{
+	WRITELOG( "CHarvesterVideoPlugin::ConstructL() - begin" );
+	
+	TLinearOrder< THarvestingHandling > cmp( THarvestingHandling::CompareFunction );
+
+	// MPEG4
+	User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+    		KExtensionMp4(), KNullDesC(), 
+    		TVideoMetadataHandling( TVideoMetadataHandling::EMp4LibHandling, KNullDesC(),
+    				KMimeTypeVideoMp4(), KMimeTypeAudioMp4() ) ), 
+    		cmp ) );
+	User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+    		KExtensionMpg4(), KNullDesC(), 
+    		TVideoMetadataHandling( TVideoMetadataHandling::EMp4LibHandling, KNullDesC(),
+    				KMimeTypeVideoMp4(), KMimeTypeAudioMp4() ) ), 
+    		cmp ) );
+	User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+    		KExtensionMpeg4(), KNullDesC(), 
+    		TVideoMetadataHandling( TVideoMetadataHandling::EMp4LibHandling, KNullDesC(),
+    				KMimeTypeVideoMp4(), KMimeTypeAudioMp4() ) ), 
+    		cmp ) );
+	User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+    		KExtensionM4v(), KMimeTypeVideoMp4(), 
+    		TVideoMetadataHandling( TVideoMetadataHandling::EMp4LibHandling, KVideo(),
+    				KMimeTypeVideoMp4(), KMimeTypeAudioMp4() ) ), 
+    		cmp ) );
+	User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+    		KExtensionM4a(), KMimeTypeAudioMp4(), 
+    		TVideoMetadataHandling( TVideoMetadataHandling::EMp4LibHandling, KAudio(),
+    				KMimeTypeVideoMp4(), KMimeTypeAudioMp4() ) ), 
+    		cmp ) );
+
+	// 3GP
+	User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+    		KExtension3gp(), KNullDesC(), 
+    		TVideoMetadataHandling( TVideoMetadataHandling::EMp4LibHandling, KNullDesC(),
+    				KMimeTypeVideo3gpp(), KMimeTypeAudio3gpp() ) ), 
+    		cmp ) );
+	User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+    		KExtension3gpp(), KNullDesC(), 
+    		TVideoMetadataHandling( TVideoMetadataHandling::EMp4LibHandling, KNullDesC(),
+    				KMimeTypeVideo3gpp(), KMimeTypeAudio3gpp() ) ), 
+    		cmp ) );
+	User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+    		KExtension3g2(), KNullDesC(), 
+    		TVideoMetadataHandling( TVideoMetadataHandling::EMp4LibHandling, KNullDesC(),
+    				KMimeTypeVideo3gpp(), KMimeTypeAudio3gpp() ) ), 
+    		cmp ) );
+
+	// RealMedia
+	User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+    		KExtensionRm(), KNullDesC(), 
+    		TVideoMetadataHandling( TVideoMetadataHandling::EHexilMetadataHandling, KNullDesC(),
+    				KMimeTypeRm(), KMimeTypeRm() ) ), 
+    		cmp ) );
+	User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+    		KExtensionRmvb(), KNullDesC(), 
+    		TVideoMetadataHandling( TVideoMetadataHandling::EHexilMetadataHandling, KNullDesC(),
+    				KMimeTypeRmvb(), KMimeTypeRmvb() ) ), 
+    		cmp ) );
+	User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+    		KExtensionRv(), KMimeTypeRv(), 
+    		TVideoMetadataHandling( TVideoMetadataHandling::EHexilMetadataHandling, KVideo(),
+    				KMimeTypeRv(), KMimeTypeRa() ) ), 
+    		cmp ) );
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+            KExtensionRa(), KMimeTypeRa(), 
+            TVideoMetadataHandling( TVideoMetadataHandling::EHexilMetadataHandling, KAudio(),
+                    KMimeTypeRv(), KMimeTypeRa() ) ), 
+            cmp ) );
+    
+    // Avi
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+            KExtensionAvi(), KMimeTypeAvi(), 
+            TVideoMetadataHandling( TVideoMetadataHandling::EHexilMetadataHandling, KVideo(),
+                    KMimeTypeAvi(), KMimeTypeAvi() ) ), 
+            cmp ) );
+    
+    // Matroska
+    User::LeaveIfError( iMimeTypeMappings.InsertInOrder( THarvestingHandling(
+            KExtensionMkv(), KNullDesC(), 
+            TVideoMetadataHandling( TVideoMetadataHandling::EHexilMetadataHandling, KNullDesC(),
+                    KMimeTypeVideoMatroska(), KMimeTypeAudioMatroska() ) ), 
+            cmp ) );
+    }
+
+
+// ---------------------------------------------------------------------------
+// GetObjectType
+// ---------------------------------------------------------------------------
+//
+void CHarvesterVideoPlugin::GetObjectType( const TDesC& aUri, TDes& aObjectType )
+	{
+	aObjectType.Zero();
+	
+	const THarvestingHandling* mapping = FindHandler( aUri );
+
+	// no matching extension found
+	if( !mapping )
+		{
+		return;
+		}
+
+	const TVideoMetadataHandling& handler = mapping->iHandler;
+	
+    // object def is defined by extension
+    if( handler.iObjectDef.Length() > 0 )
+    	{
+    	aObjectType.Copy( handler.iObjectDef );
+    	return;
+    	}
+
+    RFile64 file;
+    // File must not be allowed to be written to here. If file passes through 
+    // here while it is still open for writing, it will fail in actual harvesting
+    // and will not be processed again until the file is modified
+    const TInt error = file.Open( iFs, aUri, EFileRead | EFileShareReadersOnly  );
+    if ( error != KErrNone )
+        {
+        WRITELOG1( "CHarvesterVideoPlugin::GetObjectType - File open error: %d", error );
+        if( error == KErrInUse )
+            {
+            aObjectType.Copy( KInUse() );
+            }
+        return;
+        }
+
+    if( handler.iLibrary == TVideoMetadataHandling::EMp4LibHandling )
+    	{
+    	GetMp4Type( file, aObjectType );
+    	}
+    else if( handler.iLibrary == TVideoMetadataHandling::EHexilMetadataHandling )
+    	{
+    	TRAP_IGNORE( GetRmTypeL( file, aObjectType ) );
+    	}
+    else
+    	{
+    	WRITELOG1( "CHarvesterVideoPlugin::GetObjectType - ERROR: %S. No handling library found", &aUri );
+    	}
+
+    file.Close();
+	}
+
+void CHarvesterVideoPlugin::HarvestL( CHarvesterData* aHD )
+	{
+    CMdEObject& mdeObject = aHD->MdeObject();
+    CVideoHarvestData* fileData = new (ELeave) CVideoHarvestData;
+    CleanupStack::PushL( fileData );
+    
+#ifdef _DEBUG    
+    WRITELOG1("CHarvesterVideoPlugin::HarvestL - aHD->Uri() %S", &aHD->Uri() );
+    WRITELOG1("CHarvesterVideoPlugin::HarvestL - mdeObject.Uri() %S", &mdeObject.Uri() );
+#endif
+    
+    TRAPD( error, GatherDataL( mdeObject, *fileData ) );
+    if ( error == KErrNone || error == KErrCompletion )
+    	{
+        TBool isNewObject( mdeObject.Id() == 0 );
+        
+        if ( isNewObject || mdeObject.Placeholder() )
+            {
+            TRAP( error, HandleObjectPropertiesL( *aHD, *fileData, ETrue ) );
+            mdeObject.SetPlaceholder( EFalse );
+            }
+        else
+            {
+            TRAP( error, HandleObjectPropertiesL( *aHD, *fileData, EFalse ) );
+            }
+
+        if ( error != KErrNone )
+            {
+            WRITELOG1( "CHarvesterVideoPlugin::HarvestSingleFileL() - Handling object failed: ", error );
+            }
+    	}
+    else
+        {
+        WRITELOG1( "CHarvesterVideoPlugin::HarvestSingleFileL() - TRAP error: %d", error );
+        TInt convertedError = KErrNone;
+        MdsUtils::ConvertTrapError( error, convertedError );
+        aHD->SetErrorCode( convertedError );
+        }
+
+    CleanupStack::PopAndDestroy( fileData );
+	}
+
+// ---------------------------------------------------------------------------
+// GatherDataL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterVideoPlugin::GatherDataL( CMdEObject& aMetadataObject,
+		CVideoHarvestData& aVHD )
+    {
+    const TDesC& uri = aMetadataObject.Uri();
+    
+    WRITELOG1( "CHarvesterVideoPlugin - Gather data from file %S", &uri );
+    
+    RFile64 file;
+    TInt error = file.Open( iFs, uri, EFileRead | EFileShareReadersOnly );
+    CleanupClosePushL( file );
+    if ( error == KErrInUse ||
+         error == KErrLocked )
+        {
+        WRITELOG( "CHarvesterVideoPlugin - File is open!" );
+        CleanupStack::PopAndDestroy( &file );
+        User::Leave( KErrInUse );
+        }
+    else if( error == KErrNotFound ||
+                error == KErrPathNotFound ||
+                error == KErrDisMounted ||
+                error == KErrBadDescriptor )
+        {
+        WRITELOG1( "CHarvesterVideoPlugin - File open error: %d", error );
+        CleanupStack::PopAndDestroy( &file );
+        User::Leave( error );
+        }
+    
+    TBool dataExtracted( aMetadataObject.Id() == 0 || aMetadataObject.Placeholder() );
+    
+    if( dataExtracted )
+        {
+        CMdEProperty* prop = NULL;
+        CMdEObjectDef& objectDef = aMetadataObject.Def();
+        CMdEPropertyDef& sizeDef = objectDef.GetPropertyDefL( MdeConstants::Object::KSizeProperty );
+        aMetadataObject.Property( sizeDef, prop );
+        if( prop )
+            {
+            aVHD.iFileSize  = prop->Uint32ValueL();
+            }
+        else
+            {
+            dataExtracted = EFalse;
+            }
+        CMdEPropertyDef& modifiedDef = objectDef.GetPropertyDefL( MdeConstants::Object::KLastModifiedDateProperty );
+        aMetadataObject.Property( modifiedDef, prop );
+        if( prop )
+            {
+            aVHD.iModified  = prop->TimeValueL();
+            }
+        else
+            {
+            dataExtracted = EFalse;
+            }
+        }
+    
+    if( !dataExtracted )
+        {
+        TEntry entry;
+        const TInt errorcode = iFs.Entry( uri, entry );
+        
+        if ( errorcode != KErrNone )
+            {
+            WRITELOG1( "CHarvesterVideoPlugin - Error getting entry: %d", errorcode );
+            CleanupStack::PopAndDestroy( &file );
+            User::Leave( errorcode );
+            }
+        
+        aVHD.iModified = entry.iModified;
+        aVHD.iFileSize = (TUint)entry.iSize;
+        }
+    
+    WRITELOG1( "CHarvesterVideoPlugin - File size: %d", aVHD.iFileSize );
+
+    // now the minimum information has been harvested
+    // from now on the harvested data should always be stored
+
+    const THarvestingHandling* mapping = FindHandler( uri );
+    
+    if( !mapping )
+    	{
+    	CleanupStack::PopAndDestroy( &file );
+    	User::Leave( KErrNotFound );
+    	}
+
+    aVHD.iVideoObject = aMetadataObject.Def().Name().Compare( KVideo ) == 0;
+
+    if( error != KErrNone )
+        {
+        WRITELOG1( "CHarvesterVideoPlugin - File open error: %d", error );
+        CleanupStack::PopAndDestroy( &file );
+        User::Leave( KErrCompletion );
+        }
+    
+    if ( mapping->iHandler.iLibrary == TVideoMetadataHandling::EHexilMetadataHandling )
+    	{
+    	// doesn't own pointers to MIME types
+    	RPointerArray<HBufC> mimes;
+    	CleanupClosePushL( mimes );
+    	
+    	CHXMetaDataUtility* helixMetadata = CHXMetaDataUtility::NewL();
+        CleanupStack::PushL( helixMetadata );
+        
+        TRAP( error, helixMetadata->OpenFileL( file ) );        
+        
+        if ( error == KErrNone )
+        	{
+        	HBufC *buf = NULL;
+        	HXMetaDataKeys::EHXMetaDataId metaid;        	
+        	TUint metacount = 0;
+        	helixMetadata->GetMetaDataCount( metacount );
+        	TLex lex;
+        	for ( TUint i = 0; i < metacount; i++ )
+        		{        		
+        		helixMetadata->GetMetaDataAt( i, metaid, buf );
+        		switch (metaid)
+        			{
+        			case HXMetaDataKeys::EHXVideoBitRate:
+	        			{
+        				WRITELOG( "CHarvesterVideoPlugin - found videobitrate" );
+	        			if( aVHD.iVideoObject )
+	        				{
+	        				lex.Assign( *buf );
+	        				if( KErrNone == lex.Val( aVHD.iVideoBitrate ) )
+	        					{
+	        					aVHD.iVideoBitrate /= KKiloBytes;
+	        					}
+	        				}
+	        			break;
+	        			}
+        			case HXMetaDataKeys::EHXAudioBitRate:
+	        			{
+	        			WRITELOG( "CHarvesterVideoPlugin - found audiobitrate" );
+	        			lex.Assign( *buf );
+	        			if( KErrNone == lex.Val( aVHD.iAudioBitrate ) )
+	        				{
+	        				aVHD.iAudioBitrate /= KKiloBytes;
+	        				}
+	        			break;
+	        			}
+        			case HXMetaDataKeys::EHXClipBitRate:
+        				{
+        				WRITELOG( "CHarvesterVideoPlugin - found clipbitrate" );
+	        			lex.Assign( *buf );
+	        			if( KErrNone == lex.Val( aVHD.iClipBitrate ) )
+							{
+							aVHD.iClipBitrate /= KKiloBytes;
+							}
+        				break;
+        				}
+        			case HXMetaDataKeys::EHXDuration:
+	        			{
+	        			WRITELOG( "CHarvesterVideoPlugin - found duration" );
+	        			lex.Assign(*buf);
+	        			if( KErrNone == lex.Val( aVHD.iDuration ) )
+							{
+							aVHD.iDuration /= KThousandReal;
+							}
+						break;
+	        			}
+        			case HXMetaDataKeys::EHXFramesPerSecond:
+	        			{
+	        			WRITELOG( "CHarvesterVideoPlugin - found framerate" );
+	        			lex.Assign( *buf );
+	        			lex.Val( aVHD.iFrameRate );
+	        			break;
+	        			}
+        			case HXMetaDataKeys::EHXCopyright:
+	        			{
+	        			aVHD.iCopyright = buf->Alloc();
+	        			break;
+	        			}
+        			case HXMetaDataKeys::EHXAuthor:
+	        			{
+	        			aVHD.iAuthor = buf->Alloc();
+	        			break;
+	        			}
+        			case HXMetaDataKeys::EHXGenre:
+	        			{
+	        			aVHD.iGenre = buf->Alloc();
+	        			break;
+	        			}
+        			case HXMetaDataKeys::EHXPerformer:
+	        			{
+	        			aVHD.iPerformer = buf->Alloc();
+	        			break;
+	        			}
+        			case HXMetaDataKeys::EHXDescription:
+	        			{
+	        			aVHD.iDescription = buf->Alloc();
+	        			break;
+	        			}
+        			case HXMetaDataKeys::EHXMimeType:
+	        			{
+	        			mimes.AppendL( buf );
+	        			if( aVHD.iCodec == 0 )
+	        			    {
+	        			    CheckForCodecSupport( buf, aVHD );
+	        			    }
+	        			break;
+	        			}
+                    case HXMetaDataKeys::EHXFrameSize:
+                        {
+                        const TChar separator = 'x';    // as in e.g."177x144"
+                        const TInt separatorLocation = buf->Locate( separator );
+                        TLex input( buf->Left( separatorLocation ) );
+
+                        input.Val( aVHD.iFrameWidth );
+                        input = buf->Right(buf->Length() - separatorLocation - 1);
+                        input.Val( aVHD.iFrameHeight );
+	        			break;
+	        			}
+        			default:
+        				break;
+        			}
+        		}
+        	}
+
+        const TInt mimeCount = mimes.Count();
+        
+        TPtrC mime( NULL, 0 );
+
+        // if metadata didn't contain MIME, get it from extension mapping
+        if( mimeCount == 0 )
+        	{
+        	if( aVHD.iVideoObject )
+        		{
+        		mime.Set( mapping->iHandler.iVideoMime.Ptr(),
+        				mapping->iHandler.iVideoMime.Length() );
+        		}
+        	else
+        		{
+        		mime.Set( mapping->iHandler.iAudioMime.Ptr(),
+        				mapping->iHandler.iAudioMime.Length() );
+        		}
+        	}
+        // otherwise search from MIME type array
+        else
+        	{
+	        for( TInt i = 0; i < mimeCount; i++ )
+	        	{
+	        	HBufC* mimeTmp = mimes[i];
+	        	
+	        	if( !mimeTmp )
+	        		{
+	        		continue;
+	        		}
+	        	
+	        	mime.Set( mimeTmp->Des().Ptr(), mimeTmp->Des().Length() );
+
+	        	// MIME contains substring "application/vnd.rn-realmedia".
+	        	// That case MIME matches also with 
+	        	// string "application/vnd.rn-realmedia-vbr".
+	        	if( MdsUtils::Find( mime, KMimeTypeRm() ) != KErrNotFound )
+	        		{
+	        		break;
+	        		}
+	        	// Match MIME type, for video object with "video" substring
+	        	else if( aVHD.iVideoObject )
+	        		{
+	        		if( MdsUtils::Find( mime, KVideo() ) != KErrNotFound )
+		        		{
+		        		break;
+		        		}
+	        		}
+	        	// Match MIME type for audio object with "audio" substring
+	        	else if( MdsUtils::Find( mime, KAudio() ) != KErrNotFound )
+	        		{
+	        		break;
+	        		}
+	        	}
+	        }
+        
+        if( mime.Ptr() && ( mime.Length() > 0 ) )
+        	{
+        	aVHD.iMimeBuf = mime.Alloc();
+        	}
+        
+        CleanupStack::PopAndDestroy( helixMetadata );
+        
+        // don't destory mime type pointers just clean array
+        CleanupStack::PopAndDestroy( &mimes );
+        }
+    else if( mapping->iHandler.iLibrary == TVideoMetadataHandling::EMp4LibHandling )
+        {
+        MP4Handle handle( 0 );
+        MP4Err mp4err = MP4_OK;
+        
+        WRITELOG( "CHarvesterVideoPlugin - Before open file handle to parse" );
+        
+        WRITELOG( "CHarvesterVideoPlugin - GatherDataL - MP4ParseOpenFileHandle - start" ); 
+		
+        mp4err = MP4ParseOpenFileHandle64( &handle, &file );
+       
+        WRITELOG( "CHarvesterVideoPlugin - GatherDataL - MP4ParseOpenFileHandle - ready" );            
+        
+        if ( mp4err != MP4_OK )
+            {
+            WRITELOG( "CHarvesterVideoPlugin - Error opening file handle" );
+            
+            CleanupStack::PopAndDestroy( &file );     
+            User::Leave( KErrCompletion );
+            }
+        
+        WRITELOG( "CHarvesterVideoPlugin - Start gathering" );
+        
+        if( aVHD.iVideoObject )
+        	{
+            mp4_u32 videolength( 0 );
+            mp4_double framerate( 0 );
+            mp4_u32 videotype( 0 );
+            mp4_u32 videowidth( 0 );
+            mp4_u32 videoheight( 0 );
+            mp4_u32 timescale( 0 );
+
+	        WRITELOG( "CHarvesterVideoPlugin - GatherDataL - MP4ParseRequestVideoDescription - start" );
+	        mp4err = MP4ParseRequestVideoDescription( handle, &videolength, &framerate, 
+	        		&videotype, &videowidth, &videoheight, &timescale );
+	        WRITELOG( "CHarvesterVideoPlugin - GatherDataL - MP4ParseRequestVideoDescription - ready" );
+
+	        if ( mp4err == MP4_OK )
+	            {
+	            aVHD.iDuration = videolength / KThousandReal;
+		        aVHD.iFrameRate = framerate;
+		        aVHD.iFrameWidth = videowidth;
+		        aVHD.iFrameHeight = videoheight;
+	            }
+
+	        mp4_u32 streamSize( 0 );
+	        mp4_u32 avgBitrate( 0 );
+
+	        WRITELOG( "CHarvesterVideoPlugin - GatherDataL - MP4ParseRequestStreamDescription - start" );            
+	        mp4err = MP4ParseRequestStreamDescription( handle, &streamSize, &avgBitrate );
+	        WRITELOG( "CHarvesterVideoPlugin - GatherDataL - MP4ParseRequestStreamDescription - ready" );            
+
+	        if ( mp4err == MP4_OK )
+	            {
+	            aVHD.iClipBitrate = avgBitrate / KKiloBytes;
+	            }
+
+       		aVHD.iMimeBuf = mapping->iHandler.iVideoMime.Alloc();
+        	}
+        else
+        	{
+        	mp4_u32 audiolength;
+        	mp4_u32 audiotype;
+        	mp4_u8 framespersample;
+        	mp4_u32 timescale;
+        	mp4_u32 averagebitrate;
+
+        	WRITELOG( "CHarvesterVideoPlugin - GatherDataL - MP4ParseRequestVideoDescription - start" );
+        	mp4err = MP4ParseRequestAudioDescription( handle, &audiolength, &audiotype, 
+        			&framespersample, &timescale, &averagebitrate );
+        	WRITELOG( "CHarvesterVideoPlugin - GatherDataL - MP4ParseRequestAudioDescription - ready" );
+
+        	if ( mp4err == MP4_OK )
+	            {
+	            aVHD.iDuration = audiolength / KThousandReal;
+	        	aVHD.iSamplingFrequency = timescale;
+	        	aVHD.iAudioBitrate = averagebitrate / KKiloBytes;
+	            }
+
+       		aVHD.iMimeBuf = mapping->iHandler.iAudioMime.Alloc();
+        	}
+
+        WRITELOG( "CHarvesterVideoPlugin - Stop gathering" );
+
+        WRITELOG( "CHarvesterVideoPlugin - GatherDataL - MP4ParseClose - start" );            
+        mp4err = MP4ParseClose( handle );
+        WRITELOG( "CHarvesterVideoPlugin - GatherDataL - MP4ParseClose - ready" );            
+        if ( mp4err != MP4_OK )
+            {
+            WRITELOG( "CHarvesterVideoPlugin - Error closing file handle" );
+            }
+        }
+    WRITELOG( "CHarvesterVideoPlugin - Closing file" );        
+    CleanupStack::PopAndDestroy( &file );        
+
+    WRITELOG( "CHarvesterVideoPlugin - Start adding data to object" );
+    }
+
+// ---------------------------------------------------------------------------
+// HandleNewObjectL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterVideoPlugin::HandleObjectPropertiesL( 
+		CHarvesterData& aHD,
+		CVideoHarvestData& aVHD,
+		TBool aIsAdd )
+    {
+    WRITELOG("CHarvesterVideoPlugin::HandleObjectPropertiesL ");
+
+    CMdEObject& mdeObject = aHD.MdeObject();
+
+    if( !iPropDefs )
+    	{
+    	CMdEObjectDef& objectDef = mdeObject.Def();
+    	iPropDefs = CHarvesterVideoPluginPropertyDefs::NewL( objectDef );
+    	}
+
+    TTimeIntervalSeconds timeOffsetSeconds = User::UTCOffset();
+    TTime localModifiedDate = aVHD.iModified + timeOffsetSeconds;
+
+    if( !mdeObject.Placeholder() )
+    	{
+    	// Creation date
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iCreationDatePropertyDef, &localModifiedDate, aIsAdd );
+    
+    	// Last modified date
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iLastModifiedDatePropertyDef, &aVHD.iModified, aIsAdd );
+    
+    	// File size
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iSizePropertyDef, &aVHD.iFileSize, aIsAdd );
+    	}
+
+    // Release date
+	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iReleaseDatePropertyDef, &localModifiedDate, aIsAdd );
+
+	// Capture date
+	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iCaptureDatePropertyDef, &localModifiedDate, aIsAdd );
+
+	// Time offset
+	TInt16 timeOffsetMinutes = timeOffsetSeconds.Int() / 60;
+	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iTimeOffsetPropertyDef, &timeOffsetMinutes, aIsAdd );
+
+    // Item Type
+	if( aVHD.iMimeBuf )
+		{
+		CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iItemTypePropertyDef, aVHD.iMimeBuf, aIsAdd );
+		}
+
+    // Duration
+	if( aVHD.iDuration != 0.0f )
+		{
+		CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iDurationPropertyDef, &aVHD.iDuration, aIsAdd );
+		}
+
+	if( aVHD.iVideoObject )
+		{
+	    // Width
+	    if (aVHD.iFrameWidth != 0)
+	        {
+	    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iWidthPropertyDef, &aVHD.iFrameWidth, aIsAdd );
+	        }
+
+	    // Height
+	    if (aVHD.iFrameHeight != 0)
+	        {
+	    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iHeightPropertyDef, &aVHD.iFrameHeight, aIsAdd );
+	        }
+	
+	    // Framerate
+	    if (aVHD.iFrameRate != 0)
+	    	{
+	    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iFrameratePropertyDef, &aVHD.iFrameRate, aIsAdd );
+	    	}
+		}
+	else // audio object
+		{
+		// Sampling frequency
+	    if (aVHD.iSamplingFrequency != 0.0f)
+	        {
+	    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iSamplingFrequencyPropertyDef, &aVHD.iSamplingFrequency, aIsAdd );
+	        }
+		}
+
+	// Bitrate
+    if (aVHD.iClipBitrate != 0)
+    	{
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iBitratePropertyDef, &aVHD.iClipBitrate, aIsAdd );
+    	}
+    else
+    	{
+    	if( aVHD.iVideoObject )
+    		{
+    		CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iBitratePropertyDef, &aVHD.iVideoBitrate, aIsAdd );
+    		}
+    	else // audio object
+    		{
+    		CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iBitratePropertyDef, &aVHD.iAudioBitrate, aIsAdd );
+    		}
+    	}
+
+    // Copyright
+    if( aVHD.iCopyright )
+    	{
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iCopyrightPropertyDef, aVHD.iCopyright, aIsAdd );
+    	}
+
+    // Author
+    if( aVHD.iAuthor )
+    	{
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iAuthorPropertyDef, aVHD.iAuthor, aIsAdd );
+    	}
+
+    // Genre
+    if( aVHD.iGenre )
+    	{
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iGenrePropertyDef, aVHD.iGenre, aIsAdd );
+    	}
+
+    // Artist
+    if( aVHD.iPerformer )
+    	{
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iArtistPropertyDef, aVHD.iPerformer, aIsAdd );
+    	}
+
+    // Description
+    if( aVHD.iDescription )
+    	{
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iDescriptionPropertyDef, aVHD.iDescription, aIsAdd );
+    	}
+    
+    // Codec
+    if( aVHD.iCodec != 0 )
+        {
+        CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iAudioFourCCDef, &aVHD.iCodec, aIsAdd );
+        }
+    }
+
+void CHarvesterVideoPlugin::GetMp4Type( RFile64& aFile, TDes& aType )
+	{
+    WRITELOG( "CHarvesterVideoPlugin::GetMp4Mime - MP4ParseOpenFileHandle - start" );
+    MP4Handle handle;
+
+    MP4Err mp4err = MP4ParseOpenFileHandle64( &handle, &aFile );
+    
+    WRITELOG( "CHarvesterVideoPlugin::GetMp4Mime - MP4ParseOpenFileHandle - ready" );
+
+    if ( mp4err != MP4_OK )
+        {
+        WRITELOG( "CHarvesterVideoPlugin::GetMp4Mime - Error opening file handle" ); 
+        return;
+        }
+
+    WRITELOG( "CHarvesterVideoPlugin::GetMp4Mime - MP4ParseRequestVideoDescription - start" );
+    mp4_u32 videolength;
+    mp4_double framerate;
+    mp4_u32 videowidth;
+    mp4_u32 videoheight;
+    mp4_u32 timescale;
+    mp4_u32 videotype;
+    mp4err = MP4ParseRequestVideoDescription( handle, &videolength,
+    		&framerate, &videotype, &videowidth, &videoheight, &timescale );
+    WRITELOG( "CHarvesterVideoPlugin::GetMp4Mime - MP4ParseRequestVideoDescription - ready" );
+
+    // If no video stream found, set to Audio
+    if ( mp4err == MP4_NO_VIDEO )
+        {
+        WRITELOG( "CHarvesterVideoPlugin::GetMp4Mime - No video stream found, set to Audio" );
+        aType.Copy( KAudio() );
+        }
+    // Otherwise set to Video, regardless how badly file is corrupted
+    else
+    	{
+    	aType.Copy( KVideo() );
+    	}
+
+    MP4ParseClose( handle );
+	}
+
+void CHarvesterVideoPlugin::GetRmTypeL( RFile64& aFile, TDes& aType )
+	{
+	TBool possibleVideo = EFalse;
+
+	CHXMetaDataUtility* helixMetadata = CHXMetaDataUtility::NewL();
+	CleanupStack::PushL( helixMetadata );
+
+	TRAPD( err, helixMetadata->OpenFileL( aFile ) );
+
+	if( err == KErrNone )
+		{
+		// doesn't own pointers to MIME types
+		RPointerArray<HBufC> mimes;
+		CleanupClosePushL( mimes );
+		
+		TUint metacount = 0;
+		helixMetadata->GetMetaDataCount(metacount);
+		for (TUint i = 0; i < metacount; i++)
+			{
+			HBufC *buf = NULL;
+			HXMetaDataKeys::EHXMetaDataId metaid;
+			helixMetadata->GetMetaDataAt( i, metaid, buf );
+			if( metaid == HXMetaDataKeys::EHXMimeType )
+				{
+				mimes.AppendL( buf );
+				}
+			else if( metaid == HXMetaDataKeys::EHXVideoBitRate )
+				{
+				possibleVideo = ETrue;
+				}
+			}
+	
+		const TInt mimeCount = mimes.Count();
+		
+		// at least one MIME type must be found
+		if( mimeCount == 0 )
+			{
+			User::Leave( KErrNotFound );
+			}
+	
+		for( TInt i = 0; i < mimeCount; i++ )
+			{
+			HBufC* mime = mimes[i];
+	
+			// "application/vnd.rn-realmedia" or "application/vnd.rn-realmedia-vbr"
+			if( MdsUtils::Find( *mime, KMimeTypeRm() ) != KErrNotFound )
+				{
+				WRITELOG1( "CHarvesterVideoPlugin::GetObjectType - mimetype %S. Object type Rm", mime );
+				if( possibleVideo )
+					{
+					aType.Copy( KVideo );
+					}
+				else
+					{
+					aType.Copy( KAudio );
+					}
+				
+				break;
+				}
+			else if( MdsUtils::Find( *mime, KVideo() ) != KErrNotFound )
+				{
+				WRITELOG1( "CHarvesterVideoPlugin::GetObjectType - mimetype %S. Object type Video", mime );
+				aType.Copy( KVideo );
+	
+				// use MIME with "video" substring, if file might be video
+				if( possibleVideo )
+					{
+					break;
+					}
+				}
+			else if( MdsUtils::Find( *mime, KAudio() ) != KErrNotFound )
+				{
+				WRITELOG1( "CHarvesterVideoPlugin::GetObjectType - mimetype %S. Object type Audio", mime );
+				aType.Copy( KAudio );
+				}
+			// Set to Video, regardless how badly file is corrupted
+			else
+				{
+				aType.Copy( KVideo );
+				}
+			}
+		
+	    // don't destory mime type pointers just clean array
+	    CleanupStack::PopAndDestroy( &mimes );
+		}
+	// Set to Video, regardless how badly file is corrupted
+	else
+		{
+		aType.Copy( KVideo );
+		}
+    
+    CleanupStack::PopAndDestroy( helixMetadata );
+	}
+
+const THarvestingHandling* CHarvesterVideoPlugin::FindHandler( const TDesC& aUri )
+	{
+	TParsePtrC parse( aUri );
+    TPtrC ext = parse.Ext();
+
+    // remove '.' from extension
+    if ( ext.Length() > 1 )
+        {
+        ext.Set( ext.Mid( 1 ) );
+        }
+    else
+    	{
+    	WRITELOG1( "CHarvesterVideoPlugin::GetObjectType - ERROR: %S. No any extension found", &aUri );
+    	return NULL;
+    	}
+
+    THarvestingHandling finder( ext );
+
+	TLinearOrder<THarvestingHandling> cmp(THarvestingHandling::CompareFunction);
+
+	TInt pos = iMimeTypeMappings.FindInOrder( finder, cmp );
+
+	// no matching extension found or extension is missing from filename
+    if( KErrNotFound == pos || ext.Length() <= 0 )
+    	{
+    	WRITELOG1( "CHarvesterVideoPlugin::GetObjectType - ERROR: %S. No extension found", &aUri );
+		return NULL;
+    	}
+
+    const THarvestingHandling* mapping = &iMimeTypeMappings[pos];
+	
+	return mapping;
+	}
+
+void CHarvesterVideoPlugin::CheckForCodecSupport( HBufC* aMimeBuffer, CVideoHarvestData& aVHD )
+    {
+    if( !aMimeBuffer )
+        {
+        return;
+        }
+    
+    TPtrC mime( NULL, 0 );
+    mime.Set( aMimeBuffer->Des().Ptr(), aMimeBuffer->Des().Length() );
+    
+    if( MdsUtils::Find( mime, KAudioAC3() ) != KErrNotFound )
+        {
+        aVHD.iCodec = KMDSFourCCCodeAC3;
+        return;
+        }
+    
+    if( MdsUtils::Find( mime, KAudioEAC3() ) != KErrNotFound )
+        {
+        aVHD.iCodec = KMDSFourCCCodeEAC3;
+        return;
+        }
+    return;
+    }
+
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/VideoPlugin/src/proxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation proxy*
+*/
+
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include "harvestervideoplugin.h"
+
+// Map the interface UIDs to implementation factory functions
+const TImplementationProxy KImplementationTable[] = 
+	{
+		{{0x200009FA},	(TProxyNewLPtr)CHarvesterVideoPlugin::NewL}
+	};
+
+// Exported proxy for instantiation method resolution
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+	{
+	aTableCount = sizeof( KImplementationTable ) / sizeof( TImplementationProxy );
+	return KImplementationTable;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/WMVPlugin/data/2000B431.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource definitions for project harvesterwmvplugin
+*
+*/
+
+#include "registryinfov2.rh"
+
+// -----------------------------------------------------------------------------
+// registry_info
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE REGISTRY_INFO registry_info
+    {
+    // resource_format_version must always be set as follows
+    resource_format_version = RESOURCE_FORMAT_VERSION_2;
+    
+    dll_uid = 0x2000B431; // UID of the plugin DLL 
+
+    // Declare array of interface info
+    interfaces =
+        {
+        INTERFACE_INFO
+            {
+            // UID of harvester plugin interface that is implemented
+            interface_uid = 0x200009F8;
+            implementations = 
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid  =  0x2000B432;
+                    version_no          =  1;
+                    display_name        =  "Harvester WMV Plugin";
+                    default_data        =  "Video";
+                    opaque_data         =  "wm wmv asf";
+                    rom_only = 0;
+                    }
+                };
+            }
+        };
+    }
+    
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/WMVPlugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+harvesterwmvplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/WMVPlugin/group/harvesterwmvplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION					        10.0
+TARGET                  harvesterwmvplugin.dll
+TARGETTYPE              PLUGIN
+UID                     0x10009D8D 0x2000B431
+
+CAPABILITY              CAP_ECOM_PLUGIN
+VENDORID                VID_DEFAULT
+
+SOURCEPATH              ../src
+SOURCE                  harvesterwmvproxy.cpp
+SOURCE                  harvesterwmvplugin.cpp
+
+START RESOURCE ../data/2000B431.rss
+TARGET harvesterwmvplugin.rsc
+END
+
+USERINCLUDE   ../../../../inc
+USERINCLUDE   ../../../../harvester/server/inc
+USERINCLUDE   ../../../../harvester/common/inc
+USERINCLUDE    ../inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+SYSTEMINCLUDE /epoc32/include/ecom
+SYSTEMINCLUDE /epoc32/include/caf
+
+LIBRARY       caf.lib
+LIBRARY       euser.lib
+LIBRARY       efsrv.lib
+LIBRARY       harvestercommon.lib
+LIBRARY       harvesterplugininterface.lib
+LIBRARY       mdeclient.lib
+LIBRARY	  harvesterdata.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/WMVPlugin/inc/harvesterwmvplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,170 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvests metadata for wmv video file
+*
+*/
+
+#ifndef C_HARVESTERWMVPLUGIN_H
+#define C_HARVESTERWMVPLUGIN_H
+
+#include <e32base.h>
+#include <apmstd.h>
+
+// forward declaration
+class CMdEPropertyDef;
+class CMdEObjectDef;
+
+const TInt KMaxTitleLength( 255 ); //to fit in db
+const TInt KMaxMimeTypeLength( KMaxDataTypeLength );
+
+/**
+ * Helper class to hold all property definitions 
+ * (pointers are not owned) used in harvester OMA DRM plug-in.
+ */
+class CHarvesterWmvPluginPropertyDefs : public CBase
+	{
+	public:
+		// Common property definitions
+		CMdEPropertyDef* iCreationDatePropertyDef;
+		CMdEPropertyDef* iLastModifiedDatePropertyDef;
+		CMdEPropertyDef* iSizePropertyDef;
+		CMdEPropertyDef* iItemTypePropertyDef;
+		
+	private:
+		CHarvesterWmvPluginPropertyDefs();
+	
+		void ConstructL(CMdEObjectDef& aObjectDef);
+
+	public:	
+		static CHarvesterWmvPluginPropertyDefs* NewL(CMdEObjectDef& aObjectDef);
+	};
+
+/**
+ *  Data class for wmv harvester
+ *
+ *  Includes clip metadata to save to db.
+ *
+ */
+class CHarvesterWmvClipDetails : public CBase
+    {
+public:
+
+    /** NewL */
+    static CHarvesterWmvClipDetails* NewL()
+        {
+        CHarvesterWmvClipDetails* self = new (ELeave) CHarvesterWmvClipDetails;
+        return self;
+        }
+    
+    /** Destructor */
+    virtual ~CHarvesterWmvClipDetails()
+        {
+        }
+    
+public:
+
+    /**
+    * Mime type
+    */
+    TBuf<KMaxMimeTypeLength> iMimeType;
+
+    /**
+    * Modification date
+    */
+    TTime iModifiedDate;
+
+    /**
+    * File size
+    */
+    TUint32 iFileSize;
+
+private:
+
+    /**
+     * Default constructor
+     */
+    CHarvesterWmvClipDetails() : iFileSize( 0 )
+    {
+    }
+        
+    };
+
+#include <harvesterplugin.h>
+#include "harvesterdata.h"
+
+/**
+ *  This class implements WMV harvester plugin.
+ *
+ *  @lib harvesterwmvplugin.dll
+ *  @since S60 S60 v3.2
+ */
+class CHarvesterWMVPlugin : public CHarvesterPlugin
+    {
+public:
+
+    /**
+     * Constructs a new CHarvesterWMVPlugin implementation.
+     * 
+     * @return A pointer to the new CHarvesterWMVPlugin implementation
+     */
+    static CHarvesterWMVPlugin* NewL();
+ 
+    /**
+    * Destructor.
+    */
+    virtual ~CHarvesterWMVPlugin();
+
+// from base class CHarvesterPlugin
+    
+    /**
+    * Harvest file. 
+    * 
+    * @param aHarvesterData  
+    */
+    void HarvestL( CHarvesterData* aHarvesterData );
+
+private:
+
+    /**
+    * C++ constructor
+    */
+    CHarvesterWMVPlugin();
+
+    /**
+    * 2nd phase constructor
+    */
+    void ConstructL();
+    
+    /**
+     * Gathers data from file to meta data object. 
+     * Leaves if mime type is not supported
+     *
+     * @param aMetadataObject  Reference to metadata object to gather the data. 
+     */
+    void GatherDataL( CMdEObject& aMetadataObject, CHarvesterWmvClipDetails& aClipDetails );
+     
+     /**
+      * Handle object properties
+      */
+    void HandleObjectPropertiesL( 
+         CHarvesterData& aHD,
+         CHarvesterWmvClipDetails& aClipDetails,
+         TBool aIsAdd);
+
+
+private: // data
+	CHarvesterWmvPluginPropertyDefs* iPropDefs;
+    };
+
+#endif // C_HARVESTERWMVPLUGIN_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/WMVPlugin/src/harvesterwmvplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,212 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvests metadata from wmv video file 
+*
+*/
+
+#include <e32std.h>
+#include <caf/content.h>
+
+#include "mdsutils.h"
+#include "harvesterdata.h"
+#include "harvesterlog.h"
+#include "harvesterwmvplugin.h"
+#include <mdenamespacedef.h>
+#include <mdeobjectdef.h>
+#include "mdeobject.h"
+#include "mdetextproperty.h"
+#include "mdeobjectwrapper.h"
+
+CHarvesterWmvPluginPropertyDefs::CHarvesterWmvPluginPropertyDefs() : CBase()
+	{
+	}
+
+void CHarvesterWmvPluginPropertyDefs::ConstructL(CMdEObjectDef& aObjectDef)
+	{
+	CMdENamespaceDef& nsDef = aObjectDef.NamespaceDef();
+	
+	// Common property definitions
+	CMdEObjectDef& objectDef = nsDef.GetObjectDefL( MdeConstants::Object::KBaseObject );
+	iCreationDatePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KCreationDateProperty );
+	iLastModifiedDatePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KLastModifiedDateProperty );
+	iSizePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KSizeProperty );
+	iItemTypePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KItemTypeProperty );
+	}
+
+CHarvesterWmvPluginPropertyDefs* CHarvesterWmvPluginPropertyDefs::NewL(CMdEObjectDef& aObjectDef)
+	{
+	CHarvesterWmvPluginPropertyDefs* self = 
+		new (ELeave) CHarvesterWmvPluginPropertyDefs();
+	CleanupStack::PushL( self );
+	self->ConstructL( aObjectDef );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// Constructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterWMVPlugin* CHarvesterWMVPlugin::NewL()
+    {
+    CHarvesterWMVPlugin* self = new(ELeave) CHarvesterWMVPlugin();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterWMVPlugin::~CHarvesterWMVPlugin()
+    {
+    WRITELOG( "CHarvesterWMVPlugin::~CHarvesterWMVPlugin()" );
+    }
+
+// ---------------------------------------------------------------------------
+// Harvest file
+// ---------------------------------------------------------------------------
+//
+void CHarvesterWMVPlugin::HarvestL( CHarvesterData* aHD )    
+    {
+    WRITELOG( "CHarvesterWMVPlugin::Harvest()" );
+    CMdEObject& mdeObject = aHD->MdeObject();
+    
+    CHarvesterWmvClipDetails* clipDetails = CHarvesterWmvClipDetails::NewL();
+    CleanupStack::PushL( clipDetails );
+    
+    TRAPD( error, GatherDataL( mdeObject, *clipDetails ) );
+    if ( error == KErrNone || error == KErrCompletion )
+    	{
+    	TBool isNewObject( mdeObject.Id() == 0 );
+        
+        if ( isNewObject || mdeObject.Placeholder() )
+            {
+            TRAP( error, HandleObjectPropertiesL( *aHD, *clipDetails, ETrue ) );
+            mdeObject.SetPlaceholder( EFalse );
+            }
+        else
+            {
+            TRAP( error, HandleObjectPropertiesL( *aHD, *clipDetails, EFalse ) );
+            }
+
+        if ( error != KErrNone )
+            {
+            WRITELOG1( "CHarvesterWMVPlugin::HarvestL() - Handling object failed: ", error );
+            }
+    	}
+    else
+        {
+        TInt convertedError = KErrNone;
+        MdsUtils::ConvertTrapError( error, convertedError );
+        aHD->SetErrorCode( convertedError );
+        }
+    
+    CleanupStack::PopAndDestroy( clipDetails );
+    }
+
+// ---------------------------------------------------------------------------
+// Default constructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterWMVPlugin::CHarvesterWMVPlugin() : CHarvesterPlugin(), iPropDefs( NULL )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// 2nd phase constructor
+// ---------------------------------------------------------------------------
+//
+void CHarvesterWMVPlugin::ConstructL()
+    {
+    WRITELOG( "CHarvesterWMVPlugin::ConstructL()" );
+    }
+
+// ---------------------------------------------------------------------------
+// GatherDataL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterWMVPlugin::GatherDataL( CMdEObject& aMetadataObject, CHarvesterWmvClipDetails& aClipDetails )
+    {
+    WRITELOG( "CHarvesterWMVPlugin::GatherDataL()" );
+       
+    const TDesC& uri = aMetadataObject.Uri();
+
+    TInt error ( KErrNone );
+    TEntry* entry = new (ELeave) TEntry();
+    CleanupStack::PushL( entry );
+
+    User::LeaveIfError( iFs.Entry( uri, *entry ) );
+
+    aClipDetails.iModifiedDate = entry->iModified;
+    aClipDetails.iFileSize = (TUint)entry->iSize;
+    
+    CleanupStack::PopAndDestroy( entry );
+    
+    ContentAccess::CContent* content = ContentAccess::CContent::NewLC( uri );
+
+    //Mime type check
+    error = content->GetStringAttribute( ContentAccess::EMimeType, aClipDetails.iMimeType );
+    if (  error != KErrNone )
+        {
+        WRITELOG( "CHarvesterWMVPlugin - Could not resolve mime type, leave!" );
+        User::Leave( KErrNotSupported );
+        }
+
+    CleanupStack::PopAndDestroy( content );  
+    }
+
+// ---------------------------------------------------------------------------
+// Handle object properties
+// ---------------------------------------------------------------------------
+//
+void CHarvesterWMVPlugin::HandleObjectPropertiesL( 
+    CHarvesterData& aHD,
+    CHarvesterWmvClipDetails& aClipDetails,
+    TBool aIsAdd )
+    {
+    WRITELOG( "CHarvesterWMVPlugin::HandleObjectPropertiesL()" );
+    
+    CMdEObject& mdeObject = aHD.MdeObject();
+    
+    if( !iPropDefs )
+		{
+		CMdEObjectDef& objectDef = mdeObject.Def();
+		iPropDefs = CHarvesterWmvPluginPropertyDefs::NewL( objectDef );
+		}
+    
+    if( ! mdeObject.Placeholder() )
+    	{
+        // Creation date
+    	TTimeIntervalSeconds timeOffset = User::UTCOffset();
+    	TTime localModifiedDate = aClipDetails.iModifiedDate + timeOffset;
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    			*iPropDefs->iCreationDatePropertyDef, &localModifiedDate, aIsAdd );
+    	// Last modified date
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    			*iPropDefs->iLastModifiedDatePropertyDef, &aClipDetails.iModifiedDate, aIsAdd );
+    	// File size
+    	CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    			*iPropDefs->iSizePropertyDef, &aClipDetails.iFileSize, aIsAdd );
+    	}
+
+    // Mime Type
+    CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, 
+    		*iPropDefs->iItemTypePropertyDef, &aClipDetails.iMimeType, aIsAdd );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/WMVPlugin/src/harvesterwmvproxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,42 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include "harvesterwmvplugin.h"
+
+// --------------------------------------------------------------------------
+// Provide a key pair value table.
+// Used to identify the correct construction function
+// for the requested interface.
+// --------------------------------------------------------------------------
+//
+const TImplementationProxy ImplementationTable[] =
+    {
+    { { 0x2000B432 }, ( TProxyNewLPtr ) CHarvesterWMVPlugin::NewL }
+    };
+
+// --------------------------------------------------------------------------
+// Return an instance of the proxy table.
+// --------------------------------------------------------------------------
+//
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+    {
+    aTableCount = sizeof( ImplementationTable ) / sizeof( TImplementationProxy );
+    return ImplementationTable;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/harvesterplugins/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+#include "../ImagePlugin/group/bld.inf"
+#include "../MessagePlugin/group/bld.inf"
+#include "../VideoPlugin/group/bld.inf"
+#include "../OMADRMPlugin/group/bld.inf"
+#include "../WMVPlugin/group/bld.inf"
+#include "../RTPPlugin/group/bld.inf"
+#include "../AudioPlugin/group/bld.inf"
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/data/20007182.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// 20007182.RSS
+
+#include "registryinfov2.rh"
+
+// Declares info for one test implementation
+RESOURCE REGISTRY_INFO theInfo
+	{
+  // resource_format_version must always be set as follows
+  resource_format_version = RESOURCE_FORMAT_VERSION_2;
+    
+	// UID for the DLL
+	dll_uid = 0x20007182;
+	// Declare array of interface info
+	interfaces = 
+		{
+		INTERFACE_INFO
+			{
+			// UID of interface that is implemented
+			interface_uid = 0x20007181;
+			implementations = 
+				{
+				// Info for CHarvesterVideoPlugin
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x20007186;
+					version_no = 1;
+					display_name = "File monitor plugin";
+					default_data = "";
+					opaque_data = "";
+					rom_only = 0;
+					}
+				};
+			}
+		};
+	}
+
Binary file harvester/monitorplugins/fileplugin/data/20007182.txt has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+../data/20007182.txt /epoc32/data/z/private/10202BE9/20007182.txt
+../data/20007182.txt /epoc32/WINSCW/C/private/10202BE9/20007182.txt
+
+PRJ_MMPFILES
+filemonitorplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/group/filemonitorplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,64 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        filemonitorplugin.dll
+TARGETTYPE    PLUGIN
+UID           0x10009D8D 0x20007182
+
+CAPABILITY 	  CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+start RESOURCE ../data/20007182.rss
+target filemonitorplugin.rsc
+end
+
+SYSTEMINCLUDE /epoc32/include/ecom
+SYSTEMINCLUDE /epoc32/include/connect
+
+USERINCLUDE   ../../../../inc
+USERINCLUDE   ../../../common/inc
+USERINCLUDE   ../../../server/inc
+USERINCLUDE   ../../inc
+USERINCLUDE   ../inc
+
+SOURCEPATH    ../src
+SOURCE        filemonitorplugin.cpp
+SOURCE        proxy.cpp
+SOURCE        processoriginmapper.cpp
+SOURCE	  movetimer.cpp
+SOURCE	  FolderRenamer.cpp
+SOURCE        fileeventhandlerao.cpp
+SOURCE        filemonitorao.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       efsrv.lib
+LIBRARY       estor.lib
+LIBRARY       monitorplugininterface.lib
+LIBRARY       mdeclient.lib
+LIBRARY		  harvesterdata.lib
+LIBRARY       harvestercommon.lib 
+LIBRARY       centralrepository.lib
+
+OPTION ARMCC -O3 -OTime
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/inc/FolderRenamer.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,85 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#ifndef FOLDERRENAMER_H_
+#define FOLDERRENAMER_H_
+
+#include <e32base.h>
+#include <mdesession.h>
+
+class CFileEventHandlerAO;
+class TMdsFSPStatus;
+
+
+class CRenameItem : public CBase
+	{
+public:
+	static CRenameItem * NewL (const TDesC &aOldName, const TDesC &aNewName);
+
+	virtual ~CRenameItem();
+
+	void HandleFileEventsL(CFileEventHandlerAO &aCFileEventHandlerAO);
+	void AddFileEvent(TMdsFSPStatus &aEvent);
+	TPtrC OldName();
+	TPtrC NewName();
+
+private:
+	CRenameItem();
+	void ConstructL(const TDesC &aOldName, const TDesC &aNewName);
+
+private:
+	HBufC *iOldName;
+	HBufC *iNewName;
+	RPointerArray <TMdsFSPStatus> iFileEvents;		
+	};
+
+class CFolderRenamer : public CActive
+	{
+public:
+	virtual ~CFolderRenamer();
+	
+	void RenameL(const TDesC &aOldName, const TDesC &aNewName);
+	void HandleFileEventL(TMdsFSPStatus &aEvent);
+	void HandleFileEventsL( CArrayFixSeg< TMdsFSPStatus >* aEvents );
+	
+	static CFolderRenamer * NewL(CFileEventHandlerAO &aCFileEventHandlerAO);
+
+private:
+
+	enum TFolderRenameState
+	{
+	ERenameStateIdle,
+	ERenameStateRenaming,
+	ERenameStateWaitingMdeRename,
+	};
+
+	void ConstructL();
+	void DoCancel();
+	void RunL();
+    TInt RunError( TInt aError );
+	void SetNextRequest(TFolderRenameState aState);
+	CFolderRenamer(CFileEventHandlerAO &aCFileEventHandlerAO);
+
+private:
+	RPointerArray <CRenameItem> iRenamedFolders;		
+	TFolderRenameState iState;
+	CFileEventHandlerAO &iCFileEventHandlerAO;	
+public:
+	TBool iIsRunning;
+	};
+
+#endif /*FOLDERRENAMER_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/inc/fileeventhandlerao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,255 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors file creations, modifications and deletions.*
+*/
+
+
+#ifndef __FILEEVENTHANDLERAO_H__
+#define __FILEEVENTHANDLERAO_H__
+
+#include <e32base.h>
+#include <f32file.h>
+
+#include "movetimer.h"
+#include "mdsfileserverpluginclient.h"
+#include <harvesterdata.h>
+
+// FORWARD DECLARATION
+class CMdEHarvesterSession;
+class CProcessOriginMapper;
+class CMdEObject;
+class CMdEPropertyDef;
+class CFolderRenamer;
+class CHarvesterPluginFactory;
+class CMdsFSPQueueItem;
+
+class CFileEventHandlerAO : public CActive, public MMoveTimerObserver
+    {
+    public:
+    	enum TRequest
+    		{
+    		ERequestIdle,
+    		ERequestProcessing
+    		};
+    		
+        /**
+        * Creates and constructs a new instance of CFileEventHandlerAO.
+        *
+        * @return A pointer to the new instance of CFileEventHandlerAO
+        */
+        static CFileEventHandlerAO* NewL( MMonitorPluginObserver& aObserver,
+        		CMdEHarvesterSession* aMdeSession,
+        		CHarvesterPluginFactory* aHarvesterPluginFactory );
+        
+        /**
+        * Destructor
+        */
+        virtual ~CFileEventHandlerAO();
+        
+        /**
+        * Inherited from CActive. This method will be called on file server notifying.
+        */
+        void RunL();
+        
+        /**
+        * Handles a leave occurring in the request completion event handler RunL().
+        *
+        * @param aError  An error code.
+        * @return An error code.
+        */
+        TInt RunError( TInt aError );
+        
+        /**
+        * Cancels file server notifying. Inherited from CActive.
+        */
+        void DoCancel();
+        
+        /**
+        * Sets a list of paths not monitor to.
+        *
+        * @param aList  Contains list of paths not monitor to.
+        */
+        void SetIgnoreListL( RPointerArray<TDesC>& aList );
+        
+        /**
+         * Gets a reference to process / origin mapper, which
+         * can be used to register and match which process ids
+         * with a mde object's Origin value.
+         * @return Handle to File monitor's CProcessOriginMapper.
+         */
+        CProcessOriginMapper& Mapper();
+        
+        /**
+         * Notifies file monitor about new events
+         */
+        void HandleNotificationL(TMdsFSPStatus &aEvent);         
+        
+        /**
+         * Notifies file monitor about multiple delete events
+         */
+        void HandleMultideletionL( CArrayFixSeg< TMdsFSPStatus >* aEvents );     
+        
+        /**
+         * @Returns filemonitors mde session
+         * @return mde session object
+         */
+        CMdEHarvesterSession * MdeHarvesterSession();          
+        
+        
+        void AddToQueueL(TMdsFSPStatus &aEvent);
+        
+        void SetCachingStatus( TBool aCachingStatus );
+        
+    private:
+        /**
+        * C++ constructor - not exported;
+        * implicitly called from NewL()
+        */
+        CFileEventHandlerAO();
+        
+        /**
+        * 2nd phase construction, called by NewL()
+        */
+        void ConstructL( MMonitorPluginObserver& aObserver,
+        		CMdEHarvesterSession* aMdeSession,
+        		CHarvesterPluginFactory* aHarvesterPluginFactory );
+        
+        
+        /**
+         * 
+         */
+        void ResetEvent();
+        
+        void NotMoveEvent(RPointerArray<CHarvesterData>& aHDArray);
+        
+        /**
+         * 
+         */
+        void RenameToMDEL( const TDesC& aOldUrl, const TDesC& aNewUrl, TOrigin aOrigin );
+        
+        /**
+         * 
+         */
+        void ReplaceL( const TDesC& aOldUrl, const TDesC& aNewUrl, TOrigin aOrigin, TBool aFastHarvest );
+        
+        /**
+         * 
+         */
+        void ModifyL( const TDesC& aUrl, TOrigin aOrigin, TBool aFastHarvest );
+        
+        /**
+         * 
+         */
+        void DeleteFromMDEL( const TDesC& aUrl );
+        
+        /**
+         * 
+         */
+        void MultiDeleteFromMDEL( const RPointerArray<TDesC>& aUrls );
+        
+        /**
+         * 
+         */
+        void FormatL( TUint32 aOldMediaId, TBool aSubClose );
+        
+        /**
+         * 
+         */
+        TOrigin OriginFromMdEObjectL( CMdEObject& aObject );
+
+        /**
+         * 
+         */
+        void OriginToMdEObjectL( CMdEObject& aObject, TOrigin aOrigin );
+        
+        
+        void SetNextRequest( TRequest aRequest );
+        
+        void ReadCacheSizeFromCenrepL();
+
+        /**
+        * Set MdE object's title with aNewUrl
+        */
+       void SetTitleL( CMdEObject* aOldObject, const TDesC& aNewUrl );
+       
+       void SetModifiedTimeL( CMdEObject* aOldObject, const TDesC& aNewUrl );
+        
+    private:
+        
+        /**
+         * @var An observer class to notify about file creations, modifications and deletions.
+         */
+    	MMonitorPluginObserver* iObserver;
+        
+        /**
+         * @var A file server.
+         */
+        RFs iFs;
+
+        /**
+         * @var An ignore list. Contains paths not to monitor.
+         */
+        RPointerArray<TDesC> iIgnoreList;
+
+       
+        /**
+         * 
+         */
+        TMdsFSPStatusPckg iStatusPckg;
+
+        /**
+         * @var Mde client session pointer.
+         */
+        CMdEHarvesterSession* iMdeSession;
+        
+        /**
+         * Process id / origin mapper.
+         */
+        CProcessOriginMapper* iMapper;
+        
+        /**
+         * MoveTimer to check if move is coming...
+         */
+        CMoveTimer* iMoveTimer;
+        
+        /**
+         * Active object which is used to handle folder rename events
+         * 
+         */
+        CFolderRenamer *iFolderRenamer;
+        
+        /**
+         * @var Harvester plugin factory pointer.
+         */
+        CHarvesterPluginFactory* iHarvesterPluginFactory;
+        
+        RPointerArray<CMdsFSPQueueItem> iQueue;
+        
+        TRequest iNextRequest;
+        
+        TBool iCacheEvents;
+        
+        TMdsFSPStatus iEvent;
+        
+        CArrayFixSeg< TMdsFSPStatus >* iEventArray;
+        RPointerArray<TDesC> iUriArray;
+        
+        TInt iCacheSize;
+        
+        CMdEPropertyDef* iOriginPropertyDef;
+        CMdEPropertyDef* iTitlePropertyDef;
+        CMdEPropertyDef* iTimePropertyDef;
+    };
+
+#endif // __FILEEVENTHANDLERAO_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/inc/filemonitorao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,164 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors file creations, modifications and deletions.*
+*/
+
+#ifndef __FILEMONITORAO_H__
+#define __FILEMONITORAO_H__
+
+#include <e32base.h>
+
+#include "mdsfileserverpluginclient.h"
+#include "harvesterdata.h"
+
+// FORWARD DECLARATION
+class CMdEHarvesterSession;
+class CProcessOriginMapper;
+class CHarvesterPluginFactory;
+class CFileEventHandlerAO;
+
+class CFileMonitorAO : public CActive
+    {
+    public:
+        /**
+        * Creates and constructs a new instance of CFileMonitorAO.
+        *
+        * @return A pointer to the new instance of CFileMonitorAO
+        */
+        static CFileMonitorAO* NewL();
+        
+        /**
+        * Destructor
+        */
+        virtual ~CFileMonitorAO();
+        
+        /**
+        * Starts monitoring file system for file creations, modifications and deletions
+        * in the specified path.
+        *
+        * @param aObserver  All events are notified via aObserver.
+        * @param aPath  The path to monitor.
+        * @param aHarvesterPluginFactory  A pointer to the harvester plugin factory.
+        * @return ETrue if success, EFalse if not
+        */
+        TBool StartMonitoring( MMonitorPluginObserver& aObserver,
+        		CMdESession* aMdeSession, const TDesC& aPath,
+        		CHarvesterPluginFactory* aHarvesterPluginFactory );
+        
+        /**
+        * Stops monitoring.
+        *
+        * @return ETrue if success, EFalse if not
+        */
+        TBool StopMonitoring();
+        
+        /**
+        * Inherited from CActive. This method will be called on file server notifying.
+        */
+        void RunL();
+        
+        /**
+        * Handles a leave occurring in the request completion event handler RunL().
+        *
+        * @param aError  An error code.
+        * @return An error code.
+        */
+        TInt RunError( TInt aError );
+        
+        /**
+        * Cancels file server notifying. Inherited from CActive.
+        */
+        void DoCancel();
+        
+        /**
+         * Gets a reference to process / origin mapper, which
+         * can be used to register and match which process ids
+         * with a mde object's Origin value.
+         * @return Handle to File monitor's CProcessOriginMapper.
+         */
+        CProcessOriginMapper& Mapper();
+        
+        /**
+         * Set file event caching on/off
+         */
+        void SetCachingStatus( TBool aCachingStatus );
+        
+        
+    private:
+        /**
+        * C++ constructor - not exported;
+        * implicitly called from NewL()
+        */
+        CFileMonitorAO();
+        
+        /**
+        * 2nd phase construction, called by NewL()
+        */
+        void ConstructL();
+        
+        /**
+        * Starts file server to notify us about file changes.
+        */
+        void StartNotify();
+        
+        /**
+         * 
+         */
+        void ResetMdsFSPStatus();
+        
+    private:
+        /**
+         * @var An observer class to notify about file creations, modifications and deletions.
+         */
+    	MMonitorPluginObserver* iObserver;
+        
+        /**
+         * @var A file server.
+         */
+        RFs iFs;
+
+        /**
+         * @var Flag to signal if iFs is connected.
+         */
+        TBool iFsConnectOk;
+        
+        /**
+         * @var An ignore list. Contains paths not to monitor.
+         */
+        RPointerArray<TDesC> iIgnoreList;
+
+        /**
+         * 
+         */
+        RMdsFSPEngine iEngine;
+        
+        /**
+         * 
+         */
+        TMdsFSPStatusPckg iStatusPckg;
+
+        /**
+         * @var Mde client session pointer.
+         */
+        CMdEHarvesterSession* iMdeSession;
+        
+        /**
+         * @var Harvester plugin factory pointer.
+         */
+        CHarvesterPluginFactory* iHarvesterPluginFactory;
+        
+        CFileEventHandlerAO* iFileEventHandler;
+    };
+
+#endif // __FILEMONITORAO_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/inc/filemonitorplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,119 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors file creations, modifications and deletions.*
+*/
+
+#ifndef __FILEMONITORPLUGIN_H__
+#define __FILEMONITORPLUGIN_H__
+
+#include <e32base.h>
+
+#include "monitorplugin.h"
+#include "filemonitorao.h"
+#include "processoriginmapperinterface.h"
+
+class CFileMonitorPlugin : public CMonitorPlugin,
+                           public MProcessOriginMapperInterface
+  	{
+	public:
+		/**
+		* Creates and constructs a new instance of CFileMonitorPlugin.
+		*
+		* @return A pointer to the new instance of CFileMonitorPlugin
+		*/
+		static CFileMonitorPlugin* NewL();
+		
+		/**
+		* Destructor
+		*/
+		virtual ~CFileMonitorPlugin();
+		
+		/**
+		* Starts monitoring file system for file creations, modifications and deletions
+		* in the specified path.
+		*
+		* @param aObserver  All events are notified via the aObserver.
+		* @param aMdEClient  A pointer to MdE client.
+		* @param aCtxEngine  A pointer to context engine.
+		* @param aPluginFactory  A pointer to harvester plugin factory.
+		* @return ETrue if success, EFalse if not.
+		*/
+		TBool StartMonitoring( MMonitorPluginObserver& aObserver, CMdESession* aMdEClient, 
+				CContextEngine* aCtxEngine, CHarvesterPluginFactory* aHarvesterPluginFactory );
+		
+		/**
+		* Stops monitoring.
+		*
+		* @return ETrue if success, EFalse if not.
+		*/
+		TBool StopMonitoring();
+		
+		/**
+		* Resumes paused monitoring.
+		*
+		* @param aObserver  All events are notified via the aObserver.
+		* @param aMdEClient  A pointer to MdE client.
+		* @param aCtxEngine  A pointer to context engine.
+		* @param aPluginFactory  A pointer to harvester plugin factory.
+		* @return ETrue if success, EFalse if not.
+		*/
+		TBool ResumeMonitoring( MMonitorPluginObserver& aObserver, CMdESession* aMdEClient,
+				CContextEngine* aCtxEngine, CHarvesterPluginFactory* aHarvesterPluginFactory );
+		
+		/**
+		* Pauses monitoring.
+		*
+		* @return ETrue if success, EFalse if not.
+		*/
+		TBool PauseMonitoring();
+		
+        /**
+         * Add a process to the list.
+         * From MProcessOriginMapperInterface.
+         * @param aProcessUid  Uid of the process to add.
+         * @param aOrigin      Origin to which this process will mapped to.
+         */
+        void RegisterProcessL( const TUid& aProcessId,
+                               const TOrigin& aOrigin );
+        
+        /**
+         * Remove a process from the list.
+         * From MProcessOriginMapperInterface.
+         * @param aProcessId  Uid of the process to remove.
+         */
+        void UnregisterProcessL( const TUid& aProcessId );
+
+    private:
+		 
+		/**
+		* C++ constructor - not exported;
+		* implicitly called from NewL()
+		*/
+		CFileMonitorPlugin();
+		
+		/**
+		* 2nd phase construction, called by NewL()
+		*/
+		void ConstructL();
+		
+	private:
+		
+		/**
+		* A pointer to CFileMonitorAO.
+		*/
+		CFileMonitorAO* iFileMonitor;
+	};
+
+#endif // __FILEMONITORPLUGIN_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/inc/movetimer.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+#ifndef MOVETIMER_H
+#define MOVETIMER_H
+
+#include <e32base.h>	// For CActive, link against: euser.lib
+#include <e32std.h>		// For RTimer, link against: euser.lib
+
+// FORWARD DECLARATION
+class CHarvesterData;
+
+class MMoveTimerObserver
+	{
+public:
+	virtual void NotMoveEvent(RPointerArray<CHarvesterData>& aHDArray) = 0;
+	};
+
+class CMoveTimer : public CActive
+{
+public:
+	// Cancel and destroy
+	~CMoveTimer();
+
+	// Two-phased constructor.
+	static CMoveTimer* NewL( MMoveTimerObserver* aObserver = NULL);
+
+	// Two-phased constructor.
+	static CMoveTimer* NewLC( MMoveTimerObserver* aObserver = NULL);
+
+public: // New functions
+		
+	void AddHarvesterDataL( CHarvesterData* aHD );
+	
+	CHarvesterData* CheckUriL( const TDesC& aUri );
+
+private:
+	// C++ constructor
+	CMoveTimer( MMoveTimerObserver* aObserver = NULL );
+	
+	// Second-phase constructor
+	void ConstructL();
+	
+	// Function for making the initial request
+	void StartL();
+	
+private: // From CActive
+	// Handle completion
+	void RunL();
+	
+	// How to cancel me
+	void DoCancel();
+	
+	// Override to handle leaves from RunL(). Default implementation causes
+	// the active scheduler to panic.
+	TInt RunError( TInt aError );
+
+private:
+	RTimer	iTimer;		// Provides async timing service
+	MMoveTimerObserver* iObserver;
+	RPointerArray<CHarvesterData> iHDArray;
+};
+
+#endif // MOVETIMER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/inc/processoriginmapper.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,201 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Maintains a list of process ids and matching origin*
+*/
+
+
+#ifndef __PROCESSORIGINMAPPER_H__
+#define __PROCESSORIGINMAPPER_H__
+
+#include <e32cmn.h>
+#include <s32file.h>
+
+#include "mdeconstants.h"
+#include "processoriginmapperinterface.h"
+
+/**
+ * @var Data transfer object used for process/origin
+ * mapping table.
+ */
+struct TProcessOriginPair
+    {
+    TUid iProcessId;
+    TOrigin iOrigin;
+    };
+
+/**
+ * @var Maximum amount of items allowed in the mapping table.
+ */
+const TInt KMaxMappingSize = 100;
+
+
+/**
+ * Maintains a list of process ids and matching origin
+ * values to be set for mde objects created by a process.
+ * List is maintained in memory and in a text file.
+ * 
+ * API is provided to add and remove processes in the list
+ * and to retrieve the matching origin by a process id (if any).
+ * Mappings are read written to a file on request.
+ */
+class CProcessOriginMapper : public CBase,
+                             public MProcessOriginMapperInterface
+    {
+    public:
+
+        /**
+         * Creates and constructs a new instance of CLocationContextPlugin.
+         * Two-phase construction.
+         *
+         * @return A pointer to the created instance.
+         */
+        static CProcessOriginMapper* NewL();
+    
+        /**
+         * Destructor.
+         */
+        virtual ~CProcessOriginMapper();
+
+    private:
+
+        /**
+         * Private constructor, called by NewL() only.
+         */
+        CProcessOriginMapper();
+    
+        /**
+         * Second phase construction called by NewL().
+         */
+        void ConstructL();
+
+    public:
+
+        /**
+         * Add a process to the list.
+         * @param aProcessUid  Uid of the process to add.
+         * @param aOrigin      Origin to which this process will mapped to.
+         */
+        void RegisterProcessL( const TUid& aProcessId,
+                               const TOrigin& aOrigin );
+        
+        /**
+         * Remove a process from the list.
+         * @param aProcessId  Uid of the process to remove.
+         */
+        void UnregisterProcessL( const TUid& aProcessId );
+
+        /**
+         * Check a process from the list.
+         * @param aProcessId  Uid of the process to check.
+         * @return  Origin the given process is mapped to
+         *          or KErrNotFound if not found.
+         */
+        TOrigin OriginL( const TUid& aProcessId );
+
+        /**
+         * Read process id mappings from a file.
+         * This doesn't clear the list of currently registered mappings.
+         * @param aFile  File name and path.
+         * @return Count of mapping pairs read.
+         */
+        TInt ReadFileL( const TDesC& aFile );
+
+        /**
+         * Read process id mappings from the default file.
+         * @return Count of mapping pairs read.
+         */
+        TInt ReadFileL();
+
+        /**
+         * Write process id mappings to a file.
+         * @param aFile  File name and path.
+         */
+        void WriteFileL( const TDesC& aFile );
+
+        /**
+         * Write process id mappings to the default file.
+         */
+        void WriteFileL();
+
+        /**
+         * Clear mapping table in memory.
+         */
+        void Clear();
+
+        /**
+         * Count of registered mappings.
+         * @return Count
+         */
+        TInt Count();
+
+    private:
+
+        /**
+         * Find an index by process id.
+         * @param aProcessId  Process id.
+         * @return  Index or KErrNotFound if not found.
+         */
+        TInt FindProcess( const TUid& aProcessId );
+        
+        /**
+         * Read one process id and origin pair from file.
+         * @param aProcessUid  Uid of the process to add.
+         * @param aOrigin      Origin to which this process will mapped to.
+         */
+        void ReadProcessOriginPairL( TUid& aProcessId, TOrigin& aOrigin );
+
+        /**
+         * Write one related process/origin pair to a file.
+         * @param aProcessUid  Uid of the process to add.
+         * @param aOrigin      Origin to which this process will mapped to.
+         */
+        void WriteProcessOriginPairL( TUid& aProcessId, TOrigin& aOrigin );
+
+    private: // data
+
+        /**
+         * @var Mapping table. It holds pairs of
+         * matching process ids and origins.
+         * Content is loaded from and saved to a file.
+         */
+        RArray<TProcessOriginPair> iProcessOriginMap;
+        
+        /**
+         * File system session.
+         */
+        RFs iFs;
+        
+        /**
+         *  File stream used for reading the import file
+         */
+        RFileReadStream iReadStream;
+
+        /**
+         *  File stream used for writing the export file
+         */
+        RFileWriteStream iWriteStream;
+
+        /**
+         * A buffer used for reading lines from files.
+         */
+        HBufC8* iLineBuffer;
+
+        /**
+         * Indicates read defult origin map file.
+         * No write process should occur.
+         */
+        TBool iDefaultFileRead;
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/src/FolderRenamer.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,280 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include <e32std.h>
+
+#include "FolderRenamer.h"
+#include "harvesterlog.h"
+#include "mdeharvestersession.h"
+#include "mdeharvestersession.h"
+#include "harvesterdata.h"
+#include "fileeventhandlerao.h"
+#include "harvestercommon.h"
+
+CRenameItem * CRenameItem::NewL(
+		const TDesC &aOldName, const TDesC &aNewName)
+	{	
+	CRenameItem *self = new (ELeave) CRenameItem();
+	CleanupStack::PushL(self);
+	self->ConstructL(aOldName,aNewName);
+	CleanupStack::Pop(self);
+	return self;
+	}
+	
+CRenameItem::~CRenameItem()
+	{
+	delete iOldName;
+	delete iNewName;
+	iFileEvents.ResetAndDestroy();
+	}
+	
+
+void CRenameItem::ConstructL(const TDesC &aOldName, const TDesC &aNewName)
+	{
+	iOldName = HBufC::NewL( aOldName.Length() );
+	iNewName = HBufC::NewL( aNewName.Length() );
+
+	// convert paths to lower case
+	// Note: CopyLC doesn't push anything to cleanup stack
+	iOldName->Des().CopyLC( aOldName );
+	iNewName->Des().CopyLC( aNewName );
+	}
+
+CRenameItem::CRenameItem() : iOldName( NULL ), iNewName( NULL )
+	{
+	//No implementation required
+	}
+
+void CRenameItem::AddFileEvent(TMdsFSPStatus &aEvent)
+	{
+	TMdsFSPStatus* event = NULL;
+	event = new TMdsFSPStatus(aEvent);
+	if (event)
+		{
+		iFileEvents.Append(event);
+		}
+	}
+
+void CRenameItem::HandleFileEventsL(CFileEventHandlerAO &aCFileEventHandlerAO)
+	{
+	TInt count = iFileEvents.Count();
+	for (TInt i = 0; i < count; i++)
+		{
+		aCFileEventHandlerAO.HandleNotificationL(* (iFileEvents[i]));
+		}
+	iFileEvents.ResetAndDestroy();
+	}
+
+TPtrC CRenameItem::OldName()
+	{
+	return iOldName->Des();
+	}
+
+
+TPtrC CRenameItem::NewName()
+	{
+	return iNewName->Des();
+	}
+
+
+CFolderRenamer * CFolderRenamer::NewL(CFileEventHandlerAO &aCFileEventHandlerAO)
+	{	
+	CFolderRenamer *self = new (ELeave) CFolderRenamer(aCFileEventHandlerAO);
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+
+CFolderRenamer::CFolderRenamer(CFileEventHandlerAO &aCFileEventHandlerAO) : 
+	CActive(KHarvesterPriorityMonitorPlugin),
+	iState(ERenameStateIdle),
+	iCFileEventHandlerAO(aCFileEventHandlerAO),
+	iIsRunning( EFalse )
+	{
+	}
+
+CFolderRenamer::~CFolderRenamer()
+	{
+	Cancel();
+	}
+
+void CFolderRenamer::ConstructL()
+	{
+	CActiveScheduler::Add(this);
+	}
+	
+void CFolderRenamer::DoCancel()
+	{	
+	}
+	
+
+void CFolderRenamer::RunL()
+	{
+	switch (iState)
+		{
+		case ERenameStateIdle:
+			{
+			if (iRenamedFolders.Count() == 0)
+				{
+				iIsRunning = EFalse;
+				return;
+				}
+			} //Flow to Renaming case -> no break
+			
+		case ERenameStateRenaming:
+			{
+			if (iRenamedFolders.Count())
+				{
+				iState = ERenameStateWaitingMdeRename;			
+				CRenameItem &currItem = *iRenamedFolders[0];				
+				CMdEHarvesterSession* session = iCFileEventHandlerAO.MdeHarvesterSession();
+				session->ChangePath( currItem.OldName(), currItem.NewName(), iStatus );
+				SetActive();
+				}
+			}
+			break;
+			
+		case ERenameStateWaitingMdeRename:
+			{
+			CRenameItem *currItem = iRenamedFolders[0];
+			iRenamedFolders.Remove(0);
+			TRAP_IGNORE(currItem->HandleFileEventsL(iCFileEventHandlerAO));
+			delete currItem;
+			SetNextRequest(ERenameStateIdle);
+			if (iRenamedFolders.Count() == 0)
+				{
+				iIsRunning = EFalse;
+				iRenamedFolders.Compress();
+				}
+			}
+			break;
+			
+		default:
+			{
+			WRITELOG("Unexpected state in FolderRenamer");
+			SetNextRequest(ERenameStateIdle);
+			}			
+			break;
+		}
+	}
+
+TInt CFolderRenamer::RunError( TInt aError )
+    {
+    WRITELOG("Unexpected error in FolderRenamer");
+    SetNextRequest(ERenameStateIdle);
+    return aError;
+    }
+
+void CFolderRenamer::RenameL(const TDesC &aOldName, const TDesC &aNewName)
+	{
+    //There comes multiple events for single rename, drop these 
+	TInt count = iRenamedFolders.Count();
+	for (TInt i = 0; i < count; i++)
+		{
+		if ( iRenamedFolders[i]->OldName().CompareF(aOldName) == 0 && 
+				iRenamedFolders[i]->NewName().CompareF(aNewName) == 0 )
+			{
+			return;
+			}
+		}
+	
+	CRenameItem *renameItem = CRenameItem::NewL(aOldName,aNewName);
+	iRenamedFolders.AppendL(renameItem);
+	iIsRunning = ETrue;
+	//First item --> Kickstart
+		
+	if (iState == ERenameStateIdle)
+		{
+		SetNextRequest(ERenameStateRenaming);
+		}
+	}
+
+
+void CFolderRenamer::SetNextRequest(TFolderRenameState aState)
+	{
+	iState = aState;	
+	if (!IsActive())
+		{
+		SetActive();				
+		TRequestStatus * status = &iStatus;
+		User::RequestComplete(status,KErrNone);	
+		}
+	}
+
+
+void CFolderRenamer::HandleFileEventL(TMdsFSPStatus &aEvent)
+	{
+	if (aEvent.iFileEventType == EMdsDirRenamed)
+		{
+		RenameL(aEvent.iFileName,aEvent.iNewFileName);
+		return;
+		}
+
+	//Check whether new folder name of the rename events matches to received path. If it matches
+    //queue events until folder is renamed, otherwise send notification to filemonitor immediatedly
+    //has to be started from last event!
+	if (iIsRunning)
+		{
+		const TInt count = iRenamedFolders.Count();	
+		for (TInt i = count-1; i >= 0; i--)
+			{
+			if (aEvent.iFileName.FindF(iRenamedFolders[i]->NewName()) != KErrNotFound)
+				{
+				iRenamedFolders[i]->AddFileEvent(aEvent);
+				return;
+				}
+			}		
+		}
+			
+	iCFileEventHandlerAO.HandleNotificationL(aEvent);
+	}
+
+void CFolderRenamer::HandleFileEventsL( CArrayFixSeg< TMdsFSPStatus >* aEvents )
+    {
+    const TInt count( aEvents->Count() );  // Can hold only delete events
+    
+    if( iIsRunning )
+        {
+        for( TInt i( 0 ); i < count; i++ )
+            {
+            //Check whether new folder name of the rename events matches to received path. If it matches
+            //queue events until folder is renamed, otherwise send notification to filemonitor immediatedly
+            //has to be started from last event!
+            const TInt count = iRenamedFolders.Count();   
+            for (TInt i = count-1; i >= 0; i--)
+                {
+                if ((*aEvents)[i].iFileName.FindF(iRenamedFolders[i]->NewName()) != KErrNotFound)
+                    {
+                    iRenamedFolders[i]->AddFileEvent((*aEvents)[i]);
+                    aEvents->Delete( i );
+                    break;
+                    } 
+                }
+            }
+        aEvents->Compress();
+        }
+    
+    if( aEvents->Count() )
+        {
+        iCFileEventHandlerAO.HandleMultideletionL(aEvents);
+        }
+    }
+	
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/src/fileeventhandlerao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,977 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Handles monitored file creations, modifications and deletions.*
+*/
+
+#include <collate.h>
+#include <mdeobject.h>
+
+#include "fileeventhandlerao.h"
+#include "harvesterlog.h"
+#include "fsutil.h"
+#include "mdeconstants.h"
+#include "mdeharvestersession.h"
+#include "processoriginmapper.h"
+#include "mdenamespacedef.h"
+#include "mdeobjectdef.h"
+#include "FolderRenamer.h"
+#include "mdsutils.h"
+#include "harvesterpluginfactory.h"
+#include "mdsfspqueue.h"
+#include "harvestercommon.h"
+#include <centralrepository.h>
+
+using namespace MdeConstants;
+
+const TUid KRepositoryUid = { 0x20007182 };
+const TUint32 KCacheSizeKey = 0x00000001;
+
+const TInt KMaxEventsAtTime = 20;
+const TInt KMaxEventsGranularity = 20;
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::NewL()
+// ---------------------------------------------------------------------------
+//
+CFileEventHandlerAO* CFileEventHandlerAO::NewL( MMonitorPluginObserver& aObserver,
+		CMdEHarvesterSession* aMdeSession, CHarvesterPluginFactory* aHarvesterPluginFactory )
+    {
+    WRITELOG( "CFileEventHandlerAO::NewL" );
+
+    CFileEventHandlerAO* self = new (ELeave) CFileEventHandlerAO;
+    CleanupStack::PushL( self );
+    self->ConstructL( aObserver, aMdeSession, aHarvesterPluginFactory );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::ConstructL( MMonitorPluginObserver& aObserver,
+		CMdEHarvesterSession* aMdeSession, CHarvesterPluginFactory* aHarvesterPluginFactory )
+    {
+    WRITELOG( "CFileEventHandlerAO::ConstructL" );
+    iObserver = &aObserver;
+    iHarvesterPluginFactory = aHarvesterPluginFactory;
+    iMdeSession = aMdeSession;
+    iNextRequest = ERequestIdle;
+    iCacheEvents = EFalse;
+    
+    CActiveScheduler::Add( this );
+    iMapper = CProcessOriginMapper::NewL();
+    iMoveTimer = CMoveTimer::NewL(this);
+    iFolderRenamer = CFolderRenamer::NewL(*this);
+    TRAPD( error, iMapper->ReadFileL() );
+    if ( error != KErrNone )
+    	{
+    	WRITELOG1( "CFileEventHandlerAO::ConstructL - iMapper->ReadFileL() error %d", error );
+    	}
+    error = iFs.Connect();
+    User::LeaveIfError( error );
+    
+    TRAP( error, ReadCacheSizeFromCenrepL() );
+    if ( error == KErrNone )
+    	{
+    	iQueue.Reserve( iCacheSize );
+    	}
+    
+    iEventArray = new (ELeave) CArrayFixSeg< TMdsFSPStatus >( KMaxEventsGranularity );
+    }
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::~CFileEventHandlerAO()
+// ---------------------------------------------------------------------------
+//
+CFileEventHandlerAO::~CFileEventHandlerAO()
+    {
+    WRITELOG( "CFileEventHandlerAO::~CFileEventHandlerAO" );
+    
+    Cancel();
+    
+    iIgnoreList.ResetAndDestroy();
+    iIgnoreList.Close();
+    
+    iFs.Close();
+    
+    delete iMapper;
+    delete iMoveTimer;
+    delete iFolderRenamer;
+    
+    delete iEventArray;
+    iUriArray.Close();
+    }
+
+
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::RunL()
+// From CActive
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::RunL()
+    {
+    WRITELOG( "CFileEventHandlerAO::RunL" );
+    switch( iNextRequest )
+    	{
+    	case ( ERequestIdle ):
+    		{
+        	break;
+    		}
+    	
+    	case ( ERequestProcessing ):
+    		{
+    		if( iQueue.Count() > 0 && !iCacheEvents )
+    			{
+    			CMdsFSPQueueItem* item = iQueue[0];
+    			iQueue.Remove( 0 );
+
+    			ResetEvent();
+    			item->GetAsFspStatus(iEvent);
+    			delete item;
+    			
+    			if( iEvent.iFileEventType == EMdsFileDeleted )
+    			    {
+    			    iEventArray->AppendL( iEvent );
+    			    TInt limit( KMaxEventsAtTime );
+    			    const TInt count( iQueue.Count() );
+    			    if( count >= KMaxEventsAtTime )
+    			        {
+    			        limit = KMaxEventsAtTime;
+    			        }
+    			    else
+    			        {
+    			        limit = count;
+    			        }
+    			    
+    	            for( TInt i( 0 ); i < limit; i++ )
+    	                {
+    	                CMdsFSPQueueItem* tempItem = iQueue[0];
+    	                TMdsFSPStatus status;
+    	                tempItem->GetAsFspStatus( status );
+    	                if( status.iFileEventType == EMdsFileDeleted  )
+    	                    {
+    	                    iQueue.Remove( 0 );
+    	                    delete tempItem;
+    	                    iEventArray->AppendL( status );
+    	                    }
+    	                else
+    	                    {
+    	                    break;
+    	                    }
+    	                }
+    			    }
+    			
+    			if( iEventArray->Count() > 1 )
+    			    {
+    			    iFolderRenamer->HandleFileEventsL(iEventArray);
+    			    }
+    			else
+    			    {
+    			    iFolderRenamer->HandleFileEventL(iEvent);
+    			    }
+    			
+    			SetNextRequest( ERequestProcessing );
+    			}
+    		else
+    			{
+    			SetNextRequest( ERequestIdle );
+    			}
+        	break;
+    		}
+    	default:
+    		break;
+    	}
+    }
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::HandleNotificationL()
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::HandleNotificationL(TMdsFSPStatus &aEvent)
+    {
+    WRITELOG( "CFileEventHandlerAO::HandleNotificationL" );
+    
+    TMdsFSPStatus& status = aEvent;
+    
+    if ( !iObserver )
+        {
+        WRITELOG( "-- ERROR -- CFileEventHandlerAO::HandleNotificationL - no observer" );
+        return;
+        }
+    
+    TBool fastHarvest( EFalse );
+    
+    TOrigin origin = MdeConstants::Object::EOther;
+    if ( iMapper )
+        {
+        TRAPD( originErr, origin = iMapper->OriginL( status.iProcessId ) );
+        if( originErr == KErrNone )
+        	{
+        	if ( origin == KOriginIgnored )
+                {
+                WRITELOG1( "CFileEventHandlerAO::HandleNotificationL - ignored origin for %S", &status.iFileName );
+                return;
+                }
+        	else if( origin == KOriginFastHarvest )
+        	    {
+        	    WRITELOG( "CFileEventHandlerAO::HandleNotificationL - potential fast harvest file detected" );
+        	    fastHarvest = ETrue;
+        	    }
+    
+            _LIT(KCameraTemp,"camcordertmp");
+        	if ( origin == MdeConstants::Object::ECamera &&
+        			(aEvent.iFileEventType == EMdsFileCreated || 
+					aEvent.iFileName.FindF(KCameraTemp) != KErrNotFound) )        		
+                {
+                WRITELOG1( "CFileEventHandlerAO::HandleNotificationL - ignored camera origin for %S", &status.iFileName );
+                return;
+                }
+        	}
+        else
+        	{
+        	origin = MdeConstants::Object::EOther;
+        	}
+        }
+
+    // ignore created file event if extension is not supported by any harverter plugin
+    if( EMdsFileCreated == status.iFileEventType && 
+    		status.iFileName.Length() > 0 )
+    	{
+    	if( !iHarvesterPluginFactory->IsSupportedFileExtension( 
+    			status.iFileName ) )
+    		{
+    		WRITELOG1( "CFileEventHandlerAO::HandleNotificationL - file extension not supported: %S", &status.iFileName );
+    		return;
+    		}
+    	}
+
+    switch( status.iFileEventType )
+        {
+        case EMdsFileCreated:
+            {
+            WRITELOG1( "CFileEventHandlerAO::HandleNotificationL - EmdsFileCreated: %S", &status.iFileName );
+            HBufC* fn = status.iFileName.AllocLC();
+            CHarvesterData* hd = CHarvesterData::NewL( fn );
+            CleanupStack::Pop( fn );
+            hd->SetEventType( EHarvesterAdd );
+            hd->SetOrigin( origin );
+            CleanupStack::PushL( hd );
+            iMoveTimer->AddHarvesterDataL( hd );
+            CleanupStack::Pop( hd );
+            }
+        break;
+        
+        case EMdsFileRenamed:
+            {
+            WRITELOG2( "CFileEventHandlerAO::HandleNotificationL - EMdsFileRenamed: %S to %S", &status.iFileName, &status.iNewFileName );
+            RenameToMDEL( status.iFileName, status.iNewFileName, origin );
+            }
+        break;
+        
+        case EMdsFileModified:
+            {
+            WRITELOG1( "CFileEventHandlerAO::HandleNotificationL - EmdsFileModified: %S", &status.iFileName );
+            ModifyL( status.iFileName, origin, fastHarvest );
+            }
+        break;
+        
+        case EMdsFileReplaced:
+            {
+            WRITELOG2( "CFileEventHandlerAO::HandleNotificationL - EMdsFileReplaced: %S to %S", &status.iFileName, &status.iNewFileName );
+            ReplaceL( status.iFileName, status.iNewFileName, origin, fastHarvest );
+            }
+        break;
+        
+        case EMdsFileDeleted:
+            {
+            WRITELOG1( "CFileEventHandlerAO::HandleNotificationL - EmdsFileDeleted: %S", &status.iFileName );
+            CHarvesterData* hd = iMoveTimer->CheckUriL( status.iFileName );
+            if ( hd )
+            	{
+            	// move event
+            	CleanupStack::PushL( hd );
+            	RenameToMDEL( status.iFileName, hd->Uri(), hd->Origin() );
+            	CleanupStack::PopAndDestroy( hd );
+            	}
+
+            DeleteFromMDEL( status.iFileName );
+            }
+        break;
+
+        case EMdsDriveFormatted:
+        	{
+        	WRITELOG1( "CFileEventHandlerAO::HandleNotificationL - EMdsDriveFormatted: %d", status.iDriveNumber );
+        	// format drive
+        	FormatL( status.iDriveMediaId, status.iProcessId.iUid != 0 );
+        	}
+        break;
+        
+        default:
+            WRITELOG1( "CFileEventHandlerAO::HandleNotificationL - KErrNotSupported %d", status.iFileEventType );
+            User::Leave( KErrNotSupported );
+        break;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::HandleMultideletionL()
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::HandleMultideletionL( CArrayFixSeg< TMdsFSPStatus >* aEvents )
+    {
+    WRITELOG( "CFileEventHandlerAO::HandleMultideletionL" );
+    
+    if ( !iObserver )
+        {
+        WRITELOG( "-- ERROR -- CFileEventHandlerAO::HandleMultideletionL - no observer" );
+        return;
+        }
+    
+    const TInt count( aEvents->Count() );
+    for( TInt i( 0 ); i < count; i++ )
+        {
+        TMdsFSPStatus& status = (*aEvents)[i];
+        
+        TOrigin origin = MdeConstants::Object::EOther;
+        if ( iMapper )
+            {
+            TRAPD( originErr, origin = iMapper->OriginL( status.iProcessId ) );
+            if( originErr == KErrNone )
+                {
+                if ( origin == KOriginIgnored )
+                    {
+                    WRITELOG1( "CFileEventHandlerAO::HandleMultideletionL - ignored origin for %S", &status.iFileName );
+                    continue;
+                    }
+                }
+            }
+        
+        WRITELOG1( "CFileEventHandlerAO::HandleMultideletionL - EmdsFileDeleted: %S", &status.iFileName );
+        CHarvesterData* hd = iMoveTimer->CheckUriL( status.iFileName );
+        if ( hd )
+            {
+            // move event
+            CleanupStack::PushL( hd );
+            RenameToMDEL( status.iFileName, hd->Uri(), hd->Origin() );
+            CleanupStack::PopAndDestroy( hd );
+            }
+        iUriArray.Append( &(status.iFileName) );
+        }
+    MultiDeleteFromMDEL( iUriArray );
+    }
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::ResetMdsFSPStatus()
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::ResetEvent()
+    {
+    WRITELOG( "CFileEventHandlerAO::ResetEvent" );
+    
+    iEvent.iDriveNumber = 0;
+    iEvent.iFileEventType = EMdsFileUnknown;
+    iEvent.iFileName.Zero();
+    iEvent.iNewFileName.Zero();
+    iEvent.iProcessId = TUid::Null();
+    
+    iEventArray->Reset();
+    iUriArray.Reset();
+    }
+    
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::RenameToMDEL()
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::RenameToMDEL( const TDesC& aOldUrl, 
+		const TDesC& aNewUrl, TOrigin aOrigin )
+    {
+    WRITELOG( "CFileEventHandlerAO::RenameToMDEL" );
+
+    CMdEObject* oldObject = iMdeSession->Session()->OpenObjectL( aOldUrl );
+    if ( oldObject )
+        {
+        CleanupStack::PushL( oldObject );
+        }
+
+    CMdEObject* newObject = iMdeSession->Session()->GetObjectL( aNewUrl );
+    if ( newObject )
+        {
+        CleanupStack::PushL( newObject );
+        }
+
+    // check if not in mde, harvest
+    if ( !oldObject && !newObject && iObserver )
+        {
+        HBufC* fn = aNewUrl.AllocLC();
+        CHarvesterData* hd = CHarvesterData::NewL( fn );
+        CleanupStack::Pop( fn );
+        hd->SetEventType( EHarvesterAdd );
+        hd->SetOrigin( aOrigin );
+        iObserver->MonitorEvent( hd );
+        }
+
+    // set old url to new url
+    if ( oldObject && !newObject )
+        {
+        SetTitleL( oldObject , aNewUrl );
+        oldObject->SetUriL( aNewUrl );
+        TUint32 mediaId = FSUtil::MediaID( iFs, aNewUrl );
+        oldObject->SetMediaId( mediaId );
+        }
+
+    // if old and new then destroy new and change old
+    if ( oldObject && newObject && ( oldObject->Id() != newObject->Id()) )
+        {
+        const TItemId removedId = iMdeSession->Session()->RemoveObjectL( 
+        		newObject->Id() );
+        if ( removedId != KNoId )
+        	{
+	        oldObject->SetUriL( aNewUrl );
+	        TUint32 mediaId = FSUtil::MediaID( iFs, aNewUrl );
+	        oldObject->SetMediaId( mediaId );
+        	}
+        }
+
+    if ( newObject )
+        {
+        CleanupStack::PopAndDestroy( newObject );
+        }
+
+    if ( oldObject )
+        {
+        SetModifiedTimeL( oldObject, aNewUrl );
+        TOrigin origin = OriginFromMdEObjectL( *oldObject );
+        if( origin == MdeConstants::Object::EOther)
+        	{
+        	OriginToMdEObjectL( *oldObject, aOrigin );
+        	}
+        iMdeSession->Session()->CommitObjectL( *oldObject );
+        CleanupStack::PopAndDestroy( oldObject );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::OriginFromMdEObject()
+// ---------------------------------------------------------------------------
+//
+TOrigin CFileEventHandlerAO::OriginFromMdEObjectL( CMdEObject& aObject )
+	{
+	TOrigin retVal = MdeConstants::Object::EOther;
+
+	if( !iOriginPropertyDef )
+		{
+		CMdEObjectDef& objDef = aObject.Def();
+		iOriginPropertyDef = &objDef.GetPropertyDefL( Object::KOriginProperty );
+		}
+
+	CMdEProperty* property = NULL;
+	TInt err = aObject.Property( *iOriginPropertyDef, property );
+	if( err >= KErrNone && property )
+		{
+		CMdEUint8Property* uint8Property = (CMdEUint8Property*)property;
+		retVal = (TOrigin) uint8Property->Value();
+		}
+	 
+	return retVal;
+	}
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::OriginFromMdEObject()
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::OriginToMdEObjectL( CMdEObject& aObject, 
+		TOrigin aOrigin )
+	{
+	if( !iOriginPropertyDef )
+		{
+		CMdEObjectDef& objDef = aObject.Def();
+		iOriginPropertyDef = &objDef.GetPropertyDefL( 
+				Object::KOriginProperty );
+		}
+
+	CMdEProperty* property = NULL;
+	TInt err = aObject.Property( *iOriginPropertyDef, property );
+	if(err < KErrNone)
+		{
+		return;
+		}
+
+	if( property )
+		{
+		CMdEUint8Property* uint8Property = (CMdEUint8Property*)property;
+		TRAP_IGNORE( uint8Property->SetValueL( aOrigin ) );
+		}
+	else
+		{
+		TRAP_IGNORE( aObject.AddUint8PropertyL( *iOriginPropertyDef, 
+				(TUint8) aOrigin ) );
+		}
+	}
+    
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::ReplaceL()
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::ReplaceL( const TDesC& aOldUrl, const TDesC& aNewUrl,
+		TOrigin aOrigin,  TBool aFastHarvest )
+    {
+    WRITELOG( "CFileEventHandlerAO::ReplaceL" );
+
+    if ( !iObserver )
+        {
+        User::Leave( KErrGeneral );
+        }
+
+    CMdEObject* newObject = NULL;
+    CMdEObject* oldObject = NULL;
+    
+    if ( aNewUrl.Length() > 0 )
+    	{
+    	newObject = iMdeSession->Session()->GetObjectL( aNewUrl );
+    	if ( newObject )
+    		{
+    		CleanupStack::PushL( newObject );
+    		}
+    	}
+    
+    if ( aOldUrl.Length() > 0 )
+    	{
+    	oldObject = iMdeSession->Session()->GetObjectL( aOldUrl );
+    	if ( oldObject )
+    		{
+    		CleanupStack::PushL( oldObject );
+    		}
+    	}
+    
+    // check if not in mde, harvest
+    if ( !oldObject && !newObject )
+        {
+        HBufC* fn = NULL;        
+
+        if (aNewUrl.Length() > 0)
+        	{
+        	fn = aNewUrl.AllocLC();
+        	}
+        else
+        	{
+        	fn = aOldUrl.AllocLC();
+        	}
+        CHarvesterData* hd = CHarvesterData::NewL( fn );
+        CleanupStack::Pop( fn );
+        hd->SetEventType( EHarvesterAdd );
+        hd->SetOrigin( aOrigin );
+        if( aFastHarvest )
+            {
+            hd->SetObjectType( EFastHarvest );
+            }
+        iObserver->MonitorEvent( hd );
+        }
+
+    if ( oldObject )
+        {
+        // check if same then harvest modify
+        if ( aNewUrl.Length() == 0 || MdsUtils::Compare( aNewUrl, aOldUrl ) == 0 )
+            {
+            HBufC* fn = aOldUrl.AllocLC();
+            CHarvesterData* hd = CHarvesterData::NewL( fn );
+            CleanupStack::Pop( fn );
+            hd->SetEventType(EHarvesterEdit);
+            hd->SetOrigin( aOrigin );
+            if( aFastHarvest )
+                {
+                hd->SetObjectType( EFastHarvest );
+                }
+            iObserver->MonitorEvent( hd );
+            }
+        else if ( newObject )
+        	{
+        	// both are existing so delete new and change uri of old one
+            const TItemId removedId = iMdeSession->Session()->RemoveObjectL( 
+            		newObject->Id() );
+            if ( removedId != KNoId )
+            	{
+            	const TItemId oldObjectId = oldObject->Id();
+            	CleanupStack::PopAndDestroy( oldObject );
+            	oldObject = iMdeSession->Session()->OpenObjectL( oldObjectId );
+                if ( oldObject )
+                    {
+                    CleanupStack::PushL( oldObject );
+                    SetTitleL( oldObject , aNewUrl );
+        	        oldObject->SetUriL( aNewUrl );
+        	        TUint32 mediaId = FSUtil::MediaID( iFs, aNewUrl );
+        	        oldObject->SetMediaId( mediaId );
+        	        TOrigin origin = OriginFromMdEObjectL( *oldObject );
+        	        if( origin == MdeConstants::Object::EOther)
+        	        	{
+        	        	OriginToMdEObjectL( *oldObject, aOrigin );
+        	        	}
+                    iMdeSession->Session()->CommitObjectL( *oldObject );
+                    }
+            	}
+        	}
+        else
+        	{
+        	// case is actually rename
+        	const TItemId oldObjectId = oldObject->Id();
+        	CleanupStack::PopAndDestroy( oldObject );
+        	oldObject = iMdeSession->Session()->OpenObjectL( oldObjectId );
+            if ( oldObject )
+                {
+                CleanupStack::PushL( oldObject );
+                SetTitleL( oldObject , aNewUrl );
+    	        oldObject->SetUriL( aNewUrl );
+    	        TUint32 mediaId = FSUtil::MediaID( iFs, aNewUrl );
+    	        oldObject->SetMediaId( mediaId );
+    	        SetModifiedTimeL( oldObject, aNewUrl );
+    	        TOrigin origin = OriginFromMdEObjectL( *oldObject );
+    	        if( origin == MdeConstants::Object::EOther)
+    	        	{
+    	        	OriginToMdEObjectL( *oldObject, aOrigin );
+    	        	}
+                iMdeSession->Session()->CommitObjectL( *oldObject );
+                }
+        	}
+        }
+    else if ( newObject )
+    	{
+    	// if we replace file from not phone location (e.g. from PC)
+    	// where it create some temporary file and replace aNewUrl file
+       	WRITELOG( "CFileEventHandlerAO::ReplaceL - Different filenames... still try to harvest new one as modify" );
+       	HBufC* fn = aNewUrl.AllocLC();
+       	CHarvesterData* hd = CHarvesterData::NewL( fn );
+       	CleanupStack::Pop( fn );
+        hd->SetEventType( EHarvesterEdit );
+        hd->SetOrigin( aOrigin );
+        if( aFastHarvest )
+            {
+            hd->SetObjectType( EFastHarvest );
+            }
+       	iObserver->MonitorEvent( hd );
+    	}
+
+    if ( oldObject )
+        {
+        CleanupStack::PopAndDestroy( oldObject );
+        }
+
+    if ( newObject )
+        {
+        CleanupStack::PopAndDestroy( newObject );
+        }
+    }
+    
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::ModifyL()
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::ModifyL( const TDesC& aUrl, TOrigin aOrigin, TBool aFastHarvest )
+    {
+    WRITELOG( "CFileEventHandlerAO::ModifyL" );
+    
+    CMdEObject* oldObject = iMdeSession->Session()->GetObjectL( aUrl );
+    
+    // check if not in mde, harvest
+    if ( !oldObject && iObserver )
+        {
+        HBufC* fn = aUrl.AllocLC();
+        CHarvesterData* hd = CHarvesterData::NewL( fn );
+        CleanupStack::Pop( fn );
+        hd->SetEventType( EHarvesterAdd );
+        hd->SetOrigin( aOrigin );
+        if( aFastHarvest )
+            {
+            hd->SetObjectType( EFastHarvest );
+            }
+        iObserver->MonitorEvent( hd );
+        }
+    else if ( iObserver )
+        {
+        HBufC* fn = aUrl.AllocLC();
+        CHarvesterData* hd = CHarvesterData::NewL( fn );
+        CleanupStack::Pop( fn );
+        hd->SetEventType( EHarvesterEdit );
+        hd->SetOrigin( aOrigin );
+        if( aFastHarvest )
+            {
+            hd->SetObjectType( EFastHarvest );
+            }
+        iObserver->MonitorEvent( hd );
+        }
+        
+    if ( oldObject )
+        {
+        delete oldObject;
+        oldObject = NULL;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::DeleteFromMDEL()
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::DeleteFromMDEL( const TDesC& aUrl )
+    {
+    WRITELOG( "CFileEventHandlerAO::DeleteFromMDEL" );
+
+   	iMdeSession->Session()->RemoveObjectL( aUrl );
+    }
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::MultiDeleteFromMDEL()
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::MultiDeleteFromMDEL( const RPointerArray<TDesC>& aUrls )
+    {
+    WRITELOG( "CFileEventHandlerAO::MultiDeleteFromMDEL" );
+
+    RArray<TItemId> results;
+    CleanupClosePushL( results );
+    iMdeSession->Session()->RemoveObjectsL( aUrls, results );
+    CleanupStack::PopAndDestroy( &results );
+    }
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::FormatL()
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::FormatL( TUint32 aOldMediaId, TBool aSubClose )
+	{
+	WRITELOG2( "CFileEventHandlerAO::FormatL - old media ID %d subclose %d", 
+			aOldMediaId, aSubClose );
+
+	if ( aOldMediaId )
+		{
+		iMdeSession->SetFilesToNotPresent( aOldMediaId );
+		if ( aSubClose )
+			{
+			iMdeSession->RemoveFilesNotPresent( aOldMediaId );
+			}
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::RunError()
+// From CActive
+// ---------------------------------------------------------------------------
+//
+#ifdef _DEBUG
+TInt CFileEventHandlerAO::RunError( TInt aError )
+#else
+TInt CFileEventHandlerAO::RunError( TInt /*aError*/ )
+#endif
+    {
+    WRITELOG1( "CFileEventHandlerAO::RunError %d", aError );
+
+    SetNextRequest( ERequestProcessing );
+
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::DoCancel()
+// From CActive
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::DoCancel()
+    {
+    WRITELOG( "CFileEventHandlerAO::DoCancel" );
+
+    }
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::CFileEventHandlerAO()
+// Constructor
+// ---------------------------------------------------------------------------
+//
+CFileEventHandlerAO::CFileEventHandlerAO() : 
+		CActive( KHarvesterPriorityMonitorPlugin )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::SetIgnoreListL()
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::SetIgnoreListL( RPointerArray<TDesC>& aList )
+    {
+    WRITELOG( "CFileEventHandlerAO::SetIgnoreListL" );
+    
+    iIgnoreList.ResetAndDestroy();
+    
+    for ( TInt i = aList.Count(); --i >= 0; )
+        {
+        TDesC* listPath = aList[i];
+        
+        HBufC* name = listPath->AllocLC();
+
+        iIgnoreList.AppendL( name );
+        
+        CleanupStack::Pop( name );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::Mapper()
+// Returns a handle to CProcessOriginMapper.
+// ---------------------------------------------------------------------------
+//
+CProcessOriginMapper& CFileEventHandlerAO::Mapper()
+    {
+    return *iMapper;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CFileEventHandlerAO::NotMoveEvent()
+// Handles other than move events in move case (rename). If the case is not
+// move, then new file must be created.
+// ---------------------------------------------------------------------------
+//
+void CFileEventHandlerAO::NotMoveEvent(RPointerArray<CHarvesterData>& aHDArray)
+	{
+	TInt count = aHDArray.Count();
+	for (int i = 0; i < count; ++i)
+		{
+		CHarvesterData* hd = aHDArray[i];
+        iObserver->MonitorEvent( hd );
+		}
+	}
+
+    
+CMdEHarvesterSession * CFileEventHandlerAO::MdeHarvesterSession()
+    {
+    return iMdeSession;
+    }
+
+
+void CFileEventHandlerAO::AddToQueueL( TMdsFSPStatus& aEvent )
+	{
+	CMdsFSPQueueItem* item = CMdsFSPQueueItem::NewL(aEvent);
+	iQueue.Append(item);
+	if( iNextRequest == ERequestIdle && !iCacheEvents )
+		{
+		SetNextRequest( ERequestProcessing );
+		}
+	}
+
+void CFileEventHandlerAO::SetNextRequest( TRequest aRequest )
+    {
+    WRITELOG( "CFileEventHandlerAO::SetNextRequest" );
+    iNextRequest = aRequest;
+            
+    if ( !IsActive() )
+        {
+        iStatus = KRequestPending;
+        SetActive();
+        TRequestStatus* ptrStatus = &iStatus;
+        User::RequestComplete( ptrStatus, KErrNone );
+        }
+    }
+
+
+void CFileEventHandlerAO::SetCachingStatus( TBool aCachingStatus )
+	{
+	iCacheEvents = aCachingStatus;
+	if ( iCacheEvents )
+		{
+		SetNextRequest( ERequestIdle );
+		}
+	else if ( iQueue.Count() > 0 )
+		{
+		SetNextRequest( ERequestProcessing );
+		}
+	}
+
+void CFileEventHandlerAO::ReadCacheSizeFromCenrepL()
+	{
+	CRepository* repo = CRepository::NewLC( KRepositoryUid );
+	User::LeaveIfError( repo->Get( KCacheSizeKey, iCacheSize ) );
+	CleanupStack::PopAndDestroy( repo );
+	}
+
+//---------------------------------------------------------------------------
+// CFileEventHandlerAO::SetTitle()
+// Set MdE object's title with aNewUrl
+// ---------------------------------------------------------------------------
+//   
+void CFileEventHandlerAO::SetTitleL( CMdEObject* aOldObject, const TDesC& aNewUrl )
+    {
+    TPtrC newName;
+    if( MdsUtils::GetName( aNewUrl, newName ) )
+        {
+        if( !iTitlePropertyDef )
+        	{
+        	iTitlePropertyDef = &aOldObject->Def().GetPropertyDefL( 
+        			MdeConstants::Object::KTitleProperty );
+        	}
+        
+        CMdEProperty* titleProp = NULL;
+        aOldObject->Property( *iTitlePropertyDef, titleProp );
+        if ( titleProp )
+            {
+            TPtrC oldName;
+            if( MdsUtils::GetName( aOldObject->Uri(), oldName ) )
+            	{
+            	// update title property only, 
+            	// if title property is same as the old name and
+            	// the new name is not same as the old name
+            	if( MdsUtils::Compare( oldName, titleProp->TextValueL() ) == 0 && 
+            		MdsUtils::Compare( newName, oldName ) != 0 )
+            		{
+            		titleProp->SetTextValueL( newName );
+            		}
+				}
+            }
+        else
+            {
+            // add title property, if it doesn't exist 
+            aOldObject->AddTextPropertyL( *iTitlePropertyDef , newName );
+            }
+        }
+    }
+
+//---------------------------------------------------------------------------
+// CFileEventHandlerAO::SetModifiedTimeL()
+// ---------------------------------------------------------------------------
+//   
+void CFileEventHandlerAO::SetModifiedTimeL( CMdEObject* aOldObject, const TDesC& aNewUrl )
+    {
+    TTime time;
+    
+    const TInt errorcode = iFs.Modified( aNewUrl, time );
+    if ( errorcode != KErrNone )
+        {
+        return;
+        }
+    
+    if( !iTimePropertyDef )
+        {
+        iTimePropertyDef = &aOldObject->Def().GetPropertyDefL( 
+                       MdeConstants::Object::KLastModifiedDateProperty );
+        }
+       
+    CMdEProperty* timeProp = NULL;
+    aOldObject->Property( *iTimePropertyDef, timeProp );
+    if( timeProp )
+        {
+        timeProp->SetTimeValueL( time );
+        }
+    else
+        {
+        aOldObject->AddTimePropertyL( *iTimePropertyDef , time );
+        }
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/src/filemonitorao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,273 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors file creations, modifications and deletions.*
+*/
+
+
+#include <mdeobject.h>
+
+#include "harvestercommon.h"
+#include "filemonitorao.h"
+#include "harvesterlog.h"
+#include "fsutil.h"
+#include "mdeharvestersession.h"
+#include "processoriginmapper.h"
+#include "fileeventhandlerao.h"
+#include "harvesterpluginfactory.h"
+
+using namespace MdeConstants;
+
+_LIT( KMdsFSPluginFile, "mdsfileserverplugin" );
+_LIT( KMdsFSPluginName, "MdsFileServerPlugin" );
+
+// ---------------------------------------------------------------------------
+// CFileMonitorAO::NewL()
+// ---------------------------------------------------------------------------
+//
+CFileMonitorAO* CFileMonitorAO::NewL()
+    {
+    WRITELOG( "CFileMonitorAO::NewL" );
+
+    CFileMonitorAO* self = new (ELeave) CFileMonitorAO;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CFileMonitorAO::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CFileMonitorAO::ConstructL()
+    {
+    WRITELOG( "CFileMonitorAO::ConstructL" );
+    
+    CActiveScheduler::Add( this );
+    iFsConnectOk = EFalse;
+    }
+
+// ---------------------------------------------------------------------------
+// CFileMonitorAO::~CFileMonitorAO()
+// ---------------------------------------------------------------------------
+//
+CFileMonitorAO::~CFileMonitorAO()
+    {
+    WRITELOG( "CFileMonitorAO::~CFileMonitorAO" );
+    
+    Cancel();
+    
+    StopMonitoring();
+    
+    iIgnoreList.ResetAndDestroy();
+    iIgnoreList.Close();
+
+    
+    delete iMdeSession;
+    }
+
+// ---------------------------------------------------------------------------
+// CFileMonitorAO::StartMonitoring()
+// ---------------------------------------------------------------------------
+//
+TBool CFileMonitorAO::StartMonitoring( MMonitorPluginObserver& aObserver,
+	CMdESession* aMdeSession, const TDesC& aPath, CHarvesterPluginFactory* aHarvesterPluginFactory )
+    {
+    WRITELOG( "CFileMonitorAO::StartMonitoring" );
+    
+    iObserver = &aObserver;
+    iHarvesterPluginFactory = aHarvesterPluginFactory;
+    TRAPD( err, iMdeSession = CMdEHarvesterSession::NewL( *aMdeSession ) );
+    if ( err != KErrNone )
+    	{
+    	return EFalse;
+    	}
+    
+    TRAP( err, iFileEventHandler = CFileEventHandlerAO::NewL( aObserver, iMdeSession, aHarvesterPluginFactory ));
+    if ( err != KErrNone )
+    	{
+    	return EFalse;
+    	}
+    
+    TInt error = iFs.Connect();
+    if ( error != KErrNone )
+    	{
+    	iFs.Close();
+    	return EFalse;
+    	}
+	iFsConnectOk = ETrue;
+
+    // add mds fileserver plugin
+    error = iFs.AddPlugin( KMdsFSPluginFile );
+    if ( error != KErrAlreadyExists )
+        {
+        error = iFs.MountPlugin( KMdsFSPluginName );
+        if ( error != KErrNone )
+            {
+            return EFalse;
+            }
+        }
+    
+    error = iEngine.Open( iFs, KMdsFSPluginPosition );
+    if ( error != KErrNone )
+        {
+        return EFalse;
+        }
+
+    iEngine.Enable();
+    iEngine.AddNotificationPath( aPath );
+    
+    StartNotify();
+    return ETrue;
+    }
+
+// ---------------------------------------------------------------------------
+// CFileMonitorAO::StartNotify()
+// ---------------------------------------------------------------------------
+//
+void CFileMonitorAO::StartNotify()
+    {
+    WRITELOG( "CFileMonitorAO::StartNotify" );
+    
+    ResetMdsFSPStatus();
+        
+    iEngine.RegisterNotification( iStatusPckg, iStatus );
+    
+    SetActive();
+    }
+
+// ---------------------------------------------------------------------------
+// CFileMonitorAO::StopMonitoring()
+// ---------------------------------------------------------------------------
+//
+TBool CFileMonitorAO::StopMonitoring()
+    {
+    WRITELOG( "CFileMonitorAO::StopMonitoring" );
+
+    if ( iFsConnectOk == EFalse )
+    	{
+    	return ETrue;
+    	}
+    
+    Cancel();
+    
+    // remove mds fileserver plugin
+    iEngine.Disable();
+    iEngine.Close();
+    
+	iFs.DismountPlugin( KMdsFSPluginName );
+	iFs.RemovePlugin( KMdsFSPluginName );
+    
+    iFs.Close();
+    iFsConnectOk = EFalse;
+    
+    return ETrue;
+    }
+
+// ---------------------------------------------------------------------------
+// CFileMonitorAO::RunL()
+// From CActive
+// ---------------------------------------------------------------------------
+//
+void CFileMonitorAO::RunL()
+    {
+    WRITELOG( "CFileMonitorAO::RunL" );
+    
+    User::LeaveIfError( iStatus.Int() );
+    TMdsFSPStatus& status = iStatusPckg();
+
+    iFileEventHandler->AddToQueueL(status);
+
+    StartNotify();
+    }
+
+// ---------------------------------------------------------------------------
+// CFileMonitorAO::ResetMdsFSPStatus()
+// ---------------------------------------------------------------------------
+//
+void CFileMonitorAO::ResetMdsFSPStatus()
+    {
+    WRITELOG( "CFileMonitorAO::ResetMdsFSPStatus" );
+    
+    TMdsFSPStatus& status = iStatusPckg();
+    
+    status.iDriveNumber = 0;
+    status.iFileEventType = EMdsFileUnknown;
+    status.iFileName.Zero();
+    status.iNewFileName.Zero();
+    status.iProcessId = TUid::Null();
+    }
+    
+// ---------------------------------------------------------------------------
+// CFileMonitorAO::RunError()
+// From CActive
+// ---------------------------------------------------------------------------
+//
+TInt CFileMonitorAO::RunError( TInt aError )
+    {
+    WRITELOG1( "CFileMonitorAO::RunError %d", aError );
+
+    if ( aError == KErrInUse )
+        {
+        iEngine.NotificationCancel();
+        }
+    else
+        {
+        StartNotify();
+        }
+
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// CFileMonitorAO::DoCancel()
+// From CActive
+// ---------------------------------------------------------------------------
+//
+void CFileMonitorAO::DoCancel()
+    {
+    WRITELOG( "CFileMonitorAO::DoCancel" );
+    iEngine.Disable();
+    iEngine.NotificationCancel();
+    }
+
+// ---------------------------------------------------------------------------
+// CFileMonitorAO::CFileMonitorAO()
+// Constructor
+// ---------------------------------------------------------------------------
+//
+CFileMonitorAO::CFileMonitorAO() : CActive( KHarvesterPriorityMonitorPlugin )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// CFileMonitorAO::Mapper()
+// Returns a handle to CProcessOriginMapper.
+// ---------------------------------------------------------------------------
+//
+CProcessOriginMapper& CFileMonitorAO::Mapper()
+    {
+    return iFileEventHandler->Mapper();
+    }
+
+// ---------------------------------------------------------------------------
+// CFileMonitorAO::Mapper()
+// Set event caching status
+// ---------------------------------------------------------------------------
+//
+void CFileMonitorAO::SetCachingStatus( TBool aCachingStatus )
+	{
+	iFileEventHandler->SetCachingStatus( aCachingStatus );
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/src/filemonitorplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,148 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors file creations, modifications and deletions.*
+*/
+
+#include "mdeharvestersession.h"
+#include "filemonitorplugin.h"
+#include "processoriginmapper.h"
+#include "harvestercenreputil.h"
+
+// ---------------------------------------------------------------------------
+// CFileMonitorPlugin::NewL()
+// ---------------------------------------------------------------------------
+//
+CFileMonitorPlugin* CFileMonitorPlugin::NewL()
+	{
+	CFileMonitorPlugin* self = new (ELeave) CFileMonitorPlugin();
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// CFileMonitorPlugin::~CFileMonitorPlugin()
+// destruct
+// ---------------------------------------------------------------------------
+//
+CFileMonitorPlugin::~CFileMonitorPlugin() 
+	{
+	delete iFileMonitor;
+	}
+
+// ---------------------------------------------------------------------------
+// CFileMonitorPlugin::StartMonitoring()
+// ---------------------------------------------------------------------------
+//
+TBool CFileMonitorPlugin::StartMonitoring( MMonitorPluginObserver& aObserver,
+		CMdESession* aMdEClient, CContextEngine* /*aCtxEngine*/,
+		CHarvesterPluginFactory* aHarvesterPluginFactory )
+	{
+	_LIT( KDrive, "c:" );
+	_LIT( KMonitorPath, "\\Data" );
+	_LIT( KFullPath, "c:\\Data" );
+		
+	TInt err = KErrNone;
+	TBool success = iFileMonitor->StartMonitoring( aObserver, aMdEClient, KFullPath,
+			aHarvesterPluginFactory );
+	
+	if( success )
+		{
+		CHarvesterCenRepUtil* cenRepoUtil = NULL;
+		TRAP( err, cenRepoUtil = CHarvesterCenRepUtil::NewL() );
+		if( cenRepoUtil )
+			{
+			TRAP( err, cenRepoUtil->AddIgnorePathsToFspL( KDrive, KMonitorPath ));
+			}
+		delete cenRepoUtil;
+		}
+	return success && err == KErrNone;
+	}
+
+// ---------------------------------------------------------------------------
+// CFileMonitorPlugin::StopMonitoring()
+// ---------------------------------------------------------------------------
+//
+TBool CFileMonitorPlugin::StopMonitoring()
+	{
+	return iFileMonitor->StopMonitoring();
+	}
+
+// ---------------------------------------------------------------------------
+// CFileMonitorPlugin::ResumeMonitoring()
+// ---------------------------------------------------------------------------
+//
+TBool CFileMonitorPlugin::ResumeMonitoring( MMonitorPluginObserver& /*aObserver*/,
+		CMdESession* /*aMdEClient*/, CContextEngine* /*aCtxEngine*/,
+		CHarvesterPluginFactory* /*aHarvesterPluginFactory*/ )
+	{
+	iFileMonitor->SetCachingStatus( EFalse );
+	return ETrue;
+	}
+
+// ---------------------------------------------------------------------------
+// CFileMonitorPlugin::PauseMonitoring()
+// ---------------------------------------------------------------------------
+//
+TBool CFileMonitorPlugin::PauseMonitoring()
+	{
+	iFileMonitor->SetCachingStatus( ETrue );
+	return ETrue;
+	}
+
+// constructor support
+// don't export these, because used only by functions in this DLL, eg our NewLC()
+// ---------------------------------------------------------------------------
+// CFileMonitorPlugin::CFileMonitorPlugin()
+// first-phase C++ constructor
+// ---------------------------------------------------------------------------
+//
+CFileMonitorPlugin::CFileMonitorPlugin() : iFileMonitor( NULL )
+	{
+	// No implementation required
+	}
+
+// ---------------------------------------------------------------------------
+// CFileMonitorPlugin::ConstructL()
+// second-phase constructor
+// ---------------------------------------------------------------------------
+//
+void CFileMonitorPlugin::ConstructL() 
+	{
+	iFileMonitor = CFileMonitorAO::NewL();
+	}
+
+// ---------------------------------------------------------------------------
+// CFileMonitorPlugin::RegisterProcessOriginL()
+// Registers an origin mapping for a process
+// in file monitor CProcessOriginMapper.
+// ---------------------------------------------------------------------------
+//
+void CFileMonitorPlugin::RegisterProcessL( const TUid& aProcessId,
+        const TOrigin& aOrigin )
+    {
+    iFileMonitor->Mapper().RegisterProcessL( aProcessId, aOrigin );
+    }
+
+// ---------------------------------------------------------------------------
+// CFileMonitorPlugin::UnregisterProcessOriginL()
+// Unregisters an origin mapping for a process.
+// ---------------------------------------------------------------------------
+//
+void CFileMonitorPlugin::UnregisterProcessL( const TUid& aProcessId )
+    {
+    iFileMonitor->Mapper().UnregisterProcessL( aProcessId );
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/src/movetimer.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,132 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+#include <f32file.h>
+#include "movetimer.h"
+#include "mdsutils.h"
+#include "harvestercommon.h"
+
+#include <harvesterdata.h>
+
+const TInt KTimeout = 1000000;
+
+CMoveTimer::CMoveTimer( MMoveTimerObserver* aObserver ) : 
+		CActive( KHarvesterPriorityMonitorPlugin )
+	{
+	iObserver = aObserver;
+	}
+
+CMoveTimer* CMoveTimer::NewLC( MMoveTimerObserver* aObserver )
+	{
+	CMoveTimer* self = new ( ELeave ) CMoveTimer( aObserver );
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+	}
+
+CMoveTimer* CMoveTimer::NewL( MMoveTimerObserver* aObserver )
+	{
+	CMoveTimer* self = CMoveTimer::NewLC( aObserver );
+	CleanupStack::Pop( self ); 
+	return self;
+	}
+
+void CMoveTimer::AddHarvesterDataL( CHarvesterData* aHD )
+	{
+	iHDArray.AppendL( aHD );
+	StartL();
+	}
+
+CHarvesterData* CMoveTimer::CheckUriL( const TDesC& aUri )
+	{
+	TPtrC nameExt;
+	
+	if( MdsUtils::GetNameExt( aUri, nameExt ) )
+		{
+		
+		// check if harvester queue contains harvesting request 
+		// with same file name and extension 
+		for (int i = iHDArray.Count(); --i >= 0; )
+			{
+			CHarvesterData* hd = iHDArray[i];
+			
+			TPtrC tempNameExt;
+			
+			if ( MdsUtils::GetNameExt( hd->Uri(), tempNameExt ) && 
+				 MdsUtils::Compare( nameExt, tempNameExt ) == 0 )
+				{
+				iHDArray.Remove( i );
+				
+				if( iHDArray.Count() == 0 )
+					{
+					iHDArray.Compress();
+					}
+				
+				return hd;
+				}
+			}
+		}
+	
+	return NULL;
+	}
+
+void CMoveTimer::ConstructL()
+	{
+	User::LeaveIfError( iTimer.CreateLocal() );	// Initialize timer
+	CActiveScheduler::Add( this );				// Add to scheduler
+	}
+
+CMoveTimer::~CMoveTimer()
+	{
+	Cancel(); // Cancel any request, if outstanding
+	iTimer.Close(); // Destroy the RTimer object
+	// Delete instance variables if any
+	iHDArray.ResetAndDestroy();
+	iHDArray.Close();
+	}
+
+void CMoveTimer::DoCancel()
+	{
+	iTimer.Cancel();
+	}
+
+void CMoveTimer::StartL()
+	{
+	Cancel();							// Cancel any request, just to be sure
+	iTimer.After( iStatus, KTimeout );	// Set for later
+	SetActive();						// Tell scheduler a request is active
+	}
+
+void CMoveTimer::RunL()
+	{
+	User::LeaveIfError( iStatus.Int() );
+	if( iObserver && iHDArray.Count() > 0)
+		{
+		iObserver->NotMoveEvent( iHDArray );
+		}
+	iHDArray.Reset();
+	iHDArray.Compress();
+	}
+
+TInt CMoveTimer::RunError( TInt /*aError*/ )
+	{
+	if( iObserver && iHDArray.Count() > 0)
+		{
+		iObserver->NotMoveEvent( iHDArray );
+		}
+	iHDArray.Reset();
+	return KErrNone;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/src/processoriginmapper.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,426 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Maintains a list of process ids and matching origin*
+*/
+
+#include <e32base.h>
+#include <f32file.h>
+
+#include "processoriginmapper.h"
+#include "harvesterlog.h"
+
+// File header of the location/origin -mapping file.
+_LIT8( KFileHeader, "Process UID / Origin -mapping table\n"
+                    "\n"
+                    "UID         Origin\n" );
+
+// Location of the process/origin -mapping file.
+_LIT( KDefaultMappingFile, "C:\\private\\200009F5\\mappings.db" );
+_LIT( KDefaultMappingRomFile, "Z:\\private\\200009F5\\mappings.db" );
+
+// Maximum line length read from a file.
+// Thus also size of the line buffer and length of first file header line,
+// which should be file's longest line.
+const TInt KMaxLineLength = 36;
+
+// Length of all file header lines put together.
+const TInt KHeaderLength = 57;
+
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::NewL()
+//-----------------------------------------------------------------------------
+//
+CProcessOriginMapper* CProcessOriginMapper::NewL()
+    {
+    CProcessOriginMapper* self = new (ELeave) CProcessOriginMapper();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+    
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::~CProcessOriginMapper()
+// Destructor.
+//-----------------------------------------------------------------------------
+//
+CProcessOriginMapper::~CProcessOriginMapper()
+    {
+    delete iLineBuffer;
+    iProcessOriginMap.Close();
+    iReadStream.Close();
+    iWriteStream.Close();
+    iFs.Close();
+    }
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::CProcessOriginMapper()
+// Constructor.
+//-----------------------------------------------------------------------------
+//
+CProcessOriginMapper::CProcessOriginMapper()
+	: iLineBuffer( NULL ), iDefaultFileRead( EFalse )
+    {
+    }
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::ConstructL()
+// Second phase construction called by NewL().
+//-----------------------------------------------------------------------------
+//
+void CProcessOriginMapper::ConstructL()
+    {
+    User::LeaveIfError( iFs.Connect() );
+    iLineBuffer = HBufC8::NewL( KMaxLineLength + 4 );
+    }
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::RegisterProcessL()
+// Add a process to the list.
+//-----------------------------------------------------------------------------
+//
+void CProcessOriginMapper::RegisterProcessL( const TUid& aProcessId,
+    const TOrigin& aOrigin )
+    {
+    WRITELOG2( "CProcessOriginMapper::RegisterProcessL - processId: 0x%.8x, origin: %d", aProcessId.iUid, (TInt)aOrigin );
+    const TInt index = FindProcess( aProcessId );
+    if ( index < 0 ) // not found
+        {
+        TProcessOriginPair pair = { aProcessId, aOrigin };
+        iProcessOriginMap.AppendL( pair );
+        }
+    else if ( index < iProcessOriginMap.Count() )
+        {
+        iProcessOriginMap[index].iOrigin = aOrigin;
+        }
+    else
+        {
+        User::Leave( KErrUnknown );
+        }
+    
+    if( !iDefaultFileRead )
+    	{
+    	WriteFileL();
+    	}
+    }
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::UnregisterProcessL()
+// Remove a process from the list.
+//-----------------------------------------------------------------------------
+//
+void CProcessOriginMapper::UnregisterProcessL( const TUid& aProcessId )
+    {
+    WRITELOG1( "CProcessOriginMapper::UnregisterProcessL - processId: 0x%.8x", aProcessId.iUid );
+    const TInt index = FindProcess( aProcessId );
+    if ( index >= 0 && index < iProcessOriginMap.Count() )
+        {
+        iProcessOriginMap.Remove( index );
+        }
+    else
+        {
+        User::Leave( KErrNotFound );
+        }
+    
+    WriteFileL();
+    }
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::OriginL()
+// Check a process from the list.
+//-----------------------------------------------------------------------------
+//
+TOrigin CProcessOriginMapper::OriginL( const TUid& aProcessId )
+    {
+    WRITELOG1( "CProcessOriginMapper::OriginL - search for processId: 0x%.8x", aProcessId.iUid );
+    TOrigin origin = MdeConstants::Object::EOther;
+    const TInt index = FindProcess( aProcessId );
+    if ( index >= 0 && index < iProcessOriginMap.Count() )
+        {
+        origin = iProcessOriginMap[index].iOrigin;
+        }
+    else
+        {
+        WRITELOG( "CProcessOriginMapper::OriginL - search for processId: not found !!" );
+        User::Leave( KErrNotFound );
+        }
+
+    WRITELOG2( "CProcessOriginMapper::OriginL - processId: 0x%.8x, origin: %d", aProcessId.iUid, (TInt)origin );
+    return origin;
+    }
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::ReadFileL()
+// Read process id mappings from a file.
+// This doesn't clear the list of currently registered mappings.
+//-----------------------------------------------------------------------------
+//
+TInt CProcessOriginMapper::ReadFileL( const TDesC& aFile )
+    {
+    WRITELOG1( "CProcessOriginMapper::ReadFileL - START reading file %S", &aFile );
+    if ( aFile.Length() <= 0 || aFile.Length() > KMaxFileName )
+        {
+        User::Leave( KErrBadName );
+        }
+
+    TInt err = iReadStream.Open( iFs, aFile, EFileRead | EFileStreamText );
+    if ( err == KErrNotFound || err == KErrPathNotFound )
+        {
+        // if mappings file is not found, try to read from rom (Z) drive
+        err = iReadStream.Open( iFs, KDefaultMappingRomFile, EFileRead | EFileStreamText );
+        }
+    User::LeaveIfError( err );
+
+    // read / match file header
+
+    const TChar KLineFeed = '\n';
+    TPtr8 ptr( iLineBuffer->Des() );
+    iReadStream.ReadL( ptr, KLineFeed );
+    ptr.SetLength( KMaxLineLength-1 );
+    TBufC8<KHeaderLength> headerBuf( KFileHeader );
+    if ( headerBuf.Locate( KLineFeed ) != KMaxLineLength-1 ||
+        iLineBuffer->Compare( headerBuf.Left(KMaxLineLength-1) ) != 0 )
+        {
+        User::Leave( KErrCorrupt );
+        }
+    iReadStream.ReadL( ptr, KLineFeed );  // skip the next two lines (header stuff)
+    iReadStream.ReadL( ptr, KLineFeed );
+
+    TUid processId = { 0 };
+    TOrigin origin = MdeConstants::Object::EOther;
+
+    // read and register pairs one by one
+    // for-loop limits the maximum amount of loops
+    TInt count = 0;
+    for ( count = 0; count < KMaxMappingSize; count++ )  
+        {
+        TRAP( err, ReadProcessOriginPairL( processId, origin ) );
+        if ( err == KErrEof )
+            {
+            // successful exit
+            break;
+            }
+        else if ( err != KErrNone )
+            {
+            User::Leave( KErrCorrupt );
+            }
+        RegisterProcessL( processId, origin );
+        }
+
+    iReadStream.Release();
+    WRITELOG2( "CProcessOriginMapper::ReadFileL - END reading file %S, count %d", &aFile, count );
+    return count;
+    }
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::ReadFileL()
+// Read process id mappings from the default file.
+//-----------------------------------------------------------------------------
+//
+TInt CProcessOriginMapper::ReadFileL()
+    {
+    WRITELOG( "CProcessOriginMapper::ReadFileL - reading default file..." );
+    iDefaultFileRead = ETrue;
+    const TInt count = ReadFileL( KDefaultMappingFile );
+    iDefaultFileRead = EFalse;
+    return count;
+    }
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::WriteFileL()
+// Writes process id mappings to a file.
+//-----------------------------------------------------------------------------
+//
+void CProcessOriginMapper::WriteFileL( const TDesC& aFile )
+    {
+    WRITELOG1( "CProcessOriginMapper::WriteFileL - writing file %S", &aFile );
+    if ( aFile.Length() <= 0 || aFile.Length() > KMaxFileName )
+        {
+        User::Leave( KErrBadName );
+        }
+
+    TInt err = iWriteStream.Replace( iFs, aFile,
+            EFileWrite | EFileShareExclusive | EFileStreamText );
+    User::LeaveIfError( err );
+    CleanupClosePushL( iWriteStream );
+    
+    // write file header
+    
+    iWriteStream.WriteL( KFileHeader );
+    
+    TUid processId = { 0 };
+    TOrigin origin = MdeConstants::Object::EOther;
+
+    // write pairs one by one
+    // for-loop limits the maximum amount of loops
+    const TInt count = iProcessOriginMap.Count();
+    for ( TInt i( 0 ); i < count; i++ )
+        {
+        processId = iProcessOriginMap[i].iProcessId;
+        origin = iProcessOriginMap[i].iOrigin;
+        TRAP( err, WriteProcessOriginPairL( processId, origin ) );
+        if ( err != KErrNone )
+            {
+            User::Leave( KErrCorrupt );
+            }
+        }
+    
+    iWriteStream.CommitL();
+    iWriteStream.Release();
+
+    CleanupStack::PopAndDestroy( &iWriteStream );
+    }
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::WriteFileL()
+// Write process id mappings to the default file.
+//-----------------------------------------------------------------------------
+//
+void CProcessOriginMapper::WriteFileL()
+    {
+    WRITELOG( "CProcessOriginMapper::WriteFileL - writing default file..." );
+    WriteFileL( KDefaultMappingFile );
+    }
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::Clear()
+// Clear mapping table in memory.
+//-----------------------------------------------------------------------------
+//
+void CProcessOriginMapper::Clear()
+    {
+    WRITELOG( "CProcessOriginMapper::Clear - clearing origin map db" );
+    iProcessOriginMap.Reset();
+    }
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::Count()
+// Return the count of currently registered mappings.
+//-----------------------------------------------------------------------------
+//
+TInt CProcessOriginMapper::Count()
+    {
+    return iProcessOriginMap.Count();
+    }
+
+
+// PRIVATE METHODS
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::FindProcess()
+// Find index by process id.
+//-----------------------------------------------------------------------------
+//
+TInt CProcessOriginMapper::FindProcess( const TUid& aProcessId )
+    {
+    const TInt count = iProcessOriginMap.Count();
+    for ( TInt i( 0 ); i < count; i++ )
+        {
+        if ( iProcessOriginMap[i].iProcessId == aProcessId )
+            {
+            return i;
+            }
+        }
+
+    return KErrNotFound;
+    }
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::ReadProcessOriginPairL()
+// Read one related process/origin pair from a text file.
+//-----------------------------------------------------------------------------
+//
+void CProcessOriginMapper::ReadProcessOriginPairL( TUid& aProcessId,
+    TOrigin& aOrigin )
+    {    
+    const TUint32 KMinTestRangeId = 0xE0000000;
+    const TUint32 KMaxTestRangeId = 0xEFFFFFFF; 
+    
+    const TUint32 KMaxProcessId = 0xFFFFFFFF;
+    const TChar KLineFeed = '\n';
+
+    // read a line
+
+    TPtr8 ptr( iLineBuffer->Des() );
+    iReadStream.ReadL( ptr, KLineFeed );
+
+    TUint32 tempId = 0;
+    TInt16 tempOrigin = 0;
+    
+    // parse process id
+
+    TLex8 parser( ptr );
+    TInt err = parser.Val( tempId, EHex );
+    if ( err == KErrGeneral )
+        {
+        User::Leave( KErrEof );
+        }
+    else if ( err != KErrNone ) 
+        {
+        User::Leave( err ); // might be KErrOverflow
+        }
+
+    // parse origin
+
+    parser.SkipSpace();
+    err = parser.Val( tempOrigin );
+    if ( err == KErrGeneral )
+        {
+        User::Leave( KErrCorrupt );
+        }
+    else if ( err != KErrNone ) 
+        {
+        User::Leave( err ); // might be KErrOverflow
+        }
+
+    if ( tempOrigin < 0 )
+        {
+        User::Leave( KErrCorrupt );
+        }
+    if ( tempId >= KMinTestRangeId && 
+         tempId <= KMaxTestRangeId )
+        {
+        User::Leave( KErrCorrupt );
+        }
+    else if( tempId > KMaxProcessId )
+        {
+        User::Leave( KErrCorrupt );
+        }
+
+    // set results
+    
+    aProcessId = TUid::Uid( tempId );
+    aOrigin = TOrigin( tempOrigin );
+    }
+
+//-----------------------------------------------------------------------------
+// CProcessOriginMapper::WriteProcessOriginPairL()
+// Write one related process/origin pair to a file.
+//-----------------------------------------------------------------------------
+//
+void CProcessOriginMapper::WriteProcessOriginPairL( TUid& aProcessId,
+    TOrigin& aOrigin )
+    {
+    _LIT8( KDelimiter, "\t" );
+    _LIT8( KLineFeed, "\n" );
+    TPtr8 ptr( iLineBuffer->Des() );
+    ptr.Num( aProcessId.iUid );
+    iWriteStream.WriteL( ptr );
+    iWriteStream.WriteL( KDelimiter );
+    ptr.Num( aOrigin );
+    iWriteStream.WriteL( ptr );
+    iWriteStream.WriteL( KLineFeed );
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/fileplugin/src/proxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation proxy.*
+*/
+
+#include <e32std.h>
+#include <implementationproxy.h>
+
+#include "filemonitorplugin.h"
+
+// Map the interface UIDs to implementation factory functions
+const TImplementationProxy KImplementationTable[] = 
+	{
+		{{0x20007186},	(TProxyNewLPtr)CFileMonitorPlugin::NewL}
+	};
+
+// Exported proxy for instantiation method resolution
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+	{
+	aTableCount = sizeof(KImplementationTable) / sizeof(TImplementationProxy);
+	return KImplementationTable;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+#include "../monitorplugininterface/group/bld.inf"
+#include "../fileplugin/group/bld.inf"
+#include "../mdsfileserverplugin/group/bld.inf"
+#include "../messageplugin/group/bld.inf"
+#include "../mmcplugin/group/bld.inf"
+#include "../mdsoomplugin/group/bld.inf"
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/inc/fsutil.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Some generic utilities.*
+*/
+
+#ifndef __FSUTIL_H__
+#define __FSUTIL_H__
+
+#include <e32base.h>
+
+class CMdEHarvesterSession;
+
+class FSUtil
+    {
+	public:
+	    
+	    static inline TUint32 MediaID( const RFs& aFs, TInt aDrive );
+	        
+	    static inline TUint32 MediaID( const RFs& aFs, const TDesC& aUri );
+
+		/*
+		 * Returns previous media id was inserted to a slot
+		 * 
+		 * @param aMdeSession	Session for database access
+		 * @param aDrive		Drive letter which media id is wanted
+		 */
+		static inline TUint32 GetPreviousMediaIDL( const CMdEHarvesterSession* aMdeSession, 
+												   TChar aDrive );
+	    
+	private:
+	
+	    static inline TInt DriveNumber( const TDesC& aUri );
+    };
+
+#include "fsutil.inl" // inlined methods
+
+#endif // __FSUTIL_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/inc/fsutil.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,82 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Some generic utilities.*
+*/
+
+
+#include "mdscommoninternal.h"
+#include "mdeharvestersession.h"
+#include <e32base.h>
+
+inline TUint32 FSUtil::MediaID( const RFs& aFs, TInt aDrive )
+    {
+    TVolumeInfo vi;
+    
+    TInt err = aFs.Volume(vi, aDrive);
+    if(err == KErrNone)
+        {
+        return vi.iUniqueID;
+        }
+        
+    return 0;
+    }
+
+inline TUint32 FSUtil::MediaID( const RFs& aFs, const TDesC& aUri )
+    {
+    TInt drive = DriveNumber(aUri);
+    if(drive == -1)
+        {
+        return 0;
+        }
+        
+    return MediaID(aFs, drive);
+    }
+
+inline TUint32 FSUtil::GetPreviousMediaIDL( const CMdEHarvesterSession* aMdeSession,
+											TChar aDrive )
+	{
+	RArray<TMdEMediaInfo> presentMedias;
+	CleanupClosePushL( presentMedias );
+	CMdEHarvesterSession* sess = (CMdEHarvesterSession*) aMdeSession;
+	sess->GetPresentMediasL( presentMedias );
+
+    TUint32 mediaid = 0;
+    TInt count = presentMedias.Count();
+    for( TInt i=0;i<count;i++ )
+    	{
+    	TMdEMediaInfo info = presentMedias[i];
+    	if( info.iDrive == aDrive )
+    		{
+    		mediaid = info.iMediaId;
+    		break;
+    		}
+    	}
+    CleanupStack::PopAndDestroy( &presentMedias );
+    
+    return mediaid;
+	}
+
+inline TInt FSUtil::DriveNumber( const TDesC& aUri )
+    {
+    TChar ch = aUri[0];
+    TInt drive = 0;
+    TInt err = RFs::CharToDrive(ch, drive);
+    if(err == KErrNone)
+        {
+        return drive;
+        }
+        
+    return -1;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/inc/mdsfileserverpluginclient.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,129 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors file creations, modifications and deletions.*
+*/
+
+
+#ifndef __MDSFILESERVERPLUGINCLIENT_H__
+#define __MDSFILESERVERPLUGINCLIENT_H__
+
+enum TMdsFSPOperation
+	{
+	EMdsFSPOpEnable,
+	EMdsFSPOpDisable,
+	EMdsFSPOpRegisterNotification,
+	EMdsFSPOpAddNotificationPath,
+	EMdsFSPOpRemoveNotificationPath,
+	EMdsFSPOpAddIgnorePath,
+	EMdsFSPOpRemoveIgnorePath,
+	EMdsFSPOpNotificationCancel,
+	};
+
+class TMdsFSPStatus
+	{
+	public:
+		TInt iFileEventType;
+		TInt iDriveNumber;
+		TFileName iFileName;
+		TFileName iNewFileName;
+        TUid iProcessId;
+        TUint32 iDriveMediaId;
+	};
+
+enum TMdsFileEventType
+	{
+	EMdsFileCreated,
+	EMdsFileRenamed,
+	EMdsFileModified,
+	EMdsFileReplaced,
+	EMdsFileDeleted,
+	EMdsDriveFormatted,
+	EMdsFileUnknown,
+	EMdsDirRenamed
+	};
+
+typedef TPckgBuf<TMdsFSPStatus> TMdsFSPStatusPckg;
+
+const TInt KMdsFSPluginPosition = 0x200071CD;
+
+#ifndef __MDSFILESERVERPLUGIN_H__
+#include <f32file.h>
+#ifdef SYMBIAN_ENABLE_SPLIT_HEADERS
+#include <f32file_private.h>
+#endif
+
+
+/**
+ * 
+ */
+class RMdsFSPEngine : public RPlugin
+	{
+	public:
+
+		/**
+		 * Register...
+		 * @param aMdsFSPStatus ...
+		 * @param aStat  TRequestStatus for asyncronous operation.
+		 */
+		inline void RegisterNotification( TMdsFSPStatusPckg& aMdsFSPStatus,
+				TRequestStatus& aStat);
+
+		/**
+		 * Adds a new path to monitor.
+		 * @param aPath  Path to add.
+		 */
+		inline void AddNotificationPath( const TDesC& aPath );
+
+		/**
+		 * Removes a path from list of monitored paths.
+		 * @param aPath  Path to remove.
+		 */
+		inline void RemoveNotificationPath( const TDesC& aPath );
+
+		/**
+		 * Adds a new ignored path.
+		 * @param aPath Path descriptor.
+		 */
+		inline void AddIgnorePath( const TDesC& aPath );
+
+		/**
+		 * Removes a ignored path from the list.
+		 * @param aPath Path descriptor.
+		 */
+		inline void RemoveIgnorePath( const TDesC& aPath );
+
+		/**
+		 * Enable plugin.
+		 * @return Error code.
+		 */
+		inline TInt Enable();
+
+		/**
+		 * Disable plugin.
+		 * @return Error code.
+		 */
+		inline TInt Disable();
+
+		/**
+		 * Cancel notifications.
+		 */
+		inline void NotificationCancel();
+	};
+
+#include "mdsfileserverpluginclient.inl"  // inlined methods
+
+#endif // __MDSFILESERVERPLUGIN_H__
+
+#endif // __MDSFILESERVERPLUGINCLIENT_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/inc/mdsfileserverpluginclient.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,90 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors file creations, modifications and deletions.*
+*/
+
+
+inline TInt RMdsFSPEngine::Enable()
+	{
+	return DoControl( EMdsFSPOpEnable );
+	}
+
+inline TInt RMdsFSPEngine::Disable()
+	{
+	return DoControl( EMdsFSPOpDisable );
+	}
+
+inline void RMdsFSPEngine::RegisterNotification(
+		TMdsFSPStatusPckg& aMdsFSPStatus, TRequestStatus& aStat )
+	{
+	DoRequest( EMdsFSPOpRegisterNotification, aStat, aMdsFSPStatus );
+	}
+
+inline void RMdsFSPEngine::AddNotificationPath( const TDesC& aPath )
+	{
+	TMdsFSPStatusPckg pckg;
+	TRequestStatus rs;
+	TMdsFSPStatus& status = pckg();
+
+	status.iFileName.Zero();
+	status.iFileName.Copy( aPath );
+
+	DoRequest( EMdsFSPOpAddNotificationPath, rs, pckg );
+	User::WaitForRequest( rs );
+	}
+
+inline void RMdsFSPEngine::RemoveNotificationPath( const TDesC& aPath )
+	{
+	TMdsFSPStatusPckg pckg;
+	TRequestStatus rs;
+	TMdsFSPStatus& status = pckg();
+
+	status.iFileName.Zero();
+	status.iFileName.Copy( aPath );
+
+	DoRequest( EMdsFSPOpRemoveNotificationPath, rs, pckg );
+	User::WaitForRequest( rs );
+	}
+
+inline void RMdsFSPEngine::AddIgnorePath (const TDesC& aPath )
+	{
+	TMdsFSPStatusPckg pckg;
+	TRequestStatus rs;
+	TMdsFSPStatus& status = pckg();
+
+	status.iFileName.Zero();
+	status.iFileName.Copy( aPath );
+
+	DoRequest( EMdsFSPOpAddIgnorePath, rs, pckg );
+	User::WaitForRequest( rs );
+	}
+
+inline void RMdsFSPEngine::RemoveIgnorePath( const TDesC& aPath )
+	{
+	TMdsFSPStatusPckg pckg;
+	TRequestStatus rs;
+	TMdsFSPStatus& status = pckg();
+
+	status.iFileName.Zero();
+	status.iFileName.Copy( aPath );
+
+	DoRequest( EMdsFSPOpRemoveIgnorePath, rs, pckg );
+	User::WaitForRequest( rs );
+	}
+
+inline void RMdsFSPEngine::NotificationCancel()
+	{
+	DoCancel( EMdsFSPOpNotificationCancel );
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/inc/mdsfspqueue.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Queue/cache item for file server plugin events*
+*/
+
+
+#ifndef __MDSFSPQUEUE_H__
+#define __MDSFSPQUEUE_H__
+
+#include <e32base.h>
+#include "mdsfileserverpluginclient.h"
+
+class CMdsFSPQueueItem : public CBase
+	{
+	public: 
+		inline static CMdsFSPQueueItem* NewL();
+		inline static CMdsFSPQueueItem* NewL( TMdsFSPStatus& aStatus );
+		
+		inline virtual ~CMdsFSPQueueItem();
+		
+		inline void GetAsFspStatus( TMdsFSPStatus& aStatus );
+		
+		inline void SetStatusL( TMdsFSPStatus& aStatus );
+				
+	public:	
+		TInt iFileEventType;
+		TInt iDriveNumber;
+		HBufC* iFileName;
+		HBufC* iNewFileName;
+        TUid iProcessId;
+        TUint32 iDriveMediaId;
+	};
+	
+#include "mdsfspqueue.inl"
+
+#endif /*__MDSFSPQUEUE_H__*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/inc/mdsfspqueue.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,90 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Queue/cache item for file server plugin events*
+*/
+
+
+#include "mdsfspqueue.h"
+
+//-----------------------------------------------------------------------------
+// CMdsFSPQueueItem::NewL()
+//-----------------------------------------------------------------------------
+//
+CMdsFSPQueueItem* CMdsFSPQueueItem::NewL()
+	{
+	CMdsFSPQueueItem *self = new (ELeave) CMdsFSPQueueItem();
+	return self;
+	}
+
+
+//-----------------------------------------------------------------------------
+// CMdsFSPQueueItem::NewL()
+//-----------------------------------------------------------------------------
+//
+CMdsFSPQueueItem* CMdsFSPQueueItem::NewL( TMdsFSPStatus& aStatus )
+	{
+	CMdsFSPQueueItem *self = new (ELeave) CMdsFSPQueueItem();
+	CleanupStack::PushL( self );
+	self->SetStatusL( aStatus );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+//-----------------------------------------------------------------------------
+// CMdsFSPQueueItem::GetAsFspStatus()
+//-----------------------------------------------------------------------------
+//
+void CMdsFSPQueueItem::GetAsFspStatus( TMdsFSPStatus& aStatus )
+	{
+	aStatus.iDriveNumber = iDriveNumber;
+	aStatus.iFileName.Copy( *iFileName );
+	aStatus.iNewFileName.Copy( *iNewFileName );
+	aStatus.iFileEventType = iFileEventType;
+	aStatus.iProcessId = iProcessId;
+	}
+
+//-----------------------------------------------------------------------------
+// CMdsFSPQueueItem::SetStatus()
+//-----------------------------------------------------------------------------
+//
+void CMdsFSPQueueItem::SetStatusL( TMdsFSPStatus& aStatus )
+	{
+	iDriveNumber = aStatus.iDriveNumber;
+	iFileEventType = aStatus.iFileEventType;
+	iProcessId = aStatus.iProcessId;
+
+	if( iFileName ) 
+		{
+		delete iFileName;
+		}
+	if( iNewFileName )
+		{
+		delete iNewFileName;
+		}
+	
+	iFileName = aStatus.iFileName.AllocL();
+	iNewFileName = aStatus.iNewFileName.AllocL();
+	
+	}
+
+//-----------------------------------------------------------------------------
+// CMdsFSPQueueItem::~CMdsFSPQueueItem()
+//-----------------------------------------------------------------------------
+//
+CMdsFSPQueueItem::~CMdsFSPQueueItem()
+	{
+	delete iFileName;
+	delete iNewFileName;
+	}
+    
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mdsfileserverplugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+mdsfileserverplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mdsfileserverplugin/group/mdsfileserverplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,44 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        mdsfileserverplugin.pxt
+TARGETTYPE    fsy
+UID           0x100039DF 0x200071CD
+
+CAPABILITY 	  TCB ProtServ DiskAdmin AllFiles PowerMgmt CommDD
+VENDORID      VID_DEFAULT
+
+USERINCLUDE   ../inc
+USERINCLUDE   ../../inc
+USERINCLUDE   ../../../../inc
+
+SOURCEPATH    ../src
+SOURCE        mdsfileserverplugin.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       efile.lib
+LIBRARY       efsrv.lib
+
+OPTION ARMCC -O3 -OTime
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mdsfileserverplugin/inc/mdsfileserverplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,172 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors file creations, modifications and deletions.*
+*/
+
+
+#ifndef __MDSFILESERVERPLUGIN_H__
+#define __MDSFILESERVERPLUGIN_H__
+
+#include <f32plugin.h>
+#include "mdsfileserverpluginclient.h"
+#include "mdsfspqueue.h"
+
+const TInt KDoubleMaxFileName = 2 * KMaxFileName;
+/**
+* File server plug-in.
+*/
+class CMdsFileServerPlugin : public CFsPlugin
+	{
+    public:
+
+        /**
+         * Standard NewL()
+         * From CActive.
+         */
+        static CMdsFileServerPlugin* NewL();
+
+        /**
+         * Virtual destructor.
+         */
+        virtual ~CMdsFileServerPlugin();
+
+        /**
+         * Initialize plugin.
+         */
+        virtual void InitialiseL();
+
+        virtual TInt DoRequestL( TFsPluginRequest& aRequest );
+
+        virtual CFsPluginConn* NewPluginConnL();
+
+        TInt RegisterNotification( CFsPluginConnRequest& aRequest );
+
+        /**
+         * Add a new notification path.
+         */
+        TInt AddNotificationPath( const CFsPluginConnRequest& aRequest );
+
+        /**
+         * Remove notification path.
+         */
+        TInt RemoveNotificationPath( const CFsPluginConnRequest& aRequest );
+
+        /**
+         * Add a new path to ignore.
+         */
+        TInt AddIgnorePath( const CFsPluginConnRequest& aRequest );
+
+        /**
+         * Remove a path from the ignore list.
+         */
+        TInt RemoveIgnorePath( const CFsPluginConnRequest& aRequest );
+
+        void EnableL();
+
+        void DisableL();
+
+        /**
+         * Add CMdsFileServerPluginConn connection to this file server plugin.
+         */
+        void AddConnection();
+        
+        /**
+         * Remove CMdsFileServerPluginConn connection from this file server 
+         * plugin.
+         */
+        void RemoveConnection();
+        
+    private:
+
+        /**
+         * Private constructor.
+         */
+        CMdsFileServerPlugin();
+
+        /**
+         * Check if a path is listed.
+         * 
+         * @param aFilename  Path to check.
+         * 
+         * @return EFalse, if path is ignored.
+         *         ETrue, if the path is on the notification path list or
+         *         if there is no notification paths set.
+         *         Else EFalse.
+         */
+        TBool CheckPath( const TDesC& aFilename ) const;
+
+        /**
+         * Check if path/file hass hidden or system attribute.
+         * 
+         * @param aFilename  Filename to check.
+         * @param aIsDirectory ETrue if filename points to directory.
+         * 
+         * @return EFalse, if path or file has a hidden or system attribute set.
+         */
+        TBool CheckAttribs( const TDesC& aFilename, TBool& aIsDirectory ) const;
+
+        /**
+         * Check if directory is named correctly and ends with backslash.
+         * 
+         * @param aDirName  Directory name to check.
+         */
+		void AddBackslashIfNeeded ( TDes& aDirName ) const;
+		
+        /**
+         * Check if harvester (main observer) is alive
+         */
+        TBool CheckHarvesterStatus();
+        
+#ifdef _DEBUG_EVENTS
+        void RegisterDebugEventsL();
+        void UnregisterDebugEventsL();
+        void PrintDebugEvents( TInt aFunction );
+#endif
+    	
+    private:
+
+        CFsPluginConnRequest* iNotification;
+
+        /**
+         * An array of notification paths.
+         */
+        RPointerArray<TDesC> iPaths;
+
+        /**
+         * A queue of file server events.
+         */
+        RPointerArray<CMdsFSPQueueItem> iQueue;
+
+        RPointerArray<TDesC> iIgnorePaths;
+
+        /**
+         * File system client session.
+         */
+        RFs iFsSession;
+
+        RPointerArray<TDesC> iCreatedFiles;
+        
+        TUint32 iFormatOldMediaId;
+        TInt iFormatDriveNumber;
+        
+        TInt iConnectionCount;
+        
+        TBuf<KDoubleMaxFileName> iFileName;
+        TBuf<KDoubleMaxFileName> iNewFileName;
+        
+        TInt iPendingEvents;
+        
+    };
+
+#endif // __MDSFILESERVERPLUGIN_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mdsfileserverplugin/src/mdsfileserverplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1235 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors file creations, modifications and deletions.*
+*/
+
+
+#include <f32pluginutils.h>
+#include "mdsfileserverplugin.h"
+#include "harvesterlog.h"
+#include "mdsutils.h"
+
+_LIT( KMdsFileServerPlugin, "MdsFileServerPlugin" );
+
+/* Server name */
+_LIT( KHarvesterServerName, "HarvesterServer" );
+
+const TInt KCleanQueueTreshoald( 1000 );
+
+//-----------------------------------------------------------------------------
+// CMdsFileServerPlugin implementation
+//-----------------------------------------------------------------------------
+//
+CMdsFileServerPlugin::CMdsFileServerPlugin()
+: iFormatOldMediaId( 0 ), iFormatDriveNumber( -1 ), iConnectionCount( 0 )
+	{
+	WRITELOG( "CMdsFileServerPlugin::CMdsFileServerPlugin()" );
+	}
+	
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+CMdsFileServerPlugin::~CMdsFileServerPlugin()
+    {
+    WRITELOG( "CMdsFileServerPlugin::~CMdsFileServerPlugin()" );
+    
+    TRAP_IGNORE( DisableL() );
+    iFsSession.Close();
+    
+    iCreatedFiles.ResetAndDestroy();
+    iCreatedFiles.Close();
+  
+    iPaths.ResetAndDestroy();
+    iPaths.Close();
+    
+    iIgnorePaths.ResetAndDestroy();
+    iIgnorePaths.Close();
+        
+    iQueue.ResetAndDestroy();
+    iQueue.Close();
+    }
+    
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+CMdsFileServerPlugin* CMdsFileServerPlugin::NewL()
+    {
+    WRITELOG( "CMdsFileServerPlugin::NewL()" );
+    return new (ELeave) CMdsFileServerPlugin;
+    }
+
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+void CMdsFileServerPlugin::InitialiseL()
+    {
+    WRITELOG( "CMdsFileServerPlugin::InitializeL()" );
+    User::LeaveIfError( iFsSession.Connect() );
+    }
+    
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+void CMdsFileServerPlugin::EnableL()
+    {
+    WRITELOG( "CMdsFileServerPlugin::EnableL()" );
+    User::LeaveIfError( RegisterIntercept(EFsFileCreate, EPostIntercept) );
+    User::LeaveIfError( RegisterIntercept(EFsFileRename, EPostIntercept) );
+    User::LeaveIfError( RegisterIntercept(EFsRename, EPostIntercept) );
+    User::LeaveIfError( RegisterIntercept(EFsDelete, EPostIntercept) );
+    User::LeaveIfError( RegisterIntercept(EFsFileReplace, EPostIntercept) );
+    User::LeaveIfError( RegisterIntercept(EFsReplace, EPostIntercept) );
+    User::LeaveIfError( RegisterIntercept(EFsFileSetModified, EPostIntercept) );
+    User::LeaveIfError( RegisterIntercept(EFsFileSubClose, EPostIntercept) );
+    User::LeaveIfError( RegisterIntercept(EFsSetEntry, EPostIntercept) );
+	// format events
+	User::LeaveIfError( RegisterIntercept(EFsFormatSubClose, EPostIntercept) );
+	User::LeaveIfError( RegisterIntercept(EFsFormatOpen, EPreIntercept) );
+
+#ifdef _DEBUG_EVENTS
+    RegisterDebugEventsL();
+#endif
+    }
+    
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+void CMdsFileServerPlugin::DisableL()
+    {
+    WRITELOG( "CMdsFileServerPlugin::DisableL()" );
+    User::LeaveIfError( UnregisterIntercept(EFsFileCreate, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept(EFsFileRename, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept(EFsRename, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept(EFsDelete, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept(EFsFileReplace, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept(EFsReplace, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept(EFsFileSetModified, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept(EFsFileSubClose, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept(EFsSetEntry, EPrePostIntercept) );
+	// format events
+	User::LeaveIfError( UnregisterIntercept(EFsFormatSubClose, EPostIntercept) );
+	User::LeaveIfError( UnregisterIntercept(EFsFormatOpen, EPreIntercept) );
+
+#ifdef _DEBUG_EVENTS
+    UnregisterDebugEventsL();
+#endif
+    }
+    
+//-----------------------------------------------------------------------------
+// AddConnection
+//-----------------------------------------------------------------------------
+//
+void CMdsFileServerPlugin::AddConnection()
+    {
+    WRITELOG( "CMdsFileServerPlugin::AddConnection()" );
+    
+    ++iConnectionCount;
+    iPendingEvents = 0;
+    }
+
+//-----------------------------------------------------------------------------
+// RemoveConnection
+//-----------------------------------------------------------------------------
+//
+void CMdsFileServerPlugin::RemoveConnection()
+    {
+    WRITELOG( "CMdsFileServerPlugin::RemoveConnection()" );
+
+    --iConnectionCount;
+
+    // remove notification request if this was last connection
+    if( iConnectionCount <= 0 )
+    	{
+    	WRITELOG( "CMdsFileServerPlugin::RemoveConnection() last connection" );
+    	
+    	iNotification = NULL;
+    	iPendingEvents = 0;
+    	iQueue.ResetAndDestroy();
+    	iQueue.Compress();
+    	}
+    }
+
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+TInt CMdsFileServerPlugin::DoRequestL( TFsPluginRequest& aRequest )
+	{
+	// ignore event if there is no any client listening
+	if( iConnectionCount <= 0 )
+		{
+		WRITELOG( "CMdsFileServerPlugin::DoRequestL() - no clients -> ignore event" );
+		return KErrNone;
+		}
+	
+	TInt function = aRequest.Function();
+	
+	iFileName.Zero();
+	
+#ifdef _DEBUG_EVENTS
+    PrintDebugEvents( function );
+#endif
+    
+    if ( function == EFsFileSubClose && iCreatedFiles.Count() == 0 )
+        {
+#ifdef _DEBUG_EVENTS
+        if( GetName( &aRequest, iFileName ) == KErrNone && iFileName.Length() <= KMaxFileName )
+            {
+            WRITELOG1("Dropping subclose %S",&iFileName);
+            }
+#endif
+        return KErrNone;
+        }
+    
+    const TBool formatFunction = function == EFsFormatOpen || function == EFsFormatSubClose;
+    iNewFileName.Zero();
+        
+    WRITELOG1( "----- CMdsFileServerPlugin::DoRequestL() - plugin function: %d -----", function );
+
+	if ( !formatFunction )
+		{
+		if( GetName( &aRequest, iFileName ) != KErrNone || iFileName.Length() > KMaxFileName )
+		    {
+		    return KErrNone;
+		    }
+		else
+		    {
+		    WRITELOG1( "CMdsFileServerPlugin::DoRequestL() - fileName: %S", &iFileName );
+		    }
+		}
+
+    // get process id
+	TUid processId = { 0 };
+
+	processId = aRequest.Message().SecureId();
+
+	TBool isDirectory = EFalse;
+	
+    // if rename, check destination path
+    if ( function == EFsRename  || function == EFsFileRename || 
+    	 function == EFsReplace || function == EFsFileReplace  ||
+    	 function == EFsSetEntry )
+        {
+        const TInt newNameErr = GetNewName( &aRequest, iNewFileName );
+        if ( iNewFileName.Length() > KMaxFileName )
+        	{
+        	return KErrNone;
+        	}
+        WRITELOG2( "CMdsFileServerPlugin::DoRequestL() - newFileName: '%S' %d", &iNewFileName, newNameErr );
+        if ( newNameErr == KErrNone )
+            {
+            if ( !CheckPath(iNewFileName) )
+                {
+                WRITELOG( "CMdsFileServerPlugin::DoRequestL() - new path not supported" );
+                if( !CheckPath(iFileName) )
+                    {
+                    WRITELOG( "CMdsFileServerPlugin::DoRequestL() - old path not supported" );
+                    WRITELOG( "CMdsFileServerPlugin::DoRequestL() - ignore file" );
+                    return KErrNone;
+                    }
+                // file moved to ignored path, delete from db
+                function = EFsDelete;
+                }
+            
+            if ( !CheckAttribs( iNewFileName, isDirectory ) )
+                {
+                WRITELOG( "CMdsFileServerPlugin::DoRequestL() - new path attribute check failed" );
+                if( !CheckAttribs(iFileName, isDirectory) )
+                    {
+                    WRITELOG( "CMdsFileServerPlugin::DoRequestL() - old path attribute check failed" );
+                    WRITELOG( "CMdsFileServerPlugin::DoRequestL() - ignore file" );
+                    return KErrNone;
+                    }
+                // file set to hidden, delete from db
+                function = EFsDelete;
+                }
+            }
+        else
+        	{
+            if ( !CheckPath(iFileName) )
+                {
+                WRITELOG( "CMdsFileServerPlugin::DoRequestL() - path not supported" );
+                return KErrNone;
+                }
+
+            if ( !CheckAttribs(iFileName, isDirectory) )
+                {
+                WRITELOG( "CMdsFileServerPlugin::DoRequestL() - attribute check failed" );
+                return KErrNone;
+                }
+        	}
+        }
+    else if ( !formatFunction )
+        {
+        if ( !CheckPath(iFileName) )
+            {
+            WRITELOG( "CMdsFileServerPlugin::DoRequestL() - path not supported" );
+            return KErrNone;
+            }
+
+        if ( !CheckAttribs( iFileName, isDirectory ) )
+            {
+            WRITELOG( "CMdsFileServerPlugin::DoRequestL() - attribute check failed" );
+            return KErrNone;
+            }
+        }
+
+    TInt fileEventType = EMdsFileUnknown;
+    TInt drvNumber = aRequest.DriveNumber();
+    TVolumeInfo volInfo;
+
+    WRITELOG1( "CMdsFileServerPlugin::DoRequestL() - drive number: %d", drvNumber );
+
+    TInt err( KErrNone );
+    
+    switch( function )
+        {
+        case EFsFileCreate:
+            {
+#ifdef _DEBUG            
+            if (function == EFsFileCreate)            
+            	WRITELOG( "CMdsFileServerPlugin::DoRequestL() - EFsFileCreate" );
+            if (function == EFsFileReplace)
+            	WRITELOG( "CMdsFileServerPlugin::DoRequestL() - EFsFileReplace" );
+#endif            
+            
+            iCreatedFiles.Append( iFileName.AllocL() );
+            User::LeaveIfError( UnregisterIntercept(EFsFileSetModified, EPostIntercept) );
+            return KErrNone;
+            }
+
+        case EFsFileSubClose:
+            {
+            WRITELOG( "CMdsFileServerPlugin::DoRequestL() - EFsFileSubClose" );
+
+            TBool found = EFalse;
+
+           	for ( TInt i = iCreatedFiles.Count(); --i >= 0; )
+            		{
+           			if ( MdsUtils::Compare( iFileName, *(iCreatedFiles[i]) ) == 0 )
+            		  {
+            			fileEventType = EMdsFileCreated;
+            			delete iCreatedFiles[i];
+            			iCreatedFiles.Remove( i );
+            			
+						//Have to check whether file has been hidden
+						if ( CheckAttribs( iFileName, isDirectory ) )
+							{
+							found = ETrue;
+							}
+    						
+            			User::LeaveIfError( RegisterIntercept(EFsFileSetModified, EPostIntercept) );
+            			}
+            		}
+           	
+           	if( iCreatedFiles.Count() == 0 )
+				{
+				iCreatedFiles.GranularCompress();
+				}
+            
+            if ( !found )
+                {
+                return KErrNone;
+                }
+            }
+            break;
+
+        case EFsRename:
+            {
+            WRITELOG1( "CMdsFileServerPlugin::DoRequestL() - EFsRename, new file: %S", &iNewFileName );
+            
+            if ( isDirectory )
+            	{
+				WRITELOG( "CMdsFileServerPlugin::DoRequestL() - it is directory!" );			
+				fileEventType = EMdsDirRenamed;
+				AddBackslashIfNeeded( iNewFileName ); // new file name 
+				AddBackslashIfNeeded( iFileName ); // old file name
+            	}
+            else
+            	{
+            	fileEventType = EMdsFileRenamed;
+            	}
+            }
+            break;
+
+        case EFsFileRename:
+            WRITELOG1( "CMdsFileServerPlugin::DoRequestL() - EFsFileRename, new file: %S", &iNewFileName );
+            fileEventType = EMdsFileRenamed;
+            break;
+
+        case EFsFileSetModified:
+        case EFsSetEntry:
+            WRITELOG( "CMdsFileServerPlugin::DoRequestL() - EFsFileSetModified" );
+            fileEventType = EMdsFileModified;
+            break;
+
+        case EFsFileReplace:
+        case EFsReplace:
+            WRITELOG1( "CMdsFileServerPlugin::DoRequestL() - EFsReplace/EFsFileReplace, new file: %S", &iNewFileName );
+            fileEventType = EMdsFileReplaced;
+            break;
+
+        case EFsDelete:
+            WRITELOG( "CMdsFileServerPlugin::DoRequestL() - EFsDelete" );
+            fileEventType = EMdsFileDeleted;
+            break;
+
+		case EFsFormatOpen:
+			WRITELOG( "CMdsFileServerPlugin::DoRequestL() - EFsFormatOpen" );
+			// get the drive letter
+			err = iFsSession.Volume( volInfo, drvNumber );
+			if( KErrNone == err )
+				{
+				iFormatOldMediaId = volInfo.iUniqueID;
+				iFormatDriveNumber = drvNumber;
+				fileEventType = EMdsDriveFormatted;
+				processId.iUid = 0;
+				}
+			else
+				{
+				iFormatDriveNumber = -1;
+				}
+			return KErrNone;
+
+		case EFsFormatSubClose:
+			WRITELOG( "CMdsFileServerPlugin::DoRequestL() - EFsFormatSubClose" );
+			if ( iFormatDriveNumber < 0 )
+				{
+				return KErrNone;
+				}
+			drvNumber = iFormatOldMediaId;
+			volInfo.iUniqueID = iFormatOldMediaId;
+			iFormatOldMediaId = 0;
+			iFormatDriveNumber = -1;
+			fileEventType = EMdsDriveFormatted;
+			if ( processId.iUid == 0 )
+				{
+				processId.iUid = 1;
+				}
+			break;
+
+        default:
+            WRITELOG( "CMdsFileServerPlugin::DoRequestL() - Unknown function" );
+            return KErrNone;
+        }
+
+    if ( iNotification )
+        {
+        WRITELOG( "CMdsFileServerPlugin::DoRequestL() - iNotification found" );
+        TMdsFSPStatusPckg clientStatusBuf;
+        TMdsFSPStatus& clientStatus = clientStatusBuf();
+        clientStatus.iDriveNumber = drvNumber;
+        clientStatus.iDriveMediaId = volInfo.iUniqueID;
+        clientStatus.iFileName.Copy( iFileName );
+        clientStatus.iNewFileName.Copy( iNewFileName );
+        clientStatus.iFileEventType = fileEventType;
+        clientStatus.iProcessId = processId;
+
+        TRAP( err, iNotification->WriteParam1L(clientStatusBuf) );
+        iNotification->Complete( err );
+        iNotification = NULL;
+        WRITELOG( "CMdsFileServerPlugin::DoRequestL() - iNotification complete" );
+        }
+    else // no notification ready, put in the queue
+        {
+        WRITELOG( "CMdsFileServerPlugin::DoRequestL() - iNotification not found. Put in the queue" );
+
+        // Check if harvester is still alive
+        if( CheckHarvesterStatus() )
+            {
+            CMdsFSPQueueItem* queueItem = CMdsFSPQueueItem::NewL();
+            CleanupStack::PushL( queueItem );
+            queueItem->iDriveNumber = drvNumber;
+            queueItem->iDriveMediaId = volInfo.iUniqueID;
+            queueItem->iFileName = iFileName.AllocL();
+            queueItem->iNewFileName = iNewFileName.AllocL();
+            queueItem->iFileEventType = fileEventType;
+            queueItem->iProcessId = processId;
+
+            iQueue.AppendL( queueItem ); // owenership is transferred
+            CleanupStack::Pop( queueItem );
+            err = KErrNone;
+            iPendingEvents++;
+            WRITELOG( "CMdsFileServerPlugin::DoRequestL() - added to queue" );
+            }
+        else
+            {
+            WRITELOG( "CMdsFileServerPlugin::DoRequestL() - Harvester process not detected" );
+            iConnectionCount = 0;
+            iPendingEvents = 0;
+            iQueue.ResetAndDestroy();
+            iQueue.Compress();
+            }
+        }
+    
+    WRITELOG( "CMdsFileServerPlugin::DoRequestL() - return" );
+    return err;
+    }
+
+//-----------------------------------------------------------------------------
+// CMdsFileServerPluginConn implementation
+//-----------------------------------------------------------------------------
+class CMdsFileServerPluginConn : public CFsPluginConn
+    {
+    public:
+        static CMdsFileServerPluginConn* NewL( CMdsFileServerPlugin& aPlugin );
+        virtual ~CMdsFileServerPluginConn();
+
+        virtual TInt DoControl( CFsPluginConnRequest& aRequest );
+        virtual void DoRequest( CFsPluginConnRequest& aRequest );
+        virtual void DoCancel( TInt aReqMask );
+
+    private:
+    	CMdsFileServerPluginConn( CMdsFileServerPlugin& aPlugin );
+
+    	CMdsFileServerPlugin& iPlugin;
+
+        RMessage2* iMessage;
+    };
+    
+/**
+* Leaving New function for the plugin
+* @internalComponent
+*/
+CMdsFileServerPluginConn* CMdsFileServerPluginConn::NewL( 
+		CMdsFileServerPlugin& aPlugin )
+    {
+    WRITELOG( "CMdsFileServerPluginConn::NewL()" );
+    return new (ELeave) CMdsFileServerPluginConn( aPlugin );
+    }
+
+
+/**
+* Constructor for the plugin
+* @internalComponent
+*/
+CMdsFileServerPluginConn::CMdsFileServerPluginConn( 
+		CMdsFileServerPlugin& aPlugin ) : 
+		iPlugin( aPlugin )
+    {
+    WRITELOG( "CMdsFileServerPluginConn::CMdsFileServerPluginConn()" );
+    
+    iPlugin.AddConnection();
+    }
+
+
+/**
+* The destructor for the test virus scanner hook.
+* @internalComponent
+*/
+CMdsFileServerPluginConn::~CMdsFileServerPluginConn()
+    {
+    WRITELOG( "CMdsFileServerPluginConn::~CMdsFileServerPluginConn()" );
+    
+    iPlugin.RemoveConnection();
+    }
+
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+TInt CMdsFileServerPluginConn::DoControl( CFsPluginConnRequest& aRequest )
+    {
+    WRITELOG( "CMdsFileServerPluginConn::DoControl()" );
+    TInt err = KErrNotSupported;
+    
+    CMdsFileServerPlugin& myPlugin = *(CMdsFileServerPlugin*)Plugin();
+    
+    switch( aRequest.Function() )
+        {
+        case EMdsFSPOpEnable:
+            {
+            WRITELOG( "CMdsFileServerPluginConn::DoControl() - EMdsFSPOpEnable" );
+            TRAP( err, myPlugin.EnableL() );
+            break;
+            }
+        
+        case EMdsFSPOpDisable:
+            {
+            WRITELOG( "CMdsFileServerPluginConn::DoControl() - EMdsFSPOpDisable" );
+            TRAP( err, myPlugin.DisableL() );
+            break;
+            }
+        
+        default:
+            {
+            WRITELOG( "CMdsFileServerPluginConn::DoControl() - Unknown Control" );
+            break;            
+            }
+        }
+
+    return err;
+    }
+    
+
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+void CMdsFileServerPluginConn::DoRequest( CFsPluginConnRequest& aRequest )
+    {
+    WRITELOG( "CMdsFileServerPluginConn::DoRequest()" );
+    CMdsFileServerPlugin& myPlugin = *(CMdsFileServerPlugin*)Plugin();
+    
+    switch( aRequest.Function() )
+        {
+        case EMdsFSPOpRegisterNotification:
+            {
+            WRITELOG( "CMdsFileServerPluginConn::DoControl() - EMdsFSPOpRegisterNotification" );
+            const TInt err = myPlugin.RegisterNotification( aRequest );
+            
+            if ( err != KErrNone )
+                {
+                aRequest.Complete( err );
+                }
+            break;
+            }
+            
+        case EMdsFSPOpAddNotificationPath:
+            {
+            WRITELOG( "CMdsFileServerPluginConn::DoControl() - EMdsFSPOpAddNotificationPath" );
+            const TInt err = myPlugin.AddNotificationPath( aRequest );
+            aRequest.Complete( err );
+            break;
+            }
+            
+        case EMdsFSPOpRemoveNotificationPath:
+            {
+            WRITELOG( "CMdsFileServerPluginConn::DoControl() - EMdsFSPOpRemoveNotificationPath" );
+            const TInt err = myPlugin.RemoveNotificationPath( aRequest );
+            aRequest.Complete( err );
+            break;
+            }
+            
+        case EMdsFSPOpAddIgnorePath:
+            {
+            WRITELOG( "CMdsFileServerPluginConn::DoControl() - EMdsFSPOpAddIgnorePath" );
+            const TInt err = myPlugin.AddIgnorePath( aRequest );
+            aRequest.Complete( err );
+            break;
+            }
+            
+        case EMdsFSPOpRemoveIgnorePath:
+            {
+            WRITELOG( "CMdsFileServerPluginConn::DoControl() - EMdsFSPOpRemoveIgnorePath" );
+            const TInt err = myPlugin.RemoveIgnorePath( aRequest );
+            aRequest.Complete( err );
+            break;
+            }
+        default:
+            break;
+        }
+    }
+
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+void CMdsFileServerPluginConn::DoCancel( TInt /*aReqMask*/ )
+    {
+    WRITELOG( "CMdsFileServerPluginConn::DoCancel()" );
+    iRequestQue.DoCancelAll( KErrCancel );
+    }
+    
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+CFsPluginConn* CMdsFileServerPlugin::NewPluginConnL()
+    {
+    WRITELOG( "CMdsFileServerPluginConn::NewPluginConnL()" );
+    return CMdsFileServerPluginConn::NewL( *this );
+    }
+    
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+TInt CMdsFileServerPlugin::RegisterNotification( CFsPluginConnRequest& aRequest )
+    {
+    WRITELOG( "CMdsFileServerPlugin::RegisterNotification()" );
+    
+    if ( iNotification )
+        {
+        return KErrInUse;
+        }
+    
+    iNotification = &aRequest;
+    
+    if ( iQueue.Count() > 0 )
+        {
+        WRITELOG( "CMdsFileServerPlugin::RegisterNotification() - item in queue" );
+        
+        CMdsFSPQueueItem* queueItem = iQueue[0];
+        
+        TMdsFSPStatusPckg pckg;
+        TMdsFSPStatus& status = pckg();
+        
+        queueItem->GetAsFspStatus( status );
+
+        TRAPD( err, iNotification->WriteParam1L(pckg) );
+        iNotification->Complete( err );
+        iNotification = NULL;
+        
+        delete queueItem;
+        queueItem = NULL;
+        iQueue.Remove( 0 );
+        }
+    else
+    	{
+    	iQueue.GranularCompress();
+    	}
+    
+    return KErrNone;
+    }
+    
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+TInt CMdsFileServerPlugin::AddNotificationPath( const CFsPluginConnRequest& aRequest )
+    {
+    WRITELOG( "CMdsFileServerPlugin::AddNotificationPath()" );
+    TInt err = KErrNone;
+    
+    TMdsFSPStatusPckg pckg;
+    TRAP( err, aRequest.ReadParam1L(pckg) );
+    
+    if ( err != KErrNone )
+        {
+        return err;
+        }
+    
+    TMdsFSPStatus& status = pckg();
+    
+    if ( status.iFileName.Length() > 0 )
+        {
+        // check if already exists
+        for ( TInt i = iPaths.Count(); --i >= 0; )
+            {
+            TDesC* tf = iPaths[i];
+            if ( MdsUtils::Compare( status.iFileName, *tf ) == 0 )
+                {
+                return KErrNone;
+                }
+            }
+
+        WRITELOG1( "CMdsFileServerPlugin::AddNotificationPath() - add path: %S", &status.iFileName );
+        HBufC* fn = status.iFileName.Alloc();
+        if ( fn )
+            {
+            iPaths.Append( fn );
+            }
+        }
+    else
+        {
+        err = KErrNotFound;
+        }
+        
+    return err;
+    }
+    
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+TInt CMdsFileServerPlugin::RemoveNotificationPath( const CFsPluginConnRequest& aRequest )
+    {
+    WRITELOG( "CMdsFileServerPlugin::RemoveNotificationPath()" );
+    TInt err = KErrNone;
+    
+    TMdsFSPStatusPckg pckg;
+    TRAP( err, aRequest.ReadParam1L(pckg) );
+    
+    if ( err != KErrNone )
+        {
+        return err;
+        }
+    
+    TMdsFSPStatus& status = pckg();
+    
+    if ( status.iFileName.Length() > 0 )
+        {
+        // check if already exist
+        if ( iPaths.Count() > 0 )
+            {
+            for ( TInt i = iPaths.Count(); --i >= 0; )
+                {
+                TDesC* tf = iPaths[i];
+                if ( MdsUtils::Compare( status.iFileName, *tf ) == 0 )
+                    {
+                    WRITELOG1( "CMdsFileServerPlugin::RemoveNotificationPath() - remove path: %S", &status.iFileName );
+                    delete tf;
+                    tf = NULL;
+                    iPaths.Remove( i );
+                    }
+                }
+            }
+        }
+    else
+        {
+        err = KErrNotFound;
+        }
+        
+    return err;
+    }
+    
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+TInt CMdsFileServerPlugin::AddIgnorePath( const CFsPluginConnRequest& aRequest )
+    {
+    WRITELOG( "CMdsFileServerPlugin::AddIgnorePath()" );
+    TInt err = KErrNone;
+    
+    TMdsFSPStatusPckg pckg;
+    TRAP( err, aRequest.ReadParam1L(pckg) );
+    
+    if ( err != KErrNone )
+        {
+        return err;
+        }
+    
+    TMdsFSPStatus& status = pckg();
+    
+    if ( status.iFileName.Length() > 0 )
+        {
+        // check if already exist
+        for ( TInt i = iIgnorePaths.Count(); --i >= 0; )
+            {
+            TDesC* tf = iIgnorePaths[i];
+            if ( MdsUtils::Compare( status.iFileName, *tf ) == 0 )
+                {
+                return KErrNone;
+                }
+            }
+            
+        WRITELOG1( "CMdsFileServerPlugin::AddIgnorePath() - add path: %S", &status.iFileName );
+        HBufC* fn = status.iFileName.Alloc();
+        if ( fn )
+            {
+            iIgnorePaths.Append( fn ); // ownership is transferred
+            }
+        }
+    else
+        {
+        err = KErrNotFound;
+        }
+        
+    return err;
+    }
+    
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+TInt CMdsFileServerPlugin::RemoveIgnorePath( const CFsPluginConnRequest& aRequest )
+    {
+    WRITELOG( "CMdsFileServerPlugin::RemoveIgnorePath()" );
+    TInt err = KErrNone;
+    
+    TMdsFSPStatusPckg pckg;
+    TRAP( err, aRequest.ReadParam1L(pckg) );
+    
+    if ( err != KErrNone )
+        {
+        return err;
+        }
+    
+    TMdsFSPStatus& status = pckg();
+    
+    if ( status.iFileName.Length() > 0 )
+        {
+        // check if already exist
+        for ( TInt i = iIgnorePaths.Count(); --i >= 0; )
+            {
+            TDesC* tf = iIgnorePaths[i];
+            if ( MdsUtils::Compare(status.iFileName, *tf ) == 0 )
+                {
+                WRITELOG1( "CMdsFileServerPlugin::RemoveIgnorePath() - remove path: %S", &status.iFileName );
+                delete tf;
+                tf = NULL;
+                iIgnorePaths.Remove( i );
+                }
+            }
+        }
+    else
+        {
+        err = KErrNotFound;
+        }
+        
+    return err;
+    }
+    
+//-----------------------------------------------------------------------------
+// CheckPath
+//-----------------------------------------------------------------------------
+//
+TBool CMdsFileServerPlugin::CheckPath( const TDesC& aFilename ) const
+    {
+    // check if ignored pathlist
+    for ( TInt i = iIgnorePaths.Count(); --i >= 0; )
+        {    
+        TDesC* pathName = iIgnorePaths[i];
+        if ( MdsUtils::Find( aFilename, *pathName ) != KErrNotFound )
+            {
+            return EFalse;
+            }
+        }
+
+    // check if notification path
+    if ( iPaths.Count() > 0 )
+        {
+        for ( TInt i = iPaths.Count(); --i >= 0; )
+            {
+            TDesC* pathName = iPaths[i];
+            if ( MdsUtils::Find( aFilename, *pathName ) != KErrNotFound )
+                {
+                return ETrue;
+                }
+            }
+        }
+    else
+        {
+        return ETrue;
+        }
+
+    return EFalse;
+    }
+
+//-----------------------------------------------------------------------------
+// CheckAttribs
+//-----------------------------------------------------------------------------
+//
+TBool CMdsFileServerPlugin::CheckAttribs( const TDesC& aFilename, 
+		TBool& aIsDirectory ) const
+	{
+	// find last backslash from filename and 
+    // take drive and path from filename including last backslash
+    const TChar KBackslashChar( '\\' );
+    TInt pos = aFilename.LocateReverse( KBackslashChar );
+    if ( KErrNotFound == pos )
+    	{
+    	return ETrue;
+    	}
+    TPtrC path( aFilename.Left( pos + 1 ) );
+
+    TUint att = 0;
+
+    // check if path is hidden or system path
+    TInt err = iFsSession.Att( path, att );
+    if ( err == KErrNone )
+        {
+        if ( att & KEntryAttHidden || att & KEntryAttSystem )
+            {
+            return EFalse;
+            }
+        }
+
+    // or is the file hidden or system file
+    att = 0;
+    err = iFsSession.Att( aFilename, att );
+    if ( err == KErrNone )
+        {
+        if ( att & KEntryAttHidden || att & KEntryAttSystem )
+            {
+            return EFalse;
+            }
+        
+        aIsDirectory = att & KEntryAttDir ? ETrue : EFalse;
+        }
+
+    return ETrue;
+    }
+
+//-----------------------------------------------------------------------------
+// AddBackslashIfNeeded
+//-----------------------------------------------------------------------------
+//
+void CMdsFileServerPlugin::AddBackslashIfNeeded( TDes& aDirName ) const
+	{
+	WRITELOG1( "CMdsFileServerPlugin::AddBackslashIfNeeded() - begin, dirName: %S", &aDirName );
+
+	const TChar KBackslashChar( '\\' );
+	
+	const TInt lastChar = aDirName.Length() - 1;
+	
+	// If it is directory which not contain backslash. 
+	if ( KBackslashChar != aDirName[lastChar] )
+		{		
+		aDirName.Append( KBackslashChar );
+		}
+
+	WRITELOG1( "CMdsFileServerPlugin::AddBackslashIfNeeded() - end, dirName: %S", &aDirName );
+	}
+
+//-----------------------------------------------------------------------------
+// CheckHarvesterStatus
+//-----------------------------------------------------------------------------
+//
+TBool CMdsFileServerPlugin::CheckHarvesterStatus()
+    {
+    WRITELOG( "CMdsFileServerPlugin::CheckHarvesterStatus() - begin" );
+
+    if( iPendingEvents <= KCleanQueueTreshoald )
+        {
+        WRITELOG( "CMdsFileServerPlugin::CheckHarvesterStatus() - end" );
+        return ETrue;
+        }
+    
+    TFindServer findHarvesterServer( KHarvesterServerName );
+    TFullName name;
+
+    TInt result = findHarvesterServer.Next( name );
+    if ( result == KErrNone )
+        {
+        WRITELOG( "CMdsFileServerPlugin::CheckHarvesterStatus() - HarvesterServer running" );
+        WRITELOG( "CMdsFileServerPlugin::CheckHarvesterStatus() - end" );
+        
+        iPendingEvents = 0;
+        return ETrue;
+        }
+    
+    WRITELOG( "CMdsFileServerPlugin::CheckHarvesterStatus() - end" );
+    return EFalse;
+    }
+
+//-----------------------------------------------------------------------------
+// CMdsFileServerPluginFactory implementation
+//-----------------------------------------------------------------------------
+//
+class CMdsFileServerPluginFactory : public CFsPluginFactory
+    {
+    public:
+        CMdsFileServerPluginFactory();
+        virtual TInt Install();            
+        virtual CFsPlugin* NewPluginL();
+        virtual TInt UniquePosition();
+    };
+    
+// Constructor for the plugin factory
+// @internalComponent
+CMdsFileServerPluginFactory::CMdsFileServerPluginFactory()
+    {
+    WRITELOG( "CMdsFileServerPluginFactory::CMdsFileServerPluginFactory()" );
+    }
+
+// Install function for the plugin factory
+// @internalComponent
+TInt CMdsFileServerPluginFactory::Install()
+    {
+    WRITELOG( "CMdsFileServerPluginFactory::Install()" );
+    iSupportedDrives = KPluginAutoAttach;
+    
+    return( SetName(&KMdsFileServerPlugin) );
+    }
+
+// @internalComponent
+TInt CMdsFileServerPluginFactory::UniquePosition()
+    {
+    WRITELOG( "CMdsFileServerPluginFactory::UniquePosition()" );
+    return( KMdsFSPluginPosition );
+    }
+
+// Plugin factory function
+// @internalComponent
+CFsPlugin* CMdsFileServerPluginFactory::NewPluginL()
+    {
+    WRITELOG( "CMdsFileServerPluginFactory::NewPluginL()" );
+    return CMdsFileServerPlugin::NewL();
+    }
+
+// Create a new Plugin
+// @internalComponent
+extern "C"
+    {
+    EXPORT_C CFsPluginFactory* CreateFileSystem()
+        {
+        WRITELOG( "CMdsFileServerPluginFactory::CreateFileSystem" );
+        return( new CMdsFileServerPluginFactory() );
+        }
+    }
+
+#ifdef _DEBUG_EVENTS
+
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+void CMdsFileServerPlugin::RegisterDebugEventsL()
+    {
+    User::LeaveIfError( RegisterIntercept( EFsFileDuplicate, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileCreate, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileWrite, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileFlush, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileSetAtt, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileChangeMode, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsDelete, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileAdopt, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileLock, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileSize, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileRename, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsRename, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileOpen, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileTemp,    EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileUnLock, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileSetSize, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileDrive, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsReplace, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileSubClose, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileRead, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileSeek, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileAtt, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileSet, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsFileName, EPreIntercept) );
+    User::LeaveIfError( RegisterIntercept( EFsDirOpen, EPreIntercept) );
+    }
+    
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+void CMdsFileServerPlugin::UnregisterDebugEventsL()
+    {
+    User::LeaveIfError( UnregisterIntercept( EFsFileDuplicate, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileCreate, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileWrite, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileFlush, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileSetAtt, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileChangeMode, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsDelete, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileAdopt, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileLock, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileSize, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileRename, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsRename, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileOpen, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileTemp, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileUnLock, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileSetSize, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileDrive, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsReplace, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileSubClose, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileRead, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileSeek, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileAtt, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileSet, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsFileName, EPrePostIntercept) );
+    User::LeaveIfError( UnregisterIntercept( EFsDirOpen, EPrePostIntercept) );
+    }
+    
+//-----------------------------------------------------------------------------
+// 
+//-----------------------------------------------------------------------------
+//
+void CMdsFileServerPlugin::PrintDebugEvents( TInt aFunction )
+    {
+    switch ( aFunction )
+        {
+        case EFsFileDuplicate:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileDuplicate" );
+            break;
+            
+        case EFsFileCreate:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileCreate" );
+            break;
+        case EFsFileWrite:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileWrite" );
+            break;
+        case EFsFileFlush:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileFlush" );
+            break;
+        case EFsFileSetAtt:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileSetAtt" );
+            break;
+        case EFsFileChangeMode:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileChangeMode" );
+            break;    
+        case EFsDelete:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsDelete" );
+            break;    
+        case EFsFileAdopt:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileAdopt" );
+            break;    
+        case EFsFileReplace:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileReplace" );
+            break;    
+        case EFsFileLock:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileLock" );
+            break;    
+        case EFsFileSize:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileSize" );
+            break;    
+        case EFsFileModified:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileModified" );
+            break;    
+        case EFsFileRename:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileRename" );
+            break;    
+        case EFsRename:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsRename" );
+            break;    
+        case EFsFileOpen:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileOpen" );
+            break;    
+        case EFsFileTemp:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileTemp" );
+            break;    
+        case EFsFileUnLock:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileUnLock" );
+            break;    
+        case EFsFileSetSize:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileSetSize" );
+            break;    
+        case EFsFileSetModified:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileSetModified" );
+            break;
+        case EFsFileDrive:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileDrive" );
+            break;    
+        case EFsReplace:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsReplace" );
+            break;    
+        case EFsFileSubClose:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileSubClose" );
+            break;    
+        case EFsFileRead:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileRead" );
+            break;
+        case EFsFileSeek:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileSeek" );
+            break;    
+        case EFsFileAtt:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileAtt" );
+            break;    
+        case EFsFileSet:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileSet" );
+            break;    
+        case EFsFileName:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsFileName" );
+            break;    
+        case EFsDirOpen:
+            WRITELOG( "CMdsFileServerPlugin::PrintDebugEvents() - EFsDirOpen" );
+            break;    
+        default:
+        break;
+        }
+    }
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mdsoomplugin/data/2001B2C6.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// 2001B2C6.rss
+
+#include "registryinfov2.rh"
+#include <oommonitorplugin.hrh>
+
+RESOURCE REGISTRY_INFO theInfo
+{
+    // resource_format_version must always be set as follows
+    resource_format_version = RESOURCE_FORMAT_VERSION_2;
+	
+    dll_uid = 0x2001B2C6;
+    interfaces =
+    {
+    INTERFACE_INFO
+        {
+        interface_uid = KOomPluginInterfaceUidValue;
+        implementations =
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = 0x2001B2C6;
+					version_no = 1;
+					display_name = "MdS OOM plugin";
+					default_data = "";
+					opaque_data = "";
+					rom_only = 0;
+                    }
+                };
+        }
+    };
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mdsoomplugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+mdsoomplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mdsoomplugin/group/mdsoomplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION        10.0
+TARGETTYPE PLUGIN
+TARGET mdsoomplugin.dll
+UID 0x10009D8D 0x2001B2C6
+
+CAPABILITY 	  CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+start RESOURCE ../data/2001B2C6.rss
+TARGET       mdsoomplugin.rsc
+end
+
+SYSTEMINCLUDE /epoc32/include/ecom
+
+USERINCLUDE   ../../../../inc
+USERINCLUDE   ../inc
+USERINCLUDE   ../../../common/inc
+
+SOURCEPATH    ../src
+SOURCE        mdsoomplugin.cpp
+SOURCE        proxy.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       ECom.lib
+LIBRARY       oommonitor.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mdsoomplugin/inc/mdsoomplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,90 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Low memory observer for havester server
+*
+*/
+
+
+#ifndef MDSOOMPLUGIN_H
+#define MDSOOMPLUGIN_H
+
+// INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <e32msgqueue.h>
+
+#include <oommonitorplugin.h>
+
+// CLASS DECLARATION
+
+/**
+*  CMdSOomPlugin
+* 
+*/
+class CMdSOomPlugin : public COomMonitorPlugin
+	{
+public:
+	// Constructors and destructor
+	static CMdSOomPlugin* NewL();
+	
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdSOomPlugin();	
+	
+
+	/**
+	 * From COomMonitorPlugin
+	 * FreeRam is called when the system RAM level becomes
+	 * low. This plugin is requested to help free some RAM.
+	 */
+	void FreeRam();
+
+	/**
+	 * From COomMonitorPlugin
+	 * MemoryGood is called when the system RAM level becomes
+	 * good after being low.The plugin may take this opportunity
+	 * to start using RAM again.
+	 * Nb It is assumed that the plugin will not immediately
+	 * cause a large increase in memory use, but that memory may be
+	 * used over time, otherwise the plugin may cause oscillation
+	 * between low and good memory states.
+	 */
+	void MemoryGood();
+
+private:
+
+	/**
+	 * Constructor for performing 1st stage construction
+	 */
+	CMdSOomPlugin();
+	
+	/**
+	 * default constructor for performing 2nd stage construction
+	 */
+	void ConstructL();
+
+	/**
+	 * From COomMonitorPlugin
+	 */
+	void ExtensionInterface(TUid aInterfaceId, TAny*& aImplementation);
+    
+private:
+
+	RMsgQueue<TInt> iOomMsgQueue;
+	
+	};
+
+#endif // MDSOOMPLUGIN_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mdsoomplugin/src/mdsoomplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,75 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Low memory observer for havester server
+*
+*/
+
+
+#include "mdsoomplugin.h"
+#include "harvesterlog.h"
+#include "harvestercommon.h"
+
+
+CMdSOomPlugin::CMdSOomPlugin()
+	{
+	WRITELOG("CMdSOomPlugin::CMdSOomPlugin()");
+	}
+
+
+CMdSOomPlugin::~CMdSOomPlugin()
+	{
+	iOomMsgQueue.Close();
+	}
+
+CMdSOomPlugin* CMdSOomPlugin::NewL()
+	{
+	CMdSOomPlugin* self = new (ELeave) CMdSOomPlugin();
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+void CMdSOomPlugin::ConstructL()
+	{
+	COomMonitorPlugin::ConstructL();
+	
+	User::LeaveIfError( iOomMsgQueue.CreateGlobal(KHarvesterOomQueue, 32) );
+	}
+
+
+void CMdSOomPlugin::FreeRam()
+	{
+	WRITELOG("CMdSOomPlugin::FreeRam() - start");
+	
+	iOomMsgQueue.Send( TMdsOomFreeRam );
+	
+	WRITELOG("CMdSOomPlugin::FreeRam() - end");
+	}
+
+void CMdSOomPlugin::MemoryGood()
+	{
+	WRITELOG("CMdSOomPlugin::MemoryGood - start");
+	
+	iOomMsgQueue.Send( TMdsOomMemoryGood );	
+	
+	WRITELOG("CMdSOomPlugin::MemoryGood - end ");
+	}
+
+void CMdSOomPlugin::ExtensionInterface(TUid aInterfaceId, TAny*& aImplementation)
+	{
+	COomMonitorPlugin::ExtensionInterface(aInterfaceId, aImplementation);
+	}
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mdsoomplugin/src/proxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation proxy.*
+*/
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+
+#include "mdsoomplugin.h"
+
+const TImplementationProxy ImplementationTable[] =
+    {
+    {{0x2001B2C6}, (TProxyNewLPtr)CMdSOomPlugin::NewL}
+    };
+
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy) ;
+    return ImplementationTable;
+    }
+	
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/messageplugin/data/102823c6.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// 102823C6.RSS
+
+#include "registryinfov2.rh"
+
+// Declares info for one test implementation
+RESOURCE REGISTRY_INFO theInfo
+	{
+  // resource_format_version must always be set as follows
+  resource_format_version = RESOURCE_FORMAT_VERSION_2;
+    
+	// UID for the DLL
+	dll_uid = 0x102823C6;
+	// Declare array of interface info
+	interfaces = 
+		{
+		INTERFACE_INFO
+			{
+			// UID of interface that is implemented
+			interface_uid = 0x20007181;
+			implementations = 
+				{
+				// Info for CHarvesterMessagePlugin
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x102823C7;
+					version_no = 1;
+					display_name = "Message monitor plugin";
+					default_data = "";
+					opaque_data = "";
+					rom_only = 0;
+					}
+				};
+			}
+		};
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/messageplugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+messagemonitorplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/messageplugin/group/messagemonitorplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        MessageMonitorPlugin.dll
+TARGETTYPE    PLUGIN
+UID           0x10009D8D 0x102823C6
+
+CAPABILITY 	  CAP_ECOM_PLUGIN 
+VENDORID      VID_DEFAULT
+
+SOURCEPATH    ../src
+SOURCE        messagemonitorplugin.cpp
+SOURCE		  messagescannerao.cpp
+SOURCE        proxy.cpp
+
+USERINCLUDE   ../inc
+USERINCLUDE   ../../inc
+USERINCLUDE   ../../../server/inc
+USERINCLUDE   ../../../../inc
+USERINCLUDE   ../../../common/inc
+
+SYSTEMINCLUDE /epoc32/include/ecom
+
+SOURCEPATH     ../data
+start RESOURCE 102823c6.rss
+target MessageMonitorPlugin.rsc
+end
+
+APP_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       ECom.lib
+
+LIBRARY       MonitorPluginInterface.lib
+LIBRARY       MdEClient.lib
+LIBRARY	      msgs.lib
+LIBRARY       harvesterdata.lib
+LIBRARY         efsrv.lib
+LIBRARY       platformenv.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/messageplugin/inc/messagemonitorplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,130 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#ifndef __MESSAGEMONITORPLUGIN_H__
+#define __MESSAGEMONITORPLUGIN_H__
+
+//  INCLUDES 
+
+#include <e32base.h>
+#include <msvapi.h>
+#include <monitorplugin.h>
+#include "messagescannerao.h"
+
+class CMessageMonitorPlugin : public CMonitorPlugin, public MMsvSessionObserver
+  	{
+	public:
+		/**
+		* NewL
+		* @return
+		*/
+		static CMessageMonitorPlugin* NewL();
+
+		/**
+		* Destructor
+		*/
+		virtual ~CMessageMonitorPlugin();
+		
+		/**
+		* From CMonitorPlugin
+		*/
+		TBool StartMonitoring( MMonitorPluginObserver& aObserver, 
+                               CMdESession* aMdEClient, 
+                               CContextEngine* aCtxEngine,
+                               CHarvesterPluginFactory* aHarvesterPluginFactory );
+	
+		/**
+		* From CMonitorPlugin
+		*/
+		TBool StopMonitoring();
+		
+		/**
+		* From CMonitorPlugin
+		*/		
+		TBool ResumeMonitoring( MMonitorPluginObserver& aObserver, 
+				                CMdESession* aMdEClient, 
+								CContextEngine* aCtxEngine,
+								CHarvesterPluginFactory* aHarvesterPluginFactory );
+		
+		/**
+		* From CMonitorPlugin
+		*/		
+		TBool PauseMonitoring();
+		
+		/**
+		* From MMsvSessionObserver
+		*/
+		virtual void HandleSessionEventL( TMsvSessionEvent aEvent, 
+										  TAny* aArg1, 
+										  TAny* aArg2, 
+										  TAny* aArg3 );
+		
+		/**
+		* Creates a URI for a message.
+		*/
+		static HBufC* CreateUriL( const TUid& aMsgTypeUid, const TMsvId aMsgId );
+		
+		/**
+		 * Method CreateFileNameL.
+		 * Creates file name in variable iFileName.
+		 */
+		void CreateFileNameL(); 
+				
+	private:
+
+		/**
+		* From Constructor
+		*/
+		CMessageMonitorPlugin();
+		
+		/**
+		* 2nd phase construction
+		*/
+		void ConstructL();
+		
+		void HandleMsgMovedL( const TMsvId aFolderId1, 
+							  const TMsvId aFolderId2, 
+							  const CMsvEntrySelection& aSelection );
+
+		void HandleMsgCreatedChangedL( const CMsvEntrySelection& aSelection,
+                                       const TMsvId aFolderId,
+                                       const TMsvSessionEvent aEvent );
+		void HandleMsgDeletedL( const CMsvEntrySelection& aSelection );
+		
+		void RemoveObjectL( const TDesC& aUri );
+
+		TBool IsValidMessageTypeL( const TMsvEntry& aEntry, CMsvSession& aSession );
+		
+		/**
+		 * This method checks if the CRestoreWatcher has created a file in harvester server's
+		 * private directory as a sign of restore and starts message scanner if it finds the file.
+		 */
+		void CheckRestoreL();
+		
+		
+	private:
+		MMonitorPluginObserver* iMonitorPluginObserver;
+		CMsvSession* iMsvSession;			// Session Message server session, own
+		CMdESession* iMdeSession;
+		CMessageScannerAO* iMessageScannerAO;
+		
+		/*iFileName - File used for restore flag.*/
+		TFileName iFileName;
+	};
+
+#endif // __MESSAGEMONITORPLUGIN_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/messageplugin/inc/messagescannerao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,80 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#ifndef MESSAGESCANNER_H_
+#define MESSAGESCANNER_H_
+
+#include <e32property.h>
+#include <mdequery.h>
+
+// FORWARD DECLARATION
+class CMsvSession;
+class CMdESession;
+class CMsvFindOperation;
+class MMonitorPluginObserver;
+
+class TMessage
+	{
+	public:
+		TInt32 iMsvId;
+		TTime iCreationDate;
+		TItemId iMdeId;
+	};
+
+class CMessageScannerAO : public CActive, public MMdEQueryObserver
+	{
+	public:
+		enum TScannerState {
+			EScannerIdle,
+			EScannerRunning,
+			EScannerFinished
+		};
+	
+		static CMessageScannerAO* NewL( CMsvSession* aMsvSession, CMdESession* aMdeSession, 
+				MMonitorPluginObserver* aMonitorPluginObserver );
+		~CMessageScannerAO();
+		void StartL();
+		
+		void HandleQueryNewResults( CMdEQuery& aQuery, TInt aFirstNewItemIndex,
+				TInt aNewItemCount );
+
+		void HandleQueryCompleted( CMdEQuery& aQuery, TInt aError );
+		
+	private:
+		CMessageScannerAO( CMsvSession* aMsvSession, CMdESession* aMdeSession,
+				MMonitorPluginObserver* aMonitorPluginObserver );
+		void ConstructL();
+		void RunL();
+		void DoCancel();
+		TInt RunError( TInt aError );
+		void ScanMessagesL( RArray<TMessage>& aMessageIds );
+		void QueryAllMessagesL();
+		void ProcessMessagesL( CMdEQuery& aQuery, RArray<TMessage>& aMessages );
+		void Unregister();
+		void Cleanup();
+		
+	private:
+		CMsvFindOperation* 	iFindOperation;
+		CMsvSession* 		iMsvSession;
+		CMdESession* 		iMdeSession;
+		CMdEObjectQuery* 	iObjectQuery;
+		MMonitorPluginObserver* iMonitorPluginObserver;
+		RProperty iProperty;
+		TScannerState		iState;
+	};
+
+#endif /*MESSAGESCANNER_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/messageplugin/src/messagemonitorplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,493 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+// INCLUDE FILES
+#include "messagemonitorplugin.h"
+#include "harvesterlog.h"
+#include "mdesession.h"
+#include "clientkeywatcherkeys.h" 
+
+#include <smut.h>
+#include <mmsvattachmentmanager.h>	// MMsvAttachmentManager
+#include <msventry.h>	// CMsvEntry
+#include <msvfind.h>
+#include <msvuids.h>
+#include <mmsconst.h>
+#include <mtclreg.h>
+#include <smsclnt.h>
+#include <driveinfo.h>
+#include <PathInfo.h>
+
+// CONSTANTS
+#ifdef _DEBUG
+_LIT( KMsgMonitorHarvesterMsvPanic, "Message monitor harvester: Message server terminated" );
+#endif
+_LIT( KMsgURI, "%d.MSG" );
+
+const TInt KUriLength = 127;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::NewL
+// -----------------------------------------------------------------------------
+//
+CMessageMonitorPlugin* CMessageMonitorPlugin::NewL()
+	{
+	CMessageMonitorPlugin* self = new ( ELeave ) CMessageMonitorPlugin();
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::~CMessageMonitorPlugin
+// -----------------------------------------------------------------------------
+//
+CMessageMonitorPlugin::~CMessageMonitorPlugin() 
+	{
+	WRITELOG("ENTER ~CMessageMonitorPlugin");
+    delete iMsvSession;
+	WRITELOG("END ~CMessageMonitorPlugin");	
+	}
+
+
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::StartMonitoring
+// -----------------------------------------------------------------------------
+//
+TBool CMessageMonitorPlugin::StartMonitoring( MMonitorPluginObserver& aObserver, 
+											  CMdESession* aMdEClient, 
+											  CContextEngine* /*aCtxEngine*/,
+											  CHarvesterPluginFactory* /*aHarvesterPluginFactory*/ )
+	{
+	WRITELOG("ENTER CMessageMonitorPlugin::StartMonitoring");
+	
+	iMonitorPluginObserver = &aObserver;
+	iMdeSession = aMdEClient;
+	
+	if ( iMsvSession )
+		{
+		delete iMsvSession;
+		iMsvSession = NULL;
+		}
+	TInt error( KErrNone );
+	// Open a new session to the message server
+	TRAP( error, iMsvSession = CMsvSession::OpenSyncL( *this ) );
+	WRITELOG1("Open msgSession error: %d" , error );
+	
+	TRAP_IGNORE( CheckRestoreL() );
+		
+	TBool result = 	error ? EFalse : ETrue ;
+	WRITELOG("END CMessageMonitorPlugin::StartMonitoring");	
+		
+	return result;
+	}
+
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::CreateFileNameL
+// Filename flag can be changed to use cen rep!
+// -----------------------------------------------------------------------------
+//
+void CMessageMonitorPlugin::CreateFileNameL() 
+	{
+	TInt drive ( 0 );
+	User::LeaveIfError( 
+			DriveInfo::GetDefaultDrive( DriveInfo::EDefaultSystem, drive ) );
+
+    RFs fsSession;
+    User::LeaveIfError( fsSession.Connect() );
+  
+    TChar driveLetter;
+    fsSession.DriveToChar( drive, driveLetter );
+	
+    iFileName.Append( driveLetter );
+    iFileName.Append( KRestoreFile );  // result-> C:\\private\\200009F5\\restoredone
+ 
+    fsSession.Close();
+	}
+
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::StopMonitoring
+// -----------------------------------------------------------------------------
+//
+TBool CMessageMonitorPlugin::StopMonitoring()
+	{
+	WRITELOG("ENTER CMessageMonitorPlugin::StopMonitoring");
+	if( iMsvSession )
+		{
+	    delete iMsvSession;  
+		iMsvSession = NULL;
+		}
+	
+	WRITELOG("END CMessageMonitorPlugin::StopMonitoring");	
+	
+	return ETrue;
+	}
+
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::ResumeMonitoring
+// -----------------------------------------------------------------------------
+//
+TBool CMessageMonitorPlugin::ResumeMonitoring( MMonitorPluginObserver& /*aObserver*/, 
+											   CMdESession* /*aMdEClient*/, 
+											   CContextEngine* /*aCtxEngine*/,
+											   CHarvesterPluginFactory* /*aHarvesterPluginFactory*/ )
+	{
+	WRITELOG("ENTER CMessageMonitorPlugin::ResumeMonitoring");
+	WRITELOG("END CMessageMonitorPlugin::ResumeMonitoring");
+	
+	return ETrue;
+	}
+
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::PauseMonitoring
+// -----------------------------------------------------------------------------
+//
+TBool CMessageMonitorPlugin::PauseMonitoring()
+	{
+	WRITELOG("ENTER CMessageMonitorPlugin::PauseMonitoring");	
+	WRITELOG("END CMessageMonitorPlugin::PauseMonitoring");	
+	
+	return ETrue;
+	}
+
+void CMessageMonitorPlugin::CheckRestoreL()
+	{
+	RFs fs;
+	User::LeaveIfError( fs.Connect() );
+	CleanupClosePushL( fs );
+
+	RFile64 file;
+	CleanupClosePushL( file );
+	// only needed information is does file exist
+	TInt fileError = file.Open( fs, iFileName, EFileShareReadersOrWriters );
+	WRITELOG1("CMessageMonitorPlugin::CheckRestoreL - fileError: %d", fileError);
+	User::LeaveIfError( fileError );
+	
+	CleanupStack::PopAndDestroy( &file );
+	CleanupStack::PopAndDestroy( &fs );
+
+   	iMessageScannerAO = CMessageScannerAO::NewL( iMsvSession, iMdeSession, 
+   			iMonitorPluginObserver );
+   	iMessageScannerAO->StartL();
+	}
+
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::CMessageMonitorPlugin
+// -----------------------------------------------------------------------------
+//
+CMessageMonitorPlugin::CMessageMonitorPlugin() : CMonitorPlugin(), 
+												 iMonitorPluginObserver( NULL ),
+												 iMsvSession( NULL ),
+												 iMdeSession( NULL ),
+												 iMessageScannerAO( NULL )
+	{
+	WRITELOG("ENTER CMessageMonitorPlugin::CMessageMonitorPlugin");
+	WRITELOG("END CMessageMonitorPlugin::CMessageMonitorPlugin");		
+	}
+
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CMessageMonitorPlugin::ConstructL() 
+	{
+	WRITELOG("ENTER CMessageMonitorPlugin::ConstructL");
+	
+	CreateFileNameL();
+	
+	WRITELOG("END CMessageMonitorPlugin::ConstructL");
+	}
+	
+	
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::HandleSessionEventL
+// -----------------------------------------------------------------------------
+//
+void CMessageMonitorPlugin::HandleSessionEventL( TMsvSessionEvent aEvent, 
+										  		 TAny* aArg1, 
+										  		 TAny* aArg2, 
+										  		 TAny* aArg3 )
+	{		
+	WRITELOG("ENTER CMessageMonitorPlugin::HandleSessionEventL");
+	WRITELOG1("TMsvSessionEvent aEvent: %d", aEvent );			
+		
+	switch( aEvent )
+		{
+		case EMsvEntriesCreated:
+		case EMsvEntriesChanged:
+			{
+            CMsvEntrySelection* selection =  
+                    		reinterpret_cast<CMsvEntrySelection*> ( aArg1 );
+            TMsvId folderId = *( reinterpret_cast<TMsvId*> ( aArg2 ) );                    
+			HandleMsgCreatedChangedL( *selection, folderId, aEvent );		
+			break;
+			}		
+		case EMsvEntriesDeleted:
+			{
+		    CMsvEntrySelection* selection = 
+                reinterpret_cast<CMsvEntrySelection*> ( aArg1 );
+            HandleMsgDeletedL( *selection );						
+			break;
+			}
+		case EMsvEntriesMoved:
+			{
+			// track move operations
+			// or sent folder
+			// ... extract the useful parameters
+            if( aArg1 && aArg2 && aArg3 )
+                {
+                CMsvEntrySelection* selection = 
+                    reinterpret_cast<CMsvEntrySelection*> ( aArg1 );
+                TMsvId folderId1 = *( reinterpret_cast<TMsvId*> ( aArg2 ) );
+                TMsvId folderId2 = *( reinterpret_cast<TMsvId*> ( aArg3 ) );
+		        HandleMsgMovedL( folderId1, folderId2, *selection );
+                }
+			break;
+			}			
+		case EMsvServerFailedToStart:			
+		case EMsvCloseSession:
+		case EMsvServerTerminated:
+			{
+			__ASSERT_DEBUG( EFalse, User::Panic( KMsgMonitorHarvesterMsvPanic, KErrServerTerminated ));
+			break;				
+			}			
+		case EMsvMtmGroupInstalled:
+		case EMsvMtmGroupDeInstalled:
+		case EMsvGeneralError: // not used after v5
+		case EMsvServerReady:
+		case EMsvCorruptedIndexRebuilt:
+		case EMsvMediaChanged:
+		case EMsvMediaUnavailable:
+		case EMsvMediaAvailable:
+		case EMsvMediaIncorrect:
+		case EMsvCorruptedIndexRebuilding:
+		default:
+			{
+			break;
+			}							
+		}	
+	WRITELOG("END CMessageMonitorPlugin::HandleSessionEventL");	
+		
+	}
+
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::HandleMsgMovedL
+// -----------------------------------------------------------------------------
+//
+void CMessageMonitorPlugin::HandleMsgMovedL( const TMsvId aFolderId1, 
+											 const TMsvId aFolderId2, 
+								   			 const CMsvEntrySelection& aSelection )
+	{
+	
+	
+	
+	WRITELOG("ENTER CMessageMonitorPlugin::HandleMsgMovedL");
+	
+	TInt count( aSelection.Count() );
+	// cycle through every message in the CMsvEntrySelection
+	for ( TInt i=0; i < count; ++i )
+		{
+		TMsvId msgId = aSelection[i];
+		WRITELOG1("msgId: %d", msgId );					
+		
+		TMsvId service = 0;
+        TMsvEntry entry;
+		TInt err = iMsvSession->GetEntry( msgId, service, entry );
+
+        // if we have a message and it has been moved from the outbox to the sent 
+        // items, and it is a valid message
+        if ( ( !err ) &&
+            ( KUidMsvMessageEntry == entry.iType ) &&
+            ( KMsvSentEntryId == aFolderId1 ) &&
+            ( KMsvGlobalOutBoxIndexEntryId == aFolderId2 ) && 
+            ( IsValidMessageTypeL( entry, *iMsvSession ) ) )
+            {            
+            HBufC* uri = CreateUriL( entry.iMtm, msgId );
+            CleanupStack::PushL( uri );
+            CHarvesterData* hd = CHarvesterData::NewL( uri );
+            CleanupStack::Pop( uri );
+            hd->SetEventType( EHarvesterAdd );
+            hd->SetTakeSnapshot( EFalse );
+            hd->SetBinary( EFalse );
+            iMonitorPluginObserver->MonitorEvent( hd );
+            }          
+        }
+	WRITELOG("END CMessageMonitorPlugin::HandleMsgMovedL");	        
+	}
+
+
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::HandleMsgCreatedChangedL
+// -----------------------------------------------------------------------------
+//
+void CMessageMonitorPlugin::HandleMsgCreatedChangedL( const CMsvEntrySelection& aSelection,
+                                          	   		  const TMsvId aFolderId,
+                                          	          const TMsvSessionEvent aEvent )
+	{
+	WRITELOG("ENTER CMessageMonitorPlugin::HandleMsgCreatedChangedL");
+	
+	TInt count( aSelection.Count() );
+	
+    // cycle through every message in the CMsvEntrySelection
+	for ( TInt i=0; i < count; ++i )
+		{
+		// extract the message server entry from the parameters
+		TMsvId msgId = aSelection[i];
+		WRITELOG1("msgId: %d", msgId );					
+		
+        TMsvId service = 0;
+        TMsvEntry entry;
+		TInt err = iMsvSession->GetEntry( msgId, service, entry );
+
+		WRITELOG1("HandleMsgCreatedChangedL error: %d ", err);		
+		
+		THarvesterEventType event = 
+						( aEvent == EMsvEntriesCreated ) || entry.Unread() ? 
+						  	  								 EHarvesterAdd : 
+															 EHarvesterEdit;
+		
+        
+        // ... we only want to process message entries, that are in the inbox
+        // ... and are valid for adding to Mds.
+        if ( ( !err ) && 
+            ( KUidMsvMessageEntry == entry.iType ) && 
+            ( KMsvGlobalInBoxIndexEntryId == aFolderId ) &&
+            ( entry.Visible() && entry.Complete() && !entry.InPreparation() ) &&
+            ( IsValidMessageTypeL( entry, *iMsvSession ) ) )
+            {
+            HBufC* uri = CreateUriL( entry.iMtm, msgId );    
+            CleanupStack::PushL( uri );
+            CHarvesterData* hd = CHarvesterData::NewL( uri );
+            CleanupStack::Pop( uri );
+            hd->SetEventType( event );
+            hd->SetBinary( EFalse );
+            hd->SetTakeSnapshot( EFalse );
+			iMonitorPluginObserver->MonitorEvent( hd );
+            }
+        }
+	WRITELOG("END CMessageMonitorPlugin::HandleMsgCreatedChangedL");	        
+	}
+	
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::HandleMsgDeletedL
+// -----------------------------------------------------------------------------
+//
+void CMessageMonitorPlugin::HandleMsgDeletedL( const CMsvEntrySelection& aSelection )
+	{
+	WRITELOG("ENTER CMessageMonitorPlugin::HandleMsgDeletedL");
+	
+	TInt count( aSelection.Count() );	
+	// cycle through every message in the CMsvEntrySelection
+	for( TInt i = 0; i < count; ++i )
+		{
+		TMsvId msgId = aSelection[i];	
+		WRITELOG1("msgId: %d", msgId );
+		HBufC* uri = CreateUriL( KUidMsgTypeSMS, msgId );
+		CleanupStack::PushL( uri );
+		RemoveObjectL( *uri );
+		CleanupStack::PopAndDestroy( uri );
+		}
+	WRITELOG("END CMessageMonitorPlugin::HandleMsgDeletedL");	
+	}	
+
+// ---------------------------------------------------------------------------
+// CHarvesterMessagePluginAO::RemoveObjectL
+// ---------------------------------------------------------------------------
+//
+void CMessageMonitorPlugin::RemoveObjectL( const TDesC& aUri )
+	{
+    WRITELOG( "CMessageMonitorPlugin::RemoveObjectL enter" );
+	CMdEObject* mdeObject = iMdeSession->GetObjectL( aUri );
+
+    // check if in mde
+    if ( mdeObject )
+    	{
+    	TItemId objectId = mdeObject->Id();
+	    delete mdeObject;
+	    mdeObject = NULL;
+	    
+		TTime time( 0 );
+		CMdENamespaceDef& nsDef = iMdeSession->GetDefaultNamespaceDefL();
+		CMdEEventDef& eventDef = nsDef.GetEventDefL( MdeConstants::Events::KDeleted );
+	
+		iMdeSession->RemoveObjectL( aUri, &nsDef );
+		WRITELOG1( "aUri: %S", &aUri );							
+		time.UniversalTime();
+		CMdEEvent* event =  iMdeSession->NewEventL( eventDef, objectId, time,NULL,NULL );
+		
+		iMdeSession->AddEventL( *event );
+		delete event;
+    	}
+    
+    WRITELOG( "CMessageMonitorPlugin::RemoveObjectL return" );
+	}
+
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::IsValidMessageTypeL
+// -----------------------------------------------------------------------------
+//	
+TBool CMessageMonitorPlugin::IsValidMessageTypeL( const TMsvEntry& aEntry,
+                                                  CMsvSession& /*aSession*/)
+	{
+	WRITELOG("ENTER CMessageMonitorPlugin::IsValidMessageTypeL");
+	
+    TBool isValidMsg( EFalse );
+
+    // Mms message
+	if ( aEntry.iMtm.iUid == KUidMsgTypeMultimedia.iUid )
+        {	
+        isValidMsg = ETrue;
+        }
+    // check if this is a BIO message, if so exclude it from Hoover
+    else if ( aEntry.iBioType != 0 )
+        {
+        isValidMsg = EFalse;
+        }
+    // else if we have a normal text based SMS it is valid    
+	else if ( aEntry.iMtm.iUid == KUidMsgTypeSMS.iUid )
+		{
+		isValidMsg = ETrue;
+		}
+	WRITELOG1( "isValidMsg: %d" , isValidMsg );					
+		
+	WRITELOG("END CMessageMonitorPlugin::IsValidMessageTypeL");		
+        
+	return isValidMsg;
+	}	
+	
+// -----------------------------------------------------------------------------
+// CMessageMonitorPlugin::CreateUriL
+// -----------------------------------------------------------------------------
+//	
+HBufC* CMessageMonitorPlugin::CreateUriL( const TUid& /*aMsgTypeUid*/, const TMsvId aMsgId )
+	{
+	WRITELOG("ENTER CMessageMonitorPlugin::CreateUriL");
+	
+    HBufC* uri = HBufC::NewL( KUriLength );
+	TPtr ptrUri = uri->Des();
+	ptrUri.Format( KMsgURI, aMsgId );	
+	
+	WRITELOG("END CMessageMonitorPlugin::CreateUriL");	
+		
+	return uri;
+	}
+
+// End Of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/messageplugin/src/messagescannerao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,320 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#include <msvstd.h>
+#include <msvfind.h>
+#include <msvapi.h>
+#include <msvids.h>
+#include "mdesession.h"
+#include "mdeconstants.h"
+#include "mdenamespacedef.h"
+#include "messagescannerao.h"
+#include "harvesterlog.h"
+#include "messagemonitorplugin.h"
+#include "clientkeywatcherkeys.h"
+
+CMessageScannerAO* CMessageScannerAO::NewL( CMsvSession* aMsvSession, 
+		CMdESession* aMdeSession,
+		MMonitorPluginObserver* aMonitorPluginObserver )
+	{
+	CMessageScannerAO* self = new (ELeave) CMessageScannerAO( 
+			aMsvSession, aMdeSession, aMonitorPluginObserver );
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+CMessageScannerAO::CMessageScannerAO( CMsvSession* aMsvSession, 
+		CMdESession* aMdeSession, 
+		MMonitorPluginObserver* aMonitorPluginObserver ) :
+		CActive( CActive::EPriorityStandard ),
+		iFindOperation( NULL ), iObjectQuery( NULL )
+	{
+	CActiveScheduler::Add( this );
+	iMsvSession = aMsvSession;
+	iMdeSession = aMdeSession;
+	iMonitorPluginObserver = aMonitorPluginObserver;
+	iState = EScannerIdle;
+	}
+
+CMessageScannerAO::~CMessageScannerAO()
+	{
+	Cancel();
+	Cleanup();
+	}
+
+void CMessageScannerAO::StartL()
+	{
+	WRITELOG("CMessageScannerAO::Start()");
+	_LIT( KEmpty, "" );
+	iFindOperation = CMsvFindOperation::FindInChildrenL( *iMsvSession, KEmpty, 
+			KMsvRootIndexEntryId, KMsvMessagePartNone, iStatus );
+	SetActive();
+	iState = EScannerRunning;
+	WRITELOG("CMessageScannerAO::Start() - ends");
+	}
+		
+void CMessageScannerAO::ConstructL()
+	{
+	WRITELOG("CMessageScannerAO::ConstructL()");
+	User::LeaveIfError( iProperty.Attach( KPSRestoreWatcherCategory,
+			KPSRestoreWatcherClientsKey, EOwnerThread ) );
+	
+	TInt registeredClients = 0;
+	iProperty.Get( registeredClients );
+	TInt error = iProperty.Set( registeredClients + 1 );
+	
+	WRITELOG1("CMessageScannerAO::ConstructL() - error: %d", error);
+	}
+
+void CMessageScannerAO::RunL()
+	{
+	WRITELOG("CMessageScannerAO::RunL()");
+	if ( iStatus.Int() != KErrNone )
+		{
+#ifdef _DEBUG
+		WRITELOG1("CMessageScannerAO::RunL() . error %d", iStatus.Int());
+#endif
+		return;
+		}
+	
+	switch ( iState )
+		{
+		case EScannerRunning:
+			{
+			QueryAllMessagesL();
+			break;
+			}
+		case EScannerFinished:
+			{
+			Cleanup();
+			break;
+			}
+		}
+	}
+
+void CMessageScannerAO::DoCancel()
+	{
+	iFindOperation->Cancel();
+	iProperty.Cancel();
+	}
+
+#ifdef _DEBUG
+TInt CMessageScannerAO::RunError( TInt aError )
+#else
+TInt CMessageScannerAO::RunError( TInt /*aError*/ )
+#endif
+	{
+	WRITELOG1( "CMessageScannerAO::RunError - error: %d", aError );
+	return KErrNone;
+	}
+
+void CMessageScannerAO::QueryAllMessagesL()
+	{
+	WRITELOG("CMessageScannerAO::QueryAllMessagesL()");
+	CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+	CMdEObjectDef& messageDef = namespaceDef.GetObjectDefL( MdeConstants::Message::KMessageObject );
+	
+	iObjectQuery = iMdeSession->NewObjectQueryL( namespaceDef, messageDef, this );
+	iObjectQuery->SetResultMode( EQueryResultModeItem );
+	
+	iObjectQuery->FindL();
+	WRITELOG("CMessageScannerAO::QueryAllMessagesL() - ends");
+	}
+
+void CMessageScannerAO::HandleQueryNewResults( CMdEQuery& /*aQuery*/, TInt /*aFirstNewItemIndex*/,
+		TInt /*aNewItemCount*/ )
+	{
+	}
+
+void CMessageScannerAO::HandleQueryCompleted( CMdEQuery& aQuery, TInt /*aError*/ )
+	{
+	WRITELOG("CMessageScannerAO::HandleQueryCompleted()");
+	RArray<TMessage> messages;
+	TInt error = KErrNone;
+	
+	if ( aQuery.Count() > 0 )
+		{
+#ifdef _DEBUG
+		WRITELOG1("CMessageScannerAO::HandleQueryCompleted() - aQuery count %d", aQuery.Count());
+#endif
+		TRAP( error, ProcessMessagesL( aQuery, messages ) );
+		}
+
+	if ( error == KErrNone )
+		{
+		TRAP_IGNORE( ScanMessagesL( messages ) );
+		}
+	
+	messages.Close();
+	Unregister();
+	iState = EScannerFinished;
+	
+	SetActive();
+	TRequestStatus* pStatus = &iStatus;
+    User::RequestComplete( pStatus, KErrNone );
+	}
+
+void CMessageScannerAO::ProcessMessagesL( CMdEQuery& aQuery, RArray<TMessage>& aMessages )
+	{
+	_LIT( KPeriod, "." );
+
+	CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+	CMdEObjectDef& messageDef = namespaceDef.GetObjectDefL( MdeConstants::Message::KMessageObject );
+	CMdEPropertyDef& creationDateDef = messageDef.GetPropertyDefL( 
+			MdeConstants::Object::KCreationDateProperty );
+
+	TInt count = aQuery.Count();
+	
+	for (TInt i = 0; i < count; i++ )
+		{
+		CMdEObject& object = static_cast<CMdEObject&>( aQuery.ResultItem( i ) );
+		TInt index = object.Uri().Find( KPeriod );
+		if ( index != KErrNotFound )
+			{
+			TLex16 lex( object.Uri().Left( index ) );
+			TMessage message;
+			message.iMdeId = object.Id();
+
+			CMdEProperty* creationDateProp = NULL;
+			object.Property( creationDateDef, creationDateProp, 0 );
+			message.iCreationDate = creationDateProp->TimeValueL();
+
+			TInt error = lex.Val( message.iMsvId );
+			if ( error == KErrNone )
+				{
+				aMessages.Append( message );
+				}
+			}
+		}
+	}
+
+void CMessageScannerAO::ScanMessagesL( RArray<TMessage>& aMessages )
+	{
+	WRITELOG("CMessageScannerAO::ScanMessagesL()");
+	const CMsvFindResultSelection& findResults = iFindOperation->GetFindResult();
+	CMdENamespaceDef& defaultNamespace = iMdeSession->GetDefaultNamespaceDefL();
+	TInt msvCount = findResults.Count();
+	
+	for ( TInt i = 0; i < msvCount; i++ )
+		{
+		WRITELOG1("CMessageScannerAO::ScanMessagesL() - MSV item %d", i);
+		TBool idMatched = EFalse;
+		for ( TInt j = 0; j < aMessages.Count(); j++ )
+			{
+			WRITELOG1("CMessageScannerAO::ScanMessagesL() - MDE item %d", j);
+			if ( findResults[i].iId == aMessages[j].iMsvId )
+				{
+				WRITELOG("CMessageScannerAO::ScanMessagesL() - id matches");
+				idMatched = ETrue;
+				CMsvEntry* e = iMsvSession->GetEntryL( findResults[i].iId );
+				if ( !e )
+					{
+					WRITELOG("CMessageScannerAO::ScanMessagesL() - message entry is NULL!?");
+					continue;
+					}
+				
+				CleanupStack::PushL( e );
+				const TMsvEntry& entry = e->Entry();
+				WRITELOG("CMessageScannerAO::ScanMessagesL() - comparing dates");
+				if ( entry.iDate != aMessages[j].iCreationDate )
+					{
+					WRITELOG("CMessageScannerAO::ScanMessagesL() - creation dates don't match");
+					// Harvest the message with EHarvesterEdit event type.
+					HBufC* uri = CMessageMonitorPlugin::CreateUriL( entry.iMtm, entry.Id() );
+					CleanupStack::PushL( uri );
+					CHarvesterData* hd = CHarvesterData::NewL( uri );
+					CleanupStack::Pop( uri );
+					hd->SetEventType( EHarvesterEdit );
+					hd->SetTakeSnapshot( EFalse );
+					hd->SetBinary( EFalse );
+					iMonitorPluginObserver->MonitorEvent( hd );
+					}
+				
+				CleanupStack::PopAndDestroy( e );
+				aMessages.Remove( j );
+				j--;
+				break;
+				}
+			}
+		
+		if ( !idMatched )
+			{
+			WRITELOG("CMessageScannerAO::ScanMessagesL() - harvesting new message");
+			// Harvest the message as new message.
+			CMsvEntry* e = iMsvSession->GetEntryL( findResults[i].iId );
+			if ( !e )
+				{
+				WRITELOG("CMessageScannerAO::ScanMessagesL() - message entry is NULL!?");
+				continue;
+				}
+			
+			CleanupStack::PushL( e );
+			const TMsvEntry& entry = e->Entry();
+			HBufC* uri = CMessageMonitorPlugin::CreateUriL( entry.iMtm, entry.Id() );
+			CleanupStack::PushL( uri );
+			CHarvesterData* hd = CHarvesterData::NewL( uri );
+			CleanupStack::Pop( uri );
+			hd->SetEventType( EHarvesterAdd );
+			hd->SetTakeSnapshot( EFalse );
+			hd->SetBinary( EFalse );
+			iMonitorPluginObserver->MonitorEvent( hd );
+			
+			CleanupStack::PopAndDestroy( e );
+			}
+		}
+	
+	// Remove extra messages in MdS db.
+	if ( aMessages.Count() > 0 )
+		{
+		WRITELOG1("CMessageScannerAO::ScanMessagesL() - removing extra messages from mde (%d)", 
+				aMessages.Count() );
+		RArray<TItemId> extraMessages;
+		CleanupClosePushL( extraMessages );
+		
+		for ( TInt i = 0; i < aMessages.Count(); i++ )
+			{
+			extraMessages.Append( aMessages[i].iMdeId );
+			}
+		
+		RArray<TItemId> results;
+		CleanupClosePushL( results );
+		iMdeSession->RemoveObjectsL( extraMessages, results, &defaultNamespace );
+		CleanupStack::PopAndDestroy( 2 ); // extramessages, results
+		}
+	}
+
+void CMessageScannerAO::Unregister()
+	{
+	TInt registeredClients = 0;
+	iProperty.Get( registeredClients );
+	WRITELOG1("CMessageScannerAO::Unregister() - registered clients: %d", registeredClients);
+	if ( registeredClients > 0 )
+		{
+		iProperty.Set( registeredClients - 1 );
+		}
+	}
+
+void CMessageScannerAO::Cleanup()
+	{
+	iProperty.Close();
+	delete iFindOperation;
+	iFindOperation = NULL;
+	delete iObjectQuery;
+	iObjectQuery = NULL;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/messageplugin/src/proxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include "messagemonitorplugin.h"
+
+// Map the interface UIDs to implementation factory functions
+const TImplementationProxy ImplementationTable[] = 
+	{
+		{ { 0x102823C7 },	( TProxyNewLPtr )CMessageMonitorPlugin::NewL }
+	};
+
+// Exported proxy for instantiation method resolution
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+	{
+	aTableCount = sizeof( ImplementationTable ) / sizeof( TImplementationProxy );
+	return ImplementationTable;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/data/20007183.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// 20007183.RSS
+
+#include "registryinfov2.rh"
+
+// Declares info for one test implementation
+RESOURCE REGISTRY_INFO theInfo
+	{    
+  // resource_format_version must always be set as follows
+  resource_format_version = RESOURCE_FORMAT_VERSION_2;
+  
+	// UID for the DLL
+	dll_uid = 0x20007183;
+	// Declare array of interface info
+	interfaces = 
+		{
+		INTERFACE_INFO
+			{
+			// UID of interface that is implemented
+			interface_uid = 0x20007181;
+			implementations = 
+				{
+				// Info for CHarvesterVideoPlugin
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x20007187;
+					version_no = 1;
+					display_name = "MMC monitor plugin";
+					default_data = "";
+					opaque_data = "";
+					rom_only = 0;
+					}
+				};
+			}
+		};
+	}
+
Binary file harvester/monitorplugins/mmcplugin/data/20007183.txt has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+../data/20007183.txt /epoc32/data/z/private/10202BE9/20007183.txt
+../data/20007183.txt /epoc32/WINSCW/C/private/10202BE9/20007183.txt
+
+PRJ_MMPFILES
+mmcmonitorplugin.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/group/mmcmonitorplugin.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,63 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        mmcmonitorplugin.dll
+TARGETTYPE    PLUGIN
+UID           0x10009D8D 0x20007183
+
+CAPABILITY 	  CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+start RESOURCE ../data/20007183.rss
+target mmcmonitorplugin.rsc
+end
+
+SYSTEMINCLUDE /epoc32/include/ecom
+
+USERINCLUDE   ../inc
+USERINCLUDE   ../../inc
+USERINCLUDE   ../../../../inc
+USERINCLUDE   ../../../common/inc
+
+SOURCEPATH    ../src
+SOURCE        mmcmonitorplugin.cpp
+SOURCE        proxy.cpp
+SOURCE        mmcmonitorao.cpp
+SOURCE        mmcmounttaskao.cpp
+SOURCE        mmcusbao.cpp
+SOURCE        mmcfilelist.cpp
+SOURCE        mmcscannerao.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       PlatformEnv.lib
+LIBRARY       euser.lib
+LIBRARY       efsrv.lib
+LIBRARY       bafl.lib
+LIBRARY       monitorplugininterface.lib
+LIBRARY       mdeclient.lib
+LIBRARY	      harvesterdata.lib
+LIBRARY       harvestercommon.lib
+LIBRARY       centralrepository.lib
+
+OPTION ARMCC -O3 -OTime
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/inc/mmcfilelist.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#ifndef __MMCFILELIST_H__
+#define __MMCFILELIST_H__
+
+
+#include <e32base.h>
+#include <f32file.h>
+#include "harvestermediaidutil.h"
+
+// FORWARD DECLARATIONS
+class CHarvesterEventManager;
+class CPlaceholderData;
+class CMdEHarvesterSession;
+class CHarvesterPluginFactory;
+
+class CMmcFileList : public CBase
+{
+public:
+
+	static CMmcFileList* NewL();	
+	virtual ~CMmcFileList();
+	
+private:	
+	CMmcFileList();
+	void ConstructL();
+	
+	static TBool IsDescInArray(const TPtrC& aSearch, const RPointerArray<HBufC>& aArray);
+	
+public:	
+	void BuildFileListL(RFs& aFs, const TDesC& aDrivePath, 
+			RPointerArray<CPlaceholderData>& aEntryArray );
+	void HandleFileEntryL( CMdEHarvesterSession& aMdeSession,
+			RPointerArray<CPlaceholderData>& aEntryArray,
+			RPointerArray<CPlaceholderData>& aHarvestEntryArray,
+			TUint32 aMediaID,
+			CHarvesterPluginFactory* aPluginFactory );
+
+private:
+	CHarvesterEventManager* iHem;
+    // not own
+    CHarvesterMediaIdUtil* iMediaIdUtil;
+};
+
+#endif /*MMCFILELIST_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/inc/mmcmonitorao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,165 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors MMC insertions and removals.*
+*/
+
+
+#ifndef __MMCMONITORAO_H__
+#define __MMCMONITORAO_H__
+
+#include <e32base.h>
+#include <f32file.h>
+#include "mdscommoninternal.h"
+
+enum TMMCEventType
+    {
+    EMounted,
+    EDismounted,
+    EFormatted
+    };
+
+class MMMCMonitorObserver
+    {
+    public:
+        /**
+        * A pure virtual method to notify about any MMC insertions and removals.
+        *
+        * @param aDriveChar  A drive char of MMC which was inserted or removed.
+        * @param aEventType  EMounted if MMC is inserted, EDismounted if it is removed.
+        */
+        virtual void MountEvent( TChar aDriveChar,
+        	TUint32 aMediaID, TMMCEventType aEventType ) = 0;
+    };
+
+class CMMCMonitorAO : public CActive
+    {
+    public:
+        
+        /**
+        * Creates and constructs a new instance of CMMCMonitorAO.
+        *
+        * @return A pointer to the new instance of CMMCMonitorAO
+        */
+        static CMMCMonitorAO* NewL();
+        
+        /**
+        * Destructor
+        */
+        virtual ~CMMCMonitorAO();
+        
+        /**
+        * Starts monitoring the MMC insertions and removals.
+        *
+        * @param aObserver  Both events are notified via the aObserver.
+        * @return ETrue if success, EFalse if not
+        */
+        TBool StartMonitoring( MMMCMonitorObserver& aObserver, RArray<TMdEMediaInfo>& aMedias );
+        
+        /**
+        * Stops monitoring.
+        *
+        * @return ETrue if success, EFalse if not
+        */
+        TBool StopMonitoring();
+        
+        /**
+        * Resumes paused monitoring.
+        *
+        * @return ETrue if success, EFalse if not
+        */
+        TBool Resume();
+        
+        /**
+        * Pauses monitoring.
+        *
+        * @return ETrue if success, EFalse if not
+        */
+        TBool Pause();
+        
+        /**
+        * Inherited from CActive. This method will be called on file server notifying.
+        */
+        void RunL();
+        
+        /**
+        * Handles a leave occurring in the request completion event handler RunL().
+        *
+        * @param aError  An error code.
+        * @return An error code.
+        */
+        TInt RunError( TInt aError );
+        
+        /**
+        * Cancels file server notifying. Inherited from CActive.
+        */
+        void DoCancel();
+        
+    private:
+        
+        /**
+        * C++ constructor - not exported;
+        * implicitly called from NewL()
+        */
+        CMMCMonitorAO();
+        
+        /**
+        * 2nd phase construction, called by NewL()
+        */
+        void ConstructL();
+        
+        /**
+        * Starts file server to notify us about MMC insertions and removals.
+        */
+        void StartNotify();
+        
+        /**
+        * Makes a list of all removable medias which is present.
+        */
+        void BuildDriveList();
+        
+        /**
+        * Compares previous and present drive list. Notify an observer about any differences in lists.
+        */
+        void CompareDriveLists();
+        
+#ifdef _DEBUG
+    	void PrintAllLists();
+#endif
+    
+        
+    private:
+        /**
+        * An observer.
+        */
+        MMMCMonitorObserver* iObserver;
+        
+        /**
+        * A file server.
+        */
+        RFs iFs;
+        
+        /**
+        * A present drive list.
+        */
+        TDriveList iDriveList;
+        
+        /**
+        * A previous drive list.
+        */
+        TDriveList iPreviousDriveList;
+        
+        TUint32 iMediaIdList[KMaxDrives];
+    };
+
+#endif // __MMCMONITORAO_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/inc/mmcmonitorplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,144 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors MMC insertions and removals.*
+*/
+
+#ifndef __MMCMONITORPLUGIN_H__
+#define __MMCMONITORPLUGIN_H__
+
+#include <e32base.h>
+
+#include "mdeharvestersession.h"
+#include "mdeobject.h"
+#include "monitorplugin.h"
+#include "mmcmounttaskao.h"
+#include "mmcusbao.h"
+#include "mmcscannerao.h"
+
+class CMMCMonitorPlugin : public CMonitorPlugin, public MMMCMonitorObserver
+  	{
+	public:
+		/**
+		* Creates and constructs a new instance of CMMCMonitorPlugin.
+		*
+		* @return A pointer to the new instance of CMMCMonitorPlugin.
+		*/
+		static CMMCMonitorPlugin* NewL();
+		
+		/**
+		* Destructor
+		*/
+		virtual ~CMMCMonitorPlugin();
+				
+		/**
+		* 
+		*
+		* @param aObserver  All events are notified via the aObserver.
+		* @param aMdEClient  A pointer to MdE client.
+		* @param aCtxEngine  A pointer to context engine.
+		* @param aPluginFactory  A pointer to harvester plugin factory.
+		* @return ETrue if success, EFalse if not.
+		*/
+		TBool StartMonitoring( MMonitorPluginObserver& aObserver,
+            CMdESession* aMdEClient, CContextEngine* aCtxEngine,
+            CHarvesterPluginFactory* aHarvesterPluginFactory );
+		
+		/**
+		* Stops the monitoring.
+		*
+		* @return ETrue if success, EFalse if not.
+		*/
+		TBool StopMonitoring();
+		
+		/**
+		* Resumes paused monitoring.
+		*
+		* @param aObserver  All events are notified via the aObserver.
+		* @param aMdEClient  A pointer to MdE client.
+		* @param aCtxEngine  A pointer to context engine.
+		* @param aPluginFactory  A pointer to harvester plugin factory.
+		* @return ETrue if success, EFalse if not.
+		*/
+		TBool ResumeMonitoring( MMonitorPluginObserver& aObserver,
+            CMdESession* aMdEClient, CContextEngine* aCtxEngine,
+            CHarvesterPluginFactory* aHarvesterPluginFactory );
+		
+		/**
+		* Pauses the monitoring.
+		*
+		* @return ETrue if success, EFalse if not.
+		*/
+		TBool PauseMonitoring();
+		
+		/**
+		* Inherited from MMMCMonitorObserver. Will be called by CMMCMonitorAO when any MMC is inserted
+		* or removed.
+		*
+		* @param aDriveChar  The drive which is inserted or removed.
+		* @param aEventType  EMounted if media is inserted, EDismounted if media is removed.
+		*/
+		void MountEvent( TChar aDriveChar, TUint32 aMediaID, TMMCEventType aEventType );
+		
+	private:
+		
+		/**
+		* C++ constructor - not exported;
+		* implicitly called from NewL()
+		*/
+		CMMCMonitorPlugin();
+		
+		/**
+		* 2nd phase construction, called by NewL().
+		*/
+		void ConstructL();
+		
+		/**
+		* Creates and adds a file monitor for a specified drive.
+		*
+		* @param aDrive  A drive for file monitor.
+		*/
+		void AddNotificationPathL( TChar aDrive );
+		
+		/**
+		* Starts monitor all MMCs in the device.
+		*/
+		void StartMonitoringAllMMCsL( RArray<TMdEMediaInfo>& aMedias );
+		
+	private: // data
+		/**
+		* An observer class to notify about file creations, modifications and deletions in any MMCs.
+		*/
+		MMonitorPluginObserver* iObserver;
+		
+		/**
+		* A pointer to MMC monitor which observes any MMCs insertions and removals.
+		*/
+		CMMCMonitorAO* iMMCMonitor;
+		
+		/**
+		* A pointer to MdE client.
+		*/
+		CMdEHarvesterSession* iMdEClient;
+		
+		CMMCMountTaskAO* iMountTask;
+		
+		CMMCUsbAO* iUsbMonitor;
+		
+		CMmcScannerAO* iMmcScanner;
+		
+		CMmcScannerAO* iHddScanner;
+
+	};
+
+#endif // __MMCMONITORPLUGIN_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/inc/mmcmounttaskao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Handles mount tasks*
+*/
+
+#ifndef __MMCMOUNTTASKAO_H__
+#define __MMCMOUNTTASKAO_H__
+
+#include <e32base.h>
+#include <e32msgqueue.h>
+#include <f32file.h>
+
+#include "monitorplugin.h"
+#include "mdeharvestersession.h"
+#include "mmcfilelist.h"
+#include "harvestereventmanager.h"
+
+class CHarvesterPluginFactory;
+
+class CMMCMountTaskAO : public CActive
+  	{
+	public:
+		enum TRequest
+			{
+			ERequestStartTask,
+			ERequestMount,
+			ERequestUnmount,
+			ERequestFormat,
+			ERequestHandleFileEntry,
+			ERequestHandleReharvest,
+			ERequestCleanup,
+			ERequestIdle
+			};
+
+		static CMMCMountTaskAO* NewL();	
+		virtual ~CMMCMountTaskAO();
+		
+		void StartMount( TMountData& aMountData );
+		void StartUnmount( TMountData& aMountData );
+		void SetMonitorObserver( MMonitorPluginObserver& aObserver );
+		void SetMdeSession( CMdEHarvesterSession* aSession );
+		void SetHarvesterPluginFactory( CHarvesterPluginFactory* aPluginFactory );
+		
+		/**
+		 * Returns internal hard drive's media id if the device has one. 0 if not or drive is not present
+		 */
+		TUint32 GetInternalDriveMediaId();
+		
+        void SetCachingStatus( TBool aCachingStatus );
+        
+	protected:
+
+		void RunL();
+		TInt RunError( TInt aError );
+		void DoCancel();
+		void SetNextRequest( TRequest aRequest );
+		
+		void Initialize();
+		void Deinitialize();
+		void SetNotPresentToMDE();
+		void HandleReharvestL( RPointerArray<CPlaceholderData>& aArray );
+		void RemoveNotPresentFromMDE();
+		void StartNotifyL();
+		void StopNotifyL();
+		
+	private:
+	
+		CMMCMountTaskAO();		
+		void ConstructL();
+				
+	private:
+		
+		RFs iFs;
+		TRequest iNextRequest;
+		TMountData* iMountData;
+		RPointerArray<TMountData> iMountDataQueue;
+		RPointerArray<CPlaceholderData> iEntryArray;
+		RPointerArray<CPlaceholderData> iHarvestEntryArray;
+		MMonitorPluginObserver* iObserver;
+		CMdEHarvesterSession* iMdeSession;
+		CHarvesterPluginFactory* iHarvesterPluginFactory;
+		CMmcFileList* iMmcFileList;
+		CHarvesterEventManager* iHEM;
+        TBool iCacheEvents;
+		
+	};
+
+#endif // __MMCMOUNTTASKAO_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/inc/mmcscannerao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,101 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Scans MMC after phone reboot for file changes*
+*/
+
+#ifndef CMMCSCANNERAO_H
+#define CMMCSCANNERAO_H
+
+#include <e32base.h>	// For CActive, link against: euser.lib
+
+#include <e32std.h>		// For RTimer, link against: euser.lib
+#include "mdeharvestersession.h"
+#include "mmcfilelist.h"
+
+// FORWARD DECLARATION
+class MMonitorPluginObserver;
+
+class CMmcScannerAO : public CTimer 
+	{
+public:
+	// Cancel and destroy
+	~CMmcScannerAO();
+
+	// Two-phased constructor.
+	static CMmcScannerAO* NewL( TUint32 aMediaId, CMdEHarvesterSession* aMdEClient,
+			MMonitorPluginObserver* aObserver, CHarvesterPluginFactory* aHarvesterPluginFactory,
+			CActive::TPriority aPriority, TBool aAlreadyWaited );
+
+public:
+
+private:
+	// C++ constructor
+	CMmcScannerAO( TUint32 aMediaId, CMdEHarvesterSession* aMdEClient, 
+			MMonitorPluginObserver* aObserver, CHarvesterPluginFactory* aHarvesterPluginFactory,
+			CActive::TPriority aPriority );
+
+	// Second-phase constructor
+	void ConstructL( TBool aAlreadyWaited );
+
+private:
+	enum TCMmcScannerAOState
+		{
+		EUninitialized, // Uninitialized
+		EReadFiles,
+		EProcessFiles,
+		EHarvestFiles,
+		ERemoveNPFiles,
+		EDone,
+		EError // Error condition
+		};
+
+private:
+	// From CActive
+	// Handle completion
+	void RunL();
+
+	// Override to handle leaves from RunL(). Default implementation causes
+	// the active scheduler to panic.
+	TInt RunError( TInt aError );
+	
+	void HandleReharvestL();
+	
+	void SetState( TCMmcScannerAOState aState );		
+
+private:
+	TInt iState; // State of the active object
+	
+	TUint32 iMediaId;
+	
+	// Not owned
+	CMdEHarvesterSession* iMdEClient;
+	
+	RFs iFs;
+	
+	TBuf<2> iDrive;
+	
+	CMmcFileList* iMmcFileList;
+	
+	// Not owned
+	CHarvesterPluginFactory* iHarvesterPluginFactory;
+	
+	RPointerArray<CPlaceholderData> iEntryArray;
+	RPointerArray<CPlaceholderData> iHarvestEntryArray;
+	
+	// Not owned
+	MMonitorPluginObserver* iObserver;
+	};
+
+#endif // CMMCSCANNERAO_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/inc/mmcusbao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,64 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors Usb insertions and removals.*
+*/
+
+
+#ifndef __MMCUSBAO_H__
+#define __MMCUSBAO_H__
+
+#include <e32base.h>
+#include <f32file.h>
+#include <e32property.h>
+
+#include "mmcmonitorao.h"
+
+class CMMCUsbAO : public CActive
+    {
+    public:
+        
+        static CMMCUsbAO* NewL();
+        virtual ~CMMCUsbAO();
+        
+        TBool StartMonitoring( MMMCMonitorObserver& aObserver );
+        TBool StopMonitoring();
+        TBool Resume();
+        TBool Pause();
+        
+        void RunL();
+        TInt RunError( TInt aError );
+        void DoCancel();
+        
+    private:
+        
+        CMMCUsbAO();
+        void ConstructL();
+
+        void StartNotify();
+        TUint32 MediaID( TInt aDrive );
+        
+#ifdef _DEBUG
+        void PrintDriveStatus( TInt aStatus );
+#endif
+        
+    private:
+
+        MMMCMonitorObserver* iObserver;
+        RFs iFs;
+        RProperty iDriveState;
+        TInt iDrive;
+        TBool iMassStorageMode;
+    };
+
+#endif // __MMCUSBAO_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/src/mmcfilelist.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,282 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include <driveinfo.h>
+#include <e32msgqueue.h>
+
+#include "mmcfilelist.h"
+#include "mmcmounttaskao.h"
+#include "harvesterlog.h"
+#include "mdsfileserverpluginclient.h"
+#include "mdeharvestersession.h"
+#include "mdsutils.h"
+#include "fsutil.h"
+#include "harvestercenreputil.h"
+#include "harvestereventmanager.h"
+#include <placeholderdata.h>
+#include <harvesterdata.h>
+#include "harvesterpluginfactory.h"
+
+_LIT( KBackslash, "\\");
+
+const TInt KEntryBufferSize = 100;
+
+CMmcFileList::CMmcFileList() : iHem( NULL ), iMediaIdUtil( NULL )
+	{
+	}
+
+CMmcFileList* CMmcFileList::NewL()
+	{
+	CMmcFileList* self = new ( ELeave ) CMmcFileList();
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+void CMmcFileList::ConstructL()
+	{
+	iHem = CHarvesterEventManager::GetInstanceL();
+	iMediaIdUtil = &RMediaIdUtil::GetInstanceL();
+	}
+
+CMmcFileList::~CMmcFileList()
+	{
+	if( iHem )
+		{
+		iHem->ReleaseInstance();
+		}
+	RMediaIdUtil::ReleaseInstance();
+	}
+
+TBool CMmcFileList::IsDescInArray(const TPtrC& aSearch, const RPointerArray<HBufC>& aArray)
+	{
+	const TInt count = aArray.Count();
+	
+	for( TInt i = 0; i < count; i++ )
+		{
+		TInt result = MdsUtils::Compare( aSearch, aArray[i]->Des() );
+		
+		if( result == 0 )
+			{
+			return ETrue;
+			}
+		}
+
+	return EFalse;
+	}
+
+void CMmcFileList::BuildFileListL( RFs& aFs, const TDesC& aDrivePath, 
+		RPointerArray<CPlaceholderData>& aEntryArray )
+	{
+	WRITELOG( "CMmcFileList::BuildFileListL - start" );
+	CDesCArrayFlat* path = new(ELeave) CDesCArrayFlat( 8 );
+	CleanupStack::PushL( path );
+	TFileName firstPath;
+	firstPath.Copy( aDrivePath );
+	firstPath.Append( KBackslash );
+	path->AppendL( firstPath );
+
+	TUint32 mediaId( 0 );
+	iMediaIdUtil->GetMediaId( aDrivePath, mediaId );
+	
+	WRITELOG1( "CMmcFileList::BuildFileListL - mediaId: %d", mediaId );
+	
+	RPointerArray<HBufC> ignorePaths;
+	TCleanupItem cleanupItem( MdsUtils::CleanupPtrArray<HBufC>, &ignorePaths );
+    CleanupStack::PushL( cleanupItem );
+    
+    CHarvesterCenRepUtil::GetIgnorePathL( ignorePaths );
+	
+    CDir* directory = NULL;
+    TFileName name; 
+    
+	while ( path->Count() > 0 )
+		{
+		TInt error = aFs.GetDir( (*path)[0], KEntryAttDir, KHarvesterGetDirFlags, directory );
+		if ( error == KErrNone )
+			{
+			for ( TInt i=0; i < directory->Count(); ++i )
+				{
+				TEntry entry = (*directory)[i];
+				name.Zero();
+				name.Append( (*path)[0] );
+				// If filename is too long, skip it as the file cannot be supported
+				if( (name.Length() + entry.iName.Length()) > KMaxFileName )
+				    {
+				    continue;
+				    }
+				else
+				    {
+				    name.Append( entry.iName );     
+				    }
+			
+				if ( entry.IsDir() )
+					{
+					// If path is too long, skip it as the file cannot be supported
+	                if( name.Length() >= KMaxPath )
+	                    {
+	                    continue;
+	                    }
+	                else
+	                    {
+					    name.Append( KBackslash );
+	                    }
+					
+					// remove drive letter and colon from path
+					TPtrC pathOnly = name.Mid( 2 );
+					
+					if ( IsDescInArray( pathOnly, ignorePaths ) )
+						{
+						continue;
+						}
+
+					path->AppendL( name );
+					}
+				else
+					{
+					CPlaceholderData* phData = CPlaceholderData::NewL();
+					CleanupStack::PushL( phData );
+					phData->SetUri( name );
+					phData->SetModified( entry.iModified );
+					phData->SetFileSize( entry.iSize );
+					
+				    phData->SetMediaId( mediaId );
+#ifdef _DEBUG					
+					TBuf<256> debug;
+					debug.Copy( name );
+					WRITELOG1("CMmcFileList::BuildFileListL - Uri: %S", &debug );
+#endif
+					aEntryArray.AppendL( phData );
+					CleanupStack::Pop( phData );
+					}
+				}
+			}
+		path->Delete( 0 );
+		delete directory;
+		directory = NULL;
+		}
+	
+	CleanupStack::PopAndDestroy( &ignorePaths );
+	
+	CleanupStack::PopAndDestroy( path );
+	
+	WRITELOG( "CMmcFileList::BuildFileListL - end" );
+	}
+
+void CMmcFileList::HandleFileEntryL( CMdEHarvesterSession& aMdeSession,
+		RPointerArray<CPlaceholderData>& aEntryArray, 
+		RPointerArray<CPlaceholderData>& aHarvestEntryArray,
+		TUint32 aMediaID, CHarvesterPluginFactory* aPluginFactory )
+	{
+	WRITELOG( "CMmcFileList::HandleFileEntryL()" );
+	
+	// calculate batch size
+	TInt batchSize( 0 );
+	if ( aEntryArray.Count() >= KEntryBufferSize )
+		{
+		batchSize = KEntryBufferSize;
+		}
+	else
+		{
+		batchSize = aEntryArray.Count();
+		}
+
+#ifdef _DEBUG
+	WRITELOG2( "CMmcFileList::HandleFileEntryL() batchSize = %d, aEntryArray.Count() = %d", batchSize, aEntryArray.Count() );
+#endif
+	
+	RArray<TPtrC> uris;
+	RArray<TMdSFileInfo> fileInfos;
+	CleanupClosePushL( uris );
+	CleanupClosePushL( fileInfos );
+	
+	uris.ReserveL( batchSize );
+	fileInfos.ReserveL( batchSize );
+
+	for ( TInt i = 0; i < batchSize; i++ )
+		{
+		CPlaceholderData* e = aEntryArray[i];
+		
+		TPtr uriPtr = e->Uri();
+		TPtrC uriPtrC;
+		uriPtrC.Set( uriPtr.Ptr(), uriPtr.Length() );
+		uris.Append( uriPtr );
+
+		TMdSFileInfo fileInfo;
+		fileInfo.iModifiedTime = e->Modified().Int64();
+		fileInfo.iSize = e->FileSize();
+		fileInfos.Append( fileInfo );
+		}
+	
+	RArray<TFilePresentStates> results;
+	CleanupClosePushL( results );
+
+	WRITELOG( "CMmcFileList::HandleFileEntryL -- SetFilesToPresent start" );
+	aMdeSession.SetFilesToPresentL( aMediaID, uris, fileInfos, results );
+	WRITELOG( "CMmcFileList::HandleFileEntryL -- SetFilesToPresent end" );
+
+	for ( TInt i = 0; i < batchSize; i++ )
+		{
+		CPlaceholderData* e = aEntryArray[ 0 ];
+		aEntryArray.Remove( 0 );
+		CleanupStack::PushL( e );
+
+		TFilePresentStates found = results[ i ];
+
+		if ( found == EMdsNotFound )
+			{
+			if ( aPluginFactory && !aPluginFactory->IsSupportedFileExtension( e->Uri() ) )
+				{
+				iHem->DecreaseItemCountL( EHEObserverTypeMMC, 1 );
+				CleanupStack::PopAndDestroy( e );
+				continue;
+				}
+			e->SetPresentState( found );
+			aHarvestEntryArray.AppendL( e );
+			CleanupStack::Pop( e );
+			}
+		else if( found == EMdsPlaceholder )
+			{
+			e->SetPresentState( found );
+			aHarvestEntryArray.AppendL( e );
+			CleanupStack::Pop( e );
+			}
+		else if( found == EMdsModified )
+			{
+			e->SetPresentState( found );
+			aHarvestEntryArray.AppendL( e );
+			CleanupStack::Pop( e );
+			}
+		else
+			{
+			iHem->DecreaseItemCountL( EHEObserverTypeMMC, 1 );
+			CleanupStack::PopAndDestroy( e );
+			}
+		}
+	
+	if( aEntryArray.Count() == 0 )
+		{
+		aEntryArray.Compress();
+		}
+	
+	WRITELOG( "CMmcFileList::HandleFileEntryL -- cleanupstack" );
+	CleanupStack::PopAndDestroy( &results );
+	CleanupStack::PopAndDestroy( &fileInfos );
+	CleanupStack::PopAndDestroy( &uris );
+	WRITELOG( "CMmcFileList::HandleFileEntryL -- end" );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/src/mmcmonitorao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,364 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include <driveinfo.h>
+
+#ifdef __WINSCW__
+#include <pathinfo.h>
+#endif
+
+#include "harvesterlog.h"
+#include "harvestercommon.h"
+#include "mmcmonitorao.h"
+#include "mmcmonitorplugin.h"
+#include "fsutil.h"
+
+CMMCMonitorAO* CMMCMonitorAO::NewL()
+	{
+	WRITELOG( "CMMCMonitorAO::NewL" ); // DEBUG INFO
+	
+	CMMCMonitorAO* self = new (ELeave) CMMCMonitorAO();
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+void CMMCMonitorAO::ConstructL()
+	{
+	WRITELOG( "CMMCMonitorAO::ConstructL" ); // DEBUG INFO
+	
+	User::LeaveIfError( iFs.Connect() );
+	CActiveScheduler::Add( this );
+	for( TInt i=0; i<KMaxDrives; i++ )
+	    {
+	    iMediaIdList[i] = 0;
+	    }
+	}
+
+CMMCMonitorAO::~CMMCMonitorAO()
+	{
+	WRITELOG( "CMMCMonitorAO::~CMMCMonitorAO" ); // DEBUG INFO
+	
+	StopMonitoring();
+    iFs.Close();
+	}
+
+TBool CMMCMonitorAO::StartMonitoring( MMMCMonitorObserver& aObserver, RArray<TMdEMediaInfo>& aMedias )
+	{
+	WRITELOG( "CMMCMonitorAO::StartMonitoring" ); // DEBUG INFO
+
+	iObserver = &aObserver;
+	
+    BuildDriveList();
+    
+    for ( TInt i = 0; i < aMedias.Count(); i++ )
+    	{
+    	TInt drive(0);
+    	TInt err = iFs.CharToDrive( aMedias[i].iDrive, drive );
+    	if ( err == KErrNone )
+    		{
+    		WRITELOG2( "CMMCMonitorAO::StartMonitoring - set drive %d mediaid to %d ", drive, aMedias[i].iMediaId );
+    		iDriveList[drive] = 1; // fake value for startup (not KDriveAbsent)
+        	iMediaIdList[drive] = aMedias[i].iMediaId;
+    		}
+    	}
+    
+	iPreviousDriveList.Zero();
+	iPreviousDriveList.Copy( iDriveList );
+
+#ifdef _DEBUG
+	PrintAllLists();
+#endif
+
+	CompareDriveLists();
+
+	StartNotify();
+	
+	return ETrue;
+	}
+
+void CMMCMonitorAO::StartNotify()
+	{
+	WRITELOG( "CMMCMonitorAO::StartNotify with ENotifyEntry" ); // DEBUG INFO
+	
+	if( !IsActive() )
+		{
+		iFs.NotifyChange( ENotifyEntry, iStatus ); 
+		SetActive();                               
+		}
+	}
+
+TBool CMMCMonitorAO::StopMonitoring()
+	{
+	WRITELOG( "CMMCMonitorAO::StopNotify" ); // DEBUG INFO
+	
+	Cancel();
+	return ETrue;
+	}
+
+TBool CMMCMonitorAO::Resume()
+	{
+	WRITELOG( "CMMCMonitorAO::Resume" ); // DEBUG INFO
+
+	iPreviousDriveList.Zero();
+	iPreviousDriveList.Copy( iDriveList );
+
+	BuildDriveList();
+	CompareDriveLists();
+	StartNotify();
+	
+	return ETrue;
+	}
+
+TBool CMMCMonitorAO::Pause()
+	{
+	WRITELOG( "CMMCMonitorAO::Pause" ); // DEBUG INFO
+	
+	return StopMonitoring();
+	}
+
+void CMMCMonitorAO::RunL()
+	{
+#ifdef _DEBUG
+	WRITELOG1( "CMMCMonitorAO::RunL iStatus: %d", iStatus.Int() ); // DEBUG INFO
+#endif
+
+	if ( iStatus.Int() != KErrNone )
+		{
+		StartNotify();
+		return;
+		}
+
+	iPreviousDriveList.Zero();
+	iPreviousDriveList.Copy( iDriveList );
+
+	BuildDriveList();
+
+#ifdef _DEBUG
+	PrintAllLists();
+#endif
+
+	CompareDriveLists();
+
+#ifdef _DEBUG
+	PrintAllLists();
+#endif
+
+	StartNotify();
+	}
+
+#ifdef _DEBUG
+TInt CMMCMonitorAO::RunError( TInt aError )
+#else
+TInt CMMCMonitorAO::RunError( TInt )
+#endif
+	{
+	WRITELOG1( "CMMCMonitorAO::RunError with error code: %d", aError ); // DEBUG INFO
+	
+	StartNotify();
+	return KErrNone;
+	}
+
+void CMMCMonitorAO::DoCancel()
+	{
+	WRITELOG( "CMMCMonitorAO::DoCancel" ); // DEBUG INFO
+	
+	iFs.NotifyChangeCancel( iStatus );
+	}
+
+CMMCMonitorAO::CMMCMonitorAO() : CActive( KHarvesterPriorityMonitorPlugin ),
+    iObserver( NULL )
+	{
+	}
+
+void CMMCMonitorAO::BuildDriveList()
+	{
+	WRITELOG( "CMMCMonitorAO::BuildDriveList" ); // DEBUG INFO
+
+	iDriveList.Zero();
+    TInt numOfElements( 0 );
+    TInt err = DriveInfo::GetUserVisibleDrives( 
+    		iFs, iDriveList, numOfElements, 
+			KDriveAttExclude | KDriveAttRemote | KDriveAttRom );
+
+#ifdef __WINSCW__
+    TFileName systemPath = PathInfo::GetPath( PathInfo::EPhoneMemoryRootPath );
+    TInt systemDriveNum( -1 );
+    iFs.CharToDrive( systemPath[0], systemDriveNum );
+#endif
+    
+	if ( err != KErrNone )
+		{
+		WRITELOG1( "CMMCMonitorAO::BuildDriveList with error code: %d", err ); // DEBUG INFO
+		
+		return;
+		}
+
+	TDriveInfo driveInfo;
+	for ( TInt i=0; i < KMaxDrives; i++ )
+		{
+	
+#ifdef __WINSCW__
+        if ( i == systemDriveNum )
+            {
+            iDriveList[i] = 0;
+            continue;
+            }
+#endif
+	
+		if ( iDriveList[i] == KDriveAbsent )
+			{
+			continue;
+			}
+		err = iFs.Drive( driveInfo, i );
+		if ( err != KErrNone )
+			{
+			WRITELOG1( "CMMCMonitorAO::BuildDriveList with error code: %d", err ); // DEBUG INFO
+			}
+
+		TUint driveStatus;
+		err = DriveInfo::GetDriveStatus( iFs, i, driveStatus );
+		if ( err != KErrNone )
+			{
+			WRITELOG1( "CMMCMonitorAO::BuildDriveList with error code2: %d", err ); // DEBUG INFO
+			}
+
+#ifdef _DEBUG
+		if ( driveStatus & DriveInfo::EDriveInternal )
+			{
+			WRITELOG1("Drive %d is internal",i);
+			}		
+		
+		WRITELOG2("Drive %d type %d",i,driveInfo.iType);
+#endif
+		
+		if ( !( driveStatus & DriveInfo::EDriveRemovable ) )
+			{
+			WRITELOG1("Drive %d is not removable",i);
+			// check if driver is internal hard disk
+			if ( driveInfo.iType != EMediaHardDisk )
+				{
+				iDriveList[i] = 0;
+				continue;
+				}
+			else
+				{
+				WRITELOG1("Drive %d is hard disk",i);
+				}
+			}
+		
+		if( driveStatus & DriveInfo::EDriveUsbMemory )
+		    {
+            iDriveList[i] = 0;
+            continue;
+		    }
+
+		if ( driveInfo.iType == EMediaNotPresent )
+			{
+			WRITELOG1("Drive %d is not present",i);
+			iDriveList[i] = KDriveAbsent;
+			continue;
+			}
+
+		const TUint32 mediaId = FSUtil::MediaID(iFs, i);
+		if ( mediaId == 0 )
+			{
+			WRITELOG1("Drive %d: MediaId is 0",i);
+			iDriveList[i] = KDriveAbsent;
+			}
+		}
+	}
+
+void CMMCMonitorAO::CompareDriveLists()
+	{
+	WRITELOG( "CMMCMonitorAO::CompareDriveLists" ); // DEBUG INFO
+
+	for ( TInt i = 0; i < KMaxDrives; i++ )
+		{
+		if ( iDriveList[i] == KDriveAbsent && iPreviousDriveList[i] == KDriveAbsent )
+			{	
+			continue;
+			}
+
+		TChar chr;
+		iFs.DriveToChar( i, chr );
+		const TUint32 mediaId = FSUtil::MediaID(iFs, i);
+
+		if ( iDriveList[i] > KDriveAbsent && iPreviousDriveList[i] > KDriveAbsent )
+			{
+			if ( iMediaIdList[i] != mediaId )
+				{
+				WRITELOG3( "CMMCMonitorAO::CompareDriveLists media changed %d, old=%d, new=%d", i, iMediaIdList[i], mediaId ); // DEBUG INFO
+				// skip mount events if mediaId is 0
+				if ( iMediaIdList[i] != 0 )
+					{
+					iObserver->MountEvent( chr, iMediaIdList[i], EDismounted );
+					}
+				if ( mediaId != 0 )
+					{
+					iObserver->MountEvent( chr, mediaId, EMounted );
+					}
+				iMediaIdList[i] = mediaId;
+
+				}
+			continue;
+			}
+
+		if ( iDriveList[i] == KDriveAbsent )
+			{
+			WRITELOG1( "CMMCMonitorAO::CompareDriveLists Dismounted %d", i ); // DEBUG INFO
+			if ( mediaId )
+				{
+				iObserver->MountEvent( chr, mediaId, EDismounted );
+				}
+			else if ( iMediaIdList[i] )
+				{
+				iObserver->MountEvent( chr, iMediaIdList[i], EDismounted );
+				}
+			iMediaIdList[i] = 0;
+			}
+
+		if ( iPreviousDriveList[i] == KDriveAbsent )
+			{
+			WRITELOG1( "CMMCMonitorAO::CompareDriveLists Mounted %d", i ); // DEBUG INFO
+			iObserver->MountEvent( chr, mediaId, EMounted );
+			iMediaIdList[i] = mediaId;
+			}
+		}
+	}
+	
+#ifdef _DEBUG
+void CMMCMonitorAO::PrintAllLists()
+	{
+    WRITELOG( "CMMCMonitorAO::PrintAllLists()" );
+
+	for ( TInt i=0; i < KMaxDrives; i++ )
+		{
+		if ( !(iPreviousDriveList[i] == 0 && iDriveList[i] == 0 && iMediaIdList[i] == 0) )
+			{
+		    TInt32 drive;
+			drive = iPreviousDriveList[i];
+		    WRITELOG1( "CMMCMonitorAO::PrintAllLists() - Previous drive element: %d", drive );
+			drive = iDriveList[i];
+		    WRITELOG1( "CMMCMonitorAO::PrintAllLists() - Current drive element : %d", drive );
+			drive = iMediaIdList[i];
+		    WRITELOG1( "CMMCMonitorAO::PrintAllLists() - Current MediaId       : %d", drive );
+			}
+		}
+	}
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/src/mmcmonitorplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,348 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors MMC insertions and removals.*
+*/
+
+
+#include "mmcmonitorplugin.h"
+#include "harvesterlog.h"
+#include "mdsfileserverpluginclient.h"
+#include "fsutil.h"
+#include "harvestercenreputil.h"
+#include <driveinfo.h>
+
+#include <e32cmn.h>
+
+_LIT( KColon, ":" );
+
+// construct/destruct
+CMMCMonitorPlugin* CMMCMonitorPlugin::NewL()
+    {
+    CMMCMonitorPlugin* self = new (ELeave) CMMCMonitorPlugin();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+void CMMCMonitorPlugin::ConstructL() // second-phase constructor
+    {
+    WRITELOG( "CMMCMonitorPlugin::ConstructL" );
+
+    iMMCMonitor = CMMCMonitorAO::NewL();
+    iMountTask = CMMCMountTaskAO::NewL();
+    iUsbMonitor = CMMCUsbAO::NewL();
+    iMdEClient = NULL;
+    }
+    
+CMMCMonitorPlugin::~CMMCMonitorPlugin() // destruct
+    {
+    WRITELOG( "CMMCMonitorPlugin::~CMMCMonitorPlugin" );
+    
+    if (iMMCMonitor)
+    	{
+    	iMMCMonitor->StopMonitoring();
+    	delete iMMCMonitor;
+    	}
+    
+	if (iUsbMonitor)
+    	{
+    	iUsbMonitor->StopMonitoring();
+    	delete iUsbMonitor;
+    	}
+    
+	if (iMountTask)
+    	{
+    	delete iMountTask;
+    	}
+	
+	delete iMmcScanner;
+	delete iHddScanner;
+    }
+
+TBool CMMCMonitorPlugin::StartMonitoring( MMonitorPluginObserver& aObserver,
+    CMdESession* aMdEClient, CContextEngine* /*aCtxEngine*/, 
+    CHarvesterPluginFactory* aHarvesterPluginFactory )
+    {
+    WRITELOG( "CMMCMonitorPlugin::StartMonitoring" );
+
+    iObserver = &aObserver;
+    TRAPD( err, iMdEClient = CMdEHarvesterSession::NewL( *aMdEClient ) );
+    if( err != KErrNone )
+    	{
+    	return EFalse;
+    	}
+    
+    iMountTask->SetMonitorObserver( aObserver );
+    iMountTask->SetMdeSession( iMdEClient );
+    iMountTask->SetHarvesterPluginFactory( aHarvesterPluginFactory );
+    
+    // get present media IDs before last shutdown
+    RArray<TMdEMediaInfo> medias;
+    TRAP_IGNORE( iMdEClient->GetPresentMediasL( medias ) );
+	
+    // update db present status 
+    TRAP( err, StartMonitoringAllMMCsL( medias ) );
+    if ( err != KErrNone )
+        {
+        return EFalse;
+        }
+    
+    TChar driveLetter( 0 );
+	TBool presentState( EFalse );
+    
+	TUint32 hdMediaId( 0 );
+    hdMediaId = iMountTask->GetInternalDriveMediaId();
+    TBool alreadyWaited( EFalse );
+    
+    
+    for ( TInt i = 0; i < medias.Count(); i++ )
+    	{
+    	TRAP_IGNORE( iMdEClient->GetMediaL( medias[i].iMediaId, driveLetter, presentState ) );
+    	
+    	if ( presentState && medias[i].iMediaId != hdMediaId )
+    		{
+    		// scan MMC if card was in phone
+    		TRAP_IGNORE( iMmcScanner = CMmcScannerAO::NewL( medias[i].iMediaId, iMdEClient, iObserver,
+    		    				aHarvesterPluginFactory, CActive::EPriorityHigh, alreadyWaited ) );
+    		alreadyWaited = ETrue;
+    		}
+    	}
+ 
+    // scan mass storage to catch all chances even if battery dies during operation that should  be catched
+    if( hdMediaId )
+		{
+		TBool exists( EFalse );
+		TRAP_IGNORE( exists= iMdEClient->GetMediaL( hdMediaId, driveLetter, presentState ) );
+		
+		if ( exists )
+			{
+			WRITELOG("CMMCMonitorPlugin::StartMonitoring - start mass storage scan");
+			
+			TMdEMediaInfo hdInfo;
+			hdInfo.iMediaId = hdMediaId;
+			hdInfo.iDrive = driveLetter;
+			medias.Append( hdInfo );
+			
+			TRAP_IGNORE( iHddScanner = CMmcScannerAO::NewL( hdMediaId, iMdEClient, iObserver,
+			    				aHarvesterPluginFactory, CActive::EPriorityUserInput, alreadyWaited ));
+			}
+		}
+
+    iMMCMonitor->StartMonitoring( *this, medias );
+    
+    medias.Close();
+ 
+   	return iUsbMonitor->StartMonitoring( *this );
+    }
+
+TBool CMMCMonitorPlugin::StopMonitoring()
+    {
+    WRITELOG( "CMMCMonitorPlugin::StopMonitoring" );
+    
+    iMMCMonitor->StopMonitoring();
+    return iUsbMonitor->StopMonitoring();
+    }
+
+TBool CMMCMonitorPlugin::ResumeMonitoring( MMonitorPluginObserver& /*aObserver*/,
+    CMdESession* /*aMdEClient*/, CContextEngine* /*aCtxEngine*/,
+    CHarvesterPluginFactory* /*aHarvesterPluginFactory*/ )
+    {
+    WRITELOG( "CMMCMonitorPlugin::ResumeMonitoring" );
+    iMountTask->SetCachingStatus( EFalse );
+    return ETrue;
+    }
+
+TBool CMMCMonitorPlugin::PauseMonitoring()
+    {
+    WRITELOG( "CMMCMonitorPlugin::PauseMonitoring" ); // DEBUG INFO
+    iMountTask->SetCachingStatus( ETrue );
+    return ETrue;
+    }
+
+// constructor support
+// don't export these, because used only by functions in this DLL, eg our NewLC()
+CMMCMonitorPlugin::CMMCMonitorPlugin() // first-phase C++ constructor
+    {
+    // No implementation required
+    }
+
+void CMMCMonitorPlugin::AddNotificationPathL( TChar aDrive )
+    {
+    WRITELOG( "CMMCMonitorPlugin::AddNotificationPath" );
+
+    // 1 in length is for aDrive
+    HBufC* path = HBufC::NewLC( 1 + KColon.iTypeLength );
+    TPtr pathPtr = path->Des();
+    pathPtr.Append( aDrive );
+    pathPtr.Append( KColon );    
+    
+	CHarvesterCenRepUtil* cenRepoUtil = CHarvesterCenRepUtil::NewLC();
+	cenRepoUtil->AddIgnorePathsToFspL( pathPtr );
+	cenRepoUtil->FspEngine().AddNotificationPath( pathPtr );
+	CleanupStack::PopAndDestroy( cenRepoUtil );    
+    CleanupStack::PopAndDestroy( path );
+    }
+
+void CMMCMonitorPlugin::MountEvent( TChar aDriveChar, TUint32 aMediaID, TMMCEventType aEventType )
+    {
+    WRITELOG( "CMMCMonitorPlugin::MountEvent" );
+
+    TMountData* mountData = NULL;
+    mountData = new TMountData;
+    if ( !mountData )
+        {
+        return;
+        }
+    if( aMediaID != 0 && aEventType == EMounted)
+    	{
+	    RFs fs;
+	    const TInt err = fs.Connect();
+	    if ( err != KErrNone )
+	    	{
+	        delete mountData;
+	    	return;
+	    	}
+
+	    TUint status;
+	    TInt drive;
+	    fs.CharToDrive( aDriveChar, drive );
+		if( DriveInfo::GetDriveStatus( fs, drive, status ) == KErrNone )
+			{
+			//The "Out of disk space" mde query uses the MdE_Preferences table
+			if( !(status & DriveInfo::EDriveInternal) )
+				{
+				iMdEClient->AddMemoryCard( aMediaID );
+				}
+			}
+		
+		fs.Close();
+    	}
+
+    mountData->iDrivePath.Append( aDriveChar );
+    mountData->iDrivePath.Append( KColon );
+    mountData->iMediaID = aMediaID;
+    
+    switch ( aEventType )
+        {
+        case EMounted:
+            {
+            WRITELOG( "CMMCMonitorPlugin::MountEvent with parameter EMounted" );
+            mountData->iMountType = TMountData::EMount;
+            iMountTask->StartMount( *mountData );
+            }
+        break;
+        
+        case EDismounted:
+            {
+            if( aMediaID == 0 )
+            	{
+            	TRAP_IGNORE( mountData->iMediaID = FSUtil::GetPreviousMediaIDL( iMdEClient, aDriveChar ) );
+            	}
+            if( mountData->iMediaID )
+            	{
+	            WRITELOG( "CMMCMonitorPlugin::MountEvent with parameter EDismounted" );
+	            mountData->iMountType = TMountData::EUnmount;
+	            iMountTask->StartUnmount( *mountData );
+            	}
+            }
+        break;
+        
+        case EFormatted:
+            {
+            WRITELOG( "CMMCMonitorPlugin::MountEvent with parameter EFormatted" );
+            mountData->iMountType = TMountData::EFormat;
+            iMountTask->StartUnmount( *mountData );
+            }
+        break;
+        
+        default:
+            {
+            _LIT( KLogPanic, "unknown state" );
+            User::Panic( KLogPanic, KErrArgument );
+            }
+        break;
+        }
+    }
+
+void CMMCMonitorPlugin::StartMonitoringAllMMCsL( RArray<TMdEMediaInfo>& aMedias )
+    {
+    WRITELOG( "CMMCMonitorPlugin::StartMonitoringAllMMCs" );
+    TInt count( 0 );
+    
+    RFs fs;
+    User::LeaveIfError( fs.Connect() );
+    CleanupClosePushL( fs );
+        
+    TDriveInfo driveInfo;
+    TDriveList driveList;
+    TInt numOfElements( 0 );
+    DriveInfo::GetUserVisibleDrives( fs, 
+                                                        driveList, 
+                                                        numOfElements, 
+                                                        KDriveAttExclude | KDriveAttRemote | KDriveAttRom );
+    
+    TInt i( 0 );
+    TChar drive;
+    const TInt acount = driveList.Length();
+    const TInt mediaCount = aMedias.Count();
+    
+    // set removed medias to not present
+    for ( i = 0; i < mediaCount; i++ )
+    	{
+    	TInt driveNum(0);
+    	fs.CharToDrive( aMedias[i].iDrive, driveNum );
+    	TUint32 mediaId = FSUtil::MediaID( fs, driveNum );
+    	if ( mediaId != aMedias[i].iMediaId ) 
+    		{
+    		iMdEClient->SetMediaL( aMedias[i].iMediaId, aMedias[i].iDrive, EFalse );
+    		}
+    	}
+    
+    for ( i = 0; i < acount; i++ )
+        {
+        if ( driveList[i] > 0 )
+            {
+            TUint driveStatus( 0 );
+            DriveInfo::GetDriveStatus( fs, i, driveStatus ); 
+
+            if ( driveStatus & DriveInfo::EDriveUsbMemory )
+                {
+                driveList[i] = 0;
+                continue;
+                }
+            
+            fs.Drive( driveInfo, i );
+            if ( driveInfo.iDriveAtt & KDriveAttRemovable && driveInfo.iType != EMediaNotPresent )
+                {
+                count++; // DEBUG INFO
+                
+                fs.DriveToChar( i, drive );
+                
+                // set media id to MdE
+                TUint32 mediaId = FSUtil::MediaID( fs, i );
+                if ( mediaId != 0 )
+                    {
+                    iMdEClient->SetMediaL( mediaId, drive, ETrue );
+
+                    AddNotificationPathL( drive );
+                    }
+                }
+            }
+        }
+    
+    CleanupStack::PopAndDestroy( &fs ); 
+    
+    WRITELOG1( "CMMCMonitorPlugin::StartMonitoringAllMMCs found %d MMCs", count );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/src/mmcmounttaskao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,555 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Handles mount tasks*
+*/
+
+#include <driveinfo.h>
+
+#include <placeholderdata.h>
+#include "mmcmounttaskao.h"
+#include "mmcmonitorplugin.h"
+#include "harvesterlog.h"
+#include "mdsfileserverpluginclient.h"
+#include "mdeharvestersession.h"
+#include "harvesterdata.h"
+#include "mdsutils.h"
+#include "harvestercenreputil.h"
+#include "fsutil.h"
+#include "harvesterplugininfo.h"
+#include "harvesterpluginfactory.h"
+
+const TInt KEntryBufferSize = 100;
+
+//-----------------------------------------------------------------------------
+// CMMCMountTaskAO
+//-----------------------------------------------------------------------------
+CMMCMountTaskAO* CMMCMountTaskAO::NewL()
+	{
+	WRITELOG( "CMMCMountTaskAO::NewL" );
+	
+	CMMCMountTaskAO* self = new (ELeave) CMMCMountTaskAO();
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+void CMMCMountTaskAO::ConstructL()
+	{
+	WRITELOG("CMMCMountTaskAO::ConstructL");
+	
+	CActiveScheduler::Add( this );
+	User::LeaveIfError( iFs.Connect() );
+	iNextRequest = ERequestIdle;
+	iMmcFileList = CMmcFileList::NewL();
+	iCacheEvents = EFalse;
+	iHEM = CHarvesterEventManager::GetInstanceL();
+	}
+
+CMMCMountTaskAO::CMMCMountTaskAO() :
+		CActive( KHarvesterPriorityMonitorPlugin )
+	{
+	WRITELOG( "CMMCMountTaskAO::CMMCMountTaskAO" );
+	}
+	
+CMMCMountTaskAO::~CMMCMountTaskAO()
+	{
+	WRITELOG( "CMMCMountTaskAO::~CMMCMountTaskAO" );
+	Cancel();
+	iFs.Close();
+	
+	iMountDataQueue.ResetAndDestroy();
+	
+	delete iMdeSession;
+  
+	Deinitialize();
+	
+	if (iHEM)
+		{
+		iHEM->ReleaseInstance();
+		}
+	
+	delete iMmcFileList;
+	}
+	
+void CMMCMountTaskAO::SetMonitorObserver( MMonitorPluginObserver& aObserver )
+	{
+	WRITELOG( "CMMCMountTaskAO::SetMonitorObserver" );
+	iObserver = &aObserver;
+	}
+
+void CMMCMountTaskAO::SetMdeSession( CMdEHarvesterSession* aMdeSession )
+	{
+	iMdeSession = aMdeSession;
+	}
+
+void CMMCMountTaskAO::SetHarvesterPluginFactory( CHarvesterPluginFactory* aPluginFactory )
+	{
+	iHarvesterPluginFactory = aPluginFactory;
+	}
+	
+void CMMCMountTaskAO::StartMount( TMountData& aMountData )
+	{
+	WRITELOG("CMMCMountTaskAO::StartMount");
+	iMountDataQueue.Append( &aMountData );
+	if ( iNextRequest == ERequestIdle )
+		{
+		SetNextRequest( ERequestStartTask );
+		}
+	}
+	
+void CMMCMountTaskAO::StartUnmount(TMountData& aMountData)
+	{
+	WRITELOG("CMMCMountTaskAO::StartUnmount");
+	
+	// make sure that drive is not currently mounting
+	if ( iMountData )
+		{
+		if ( iMountData->iDrivePath.Compare( aMountData.iDrivePath ) == 0 )
+			{
+			Cancel();
+			Deinitialize();
+			iNextRequest = ERequestIdle;
+			}
+		}
+		
+	iMountDataQueue.Append( &aMountData );
+	SetNextRequest( ERequestStartTask );
+	}
+	
+void CMMCMountTaskAO::RunL()
+	{
+	WRITELOG1( "CMMCMountTaskAO::RunL iStatus: %d", iStatus.Int() );
+	
+	User::LeaveIfError( iStatus.Int() );
+	
+	if ( iCacheEvents )
+		{
+		if ( iMountData )
+			{
+			iMountDataQueue.Insert( iMountData, 0 );
+			iMountData = NULL;
+			}
+		Deinitialize();
+		return;
+		}
+	
+	switch( iNextRequest )
+		{
+		case ERequestStartTask:
+			{
+			WRITELOG( "CMMCMountTaskAO::RunL - ERequestStartTask" );
+			if ( iMountData )
+				{
+				delete iMountData;
+				iMountData = NULL;
+				}
+			
+			if( iMountDataQueue.Count() > 0 )
+				{
+				iMountData = iMountDataQueue[0];
+				iMountDataQueue.Remove(0);
+
+				WRITELOG1( "iMountData.iMountType: %d", iMountData->iMountType );
+				WRITELOG1( "iMountData.iDrivePath: %S", &iMountData->iDrivePath );
+				WRITELOG1( "iMountData.iMediaID: %d", iMountData->iMediaID );
+
+				if ( iMountData->iMountType == TMountData::EMount )
+					{
+					SetNextRequest( ERequestMount );
+					}
+				else if ( iMountData->iMountType == TMountData::EUnmount )
+					{
+					SetNextRequest( ERequestUnmount );
+					}
+				else if ( iMountData->iMountType == TMountData::EFormat )
+					{
+					SetNextRequest( ERequestFormat );
+					}
+				}
+			else
+				{
+				SetNextRequest( ERequestIdle );
+				iMountDataQueue.Compress();
+				}
+			}
+		break;
+		
+		case ERequestMount:
+			{
+			WRITELOG( "CMMCMountTaskAO::RunL - ERequestMount" );
+			Initialize();
+			StartNotifyL();
+			SetNotPresentToMDE();
+			TRAPD( err, iMmcFileList->BuildFileListL( iFs, iMountData->iDrivePath, iEntryArray ));
+			if ( err == KErrNoMemory )
+				{
+				iMountDataQueue.Insert( iMountData, 0 );
+				iMountData = NULL;
+				Deinitialize();
+				SetNextRequest( ERequestStartTask );
+				break;
+				}
+			
+			// send start event
+			const TInt entryCount = iEntryArray.Count();
+			if( entryCount > 0 )
+				{
+				iHEM->IncreaseItemCount( EHEObserverTypeMMC, entryCount );
+				iHEM->SendEventL( EHEObserverTypeMMC, EHEStateStarted, iHEM->ItemCount( EHEObserverTypeMMC ) );
+				}
+
+			SetNextRequest( ERequestHandleFileEntry );
+			}
+		break;
+		
+		case ERequestUnmount:
+			{
+			WRITELOG( "CMMCMountTaskAO::RunL - ERequestUnmount" );
+			
+			const TUint entryCount = iEntryArray.Count();
+			WRITELOG1( "CMMCMountTaskAO::RunL - ERequestUnmount entryCount = %d", entryCount );
+            if( entryCount )
+        		{
+        		iHEM->DecreaseItemCountL( EHEObserverTypeMMC, entryCount );
+		        }
+            
+            const TUint harvestEntryCount = iHarvestEntryArray.Count();
+            WRITELOG1( "CMMCMountTaskAO::RunL - ERequestUnmount harvestEntryCount = %d", harvestEntryCount );
+            if( harvestEntryCount )
+                {
+                iHEM->DecreaseItemCountL( EHEObserverTypeMMC, harvestEntryCount );
+                }
+			
+			RMsgQueue<TInt> unmountQueue;
+			_LIT( KUnmountHandlerAOString, "unmounthandlerao" );
+			TInt err = unmountQueue.OpenGlobal( KUnmountHandlerAOString );
+			if( err == KErrNone )
+				{
+				unmountQueue.Send( iMountData->iMediaID );
+				}
+			
+			SetNotPresentToMDE();
+			StopNotifyL();
+			SetNextRequest( ERequestCleanup );
+			}
+		break;
+		
+		case ERequestFormat:
+			{
+			WRITELOG( "CMMCMountTaskAO::RunL - ERequestFormat" );
+			SetNotPresentToMDE();
+			RemoveNotPresentFromMDE();
+			StopNotifyL();
+			SetNextRequest( ERequestCleanup );
+			}
+		break;
+		
+		case ERequestHandleFileEntry:
+			{
+			WRITELOG( "CMMCMountTaskAO::RunL - ERequestHandleFileEntry" );
+			
+			if( iNextRequest == ERequestStartTask )
+                {
+                WRITELOG( "CMMCMountTaskAO::RunL - ERequestHandleFileEntry stop processing media is unmounted");
+                SetNextRequest( ERequestStartTask );
+				return;
+                }
+            else if ( iEntryArray.Count() > 0 )
+				{
+				TRAPD( err, iMmcFileList->HandleFileEntryL( *iMdeSession, iEntryArray, 
+						iHarvestEntryArray, iMountData->iMediaID, iHarvesterPluginFactory ));
+				if ( err != KErrNone )
+					{
+					if( err == KErrNoMemory )
+						{
+						iMountDataQueue.Insert( iMountData, 0 );
+						iMountData = NULL;
+						}
+					Deinitialize();
+					SetNextRequest( ERequestStartTask );
+					break;
+					}
+				}
+			else
+				{
+				RemoveNotPresentFromMDE();
+				SetNextRequest( ERequestCleanup );
+				break;
+				}
+				
+			if ( iHarvestEntryArray.Count() > 0 )
+				{
+				SetNextRequest( ERequestHandleReharvest );
+				}
+			else
+				{
+				SetNextRequest( ERequestHandleFileEntry );
+				}
+			}
+		break;
+		
+		case ERequestHandleReharvest:
+			{
+			WRITELOG( "CMMCMountTaskAO::RunL - ERequestHandleReharvest" );
+			
+			if( iNextRequest == ERequestStartTask )
+                {
+                WRITELOG( "CMMCMountTaskAO::RunL - ERequestHandleReharvest stop processing media is unmounted");
+                SetNextRequest( ERequestStartTask );
+				return;
+                }
+         	else if ( iHarvestEntryArray.Count() > 0 )
+				{
+				HandleReharvestL( iHarvestEntryArray );
+				SetNextRequest( ERequestHandleReharvest );
+				}
+          	else
+				{
+				SetNextRequest( ERequestHandleFileEntry );
+				}
+			}
+		break;
+		
+		case ERequestCleanup:
+			{
+			WRITELOG( "CMMCMountTaskAO::RunL - ERequestCleanup" );
+			TBool present = (iMountData->iMountType == TMountData::EMount);
+			iMdeSession->SetMediaL( iMountData->iMediaID, iMountData->iDrivePath[0], present );
+			Deinitialize();
+			SetNextRequest( ERequestStartTask );
+			}
+		break;
+		
+		case ERequestIdle:
+			{
+			WRITELOG( "CMMCMountTaskAO::RunL - ERequestIdle" );
+			// all done
+			}
+		break;
+		
+		default:
+            User::Leave( KErrNotSupported );
+		break;
+		}
+	}
+
+#ifdef _DEBUG
+TInt CMMCMountTaskAO::RunError( TInt aError )
+#else
+TInt CMMCMountTaskAO::RunError( TInt )
+#endif
+	{
+	WRITELOG1( "CMMCMountTaskAO::RunError with error code: %d", aError );
+	Deinitialize();
+	return KErrNone;
+	}
+
+void CMMCMountTaskAO::DoCancel()
+	{
+	WRITELOG( "CMMCMountTaskAO::DoCancel" );
+	}
+
+void CMMCMountTaskAO::SetNextRequest( TRequest aRequest )
+	{
+	WRITELOG("CMMCMountTaskAO::SetNextRequest" );
+	if ( !IsActive() )
+		{
+		iNextRequest = aRequest;
+		TRequestStatus* ptrStatus = &iStatus;
+		User::RequestComplete( ptrStatus, KErrNone );
+		SetActive();
+		}
+	}
+
+void CMMCMountTaskAO::SetNotPresentToMDE()
+	{
+	WRITELOG1("CMMCMountTaskAO::SetNotPresentToMDE - MediaID %d", iMountData->iMediaID);
+	if ( iMountData->iMediaID )
+		{
+		iMdeSession->SetFilesToNotPresent( iMountData->iMediaID );
+		}
+	else
+		{
+		WRITELOG("CMMCMountTaskAO::SetNotPresentToMDE - MediaID 0, not setting");
+		}
+	}
+	
+void CMMCMountTaskAO::HandleReharvestL( RPointerArray<CPlaceholderData>& aArray )
+	{
+	WRITELOG("CMMCMountTaskAO::HandleReharvestL");
+	
+	TInt batchSize( 0 );
+	RPointerArray<CHarvesterData> hdArray;
+	CleanupClosePushL( hdArray );
+	
+	if ( aArray.Count() >= KEntryBufferSize )
+		{
+		batchSize = KEntryBufferSize;
+		}
+	else
+		{
+		batchSize = aArray.Count();
+		}
+			
+	for ( TInt i = 0; i < batchSize; i++ )
+		{
+		CPlaceholderData* ei = aArray[0];
+		
+		HBufC* fileName = ei->Uri().AllocLC();
+		CHarvesterData* hd = CHarvesterData::NewL( fileName );
+		hd->SetOrigin( MdeConstants::Object::EOther );
+		CleanupStack::Pop( fileName );
+		
+		if ( ei->PresentState() == EMdsPlaceholder || 
+			 ei->PresentState() == EMdsModified )
+			{
+			hd->SetEventType( EHarvesterEdit );
+			hd->SetObjectType( ENormal );
+			delete ei;
+			}
+		else
+			{
+			hd->SetEventType( EHarvesterAdd );
+			hd->SetObjectType( EPlaceholder );
+			hd->SetClientData( ei );
+			}
+		
+		hdArray.Append( hd );
+		aArray.Remove( 0 );
+		}
+	
+	aArray.Compress();
+			
+	if ( iObserver )
+		{
+		if( hdArray.Count() > 0)
+			{
+			iObserver->MonitorEvent( hdArray );
+			}
+		}
+	
+	CleanupStack::PopAndDestroy( &hdArray ); 
+	}
+	
+void CMMCMountTaskAO::RemoveNotPresentFromMDE()
+	{
+	WRITELOG( "CMMCMountTaskAO::RemoveNotPresentFromMDE" );
+	
+	iMdeSession->RemoveFilesNotPresent( iMountData->iMediaID );
+	}
+	
+void CMMCMountTaskAO::StartNotifyL()
+	{
+	WRITELOG( "CMMCMountTaskAO::StartNotify" );
+
+	CHarvesterCenRepUtil* cenRepoUtil = CHarvesterCenRepUtil::NewLC();
+	cenRepoUtil->AddIgnorePathsToFspL( iMountData->iDrivePath );
+	cenRepoUtil->FspEngine().AddNotificationPath( iMountData->iDrivePath );
+	CleanupStack::PopAndDestroy( cenRepoUtil );
+	}
+	
+void CMMCMountTaskAO::StopNotifyL()
+	{
+	WRITELOG( "CMMCMountTaskAO::StopNotify" );
+	
+	CHarvesterCenRepUtil* cenRepoUtil = CHarvesterCenRepUtil::NewLC();
+	cenRepoUtil->RemoveIgnorePathsFromFspL( iMountData->iDrivePath );
+	cenRepoUtil->FspEngine().RemoveNotificationPath( iMountData->iDrivePath );
+	CleanupStack::PopAndDestroy( cenRepoUtil );
+	}
+	
+void CMMCMountTaskAO::Initialize()
+	{
+	WRITELOG( "CMMCMountTaskAO::Initialize" );
+	iEntryArray.Reset();
+	iHarvestEntryArray.Reset();
+	}
+	
+void CMMCMountTaskAO::Deinitialize()
+	{
+	WRITELOG( "CMMCMountTaskAO::Deinitialize" );
+    
+    WRITELOG1( "CMMCMountTaskAO::Deinitialize - iEntryArray.Count() = %d", iEntryArray.Count() );
+    if( iEntryArray.Count() > 0)
+        {
+        TRAP_IGNORE( iHEM->DecreaseItemCountL( EHEObserverTypeMMC, iEntryArray.Count() ) );
+        }
+    
+    WRITELOG1( "CMMCMountTaskAO::Deinitialize - iHarvestEntryArray.Count() = %d", iHarvestEntryArray.Count() );
+    if( iHarvestEntryArray.Count() > 0)
+        {
+        TRAP_IGNORE( iHEM->DecreaseItemCountL( EHEObserverTypeMMC, iHarvestEntryArray.Count() ) );
+        }
+	
+	iEntryArray.ResetAndDestroy();
+	iHarvestEntryArray.ResetAndDestroy();
+
+	if ( iMountData )
+		{
+		delete iMountData;
+		iMountData = NULL;
+		}
+	}
+
+TUint32 CMMCMountTaskAO::GetInternalDriveMediaId()
+	{
+    WRITELOG( "CMMCMountTaskAO::GetInternalDriveMediaId" );
+	    
+	TDriveInfo driveInfo;
+	TDriveList driveList;
+    TInt numOfElements( 0 );
+
+    TInt err = DriveInfo::GetUserVisibleDrives( 
+    		iFs, driveList, numOfElements, 
+    		KDriveAttExclude | KDriveAttRemote | KDriveAttRom );
+    if( err != KErrNone )
+    	{
+    	return 0;
+    	}
+    
+	TUint32 hdMediaId = 0;
+	TInt i( 0 );
+
+	for ( i = 0; i < driveList.Length(); i++ )
+		{
+	    if ( driveList[i] > 0 )
+	    	{
+	    	iFs.Drive( driveInfo, i );
+	        if ( driveInfo.iType == EMediaHardDisk )
+	        	{
+	        	// check if disk is internal
+	        	TUint driveStatus;
+	        	TInt err = DriveInfo::GetDriveStatus( iFs, i, driveStatus );
+	        	if ( (err == KErrNone ) && ( driveStatus & DriveInfo::EDriveInternal ) )
+	        		{
+	        		// get media id
+	        		hdMediaId = FSUtil::MediaID( iFs, i );
+	        		break;
+	        		}
+	        	}
+	    	}
+		}
+
+	return hdMediaId;
+	}
+
+void CMMCMountTaskAO::SetCachingStatus( TBool aCachingStatus )
+	{
+	iCacheEvents = aCachingStatus;
+	if( !iCacheEvents )
+		{
+		SetNextRequest( ERequestStartTask );
+		}
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/src/mmcscannerao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,272 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Scans MMC after phone reboot for file changes*
+*/
+
+#include "mmcscannerao.h"
+#include "harvesterlog.h"
+#include "fsutil.h"
+#include <harvesterdata.h>
+#include <placeholderdata.h>
+#include <centralrepository.h>
+
+_LIT( KColon, ":" );
+
+const TInt KEntryBufferSize = 100;
+const TInt KDefaultDelay = 4;
+const TInt KMillion = 1000000;
+
+const TUid KRepositoryUid = { 0x20007183 };
+const TUint32 KScanDelayKey = 0x00000001;
+
+CMmcScannerAO::CMmcScannerAO( TUint32 aMediaId, 
+		CMdEHarvesterSession* aMdEClient, MMonitorPluginObserver* aObserver, 
+		CHarvesterPluginFactory* aHarvesterPluginFactory, CActive::TPriority aPriority ) : 
+		CTimer( aPriority ), iState( EUninitialized ), iMmcFileList( NULL )   
+	{
+	iMediaId = aMediaId;
+	iMdEClient = aMdEClient;
+	iObserver = aObserver;
+	iHarvesterPluginFactory = aHarvesterPluginFactory;
+	}
+
+CMmcScannerAO* CMmcScannerAO::NewL( TUint32 aMediaId, CMdEHarvesterSession* aMdEClient,
+		MMonitorPluginObserver* aObserver, CHarvesterPluginFactory* aHarvesterPluginFactory, 
+		CActive::TPriority aPriority, TBool aAlreadyWaited )
+	{
+	CMmcScannerAO* self = new ( ELeave ) CMmcScannerAO( aMediaId, aMdEClient, aObserver, 
+			aHarvesterPluginFactory, aPriority );
+	
+	CleanupStack::PushL( self );
+	self->ConstructL( aAlreadyWaited );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+void CMmcScannerAO::ConstructL( TBool aAlreadyWaited )
+	{
+	CTimer::ConstructL();
+	CActiveScheduler::Add( this ); // Add to scheduler
+	iState = EUninitialized;
+	User::LeaveIfError( iFs.Connect() );
+	iMmcFileList = CMmcFileList::NewL();
+	
+	if( !aAlreadyWaited )
+	    {
+        TInt tmpDelay( KDefaultDelay );
+        TTimeIntervalMicroSeconds32 delay( tmpDelay * KMillion ); 
+        CRepository* repo = CRepository::NewLC( KRepositoryUid );
+        TInt err = repo->Get( KScanDelayKey, tmpDelay );
+        if ( err == KErrNone )
+            {
+            delay = tmpDelay * KMillion;
+            }
+        CleanupStack::PopAndDestroy( repo );
+        After( delay );
+	    }
+	else
+	    {
+	    TTimeIntervalMicroSeconds32 delay( 5 ); 
+	    After( delay );
+	    }
+	}
+
+CMmcScannerAO::~CMmcScannerAO()
+	{
+	Cancel(); // Cancel any request, if outstanding
+	// Delete instance variables if any
+	
+	delete iMmcFileList;
+	
+	iEntryArray.ResetAndDestroy();
+	iEntryArray.Close();
+
+	iHarvestEntryArray.ResetAndDestroy();
+	iHarvestEntryArray.Close();
+	
+	iFs.Close();
+	}
+
+
+void CMmcScannerAO::RunL()
+	{
+	switch( iState )
+		{
+		case( EUninitialized ):
+			{
+			WRITELOG("CMmcScannerAO::RunL - Setting files to not present");
+			iMdEClient->SetFilesToNotPresent( iMediaId, ETrue );
+			SetState( EReadFiles );
+			break;
+			}
+		
+		case( EReadFiles ):
+			{
+			for ( TInt i=0; i < KMaxDrives; i++ )
+				{
+				const TUint32 mediaId = FSUtil::MediaID(iFs, i);
+				if( mediaId == iMediaId )
+					{
+					TChar chr;
+					iFs.DriveToChar( i, chr );
+					i = KMaxDrives;
+					iDrive.Zero();
+					iDrive.Append( chr );
+					iDrive.Append( KColon );
+					}
+				}
+			// drive not found (unmount before scanning delay)
+			if ( iDrive.Length() == 0 )
+				{
+				SetState( EDone );
+				break;
+				}
+			
+			WRITELOG("CMmcScannerAO::RunL - build file list");
+			iMmcFileList->BuildFileListL( iFs, iDrive, iEntryArray );
+			SetState( EProcessFiles );
+			break;
+			}
+		
+		case( EProcessFiles ):
+			{
+			if( iEntryArray.Count() > 0 )
+				{
+				WRITELOG("CMmcScannerAO::RunL - handling file list");
+				iMmcFileList->HandleFileEntryL( *iMdEClient, iEntryArray, 
+						iHarvestEntryArray, iMediaId, iHarvesterPluginFactory );
+				SetState( EHarvestFiles );
+				}
+			else 
+				{
+				SetState( ERemoveNPFiles );
+				}
+			break;
+			}
+		
+		case( EHarvestFiles ):
+			{
+			if ( iHarvestEntryArray.Count() > 0 )
+				{
+				WRITELOG("CMmcScannerAO::RunL - adding new files to harvester queue");
+				HandleReharvestL();
+				SetState( EHarvestFiles );
+				}
+			else
+				{
+				SetState( EProcessFiles );
+				}
+			break;
+			}
+		
+		case( ERemoveNPFiles ):
+			{
+			WRITELOG("CMmcScannerAO::RunL - Removing not present files");
+			iMdEClient->RemoveFilesNotPresent( iMediaId, ETrue );
+			SetState( EDone );
+			break;
+			}
+		
+		case( EDone ):
+			{
+			iFs.Close();
+			break;
+			}
+		
+		default: 
+			break;
+		
+		}
+	}
+
+void CMmcScannerAO::HandleReharvestL()
+	{
+	WRITELOG("CMMCMountTaskAO::HandleReharvestL");
+		
+	TInt batchSize( 0 );
+	RPointerArray<CHarvesterData> hdArray;
+	CleanupClosePushL( hdArray );
+	
+    if ( iHarvestEntryArray.Count() >= KEntryBufferSize )
+        {
+        batchSize = KEntryBufferSize;
+        }
+    else
+        {
+        batchSize = iHarvestEntryArray.Count();
+        }
+        
+    for ( TInt i = 0; i < batchSize; i++ )
+        {
+        CPlaceholderData* ei = iHarvestEntryArray[0];
+
+        HBufC* fileName = ei->Uri().AllocLC();
+        CHarvesterData* hd = CHarvesterData::NewL( fileName );
+		hd->SetOrigin( MdeConstants::Object::EOther );
+		CleanupStack::Pop( fileName );
+
+		if ( ei->PresentState() == EMdsPlaceholder || 
+			 ei->PresentState() == EMdsModified )
+			{
+			hd->SetEventType( EHarvesterEdit );
+			hd->SetObjectType( ENormal );
+			delete ei;
+			}
+		else
+			{
+			hd->SetEventType( EHarvesterAdd );
+			hd->SetObjectType( EPlaceholder );
+			hd->SetClientData( ei );
+			}
+		hdArray.Append( hd );
+        iHarvestEntryArray.Remove( 0 );
+        }
+
+    if( iHarvestEntryArray.Count() == 0 )
+    	{
+    	iHarvestEntryArray.Compress();
+    	}
+    
+	if ( iObserver )
+		{
+		if( hdArray.Count() > 0)
+			{
+			iObserver->MonitorEvent( hdArray );
+			}
+		else
+			{
+			iObserver->MonitorEvent( hdArray[0] );
+			}
+		}
+	
+	CleanupStack::PopAndDestroy( &hdArray ); 
+	}
+	
+
+TInt CMmcScannerAO::RunError( TInt /*aError*/ )
+	{
+	return KErrNone;
+	}
+
+void CMmcScannerAO::SetState( TCMmcScannerAOState aState )
+	{
+	WRITELOG("CMmcScannerAO::SetNextRequest" );
+	if ( !IsActive() )
+		{
+		iState = aState;
+		TRequestStatus* ptrStatus = &iStatus;
+		User::RequestComplete( ptrStatus, KErrNone );
+		SetActive();
+		}
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/src/mmcusbao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,266 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitors Usb insertions and removals.*
+*/
+
+
+#include <usbmsshared.h>
+
+#include "harvesterlog.h"
+#include "harvestercommon.h"
+#include "mmcusbao.h"
+#include "mmcmonitorplugin.h"
+
+CMMCUsbAO* CMMCUsbAO::NewL()
+    {
+    WRITELOG( "CMMCUsbAO::NewL" );
+    
+    CMMCUsbAO* self = new (ELeave) CMMCUsbAO();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+CMMCUsbAO::CMMCUsbAO() : CActive( KHarvesterPriorityMonitorPlugin ), iObserver( NULL )
+    {
+    iDrive = 0;
+    iMassStorageMode = EFalse;
+    }
+
+void CMMCUsbAO::ConstructL()
+    {
+    WRITELOG( "CMMCUsbAO::ConstructL" );
+    
+    CActiveScheduler::Add( this );
+    
+    User::LeaveIfError( iFs.Connect() );
+
+    User::LeaveIfError( iDriveState.Attach( 
+    		KUsbMsDriveState_Category, EUsbMsDriveState_DriveStatus ) );
+    }
+
+CMMCUsbAO::~CMMCUsbAO()
+    {
+    WRITELOG( "CMMCUsbAO::~CMMCUsbAO" );
+    StopMonitoring();
+    }
+
+TBool CMMCUsbAO::StartMonitoring( MMMCMonitorObserver& aObserver )
+    {
+    WRITELOG( "CMMCUsbAO::StartMonitoring" );
+    
+    iObserver = &aObserver;
+    
+    return Resume();
+    }
+
+void CMMCUsbAO::StartNotify()
+    {
+    WRITELOG( "CMMCUsbAO::StartNotify" );
+    iDriveState.Subscribe( iStatus );
+    SetActive();
+    }
+
+TBool CMMCUsbAO::StopMonitoring()
+    {
+    WRITELOG( "CMMCUsbAO::StopNotify" );
+    
+    return Pause();
+    }
+
+TBool CMMCUsbAO::Resume()
+    {
+    WRITELOG( "CMMCUsbAO::Resume" );
+        
+    StartNotify();
+    
+    return ETrue;
+    }
+
+TBool CMMCUsbAO::Pause()
+    {
+    WRITELOG( "CMMCUsbAO::Pause" );
+    
+    Cancel();
+    iDriveState.Close();
+    iFs.Close();
+    
+    return ETrue;
+    }
+
+void CMMCUsbAO::RunL()
+    {
+    WRITELOG1( "CMMCUsbAO::RunL iStatus: %d", iStatus.Int() );
+    
+    // check if change to pc-suite mode
+    if ( iStatus.Int() == KErrNotFound )
+        {
+        TChar chr;
+        RFs::DriveToChar( iDrive, chr );
+        iObserver->MountEvent( chr, MediaID(iDrive), EMounted );
+        iMassStorageMode = EFalse;
+        StartNotify();
+        return;
+        }
+    else
+        {
+        User::LeaveIfError( iStatus.Int() );
+        }
+        
+    TUsbMsDrivesStatus allDrivesStatus;
+    const TInt err = iDriveState.Get( allDrivesStatus );
+    
+    if ( err == KErrNone )
+        {
+        WRITELOG1( "CMMCUsbAO::RunL - allDrivesStatus.Length(): %d", allDrivesStatus.Length() );
+        const TInt count = allDrivesStatus.Length()/2;
+        for ( TInt i = 0; i < count; i++ )
+            {
+            TInt driveNumber = allDrivesStatus[2*i];
+            TInt driveStatus = allDrivesStatus[2*i+1];
+            TChar driveChar;
+            RFs::DriveToChar( driveNumber, driveChar );
+#ifdef _DEBUG
+            TFileName* fn = new (ELeave) TFileName( driveChar );
+            _LIT( KIndicator, ":" );
+            fn->Append( KIndicator );
+            WRITELOG1( "CMMCUsbAO::RunL - drive letter: %S", fn );
+            PrintDriveStatus( driveStatus );
+            delete fn;
+            fn = NULL;
+#endif
+            switch( driveStatus )
+                {
+                case EUsbMsDriveState_Connected:
+                    {
+                    if ( iMassStorageMode )
+                        {
+                        break;
+                        }
+                    iObserver->MountEvent( driveChar, MediaID(driveNumber), EDismounted );
+                    iMassStorageMode = ETrue;
+                    iDrive = driveNumber;
+                    }
+                break;
+                
+                case EUsbMsDriveState_Removed:
+                    {
+                    iObserver->MountEvent( driveChar, MediaID(driveNumber), EMounted );
+                    iMassStorageMode = EFalse;
+                    }
+                break;
+                
+                default:
+                	break;
+                }
+            }
+        }
+    else
+        {
+        WRITELOG1( "CMMCUsbAO::RunL - drive state error %d", err );
+        }
+    
+    StartNotify();
+    }
+
+#ifdef _DEBUG
+TInt CMMCUsbAO::RunError( TInt aError )
+#else
+TInt CMMCUsbAO::RunError( TInt )
+#endif
+    {
+    WRITELOG1( "CMMCUsbAO::RunError with error code: %d", aError );
+    
+    StartNotify();
+    return KErrNone;
+    }
+
+void CMMCUsbAO::DoCancel()
+    {
+    WRITELOG( "CMMCUsbAO::DoCancel" );
+    
+    iDriveState.Cancel();
+    }
+
+TUint32 CMMCUsbAO::MediaID( TInt aDrive )
+    {
+    TUint32 uid = 0;
+    TVolumeInfo* vi = NULL;
+    vi = new TVolumeInfo;
+    if ( !vi )
+        {
+        return uid;
+        }
+    
+    const TInt err = iFs.Volume( *vi, aDrive );
+    if ( err == KErrNone )
+        {
+        uid = vi->iUniqueID;
+        }
+
+    delete vi;
+    vi = NULL;
+    
+    return uid;
+    }
+
+#ifdef _DEBUG
+void CMMCUsbAO::PrintDriveStatus( TInt aStatus )
+    {
+    switch( aStatus )
+        {
+        case EUsbMsDriveState_Disconnected:
+        WRITELOG( "CMMCUsbAO::RunL - drive status: EUsbMsDriveState_Disconnected" );
+        break;
+        
+        case EUsbMsDriveState_Connecting:
+        WRITELOG( "CMMCUsbAO::RunL - drive status: EUsbMsDriveState_Connecting" );
+        break;
+        
+        case EUsbMsDriveState_Connected:
+        WRITELOG( "CMMCUsbAO::RunL - drive status: EUsbMsDriveState_Connected" );
+        break;
+        
+        case EUsbMsDriveState_Disconnecting:
+        WRITELOG( "CMMCUsbAO::RunL - drive status: EUsbMsDriveState_Disconnecting" );
+        break;
+        
+        case EUsbMsDriveState_Active:
+        WRITELOG( "CMMCUsbAO::RunL - drive status: EUsbMsDriveState_Active" );
+        break;
+        
+        case EUsbMsDriveState_Locked:
+        WRITELOG( "CMMCUsbAO::RunL - drive status: EUsbMsDriveState_Locked" );
+        break;
+        
+        case EUsbMsDriveState_MediaNotPresent:
+        WRITELOG( "CMMCUsbAO::RunL - drive status: EUsbMsDriveState_MediaNotPresent" );
+        break;
+        
+        case EUsbMsDriveState_Removed:
+        WRITELOG( "CMMCUsbAO::RunL - drive status: EUsbMsDriveState_Removed" );
+        break;
+        
+        case EUsbMsDriveState_Error:
+        WRITELOG( "CMMCUsbAO::RunL - drive status: EUsbMsDriveState_Error" );
+        break;
+        
+        default:
+        WRITELOG( "CMMCUsbAO::RunL - drive status: Unknown" );
+        break;
+        }
+    }
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/mmcplugin/src/proxy.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation proxy*
+*/
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include "mmcmonitorplugin.h"
+
+// Map the interface UIDs to implementation factory functions
+const TImplementationProxy KImplementationTable[] = 
+	{
+		{{0x20007187},	(TProxyNewLPtr)CMMCMonitorPlugin::NewL}
+	};
+
+// Exported proxy for instantiation method resolution
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+	{
+	aTableCount = sizeof(KImplementationTable) / sizeof(TImplementationProxy);
+	return KImplementationTable;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/monitorplugininterface/bwincw/monitorplugininterfacewinscw.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	??1CMonitorPlugin@@UAE@XZ @ 1 NONAME ; CMonitorPlugin::~CMonitorPlugin(void)
+	?ListImplementationsL@CMonitorPlugin@@SAXAAV?$RPointerArray@VCImplementationInformation@@@@@Z @ 2 NONAME ; void CMonitorPlugin::ListImplementationsL(class RPointerArray<class CImplementationInformation> &)
+	?NewL@CMonitorPlugin@@SAPAV1@ABVTUid@@@Z @ 3 NONAME ; class CMonitorPlugin * CMonitorPlugin::NewL(class TUid const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/monitorplugininterface/eabi/monitorplugininterfacearm.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,9 @@
+EXPORTS
+	_ZN14CMonitorPlugin20ListImplementationsLER13RPointerArrayI26CImplementationInformationE @ 1 NONAME
+	_ZN14CMonitorPlugin4NewLERK4TUid @ 2 NONAME
+	_ZN14CMonitorPluginD0Ev @ 3 NONAME
+	_ZN14CMonitorPluginD1Ev @ 4 NONAME
+	_ZN14CMonitorPluginD2Ev @ 5 NONAME
+	_ZTI14CMonitorPlugin @ 6 NONAME ; #<TI>#
+	_ZTV14CMonitorPlugin @ 7 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/monitorplugininterface/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+monitorplugininterface.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/monitorplugininterface/group/monitorplugininterface.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION       10.0
+TARGET        monitorplugininterface.dll
+TARGETTYPE    dll
+UID           0x1000008D 0x20007181
+
+CAPABILITY 	  CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+USERINCLUDE   .
+
+SYSTEMINCLUDE /epoc32/include/ecom
+USERINCLUDE   ../../../../inc
+USERINCLUDE   ../../../common/inc
+
+SOURCEPATH    ../src
+SOURCE        monitorplugin.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       ECOM.LIB
+
+#if defined(WINS)
+    deffile ../bwincw/monitorplugininterfacewinscw.def
+#elif defined(ARMCC)
+    deffile ../eabi/monitorplugininterfacearm.def
+#endif
+nostrictdef
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/monitorplugins/monitorplugininterface/src/monitorplugin.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Base class for monitor plug-ins.*
+*/
+
+
+#include "monitorplugin.h"
+
+EXPORT_C CMonitorPlugin* CMonitorPlugin::NewL(const TUid& aUid)
+	{
+	TAny* monitorPlugin = REComSession::CreateImplementationL(
+			aUid, _FOFF( CMonitorPlugin, iDtor_ID_Key ) );
+	return (reinterpret_cast<CMonitorPlugin*>(monitorPlugin));
+	}
+
+EXPORT_C void CMonitorPlugin::ListImplementationsL(RImplInfoPtrArray& aImplInfoArray)
+	{
+	REComSession::ListImplementationsL(
+			KMonitorPluginInterfaceUid, aImplInfoArray );
+	}
+	
+// Destructor
+EXPORT_C CMonitorPlugin::~CMonitorPlugin()
+	{
+	REComSession::DestroyedImplementation( iDtor_ID_Key );
+	}
+
+GLDEF_C TInt E32Dll()
+	{
+	return(KErrNone);
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+harvesterserver.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/group/harvesterserver.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,79 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION           10.0
+TARGET            harvesterserver.exe
+TARGETTYPE        exe
+UID               0x0 0x200009F5
+
+EPOCSTACKSIZE     0x14000
+#ifdef WINS
+EPOCHEAPSIZE      0x200 0x1400000
+#else
+EPOCHEAPSIZE      0x400 0x2800000
+#endif
+
+CAPABILITY        CAP_SERVER DiskAdmin AllFiles WriteDeviceData
+VENDORID          VID_DEFAULT
+
+SYSTEMINCLUDE     /epoc32/include/ecom
+SYSTEMINCLUDE     /epoc32/include/connect
+
+USERINCLUDE       ../../../inc
+USERINCLUDE       ../../common/inc
+USERINCLUDE       ../inc
+USERINCLUDE       ../../monitorplugins/inc
+
+SOURCEPATH        ../src
+SOURCE		harvesterserver.cpp
+SOURCE      harvesterserversession.cpp
+SOURCE      harvesterqueue.cpp
+SOURCE      harvesterao.cpp
+SOURCE      reharvesterao.cpp
+SOURCE		backupsubscriber.cpp
+SOURCE		ondemandao.cpp
+SOURCE		mdsactivescheduler.cpp
+SOURCE		mdeobjecthandler.cpp
+SOURCE		unmounthandlerao.cpp
+SOURCE 		restorewatcher.cpp
+SOURCE      harvesteroomao.cpp
+SOURCE      pauseobserverao.cpp
+SOURCE    harvestershutdownobserver.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY           euser.lib
+LIBRARY           ecom.lib
+LIBRARY		      efsrv.lib
+LIBRARY           contextengine.lib
+LIBRARY           mdeclient.lib
+LIBRARY           monitorplugininterface.lib
+LIBRARY           composerplugininterface.lib
+LIBRARY		      harvesterdata.lib
+LIBRARY           harvestercommon.lib
+LIBRARY		      locationmanager.lib
+LIBRARY           platformenv.lib 
+
+UNPAGED
+
+OPTION ARMCC -O3 -OTime
+
+EPOCPROCESSPRIORITY background
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/backupsubscriber.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,111 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observes Backup & Restore's state key and status -*
+*/
+
+
+#ifndef CTBACKUPSUBSCRIBER_H
+#define CTBACKUPSUBSCRIBER_H
+
+// SYSTEM INCLUDE
+#include <e32base.h>
+#include <e32cmn.h>
+
+// USER INCLUDE
+#include "mpropertyobserver.h"
+
+// FORWARD CLASS DECLERATION
+class CPropertyWatcher;
+
+/**
+ * Observer interface for Backup & Restore changes.
+ */
+ class MBackupRestoreObserver
+     {
+     public:
+         /**
+          * Called by CBlacklistBackupSubscriberAO when
+          * Backup&Restore is backing up or restoring.
+          */
+         virtual void BackupRestoreStart() = 0;
+
+         /**
+          * Called by CBlacklistBackupSubscriberAO when
+          * Backup&Restore has finished backup or restore.
+          */
+         virtual void BackupRestoreReady() = 0;
+     };
+
+/**
+* This class implements object for watching
+* Backup & Restore is state. 
+*/
+ NONSHARABLE_CLASS( CBackupSubscriber ) : public CBase, public MKeyAndStatusObserver
+  	{
+public:
+
+    /**
+     * Creates and constructs a new instance of CBackupSubscriber.
+     *
+     * @return A pointer to the new instance.
+     */
+    static CBackupSubscriber* NewL( MBackupRestoreObserver& aObserver );
+
+    /**
+     * Destructor.
+     */
+    virtual ~CBackupSubscriber();
+  
+public:
+   /*
+    @function NotifyKeyAndStatusL - get called when propertys value has changed.
+    @param aKeyValue - key's value.
+    @param aStatus - active object status, get from CListener object.
+    @param aPropertyCategory observed key's category.       
+    @param aKey observed key.
+    */
+	void CBackupSubscriber::NotifyKeyAndStatusL( 
+		const TInt aKeyValue,
+		TRequestStatus& aStatus,
+		const TUid aPropertyCategory,
+		const TUint aKey );
+
+
+private:
+
+    /**
+     * Default constructor, implicitly called by NewL().
+     */
+    CBackupSubscriber( MBackupRestoreObserver& aObserver );
+
+    /**
+     * 2nd phase construction, called by NewL().
+     */
+    void ConstructL();
+    
+    /**
+     * Check Backup & Restore's state key status and act accordingly.
+     */
+    void CheckBackupState( const TInt aKeyValue, TRequestStatus& aStatus );
+
+private: // data
+
+	/*iPropertyWatcher - constains observed key's, owned by this class*/
+	CPropertyWatcher* iPropertyWatcher;
+    
+	/*iObserver - callback for HarvesterAO to notify when backup/restore starts.*/
+	MBackupRestoreObserver& iObserver;
+  	};
+
+#endif // CTBACKUPSUBSCRIBER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/cclientkeywatcherao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef CCLIENTKEYWATCHERAO_H_
+#define CCLIENTKEYWATCHERAO_H_
+
+#include <e32base.h>
+#include <e32cmn.h>
+#include <e32property.h>
+
+class CRestoreWatcher;
+
+const TUid KPSRestoreWatcherCategory = { 0x200009F5 };
+const TUint KPSRestoreWatcherClientsKey = 0x00000010;
+
+class CClientKeyWatcherAO : public CActive
+	{	
+	public:
+		static CClientKeyWatcherAO* NewL( CRestoreWatcher* aRestoreWatcher );
+		virtual ~CClientKeyWatcherAO();
+	
+	private:
+		CClientKeyWatcherAO( CRestoreWatcher* aRestoreWatcher );
+		void ConstructL();
+		void RunL();
+		void DoCancel();
+		TInt RunError( TInt );
+		
+	private:
+		// Not owned
+		CRestoreWatcher* iRestoreWatcher;
+
+		RProperty iClientsProperty;
+		TInt iClients;
+	};
+
+#endif /*CCLIENTKEYWATCHERAO_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/harvesterao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,540 @@
+/*
+* Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Thread which actually performs the harvesting of the files*
+*/
+
+
+#ifndef __CHARVESTERAO_H__
+#define __CHARVESTERAO_H__
+
+#include <e32cmn.h>
+#include <e32base.h>
+
+#include "contextengine.h"
+#include "mdeharvestersession.h"
+
+#include "harvesterplugin.h"
+#include "composerplugin.h"
+#include "harvesterplugininfo.h"
+#include "harvesterqueue.h"
+#include "reharvesterao.h"
+#include "harvesterpluginfactory.h"
+#include "unmounthandlerao.h"
+#include "harvesteroomao.h"
+#include "backupsubscriber.h"
+#include "harvestermediaidutil.h"
+
+
+// forward declarations
+class CHarvesterBlacklist;
+class MProcessOriginMapperInterface;
+class COnDemandAO;
+class CMdeObjectHandler;
+class CHarvesterData;
+class CHarvesterEventManager;
+class CRestoreWatcher;
+class CHarvesterServerSession;
+struct TScanItem;
+
+/**
+ * Helper class to hold all property definitions 
+ * (pointers are not owned) used in harvester AO.
+ */
+class CHarvesterAoPropertyDefs : public CBase
+	{
+	public:
+		// Common property definitions
+		CMdEPropertyDef* iCreationDatePropertyDef;
+		CMdEPropertyDef* iLastModifiedDatePropertyDef;
+		CMdEPropertyDef* iSizePropertyDef;
+		CMdEPropertyDef* iOriginPropertyDef;
+		
+		// Media property definitions
+		CMdEPropertyDef* iPreinstalledPropertyDef;
+
+	private:
+		CHarvesterAoPropertyDefs();
+	
+		void ConstructL(CMdEObjectDef& aObjectDef);
+
+	public:	
+		static CHarvesterAoPropertyDefs* NewL(CMdEObjectDef& aObjectDef);
+	};
+
+/**
+ * MHarvesterStatusObserver
+ */	
+
+class MHarvesterStatusObserver
+	{
+	public:
+		virtual void PauseReady( TInt aError ) = 0;
+		virtual void ResumeReady( TInt aError ) = 0;
+	};
+
+/**
+* Harvester server active object.
+*
+* @lib harvesterblacklist.lib
+*/
+
+class CHarvesterAO : public CActive,
+                     public MHarvesterPluginObserver, 
+                     public MContextInitializationObserver,
+                     public MContextSnapshotObserver,
+                     public MMdESessionObserver,
+                     public MBackupRestoreObserver,
+                     public MUnmountObserver,
+                     public MHarvesterOomObserver
+	{
+    public:
+    
+        enum TRequest
+        	{
+        	ERequestIdle,
+        	ERequestHarvest,
+        	ERequestPause,
+        	ERequestResume,
+        	ERequestContainerPlaceholder
+        	};
+        	
+
+
+        /**
+         * Constructs a new harvesting thread
+         *
+         * @return  Harvester thread implementation
+         */
+        static CHarvesterAO* NewL();
+
+        /**
+         * Constructs a new harvesting thread and leaves the server implementation
+         * in the cleanup stack.
+         *
+         * @return  Harvester thread implementation
+         */
+        static CHarvesterAO* NewLC();
+
+        /**
+         * C++ Destructor.
+         */
+        virtual ~CHarvesterAO();
+        		
+        /**
+         * Derived from MHarvesterPluginObserver - used to indicate when harvesting of a file is done
+         * @param aHD  harvester data type
+         */
+        void HarvestingCompleted( CHarvesterData* aHD );
+
+        /**
+         * Derived from MContextInitializationObserver - for checking Context Engine initialization
+         * @param aErrorCode  Indicates whether Context Engine was successfully initialized
+         */
+        void ContextInitializationStatus( TInt aErrorCode );
+        	
+        /**
+         * Derived from MMdESessionObserver - for checking MdE initialization status
+         * @param aSession  MdE Session which was opened
+         * @param aError  Error code from the opening
+         */
+        void HandleSessionOpened( CMdESession& aSession, TInt aError );
+
+        /**
+         * Derived from MMdESessionObserver - for checking MdE session errors
+         * @param aSession  MdE Session which was opened
+         * @param aError  Error which has occurred
+         */
+        void HandleSessionError( CMdESession& aSession, TInt aError );
+
+        /**
+         * Method used to pause monitor plugins
+         */
+        void PauseMonitoring();
+
+        /**
+         * Method used to resume monitor plugins
+         */       
+        void ResumeMonitoring();
+
+        /**
+         * Standard RunL-method.
+         * From CActive.
+         */       
+        void RunL();
+
+        /**
+         * From CActive.
+         */       
+        void DoCancel();
+
+        /**
+         * From CActive.
+         * @param aError  Leave error code.
+         * @return Always KErrNone.
+         */       
+        TInt RunError( TInt aError );
+
+        /**
+         * Set next request (=state) of this active object.
+         * @param aRequest  State enumeration.
+         */       
+        void SetNextRequest( TRequest aRequest );
+
+        /**
+         * Checks if harvester server is paused.
+         * @return Truth value.
+         */       
+        TBool IsServerPaused();
+        
+        /**
+         * Checks whether connection to MDE has been established
+         * @return ETrue if connection to MDE has been made otherwise EFalse
+         */
+         TBool IsConnectedToMde();        
+        
+        
+        /**
+         * Starts a file harvest.
+         * @param aMessage  A message containing file info (URI etc)
+         */       
+        void HarvestFile( const RMessage2& aMessage );
+        
+        /**
+         * Starts a file harvest.
+         * @param aMessage  A message containing file info (URI etc)
+         */       
+        void HarvestFileWithUID( const RMessage2& aMessage );
+
+        /**
+         * Register an origin value for a process.
+         * @param aMessage  A message containing process id and origin.
+         */       
+        void RegisterProcessOrigin( const RMessage2& aMessage );
+
+        /**
+         * Unregister an origin value for a process.
+         * @param aMessage  A message containing process id.
+         */       
+        void UnregisterProcessOrigin( const RMessage2& aMessage );
+
+        /**
+         * This method is called by Context framework after context snapshot is taken
+         * @param aHD  Harvester data type (if ErrorCode() == KErrNone - snapshot taken ok)
+         */
+         void ContextSnapshotStatus( CHarvesterData* aHD );
+
+		/**
+         * Register a harvesting complete from server
+         * @param aMessage  Message which was received from the client side.
+         * @param aSession  harvester server session.
+         */ 
+        TInt RegisterHarvestComplete( const CHarvesterServerSession& aSession, const RMessage2& aMessage );
+        
+        /**
+         * Unregister a harvesting complete from server
+         * @param aMessage  Message which was received from the client side.
+         */ 
+        TInt UnregisterHarvestComplete( const CHarvesterServerSession& aSession );
+        
+        /**
+         * Register a harvester event from server
+         * @param aMessage  Message which was received from the client side.
+         */ 
+        void RegisterHarvesterEvent( const RMessage2& aMessage );
+        
+        /**
+	     * Unregister a harvester event from server
+	     * @param aMessage  Message which was received from the client side.
+	     */ 
+	    void UnregisterHarvesterEvent( const RMessage2& aMessage );
+	    
+        void GetLastObserverId( const RMessage2& aMessage );
+
+	// from MBackupRestoreObserver
+
+        /**
+         * From MBackupRestoreObserver.
+         * Called by CBlacklistBackupSubscriberAO when
+         * Backup&Restore is backing up or restoring.
+         */
+        void BackupRestoreStart();
+
+        /**
+         * From MBackupRestoreObserver.
+         * Called by CBlacklistBackupSubscriberAO when
+         * Backup&Restore has finished backup or restore.
+         */
+        void BackupRestoreReady();
+        
+        /** */  	
+        void HandleUnmount( TUint32 aMediaId );
+        
+        void SetHarvesterStatusObserver( MHarvesterStatusObserver* aObserver );
+        
+        /**
+         * From MHarvesterOomObserver
+         */
+        void MemoryLow();
+        
+        /**
+         * From MHarvesterOomObserver
+         */
+        void MemoryGood();
+		
+	private:
+		
+	struct THarvestFileRequest
+		{
+		const CHarvesterServerSession& iSession;
+		RMessage2 iMessage;
+			
+		THarvestFileRequest( const CHarvesterServerSession& aSession,
+				const RMessage2& aMessage ) :
+	       		iSession( aSession ), 
+	       		iMessage( aMessage )
+	       		{}
+		};
+	
+	/**
+         * C++ Constructor, called by NewLC()
+         */
+        CHarvesterAO();
+
+        /**
+         * 2nd-phase construction, called by NewLC()
+         */
+        void ConstructL(); 		
+
+        /**
+         * Method used to load monitor plugins
+         */        
+        void LoadMonitorPluginsL();
+
+        /**
+         * Method used to delete monitor plugins
+         */           
+        void DeleteMonitorPlugins();
+
+        /**
+         * Method used to start monitor plugins
+         */  
+        void StartMonitoring();
+
+        /**
+         * Method used to stop monitor plugins
+         */          
+        void StopMonitoring();
+
+        /**
+         * Method used to start composer plugins
+         */  
+        void StartComposersL();
+
+        /**
+         * Method used to stop composer plugins
+         */  		
+        void StopComposers();
+
+        /**
+         * Method used to delete composer plugins
+         */  
+        void DeleteComposers();
+
+        /**
+         * Method used to check whether composer plugins are active
+         * @return  Whether all compsosers are ready
+         */  				
+        TBool IsComposingReady();
+
+        /**
+         * Method used to read one harvester item from queue
+         */	    
+        void ReadItemFromQueueL();
+        
+        /**
+         * Method used to handle placeholder object to database
+         */	    
+        void HandlePlaceholdersL( TBool aCheck );
+
+        /**
+         * Method used to check file extension and harvest file
+         * @param aFile  File to be harvester 
+         * @param aEventType  Harveting type
+         * @param aTakeSnapshot  Whether context snapshot should be added to metadata
+         */		
+        void CheckFileExtensionAndHarvestL( CHarvesterData* aHD );
+
+        /**
+         * Method used to pause the operation of the Harvesting thread
+         * @return  Whether pausing of the harvesting thread succeeded 
+         */	
+        TInt PauseHarvester();
+
+        /**
+         * Method used to resume the operation of the Harvesting thread
+         */			
+        void ResumeHarvesterL();
+        
+        /**
+         * Signals the client observer for file harvesting was completed
+         * @param aClientId, RMessage2.Identity
+         * @param aFile, Harvested file name
+         * @param aErr, KErrNone, or system wide error code if exists
+         */ 
+        void HarvestCompleted( TUid aClientId, const TDesC& aUri, TInt aErr );
+        
+        /**
+         * Scan ROM drive (Z) in first phone boot
+         */
+        void BootRomScanL();
+        
+        /**
+         * Scan system drive (C) after partial restore
+         */
+        void BootPartialRestoreScanL();
+        
+        static TBool IsDescInArray(const TPtrC& aSearch, const RPointerArray<HBufC>& aArray);
+        
+        /**
+         * Method used to scan paths for file to be harvest. This method 
+         * removes paths from aPaths after scanning.
+         * 
+         * @param aScanPaths scan paths
+         * @param aIgnorePaths ignored paths
+         */
+        void BootScanL( RPointerArray<TScanItem>& aScanItems,
+        		        const RPointerArray<HBufC>& aIgnorePaths,
+        		        TBool aCheckDrive );
+        
+        /**
+         * Checks if there are any items unharvested in harvester plugins.
+         * @return  Whether or not there are any files to be harvested in plugin queues.
+         */
+        TBool UnharvestedItemsLeftInPlugins();
+
+        void PreallocateNamespaceL( CMdENamespaceDef& aNamespaceDef );
+        
+        void StartThumbAGDaemon();
+        
+ 	private:
+ 	
+        /**
+         * Pointer to Context Engine implementation
+         */	
+        CContextEngine* iCtxEngine;
+
+        /**
+         * Pointer to Metadata Engine session
+         */			
+        CMdESession* iMdESession;
+        
+        /**
+         * Pointer to Harvester Metadata Engine session
+         */			
+        CMdEHarvesterSession* iMdEHarvesterSession;
+
+        /**
+         * Harvester server internal event queue
+         */	
+        CHarvesterQueue* iQueue;
+
+        /**
+         * Blacklister of files that have failed harvesting.
+         */
+        CHarvesterBlacklist* iBlacklist;
+
+        /**
+         * Publish & Subscribe subscriber for Backup & Restore.
+         * Notifies harvester server when something happens.
+         */
+        CBackupSubscriber* iBackupSubscriber;
+
+        /**
+         * This array contains pointers to monitor plugins
+         */		
+        RPointerArray<CMonitorPlugin> iMonitorPluginArray;
+        
+        /**
+         * This array contains pointers to composer plugins
+         */		
+        RPointerArray<CComposerPlugin> iComposerPluginArray;
+
+        /**
+         * Indicates whether server is paused or not
+         */			
+        TBool iServerPaused;		
+
+        /**
+         * Indicator to show which task will be next to do
+         */
+        TRequest iNextRequest;
+        
+        /** */
+		RArray<THarvestFileRequest> iHarvestFileMessages;
+        /** Re-harvester */
+        CReHarvesterAO* iReHarvester;
+        
+        /** Flag to signal if mde session is properly initialized. */
+        TBool iMdeSessionInitialized;
+
+        /** Flag to signal if context engine is properly initialized. */
+        TBool iContextEngineInitialized;
+        
+        /** Connection to file server (CheckForMoveEventL) */
+        RFs iFs;
+
+        /** */
+        CHarvesterPluginFactory* iHarvesterPluginFactory;
+
+		/** */
+        RPointerArray<CHarvesterData> iPHArray;
+		
+		/** */
+        RPointerArray<CHarvesterData> iReadyPHArray;
+        
+        /** */
+        RPointerArray<CHarvesterData> iContainerPHArray;
+                
+        /**
+         * Pointer to process origin mapper for registering mappings.
+         * Implemented by file monitor plugin.
+         */
+        MProcessOriginMapperInterface* iProcessOriginMapper;
+        
+		/** */
+        COnDemandAO* iOnDemandAO;
+        
+		/** */
+        CMdeObjectHandler* iMdeObjectHandler;
+		
+        /** */
+        CUnmountHandlerAO* iUnmountHandlerAO;
+        
+        /** */
+        CHarvesterEventManager* iHarvesterEventManager;
+                
+        MHarvesterStatusObserver* iHarvesterStatusObserver;
+        TBool iHarvesting;
+        
+        CRestoreWatcher* iRestoreWatcher;
+        
+        CHarvesterOomAO* iHarvesterOomAO;
+        
+        // not own
+        CHarvesterMediaIdUtil* iMediaIdUtil;
+        
+        CHarvesterAoPropertyDefs* iPropDefs;
+	};
+	
+#endif //__CHARVESTERAO_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/harvesteroomao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,94 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Low memory observer for havester server
+*
+*/
+
+#ifndef __HARVESTEROOMAO_H__
+#define __HARVESTEROOMAO_H__
+
+
+// INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <e32msgqueue.h>
+
+// CLASS DECLARATION
+
+/**
+ * MHarvesterPluginObserver
+ */
+class MHarvesterOomObserver
+	{
+    public:
+    	virtual void MemoryLow() = 0;
+    	virtual void MemoryGood() = 0;
+	};
+
+/**
+*  CMdSOomPlugin
+* 
+*/
+class CHarvesterOomAO : public CActive
+	{
+public:
+	// Constructors and destructor
+	static CHarvesterOomAO* NewL( MHarvesterOomObserver& aObserver );
+	
+	/**
+	 * Destructor.
+	 */
+	virtual ~CHarvesterOomAO();	
+	
+    /**
+     * Standard RunL-method.
+     * From CActive.
+     */       
+    void RunL();
+
+    /**
+     * From CActive.
+     */       
+    void DoCancel();
+
+    /**
+     * From CActive.
+     * @param aError  Leave error code.
+     * @return Always KErrNone.
+     */       
+    TInt RunError( TInt aError );
+
+
+private:
+
+	/**
+	 * Constructor for performing 1st stage construction
+	 */
+	CHarvesterOomAO( MHarvesterOomObserver& aObserver );
+	
+	/**
+	 * default constructor for performing 2nd stage construction
+	 */
+	void ConstructL();
+
+    
+private:
+	
+	RMsgQueue<TInt> iOomMsgQueue;
+	MHarvesterOomObserver* iObserver;
+	
+	};
+
+
+#endif /*__HARVESTEROOMAO_H__*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/harvesterqueue.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,123 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implements queue that the Harvester server reads*
+*/
+
+#ifndef __CHARVESTERQUEUE__
+#define __CHARVESTERQUEUE__
+
+#include <monitorplugin.h>
+#include "harvestermediaidutil.h"
+
+// FORWARD DECLARATION
+class CHarvesterAO;
+class CHarvesterBlacklist;
+class CRestoreWatcher;
+
+class CHarvesterQueue : public CBase, 
+                        public MMonitorPluginObserver
+    {
+
+    public:
+    
+        /**
+         * Constructs a new harvester queue
+         *
+         * @return  Harvester server queue implementation
+         */
+        static CHarvesterQueue* NewL( CHarvesterAO* aHarvesterAO,
+        		CHarvesterBlacklist* aBlacklist );
+
+        /**
+         * Constructs a new harvester queue implementation and leaves the queue implementation
+         * in the cleanup stack.
+         *
+         * @return  Harvester server queue implementation
+         */
+        static CHarvesterQueue* NewLC( CHarvesterAO* aHarvesterAO,
+        		CHarvesterBlacklist* aBlacklist );
+
+        /**
+         * Destructor
+         */         
+        virtual ~CHarvesterQueue();
+
+        /**
+         * ConstructL
+         */     
+        void ConstructL();
+       
+        /**
+         * ItemsInQueue
+         * @return Number of items in the server queue
+         */ 
+        TInt ItemsInQueue();
+        
+        /**
+         * Gets next item in the Harvester server queue
+         * @returns The next item from the queue (FIFO)
+         */         
+        CHarvesterData* GetNextItem();
+        
+        /**
+         * Adds a item to the end of the queue
+         * @param aItem  Item to be added to the queue
+         */         
+        void Append( CHarvesterData* aItem );
+        
+        /**
+         * Derived from MMonitorPluginObserver - for getting new items to harvest
+         * @param aHarvesterData  data type which contains information needed by harvester
+         */   
+        void MonitorEvent( CHarvesterData* aHarvesterData );
+        
+        /**
+         * Derived from MMonitorPluginObserver - for getting new items to harvest
+         * @param aHarvesterData  array of data type which contains information needed by harvester
+         */   
+        void MonitorEvent( RPointerArray<CHarvesterData>& aHarvesterData );
+        
+        /**
+         * Remove items from harvesting queue
+         */
+        TUint RemoveItems(TUint32 aMediaId);
+        
+    private:
+        /**
+         * Constructor
+         */             
+        CHarvesterQueue( CHarvesterAO* aHarvesterAO, CHarvesterBlacklist* aBlacklist );
+        
+    private:
+   
+        /**
+        * Array which holds the details of the available plugins - filled during startup
+        */
+        RPointerArray<CHarvesterData> iItemQueue;
+     
+        /** Pointer to harvester active object */
+        CHarvesterAO* iHarvesterAO;
+
+        /** Pointer to harvester blacklisting */
+        CHarvesterBlacklist* iBlacklist;
+
+        RFs iFs;
+        
+        TVolumeInfo iVolInfo;
+        
+        // not own
+        CHarvesterMediaIdUtil* iMediaIdUtil;
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/harvesterserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,249 @@
+/*
+* Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester server*
+*/
+
+#ifndef __CHARVESTERSERVER__
+#define __CHARVESTERSERVER__
+
+#include <e32cmn.h>
+#include <apmrec.h>
+
+#include "mdeharvestersession.h"
+#include "contextengine.h"
+
+#include "harvesterplugin.h"
+#include "composerplugin.h"
+#include "harvesterplugininfo.h"
+#include "harvesterqueue.h"
+#include "harvesterao.h"
+#include "pauseobserverao.h"
+#include "harvestershutdownobserver.h"
+
+_LIT( KDefaultPanicName, "Harvester Server Panic" );
+_LIT( KHarvesterServerName, "HarvesterServer" );
+
+class CHarvesterServer : public CPolicyServer,
+						 public MHarvesterStatusObserver,
+						 public MHarvesterShutdownObserver
+	{
+
+    public:
+
+	    /**
+	    * Constructs a new harvester server implementation.
+	    *
+	    * @return  Harvester server implementation
+	    */
+        static CHarvesterServer* NewL();
+
+	    /**
+	    * Constructs a new harvester server implementation and leaves the server implementation
+	    * in the cleanup stack.
+	    *
+	    * @return  Harvester server implementation.
+	    */
+        static CHarvesterServer* NewLC();
+        
+        /**
+        * C++ Constructor.
+        * @param aPriority  Server process priority.
+        * @param aPolicy  Server policies.
+        * @param aType  Indicates what session type server supports .
+        */
+        CHarvesterServer( TInt aPriority, const TPolicy& aPolicy, TServerType aType );
+ 		
+ 		/**
+ 		* 2nd-phase construction, called by NewLC()
+ 		*/
+ 		void ConstructL();
+ 		
+	    /**
+	    * Destructor.
+	    */
+        virtual ~CHarvesterServer();
+        
+        /**
+        * Public method to start the server.
+        * @param aNone  Not used.
+        * @return Error code.
+        */
+        static TInt ThreadFunction( TAny* aNone );
+        
+        /**
+        * Method used to panic the client.
+        * @param aMessage  Message that is received from client.
+        * @param aPanic  Panic code which to raise on client side.
+        * @param aPanicDescription  Description of the panic.
+        */
+        static void PanicClient( const RMessage2& aMessage, TInt aPanic,
+        		const TDesC& aPanicDescription = KDefaultPanicName );
+
+        /**
+        * Method used to panic the server.
+        * @param aPanic  Panic code which to raise.
+        * @param aPanicDescription  Description of the panic.
+        */
+        static void PanicServer( TInt aPanic, const TDesC& aPanicDescription = KDefaultPanicName );
+
+        /**
+        * Method used to pause the server.
+        * @param aMessage  Message which was received from the client side.
+        */
+		void Pause( const RMessage2& aMessage );
+
+        /**
+        * Method used to resume the operation of the server.
+        * @param aMessage  Message which was received from the client side.
+        */				
+		void Resume( const RMessage2& aMessage );
+		
+        /**
+         * Method used to pause the server.
+         */
+ 		void Pause();
+
+         /**
+         * Method used to resume the operation of the server.
+         */				
+ 		void Resume();
+ 		
+        /**
+        * Method used to initiate harvesting of a file.
+        * @param aMessage  Message which was received from the client side.
+        */             
+		void HarvestFile( const RMessage2& aMessage );
+
+        /**
+        * Method used to initiate harvesting of a file.
+        * @param aMessage  Message which was received from the client side.
+        */             
+        void HarvestFileWithUID( const RMessage2& aMessage );
+		
+        /**
+        * Register a processes's origin value.
+        * @param aMessage  Message which was received from the client side.
+        */             
+        void RegisterProcessOrigin( const RMessage2& aMessage );
+
+        /**
+        * Unregister a process origin mapping.
+        * @param aMessage  Message which was received from the client side.
+        */             
+        void UnregisterProcessOrigin( const RMessage2& aMessage );
+
+        /**
+         * Register a harvesting complete from server
+         * @param aMessage  Message which was received from the client side.
+         */ 
+        TInt RegisterHarvestComplete( const CHarvesterServerSession& aSession, const RMessage2& aMessage );
+        
+        /**
+         * Unregister a harvesting complete from server
+         * @param aSession harvester server session.
+         */ 
+        TInt UnregisterHarvestComplete( const CHarvesterServerSession& aSession);
+        
+        /**
+         * Register a harvester event from server
+         * @param aMessage  Message which was received from the client side.
+         */ 
+        void RegisterHarvesterEvent( const RMessage2& aMessage );
+        
+        /**
+         * Unregister a harvester event from server
+         * @param aMessage  Message which was received from the client side.
+         */ 
+        void UnregisterHarvesterEvent( const RMessage2& aMessage );
+
+    public: // MHarvesterStatusObserver
+		virtual void PauseReady( TInt aError );
+		virtual void ResumeReady( TInt aError );
+        
+        /**
+         * Returns the ID of the latest registered event observer.
+         * @param aMessage  Message which was received from the client side.
+         */
+        void GetLastObserverId( const RMessage2& aMessage );
+        
+    public: // MHarvesterShutdownObserver
+        
+        void ShutdownNotification();
+        
+        void RestartNotification();
+        
+    protected: // Functions from base classes
+
+        /**
+        * From CPolicyServer.
+        * Handles capability checking for certain server requests.
+        * @param aMsg  Message which was received from the client side
+        * @param aAction  
+        * @param aMissing
+        * @result return one of TCustomResult set {EPass, EFail, EAsync}.
+        */
+        CPolicyServer::TCustomResult CustomSecurityCheckL( 
+            const RMessage2 &aMsg, TInt &aAction, TSecurityInfo &aMissing );
+
+        /**
+        * From CPolicyServer.
+        * Handles failure
+        * @param aMsg  Message which was received from the client side
+        * @param aAction  
+        * @param aMissing
+        * @result return one of TCustomResult set {EPass, EFail, EAsync}.
+        */
+        CPolicyServer::TCustomResult CustomFailureActionL(
+            const RMessage2 &aMsg, TInt aAction, const TSecurityInfo &aMissing );
+
+	private:
+	   
+	    /**
+         * Method that initializes the server.
+         */
+		static void ThreadFunctionL();
+
+	    /**
+         * RunError.
+         * @param aError  Error which has occurred
+         * @return  Error code - how operation should continue
+         */
+		TInt RunError( TInt aError );
+	    
+	    /**
+         * Method used to create new server session.
+         * @param  Mandatory Client/Server framework parameter - not used
+         * @param  Mandatory Client/Server framework parameter - not used
+         */		
+		CSession2* NewSessionL( const TVersion&, const RMessage2& ) const;
+		
+	private:
+
+	    /**
+         * Active Object which runs the harvesting operation
+         */		
+		CHarvesterAO* iHarvesterAO;
+		
+		const RMessage2* iMessage;
+		
+		/**
+		 * Pause P&S observer
+		 */
+		CPauseObserverAO* iPauseObserverAO;
+			    
+		CHarvesterShutdownObserver* iShutdownObserver;	    	  
+
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/harvesterserversession.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,96 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester servers session*
+*/
+
+
+#ifndef __CHARVESTERSERVERSESSION_H__
+#define __CHARVESTERSERVERSESSION_H__
+
+// INCLUDE FILES
+#include <e32base.h>
+
+// LOCAL INCLUDES
+#include "harvesterserver.h"
+
+// CLASS DECLARATION
+/**
+* CServerSession.
+*  An instance of class CHarvesterServerSession is created for each client.
+*/
+class CHarvesterServerSession : public CSession2
+    {
+    public: // Constructors and destructors
+
+        /**
+        * NewL.
+        * Two-phased constructor.
+        * @param aServer  Harvester server implementation
+        * @return Pointer to created CHarvesterServerSession object.
+        */
+        static CHarvesterServerSession* NewL( CHarvesterServer& aServer );
+
+        /**
+        * NewLC.
+        * Two-phased constructor.
+        * @param aServer  Harvester server implementation
+        * @return Pointer to created CHarvesterServerSession object.
+        */
+        static CHarvesterServerSession* NewLC( CHarvesterServer& aServer );
+
+        /**
+        * ~CHarvesterServerSession 
+        * Destructor.
+        */
+        virtual ~CHarvesterServerSession(); 
+
+
+    protected:
+    
+       /**
+        * ~ServiceL 
+        * Protected ServiceL method
+        * @param aMessage  Message receved from the Harvester Client
+        */
+        void ServiceL( const RMessage2& aMessage );
+        
+        virtual void Disconnect(const RMessage2 &aMessage);
+
+    private: // Constructors and destructors
+
+        /**
+        * CMdSServerSession.
+        * C++ default constructor.
+        * @param aServer  Harvester server implementation
+        */
+        CHarvesterServerSession( CHarvesterServer& aServer );
+
+        /**
+        * ConstructL.
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+        /**
+        * Reference to Harvester Server implementation
+        */
+        CHarvesterServer& iServer;
+
+    };
+
+#endif //  __CHARVESTERSERVERSESSION_H__
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/harvestershutdownobserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,113 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#ifndef HARVESTERSHUTDOWNOBSERVER_H
+#define HARVESTERSHUTDOWNOBSERVER_H
+
+#include <e32base.h>
+#include <w32std.h>
+#include <e32property.h> 
+
+
+/**
+ * Observer interface for signaling the need for shutdown
+ */
+class MHarvesterShutdownObserver
+    {
+public:
+
+    virtual void ShutdownNotification() = 0;
+    
+    virtual void RestartNotification() = 0;
+    };
+
+/**
+ *  Active object for observing P&S keys
+ *
+ *  @since S60 v5.0
+ */
+class CHarvesterShutdownObserver  : public CActive
+    {
+public:
+
+    /**
+     * Two-phased constructor.
+     *
+     * @since S60 v5.0
+     * @return Instance of CTMShutdownObserver.
+     */
+    IMPORT_C static CHarvesterShutdownObserver* NewL( MHarvesterShutdownObserver& aObserver/*, const TUid& aKeyCategory*/ );
+
+    /**
+     * Destructor
+     *
+     * @since S60 v5.0
+     */
+    virtual ~CHarvesterShutdownObserver();
+
+public:
+
+	/**
+	* Returns IAD update status
+	*/
+	TBool UpdateInProgress();
+    
+protected:
+
+    /**
+     * Handles an active object's request completion event.
+     *
+     * @since S60 v5.0
+     */
+    void RunL();
+
+    /**
+     * Implements cancellation of an outstanding request.
+     *
+     * @since S60 v5.0
+     */
+    void DoCancel();
+    
+    TInt RunError( TInt aError );
+
+private:
+
+    /**
+     * C++ default constructor
+     *
+     * @since S60 v5.0
+     * @return Instance of CShutdownObserver.
+     */
+    CHarvesterShutdownObserver( MHarvesterShutdownObserver& aObserver/*, const TUid& aKeyCategory*/ );
+
+    /**
+     * Symbian 2nd phase constructor can leave.
+     *
+     * @since S60 v5.0
+     */
+    void ConstructL();
+
+private:
+    
+    // not own
+    MHarvesterShutdownObserver& iObserver;
+    
+    RProperty iProperty;
+	TInt iValue;
+};
+
+#endif // SHUTDOWNOBSERVER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/mdeobjecthandler.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,75 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*/
+
+#ifndef MDEOBJECTHANDLER_H
+#define MDEOBJECTHANDLER_H
+
+// INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <f32file.h>
+
+// CLASS DECLARATION
+class CMdESession;
+class CHarvesterData;
+class CMdENamespaceDef;
+class CMdEObject;
+
+/**
+*  CMdeObjectHandler
+* 
+*/
+class CMdeObjectHandler : public CBase
+{
+public: // Constructors and destructor
+
+	/**
+		* Destructor.
+		*/
+	~CMdeObjectHandler();
+
+		/**
+		* Two-phased constructor.
+		*/
+	static CMdeObjectHandler* NewL( CMdESession& aSession );
+
+		/**
+		* Two-phased constructor.
+		*/
+	static CMdeObjectHandler* NewLC( CMdESession& aSession );
+	
+	void SetMetadataObjectL( CHarvesterData& aHD );
+	CMdEObject* GetMetadataObjectL( CHarvesterData& aHD, const TDesC& aObjectDefStr );
+	
+private:
+
+	/**
+		* Constructor for performing 1st stage construction
+		*/
+	CMdeObjectHandler( CMdESession& aSession );
+
+	/**
+		* default constructor for performing 2nd stage construction
+		*/
+	void ConstructL();
+	
+	CMdESession* iMdeSession;
+	CMdENamespaceDef* iDefaultNamespace;
+	RFs iFs;
+};
+
+#endif // MDEOBJECTHANDLER_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/mdsactivescheduler.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include <e32base.h>
+
+#ifndef MDSACTIVESCHEDULER_H_
+#define MDSACTIVESCHEDULER_H_
+
+class CMdsActiveScheduler : public CActiveScheduler
+{
+public:
+	IMPORT_C virtual void WaitForAnyRequest();
+	IMPORT_C void SetAllowedAOStatus(TRequestStatus& aStatus);
+	IMPORT_C void RemoveAllowedAOStatus();
+	IMPORT_C virtual void Error(TInt aError) const;
+private:
+	TRequestStatus* iAllowedAOStatus;
+};
+
+#endif /*MDSACTIVESCHEDULER_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/ondemandao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,76 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*/
+
+#ifndef __ONDEMANDAO_H__
+#define __ONDEMANDAO_H__
+
+#include <e32base.h>	// For CActive, link against: euser.lib
+#include <e32std.h>		// For RTimer, link against: euser.lib
+
+class CMdESession;
+class CMdEHarvesterSession;
+class MMonitorPluginObserver;
+class CHarvesterPluginFactory;
+class CHarvesterData;
+
+class COnDemandAO : public CActive
+{
+public:
+	// Cancel and destroy
+	~COnDemandAO();
+
+	// Two-phased constructor.
+	static COnDemandAO* NewL( CMdESession& aSession, MMonitorPluginObserver& aObserver,
+			CHarvesterPluginFactory& aPluginFactory, RPointerArray<CHarvesterData>* aPhArray);
+
+	// Two-phased constructor.
+	static COnDemandAO* NewLC( CMdESession& aSession, MMonitorPluginObserver& aObserver,
+			CHarvesterPluginFactory& aPluginFactory, RPointerArray<CHarvesterData>* aPhArray);
+
+public: // New functions
+	void StartL();
+
+private:
+	// C++ constructor
+	COnDemandAO();
+	
+	// Second-phase constructor
+	void ConstructL( CMdESession& aSession, MMonitorPluginObserver& aObserver,
+			CHarvesterPluginFactory& aPluginFactory, RPointerArray<CHarvesterData>* aPhArray);
+	void WaitHarvestingRequest();
+	
+private: // From CActive
+	// Handle completion
+	void RunL();
+	
+	// How to cancel me
+	void DoCancel();
+	
+	// Override to handle leaves from RunL(). Default implementation causes
+	// the active scheduler to panic.
+	TInt RunError( TInt aError );
+
+private:
+
+private:
+	CMdEHarvesterSession* iMdEHarvesterSession;
+	MMonitorPluginObserver* iObserver;
+	CHarvesterPluginFactory* iPluginFactory;
+	
+	RPointerArray<CHarvesterData> *iReadyPhArray;
+};
+
+#endif // __ONDEMANDAO_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/pauseobserverao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester server's P&S pause observer active object
+*
+*/
+
+
+#ifndef PAUSEOBSERVERAO_H_
+#define PAUSEOBSERVERAO_H_
+
+#include <e32base.h>
+#include <e32property.h>
+
+class CHarvesterServer;
+
+class CPauseObserverAO : public CActive
+	{	
+	public:
+		static CPauseObserverAO* NewL( CHarvesterServer& aHarvesterServer );
+		virtual ~CPauseObserverAO();
+	
+	private:
+		CPauseObserverAO( CHarvesterServer& aHarvesterServer );
+		void ConstructL();
+		void RunL();
+		void DoCancel();
+		TInt RunError( TInt aError );
+		
+	private:
+		CHarvesterServer& iHarvesterServer;
+		RProperty iPauseProperty;
+	};
+
+#endif /*PAUSEOBSERVERAO_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/reharvesterao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Active Object which actually performs the re-harvesting of the files*
+*/
+
+
+#ifndef __CREHARVESTERAO_H__
+#define __CREHARVESTERAO_H__
+
+#include <e32base.h>
+#include "harvesterqueue.h"
+
+class CReHarvesterAO : public CActive
+	{
+    public:
+    
+        static CReHarvesterAO* NewL();
+        static CReHarvesterAO* NewLC();
+        virtual ~CReHarvesterAO();
+        void ConstructL();
+
+        void RunL();
+
+        void DoCancel();
+
+        TInt RunError( TInt aError );
+        
+        void SetHarvesterQueue( CHarvesterQueue* aQueue );
+        void AddItem( CHarvesterData* aItem );
+        void CheckItem( CHarvesterData& aItem );
+        TInt ItemsInQueue();
+
+	private:
+	
+	    CReHarvesterAO();
+		
+ 	private:
+ 	    CHarvesterQueue* iQueue;
+ 	    RPointerArray<CHarvesterData> iItems;
+ 	    RTimer iTimer;
+ 	    TInt iDelay;
+	};
+	
+#endif //__CREHARVESTERAO_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/restorewatcher.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,144 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition of CRestoreWatcher class. Observers restore changes.
+*
+*/
+
+
+#ifndef RESTOREWATCHER_H
+#define RESTOREWATCHER_H
+
+// SYSTEM INCLUDE
+#include <e32base.h>
+#include <e32cmn.h>
+#include <e32property.h>
+
+// USER INCLUDE
+#include "mpropertyobserver.h"
+
+// FORWARD DECLERAATIONS
+class CPropertyWatcher;
+
+// CLASS DECLARATION
+/**
+ *  An instance of the CRestoreWatcher object.
+ *  Controls harvesterAO and message monitor behaviour when
+ *  user restoring data.
+ *
+ *  @code
+ *   
+ * 
+ * @endcode
+ *
+ *  @lib -
+ *  @since -
+ */
+NONSHARABLE_CLASS( CRestoreWatcher ) : public CBase, public MKeyObserver
+	{	
+
+public: 
+    
+	/**
+     * Factory method NewL
+     */
+	static CRestoreWatcher* NewL();
+
+	/**
+	 * Destructor
+	 */
+	virtual ~CRestoreWatcher();
+
+public:	
+	/**
+     * Method Register.
+     */
+	TBool Register();
+
+	/**
+     * Method UnregisterL.
+     */
+	void UnregisterL();
+	
+public:	 // From MKeyObserver.
+
+	/**
+	 * Method NotifyKeyL from MKeyObserver get notifications when
+	 * property key has changed.
+	 */
+	void NotifyKeyL( 
+			const TInt aKeyValue,
+			const TUid aPropertyCategory,
+			const TUint aKey ); 
+
+private: // Construction 
+
+	/**
+	 * Constructor
+	 */
+	CRestoreWatcher();
+
+	/**
+	 * Symbian 2nd phase constructor.
+	 */
+	void ConstructL();
+		
+private:
+
+	/**
+	 * Method HandleBackupRestoreKeyActionL.
+	 * If user make full restore sets restore flag on.
+	 */
+	void HandleBackupRestoreKeyActionL( const TUint aKeyValue );
+	
+	/**
+	 * Method HandleClientsKeyActionL.
+	 * Unregister and register message clients. 	
+	 */
+	void HandleClientsKeyActionL( const TUint aKeyValue );
+	
+	/**
+	 * Method SetRestoreFlagL.
+	 */
+	void SetRestoreFlagL( TBool aRestoreDone );
+	
+	/**
+	 * Method CheckRestoreL.
+	 */
+	void CheckRestoreL();
+	
+	/**
+	 * Method CreateFileNameL.
+	 * Creates file name in variable iFileName.
+	 */
+	void CreateFileNameL(); 
+
+private:
+	
+	/*iRegisteredClients - registered clients for this observer.*/
+	static TInt iRegisteredClients;
+	
+	/*iPartialRestoreDone - indicates if restore is executed.*/
+	static TBool iRestoreDone;
+	
+	/*iPropertyWatcher - constains observed key's, owned by this class*/
+	CPropertyWatcher* iPropertyWatcher;
+    
+	/*iClients - messageclients count.*/
+	TInt iClients;
+	
+	/*iFileName - File used for restore flag.*/
+	TFileName iFileName;
+	};
+
+#endif  // RESTOREWATCHER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/unmounthandlerao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,69 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*/
+
+#ifndef UNMOUNTHANDLERAO_H
+#define UNMOUNTHANDLERAO_H
+
+#include <e32base.h>	// For CActive, link against: euser.lib
+#include <e32std.h>		// For RTimer, link against: euser.lib
+#include <e32msgqueue.h>
+
+class MUnmountObserver
+{
+public:
+	virtual void HandleUnmount( TUint32 aMediaId ) = 0;
+};
+
+class CUnmountHandlerAO : public CActive
+{
+public:
+	// Cancel and destroy
+	~CUnmountHandlerAO();
+
+	// Two-phased constructor.
+	static CUnmountHandlerAO* NewL( MUnmountObserver& aObserver );
+
+	// Two-phased constructor.
+	static CUnmountHandlerAO* NewLC( MUnmountObserver& aObserver );
+
+public: // New functions
+	// Function for making the initial request
+	void WaitForUnmountL();
+
+private:
+	// C++ constructor
+	CUnmountHandlerAO( MUnmountObserver& aObserver );
+	
+	// Second-phase constructor
+	void ConstructL();
+	
+private: // From CActive
+	// Handle completion
+	void RunL();
+	
+	// How to cancel me
+	void DoCancel();
+	
+	// Override to handle leaves from RunL(). Default implementation causes
+	// the active scheduler to panic.
+	TInt RunError( TInt aError );
+
+private:
+	MUnmountObserver* iUnmountObserver;
+	RMsgQueue<TUint32> iMsgQueue;
+};
+
+#endif // UNMOUNTHANDLERAO_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/backupsubscriber.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,164 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observes Backup & Restore's state key and status -*
+*/
+
+
+// SYSTEM INCLUDE
+#include <e32property.h>
+#include <sbdefs.h>
+
+//USER INCLUDE
+#include "backupsubscriber.h"
+#include "harvesterlog.h"
+#include "mdsactivescheduler.h"
+#include "propertywatcher.h"
+
+// ---------------------------------------------------------------------------
+// CBackupSubscriber::CBackupSubscriber
+// Default constructor.
+// ---------------------------------------------------------------------------
+//
+CBackupSubscriber::CBackupSubscriber( MBackupRestoreObserver& aObserver )
+	: iPropertyWatcher( NULL ), iObserver( aObserver ) 
+    {
+    // No implementation required.
+    }
+
+// ---------------------------------------------------------------------------
+// CBackupSubscriber::NewL
+// Standard NewL for first phase construction.
+// ---------------------------------------------------------------------------
+//
+CBackupSubscriber* CBackupSubscriber::NewL( MBackupRestoreObserver& aObserver )
+    {
+    WRITELOG( "CBackupSubscriber::NewL - begin" ); 
+
+    CBackupSubscriber* self = new ( ELeave ) CBackupSubscriber( aObserver );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    
+    WRITELOG( "CBackupSubscriber::NewL - end" );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CBackupSubscriber::ConstructL
+// 2nd phase construction.
+// ---------------------------------------------------------------------------
+//
+void CBackupSubscriber::ConstructL()
+    {
+    WRITELOG( "CBackupSubscriber::ConstructL - begin" ); 
+    
+	iPropertyWatcher = CPropertyWatcher::GetInstanceL();
+    
+	// Want to listen when backup/restore starts.
+	// Calls NotifyKeyL when key's state has changed. 
+	iPropertyWatcher->ListenKeyAndStatusChangesL( 
+			KUidSystemCategory,
+			conn::KUidBackupRestoreKey,
+			this
+			);
+	
+    WRITELOG( "CBackupSubscriber::ConstructL - end" ); 
+    }
+
+// ---------------------------------------------------------------------------
+// CBackupSubscriber::~CBackupSubscriber
+// Destructor.
+// ---------------------------------------------------------------------------
+//
+CBackupSubscriber::~CBackupSubscriber()
+    {
+    WRITELOG( "CBackupSubscriber::~CBackupSubscriber - begin" ); 
+    
+	if( iPropertyWatcher )
+		{
+		iPropertyWatcher->StopListeningKeyAndStatusChanges( 
+				KUidSystemCategory,
+				conn::KUidBackupRestoreKey, this );
+		
+		iPropertyWatcher->Delete(); // Release connection to TLS object.
+		}
+    
+	WRITELOG( "CBackupSubscriber::~CBackupSubscriber - end" );
+    }
+
+// -----------------------------------------------------------------------------
+// CBackupSubscriber::NotifyKeyAndStatusL
+// CPropertyWatcher's callback.
+// -----------------------------------------------------------------------------
+//
+void CBackupSubscriber::NotifyKeyAndStatusL( 
+		const TInt aKeyValue,
+		TRequestStatus& aStatus,
+		const TUid aPropertyCategory,
+		const TUint aKey )
+	{
+	WRITELOG("CBackupSubscriber::NotifyKeyAndStatusL() - begin");
+	
+	if( aPropertyCategory == KUidSystemCategory &&
+			aKey == conn::KUidBackupRestoreKey )
+		{
+		CheckBackupState( aKeyValue,  aStatus );
+		}
+	
+	WRITELOG("CBackupSubscriber::NotifyKeyAndStatusL() - end");
+	}
+
+
+// ---------------------------------------------------------------------------
+// CBackupSubscriber::CheckBackupState
+// Check Backup & Restore's state key status and act accordingly. 
+// ---------------------------------------------------------------------------
+//
+void CBackupSubscriber::CheckBackupState( 
+		const TInt aKeyValue,
+		TRequestStatus& aStatus )
+    {
+    WRITELOG( "CBackupSubscriber::CheckBackupState, begin" );
+    
+    TInt backupStateValue = aKeyValue;
+	backupStateValue &= conn::KBURPartTypeMask;
+	WRITELOG1( "CBackupSubscriber::CheckBackupState(), backupStateValue = %d", backupStateValue ); 	
+	
+	switch ( backupStateValue )
+		{
+		case conn::EBURBackupFull:
+		case conn::EBURBackupPartial:
+		case conn::EBURRestoreFull:
+		case conn::EBURRestorePartial:
+			{
+			iObserver.BackupRestoreStart();
+			CMdsActiveScheduler* mdsScheduler = static_cast<CMdsActiveScheduler*> (CActiveScheduler::Current());
+   			mdsScheduler->SetAllowedAOStatus( aStatus );
+			break;
+			}
+		case conn::EBURNormal:
+		case conn::EBURUnset:
+		default:
+			{
+			// backup or restore is completed, so resume normal operation.
+       		iObserver.BackupRestoreReady();
+			CMdsActiveScheduler* mdsScheduler = static_cast<CMdsActiveScheduler*> (CActiveScheduler::Current());
+       		mdsScheduler->RemoveAllowedAOStatus();
+			}
+		}
+
+    WRITELOG( "CBackupSubscriber::CheckBackupState, end" ); 
+    }
+
+// End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/cclientkeywatcherao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include "harvesterlog.h"
+#include "cclientkeywatcherao.h"
+#include "crestorewatcher.h"
+
+CClientKeyWatcherAO* CClientKeyWatcherAO::NewL( CRestoreWatcher* aRestoreWatcher )
+	{
+	WRITELOG("CClientKeyWatcherAO::NewL()");
+	CClientKeyWatcherAO* self = new (ELeave) CClientKeyWatcherAO( aRestoreWatcher );
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+CClientKeyWatcherAO::~CClientKeyWatcherAO()
+	{
+	Cancel();
+	iClientsProperty.Close();
+
+	iRestoreWatcher = NULL;
+	}
+
+
+CClientKeyWatcherAO::CClientKeyWatcherAO( CRestoreWatcher* aRestoreWatcher ) :
+		CActive( CActive::EPriorityUserInput )
+	{
+	CActiveScheduler::Add( this );
+	iRestoreWatcher = aRestoreWatcher;
+	}
+
+void CClientKeyWatcherAO::ConstructL()
+	{
+	WRITELOG("CClientKeyWatcherAO::ConstructL()");
+	
+	User::LeaveIfError( iClientsProperty.Attach( KPSRestoreWatcherCategory, 
+			KPSRestoreWatcherClientsKey, EOwnerThread ) );
+    
+	iClientsProperty.Subscribe( iStatus );
+    SetActive();
+    WRITELOG("CClientKeyWatcherAO::ConstructL() - ends");
+	}
+
+void CClientKeyWatcherAO::RunL()
+	{
+	WRITELOG("CClientKeyWatcherAO::RunL()");
+	if( iStatus.Int() != KErrNone )
+        {
+#ifdef _DEBUG
+        WRITELOG1("CClientKeyWatcherAO::RunL() - error: %d", iStatus.Int());
+#endif
+        return;
+        }
+	
+	TInt clients = 0;
+	iClientsProperty.Get( clients );
+	
+	if ( clients < iClients )
+		{
+		WRITELOG("CClientKeyWatcherAO::RunL() - unregistering");
+		iRestoreWatcher->UnregisterL();
+		}
+	else if ( clients > iClients )
+		{
+		WRITELOG("CClientKeyWatcherAO::RunL() - registering");
+		iRestoreWatcher->Register();
+		}
+	
+	iClients = clients;
+	
+	iClientsProperty.Subscribe( iStatus );
+	SetActive();
+	}
+
+void CClientKeyWatcherAO::DoCancel()
+	{
+	iClientsProperty.Cancel();
+	}
+
+TInt CClientKeyWatcherAO::RunError( TInt )
+	{
+	return KErrNone;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/harvesterao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,2498 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Thread which actually performs the harvesting of the files*
+*/
+
+
+#include <e32svr.h>
+#include <caf/caf.h>
+
+#include <rlocationobjectmanipulator.h>
+#include <placeholderdata.h>
+#include <harvesterclientdata.h>
+
+using namespace ContentAccess;
+
+#include "harvesterao.h"
+#include "harvesterlog.h"
+#include "harvesterblacklist.h"
+#include "mdeobject.h"
+#include "mdsutils.h"
+#include "mdeconstants.h"
+#include "harvesterdata.h"
+#include "ondemandao.h"
+#include "harvestercommon.h"
+#include "processoriginmapperinterface.h"
+#include "mdeobjecthandler.h"
+#include "harvestereventmanager.h"
+#include "harvestercenreputil.h"
+#include "restorewatcher.h"
+#include "backupsubscriber.h"
+
+// constants
+const TInt32 KFileMonitorPluginUid = 0x20007186;  // file monitor plugin implementation uid
+
+const TInt KPlaceholderQueueSize = 99;
+const TInt KContainerPlaceholderQueueSize = 10;
+const TInt KObjectDefStrSize = 20;
+
+const TInt KCacheItemCountForEventCaching = 1;
+
+_LIT( KTAGDaemonName, "ThumbAGDaemon" );
+_LIT( KTAGDaemonExe, "thumbagdaemon.exe" );
+
+_LIT(KInUse, "InUse");
+
+CHarvesterAoPropertyDefs::CHarvesterAoPropertyDefs() : CBase()
+	{
+	}
+
+void CHarvesterAoPropertyDefs::ConstructL(CMdEObjectDef& aObjectDef)
+	{
+	CMdENamespaceDef& nsDef = aObjectDef.NamespaceDef();
+
+	// Common property definitions
+	CMdEObjectDef& objectDef = nsDef.GetObjectDefL( MdeConstants::Object::KBaseObject );
+	iCreationDatePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KCreationDateProperty );
+	iLastModifiedDatePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KLastModifiedDateProperty );
+	iSizePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KSizeProperty );
+	iOriginPropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KOriginProperty );
+	
+	CMdEObjectDef& mediaDef = nsDef.GetObjectDefL( MdeConstants::MediaObject::KMediaObject );
+	iPreinstalledPropertyDef = &mediaDef.GetPropertyDefL( MdeConstants::MediaObject::KPreinstalledProperty );
+	}
+
+CHarvesterAoPropertyDefs* CHarvesterAoPropertyDefs::NewL(CMdEObjectDef& aObjectDef)
+	{
+	CHarvesterAoPropertyDefs* self = 
+		new (ELeave) CHarvesterAoPropertyDefs();
+	CleanupStack::PushL( self );
+	self->ConstructL( aObjectDef );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+CHarvesterAO* CHarvesterAO::NewLC()
+    {
+    WRITELOG( "CHarvesterAO::NewLC() - begin" );
+    
+    CHarvesterAO* self = new (ELeave) CHarvesterAO();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+    
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CHarvesterAO* CHarvesterAO::NewL()
+    {
+    WRITELOG( "CHarvesterAO::NewL() - begin" );
+    
+    CHarvesterAO* self = CHarvesterAO::NewLC();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterAO
+// ---------------------------------------------------------------------------
+//
+CHarvesterAO::CHarvesterAO() : CActive( CActive::EPriorityStandard )
+    {
+    WRITELOG( "CHarvesterAO::CHarvesterAO() - begin" );
+    
+    iServerPaused = ETrue;
+    iNextRequest = ERequestIdle;
+    
+    iContextEngineInitialized = EFalse;
+    iMdeSessionInitialized = EFalse;
+    iHarvesting = EFalse;
+    }
+     
+// ---------------------------------------------------------------------------
+// ~CHarvesterAO
+// ---------------------------------------------------------------------------
+//
+CHarvesterAO::~CHarvesterAO()
+    {
+    WRITELOG( "CHarvesterAO::~CHarvesterAO()" );
+    
+    Cancel();
+
+	iFs.Close();
+	
+	if (iCtxEngine)
+		{
+		iCtxEngine->ReleaseInstance();
+		}
+			
+   	if (iHarvesterEventManager)
+		{
+		iHarvesterEventManager->ReleaseInstance();
+		}
+
+    StopMonitoring();
+    DeleteMonitorPlugins();        
+    
+    StopComposers();
+    DeleteComposers();
+
+	delete iBackupSubscriber;
+    
+    if (iBlacklist)
+		{
+		iBlacklist->CloseDatabase();
+		delete iBlacklist;
+		}
+	delete iReHarvester;
+
+    if ( iHarvestFileMessages.Count() > 0 )
+        {
+        for ( TInt i = iHarvestFileMessages.Count()-1; i >= 0; --i )
+            {
+            RMessage2& msg = iHarvestFileMessages[i].iMessage;
+            if (!msg.IsNull())
+            	{
+            	msg.Complete( KErrCancel );
+            	}
+            iHarvestFileMessages.Remove( i );
+            }
+        }
+    iHarvestFileMessages.Close();
+    
+    iMonitorPluginArray.ResetAndDestroy();
+    iMonitorPluginArray.Close();
+  	
+    iPHArray.ResetAndDestroy();
+    iPHArray.Close();
+	
+   	iReadyPHArray.ResetAndDestroy();
+    iReadyPHArray.Close();
+    
+    iContainerPHArray.ResetAndDestroy();
+    iContainerPHArray.Close();
+	
+    delete iRestoreWatcher;
+	delete iOnDemandAO;
+	delete iMdEHarvesterSession;
+	delete iMdESession;
+	delete iQueue;
+	delete iHarvesterPluginFactory;
+	delete iMdeObjectHandler;
+	delete iUnmountHandlerAO;
+	
+	delete iPropDefs;
+	
+	RMediaIdUtil::ReleaseInstance();
+    
+    REComSession::FinalClose();
+    }
+
+ // ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::ConstructL()
+    {
+    WRITELOG( "CHarvesterAO::ConstructL() - begin" );
+    
+    CActiveScheduler::Add( this );
+
+	User::LeaveIfError( iFs.Connect() );
+
+    // Setting up MdE Session
+	iMdESession = CMdESession::NewL( *this );
+	
+    RProcess process;
+ 	process.SetPriority( EPriorityBackground );
+ 	process.Close();
+ 	
+    // Setting up context Engine (initialization is ready when ContextInitializationStatus -callback is called)
+    iCtxEngine = CContextEngine::GetInstanceL( this ); // Create the context engine
+
+    iBackupSubscriber = CBackupSubscriber::NewL( *this );
+	
+	iUnmountHandlerAO = CUnmountHandlerAO::NewL( *this );
+	iUnmountHandlerAO->WaitForUnmountL();
+	
+	iHarvesterEventManager = CHarvesterEventManager::GetInstanceL();
+	
+	iRestoreWatcher = CRestoreWatcher::NewL();
+	
+	iHarvesterOomAO = CHarvesterOomAO::NewL( *this );
+	
+	iMediaIdUtil = &RMediaIdUtil::GetInstanceL();
+	
+    iBlacklist = CHarvesterBlacklist::NewL();
+    iBlacklist->OpenDatabase();
+    
+    // Setting up Harvester queue
+    iQueue = CHarvesterQueue::NewL( this, iBlacklist );
+    
+    // Setting up reharvester
+    iReHarvester = CReHarvesterAO::NewL();
+    iReHarvester->SetHarvesterQueue( iQueue );
+    
+    iHarvesterPluginFactory = CHarvesterPluginFactory::NewL();
+    iHarvesterPluginFactory->SetBlacklist( *iBlacklist );
+	
+    WRITELOG( "CHarvesterAO::ConstructL() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// LoadMonitorPluginsL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::LoadMonitorPluginsL()
+    {
+    WRITELOG( "CHarvesterAO::LoadMonitorPluginsL()" );
+    
+    RImplInfoPtrArray infoArray;
+    
+    TCleanupItem cleanupItem( MdsUtils::CleanupEComArray, &infoArray );
+    CleanupStack::PushL( cleanupItem );
+    
+    CMonitorPlugin::ListImplementationsL( infoArray );
+    TInt count( 0 );
+    count = infoArray.Count();
+    CMonitorPlugin* plugin = NULL;
+    
+    for ( TInt i = 0; i < count; i++ )
+        {
+        TUid uid = infoArray[i]->ImplementationUid();    // Create the plug-ins
+        plugin = NULL;
+        TRAPD( err, plugin = CMonitorPlugin::NewL( uid ) );
+        if ( err == KErrNone && plugin )
+            {
+            CleanupStack::PushL( plugin );
+            iMonitorPluginArray.AppendL( plugin ); // and add them to array
+            CleanupStack::Pop( plugin );
+            if ( uid.iUid == KFileMonitorPluginUid )
+                {
+                void* ptr = plugin;
+                iProcessOriginMapper = STATIC_CAST( MProcessOriginMapperInterface*, ptr );
+                }
+            }
+        else
+            {
+            WRITELOG( "CHarvesterAO::LoadMonitorPlugins() - Failed to load a monitor plugin!" );
+            delete plugin;
+            plugin = NULL;
+            }
+        }
+    
+    CleanupStack::PopAndDestroy( &infoArray ); // infoArray, results in a call to CleanupEComArray
+    }
+
+// ---------------------------------------------------------------------------
+// DeleteMonitorPlugins
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::DeleteMonitorPlugins()
+    {
+    WRITELOG( "CHarvesterAO::DeleteMonitorPlugins()" );
+    
+    iMonitorPluginArray.ResetAndDestroy();
+    }
+
+// ---------------------------------------------------------------------------
+// StartMonitoring
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::StartMonitoring()
+    {
+    WRITELOG( "CHarvesterAO::StartMonitoring()" );
+
+    TInt count( iMonitorPluginArray.Count() );  
+    
+    for ( TInt i = 0; i < count; i++ )
+        {
+        iMonitorPluginArray[i]->StartMonitoring( *iQueue, iMdESession, NULL, 
+        		iHarvesterPluginFactory );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// StopMonitoring
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::StopMonitoring()
+    {
+    WRITELOG( "CHarvesterAO::StopMonitoring()" );
+
+    TInt count( iMonitorPluginArray.Count() );
+    
+    for ( TInt i = 0; i < count; i++ )
+        {
+        iMonitorPluginArray[i]->StopMonitoring();
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// PauseMonitoring
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::PauseMonitoring()
+    {
+    WRITELOG( "CHarvesterAO::PauseMonitoring()" );
+    TInt count( iMonitorPluginArray.Count() );
+    
+    for ( TInt i = 0; i<count; i++ )
+        {
+        iMonitorPluginArray[i]->PauseMonitoring();
+        }
+    WRITELOG( "CHarvesterAO::PauseMonitoring() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// ResumeMonitoring
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::ResumeMonitoring()
+    {
+    WRITELOG( "CHarvesterAO::ResumeMonitoring()" );
+    
+    TInt count( iMonitorPluginArray.Count() );
+    
+    for ( TInt i=0; i < count; i++ )
+        {
+        iMonitorPluginArray[i]->ResumeMonitoring( *iQueue, iMdESession, NULL,
+        		iHarvesterPluginFactory );
+        }
+    WRITELOG( "CHarvesterAO::ResumeMonitoring() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// HandleUnmount
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::HandleUnmount( TUint32 aMediaId )
+	{
+	WRITELOG1( "CHarvesterAO::HandleUnmount(%d)", aMediaId );
+	
+    TUint32 mediaId(0);
+    TUint removed(0);
+    TInt err(0);
+    CHarvesterData* hd = NULL;
+    
+#ifdef _DEBUG
+    WRITELOG1( "CHarvesterAO::HandleUnmount() iReadyPHArray.Count() = %d", iReadyPHArray.Count() );
+#endif
+	if( iReadyPHArray.Count() > 0 )
+		{
+		TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypePlaceholder, iReadyPHArray.Count() ) );
+		TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypeMMC, iReadyPHArray.Count()) );
+		iReadyPHArray.ResetAndDestroy();
+		}
+
+#ifdef _DEBUG
+	WRITELOG1( "CHarvesterAO::HandleUnmount() iPHArray.Count() = %d", iPHArray.Count() );
+#endif
+   if( iPHArray.Count() > 0 )
+        {
+        for( TInt i=iPHArray.Count()-1; i>= 0; i--)
+            {
+            hd = iPHArray[i];
+            err = iMediaIdUtil->GetMediaId( hd->Uri(), mediaId );
+            
+            if( err == KErrNone && mediaId == aMediaId )
+                {
+                WRITELOG1( "CHarvesterAO::HandleUnmount() remove iPHArray %d", i);
+                delete hd;
+				hd = NULL;
+                iPHArray.Remove( i );
+                removed++;
+                }
+            }
+        WRITELOG1( "CHarvesterAO::HandleUnmount() DecreaseItemCountL iPHArray %d", removed);
+        TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypePlaceholder, removed) );
+        }
+   
+   removed = 0;
+   
+#ifdef _DEBUG
+   WRITELOG1( "CHarvesterAO::HandleUnmount() iContainerPHArray.Count() = %d", iContainerPHArray.Count() );
+#endif
+   if( iContainerPHArray.Count() > 0 )
+        {
+        for( TInt i=iContainerPHArray.Count()-1; i>= 0; i--)
+            {
+            hd = iContainerPHArray[i];
+            err = iMediaIdUtil->GetMediaId( hd->Uri(), mediaId );
+            
+            if( err == KErrNone && mediaId == aMediaId )
+                {
+                WRITELOG1( "CHarvesterAO::HandleUnmount() remove iContainerPHArray %d", i);
+                delete hd;
+				hd = NULL;
+                iContainerPHArray.Remove( i );
+                removed++;
+                }
+            }
+        WRITELOG1( "CHarvesterAO::HandleUnmount() DecreaseItemCountL iContainerPHArray %d", removed);
+        TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypePlaceholder, removed) );
+        }
+	
+	TUint count = iQueue->ItemsInQueue();
+	WRITELOG1( "CHarvesterAO::HandleUnmount() iQueue.Count() = %d", count );
+	if( count > 0 )
+	    {
+	    WRITELOG( "CHarvesterAO::HandleUnmount() remove iQueue" );
+	    TUint removed = iQueue->RemoveItems( aMediaId );
+	    WRITELOG1( "CHarvesterAO::HandleUnmount() removed iQueue = %d", removed );
+	    TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypePlaceholder, removed ) );
+        TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypeMMC, removed ) );
+	    }
+	
+	iMediaIdUtil->RemoveMediaId( aMediaId );
+	
+	removed = 0;
+	
+	RPointerArray<CHarvesterPluginInfo>& hpiArray = iHarvesterPluginFactory->GetPluginInfos();
+	if( hpiArray.Count() > 0 )
+		{
+		RArray<TItemId> placeholders;
+		
+		TUint32 mediaId(0);
+		TInt err(0);
+		
+		for( TInt i = hpiArray.Count(); --i >= 0; )
+			{
+			CHarvesterPluginInfo* hpi = hpiArray[i];
+			for( TInt j = hpi->iQueue.Count(); --j >= 0; )
+				{
+				CHarvesterData* hd = hpi->iQueue[j];
+				CMdEObject& mdeobj = hd->MdeObject();
+				
+				err = iMediaIdUtil->GetMediaId( mdeobj.Uri(), mediaId );
+	
+				if( mdeobj.Placeholder() && ( aMediaId == mediaId || err != KErrNone ))
+					{
+					removed++;
+					                    
+					TItemId id = mdeobj.Id();
+					placeholders.Append( id );
+					TRAP_IGNORE( iMdESession->CancelObjectL( mdeobj ) );
+					
+					delete hd;
+					hd = NULL;
+					hpi->iQueue.Remove(j);
+					
+					if( hpi->iQueue.Count() == 0 )
+						{
+						hpi->iQueue.Compress();
+						}
+					}
+				}
+			}
+		
+		if( removed )
+		    {
+            WRITELOG1( "CHarvesterAO::HandleUnmount() remove from plugins = %d", removed);
+            TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypePlaceholder, removed ) );
+            TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypeMMC, removed ) );
+		    }
+		
+		RArray<TItemId> results;
+		TRAP_IGNORE( iMdESession->RemoveObjectsL( placeholders, results, NULL ) );
+		results.Close();
+		placeholders.Close();
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// StartComposersL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::StartComposersL()
+    {
+    WRITELOG( "CHarvesterAO::StartComposersL()" );
+    
+    RImplInfoPtrArray infoArray;
+    TCleanupItem cleanupItem( MdsUtils::CleanupEComArray, &infoArray );
+    CleanupStack::PushL( cleanupItem );
+    CComposerPlugin::ListImplementationsL( infoArray );
+    TInt count( 0 );
+    count = infoArray.Count();
+
+    for ( TInt i=0; i < count; i++ )
+        {
+        TUid uid = infoArray[i]->ImplementationUid();
+        CComposerPlugin* plugin = NULL;
+        TRAPD(trapError, plugin = CComposerPlugin::NewL( uid ) );
+        if ( trapError != KErrNone )
+            {
+            WRITELOG( "CHarvesterAO::StartComposersL() - failed to create new composer" );
+            }
+        else
+            {
+            plugin->SetSession( iMdEHarvesterSession->SessionRef() );
+            iComposerPluginArray.AppendL( plugin );            
+            }
+        }
+            
+    CleanupStack::PopAndDestroy( &infoArray );    
+    WRITELOG( "CHarvesterAO::StartComposersL() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// StopComposers
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::StopComposers()
+    {
+    WRITELOG( "CHarvesterAO::StopComposers()" );
+    
+    for ( TInt i = iComposerPluginArray.Count(); --i >= 0; )
+        {
+        iComposerPluginArray[i]->RemoveSession();
+        }
+
+    WRITELOG( "CHarvesterAO::StopComposers() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// DeleteComposers
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::DeleteComposers()
+    {
+    WRITELOG( "CHarvesterAO::DeleteComposers()" );
+    
+    iComposerPluginArray.ResetAndDestroy();
+
+    WRITELOG( "CHarvesterAO::DeleteComposers() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// IsComposingReady
+// ---------------------------------------------------------------------------
+//
+TBool CHarvesterAO::IsComposingReady()
+    {
+    WRITELOG( "CHarvesterAO::IsComposingReady()" );
+    
+    for ( TInt i = iComposerPluginArray.Count(); --i >= 0; )
+        {
+        if ( iComposerPluginArray[i]->IsComposingComplete() == EFalse )
+            {
+            return EFalse;
+            }
+        }
+
+    WRITELOG( "CHarvesterAO::IsComposingReady() - end" );
+    return ETrue;
+    }
+
+// ---------------------------------------------------------------------------
+// ReadItemFromQueueL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::ReadItemFromQueueL()
+    {
+    WRITELOG( "CHarvesterAO::ReadItemFromQueueL()" );
+    
+    CHarvesterData* hd = iQueue->GetNextItem();
+    
+    if ( hd->ObjectType() == EPlaceholder )
+    	{
+    	while( hd != NULL &&
+				iPHArray.Count() < KPlaceholderQueueSize &&
+				hd->ObjectType() == EPlaceholder )
+    		{
+        	iPHArray.Append( hd );
+        	hd = iQueue->GetNextItem();
+    		}
+    	
+		if( hd )
+    		{
+	    	if( hd->ObjectType() == EPlaceholder )
+	    		{
+	        	iPHArray.Append( hd );
+	    		}
+	    	else
+	    		{
+	    		CheckFileExtensionAndHarvestL( hd );
+	    		}
+    		}
+			
+    	if( iPHArray.Count() > 0 )
+    		{
+	    	TRAPD( err, HandlePlaceholdersL( ETrue ) );
+
+	    	// make sure that when HandlePlaceholdersL leaves, iPHArray is cleared
+	    	if ( err != KErrNone )
+	    		{
+	    		iPHArray.ResetAndDestroy();
+	    		User::Leave( err );
+	    		}
+    		}
+    	}
+    else
+    	{
+        CheckFileExtensionAndHarvestL( hd );
+    	}
+    }
+
+// ---------------------------------------------------------------------------
+// HandlePlaceholdersL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::HandlePlaceholdersL( TBool aCheck )
+	{
+	WRITELOG( "CHarvesterAO::HandlePlaceholdersL()" );
+
+	RPointerArray<CMdEObject> mdeObjectArray;
+	CleanupClosePushL( mdeObjectArray );
+
+	TTimeIntervalSeconds timeOffsetSeconds = User::UTCOffset();
+	
+	TInt fastHarvestPlaceholderCount = 0;
+	
+	for (TInt i = iPHArray.Count() ; --i >= 0;)
+		{
+		CHarvesterData* hd = iPHArray[i];
+		
+		if( aCheck && iHarvesterPluginFactory->IsContainerFileL( hd->Uri() ) )
+			{
+			iContainerPHArray.Append( hd );
+			iPHArray.Remove( i );
+			continue;
+			}
+		TBuf<KObjectDefStrSize> objDefStr;
+		iHarvesterPluginFactory->GetObjectDefL( *hd, objDefStr );
+	    
+		if( objDefStr.Length() == 0 ||
+		    ( objDefStr == KInUse ) )
+			{
+			const TInt error( KErrUnknown );
+            // notify observer, notification is needed even if file is not supported
+            HarvestCompleted( hd->ClientId(), hd->Uri(), error );
+			delete hd;
+			hd = NULL;
+			iPHArray.Remove( i );
+			iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypeMMC, 1 );
+			continue;
+			}
+
+		CMdENamespaceDef& defNS = iMdESession->GetDefaultNamespaceDefL();
+		CMdEObjectDef& mdeObjectDef = defNS.GetObjectDefL( objDefStr );
+
+		CMdEObject* mdeObject = iMdESession->NewObjectL( mdeObjectDef, hd->Uri() );
+		
+		CPlaceholderData* phData = NULL;
+
+		if( hd->TakeSnapshot() )
+			{
+		    phData = CPlaceholderData::NewL();
+		    CleanupStack::PushL( phData );
+		    TEntry* entry = new (ELeave) TEntry();
+		    CleanupStack::PushL( entry );
+		    const TDesC& uri = hd->Uri();
+		    TInt err = iFs.Entry( uri, *entry );
+		    if ( err != KErrNone )
+		    	{
+		    	WRITELOG( "CHarvesterAO::HandlePlaceholdersL() - cannot create placeholder data object for camera. file does not exists" );
+	    		// notify observer
+	    	    HarvestCompleted( hd->ClientId(), hd->Uri(), err );
+				delete hd;
+				hd = NULL;
+				iPHArray.Remove( i );
+				iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypeMMC, 1 );
+				CleanupStack::PopAndDestroy( entry );
+				CleanupStack::PopAndDestroy( phData );
+				continue;
+		    	}
+		    phData->SetUri( uri );
+			phData->SetModified( entry->iModified );
+			phData->SetFileSize( entry->iSize );
+			CleanupStack::PopAndDestroy( entry );
+
+			TUint32 mediaId( 0 );
+			User::LeaveIfError( iMediaIdUtil->GetMediaId( uri, mediaId ) );
+			phData->SetMediaId( mediaId );
+			}
+		else
+			{
+			phData = static_cast<CPlaceholderData*> ( hd->ClientData() );
+		    if( !phData )
+		    	{
+		    	WRITELOG( "CHarvesterAO::HandlePlaceholdersL() - Placeholder data object NULL - abort" );
+		    	const TInt error( KErrUnknown );
+	    		// notify observer
+	    	    HarvestCompleted( hd->ClientId(), hd->Uri(), error );
+				delete hd;
+				hd = NULL;
+				iPHArray.Remove( i );
+				iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypeMMC, 1 );
+				continue;
+		    	}	
+			CleanupStack::PushL( phData );
+			}	
+		
+		// set media id
+		mdeObject->SetMediaId( phData->MediaId() );
+	    
+	    // set placeholder
+	    mdeObject->SetPlaceholder( ETrue );
+	    
+	    if( !iPropDefs )
+	    	{
+	    	iPropDefs = CHarvesterAoPropertyDefs::NewL( mdeObjectDef );
+	    	}
+
+	    // set file size
+    	mdeObject->AddUint32PropertyL( *iPropDefs->iSizePropertyDef, phData->FileSize() );
+
+	    // set creation date
+    	TTime localModifiedDate = phData->Modified() + timeOffsetSeconds;
+    	mdeObject->AddTimePropertyL( *iPropDefs->iCreationDatePropertyDef, localModifiedDate );
+
+	    // set modification date
+    	mdeObject->AddTimePropertyL( *iPropDefs->iLastModifiedDatePropertyDef, phData->Modified() );
+	    
+    	// set origin
+		mdeObject->AddUint8PropertyL( *iPropDefs->iOriginPropertyDef, hd->Origin() );
+    	
+    	CPlaceholderData* ph = static_cast<CPlaceholderData*>( hd->ClientData() );
+	    TInt isPreinstalled = ph->Preinstalled();
+	    if( isPreinstalled == MdeConstants::MediaObject::EPreinstalled )
+	    	{
+	    	WRITELOG("CHarvesterAO::HandlePlaceholdersL() - preinstalled");
+	    	mdeObject->AddInt32PropertyL( *iPropDefs->iPreinstalledPropertyDef, isPreinstalled );
+	    	}	    
+		
+	    hd->SetEventType( EHarvesterEdit );
+	    
+		// skip 
+		if( hd->TakeSnapshot() )
+			{
+			fastHarvestPlaceholderCount++;
+			hd->SetObjectType( EFastHarvest );
+			}
+		else
+			{
+			hd->SetClientData( NULL );
+			hd->SetObjectType( ENormal );
+			}
+		
+		hd->SetMdeObject( mdeObject );
+		
+		mdeObjectArray.Append( mdeObject );
+		
+	    CleanupStack::PopAndDestroy( phData );
+		
+		iReadyPHArray.Append( hd );
+		iPHArray.Remove( i );
+		}
+	
+	TInt objectCount = mdeObjectArray.Count();  
+	
+    if( objectCount > 0 )
+		{
+		// add object to mde
+		iMdEHarvesterSession->AutoLockL( mdeObjectArray );
+		const TInt addError( iMdESession->AddObjectsL( mdeObjectArray ) );
+		if( addError != KErrNone )
+		    {
+		    // If some error occures, retry
+		    iMdESession->AddObjectsL( mdeObjectArray );
+		    }
+
+		const TInt eventObjectCount = objectCount - fastHarvestPlaceholderCount;
+
+		if( eventObjectCount > 0 )
+			{
+			iHarvesterEventManager->IncreaseItemCount( EHEObserverTypePlaceholder, 
+					eventObjectCount );
+			iHarvesterEventManager->SendEventL( EHEObserverTypePlaceholder, EHEStateStarted, 
+					iHarvesterEventManager->ItemCount( EHEObserverTypePlaceholder ) );
+			}
+		
+#ifdef _DEBUG
+		for (TInt i = 0; i < mdeObjectArray.Count(); ++i)
+			{
+			CMdEObject* mdeObject = mdeObjectArray[i];
+			if(mdeObject->Id() == 0)
+				{
+				WRITELOG1( "CHarvesterAO::HandlePlaceholdersL() - failed to add: %S", &mdeObject->Uri() );
+				}
+			}
+#endif
+		}
+
+	iPHArray.ResetAndDestroy();
+	
+	CleanupStack::PopAndDestroy( &mdeObjectArray );
+	}
+
+// ---------------------------------------------------------------------------
+// CheckFileExtensionAndHarvestL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::CheckFileExtensionAndHarvestL( CHarvesterData* aHD )
+    {
+    TBool isError = EFalse;
+    CMdEObject* mdeObject = &aHD->MdeObject();
+    const TDesC& uri = aHD->Uri();
+    TBool objectExisted = ETrue;
+    
+    if( ! mdeObject )
+    	{
+    	objectExisted = EFalse;
+    	WRITELOG1( "CHarvesterAO::CheckFileExtensionAndHarvestL() - no mdeobject. URI: %S", &uri );
+	    TBuf<KObjectDefStrSize> objDefStr;
+		iHarvesterPluginFactory->GetObjectDefL( *aHD, objDefStr );
+		
+		if( objDefStr.Length() == 0 )
+			{
+			WRITELOG( "CHarvesterAO::CheckFileExtensionAndHarvestL() - cannot get object definition" );
+			isError = ETrue;
+			}
+		else if( objDefStr == KInUse )
+		    {
+            aHD->SetErrorCode( KMdEErrHarvestingFailed );
+            HarvestingCompleted( aHD );
+            return;
+		    }
+		else
+			{
+			TInt mdeError( KErrNone );
+			
+			// Check if non-binary object (messages) already exists in db 
+			if ( !aHD->IsBinary() )
+				{
+				CMdENamespaceDef& defNS = iMdESession->GetDefaultNamespaceDefL();
+				CMdEObjectDef& mdeObjectDef = defNS.GetObjectDefL( objDefStr );
+				TRAP( mdeError, mdeObject = iMdESession->OpenObjectL( aHD->Uri(), mdeObjectDef ));
+				}
+			
+			if ( mdeObject )
+				{
+				aHD->SetTakeSnapshot( EFalse );
+				aHD->SetEventType( EHarvesterEdit );
+				}
+			else
+				{
+				WRITELOG( "CHarvesterAO::CheckFileExtensionAndHarvestL() - getting mdeobject" );
+				TRAP( mdeError, mdeObject = iMdeObjectHandler->GetMetadataObjectL( *aHD, objDefStr ) );
+				}
+			TInt harvesterError = KErrNone;
+			if( mdeError != KErrNone)
+				{
+				WRITELOG1( "CHarvesterAO::CheckFileExtensionAndHarvestL() - cannot get mde object. error: %d", mdeError );
+				MdsUtils::ConvertTrapError( mdeError, harvesterError );
+				if( harvesterError == KMdEErrHarvestingFailedPermanent )
+					{
+					WRITELOG( "CHarvesterAO::CheckFileExtensionAndHarvestL() - permanent fail" );
+					isError = ETrue;
+					}
+				else if ( harvesterError == KMdEErrHarvestingFailed )
+					{
+	                WRITELOG( "CHarvesterAO::CheckFileExtensionAndHarvestL() - KMdEErrHarvestingFailed");
+	                aHD->SetErrorCode( KMdEErrHarvestingFailed );
+	                HarvestingCompleted( aHD );
+	                return;
+					}
+				}
+
+			if( !mdeObject )
+				{
+				WRITELOG( "CHarvesterAO::CheckFileExtensionAndHarvestL() - mde object is null. stop harvesting" );
+				isError = ETrue;
+				}
+			}
+		if( isError )
+			{
+            aHD->SetErrorCode( KMdEErrHarvestingFailedPermanent );
+            HarvestingCompleted( aHD );
+            return;
+			}
+		
+		CleanupStack::PushL( aHD );
+		
+		TUint32 mediaId( 0 );
+		if ( aHD->IsBinary() )
+			{
+			User::LeaveIfError( iMediaIdUtil->GetMediaId( uri, mediaId ) );
+			}
+		mdeObject->SetMediaId( mediaId );
+		
+		aHD->SetMdeObject( mdeObject );
+		CleanupStack::Pop( aHD );
+    	}
+    
+#ifdef _DEBUG
+    WRITELOG1("CHarvesterAO::CheckFileExtensionAndHarvestL() - mdeobject URI: %S", &mdeObject->Uri() );
+#endif
+	
+	aHD->SetPluginObserver( *this );
+	
+    if( objectExisted && aHD->EventType() == EHarvesterAdd )
+    	{
+    	iMdESession->RemoveObjectL( aHD->Uri() );
+    	}
+	
+	TInt pluginErr = KErrNone;
+    TRAPD( err, pluginErr = iHarvesterPluginFactory->HarvestL( aHD ));
+    if ( err != KErrNone )
+    	{
+    	WRITELOG1( "CHarvesterAO::CheckFileExtensionAndHarvestL() - plugin error: %d", err );
+    	if ( err == KErrInUse )
+    		{
+            WRITELOG( "CHarvesterAO::CheckFileExtensionAndHarvestL() - item in use" );
+            aHD->SetErrorCode( KMdEErrHarvestingFailed );
+            HarvestingCompleted( aHD );
+            return;
+    		}
+    	
+    	aHD->SetErrorCode( KMdEErrHarvestingFailedUnknown );
+    	HarvestingCompleted( aHD );
+    	return;
+    	}
+    
+    if( pluginErr != KErrNone )
+    	{
+    	aHD->SetErrorCode( KMdEErrHarvestingFailedUnknown );
+    	HarvestingCompleted( aHD );
+    	return;
+    	}
+    
+    WRITELOG1("CHarvesterAO::CheckFileExtensionAndHarvestL() - ends with error %d", pluginErr );
+    SetNextRequest( ERequestHarvest );
+    }
+
+// ---------------------------------------------------------------------------
+// HarvestingCompleted
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::HarvestingCompleted( CHarvesterData* aHD )
+    {
+    WRITELOG( "CHarvesterAO::HarvestingCompleted()" );
+    
+    if ( aHD->ErrorCode() == KErrNone )
+        {
+        iReHarvester->CheckItem( *aHD );
+
+        TInt mdeError = KErrNone;
+        if( !aHD->TakeSnapshot() )
+        	{
+        	WRITELOG( "CHarvesterAO::HarvestingCompleted() origin is not camera or clf" );
+            aHD->MdeObject().SetPlaceholder( EFalse );
+            TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypePlaceholder ) );
+        	TRAP( mdeError, iMdeObjectHandler->SetMetadataObjectL( *aHD ) );
+        	}
+
+        if(mdeError != KErrNone)
+        	{
+        	WRITELOG( "==============================ERROR===============================" );
+            WRITELOG( "CHarvesterAO::HarvestingCompleted() - cannot set metadata object" );
+            WRITELOG( "==============================ERROR done =========================" );
+            delete aHD;
+            aHD = NULL;
+
+            TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypeMMC, 1 ) );
+        	}
+        else
+        	{
+        	WRITELOG( "CHarvesterAO::HarvestingCompleted() mdeError == KErrNone" );
+	        if ( aHD->TakeSnapshot() && iCtxEngine )
+	            {
+	            WRITELOG( "CHarvesterAO::HarvestingCompleted() - Taking a context snapshot." );
+	            iCtxEngine->ContextSnapshot( *this, *aHD );
+	            }
+	        else
+	        	{
+	        	TLocationData* locData = aHD->LocationData();
+	        	if( locData )
+	        		{
+	        		WRITELOG( "CHarvesterAO::HarvestingCompleted() - Creating location object. " );
+	        		RLocationObjectManipulator lo;
+	        		
+	        		TInt loError = KErrNone;     		
+	        		loError = lo.Connect();
+	        		
+	        		if (loError == KErrNone)
+	        			{
+	        			TInt err = lo.CreateLocationObject( *locData, aHD->MdeObject().Id() );
+	        			if( err != KErrNone )
+	        				{
+	        				WRITELOG( "CHarvesterAO::HarvestingCompleted() - Location object creation failed!!!" );
+	        				}
+	        			}
+	        		else
+	        			{
+	        			WRITELOG( "CHarvesterAO::HarvestingCompleted() - LocationObjectManipulator connect failed!!!" );
+	        			}
+	        		
+	        		lo.Close();
+	        		}
+	        	
+	        	TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypeMMC, 1 ) );
+	        	
+				delete aHD;
+				aHD = NULL;
+	        	}
+        	}        
+        }
+    else
+        {
+#ifdef _DEBUG
+        WRITELOG( "==============================ERROR===============================" );
+        WRITELOG1( "CHarvesterAO::HarvestingCompleted() - not OK! Error: %d", aHD->ErrorCode() );
+#endif
+				 
+		const TInt errorCode( aHD->ErrorCode() );
+        if ( errorCode== KMdEErrHarvestingFailed )
+            {
+#ifdef _DEBUG
+            WRITELOG1("CHarvesterAO::HarvestingCompleted() - KMdEErrHarvestingFailed - %S - reharvesting", &aHD->Uri() );
+#endif
+            iReHarvester->AddItem( aHD );
+            }
+        else if ( errorCode == KMdEErrHarvestingFailedPermanent ||
+                errorCode == KMdEErrHarvestingFailedUnknown )
+            {
+            WRITELOG( "CHarvesterAO::HarvestingCompleted() - KMdEErrHarvestingFailedPermanent - no need to re-harvest!" );
+            
+            TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypeMMC, 1 ) );
+            
+            delete aHD;
+			aHD = NULL;
+			return;
+            }
+        else
+            {
+            WRITELOG1( "CHarvesterAO::HarvestingCompleted() - unknown error: %d", errorCode );
+            }
+        
+        WRITELOG( "==============================ERROR done =========================" );
+        }
+           
+    SetNextRequest( ERequestHarvest );
+    }
+
+// ---------------------------------------------------------------------------
+// HandleSessionOpened
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::HandleSessionOpened( CMdESession& aSession, TInt aError )
+    {
+    WRITELOG( "HarvesterThread::HandleSessionOpened()" );
+    if ( KErrNone == aError )
+        {
+        TBool isTNMDaemonEnabled( EFalse );
+        TRAP_IGNORE( CHarvesterCenRepUtil::IsThumbnailDaemonEnabledL( isTNMDaemonEnabled ) );
+
+        if( isTNMDaemonEnabled )
+            {
+            StartThumbAGDaemon();
+            }
+        
+        TRAPD( errorTrap, iMdEHarvesterSession = CMdEHarvesterSession::NewL( *iMdESession ) );
+        if ( errorTrap == KErrNone )
+            {
+        	iMdeSessionInitialized = ETrue;
+            }
+        else
+        	{
+            WRITELOG( "CHarvesterAO::HandleSessionOpened() - error creating mde harvester session" );
+        	}
+#ifdef _DEBUG
+        TRAP( errorTrap, PreallocateNamespaceL( aSession.GetDefaultNamespaceDefL() ) );
+        if ( errorTrap != KErrNone )
+            {
+            WRITELOG( "CHarvesterAO::HandleSessionOpened() - error loading default schema" );
+            }
+        
+        // Setting up monitor plugins
+        TRAP( errorTrap, LoadMonitorPluginsL() );
+        if ( errorTrap != KErrNone )
+            {
+            WRITELOG( "CHarvesterAO::HandleSessionOpened() - error loading monitor plugins" );
+            }
+            
+        TRAP( errorTrap, StartComposersL() );
+        if ( errorTrap != KErrNone )
+            {
+            WRITELOG( "CHarvesterAO::HandleSessionOpened() - couldn't start composer plugins" );
+            }
+#else
+        // The idea here is that all of these three methods needs to be called,
+        // even if some leave, thus the three TRAPs
+        TRAP_IGNORE( PreallocateNamespaceL( aSession.GetDefaultNamespaceDefL() ) );
+        TRAP_IGNORE( LoadMonitorPluginsL() );
+        TRAP_IGNORE( StartComposersL() );
+        
+#endif
+
+        if ( iContextEngineInitialized )
+            {
+            iCtxEngine->SetMdeSession( iMdESession );
+            }
+
+            // Starting monitor plugins
+        StartMonitoring();
+        
+        TRAP( errorTrap, iOnDemandAO = COnDemandAO::NewL( *iMdESession, *iQueue, 
+        		*iHarvesterPluginFactory, &iReadyPHArray ) );
+        if ( errorTrap == KErrNone )
+        	{
+        	TRAP( errorTrap, iOnDemandAO->StartL() );
+        	if ( errorTrap != KErrNone )
+        		{
+        		WRITELOG( "CHarvesterAO::HandleSessionOpened() - couldn't start on demand observer" );
+        		}
+        	}
+        else
+        	{
+        	WRITELOG( "CHarvesterAO::HandleSessionOpened() - couldn't create on demand observer" );
+        	}
+
+    	TRAPD( ohTrap, iMdeObjectHandler = CMdeObjectHandler::NewL( *iMdESession ) );
+    	if ( ohTrap != KErrNone )
+				{
+				WRITELOG( "CHarvesterAO::HandleSessionOpened() - ObjectHandler creation failed" );
+				}
+    	
+        // Initializing pause indicator
+        iServerPaused = EFalse;
+#ifdef _DEBUG
+        WRITELOG( "HarvesterThread::HandleSessionOpened() - Succeeded!" );
+        
+        TBool isRomScanEnabled( EFalse );
+        TRAP_IGNORE( CHarvesterCenRepUtil::IsRomScanEnabledL( isRomScanEnabled ) );
+        
+        if( isRomScanEnabled )
+            {
+            TRAP( errorTrap, BootRomScanL() );
+            if( errorTrap != KErrNone )
+                {
+                WRITELOG1( "CHarvesterAO::HandleSessionOpened() - BootRomScanL() returned error: %d", errorTrap );
+                }
+            }
+
+        TRAP( errorTrap, BootPartialRestoreScanL() );
+        if( errorTrap != KErrNone )
+        	{
+        	WRITELOG1( "CHarvesterAO::HandleSessionOpened() - BootPartialRestoreScanL() returned error: %d", errorTrap );
+        	}
+#else
+        // The idea here is that all of these three methods needs to be called,
+        // even if some leave, thus the two TRAPs
+        TBool isRomScanEnabled( EFalse );
+        TRAP_IGNORE( CHarvesterCenRepUtil::IsRomScanEnabledL( isRomScanEnabled ) );
+        
+        if( isRomScanEnabled )
+            {
+            TRAP_IGNORE( BootRomScanL() );
+            }
+        TRAP_IGNORE( BootPartialRestoreScanL() );
+#endif
+        }
+    else
+        {
+        iServerPaused = ETrue;    
+        WRITELOG1( "HarvesterThread::HandleSessionOpened() - Failed: %d!", aError );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// HandleSessionError
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::HandleSessionError( CMdESession& /*aSession*/, TInt aError )
+    {    
+    if ( KErrNone != aError )
+        {
+        WRITELOG1( "HarvesterThread::HandleSessionError() - Error: %d!", aError );        
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// ContextInitializationStatus
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::ContextInitializationStatus( TInt aErrorCode )
+    {
+    WRITELOG( "CHarvesterAO::ContextInitializationStatus()" );
+    
+    if ( KErrNone == aErrorCode )
+        {
+        WRITELOG( "HarvesterThread::ContextInitializationStatus() - Succeeded!" );
+        iContextEngineInitialized = ETrue;
+        if ( iMdeSessionInitialized )
+            {
+            iCtxEngine->SetMdeSession( iMdESession );
+            }
+        }
+    else
+        {
+        WRITELOG1( "HarvesterThread::ContextInitializationStatus() - Failed: %d!", aErrorCode );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// PauseHarvester
+// ---------------------------------------------------------------------------
+//
+TInt CHarvesterAO::PauseHarvester()
+    {
+    WRITELOG( "CHarvesterAO::PauseHarvester()" );
+
+    iServerPaused = ETrue;
+    
+    // Everything is paused
+    WRITELOG( "CHarvesterAO::PauseHarvester() - Moving paused state paused" );
+    
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// ResumeHarvester
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::ResumeHarvesterL()
+    {
+    WRITELOG( "CHarvesterAO::ResumeHarvesterL()" );
+    
+    iServerPaused = EFalse;
+    
+    SetNextRequest( ERequestHarvest );
+    }
+
+// ---------------------------------------------------------------------------
+// RunL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::RunL()
+    {
+    WRITELOG( "CHarvesterAO::RunL" );
+    // check if pause is requested
+    if ( this->iServerPaused && iNextRequest != ERequestPause && iNextRequest != ERequestResume)
+    	{
+    	iNextRequest = ERequestIdle;
+    	}
+    User::LeaveIfError( iStatus.Int() );
+    switch( iNextRequest )
+        {
+        // no more items in queue
+        case ERequestIdle:
+            {
+            WRITELOG( "CHarvesterAO::RunL - ERequestIdle" );
+            }
+        break;
+
+        // data added to harvester queue
+        case ERequestHarvest:
+            {
+            WRITELOG( "CHarvesterAO::RunL - ERequestHarvest" );
+            
+            // harvest new items first...
+            if ( iQueue->ItemsInQueue() > 0 )
+                {
+                if ( !iHarvesting )
+                	{
+                	iHarvesting = ETrue;
+                	iHarvesterEventManager->SendEventL( EHEObserverTypeOverall, EHEStateStarted );
+                	// This next line is for caching the harvester started event for observers registering
+                	// after harvesting has already started
+                	iHarvesterEventManager->IncreaseItemCount( EHEObserverTypeOverall, KCacheItemCountForEventCaching );
+                	}
+                
+                ReadItemFromQueueL();
+				SetNextRequest( ERequestHarvest );
+                }
+
+            // no more items to harvest
+            else
+                {
+                
+                // if container files to harvest, handle those
+                if( iContainerPHArray.Count() > 0 )
+                	{
+                	SetNextRequest( ERequestContainerPlaceholder );
+                	break;
+                	}
+                
+				if(iReadyPHArray.Count() > 0)
+            		{
+#ifdef _DEBUG
+            		WRITELOG1("CHarvesterAO::RunL - items in ready pharray: %d", iReadyPHArray.Count() );
+#endif   		
+            		for ( TInt i = iReadyPHArray.Count(); --i >= 0; )
+            			{
+                		CheckFileExtensionAndHarvestL( iReadyPHArray[i] );
+                		iReadyPHArray.Remove( i );
+            			}
+            		iReadyPHArray.Reset();
+            		}
+				
+				if ( iHarvesting && !UnharvestedItemsLeftInPlugins() && 
+					 !iReHarvester->ItemsInQueue() )
+					{
+					iHarvesting = EFalse;						
+					iHarvesterEventManager->SendEventL( EHEObserverTypeOverall, EHEStateFinished );
+					iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypeOverall, KCacheItemCountForEventCaching );
+				    iReadyPHArray.Compress();
+				    iContainerPHArray.Compress();
+				    iPHArray.Compress();
+					}
+
+                SetNextRequest( ERequestIdle );
+                }
+            }
+        break;
+        
+        case ERequestContainerPlaceholder:
+        	{
+#ifdef _DEBUG
+        	WRITELOG( "CHarvesterAO::RunL - ERequestContainerPlaceholder" );
+        	WRITELOG1( "CHarvesterAO::RunL - Items in container pharray: %d", iContainerPHArray.Count() );
+#endif
+        	TInt count = iContainerPHArray.Count() > KContainerPlaceholderQueueSize ? KContainerPlaceholderQueueSize : iContainerPHArray.Count();
+        	TInt i = 0;
+        	while( i < count )
+        		{
+        		CHarvesterData* hd = iContainerPHArray[0];
+        		iPHArray.Append( hd );
+        		iContainerPHArray.Remove( 0 );
+        		i++;
+        		}
+        	TRAPD( err, HandlePlaceholdersL( EFalse ) );
+
+	    	// make sure that when HandlePlaceholdersL leaves, iPHArray is cleared
+	    	if ( err != KErrNone )
+	    		{
+	    		iPHArray.ResetAndDestroy();
+	    		User::Leave( err );
+	    		}
+	    	SetNextRequest( ERequestHarvest );
+        	}
+        break;
+        
+        // pause request
+        case ERequestPause:
+            {
+            WRITELOG( "CHarvesterAO::RunL - ERequestPause" );
+            User::LeaveIfError( PauseHarvester() );
+            iHarvesterEventManager->SendEventL( EHEObserverTypeOverall, EHEStatePaused );
+            if( iHarvesterStatusObserver )
+            	{
+            	iHarvesterStatusObserver->PauseReady( KErrNone );
+            	}
+            }
+        break;
+
+        // resume request
+        case ERequestResume:
+            {
+            WRITELOG( "CHarvesterAO::RunL - ERequestResume" );
+            ResumeHarvesterL();
+            iHarvesterEventManager->SendEventL( EHEObserverTypeOverall, EHEStateResumed );
+            if( iHarvesterStatusObserver )
+            	{
+                iHarvesterStatusObserver->ResumeReady( KErrNone );
+            	}
+            SetNextRequest( ERequestHarvest );
+            }
+        break;
+        
+        default:
+            {
+            WRITELOG( "CHarvesterAO::RunL - Not supported request" );
+            User::Leave( KErrNotSupported );
+            }
+        break;
+        }
+    }
+    
+// ---------------------------------------------------------------------------
+// DoCancel
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::DoCancel()
+    {
+    WRITELOG( "CHarvesterAO::DoCancel()" );
+    }
+    
+// ---------------------------------------------------------------------------
+// RunError
+// ---------------------------------------------------------------------------
+//
+TInt CHarvesterAO::RunError( TInt aError )
+    {
+    WRITELOG( "CHarvesterAO::RunError" );
+    switch( iNextRequest )
+        {
+        case ERequestHarvest:
+            {
+            WRITELOG( "CHarvesterAO::RunError - state ERequestHarvest" );
+            }
+        break;
+        
+        case ERequestPause:
+            {
+            WRITELOG( "CHarvesterAO::RunError - state ERequestPause" );
+            if ( aError == KErrNotReady )
+                {
+                SetNextRequest( ERequestPause );
+                }
+            else if( iHarvesterStatusObserver )
+            	{
+                iHarvesterStatusObserver->PauseReady( aError );
+            	}
+            }
+        break;
+        
+        case ERequestResume:
+            {
+            WRITELOG( "CHarvesterAO::RunError - state ERequestResume" );
+            if( iHarvesterStatusObserver )
+            	{
+                iHarvesterStatusObserver->ResumeReady( aError );
+            	}
+            }
+        break;
+        
+        default:
+            {
+            WRITELOG( "CHarvesterAO::RunError - unknown state" );
+            }
+        break;
+        }
+        
+    return KErrNone;
+    }
+    
+// ---------------------------------------------------------------------------
+// SetNextRequest
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::SetNextRequest( TRequest aRequest )
+    {
+    WRITELOG( "CHarvesterAO::SetNextRequest" );
+    iNextRequest = aRequest;
+            
+    if ( !IsActive() )
+        {
+        iStatus = KRequestPending;
+        SetActive();
+        TRequestStatus* ptrStatus = &iStatus;
+        User::RequestComplete( ptrStatus, KErrNone );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// IsServerPaused
+// ---------------------------------------------------------------------------
+//
+TBool CHarvesterAO::IsServerPaused()
+    {
+    WRITELOG( "CHarvesterAO::IsServerPaused" );
+    return iServerPaused;
+    }
+
+// ---------------------------------------------------------------------------
+// From MBackupRestoreObserver.
+// Called by CBlacklistBackupSubscriberAO when
+// Backup&Restore is backing up or restoring.
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::BackupRestoreStart()
+    {
+    // close blacklist database connection
+    WRITELOG( "CHarvesterAO::BackupRestoreStart" );
+    iBlacklist->CloseDatabase();
+    }
+
+// ---------------------------------------------------------------------------
+// From MBackupRestoreObserver.
+// Called by CBlacklistBackupSubscriberAO when
+// Backup&Restore has finished backup or restore.
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::BackupRestoreReady()
+    {
+    // restart blacklist database connection
+    WRITELOG( "CHarvesterAO::BackupRestoreReady" );
+    iBlacklist->OpenDatabase();
+    }
+
+// ---------------------------------------------------------------------------
+// HarvestFile
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::HarvestFile( const RMessage2& aMessage )
+    {
+    WRITELOG( "CHarvesterAO::HarvestFile" );
+    const TInt KParamUri = 0;
+    const TInt KParamAlbumIds = 1;
+    const TInt KParamAddLocation = 2;
+    
+    // read uri
+    HBufC* uri = HBufC::New( KMaxFileName );
+    
+    if ( ! uri )
+        {
+        WRITELOG( "CHarvesterAO::HarvestFile - out of memory creating uri container" );
+        if (!aMessage.IsNull())
+            {
+            aMessage.Complete( KErrNoMemory );
+            }
+        return;
+        }
+    
+    TPtr uriPtr( uri->Des() );
+    TInt err = aMessage.Read( KParamUri, uriPtr );
+    if ( err != KErrNone )
+        {
+        WRITELOG1( "CHarvesterAO::HarvestFile - error in reading aMessage (uri): %d", err );
+        if (!aMessage.IsNull())
+            {
+            aMessage.Complete( err );
+            }
+        delete uri;
+        uri = NULL;
+        return;
+        }
+    WRITELOG1( "CHarvesterAO::HarvestFile - uri: %S", uri );
+    
+    // read album ids
+    RArray<TItemId> albumIds;
+    const TInt KAlbumIdsLength = aMessage.GetDesLength( KParamAlbumIds );
+    if ( KAlbumIdsLength > 0 )
+        {
+        HBufC8* albumIdBuf = HBufC8::New( KAlbumIdsLength );
+        if ( !albumIdBuf )
+            {
+            WRITELOG( "CHarvesterAO::HarvestFile - error creating album id buffer." );
+            if (!aMessage.IsNull())
+                {
+                aMessage.Complete( KErrNoMemory );
+                }
+            delete uri;
+            uri = NULL;
+            return;
+            }
+        TPtr8 ptr( albumIdBuf->Des() );
+        err = aMessage.Read( KParamAlbumIds, ptr );
+        if ( err != KErrNone )
+            {
+            WRITELOG1( "CHarvesterAO::HarvestFile - error in reading aMessage (albumIds): %d", err );
+            delete albumIdBuf;
+            albumIdBuf = NULL;
+            delete uri;
+            uri = NULL;
+            if (!aMessage.IsNull())
+                {
+                aMessage.Complete( err );
+                }
+            return;
+            }
+
+        TRAPD( err, DeserializeArrayL( ptr, albumIds ) );
+        if ( err != KErrNone )
+            {
+            WRITELOG1( "CHarvesterAO::HarvestFile - error in reading album id array: %d", err );
+            delete albumIdBuf;
+            albumIdBuf = NULL;
+            delete uri;
+            uri = NULL;
+            if (!aMessage.IsNull())
+                {
+                aMessage.Complete( err );
+                }
+            return;
+            }
+
+#ifdef _DEBUG
+        const TInt count = albumIds.Count();
+        for (TInt i = 0; i < count; ++i)
+        	{
+        	WRITELOG2( "RHarvesterClient::HarvestFile - album id[%d]: %d", i, albumIds[i] );
+        	}
+#endif
+        
+        delete albumIdBuf;
+        albumIdBuf = NULL;
+        
+        WRITELOG1( "CHarvesterAO::HarvestFile - album id count: %d", albumIds.Count() );
+        }
+    
+    TBool addLocation;    
+    TPckg<TBool> location( addLocation );	
+		err = aMessage.Read(KParamAddLocation, location);
+		if ( err != KErrNone )
+			{
+			WRITELOG1( "CHarvesterAO::HarvestFile - error in reading aMessage (addLocation): %d", err );
+			delete uri;
+			uri = NULL;
+			if (!aMessage.IsNull())
+				{
+				aMessage.Complete( err );
+				}
+			return;
+			}	
+	
+		WRITELOG1( "RHarvesterClient::HarvestFile - add location: %d", addLocation );
+    
+    CHarvesterData* hd = NULL;
+    TRAP( err, hd = CHarvesterData::NewL( uri ) );
+    if ( err != KErrNone )
+        {
+        WRITELOG( "CHarvesterAO::HarvestFile - creating harvUri failed" );
+        albumIds.Close();
+        delete uri;
+        uri = NULL;
+        if (!aMessage.IsNull())
+            {
+            aMessage.Complete( err );
+            }
+        return;
+        }
+
+    hd->SetEventType( EHarvesterAdd );
+    hd->SetOrigin( MdeConstants::Object::ECamera );
+    hd->SetObjectType( EPlaceholder );
+    hd->SetTakeSnapshot( ETrue );
+    hd->SetClientId( aMessage.Identity() );
+    hd->SetAddLocation( addLocation );
+
+    CHarvestClientData* clientData = CHarvestClientData::New();
+    if ( clientData )
+        {
+        clientData->SetAlbumIds( albumIds );
+        hd->SetClientData( clientData ); // ownership is transferred
+        }
+    else
+        {
+        WRITELOG( "CHarvesterAO::HarvestFile - creating clientData failed" );
+        }
+
+    if( iQueue && hd )
+        {
+        iQueue->Append( hd );
+        
+        // signal to start harvest if harvester idles
+        if ( !IsServerPaused() )
+            {
+            SetNextRequest( CHarvesterAO::ERequestHarvest );
+            }
+        }
+    else
+        {
+        err = KErrUnknown;
+        }
+    
+    if (!aMessage.IsNull())
+        {
+        aMessage.Complete( err );
+        }
+    
+    albumIds.Close();
+    }
+  
+// ---------------------------------------------------------------------------
+// HarvestFileWithUID
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::HarvestFileWithUID( const RMessage2& aMessage )
+    {
+    WRITELOG( "CHarvesterAO::HarvestFileWithUID" );
+    const TInt KParamUri = 0;
+    const TInt KParamAlbumIds = 1;
+    const TInt KParamAddLocation = 2;
+    
+    // read uri
+    HBufC* uri = HBufC::New( KMaxFileName );
+    
+    if ( ! uri )
+        {
+        WRITELOG( "CHarvesterAO::HarvestFileWithUID - out of memory creating uri container" );
+        if (!aMessage.IsNull())
+            {
+            aMessage.Complete( KErrNoMemory );
+            }
+        return;
+        }
+    
+    TPtr uriPtr( uri->Des() );
+    TInt err = aMessage.Read( KParamUri, uriPtr );
+    if ( err != KErrNone )
+        {
+        WRITELOG1( "CHarvesterAO::HarvestFileWithUID - error in reading aMessage (uri): %d", err );
+        if (!aMessage.IsNull())
+            {
+            aMessage.Complete( err );
+            }
+        delete uri;
+        uri = NULL;
+        return;
+        }
+    WRITELOG1( "CHarvesterAO::HarvestFileWithUID - uri: %S", uri );
+    
+    // read album ids
+    RArray<TItemId> albumIds;
+    const TInt KAlbumIdsLength = aMessage.GetDesLength( KParamAlbumIds );
+    if ( KAlbumIdsLength > 0 )
+        {
+        HBufC8* albumIdBuf = HBufC8::New( KAlbumIdsLength );
+        if ( !albumIdBuf )
+            {
+            WRITELOG( "CHarvesterAO::HarvestFileWithUID - error creating album id buffer." );
+            if (!aMessage.IsNull())
+                {
+                aMessage.Complete( KErrNoMemory );
+                }
+            delete uri;
+            uri = NULL;
+            return;
+            }
+        TPtr8 ptr( albumIdBuf->Des() );
+        err = aMessage.Read( KParamAlbumIds, ptr );
+        if ( err != KErrNone )
+            {
+            WRITELOG1( "CHarvesterAO::HarvestFileWithUID - error in reading aMessage (albumIds): %d", err );
+            delete albumIdBuf;
+            albumIdBuf = NULL;
+            delete uri;
+            uri = NULL;
+            if (!aMessage.IsNull())
+                {
+                aMessage.Complete( err );
+                }
+            return;
+            }
+
+        TRAPD( err, DeserializeArrayL( ptr, albumIds ) );
+        if ( err != KErrNone )
+            {
+            WRITELOG1( "CHarvesterAO::HarvestFileWithUID - error in reading album id array: %d", err );
+            delete albumIdBuf;
+            albumIdBuf = NULL;
+            delete uri;
+            uri = NULL;
+            if (!aMessage.IsNull())
+                {
+                aMessage.Complete( err );
+                }
+            return;
+            }
+
+        #ifdef _DEBUG
+        const TInt count = albumIds.Count();
+        for (TInt i = 0; i < count; ++i)
+            {
+            WRITELOG2( "RHarvesterClient::HarvestFileWithUID - album id[%d]: %d", i, albumIds[i] );
+            }
+        #endif
+        
+        delete albumIdBuf;
+        albumIdBuf = NULL;
+		
+#ifdef _DEBUG        
+        WRITELOG1( "CHarvesterAO::HarvestFileWithUID - album id count: %d", albumIds.Count() );
+#endif
+        }
+    
+    TBool addLocation;    
+    TPckg<TBool> location( addLocation );   
+        err = aMessage.Read(KParamAddLocation, location);
+        if ( err != KErrNone )
+            {
+            WRITELOG1( "CHarvesterAO::HarvestFileWithUID - error in reading aMessage (addLocation): %d", err );
+            delete uri;
+            uri = NULL;
+            if (!aMessage.IsNull())
+                {
+                aMessage.Complete( err );
+                }
+            return;
+            }   
+    
+        WRITELOG1( "RHarvesterClient::HarvestFileWithUID - add location: %d", addLocation );
+    
+    CHarvesterData* hd = NULL;
+    TRAP( err, hd = CHarvesterData::NewL( uri ) );
+    if ( err != KErrNone )
+        {
+        WRITELOG( "CHarvesterAO::HarvestFileWithUID - creating harvUri failed" );
+        albumIds.Close();
+        delete uri;
+        uri = NULL;
+        if (!aMessage.IsNull())
+            {
+            aMessage.Complete( err );
+            }
+        return;
+        }
+
+    hd->SetEventType( EHarvesterAdd );
+    hd->SetOrigin( MdeConstants::Object::EOther );
+    hd->SetObjectType( EPlaceholder );
+    hd->SetTakeSnapshot( ETrue );
+    hd->SetClientId( aMessage.Identity() );
+    hd->SetAddLocation( addLocation );
+
+    CHarvestClientData* clientData = CHarvestClientData::New();
+    if ( clientData )
+        {
+        clientData->SetAlbumIds( albumIds );
+        hd->SetClientData( clientData ); // ownership is transferred
+        }
+    else
+        {
+        WRITELOG( "CHarvesterAO::HarvestFileWithUID - creating clientData failed" );
+        }
+
+    if( iQueue && hd )
+    	{
+    	iQueue->Append( hd );
+
+    	// signal to start harvest if harvester idles
+    	if ( !IsServerPaused() )
+    		{
+    		SetNextRequest( CHarvesterAO::ERequestHarvest );
+    		}
+    	}
+    else
+        {
+        err = KErrUnknown;
+        }
+
+    if (!aMessage.IsNull())
+        {
+        aMessage.Complete( err );
+        }
+    
+    albumIds.Close();
+    }
+
+// ---------------------------------------------------------------------------
+// RegisterProcessOrigin()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::RegisterProcessOrigin( const RMessage2& aMessage )
+    {
+    WRITELOG( "CHarvesterAO::RegisterProcessOrigin" );
+    
+    if ( !iProcessOriginMapper )
+        {
+        WRITELOG( "CHarvesterAO::RegisterProcessOrigin - mapper not available." );
+        if (!aMessage.IsNull())
+            {
+            aMessage.Complete( KErrNotSupported );
+            }
+        return;
+        }
+
+    TUid processId = { 0 };
+    processId.iUid = aMessage.Int0();
+    if ( MdsUtils::IsValidProcessId( processId ) )
+        {
+        WRITELOG1( "CHarvesterAO::RegisterProcessOrigin - error reading processId. Read: %d", processId.iUid );
+        if (!aMessage.IsNull())
+            {
+            aMessage.Complete( KErrCorrupt );
+            }
+        return;
+        }
+    
+    // read origin
+
+    TOrigin origin = STATIC_CAST( TOrigin, aMessage.Int1() );
+    WRITELOG1( "CHarvesterAO::RegisterProcessOrigin - origin: %d", origin );
+    if ( origin < 0 )
+        {
+        WRITELOG( "CHarvesterAO::RegisterProcessOrigin - error reading origin from aMessage (negative)." );
+        if (!aMessage.IsNull())
+            {
+            aMessage.Complete( KErrCorrupt );
+            }
+        return;
+        }
+
+    TRAPD( err, iProcessOriginMapper->RegisterProcessL( processId, origin ) );
+    if ( err != KErrNone )
+        {
+        WRITELOG1( "CHarvesterAO::RegisterProcessOrigin - error registering mapping: %d", err );
+        if (!aMessage.IsNull())
+            {
+            aMessage.Complete( err );
+            }
+        return;
+        }
+    if (!aMessage.IsNull())
+        {
+        aMessage.Complete( KErrNone );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// UnregisterProcessOrigin()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::UnregisterProcessOrigin( const RMessage2& aMessage )
+    {
+    WRITELOG( "CHarvesterAO::UnregisterProcessOrigin" );
+    
+    if ( !iProcessOriginMapper )
+        {
+        WRITELOG( "CHarvesterAO::RegisterProcessOrigin - mapper not available." );
+        if (!aMessage.IsNull())
+            {
+            aMessage.Complete( KErrNotSupported );
+            }
+        return;
+        }
+
+    TUid processId = { 0 };
+    processId.iUid = aMessage.Int0();
+    if ( MdsUtils::IsValidProcessId( processId ) )
+        {
+        WRITELOG1( "CHarvesterAO::UnregisterProcessOrigin - error reading processId. Read: %d", processId.iUid );
+        if (!aMessage.IsNull())
+            {
+            aMessage.Complete( KErrCorrupt );
+            }
+        return;
+        }
+    
+    TRAPD( err, iProcessOriginMapper->UnregisterProcessL( processId ) );
+    if ( err != KErrNone )
+        {
+        WRITELOG1( "CHarvesterAO::UnregisterProcessOrigin - error unregistering mapping: %d", err );
+        if (!aMessage.IsNull())
+            {
+            aMessage.Complete( err );
+            }
+        return;
+        }
+    if (!aMessage.IsNull())
+        {
+        aMessage.Complete( KErrNone );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// RegisterHarvestComplete()
+// ---------------------------------------------------------------------------
+//
+TInt CHarvesterAO::RegisterHarvestComplete( const CHarvesterServerSession& aSession, const RMessage2& aMessage )
+    {
+    WRITELOG( "CHarvesterAO::RegisterHarvestComplete" );
+    
+    return iHarvestFileMessages.Append( 
+    		THarvestFileRequest( aSession, aMessage ) );
+    }
+
+// ---------------------------------------------------------------------------
+// UnregisterHarvestComplete()
+// ---------------------------------------------------------------------------
+//
+TInt CHarvesterAO::UnregisterHarvestComplete( const CHarvesterServerSession& aSession )
+    {    
+    WRITELOG( "CHarvesterAO::UnregisterHarvestComplete" );
+    
+    TInt err( KErrNotFound );
+    if ( iHarvestFileMessages.Count() > 0 )
+        {
+        for ( TInt i = iHarvestFileMessages.Count()-1; i >= 0; --i )
+            {
+            THarvestFileRequest& req = iHarvestFileMessages[i];
+            
+            if ( req.iMessage.IsNull() )
+            	{
+            	iHarvestFileMessages.Remove( i );
+            	continue;
+            	}
+            
+            //if (aMessage.Identity() == msg.Identity())
+            if( &req.iSession == &aSession )
+            	{
+            	err = KErrNone;
+	            if (!req.iMessage.IsNull())
+	            	{
+	            	// cancels found request
+	            	req.iMessage.Complete( KErrCancel );
+	            	}
+                iHarvestFileMessages.Remove( i );
+                
+                if( iHarvestFileMessages.Count() == 0 )
+            		{
+            		iHarvestFileMessages.Compress();
+            		}
+            	}
+            }
+        }
+
+    return err;
+    }
+
+// ---------------------------------------------------------------------------
+// RegisterHarvesterEvent()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::RegisterHarvesterEvent( const RMessage2& aMessage )
+    {
+    WRITELOG( "CHarvesterAO::RegisterHarvesterEvent" );
+
+    TRAPD( err, iHarvesterEventManager->RegisterEventObserverL( aMessage ) );
+    aMessage.Complete( err );
+    }
+
+// ---------------------------------------------------------------------------
+// UnregisterHarvesterEvent()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::UnregisterHarvesterEvent( const RMessage2& aMessage )
+    {
+    WRITELOG( "CHarvesterAO::UnregisterHarvesterEvent" );
+    
+    const TInt err = iHarvesterEventManager->UnregisterEventObserver( aMessage );
+    aMessage.Complete( err );
+    }
+
+void CHarvesterAO::GetLastObserverId( const RMessage2& aMessage )
+	{
+	WRITELOG( "CHarvesterAO::GetLastObserverId" );
+	
+	TUint observerId = iHarvesterEventManager->GetLastClientId();
+	
+	TPckg<TUint> pckgId( observerId );
+	aMessage.Write( 0, pckgId );
+	aMessage.Complete( KErrNone );
+	}
+
+// ---------------------------------------------------------------------------
+// ContextSnapshotStatus
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::ContextSnapshotStatus( CHarvesterData* aHD )
+    {
+    WRITELOG( "CHarvesterAO::ContextSnapshotStatus()" );
+    
+    HarvestCompleted( aHD->ClientId(), aHD->Uri(), aHD->ErrorCode() );
+
+    const TInt errorCode = aHD->ErrorCode();
+    if( errorCode != KErrNone )
+    	{
+        WRITELOG1( "CHarvesterAO::ContextSnapshotStatus() - error occurred: %d", errorCode );    	
+    	}
+    else
+    	{
+        WRITELOG( "CHarvesterAO::ContextSnapshotStatus() - successfully completed" );
+        if( aHD->Origin() == MdeConstants::Object::ECamera )
+        	{
+            aHD->MdeObject().SetPlaceholder( EFalse );
+        	TRAPD(mdeError, iMdeObjectHandler->SetMetadataObjectL( *aHD ) );
+        	if(mdeError != KErrNone)
+            	{
+            	WRITELOG( "==============================ERROR===============================" );
+                WRITELOG( "CHarvesterAO::HarvestingCompleted() - cannot set metadata object" );
+                WRITELOG( "==============================ERROR done =========================" );
+            	}
+        	}
+    	}
+
+    delete aHD;
+    }
+
+// ---------------------------------------------------------------------------
+// IsConnectedToMde
+// ---------------------------------------------------------------------------
+//
+TBool CHarvesterAO::IsConnectedToMde()
+    {
+    return iMdESession != NULL;
+    }
+
+// ---------------------------------------------------------------------------
+// HarvestCompleted
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::HarvestCompleted( TUid aClientId, const TDesC& aUri, TInt aErr )
+	{
+	const TInt KParamUri = 0;
+    // check if fast harvested file
+    if ( iHarvestFileMessages.Count() > 0 )
+        {
+        for ( TInt i = iHarvestFileMessages.Count()-1; i >= 0; --i )
+            {
+            RMessage2& msg = iHarvestFileMessages[i].iMessage;
+            if ( aClientId == msg.Identity() )
+                {
+                WRITELOG1( "CHarvesterAO::HarvestingCompleted() - Completing Fast Harvest request! Error code: %d", aErr );
+                if (!msg.IsNull())
+                	{
+                	msg.Write( KParamUri, aUri );
+                	msg.Complete( aErr );
+                	}
+                else
+                	{
+                	WRITELOG("CHarvesterAO::HarvestingCompleted() NOT COMPLETING AS msg->iMessage->IsNull returns ETrue");
+                	} 
+                iHarvestFileMessages.Remove( i );
+                }
+            }
+        }
+	}
+
+void CHarvesterAO::BootRomScanL()
+	{
+	WRITELOG("CHarvesterAO::BootRomScanL()");
+
+    if( !iMdeSessionInitialized )
+        {
+        return;
+        }
+	
+	RPointerArray<TScanItem> scanItems;
+	TCleanupItem cleanupItem( MdsUtils::CleanupPtrArray<TScanItem>, &scanItems );
+    CleanupStack::PushL( cleanupItem );
+
+	CHarvesterCenRepUtil::GetScanItemsL( scanItems );
+
+	RPointerArray<HBufC> ignorePaths;
+	TCleanupItem cleanupItem2( MdsUtils::CleanupPtrArray<HBufC>, &ignorePaths );
+    CleanupStack::PushL( cleanupItem2 );
+
+	CHarvesterCenRepUtil::GetIgnoredScanPathsL( ignorePaths );
+
+	BootScanL( scanItems, ignorePaths, ETrue );
+
+	CleanupStack::PopAndDestroy( &ignorePaths );
+	CleanupStack::PopAndDestroy( &scanItems );
+	}
+
+void CHarvesterAO::BootPartialRestoreScanL()
+	{
+	// check if partial restore was done before last boot
+	TBool partialRestore = iRestoreWatcher->Register();
+		
+	if ( !partialRestore )
+		{
+		return;
+		}
+	
+	if( !iMdeSessionInitialized )
+	    {
+	    return;
+	    }
+	
+	iMdEHarvesterSession->ChangeCDriveMediaId();
+
+	WRITELOG("CHarvesterAO::BootPartialRestoreScanL() - partial restore");
+		
+	RPointerArray<TScanItem> scanItems;
+	TCleanupItem cleanupItem( MdsUtils::CleanupPtrArray<TScanItem>, &scanItems );
+    CleanupStack::PushL( cleanupItem );
+
+	CHarvesterCenRepUtil::GetPartialRestorePathsL( scanItems );
+
+	RPointerArray<HBufC> ignorePaths;
+	TCleanupItem cleanupItem2( MdsUtils::CleanupPtrArray<HBufC>, &ignorePaths );
+    CleanupStack::PushL( cleanupItem2 );
+
+	CHarvesterCenRepUtil::GetIgnoredPartialRestorePathsL( ignorePaths );
+
+	BootScanL( scanItems, ignorePaths, EFalse );
+	
+	WRITELOG("CHarvesterAO::BootPartialRestoreScanL() - iRestoreWatcher->UnregisterL()");
+	iRestoreWatcher->UnregisterL();
+
+	CleanupStack::PopAndDestroy( &ignorePaths );
+	CleanupStack::PopAndDestroy( &scanItems );
+	}
+
+TBool CHarvesterAO::IsDescInArray(const TPtrC& aSearch, const RPointerArray<HBufC>& aArray)
+	{
+	const TInt count = aArray.Count();
+	
+	for( TInt i = 0; i < count; i++ )
+		{
+		const TDesC& ignorePath = aArray[i]->Des();
+		
+		TInt result = MdsUtils::Compare( aSearch, ignorePath );
+		
+		if( result == 0 )
+			{
+			return ETrue;
+			}
+		}
+
+	return EFalse;
+	}
+
+void CHarvesterAO::BootScanL( RPointerArray<TScanItem>& aScanItems, 
+		const RPointerArray<HBufC>& aIgnorePaths,
+        TBool aCheckDrive )
+	{
+	WRITELOG("CHarvesterAO::BootScanL() - begin");
+
+	TVolumeInfo volumeInfo;
+	iFs.Volume( volumeInfo, EDriveC );
+
+	iMdEHarvesterSession->SetFilesToNotPresent( volumeInfo.iUniqueID, ETrue );
+	
+	_LIT( KDirectorySeparator, "\\" );
+
+#ifdef _DEBUG
+	WRITELOG1("CHarvesterAO::BootScanL() - item count: %d", aScanItems.Count() );
+#endif
+	
+	RPointerArray<CHarvesterData> hdArray;
+	CleanupClosePushL( hdArray );
+	
+	while( aScanItems.Count() > 0 )
+		{
+		HBufC* folder = aScanItems[0]->iPath;
+		TUint32 preinstalled = aScanItems[0]->iPreinstalled;
+
+		CDir* directory = NULL;
+		TInt error = iFs.GetDir( folder->Des(), KEntryAttDir, KHarvesterGetDirFlags, directory );
+		
+		if ( error == KErrNone )
+			{
+			CleanupStack::PushL( directory );
+
+			TInt count = directory->Count();
+			
+			TUint32 mediaId( 0 );
+			
+			if( count > 0 )
+				{
+				TInt drive = 0;
+				if( iFs.CharToDrive( (folder->Des())[0], drive ) == KErrNone )
+					{
+					TVolumeInfo volInfo;
+					if( iFs.Volume( volInfo, drive ) == KErrNone )
+						{
+						mediaId = volInfo.iUniqueID;
+						}
+					}
+				}			
+			
+			for ( TInt i = 0; i < count; i++ )
+				{
+				TEntry entry = (*directory)[i];
+				
+				TInt length = folder->Length() + entry.iName.Length() + KDirectorySeparator().Length();
+				HBufC* name = HBufC::NewLC( length );
+				name->Des().Append( *folder );
+				TPtrC ptr = *folder;
+				if( ptr[ ptr.Length() - 1 ] == TChar('\\') )
+					{
+					name->Des().Append( entry.iName );
+					}
+			
+				if ( entry.IsDir() )
+					{					
+					name->Des().Append( KDirectorySeparator );
+					TPtrC path = *name;
+					if( !aCheckDrive )
+						{
+						path.Set( (*name).Mid( 2 ) );
+						}
+					if( !IsDescInArray( path, aIgnorePaths ) )
+						{
+						WRITELOG("CHarvesterAO::BootScanL() - scanFolders.AppendL");
+						TScanItem* item = new (ELeave) TScanItem();
+						item->iPath = name->AllocL();
+						item->iPreinstalled = MdeConstants::MediaObject::ENotPreinstalled;
+						aScanItems.AppendL( item );
+						}
+					}
+				else
+					{
+					TPtrC filename = *name;
+					if( !aCheckDrive )
+						{
+						filename.Set( (*name).Mid( 2 ) );
+						}
+					if( !IsDescInArray( filename, aIgnorePaths ) )
+						{
+						WRITELOG("CHarvesterAO::BootScanL() - check files");
+						
+					    RArray<TPtrC> uris;
+					    RArray<TMdSFileInfo> fileInfos;
+					    RArray<TFilePresentStates> results;
+					    CleanupClosePushL( uris );
+					    CleanupClosePushL( fileInfos );
+					    CleanupClosePushL( results );
+						
+					    TMdSFileInfo fileInfo;
+					    fileInfo.iModifiedTime = entry.iModified.Int64();
+					    fileInfo.iSize = entry.iSize;
+					    fileInfos.Append( fileInfo );
+					    uris.Append( name->Des() );
+						
+					    TFilePresentStates found;
+					    
+					    if( mediaId == volumeInfo.iUniqueID )
+					        {
+					        iMdEHarvesterSession->SetFilesToPresentL( volumeInfo.iUniqueID, uris, fileInfos, results );
+					        found = results[ 0 ];
+					        }
+					    else
+					        {
+					        found = EMdsNotFound;
+					        }
+						
+						// scan file if it was not found from DB, or if it has been modified
+						if( found == EMdsNotFound ||
+						    found == EMdsPlaceholder ||
+						    found == EMdsModified )
+						    {
+	                        CPlaceholderData* phData = CPlaceholderData::NewL();
+	                        CleanupStack::PushL( phData );
+	                        phData->SetUri( *name );
+	                        phData->SetModified( entry.iModified );
+	                        phData->SetFileSize( entry.iSize );
+	                        phData->SetMediaId( mediaId );
+	                        phData->SetPreinstalled( preinstalled );
+
+	                        CHarvesterData* hd = CHarvesterData::NewL( name->AllocL() );
+	                        hd->SetEventType( EHarvesterAdd );
+	                        hd->SetObjectType( EPlaceholder );
+	                        hd->SetOrigin( MdeConstants::Object::EOther );
+	                        hd->SetClientData( phData );
+
+	                        CleanupStack::Pop( phData );
+	                        hdArray.Append( hd );
+						    }
+						CleanupStack::PopAndDestroy( &results );
+						CleanupStack::PopAndDestroy( &fileInfos );
+						CleanupStack::PopAndDestroy( &uris );
+						}
+					}
+				CleanupStack::PopAndDestroy( name );
+				}
+			
+			CleanupStack::PopAndDestroy( directory );
+			}
+		folder = NULL;
+		delete aScanItems[0];
+		aScanItems.Remove( 0 );
+		}
+	
+	WRITELOG("CHarvesterAO::BootScanL() - iQueue->Append");
+	iQueue->MonitorEvent( hdArray );
+	CleanupStack::PopAndDestroy( &hdArray ); 
+
+	iMdEHarvesterSession->RemoveFilesNotPresent( volumeInfo.iUniqueID, ETrue );
+	
+	WRITELOG("CHarvesterAO::BootScanL() - end");
+	}
+
+void CHarvesterAO::SetHarvesterStatusObserver( MHarvesterStatusObserver* aObserver )
+	{
+	iHarvesterStatusObserver = aObserver;
+	}
+
+TBool CHarvesterAO::UnharvestedItemsLeftInPlugins()
+	{
+	RPointerArray<CHarvesterPluginInfo>& infos = iHarvesterPluginFactory->GetPluginInfos();
+	TInt count = infos.Count();
+	for ( TInt i = count; --i >= 0; )
+		{
+		if ( infos[i]->iQueue.Count() > 0 )
+			{
+			return ETrue;
+			}
+		}
+	
+	return EFalse;
+	}
+
+void CHarvesterAO::PreallocateNamespaceL( CMdENamespaceDef& aNamespaceDef )
+	{
+	const TInt objectDefCount = aNamespaceDef.ObjectDefCount();
+
+	for( TInt i = 0; i < objectDefCount; i++ )
+		{
+		CMdEObjectDef& objectDef = aNamespaceDef.ObjectDefL( i );
+
+		const TInt propertyDefCount = objectDef.PropertyDefCount();
+
+		for( TInt j = 0; j < propertyDefCount; j++ )
+			{
+			CMdEPropertyDef& propertyDef = objectDef.PropertyDefL( j );
+			}
+		}
+	}
+
+void CHarvesterAO::StartThumbAGDaemon()
+    {
+    TInt res( KErrNone );
+    
+    // create server - if one does not already exist
+    TFindServer findServer( KTAGDaemonName );
+    TFullName name;
+    if ( findServer.Next( name ) != KErrNone )
+        {
+        RProcess server;
+        // Create the server process
+        // KNullDesC param causes server's E32Main() to be run
+        res = server.Create( KTAGDaemonExe, KNullDesC );
+        if ( res != KErrNone )
+            {
+            return;
+            }
+
+        // Process created successfully
+        TRequestStatus status;
+        server.Rendezvous( status );
+        
+        if ( status != KRequestPending )
+            {
+            server.Kill( 0 );     // abort startup
+            }
+        else
+            {
+            server.Resume();    // logon OK - start the server
+            }       
+
+        // Wait until the completion of the server creation
+        User::WaitForRequest( status );
+
+        server.Close(); // we're no longer interested in the other process
+        }    
+    }
+
+void CHarvesterAO::MemoryLow()
+	{
+	WRITELOG("CHarvesterAO::MemoryLow()");
+	// cache monitored events
+	PauseMonitoring();
+	
+	PauseHarvester();
+	}
+
+void CHarvesterAO::MemoryGood()
+	{
+	WRITELOG("CHarvesterAO::MemoryGood()");
+	// resume monitoring
+	ResumeMonitoring();
+	
+	TRAP_IGNORE( ResumeHarvesterL() );
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/harvesteroomao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,109 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Low memory observer for havester server
+*
+*/
+
+
+#include "harvesteroomao.h"
+#include "harvestercommon.h"
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CHarvesterOomAO* CHarvesterOomAO::NewL( MHarvesterOomObserver& aObserver )
+	{
+	CHarvesterOomAO* self = new (ELeave) CHarvesterOomAO( aObserver );
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// CHarvesterOomAO
+// ---------------------------------------------------------------------------
+//
+CHarvesterOomAO::CHarvesterOomAO( MHarvesterOomObserver& aObserver ) : 
+		CActive( CActive::EPriorityUserInput )
+	{
+	iObserver = &aObserver;
+	}
+
+
+// ---------------------------------------------------------------------------
+// ~CHarvesterOomAO
+// ---------------------------------------------------------------------------
+//
+CHarvesterOomAO::~CHarvesterOomAO()
+	{
+	iOomMsgQueue.Close();
+	}
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterOomAO::ConstructL()
+	{
+	CActiveScheduler::Add( this);
+	
+	iOomMsgQueue.OpenGlobal( KHarvesterOomQueue );
+	iOomMsgQueue.NotifyDataAvailable( iStatus );
+	SetActive();
+	}
+
+// ---------------------------------------------------------------------------
+// RunL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterOomAO::RunL()
+	{
+	User::LeaveIfError( iStatus.Int() );
+	
+	TInt oomStatus(0);
+	TInt err = iOomMsgQueue.Receive( oomStatus );
+	
+	if( oomStatus == TMdsOomFreeRam )
+		{
+		iObserver->MemoryLow();
+		}
+	else
+		{
+		iObserver->MemoryGood();
+		}
+	
+	iOomMsgQueue.NotifyDataAvailable( iStatus );
+	SetActive();
+	}
+
+// ---------------------------------------------------------------------------
+// DoCancel
+// ---------------------------------------------------------------------------
+//
+void CHarvesterOomAO::DoCancel()
+	{
+	iOomMsgQueue.CancelDataAvailable();
+	}
+
+// ---------------------------------------------------------------------------
+// RunError
+// ---------------------------------------------------------------------------
+//
+TInt CHarvesterOomAO::RunError( TInt /*aError*/ )
+	{
+	return KErrNone;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/harvesterqueue.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,261 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester server harvesting queue*
+*/
+
+
+#include "harvesterqueue.h"
+#include "harvesterao.h"
+#include "harvesterlog.h"
+#include "harvesterblacklist.h"
+#include "mdsutils.h"
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CHarvesterQueue* CHarvesterQueue::NewL( CHarvesterAO* aHarvesterAO,
+		CHarvesterBlacklist* aBlacklist )
+    {
+    WRITELOG( "CHarvesterQueue::NewL()" );
+
+    CHarvesterQueue* self = CHarvesterQueue::NewLC( aHarvesterAO, aBlacklist );
+    CleanupStack::Pop( self );
+    return self;	
+    }
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+CHarvesterQueue* CHarvesterQueue::NewLC( CHarvesterAO* aHarvesterAO,
+		CHarvesterBlacklist* aBlacklist )
+    {
+    WRITELOG( "CHarvesterQueue::NewLC()" );
+
+    CHarvesterQueue* self = new ( ELeave ) CHarvesterQueue(
+    		aHarvesterAO, aBlacklist );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+        
+// ---------------------------------------------------------------------------
+// CHarvesterQueue
+// ---------------------------------------------------------------------------
+//            
+CHarvesterQueue::CHarvesterQueue( CHarvesterAO* aHarvesterAO,
+		CHarvesterBlacklist* aBlacklist ) : iMediaIdUtil( NULL )
+    {
+    WRITELOG( "CHarvesterQueue::CHarvesterQueue()" );
+    iHarvesterAO = aHarvesterAO;
+    iBlacklist = aBlacklist;
+    }
+
+// ---------------------------------------------------------------------------
+// ~CHarvesterQueue
+// ---------------------------------------------------------------------------
+//            
+CHarvesterQueue::~CHarvesterQueue()
+    {
+    WRITELOG( "CHarvesterQueue::CHarvesterQueue()" );
+    iItemQueue.ResetAndDestroy();
+    iItemQueue.Close();
+    iFs.Close();
+    RMediaIdUtil::ReleaseInstance();
+    }
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterQueue::ConstructL()
+    {
+    WRITELOG( "CHarvesterQueue::ConstructL()" );
+    User::LeaveIfError( iFs.Connect() );
+	iMediaIdUtil = &RMediaIdUtil::GetInstanceL();
+    }
+
+// ---------------------------------------------------------------------------
+// ItemsInQueue
+// ---------------------------------------------------------------------------
+// 
+TInt CHarvesterQueue::ItemsInQueue()
+    {
+    WRITELOG( "CHarvesterQueue::ItemsInQueue()" );
+
+    return iItemQueue.Count();
+    }
+
+// ---------------------------------------------------------------------------
+// GetNextItem
+// ---------------------------------------------------------------------------
+//
+CHarvesterData* CHarvesterQueue::GetNextItem()
+	{
+    WRITELOG( "CHarvesterQueue::GetNextItem()" );
+    CHarvesterData* item = NULL;
+     
+   	if ( iItemQueue.Count() > 0 )
+        {
+#ifdef _DEBUG
+        WRITELOG1( "Harvester queue items = %d", iItemQueue.Count() );
+#endif
+        item = iItemQueue[0];
+        iItemQueue.Remove( 0 );	
+        }
+   	else
+        {
+        WRITELOG( "Harvester queue items zero!" );
+        iItemQueue.Compress();
+        }
+   	
+   	WRITELOG( "CHarvesterQueue::GetNextItem, end" );
+   	return item;
+	}    
+
+// ---------------------------------------------------------------------------
+// Append
+// Files are checked against blacklist and blacklisted files
+// will not be appended.
+// ---------------------------------------------------------------------------
+//
+void CHarvesterQueue::Append( CHarvesterData* aItem )
+	{
+    WRITELOG( "CHarvesterQueue::Append()" );
+    TInt err = KErrNone;
+
+    if ( iBlacklist )
+        {
+        TUint32 mediaId( 0 );
+		err = iMediaIdUtil->GetMediaId( aItem->Uri(), mediaId );
+        
+        TTime time( 0 );
+        if ( err == KErrNone && iBlacklist->IsBlacklisted(
+        		aItem->Uri(), mediaId, time ) )
+            {
+            WRITELOG( "CHarvesterQueue::Append() - found a blacklisted file" );
+            delete aItem;
+            aItem = NULL;
+            err = KErrCorrupt;
+            }
+        }
+
+    if ( err != KErrCorrupt )
+        {
+		// check if fast harvest file and add to start of queue
+    	if ( aItem->ObjectType() == EFastHarvest || aItem->Origin() == MdeConstants::Object::ECamera )
+    		{
+    		err = iItemQueue.Insert( aItem, 0 );
+    		}
+    	else
+    		{
+    		err = iItemQueue.Append( aItem );
+    		}
+    	
+    	if( err != KErrNone )
+			{
+			delete aItem;
+			aItem = NULL;
+			}
+        }
+
+    if ( err != KErrNone )
+        {
+        WRITELOG1( "CHarvesterQueue::Append() - error: %d", err );
+        delete aItem;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// RemoveItems
+// Remove items from the queue based on them mediaid.
+// ---------------------------------------------------------------------------
+//
+TUint CHarvesterQueue::RemoveItems( TUint32 aMediaId )
+    {
+#ifdef _DEBUG
+    WRITELOG1( "CHarvesterQueue::RemoveItems( %d )", aMediaId);
+    
+    WRITELOG1( "CHarvesterQueue::RemoveItems() iItemQueue.Count() == %d", iItemQueue.Count());
+#endif
+
+    TUint removedCount(0);
+    TInt err(KErrNone);
+    TUint32 mediaId( 0 );
+    CHarvesterData* hd = NULL;
+    
+    for(TInt i = iItemQueue.Count() - 1; i >=0; i--)
+        {
+        hd = iItemQueue[i];
+        err = iMediaIdUtil->GetMediaId( hd->Uri(), mediaId );
+        
+        if( err == KErrNone)
+            {
+            if( mediaId == aMediaId)
+                {
+                delete hd;
+                hd = NULL;
+                iItemQueue.Remove( i );
+                removedCount++;
+                }
+            else
+                {
+                WRITELOG2( "CHarvesterQueue::RemoveItems( ) %d != %d", mediaId, aMediaId);
+                }
+            }
+        else
+            {
+            WRITELOG1( "CHarvesterQueue::RemoveItems( ) GetMediaId err == %d", err);
+            }
+        }
+    iItemQueue.Compress();
+#ifdef _DEBUG
+    WRITELOG2( "CHarvesterQueue::RemoveItems() iItemQueue.Count() = %d, removedCount = %d", iItemQueue.Count(), removedCount);
+#endif
+    return removedCount;
+    }
+
+// ---------------------------------------------------------------------------
+// MonitorEvent
+// ---------------------------------------------------------------------------
+//  
+void CHarvesterQueue::MonitorEvent( CHarvesterData* aHarvesterData )
+    {
+   	Append( aHarvesterData );
+
+    // signal to start harvest if harvester idles
+    if ( !iHarvesterAO->IsServerPaused() )
+        {
+        iHarvesterAO->SetNextRequest( CHarvesterAO::ERequestHarvest );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// MonitorEvent
+// ---------------------------------------------------------------------------
+//  
+void CHarvesterQueue::MonitorEvent(
+        RPointerArray<CHarvesterData>& aHarvesterDataArray )
+    {
+    for( TInt i = aHarvesterDataArray.Count(); --i >= 0; )
+    	{
+    	MonitorEvent( aHarvesterDataArray[i] );
+    	}
+    
+    // "clear" array after ownership of items
+    // was changed for MonitorEvent-method
+    aHarvesterDataArray.Reset();
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/harvesterserver.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,579 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester server*
+*/
+
+#include <e32svr.h>
+#include <apgcli.h>
+#include <apmrec.h>
+
+#include "harvesterserver.h"
+#include "harvesterserversession.h"
+#include "harvestercommon.h"
+#include "harvesterlog.h"
+#include "harvesterao.h"
+#include "harvesterblacklist.h"
+#include "mdsactivescheduler.h"
+
+// ----------------------------------------------------------------------------------------
+// Server's policy here
+// ----------------------------------------------------------------------------------------
+
+// ----------------------------------------------------------------------------------------
+// Total number of ranges
+// ----------------------------------------------------------------------------------------
+const TUint KHarvesterServerRangeCount = 10;
+ 
+// ----------------------------------------------------------------------------------------
+// Definition of the ranges
+// ----------------------------------------------------------------------------------------
+const TInt KHarvesterServerRanges[KHarvesterServerRangeCount] = 
+{
+	EResumeHarvester,        // Resume/start Harvester server
+	EPauseHarvester,          // Pause Harvester server
+	EHarvestFile,
+    ERegisterProcessOrigin,
+    EUnregisterProcessOrigin,
+    ERegisterHarvestComplete,
+    EUnregisterHarvestComplete,
+    ERegisterHarvesterEvent,
+    EUnregisterHarvesterEvent,
+    EHarvestFileWithUID,
+};
+
+// ----------------------------------------------------------------------------------------
+// Policy to implement for each of the above ranges 
+// ----------------------------------------------------------------------------------------      
+const TUint8 KHarvesterServerElementsIndex[KHarvesterServerRangeCount] = 
+	{
+	CPolicyServer::ECustomCheck,    // EResumeHarvester
+    CPolicyServer::ECustomCheck,    // EPauseHarvester
+    CPolicyServer::ECustomCheck,    // EHarvestFile
+    CPolicyServer::ECustomCheck,    // ERegisterProcessOrigin
+    CPolicyServer::ECustomCheck,    // EUnregisterProcessOrigin
+    CPolicyServer::ECustomCheck,    // ERegisterHarvestComplete
+    CPolicyServer::ECustomCheck,    // EUnregisterHarvestComplete
+    CPolicyServer::ECustomCheck,    // ERegisterHarvesterEvent
+    CPolicyServer::ECustomCheck,    // EUnregisterHarvesterEvent
+    CPolicyServer::ECustomCheck,    // EHarvestFileWithUID
+	};
+
+// ----------------------------------------------------------------------------------------
+// Package all the above together into a policy 
+// ---------------------------------------------------------------------------------------- 
+const CPolicyServer::TPolicy KHarvesterServerPolicy =
+	{
+	CPolicyServer::EAlwaysPass,
+	KHarvesterServerRangeCount,      // number of ranges
+	KHarvesterServerRanges,          // ranges array
+	KHarvesterServerElementsIndex,   // elements<->ranges index
+	NULL 
+	                           // array of elements
+	};
+
+// ---------------------------------------------------------------------------
+// CustomSecurityCheckL
+// ---------------------------------------------------------------------------
+//
+CPolicyServer::TCustomResult CHarvesterServer::CustomSecurityCheckL(
+        const RMessage2& aMsg, TInt& /*aAction*/, TSecurityInfo& /*aMissing*/ )
+	{
+    WRITELOG( "CHarvesterServer::CustomSecurityCheckL()" );
+    
+    CPolicyServer::TCustomResult securityCheckResult = EFail;
+    
+    switch ( aMsg.Function() )
+    	{
+        case ERegisterHarvestComplete:
+        case EUnregisterHarvestComplete:
+        case ERegisterHarvesterEvent:
+        case EUnregisterHarvesterEvent:
+            {
+            if( aMsg.HasCapability( ECapabilityReadUserData ) )
+                {
+                securityCheckResult = EPass;
+                }
+            break;
+            }
+    	
+        case EHarvestFileWithUID:
+            {
+            if( aMsg.HasCapability( ECapabilityWriteUserData ) )
+                {
+                securityCheckResult = EPass;
+                }
+            break;
+            }
+            
+        case EHarvestFile:
+    	case EResumeHarvester:
+    	case EPauseHarvester:
+    	case ERegisterProcessOrigin:
+    	case EUnregisterProcessOrigin:
+    			{
+            if( aMsg.HasCapability( ECapabilityWriteDeviceData ) )
+                {
+                securityCheckResult = EPass;
+                }
+    		}
+        break;
+        
+        default:
+            {
+            securityCheckResult = EFail;
+            }
+   	    }
+    
+    return securityCheckResult;
+	}
+// ---------------------------------------------------------------------------
+// CustomFailureActionL
+// ---------------------------------------------------------------------------
+//
+CPolicyServer::TCustomResult CHarvesterServer::CustomFailureActionL(
+        const RMessage2& /*aMsg*/, TInt /*aAction*/, const TSecurityInfo& /*aMissing*/ )
+	{
+    // Not used
+    return EFail;
+	}
+ 
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+CHarvesterServer* CHarvesterServer::NewLC()
+	{
+    WRITELOG( "CHarvesterServer::NewLC() - begin" );
+    
+	CHarvesterServer* self = new (ELeave) CHarvesterServer(
+			CActive::EPriorityStandard, KHarvesterServerPolicy, 
+			ESharableSessions );
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+	}
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CHarvesterServer* CHarvesterServer::NewL()
+	{
+    WRITELOG( "CHarvesterServer::NewL() - begin" );
+    
+	CHarvesterServer* self = CHarvesterServer::NewLC();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// CHarvesterServer
+// ---------------------------------------------------------------------------
+//
+CHarvesterServer::CHarvesterServer( TInt aPriority, const TPolicy& aPolicy, 
+		TServerType aType )
+ 	: CPolicyServer( aPriority, aPolicy, aType )
+ 	{
+    WRITELOG( "CHarvesterServer::CHarvesterServer() - begin" );
+ 	}
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::ConstructL()
+	{
+	WRITELOG( "CHarvesterServer::ConstructL() - begin" );
+	StartL( KHarvesterServerName );
+	iHarvesterAO = CHarvesterAO::NewL();
+	iHarvesterAO->SetHarvesterStatusObserver( this );
+	
+	iPauseObserverAO = CPauseObserverAO::NewL( *this );
+	
+    // create shutdown observer
+    iShutdownObserver = CHarvesterShutdownObserver::NewL( *this );                                                
+	
+	WRITELOG( "CHarvesterServer::ConstructL() - end" );
+	}
+
+// ---------------------------------------------------------------------------
+// Pause
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::Pause( const RMessage2& aMessage )
+	{
+	WRITELOG( "CHarvesterServer::Pause() - begin" );
+
+	if ( !iHarvesterAO->IsServerPaused() )
+		{
+		iMessage = &aMessage;
+		iHarvesterAO->SetNextRequest( CHarvesterAO::ERequestPause );
+		}
+	else
+		{
+		aMessage.Complete( KErrInUse );
+		}
+	}
+
+
+// ---------------------------------------------------------------------------
+// Resume
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::Resume( const RMessage2& aMessage )
+	{
+	WRITELOG( "CHarvesterServer::Resume()" ); 
+	
+	if ( iHarvesterAO->IsServerPaused() )
+		{
+		iMessage = &aMessage;
+		iHarvesterAO->SetNextRequest( CHarvesterAO::ERequestResume );
+		}
+	else
+		{
+		aMessage.Complete( KErrInUse );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// Pause
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::Pause()
+	{
+	WRITELOG( "CHarvesterServer::Pause()" );
+
+	if ( !iHarvesterAO->IsServerPaused() )
+		{
+		iHarvesterAO->SetNextRequest( CHarvesterAO::ERequestPause );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// Resume
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::Resume()
+	{
+	WRITELOG( "CHarvesterServer::Resume()" ); 
+
+	if ( iHarvesterAO->IsServerPaused() )
+		{
+		iHarvesterAO->SetNextRequest( CHarvesterAO::ERequestResume );
+		}
+	}
+
+
+void CHarvesterServer::PauseReady( TInt aError )
+	{
+	WRITELOG1( "CHarvesterServer::PauseReady( %d )", aError );
+	if( iMessage )
+		{
+		iMessage->Complete( aError );
+		iMessage = NULL;
+		}
+	}
+
+void CHarvesterServer::ResumeReady( TInt aError )
+	{
+	WRITELOG1( "CHarvesterServer::ResumeReady( %d )", aError );
+	if( iMessage )
+		{
+		iMessage->Complete( aError );
+		iMessage = NULL;
+		}
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterServer::ShutdownNotification
+// -----------------------------------------------------------------------------
+//
+void CHarvesterServer::ShutdownNotification()
+    {
+    WRITELOG( "CHarvesterServer::ShutdownNotification" );
+    CActiveScheduler::Stop();
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterServer::ShutdownNotification
+// -----------------------------------------------------------------------------
+//
+void CHarvesterServer::RestartNotification()
+    {
+    WRITELOG( "CHarvesterServer::RestartNotification" );    
+    }
+
+
+// ---------------------------------------------------------------------------
+// Harvest File
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::HarvestFile( const RMessage2& aMessage )
+	{
+	WRITELOG( "CHarvesterServer::HarvestFile()" );
+	
+	iHarvesterAO->HarvestFile( aMessage );
+	}
+
+// ---------------------------------------------------------------------------
+// Harvest File with UID
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::HarvestFileWithUID( const RMessage2& aMessage )
+    {
+    WRITELOG( "CHarvesterServer::HarvestFile()" );
+    
+    iHarvesterAO->HarvestFileWithUID( aMessage );
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterServer::RegisterProcessOrigin()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::RegisterProcessOrigin( const RMessage2& aMessage )
+    {
+    WRITELOG( "CHarvesterServer::RegisterProcessOrigin()" );
+    
+    iHarvesterAO->RegisterProcessOrigin( aMessage );
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterServer::UnregisterProcessOrigin()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::UnregisterProcessOrigin( const RMessage2& aMessage )
+    {
+    WRITELOG( "CHarvesterServer::UnregisterProcessOrigin()" );
+    
+    iHarvesterAO->UnregisterProcessOrigin( aMessage );
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterServer::RegisterHarvestComplete()
+// ---------------------------------------------------------------------------
+//
+TInt CHarvesterServer::RegisterHarvestComplete( const CHarvesterServerSession& aSession, const RMessage2& aMessage )
+    {
+    WRITELOG( "CHarvesterServer::RegisterHarvestComplete()" );
+    
+    return iHarvesterAO->RegisterHarvestComplete( aSession, aMessage );
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterServer::UnregisterHarvestComplete()
+// ---------------------------------------------------------------------------
+//
+TInt CHarvesterServer::UnregisterHarvestComplete( const CHarvesterServerSession& aSession )
+    {
+    WRITELOG( "CHarvesterServer::UnregisterHarvestComplete()" );
+    
+    return iHarvesterAO->UnregisterHarvestComplete( aSession );
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterServer::RegisterHarvesterEvent()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::RegisterHarvesterEvent( const RMessage2& aMessage )
+    {
+    WRITELOG( "CHarvesterServer::RegisterHarvesterEvent()" );
+    
+    iHarvesterAO->RegisterHarvesterEvent( aMessage );
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterServer::UnregisterHarvesterEvent()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::UnregisterHarvesterEvent( const RMessage2& aMessage )
+    {
+    WRITELOG( "CHarvesterServer::UnregisterHarvesterEvent()" );
+    
+    iHarvesterAO->UnregisterHarvesterEvent( aMessage );
+    }
+
+// ---------------------------------------------------------------------------
+// ~CHarvesterServer
+// ---------------------------------------------------------------------------
+//
+CHarvesterServer::~CHarvesterServer()
+    {
+    WRITELOG( "CHarvesterServer::~CHarvesterServer()" );
+    delete iHarvesterAO;
+    delete iPauseObserverAO;
+    delete iShutdownObserver;
+    WRITELOG( "CHarvesterServer::~CHarvesterServer() end" );
+    }
+
+// ---------------------------------------------------------------------------
+// PanicClient
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::PanicClient( const RMessage2& aMessage, TInt aPanic, 
+											const TDesC& aPanicDescription )
+	{
+    WRITELOG( "CHarvesterServer::PanicClient()" );
+    
+    aMessage.Panic( aPanicDescription, aPanic );
+ 	}
+
+// ---------------------------------------------------------------------------
+// PanicServer
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::PanicServer( TInt aPanic, const TDesC& aPanicDescription )
+	{   
+    WRITELOG( "CHarvesterServer::PanicServer() - begin" );
+    
+    User::Panic( aPanicDescription, aPanic );
+ 	}
+
+// ---------------------------------------------------------------------------
+// NewSessionL
+// ---------------------------------------------------------------------------
+//
+CSession2* CHarvesterServer::NewSessionL(
+    const TVersion& aVersion, const RMessage2& ) const
+	{
+	WRITELOG( "CHarvesterServer::NewSessionL() - begin" );
+
+    //If there isn't connection to mde, we can't do much. Inform client about situation.
+    //This doesn't leave on first client because Process::Rendezcvouz is called when mde:s
+    //HandleSessionOpened is called.
+	if (!iHarvesterAO->IsConnectedToMde())
+	    {
+	    User::Leave(KErrNotReady);
+	    }
+    
+	if ( iShutdownObserver->UpdateInProgress() )
+	    {
+	    WRITELOG( "CHarvesterServer::NewSessionL - iad update in progress: KErrLocked");
+	    User::Leave(KErrLocked);
+	    }
+
+    // Check we are the right version
+    if ( !User::QueryVersionSupported( TVersion( KHarvesterServerMajorVersion,
+                                                 KHarvesterServerMinorVersion,
+                                                 KHarvesterServerBuildVersion ),
+                                       aVersion ) )
+    	{
+        User::Leave( KErrNotSupported );
+    	}
+
+    return CHarvesterServerSession::NewL( *const_cast<CHarvesterServer*>( this ) );
+	}
+
+	
+// ---------------------------------------------------------------------------
+// RunError
+// ---------------------------------------------------------------------------
+//
+TInt CHarvesterServer::RunError( TInt aError )
+	{
+	WRITELOG1( "CHarvesterServer::RunError - %d()", aError );
+	    
+    if ( aError == KErrBadDescriptor )
+ 		{
+        // A bad descriptor error implies a badly programmed client,
+        // so panic it; otherwise report the error to the client
+        PanicClient( Message(), KErrBadDescriptor );
+    	}
+    else
+    	{
+        Message().Complete( aError );
+    	}
+
+    // The leave will result in an early return from CServer::RunL(), skipping
+    // the call to request another message. So do that now in order to keep the
+    // server running.
+    ReStart();
+
+    return KErrNone;    // Handled the error fully
+ 	}
+
+// ---------------------------------------------------------------------------
+// ThreadFunctionL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServer::ThreadFunctionL()
+	{
+	WRITELOG( "CHarvesterServer::ThreadFunctionL() - begin" );
+    
+    User::LeaveIfError( User::RenameThread( KHarvesterServerName ) );
+    // Construct active scheduler
+    CActiveScheduler* activeScheduler = new (ELeave) CActiveScheduler;
+    CleanupStack::PushL( activeScheduler );
+
+    // Install active scheduler
+    // We don't need to check whether an active scheduler is already installed
+    // as this is a new thread, so there won't be one
+    CActiveScheduler::Install( activeScheduler );
+    
+    CHarvesterServer::NewLC();
+
+    RProcess::Rendezvous(KErrNone);
+
+    // Start handling requests
+	CActiveScheduler::Start();
+
+	CleanupStack::PopAndDestroy( 2, activeScheduler );
+    
+    WRITELOG( "CHarvesterServer::ThreadFunctionL() - end" );
+	}
+
+// ---------------------------------------------------------------------------
+// ThreadFunction
+// ---------------------------------------------------------------------------
+//
+TInt CHarvesterServer::ThreadFunction( TAny* /*aNone*/ )
+	{    
+ 	WRITELOG( "CHarvesterServer::ThreadFunction() - TAny - begin" );
+ 	
+    CTrapCleanup* cleanupStack = CTrapCleanup::New();
+	if ( !cleanupStack )
+		{
+        PanicServer( KErrServerTerminated );
+	 	}
+
+    TRAPD( err, ThreadFunctionL() );
+
+    if ( cleanupStack )
+    	{
+        delete cleanupStack;
+        cleanupStack = NULL;	
+    	}
+    WRITELOG( "CHarvesterServer::ThreadFunction() - TAny - end" );
+    
+    return err;
+	}
+
+// ---------------------------------------------------------------------------
+// E32Main
+// ---------------------------------------------------------------------------
+//
+TInt E32Main()
+	{    
+    WRITELOG( "CHarvesterServer::E32Main() - begin" );
+
+    __UHEAP_MARK;
+
+    const TInt result = CHarvesterServer::ThreadFunction( NULL );
+
+    __UHEAP_MARKEND;
+
+    return result;
+	}
+
+// End of file
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/harvesterserversession.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,214 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester server session*
+*/
+
+// INCLUDE FILES
+#include "harvesterserversession.h"
+#include "harvestercommon.h"
+#include "harvesterlog.h"
+
+// ========================= MEMBER FUNCTIONS ==================================
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CHarvesterServerSession* CHarvesterServerSession::NewL( CHarvesterServer& aServer )
+	{
+    WRITELOG( "CHarvesterServerSession::NewL()" );
+    
+    CHarvesterServerSession* self = CHarvesterServerSession::NewLC( aServer );
+    CleanupStack::Pop( self );
+    return self;
+	}
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+CHarvesterServerSession* CHarvesterServerSession::NewLC( CHarvesterServer& aServer )
+	{
+    WRITELOG( "CHarvesterServerSession::NewLC()" );
+    
+    CHarvesterServerSession* self = new ( ELeave ) CHarvesterServerSession( aServer );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+	}
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServerSession::ConstructL()
+	{
+    WRITELOG( "CHarvesterServerSession::ConstructL()" );
+
+	}
+
+// ---------------------------------------------------------------------------
+// Default constructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterServerSession::CHarvesterServerSession( CHarvesterServer& aServer )
+	: iServer( aServer )
+	{
+    WRITELOG( "CHarvesterServerSession::CHarvesterServerSession()" );
+	}
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CHarvesterServerSession::~CHarvesterServerSession()
+	{
+    WRITELOG( "CHarvesterServerSession::~CHarvesterServerSession()" );
+	}
+
+// ---------------------------------------------------------------------------
+// ServiceL
+// ---------------------------------------------------------------------------
+//
+void CHarvesterServerSession::ServiceL( const RMessage2& aMessage )
+	{
+    WRITELOG( "CHarvesterServerSession::ServiceL()" );	
+    
+    /* Command can't be negative */
+    if ( aMessage.Function() < 0 )
+        {
+        User::Leave( aMessage.Function() );
+        }
+    
+    switch ( aMessage.Function() )
+   		{
+		case EResumeHarvester:
+			{
+			WRITELOG( "CHarvesterServerSession::ServiceL() - EResumeHarvester command received" );
+			iServer.Resume( aMessage );	
+			}
+		break;
+		
+		case EPauseHarvester:
+			{
+			WRITELOG( "CHarvesterServerSession::ServiceL() - EPauseHarvester command received" );
+		    iServer.Pause( aMessage );			
+			}
+		break;
+			
+		case EHarvestFile:
+			{
+#ifdef _DEBUG
+			WRITELOG( "CHarvesterServerSession::ServiceL() - EHarvestFile command received" );
+			WRITELOG1( "CHarvesterServerSession::ServiceL() - EHarvestFile, param 0 size: %d", aMessage.GetDesLength(0) );
+			WRITELOG1( "CHarvesterServerSession::ServiceL() - EHarvestFile, param 1 size: %d", aMessage.GetDesLength(1) );
+
+			WRITELOG( "CHarvesterServerSession::ServiceL() - before harvest file" );
+#endif
+		    iServer.HarvestFile( aMessage );
+			WRITELOG( "CHarvesterServerSession::ServiceL() - after harvest file" );
+			}
+		break;
+			
+        case ERegisterProcessOrigin:
+            {
+            WRITELOG( "CHarvesterServerSession::ServiceL() - ERegisterProcessOrigin command received" );
+            iServer.RegisterProcessOrigin( aMessage );          
+            }
+        break;
+
+        case EUnregisterProcessOrigin:
+            {
+            WRITELOG( "CHarvesterServerSession::ServiceL() - EUnregisterProcessOrigin command received" );
+            iServer.UnregisterProcessOrigin( aMessage );          
+            }
+        break;
+		
+		case ERegisterHarvestComplete:
+			{
+			WRITELOG( "CHarvesterServerSession::ServiceL() - ERequestHarvestComplete command received" );
+			TInt error = iServer.RegisterHarvestComplete( *this, aMessage );
+			
+			// complete message if registering failed
+			if ( error != KErrNone && !aMessage.IsNull())
+	        	{
+	        	aMessage.Complete( error );
+	        	}
+			}
+		break;
+		
+		case EUnregisterHarvestComplete:
+			{
+			WRITELOG( "CHarvesterServerSession::ServiceL() - EUnregisterHarvestComplete command received" );
+			TInt error = iServer.UnregisterHarvestComplete( *this );
+			
+			// complete message if registering failed
+			if ( !aMessage.IsNull() )
+	        	{
+	        	aMessage.Complete( error );
+	        	}
+			}
+		break;
+		
+		case ERegisterHarvesterEvent:
+			{
+			WRITELOG( "CHarvesterServerSession::ServiceL() - ERegisterHarvesterEvent command received" );
+			iServer.RegisterHarvesterEvent( aMessage );
+			}
+		break;
+		
+		case EUnregisterHarvesterEvent:
+			{
+			WRITELOG( "CHarvesterServerSession::ServiceL() - EUnregisterHarvesterEvent command received" );
+			iServer.UnregisterHarvesterEvent( aMessage );
+			}
+		break;
+		
+	    case EHarvestFileWithUID:
+	        {
+#ifdef _DEBUG
+	        WRITELOG( "CHarvesterServerSession::ServiceL() - EHarvestFileWithUID command received" );
+	        WRITELOG1( "CHarvesterServerSession::ServiceL() - EHarvestFileWithUID, param 0 size: %d", aMessage.GetDesLength(0) );
+	        WRITELOG1( "CHarvesterServerSession::ServiceL() - EHarvestFileWithUID, param 1 size: %d", aMessage.GetDesLength(1) );
+
+	        WRITELOG( "CHarvesterServerSession::ServiceL() - before harvest file" );
+#endif
+	        iServer.HarvestFileWithUID( aMessage );
+	        WRITELOG( "CHarvesterServerSession::ServiceL() - after harvest file" );
+	        }
+	    break;
+		
+        default:
+			{
+#ifdef _DEBUG
+			WRITELOG1( "CHarvesterServerSession::ServiceL() - Invalid Call!!! Number: %d", aMessage.Function() );
+#endif
+			_LIT( KMessage, "Command not supported!" );
+			iServer.PanicClient( aMessage, KErrNotSupported, KMessage );
+			}
+		break;
+		}
+	}
+
+void CHarvesterServerSession::Disconnect(const RMessage2 &aMessage)
+	{
+	//just make sure the server is cleaned after client crash
+	WRITELOG( "CHarvesterServerSession::Disconnect()" );
+	
+	iServer.UnregisterHarvestComplete( *this );
+	
+	// Overridden CSession2 Disconnect, Message must completed
+	// via CSession2::Disconnect
+	CSession2::Disconnect( aMessage );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/harvestershutdownobserver.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,133 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+#include <e32base.h>
+
+#include "harvestershutdownobserver.h"
+#include "mdscommoninternal.h"
+#include "harvesterlog.h"
+
+// ---------------------------------------------------------------------------
+// CHarvesterShutdownObserver::NewL()
+// ---------------------------------------------------------------------------
+//
+CHarvesterShutdownObserver* CHarvesterShutdownObserver::NewL( MHarvesterShutdownObserver& aObserver/*, const TUid& aKeyCategory */)
+    { 
+    CHarvesterShutdownObserver* self = new( ELeave )CHarvesterShutdownObserver( aObserver/*, aKeyCategory */);
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterShutdownObserver::CHarvesterShutdownObserver()
+// ---------------------------------------------------------------------------
+//
+CHarvesterShutdownObserver::CHarvesterShutdownObserver( MHarvesterShutdownObserver& aObserver/*, const TUid& aKeyCategory */)
+    : CActive( CActive::EPriorityUserInput ), iObserver( aObserver ), iValue( KErrNone )/*, iKeyCategory( aKeyCategory )*/
+    {       
+    CActiveScheduler::Add( this );
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterShutdownObserver::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterShutdownObserver::ConstructL()
+    {
+    WRITELOG( "CHarvesterShutdownObserver::ConstructL()" );
+    
+    const TInt error = RProperty::Define(KHarvesterPSShutdown, KShutdown,RProperty::EInt,KAllowAllPolicy,KPowerMgmtPolicy);
+    
+    WRITELOG1( "CHarvesterShutdownObserver::ConstructL, defineError = %d", error );
+    
+    // attach to the property    
+    User::LeaveIfError( iProperty.Attach(KHarvesterPSShutdown,KShutdown,EOwnerThread) );
+    
+    // wait for the previously attached property to be updated
+    iProperty.Subscribe(iStatus);       
+    
+    SetActive();
+    
+    WRITELOG("CHarvesterShutdownObserver::ConstructL() end");
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterShutdownObserver::~CHarvesterShutdownObserver()
+// ---------------------------------------------------------------------------
+//
+CHarvesterShutdownObserver::~CHarvesterShutdownObserver()
+    {
+    WRITELOG( "CHarvesterShutdownObserver::~CHarvesterShutdownObserver()" );
+    Cancel();
+    iProperty.Close();
+    WRITELOG( "CHarvesterShutdownObserver::~CHarvesterShutdownObserver() end" );
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterShutdownObserver::RunL()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterShutdownObserver::RunL()
+    {
+    // resubscribe before processing new value to prevent missing updates
+    iProperty.Subscribe( iStatus );
+    SetActive();
+    
+    // retrieve the Uid of the package going to be updated
+    TInt value = 0;
+    const TInt err = iProperty.Get(value);
+    User::LeaveIfError(err);
+
+	iValue = value;
+
+    // observer callback
+    if (value)
+        {
+        iObserver.ShutdownNotification();
+        }
+    else
+        {
+        iObserver.RestartNotification();
+        }
+    }
+
+TInt CHarvesterShutdownObserver::RunError( TInt /*aError*/ )
+    {
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterShutdownObserver::DoCancel()
+// ---------------------------------------------------------------------------
+//
+void CHarvesterShutdownObserver::DoCancel()
+    {
+    iProperty.Cancel();
+    }
+
+// ---------------------------------------------------------------------------
+// CHarvesterShutdownObserver::UpdateInProgress()
+// ---------------------------------------------------------------------------
+//
+TBool CHarvesterShutdownObserver::UpdateInProgress()
+    {
+    return iValue > 0 ? ETrue : EFalse;
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/mdeobjecthandler.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,204 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*/
+
+#include "mdeobjecthandler.h"
+#include "mdesession.h"
+#include "harvesterdata.h"
+#include "harvesterlog.h"
+#include "harvesterplugin.h"
+#include "mdeconstants.h"
+#include "mdsutils.h"
+#include <harvesterclientdata.h>
+
+using namespace MdeConstants;
+
+CMdeObjectHandler::CMdeObjectHandler( CMdESession& aSession ) : iDefaultNamespace( NULL )
+    {
+	iMdeSession = &aSession;
+    }
+
+
+CMdeObjectHandler::~CMdeObjectHandler()
+    {
+	iFs.Close();
+    }
+
+CMdeObjectHandler* CMdeObjectHandler::NewLC( CMdESession& aSession )
+    {
+	CMdeObjectHandler* self = new (ELeave)CMdeObjectHandler( aSession );
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+    }
+
+CMdeObjectHandler* CMdeObjectHandler::NewL( CMdESession& aSession )
+    {
+	CMdeObjectHandler* self=CMdeObjectHandler::NewLC( aSession );
+	CleanupStack::Pop(); // self;
+	return self;
+    }
+
+void CMdeObjectHandler::ConstructL()
+    {
+	iDefaultNamespace = &iMdeSession->GetDefaultNamespaceDefL();
+	User::LeaveIfError( iFs.Connect() );
+    }
+
+void CMdeObjectHandler::SetMetadataObjectL( CHarvesterData& aHD )
+	{
+	WRITELOG( "CMdeObjectHandler::SetMetadataObjectL()" );
+    
+    TTime time( 0 );
+    time.UniversalTime();
+    CMdEEventDef* eventDef = NULL;
+    CMdEObject& mdeObject = aHD.MdeObject();
+    
+    const THarvesterEventType type( aHD.EventType() );
+    if ( type == EHarvesterAdd )
+        {
+        if( aHD.IsBinary() && !MdsUtils::FileExists( iFs, mdeObject.Uri() )) 
+        	{
+            const TDesC16& uri = mdeObject.Uri();
+            WRITELOG1( "CMdeObjectHandler::SetMetadataObjectL - File doesn't exist any more! Uri: %S", &uri );
+            aHD.SetErrorCode( KMdEErrHarvestingFailedPermanent );
+            return;
+            }
+        
+        const TInt id( iMdeSession->AddObjectL( mdeObject ) );
+        if( id == KNoId )
+            {
+            // If add failure occures, retry
+            iMdeSession->AddObjectL( mdeObject );
+            }
+        
+        if ( mdeObject.Id() == 0 )
+            {
+            const TDesC16& uri = mdeObject.Uri();
+            WRITELOG1( "CMdeObjectHandler::SetMetadataObjectL - Adding to db failed! Uri: %S", &uri );
+            aHD.SetErrorCode( KMdEErrHarvestingFailedPermanent );
+            return;
+            }
+        
+        // Since event was EHarvesterAdd
+        eventDef = &iDefaultNamespace->GetEventDefL( Events::KCreated );
+        }
+    else if ( type== EHarvesterEdit )
+        {    
+        iMdeSession->CommitObjectL( mdeObject );
+        eventDef = &iDefaultNamespace->GetEventDefL( Events::KEdited );        
+        }    
+
+    RPointerArray<CMdEInstanceItem> relationEventArray;
+    TCleanupItem cleanupItem( MdsUtils::CleanupPtrArray<CMdEInstanceItem>, &relationEventArray );
+    CleanupStack::PushL( cleanupItem );
+
+    // If additional parameters are given, add relations between metadata objects and albums.
+    if ( aHD.ClientData() )
+        { 
+        WRITELOG( "CMdeObjectHandler::SetMetadataObjectL() - Creating album relations." );
+        
+        CMdERelationDef& albumRelationDef = iDefaultNamespace->
+        		GetRelationDefL( Relations::KContains );        
+        
+        TItemId objectId = mdeObject.Id();
+        if ( objectId != 0 )
+            {
+            CHarvestClientData* clientData = STATIC_CAST( CHarvestClientData*, aHD.ClientData() );
+            const TInt count = clientData->iAlbumIds.Count();
+            for ( TInt i = 0 ; i < count; i++ )
+                {
+                TItemId albumId = clientData->iAlbumIds[i];
+
+                WRITELOG1( "CMdeObjectHandler::SetMetadataObjectL() - AlbumID: %d", albumId );
+                CMdERelation* relation =  
+               		iMdeSession->NewRelationLC(
+                		albumRelationDef, albumId, objectId, 0 );
+                relationEventArray.Append( STATIC_CAST( CMdEInstanceItem*, relation ) );
+                CleanupStack::Pop();
+                }
+            }
+        }
+    
+    if ( eventDef )
+        {
+        WRITELOG( "CMdeObjectHandler::SetMetadataObjectL() - Creating event array" );
+        const TItemId objectId = mdeObject.Id();
+        if ( objectId != 0 )
+            {
+            CMdEEvent* event = iMdeSession->NewEventLC( 
+            		*eventDef, objectId, time );
+            relationEventArray.Append( STATIC_CAST( CMdEInstanceItem*, event ) );
+            CleanupStack::Pop();
+            }
+        }
+
+    if ( relationEventArray.Count() > 0 )
+        {
+#ifdef _DEBUG
+        WRITELOG1( "CMdeObjectHandler::SetMetadataObjectL() - Event and relation array count: %d", relationEventArray.Count() );
+#endif
+        iMdeSession->AddItemsL( relationEventArray );
+        }        
+
+    CleanupStack::PopAndDestroy( &relationEventArray );
+	}
+
+// ---------------------------------------------------------------------------
+// GetMetadataObjectL
+// ---------------------------------------------------------------------------
+//
+CMdEObject* CMdeObjectHandler::GetMetadataObjectL( CHarvesterData& aHD, const TDesC& aObjectDefStr )
+    {
+    WRITELOG( "CMdeObjectHandler::GetMetadataObjectL()" );
+    
+    CMdEObjectDef& mdeObjectDef = 
+    	iDefaultNamespace->GetObjectDefL( aObjectDefStr );
+    	
+    if ( aHD.EventType() == EHarvesterEdit )
+        {
+        if( aHD.IsBinary() )
+        	{
+        	// Checking whether file is open
+        	TBool isOpen( EFalse );
+        	TInt error = iFs.IsFileOpen( aHD.Uri(), isOpen );
+            if ( error != KErrNone )
+                {
+                WRITELOG1( "CMdeObjectHandler::GetMetadataObjectL() - file error %d", error );
+                User::Leave( error );
+                }
+        	if ( isOpen )
+        		{
+        		// The file can be open, as long as it is not open for modification anywhere
+                RFile64 tempFile;
+                error = tempFile.Open( iFs, aHD.Uri(), EFileRead | EFileShareReadersOnly );
+                if( error != KErrNone )
+                    {
+                    WRITELOG( "CMdeObjectHandler::GetMetadataObjectL() - file handle is open! Returning." );
+                    return NULL;
+                    }
+                tempFile.Close();
+        		}
+        	}
+
+        WRITELOG( "CMdeObjectHandler::GetMetadataObjectL() - open object" );
+        return iMdeSession->OpenObjectL( aHD.Uri(), mdeObjectDef );
+        }
+
+    WRITELOG( "CMdeObjectHandler::GetMetadataObjectL() - new object" );
+    CMdEObject* mdeObject = iMdeSession->NewObjectL( mdeObjectDef, aHD.Uri() );
+
+    return mdeObject;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/mdsactivescheduler.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include "mdsactivescheduler.h"
+#include "harvesterlog.h"
+
+EXPORT_C void CMdsActiveScheduler::WaitForAnyRequest()
+	{
+		if(iAllowedAOStatus != NULL)
+			{
+			User::WaitForRequest(*iAllowedAOStatus);
+			}
+		else
+			{
+			CActiveScheduler::WaitForAnyRequest();
+			}
+	}
+
+EXPORT_C void CMdsActiveScheduler::SetAllowedAOStatus(TRequestStatus& aStatus)
+	{
+	WRITELOG("CMdsActiveScheduler::SetBackupSubscribeStatus()");
+	iAllowedAOStatus = &aStatus;
+	}
+
+EXPORT_C void CMdsActiveScheduler::RemoveAllowedAOStatus()
+	{
+	WRITELOG("CMdsActiveScheduler::RemoveBackupSubscribeStatus()");
+	iAllowedAOStatus = NULL;
+	}
+
+EXPORT_C void CMdsActiveScheduler::Error(TInt aError) const
+	{
+	_LIT( KPanicNote, "CMdsActiveScheduler");
+	if ( aError != KErrNone )
+		{
+		User::Panic( KPanicNote, aError );
+		}
+	}
+	
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/ondemandao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,182 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*/
+#include "ondemandao.h"
+#include "mdeharvestersession.h"
+#include "harvesterdata.h"
+#include "harvesterlog.h"
+#include "harvesterplugin.h"
+#include "harvesterplugininfo.h"
+#include "harvesterpluginfactory.h"
+
+COnDemandAO::COnDemandAO() :
+	CActive( CActive::EPriorityUserInput )
+	{
+	WRITELOG("COnDemandAO::COnDemandAO");
+	}
+
+COnDemandAO* COnDemandAO::NewLC( CMdESession& aSession, MMonitorPluginObserver& aObserver,
+		CHarvesterPluginFactory& aPluginFactory, RPointerArray<CHarvesterData>* aPhArray )
+	{
+	WRITELOG("COnDemandAO::NewLC");
+	COnDemandAO* self = new ( ELeave ) COnDemandAO();
+	CleanupStack::PushL ( self);
+	self->ConstructL ( aSession, aObserver, aPluginFactory, aPhArray );
+	return self;
+	}
+
+COnDemandAO* COnDemandAO::NewL( CMdESession& aSession, MMonitorPluginObserver& aObserver,
+		CHarvesterPluginFactory& aPluginFactory, RPointerArray<CHarvesterData>* aPhArray )
+	{
+	WRITELOG("COnDemandAO::NewL");
+	COnDemandAO* self = COnDemandAO::NewLC ( aSession, aObserver, aPluginFactory, aPhArray );
+	CleanupStack::Pop (); // self;
+	return self;
+	}
+
+void COnDemandAO::ConstructL( CMdESession& aSession, MMonitorPluginObserver& aObserver,
+		CHarvesterPluginFactory& aPluginFactory, RPointerArray<CHarvesterData>* aPhArray )
+	{
+	WRITELOG("COnDemandAO::ConstructL");
+	iMdEHarvesterSession = CMdEHarvesterSession::NewL ( aSession);
+	iObserver = &aObserver;
+	iPluginFactory = &aPluginFactory;
+	iReadyPhArray = aPhArray;
+	CActiveScheduler::Add ( this ); // Add to scheduler
+	}
+
+COnDemandAO::~COnDemandAO()
+	{
+	WRITELOG("COnDemandAO::~COnDemandAO");
+	Cancel (); // Cancel any request, if outstanding
+	if( iMdEHarvesterSession )
+		{
+		delete iMdEHarvesterSession;
+		}
+	// Delete instance variables if any
+	}
+
+void COnDemandAO::DoCancel()
+	{
+	WRITELOG("COnDemandAO::DoCancel");
+	iMdEHarvesterSession->CancelHarvestingPrioritizationObserver ();
+	}
+
+void COnDemandAO::StartL()
+	{
+	WRITELOG("COnDemandAO::StartL");
+	// Cancel any request, just to be sure
+	Cancel ();
+	iMdEHarvesterSession->SetHarvestingPrioritizationChunkL ( 16384 );
+	WaitHarvestingRequest ();
+	}
+
+void COnDemandAO::RunL()
+	{
+	WRITELOG("COnDemandAO::RunL");
+	if( iStatus.Int() != KErrNotFound )
+		{
+		User::LeaveIfError ( iStatus.Int ());
+		
+		TInt count = iMdEHarvesterSession->HarvestingPrioritizationUriCountL();
+		if( count > 0 )
+			{
+			RPointerArray<CHarvesterPluginInfo>& pluginInfos = iPluginFactory->GetPluginInfos();
+			TInt plugins = pluginInfos.Count();
+
+			for (TInt i = count; --i >= 0;)
+				{
+				HBufC* uri = iMdEHarvesterSession->HarvestingPrioritizationUriL( i );
+				CleanupStack::PushL( uri );
+				TBool found = EFalse;
+
+				for ( TInt j = 0; j < plugins && !found; j++ )
+					{
+					RPointerArray<CHarvesterData>& queue = pluginInfos[j]->iQueue;
+					TInt queueSize = queue.Count();
+					for ( TInt k = 0; k < queueSize && !found; k++ )
+						{				
+						if ( queue[k]->Uri().CompareF( *uri ) == 0 )
+							{
+							WRITELOG2("COnDemandAO::RunL URI %S found in plugin %d queue", uri, j);
+							CHarvesterData* hd = queue[k];
+							hd->SetEventType( EHarvesterEdit );
+							hd->SetObjectType( EFastHarvest );
+							queue.Remove( k );
+							queue.Insert( hd, 0 );
+							found = ETrue;
+							}							
+						}
+					}
+
+				const TInt readyPhArraySize = iReadyPhArray->Count();
+				for ( TInt j = 0; j < readyPhArraySize && !found; j++ )
+					{
+					if ( (*iReadyPhArray)[j]->Uri().CompareF( *uri ) == 0 )
+						{
+						WRITELOG1("COnDemandAO::RunL URI %S found in ph array", uri);
+						CHarvesterData* hd = (*iReadyPhArray)[j];
+						hd->SetEventType( EHarvesterEdit );
+						hd->SetObjectType( EFastHarvest );
+						iReadyPhArray->Remove( j );
+						iReadyPhArray->Insert( hd, 0 );
+						found = ETrue;
+						}
+					}
+
+				if ( !found )
+					{
+					WRITELOG1("COnDemandAO::RunL URI %S wasn't found in placeholder queue.", uri);
+					
+					CMdESession& session = iMdEHarvesterSession->SessionRef();
+					TMdEObject object;
+					TRAPD( err, session.CheckObjectL( object, *uri ));
+					if ( err == KErrNone && object.Placeholder() )
+						{
+						CHarvesterData* hd = CHarvesterData::NewL( uri );
+						hd->SetEventType( EHarvesterEdit );
+						hd->SetObjectType( EFastHarvest );
+						iObserver->MonitorEvent( hd );
+						CleanupStack::Pop( uri );
+						}
+					else
+						{
+						CleanupStack::PopAndDestroy( uri );
+						}
+					}
+				else
+					{
+					CleanupStack::PopAndDestroy( uri );
+					}
+				}
+			}
+		}
+
+	WaitHarvestingRequest();
+	}
+
+TInt COnDemandAO::RunError( TInt /*aError*/ )
+	{
+	return KErrNone;
+	}
+
+void COnDemandAO::WaitHarvestingRequest()
+	{
+	WRITELOG("COnDemandAO::WaitHarvestingRequest");
+	iStatus = KRequestPending;
+	iMdEHarvesterSession->AddHarvestingPrioritizationObserver( iStatus );
+	// Tell scheduler a request is active
+	SetActive();
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/pauseobserverao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,118 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester server's P&S pause observer active object
+*
+*/
+
+#include "pauseobserverao.h"
+
+#include <harvesterpauseps.h>
+#include "harvesterserver.h"
+
+#include "harvesterlog.h"
+
+CPauseObserverAO* CPauseObserverAO::NewL( CHarvesterServer& aHarvesterServer )
+	{
+	WRITELOG("CPauseObserverAO::NewL()");
+	CPauseObserverAO* self = new (ELeave) CPauseObserverAO( aHarvesterServer );
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+CPauseObserverAO::~CPauseObserverAO()
+	{
+	Cancel();
+	iPauseProperty.Close();
+	}
+
+
+CPauseObserverAO::CPauseObserverAO( CHarvesterServer& aHarvesterServer ) :
+	CActive( CActive::EPriorityUserInput ), 
+	iHarvesterServer( aHarvesterServer )
+	{
+	CActiveScheduler::Add( this );
+	}
+
+void CPauseObserverAO::ConstructL()
+	{
+	WRITELOG("CPauseObserverAO::ConstructL()");
+
+	TUid cat = KPsHarvesterPauseCategory;
+	TInt key = KPsHarvesterPauseKey;
+	TInt error = iPauseProperty.Define( cat, 
+			key, RProperty::EInt );
+
+	WRITELOG1("CPauseObserverAO::ConstructL() Define error: %d", error);
+
+	if( KErrAlreadyExists != error )
+		{
+		User::LeaveIfError( error );
+		}
+
+	error = iPauseProperty.Attach( cat, 
+			key, EOwnerThread );
+
+	WRITELOG1("CPauseObserverAO::ConstructL() Attach error: %d", error);	
+
+	User::LeaveIfError( error );
+
+	iPauseProperty.Subscribe( iStatus );
+    SetActive();
+    WRITELOG("CPauseObserverAO::ConstructL() - ends");
+	}
+
+void CPauseObserverAO::RunL()
+	{
+	WRITELOG("CPauseObserverAO::RunL()");
+
+	TInt status = iStatus.Int();
+
+	if( status != KErrNone )
+        {
+        WRITELOG1("CPauseObserverAO::RunL() - error: %d", status);
+        }
+
+    // resubscribe before processing new value to prevent missing updates
+	iPauseProperty.Subscribe( iStatus );
+    SetActive();
+
+	TInt pauseState = EPsHarvesterPauseResume;
+
+	TUid cat = KPsHarvesterPauseCategory;
+	TInt key = KPsHarvesterPauseKey;	
+	iPauseProperty.Get( cat, key, pauseState );
+
+	if ( EPsHarvesterPausePause == pauseState )
+		{
+		WRITELOG("CPauseObserverAO::RunL() - pause");
+		iHarvesterServer.Pause();
+		}
+	else
+		{
+		WRITELOG("CPauseObserverAO::RunL() - resume");
+		iHarvesterServer.Resume();
+		}	
+	}
+
+void CPauseObserverAO::DoCancel()
+	{
+	iPauseProperty.Cancel();
+	}
+
+TInt CPauseObserverAO::RunError( TInt /*aError*/ )
+	{
+	return KErrNone;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/reharvesterao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,229 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Active Object which actually performs the re-harvesting of the files*
+*/
+
+#include "reharvesterao.h"
+#include "harvesterlog.h"
+#include "mdeobject.h"
+#include "mdsutils.h"
+
+const TInt KResumeTime = 2000000;  //microseconds
+const TInt KTimeIncrease = 500000; //microseconds
+const TInt KTimeLimit = 30000000;    //microseconds
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+CReHarvesterAO* CReHarvesterAO::NewLC()
+	{
+    WRITELOG( "CReHarvesterAO::NewLC() - begin" );
+    
+	CReHarvesterAO* self = new (ELeave) CReHarvesterAO();
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+	}
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CReHarvesterAO* CReHarvesterAO::NewL()
+	{  
+    WRITELOG( "CReHarvesterAO::NewL() - begin" );
+    
+	CReHarvesterAO* self = CReHarvesterAO::NewLC();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// CReHarvesterAO
+// ---------------------------------------------------------------------------
+//
+CReHarvesterAO::CReHarvesterAO() : CActive( CActive::EPriorityStandard ),
+    iQueue( NULL ), iDelay( KResumeTime )
+ 	{
+    WRITELOG( "CReHarvesterAO::CReHarvesterAO()" );
+ 	}
+ 	
+// ---------------------------------------------------------------------------
+// ~CReHarvesterAO
+// ---------------------------------------------------------------------------
+//
+CReHarvesterAO::~CReHarvesterAO()
+	{
+	WRITELOG( "CReHarvesterAO::~CReHarvesterAO()" );
+	
+	Cancel();
+	iItems.ResetAndDestroy();
+	iItems.Close();
+	iTimer.Close();
+	}
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CReHarvesterAO::ConstructL()
+	{
+	WRITELOG( "CReHarvesterAO::ConstructL()" );
+	
+	CActiveScheduler::Add( this );
+	iTimer.CreateLocal();
+	}
+
+// ---------------------------------------------------------------------------
+// RunL
+// ---------------------------------------------------------------------------
+//
+void CReHarvesterAO::RunL()
+	{
+	WRITELOG( "ATTENTION!!! CReHarvesterAO::RunL" );
+	User::LeaveIfError( iStatus.Int() );
+	if ( iItems.Count() > 0 )
+	    {
+	    while( iItems.Count() > 0 )
+    	    {
+    	    CHarvesterData* item = iItems[0];
+    	    iQueue->MonitorEvent( item );
+    	    iItems.Remove( 0 );
+    	    }
+	    
+	    iItems.Compress();
+	    
+	    iDelay += KTimeIncrease;
+	    if( iDelay > KTimeLimit )
+	        {
+	        iDelay = KResumeTime;
+	        }
+	    
+	    const TTimeIntervalMicroSeconds32 delay = TTimeIntervalMicroSeconds32( iDelay );
+    	iTimer.After( iStatus, delay );
+	    SetActive();
+	    }
+	}
+	
+// ---------------------------------------------------------------------------
+// DoCancel
+// ---------------------------------------------------------------------------
+//
+void CReHarvesterAO::DoCancel()
+	{
+	WRITELOG( "CReHarvesterAO::DoCancel()" );
+	}
+	
+// ---------------------------------------------------------------------------
+// RunError
+// ---------------------------------------------------------------------------
+//
+TInt CReHarvesterAO::RunError( TInt aError )
+	{
+	if (aError != KErrNone)
+		{	
+		WRITELOG1( "CReHarvesterAO::RunError - error: %d", aError );
+		}
+	return KErrNone;
+	}
+
+// ---------------------------------------------------------------------------
+// SetHarvesterQueue
+// ---------------------------------------------------------------------------
+//
+void CReHarvesterAO::SetHarvesterQueue( CHarvesterQueue* aQueue )
+    {
+    WRITELOG( "CReHarvesterAO::SetHarvesterQueue()" );
+    iQueue = aQueue;
+    }
+    
+// ---------------------------------------------------------------------------
+// AddItem
+// ---------------------------------------------------------------------------
+//
+void CReHarvesterAO::AddItem( CHarvesterData* aItem )
+    {
+    WRITELOG( "CReHarvesterAO::AddItem()" );
+    aItem->SetErrorCode( KErrNone );
+    // check if already exists
+    for( TInt i = iItems.Count(); --i >= 0; )
+        {
+        if ( MdsUtils::Compare( iItems[i]->Uri(), aItem->Uri() ) == 0 )
+            {
+#ifdef _DEBUG
+            WRITELOG1("CReHarvesterAO::AddItem() - %S already exists in re-harvester queue", &aItem->Uri() );
+#endif
+            delete aItem;
+            return;
+            }
+        }
+    
+    CMdEObject* mdeObject = &aItem->MdeObject();
+    if( mdeObject )
+    	{
+    	delete mdeObject;
+    	aItem->SetMdeObject( NULL );
+    	}
+    
+    iItems.Append( aItem );
+    
+    iDelay = KResumeTime;
+    const TTimeIntervalMicroSeconds32 delay = TTimeIntervalMicroSeconds32( iDelay );
+    
+    if ( !IsActive() )
+        {
+        iTimer.After( iStatus, delay );
+        SetActive();
+        }
+    }
+    
+// ---------------------------------------------------------------------------
+// CheckItem
+// ---------------------------------------------------------------------------
+//
+void CReHarvesterAO::CheckItem( CHarvesterData& aItem )
+    {
+    WRITELOG( "CReHarvesterAO::CheckItem()" );
+    
+    for( TInt i = iItems.Count(); --i >= 0; )
+        {
+        CHarvesterData* item = iItems[i];
+        if ( aItem.Uri().CompareC( item->Uri(), 1, NULL ) != 0 )
+            {
+            continue;
+            }
+        // found matching item
+	    iItems.Remove( i );
+	    delete item;
+        }
+    
+    if ( iItems.Count() == 0 )
+        {
+        WRITELOG( "CReHarvesterAO::CheckItem() - item count 0" );
+        
+        iItems.Compress();
+        
+        Cancel();
+        iTimer.Cancel();
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// ItemsInQueue
+// ---------------------------------------------------------------------------
+//
+TInt CReHarvesterAO::ItemsInQueue()
+	{
+	return iItems.Count();
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/restorewatcher.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,322 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This implements CRestoreWatcher class.
+*
+*/
+
+// SYSTEM INCLUDE
+#include <centralrepository.h>
+#include <sbdefs.h>
+#include <driveinfo.h>
+#include <PathInfo.h>
+
+// USER INCLUDE
+#include "restorewatcher.h"
+#include "harvesterlog.h"
+#include "propertywatcher.h"
+#include "clientkeywatcherkeys.h"
+
+// STATIC MEMBERS
+TInt CRestoreWatcher::iRegisteredClients = 0;
+TBool CRestoreWatcher::iRestoreDone = EFalse;
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CRestoreWatcher::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CRestoreWatcher* CRestoreWatcher::NewL()
+	{
+	WRITELOG("CRestoreWatcher* CRestoreWatcher::NewL()");
+	CRestoreWatcher* self = new (ELeave) CRestoreWatcher();
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CRestoreWatcher::CRestoreWatcher
+// Standard C++ constructor.
+// -----------------------------------------------------------------------------
+//
+CRestoreWatcher::CRestoreWatcher() : iPropertyWatcher( NULL ), iClients( 0 )
+	{
+	// No implementation required.
+	}
+
+// -----------------------------------------------------------------------------
+// CRestoreWatcher::~CRestoreWatcher
+// Standard C++ destructor.
+// -----------------------------------------------------------------------------
+//
+CRestoreWatcher::~CRestoreWatcher()
+	{
+	
+	if( iPropertyWatcher )
+		{
+		iPropertyWatcher->StopListeningKeyChanges( 
+				KUidSystemCategory,
+				conn::KUidBackupRestoreKey, this );
+		
+	
+		iPropertyWatcher->StopListeningKeyChanges( 
+				KPSRestoreWatcherCategory,
+				KPSRestoreWatcherClientsKey, this );
+		
+		iPropertyWatcher->Delete(); // Release connection to TLS object.
+		}
+	}
+
+// -----------------------------------------------------------------------------
+// CRestoreWatcher::ConstructL
+// Symbian 2nd phase constructor.
+// -----------------------------------------------------------------------------
+//
+void CRestoreWatcher::ConstructL()
+	{
+	WRITELOG("CRestoreWatcher::ConstructL()");
+
+	CreateFileNameL();
+	CheckRestoreL();
+    WRITELOG1("CRestoreWatcher::ConstructL() - iRestoreDone: %d", iRestoreDone );
+	
+	WRITELOG("CRestoreWatcher::ConstructL() - creating restore watcher PS key");
+	RProperty clientsProperty;
+    const TInt error = clientsProperty.Define(
+    		KPSRestoreWatcherCategory, 
+			KPSRestoreWatcherClientsKey,
+			RProperty::EInt );
+	
+    clientsProperty.Close();
+	
+	if( error != KErrAlreadyExists ) // KErrAlreadyExists not error.
+		{
+		User::LeaveIfError( error );
+		}
+	
+	iPropertyWatcher = CPropertyWatcher::GetInstanceL();
+	
+	// Want to listen when backup/restore starts.
+	// Calls NotifyKeyL when key's state has changed. 
+	iPropertyWatcher->ListenKeyChangesL( 
+			KUidSystemCategory,
+			conn::KUidBackupRestoreKey, this );
+	
+	// Listen message clients.
+	iPropertyWatcher->ListenKeyChangesL( 
+			KPSRestoreWatcherCategory,
+			KPSRestoreWatcherClientsKey, this );
+	
+	
+	WRITELOG("CRestoreWatcher::ConstructL() ends");
+	}
+	
+// -----------------------------------------------------------------------------
+// CRestoreWatcher::CreateFileNameL
+// Filename flag can be changed to use cen rep!
+// -----------------------------------------------------------------------------
+//
+void CRestoreWatcher::CreateFileNameL() 
+	{
+	TInt drive ( 0 );
+	User::LeaveIfError( 
+			DriveInfo::GetDefaultDrive( DriveInfo::EDefaultSystem, drive ) );
+
+    RFs fsSession;
+    User::LeaveIfError( fsSession.Connect() );
+  
+    TChar driveLetter;
+    fsSession.DriveToChar( drive, driveLetter );
+	
+    iFileName.Append( driveLetter );
+    iFileName.Append( KRestoreFile );  // result-> C:\\private\\200009F5\\restoredone
+ 
+    fsSession.Close();
+	}
+
+
+// -----------------------------------------------------------------------------
+// CRestoreWatcher::NotifyKeyL
+// CPropertyWatcher's callback.
+// -----------------------------------------------------------------------------
+//
+void CRestoreWatcher::NotifyKeyL( 
+		const TInt aKeyValue,
+		const TUid aPropertyCategory,
+		const TUint aKey )
+	{
+	WRITELOG("CRestoreWatcher::NotifyKeyL() - begin");
+	
+	if( aPropertyCategory == KUidSystemCategory &&
+			aKey == conn::KUidBackupRestoreKey )
+		{
+		HandleBackupRestoreKeyActionL( aKeyValue );
+		}
+	
+	if( aPropertyCategory == KPSRestoreWatcherCategory &&
+			aKey == KPSRestoreWatcherClientsKey )
+		{
+		HandleClientsKeyActionL( aKeyValue );
+		}
+	
+	WRITELOG("CRestoreWatcher::NotifyKeyL() - end");
+	}
+
+// -----------------------------------------------------------------------------
+// CRestoreWatcher::HandleBackupKeyActionL
+// When user starts restore sets flag on.
+// -----------------------------------------------------------------------------
+//
+void CRestoreWatcher::HandleBackupRestoreKeyActionL( const TUint aKeyValue )
+	{	
+	WRITELOG("CRestoreWatcher::HandleBackupKeyActionL() - begin");
+	
+	TInt backupStateValue = aKeyValue;
+	backupStateValue &= conn::KBURPartTypeMask;
+
+	if ( backupStateValue == conn::EBURRestoreFull ||
+	     backupStateValue == conn::EBURRestorePartial )
+		{
+		WRITELOG("CRestoreWatcher::RunL() - setting restore to TRUE");
+		SetRestoreFlagL( ETrue );
+		}
+	
+	WRITELOG("CRestoreWatcher::HandleBackupKeyActionL() - end");
+	}
+
+// -----------------------------------------------------------------------------
+// CRestoreWatcher::HandleClientsKeyActionL
+// Handle message clients registering to watcher.
+// -----------------------------------------------------------------------------
+//
+void CRestoreWatcher::HandleClientsKeyActionL( const TUint aKeyValue )
+	{	
+	WRITELOG("CRestoreWatcher::HandleBackupKeyActionL() - begin");
+
+	// aKeyValue contains clients count.
+	if ( aKeyValue < iClients )
+		{
+		WRITELOG("CRestoreWatcher::HandleClientsKeyActionL - unregistering");
+		UnregisterL();
+		}
+	else if ( aKeyValue > iClients )
+		{
+		WRITELOG("CRestoreWatcher::HandleClientsKeyActionL - registering");
+		Register();
+		}
+	
+	iClients = aKeyValue;
+
+	WRITELOG("CRestoreWatcher::HandleBackupKeyActionL() - end");	
+	}
+
+// -----------------------------------------------------------------------------
+// CRestoreWatcher::Register
+// Registers client to watcher.
+// -----------------------------------------------------------------------------
+//
+TBool CRestoreWatcher::Register()
+	{	
+	WRITELOG("CRestoreWatcher::Register()");
+	if ( iRestoreDone )
+		{
+		WRITELOG("CRestoreWatcher::Register() - partial restore was done.");
+		iRegisteredClients++;
+		WRITELOG1("CRestoreWatcher::Register() - registered clients: %d", iRegisteredClients);
+		}
+	
+	return iRestoreDone;
+	}
+
+// -----------------------------------------------------------------------------
+// CRestoreWatcher::UnregisterL
+// Unregister client to watcher.
+// -----------------------------------------------------------------------------
+//
+void CRestoreWatcher::UnregisterL()
+	{
+	WRITELOG("CRestoreWatcher::UnregisterL()");
+	if ( iRegisteredClients <= 0 )
+		{
+		WRITELOG("CRestoreWatcher::UnregisterL() - 0 clients");
+		return;
+		}
+	
+	iRegisteredClients--;
+	WRITELOG1("CRestoreWatcher::UnregisterL() - registered clients: %d", iRegisteredClients);
+	
+	if ( iRegisteredClients == 0 )
+		{
+		WRITELOG("CRestoreWatcher::UnregisterL() - setting CentRep value to 0");
+		SetRestoreFlagL( EFalse );
+		}
+	}
+
+// -----------------------------------------------------------------------------
+// CRestoreWatcher::SetRestoreFlagL
+// Sets restore flag on.
+// -----------------------------------------------------------------------------
+//
+void CRestoreWatcher::SetRestoreFlagL( TBool aRestoreDone )
+	{	
+	RFs fs;
+	User::LeaveIfError( fs.Connect() );
+	
+	iRestoreDone = aRestoreDone;
+	if( aRestoreDone )
+		{	
+		RFile64 file;
+		file.Replace( fs, iFileName, EFileWrite );
+		file.Close();
+		}
+	else
+		{
+		fs.Delete( iFileName );
+		}
+	
+	fs.Close();
+	}
+
+// -----------------------------------------------------------------------------
+// CRestoreWatcher::CheckRestoreL
+// Check if restore has done when booting up harvester server.
+// -----------------------------------------------------------------------------
+//
+void CRestoreWatcher::CheckRestoreL()
+	{
+	RFs fs;
+	RFile64 file;
+	User::LeaveIfError( fs.Connect() );
+	TInt fileError( KErrNotFound );
+	fileError = file.Open( fs, iFileName, EFileRead );
+	file.Close();
+	fs.Close();
+    
+	WRITELOG1("CRestoreWatcher::StartMonitoring - fileError: %d", fileError);
+	
+    if ( fileError == KErrNone )
+    	{
+    	iRestoreDone = ETrue;
+    	}
+    else
+    	{
+    	iRestoreDone = EFalse;
+    	}
+	}
+
+// End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/unmounthandlerao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,83 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*/
+
+#include "unmounthandlerao.h"
+
+CUnmountHandlerAO::CUnmountHandlerAO( MUnmountObserver& aObserver ) : 
+		CActive( CActive::EPriorityHigh )
+    {
+	iUnmountObserver = &aObserver;
+    }
+
+CUnmountHandlerAO* CUnmountHandlerAO::NewLC( MUnmountObserver& aObserver )
+    {
+	CUnmountHandlerAO* self = new ( ELeave ) CUnmountHandlerAO( aObserver );
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+    }
+
+CUnmountHandlerAO* CUnmountHandlerAO::NewL( MUnmountObserver& aObserver )
+    {
+	CUnmountHandlerAO* self = CUnmountHandlerAO::NewLC( aObserver );
+	CleanupStack::Pop(); // self;
+	return self;
+    }
+
+void CUnmountHandlerAO::ConstructL()
+    {
+	CActiveScheduler::Add( this );				// Add to scheduler
+	_LIT( KNote, "unmounthandlerao" );
+	User::LeaveIfError( iMsgQueue.CreateGlobal( KNote, 32) );
+    }
+
+CUnmountHandlerAO::~CUnmountHandlerAO()
+    {
+	Cancel(); // Cancel any request, if outstanding
+	iMsgQueue.Close();
+    }
+
+void CUnmountHandlerAO::DoCancel()
+    {
+	iMsgQueue.CancelDataAvailable();
+    }
+
+void CUnmountHandlerAO::WaitForUnmountL()
+    {
+	Cancel();							// Cancel any request, just to be sure
+	iMsgQueue.NotifyDataAvailable( iStatus );
+	SetActive();						// Tell scheduler a request is active
+    }
+
+void CUnmountHandlerAO::RunL()
+    {
+	User::LeaveIfError( iStatus.Int() );
+	if( iUnmountObserver )
+		{
+		TUint32 mediaId;
+		const TInt err = iMsgQueue.Receive( mediaId );
+		if( err == KErrNone )
+			{
+			iUnmountObserver->HandleUnmount( mediaId );
+			}
+		}
+	WaitForUnmountL();
+    }
+
+TInt CUnmountHandlerAO::RunError( TInt /*aError*/ )
+    {
+	return KErrNone;
+    }
Binary file harvester/sis/blacklistserver/blacklistserver_stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/blacklistserver/depends.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ad:metadata xmlns="http://nokia.com/arrow/repository/ia_component"
+  xmlns:ad="http://nokia.com/arrow/application_metadata">
+  <appResources>
+     <appResource>
+        <language>1</language>
+        <iacName>Blacklist Server</iacName>
+        <iacDescription>Upgrade package for Blacklist Server</iacDescription>
+     </appResource>
+  </appResources>
+  <swPlatformDep>
+     <platform>S60</platform>
+     <versionFrom>
+        <major>5</major>
+        <minor>0</minor>
+        <date>
+           <year>2009</year>
+           <week>16</week>
+        </date>
+     </versionFrom>
+  </swPlatformDep>
+  <interDeps>
+  </interDeps>
+</ad:metadata>
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/blacklistserver/package.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Blacklist Server Patch"},(0x2001B2EB), 2, 0, 0, TYPE=SA, RU
+
+; Localised vendor name
+%{"Nokia"}
+
+; Unique vendor name
+:"Nokia"
+
+;Files
+"\EPOC32\RELEASE\ARMV5\UREL\blacklistserver.exe" -"c:\sys\bin\blacklistserver.exe"
+"\EPOC32\RELEASE\ARMV5\UREL\blacklistclient.dll" -"c:\sys\bin\blacklistclient.dll"
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/blacklistserver/stub.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,30 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;Header
+# {"Blacklist Server"}, (0x2001B2EB), 1, 0, 0, TYPE=SA
+
+;Localised Vendor name
+%{"Nokia"}
+
+;Unique Vendor name
+:"Nokia"
+
+;Files
+
+
Binary file harvester/sis/composerplugins/composerplugins_stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/composerplugins/depends.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ad:metadata xmlns="http://nokia.com/arrow/repository/ia_component"
+  xmlns:ad="http://nokia.com/arrow/application_metadata">
+  <appResources>
+     <appResource>
+        <language>1</language>
+        <iacName>Composer Plugins</iacName>
+        <iacDescription>Upgrade package for Composer Plugins</iacDescription>
+     </appResource>
+  </appResources>
+  <swPlatformDep>
+     <platform>S60</platform>
+     <versionFrom>
+        <major>5</major>
+        <minor>0</minor>
+        <date>
+           <year>2009</year>
+           <week>16</week>
+        </date>
+     </versionFrom>
+  </swPlatformDep>
+  <interDeps>
+  </interDeps>
+</ad:metadata>
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/composerplugins/package.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Composer Plugins Patch"},(0x2000717E), 2, 0, 0, TYPE=SA, RU
+
+; Localised vendor name
+%{"Nokia"}
+
+; Unique vendor name
+:"Nokia"
+
+;Files
+"\epoc32\RELEASE\armv5\UREL\composerplugininterface.dll"-"c:\sys\bin\composerplugininterface.dll"
+"\epoc32\RELEASE\armv5\UREL\composerimageplugin.dll"-"c:\sys\bin\composerimageplugin.dll"
+"\epoc32\data\z\resource\plugins\composerimageplugin.rsc"-"c:\resource\plugins\composerimageplugin.rsc"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/composerplugins/stub.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;Header
+# {"Composer Plugins"}, (0x2000717E), 1, 0, 0, TYPE=SA
+
+;Localised Vendor name
+%{"Nokia"}
+
+;Unique Vendor name
+:"Nokia"
+
+;Files
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/harvester/depends.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ad:metadata xmlns="http://nokia.com/arrow/repository/ia_component"
+  xmlns:ad="http://nokia.com/arrow/application_metadata">
+  <appResources>
+     <appResource>
+        <language>1</language>
+        <iacName>MdS Harvester</iacName>
+        <iacDescription>Upgrade package for MdS Harvester</iacDescription>
+     </appResource>
+  </appResources>
+  <swPlatformDep>
+     <platform>S60</platform>
+     <versionFrom>
+        <major>5</major>
+        <minor>0</minor>
+        <date>
+           <year>2009</year>
+           <week>16</week>
+        </date>
+     </versionFrom>
+  </swPlatformDep>
+  <interDeps>
+  </interDeps>
+</ad:metadata>
\ No newline at end of file
Binary file harvester/sis/harvester/harvester_stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/harvester/package.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,33 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Metadata Harvester Patch"},(0x200009F4), 2, 0, 0, TYPE=SA, RU
+
+; Localised vendor name
+%{"Nokia"}
+
+; Unique vendor name
+:"Nokia"
+
+;Files
+"\epoc32\RELEASE\armv5\UREL\harvesterclient.dll" -"c:\sys\bin\harvesterclient.dll"
+"\epoc32\RELEASE\armv5\UREL\harvestercommon.dll" -"c:\sys\bin\harvestercommon.dll"
+"\epoc32\RELEASE\armv5\UREL\harvesterdata.dll" -"c:\sys\bin\harvesterdata.dll"
+"\epoc32\RELEASE\armv5\UREL\harvesterplugininterface.dll" -"c:\sys\bin\harvesterplugininterface.dll"
+"\epoc32\RELEASE\armv5\UREL\harvesterserver.exe" -"c:\sys\bin\harvesterserver.exe"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/harvester/stub.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;Header
+# {"Metadata Harvester"}, (0x200009F4), 1, 0, 0, TYPE=SA
+
+;Localised Vendor name
+%{"Nokia"}
+
+;Unique Vendor name
+:"Nokia"
+
+;Files
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/harvesterplugins/depends.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ad:metadata xmlns="http://nokia.com/arrow/repository/ia_component"
+  xmlns:ad="http://nokia.com/arrow/application_metadata">
+  <appResources>
+     <appResource>
+        <language>1</language>
+        <iacName>MdS Harvester Plugins</iacName>
+        <iacDescription>Upgrade package for MdS Harvester Plugins</iacDescription>
+     </appResource>
+  </appResources>
+  <swPlatformDep>
+     <platform>S60</platform>
+     <versionFrom>
+        <major>5</major>
+        <minor>0</minor>
+        <date>
+           <year>2009</year>
+           <week>16</week>
+        </date>
+     </versionFrom>
+  </swPlatformDep>
+  <interDeps>
+  </interDeps>
+</ad:metadata>
\ No newline at end of file
Binary file harvester/sis/harvesterplugins/harvesterplugins_stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/harvesterplugins/package.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,42 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Harvester Plugins Patch"},(0x2001116A), 2, 0, 0, TYPE=SA, RU
+
+; Localised vendor name
+%{"Nokia"}
+
+; Unique vendor name
+:"Nokia"
+
+;Files
+"\epoc32\RELEASE\armv5\UREL\harvesteraudioplugin.dll"-"c:\sys\bin\harvesteraudioplugin.dll"
+"\epoc32\data\z\resource\plugins\harvesteraudioplugin.rsc"-"c:\resource\plugins\harvesteraudioplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\harvesterimageplugin.dll"-"c:\sys\bin\harvesterimageplugin.dll"
+"\epoc32\data\z\resource\plugins\harvesterimageplugin.rsc"-"c:\resource\plugins\harvesterimageplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\harvestermessageplugin.dll"-"c:\sys\bin\harvestermessageplugin.dll"
+"\epoc32\data\z\resource\plugins\harvestermessageplugin.rsc"-"c:\resource\plugins\harvestermessageplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\harvesteromadrmplugin.dll"-"c:\sys\bin\harvesteromadrmplugin.dll"
+"\epoc32\data\z\resource\plugins\harvesteromadrmplugin.rsc"-"c:\resource\plugins\harvesteromadrmplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\harvesterrtpplugin.dll"-"c:\sys\bin\harvesterrtpplugin.dll"
+"\epoc32\data\z\resource\plugins\harvesterrtpplugin.rsc"-"c:\resource\plugins\harvesterrtpplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\harvestervideoplugin.dll"-"c:\sys\bin\harvestervideoplugin.dll"
+"\epoc32\data\z\resource\plugins\harvestervideoplugin.rsc"-"c:\resource\plugins\harvestervideoplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\harvesterwmvplugin.dll"-"c:\sys\bin\harvesterwmvplugin.dll"
+"\epoc32\data\z\resource\plugins\harvesterwmvplugin.rsc"-"c:\resource\plugins\harvesterwmvplugin.rsc"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/harvesterplugins/stub.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;Header
+# {"Harvester Plugins"}, (0x2001116A), 1, 0, 0, TYPE=SA
+
+;Localised Vendor name
+%{"Nokia"}
+
+;Unique Vendor name
+:"Nokia"
+
+;Files
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/monitorplugins/depends.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ad:metadata xmlns="http://nokia.com/arrow/repository/ia_component"
+  xmlns:ad="http://nokia.com/arrow/application_metadata">
+  <appResources>
+     <appResource>
+        <language>1</language>
+        <iacName>MdS Monitor Plugins</iacName>
+        <iacDescription>Upgrade package for MdS Monitor Plugins</iacDescription>
+     </appResource>
+  </appResources>
+  <swPlatformDep>
+     <platform>S60</platform>
+     <versionFrom>
+        <major>5</major>
+        <minor>0</minor>
+        <date>
+           <year>2009</year>
+           <week>16</week>
+        </date>
+     </versionFrom>
+  </swPlatformDep>
+  <interDeps>
+  </interDeps>
+</ad:metadata>
\ No newline at end of file
Binary file harvester/sis/monitorplugins/monitorplugins_stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/monitorplugins/package.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,42 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Harvester Monitor Plugins Patch"},(0x20007182), 2, 0, 0, TYPE=SA, RU
+
+; Localised vendor name
+%{"Nokia"}
+
+; Unique vendor name
+:"Nokia"
+
+;Files
+"\epoc32\RELEASE\armv5\UREL\monitorplugininterface.dll"-"c:\sys\bin\monitorplugininterface.dll"
+"\epoc32\RELEASE\armv5\UREL\mdsfileserverplugin.pxt"-"c:\sys\bin\mdsfileserverplugin.pxt"
+
+"\epoc32\RELEASE\armv5\UREL\filemonitorplugin.dll"-"c:\sys\bin\filemonitorplugin.dll"
+"\epoc32\data\z\resource\plugins\filemonitorplugin.rsc"-"c:\resource\plugins\filemonitorplugin.rsc"
+
+"\epoc32\RELEASE\armv5\UREL\MessageMonitorPlugin.dll"-"c:\sys\bin\MessageMonitorPlugin.dll"
+"\epoc32\data\z\resource\plugins\MessageMonitorPlugin.rsc"-"c:\resource\plugins\MessageMonitorPlugin.rsc"
+
+"\epoc32\RELEASE\armv5\UREL\mmcmonitorplugin.dll"-"c:\sys\bin\mmcmonitorplugin.dll"
+"\epoc32\data\z\resource\plugins\mmcmonitorplugin.rsc"-"c:\resource\plugins\mmcmonitorplugin.rsc"
+
+"\epoc32\RELEASE\armv5\UREL\mdsoomplugin.dll"-"c:\sys\bin\mdsoomplugin.dll"
+"\epoc32\data\z\resource\plugins\mdsoomplugin.rsc"-"c:\resource\plugins\mdsoomplugin.rsc"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/sis/monitorplugins/stub.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,28 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;Header
+# {"Harvester Monitor Plugins"}, (0x20007182), 1, 0, 0, TYPE=SA
+
+;Localised Vendor name
+%{"Nokia"}
+
+;Unique Vendor name
+:"Nokia"
+
+;Files
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/iadstoprestart/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_MMPFILES
+iadstop.mmp
+iadrestart.mmp
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/iadstoprestart/group/iadrestart.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,44 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION					10.0
+TARGET                  mdsiadrestart.exe
+TARGETTYPE              EXE
+UID                     0x0 0x20022E95
+
+CAPABILITY              ALL -TCB
+VENDORID                VID_DEFAULT
+
+SOURCEPATH              ../src
+SOURCE                  iadrestart.cpp
+
+// Default system include paths for middleware layer modules.
+MW_LAYER_SYSTEMINCLUDE
+
+USERINCLUDE             ../inc
+USERINCLUDE             ../../inc
+//USERINCLUDE             ../../thumbagdaemon/inc
+
+LIBRARY                 euser.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+
+EPOCPROCESSPRIORITY background
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/iadstoprestart/group/iadstop.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION					10.0
+TARGET                  mdsiadstop.exe
+TARGETTYPE              EXE
+UID                     0x100039ce 0x20022E94
+
+VENDORID                VID_DEFAULT
+//CAPABILITY              ALL -TCB
+CAPABILITY              CAP_GENERAL_DLL
+
+SOURCEPATH              ../src
+SOURCE                  iadstop.cpp
+
+// Default system include paths for middleware layer modules.
+MW_LAYER_SYSTEMINCLUDE
+
+USERINCLUDE             ../inc
+USERINCLUDE             ../../inc
+//USERINCLUDE             ../../thumbagdaemon/inc
+
+LIBRARY                 euser.lib
+
+BYTEPAIRCOMPRESSTARGET
+PAGED
+
+EPOCPROCESSPRIORITY background
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/iadstoprestart/inc/iadrestart.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Helper application to restart servers for IAD upgrade
+*
+*/
+
+#ifndef IADRESTART_H
+#define IADRESTART_H
+
+#include <e32base.h>
+#include <w32std.h>
+
+GLDEF_C TInt E32Main();
+
+#endif // IADRESTART_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/iadstoprestart/inc/iadstop.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Helper application to stop servers for IAD upgrade
+*
+*/
+
+#ifndef IADSTOP_H
+#define IADSTOP_H
+
+#include <e32base.h>
+#include <w32std.h>
+
+_LIT( KHarvesterServerName, "HarvesterServer" );
+_LIT( KHarvesterServerProcess, "*HarvesterServer*");
+_LIT( KHarvesterServerExe, "harvesterserver.exe" );
+
+_LIT( KMdsServerName, "MdSServer" );
+_LIT( KMdSServerProcess, "*mdsserver*");
+
+_LIT( KTAGDaemonName, "ThumbAGDaemon" );
+_LIT( KTAGDaemonProcess, "*ThumbAGDaemon*" );
+_LIT( KTAGDaemonExe, "thumbagdaemon.exe" );
+
+_LIT( KListenerProcess, "*iadlistener*");
+
+_LIT( KWatchdogProcess, "*mdswatchdog*");
+
+GLDEF_C TInt E32Main();
+
+#endif // IADRESTART_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/iadstoprestart/src/iadrestart.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Helper application to restart servers for IAD upgrade
+*
+*/
+
+#include <e32base.h>
+#include <e32std.h>  
+#include <e32property.h>
+
+#include "mdscommoninternal.h"
+#include "iadrestart.h"
+
+// Print macro
+#ifdef _DEBUG
+#include <e32svr.h>
+#define PRINT(x) RDebug::Print x
+#else
+#define PRINT(x)
+#endif
+
+LOCAL_C void MainL()
+    {
+    
+    PRINT(_L("IADRestart - Reset key"));
+
+	// reset key
+    RProperty::Set(KWatchdogPSShutdown,KShutdown,0);
+    
+    // reset key
+    RProperty::Set(KMdSPSShutdown,KShutdown,0);
+    RProperty::Set(KHarvesterPSShutdown,KShutdown,0);
+
+    }
+
+GLDEF_C TInt E32Main()
+    {
+    // Create cleanup stack
+    __UHEAP_MARK;
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+
+    // Run application code inside TRAP harness
+    TInt err = KErrNone;
+    TRAP(err, MainL());
+
+    delete cleanup;
+    __UHEAP_MARKEND;
+    return err;
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/iadstoprestart/src/iadstop.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,165 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Helper application to stop servers for IAD upgrade
+*
+*/
+
+#include <e32base.h>
+#include <e32std.h>  
+#include <e32property.h>
+
+#include "mdscommoninternal.h"
+#include "iadstop.h"
+
+// Print macro
+#ifdef _DEBUG
+#include <e32svr.h>
+#define PRINT(x) RDebug::Print x
+#else
+#define PRINT(x)
+#endif
+
+LOCAL_C void MainL()
+    {
+    
+    TInt res( KErrNone );
+    RProcess process;
+    TFullName name;
+    
+    // define P&S property types    
+    res = RProperty::Define(KMdSPSShutdown,KShutdown,RProperty::EInt,KAllowAllPolicy,KPowerMgmtPolicy);
+    
+    PRINT((_L("IADStop - terminate Harvester server, res = %d"), res ));    
+    
+    // find and terminate Harvester Server
+    TFindProcess findProcess2( KHarvesterServerProcess );
+    if ( findProcess2.Next(name) == KErrNone )
+        {        
+                 
+        res = process.Open(name);
+         
+        // logon to get termination signal
+        TRequestStatus status;
+        process.Logon(status);
+
+        // shutdown using P&S key
+        TInt error = RProperty::Set(KHarvesterPSShutdown, KShutdown, 1);
+        
+        PRINT((_L("IADStop - set property, error = %d"), error ));
+
+        // blocks here until thread is terminated
+        User::WaitForRequest(status); 
+
+        PRINT(_L("IADStop - Harvester server terminated"));
+          
+        process.Close();
+        }
+
+    PRINT(_L("IADStop - terminate MdS server"));
+            
+    // find and terminate Mds Server
+    TFindProcess findProcess( KMdSServerProcess );
+    if ( findProcess.Next(name) == KErrNone )
+        {
+        PRINT(_L("IADStop - found MdS server"));
+                 
+        res = process.Open(name);
+         
+        // logon to get termination signal
+        TRequestStatus status;
+        process.Logon(status);
+
+        // shutdown using P&S key
+        RProperty::Set(KMdSPSShutdown, KShutdown, 1);               
+
+        // blocks here until thread is terminated
+        User::WaitForRequest(status); 
+
+        PRINT(_L("IADStop - MdS server terminated"));
+          
+        process.Close();
+        }    
+    
+    else
+        {
+        PRINT(_L("IADStop - terminate Thumb AG Daemon"));
+        
+        // Kill Thumb AG Daemon !!!
+        // find and terminate Mds Server
+        TFindProcess findProcess3( KTAGDaemonProcess );
+        if ( findProcess3.Next(name) == KErrNone )
+            {
+            PRINT(_L("IADStop - found thumb daemon"));
+                     
+            res = process.Open(name);
+             
+            // logon to get termination signal
+            TRequestStatus status;
+            process.Logon(status);
+
+            // shutdown using P&S key
+            RProperty::Set(KMdSPSShutdown, KShutdown, 1);               
+
+            // blocks here until thread is terminated
+            User::WaitForRequest(status); 
+
+            PRINT(_L("IADStop - thumb daemon terminated"));
+              
+            process.Close();
+            }    
+        }
+
+    PRINT(_L("IADStop - terminate MdS watchdog"));    
+    
+    // find and terminate mds watchdog
+    TFindProcess findProcess4( KWatchdogProcess );
+    if ( findProcess4.Next(name) == KErrNone )
+        {        
+                 
+        res = process.Open(name);
+         
+        // logon to get termination signal
+        TRequestStatus status;
+        process.Logon(status);
+
+        // shutdown using P&S key
+        TInt error = RProperty::Set(KWatchdogPSShutdown, KShutdown, 1);
+        
+        PRINT((_L("IADStop - set property, error = %d"), error ));
+
+        // blocks here until thread is terminated
+        User::WaitForRequest(status); 
+
+        PRINT(_L("IADStop - MdS watchdog terminated"));
+          
+        process.Close();
+        }
+    }
+
+GLDEF_C TInt E32Main()
+    {
+    // Create cleanup stack
+    __UHEAP_MARK;
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+
+    // Run application code inside TRAP harness
+    TInt err = KErrNone;
+    TRAP(err, MainL());
+
+    delete cleanup;
+    __UHEAP_MARKEND;
+    return err;
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/harvesterlog.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,74 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester server commands*
+*/
+
+
+#ifndef HARVESTERLOG_H
+#define HARVESTERLOG_H
+
+#include <e32debug.h>
+#include <utf.h>
+
+#define HARVESTER_MASTER_LOG
+
+#ifdef _DEBUG
+
+#ifdef HARVESTER_MASTER_LOG
+
+#define WRITELOG(a) RDebug::Print(_L(a))
+#define WRITELOG1(a,b) RDebug::Print(_L(a),(b))
+#define WRITELOG2(a,b,c) RDebug::Print(_L(a),(b),(c))
+#define WRITELOG3(a,b,c,d) RDebug::Print(_L(a),(b),(c),(d))
+
+#define HLOG(a)  RDebug::Print((a))
+#define HLOG1(a, b)  RDebug::Print((a), (b))
+#define HLOG2(a, b, c)  RDebug::Print((a), (b), (c))
+#define HLOG3(a, b, c, d)  RDebug::Print((a), (b), (c), (d))
+#define HLOG4(a, b, c, d, e)  RDebug::Print((a), (b), (c), (d), (e))
+#define HLOG5(a, b, c, d, e, f)  RDebug::Print((a), (b), (c), (d), (e), (f))
+
+#else //HARVESTER_MASTER_LOG
+
+#define WRITELOG(a)
+#define WRITELOG1(a,b)
+#define WRITELOG2(a,b,c)
+#define WRITELOG3(a,b,c,d)
+
+#define HLOG(a)
+#define HLOG1(a, b)
+#define HLOG2(a, b, c) 
+#define HLOG3(a, b, c, d) 
+#define HLOG4(a, b, c, d, e) 
+#define HLOG5(a, b, c, d, e, f) 
+
+#endif //HARVESTER_MASTER_LOG
+
+#else  //_DEBUG
+
+#define WRITELOG(a)
+#define WRITELOG1(a,b)
+#define WRITELOG2(a,b,c)
+#define WRITELOG3(a,b,c,d)
+
+#define HLOG(a)
+#define HLOG1(a, b)
+#define HLOG2(a, b, c) 
+#define HLOG3(a, b, c, d) 
+#define HLOG4(a, b, c, d, e) 
+#define HLOG5(a, b, c, d, e, f) 
+
+#endif //_DEBUG
+
+#endif  // HARVESTERLOG_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdccommon.pan	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef __MDCCOMMON_PAN__
+#define __MDCCOMMON_PAN__
+
+/** Panic Category */
+_LIT( KMetadataEngine, "MetadataEngine" );
+
+/** CMdEServer panic codes */
+enum TMetadataPanic
+    {
+    EBadRequest = 100,
+    /*EBadDescriptor = 101,*/
+    ESrvCreateServer = 102,
+    ECreateTrapCleanup = 103,
+    /*EBadState = 104,*/
+    EDatabaseFault = 105,
+    /*EInternal = 106,
+    EInternalSchemaCorrupt = 107,
+    EInternalDbCorrupt = 108,
+    EInternalHierarchyCorrupt = 109,
+    EInternalImportFault = 110,
+    EBadFormatInQueryCriteria = 111,
+	EInternalNotifierCollision = 112,
+	EServerCommunication = 113,
+	EInternalExportFault = 114,*/
+	EServerBackupOrRestore = 115
+    };
+
+#endif // __MDCCOMMON_PAN__
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdccriteria.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  common criteria object for MdE
+*
+*/
+
+#ifndef MDCCRITERIA_H_
+#define MDCCRITERIA_H_
+
+#include "mdscommoninternal.h"
+#include "mdcserializationtype.h"
+
+TMdCSearchCriteria : protected TMdCSerializationType
+{
+	TInt16 iQueryResultType;
+	TInt16 iQueryType;
+	TDefId iNamespaceDefId;
+	TDefId iObjectDefId;
+	TMdCValueUnion iObjectDefIds;
+	TUint32 iLimit;
+	//TUint32 iOffset; NOT USED
+	TUint32 iOptimizationFlags;
+	TUint32 iRootConditionOffset;
+	TMdCValueUnion iOrderRules;
+	TMdCValueUnion iPropertyFilters;
+};
+
+TMdCOrderRule : protected TMdCSerializationType
+{
+	TInt16 iOrderRule;
+	TUint16 iFlags;
+	TDefId iPropertyDefId;
+};
+
+TMdCCondition : protected TMdCSerializationType
+{
+	TInt16 iConditionType;
+	TInt16 iNegated;
+};
+
+TMdCLogicCondition : public TMdCCondition
+{
+	TInt16 iOperator;
+	TUint32 iOptimizationFlags;
+	TMdCValueUnion iChildConditions;
+};
+
+TMdCObjectCondition : public TMdCCondition
+{
+	TInt16 iConfidentialityLevel;
+	TInt16 iCompareMethod;
+	TUint32 iFlags;
+	TUint32 iConditionOffset;
+};
+
+TMdCPropertyCondition : public TMdCCondition
+{
+	TDefId iObjectDefId;
+	TDefId iPropertyDefId;
+	TUint32 iConditionOffset;
+};
+
+TMdCRelationCondition : public TMdCCondition
+{
+	TInt16 iObjectSide;
+	TItemId iRelationId;
+	TMdCValueUnion iRelationIds;
+	TDefId iRelationDefId;
+	TUint32 iGuidOffset;
+	TUint32 iParameterRangeOffset;
+	TUint32 iLeftObjectConditionOffset;
+	TUint32 iRightObjectConditionOffset;
+	TUint32 iLastModifiedDateRangeOffset;
+};
+
+TMdCEventCondition : public TMdCCondition
+{
+	TInt16 iCompareMethod;
+	TItemId iEventId;
+	TDefId iEventDefId;
+	TUint32 iCreationTimeOffset;
+	TUint32 iObjectConditionOffset;
+	TUint32 iSourceConditionOffset;
+	TUint32 iParticipantConditionOffset;
+	TUint32 iUriConditionOffset;
+};
+
+#endif /*MDCCRITERIA_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdcdef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,121 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  common item object for MdE
+*
+*/
+
+#ifndef __MDCDEF_H__
+#define __MDCDEF_H__
+
+#include "mdscommoninternal.h"
+#include "mdcserializationtype.h"
+
+
+NONSHARABLE_CLASS(TMdCDef) : protected TMdCSerializationType
+	{
+	protected:
+		TMdCDef(TMdCStructTypes aType) : TMdCSerializationType( aType )
+			{
+			}
+		
+	public:
+		TDefId iDefId;
+		TMdCValueUnion iName;
+	};
+
+
+NONSHARABLE_CLASS(TMdCObjectDef) : public TMdCDef
+	{
+	public:
+		IMPORT_C TMdCObjectDef();
+
+		IMPORT_C static const TMdCObjectDef& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TDefId iParentId;
+		TMdCValueUnion iPropertyDefs;
+	};
+
+NONSHARABLE_CLASS(TMdCRelationDef) : public TMdCDef
+	{
+	public:
+		IMPORT_C TMdCRelationDef();
+
+		IMPORT_C static const TMdCRelationDef& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+	};
+	
+NONSHARABLE_CLASS(TMdCEventDef) : public TMdCDef
+	{
+	public:
+		IMPORT_C TMdCEventDef();
+
+		IMPORT_C static const TMdCEventDef& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+	};
+	
+NONSHARABLE_CLASS(TMdCPropertyDef) : public TMdCDef
+	{
+	public:
+		IMPORT_C TMdCPropertyDef();
+		
+		IMPORT_C static const TMdCPropertyDef& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TUint16 iFlags;
+		TUint16 iValueType;
+		TMdCValueUnion iMinValue;
+		TMdCValueUnion iMaxValue;
+	};
+
+NONSHARABLE_CLASS(TMdCNamespaceDef) : public TMdCDef
+	{
+	public:
+		IMPORT_C TMdCNamespaceDef();
+		
+		IMPORT_C static const TMdCNamespaceDef& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+	
+	public:
+		TBool iReadOnly;
+		TMdCValueUnion iObjectDefs;
+		TMdCValueUnion iRelationDefs;
+		TMdCValueUnion iEventDefs;
+	};
+
+NONSHARABLE_CLASS(TMdCSchema) : protected TMdCSerializationType
+	{
+	public:
+		IMPORT_C TMdCSchema();
+
+		IMPORT_C static const TMdCSchema& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TMdCValueUnion iNamespaceDefs;
+	};
+
+#endif /*__MDCDEF_H__*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdcitem.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,105 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  common item object for MdE
+*
+*/
+
+#ifndef __MDCITEM_H__
+#define __MDCITEM_H__
+
+#include "mdscommoninternal.h"
+#include "mdcserializationtype.h"
+
+NONSHARABLE_CLASS(TMdCItem) : protected TMdCSerializationType
+	{
+	protected:
+		TMdCItem(TMdCStructTypes aType) : TMdCSerializationType( aType )
+			{
+			}
+		
+	public:
+		TItemId iId;
+		TDefId  iDefId;
+	};
+
+NONSHARABLE_CLASS(TMdCObject) : public TMdCItem
+	{
+	public:
+		IMPORT_C TMdCObject();
+
+		IMPORT_C static const TMdCObject& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TUint32 iFlags;
+		TUint32 iMediaId;
+		TUint32 iUsageCount;
+		TInt64 iGuidHigh;
+		TInt64 iGuidLow;
+		TMdCValueUnion iUri;
+		TMdCValueUnion iProperties;
+		TMdCValueUnion iFreeTexts;
+	};
+
+NONSHARABLE_CLASS(TMdCRelation) : public TMdCItem
+	{
+	public:
+		IMPORT_C TMdCRelation();
+
+		IMPORT_C static const TMdCRelation& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TItemId iLeftObjectId;
+		TItemId iRightObjectId;
+		TInt32 iParameter;
+		TInt64 iGuidHigh;
+		TInt64 iGuidLow;
+		TTime iLastModifiedDate;
+	};
+
+NONSHARABLE_CLASS(TMdCEvent) : public TMdCItem
+	{
+	public:
+		IMPORT_C TMdCEvent();
+
+		IMPORT_C static const TMdCEvent& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TItemId iObjectId;
+		TTime iTime;
+		TMdCValueUnion iSourceText;
+		TMdCValueUnion iParticipantText;
+	};
+
+NONSHARABLE_CLASS(TMdCProperty) : public TMdCSerializationType
+	{
+	public:
+		IMPORT_C TMdCProperty();
+		
+		IMPORT_C static const TMdCProperty& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TDefId iPropertyDefId;
+		TUint32 iModFlags;
+		TMdCValueUnion iValue;
+	};
+
+#endif /* __MDCITEM_H__ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdcquery.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,178 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  common query and condition definitions for MdE
+*
+*/
+
+#ifndef __MDCQUERY_H__
+#define __MDCQUERY_H__
+
+#include "mdscommoninternal.h"
+#include "mdcserializationtype.h"
+
+
+NONSHARABLE_CLASS(TMdCCondition) : protected TMdCSerializationType
+	{
+	protected:
+		TMdCCondition(TMdCStructTypes aType) : TMdCSerializationType( aType )
+			{
+			}
+
+	public:
+		/**
+		 * Get condition reference from buffer. Doesn't change position of the 
+		 * buffer. Doesn't do type check.
+		 * 
+		 * @param aBuffer serialization buffer
+		 * 
+		 * @return reference to condition
+		 */
+		IMPORT_C static const TMdCCondition& GetFromBufferL( 
+				CMdCSerializationBuffer& aBuffer );
+
+	public:
+		TInt16 iConditionType;
+		TInt16 iNegated;
+	};
+
+
+NONSHARABLE_CLASS(TMdCLogicCondition) : public TMdCCondition
+	{
+	public:
+		IMPORT_C TMdCLogicCondition();
+
+		IMPORT_C static const TMdCLogicCondition& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TInt16  iOperator;
+		TUint32 iOptimizationFlags;
+		TMdCValueUnion iChildConditions;
+	};
+
+NONSHARABLE_CLASS(TMdCObjectCondition) : public TMdCCondition
+	{
+	public:
+		IMPORT_C TMdCObjectCondition();
+
+		IMPORT_C static const TMdCObjectCondition& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TInt16 iConfidentialityLevel;
+		TInt16 iCompareMethod;
+		TUint32 iFlags;
+		TMdCOffset iCondition;
+	};
+	
+NONSHARABLE_CLASS(TMdCEventCondition) : public TMdCCondition
+	{
+	public:
+		IMPORT_C TMdCEventCondition();
+
+		IMPORT_C static const TMdCEventCondition& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TInt16 iCompareMethod;
+		TItemId iEventId;
+		TDefId iEventDefId;
+		TMdCOffset iCreationTimeRange;
+		TMdCOffset iObjectCondition;
+		TMdCOffset iSourceCondition;
+		TMdCOffset iParticipantCondition;
+		TMdCOffset iUriCondition;
+	};
+	
+NONSHARABLE_CLASS(TMdCPropertyCondition) : public TMdCCondition
+	{
+	public:
+		IMPORT_C TMdCPropertyCondition();
+		
+		IMPORT_C static const TMdCPropertyCondition& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TDefId iObjectDefId;
+		TDefId iPropertyDefId;
+		TMdCOffset iCondition;
+	};
+
+NONSHARABLE_CLASS(TMdCRelationCondition) : public TMdCCondition
+	{
+	public:
+		IMPORT_C TMdCRelationCondition();
+		
+		IMPORT_C static const TMdCRelationCondition& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TUint16 iObjectSide;
+		TDefId iRelationDefId;
+		TItemId iRelationId;
+		TMdCValueUnion iRelationIds; // IN
+		TMdCOffset iGuid;
+		TMdCOffset iParameterRange;
+		TMdCOffset iLeftObjectCondition;
+		TMdCOffset iRightObjectCondition;
+		TMdCOffset iLastModifiedDateRange;
+	};
+
+NONSHARABLE_CLASS(TMdCSearchCriteria) : protected TMdCSerializationType
+	{
+	public:
+		IMPORT_C TMdCSearchCriteria();
+		
+		IMPORT_C static const TMdCSearchCriteria& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+		
+	public:
+		TInt16 iQueryResultType;
+		TInt16 iQueryType;
+		TDefId iNamespaceDefId;
+		TDefId iObjectDefId;
+		TMdCValueUnion iObjectDefIds;
+		TUint32 iLimit;
+		TUint32 iOffset;
+		TUint32 iOptimizationFlags;
+		TMdCOffset iRootCondition;
+		TMdCValueUnion iOrderRules;
+		TMdCValueUnion iPropertyFilters;
+	};
+
+NONSHARABLE_CLASS(TMdCOrderRule) : protected TMdCSerializationType
+	{
+	public:
+		IMPORT_C TMdCOrderRule();
+		
+		IMPORT_C static const TMdCOrderRule& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+		
+	public:
+		TInt16 iOrderRule;
+		TBool iAscending;
+		TBool iCaseSensitive;
+		TDefId iPropertyDefId;
+	};
+
+	
+
+#endif /*__MDCQUERY_H__*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdcresult.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,76 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  common item result definitions for MdE
+*
+*/
+
+#ifndef __MDCRESULT_H__
+#define __MDCRESULT_H__
+
+#include "mdscommoninternal.h"
+#include "mdcserializationtype.h"
+
+NONSHARABLE_CLASS(TMdCItems) : public TMdCSerializationType
+	{
+	public:
+		IMPORT_C TMdCItems();
+
+		IMPORT_C static const TMdCItems& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TDefId iNamespaceDefId;
+		TInt32 iErrorCode;
+		TMdCValueUnion iObjects;
+		TMdCValueUnion iRelations;
+		TMdCValueUnion iEvents;
+	};
+
+NONSHARABLE_CLASS(TMdCItemIds) : public TMdCSerializationType
+	{
+	public:
+		IMPORT_C TMdCItemIds();
+
+		IMPORT_C static const TMdCItemIds& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TDefId iNamespaceDefId;
+		TInt32 iErrorCode;
+		TMdCValueUnion iObjectIds;
+		TMdCValueUnion iObjectUris;
+		TMdCValueUnion iRelationIds;
+		TMdCValueUnion iEventIds;
+	};
+
+NONSHARABLE_CLASS(TMdCItemCounts) : public TMdCSerializationType
+	{
+	public:
+		IMPORT_C TMdCItemCounts();
+
+		IMPORT_C static const TMdCItemCounts& GetFromBufferL( CMdCSerializationBuffer& aBuffer );
+		IMPORT_C void SerializeL(CMdCSerializationBuffer& aBuffer);
+		IMPORT_C void DeserializeL(CMdCSerializationBuffer& aBuffer);
+
+	public:
+		TDefId iNamespaceDefId;
+		TInt32 iObjects;
+		TInt32 iRelations;
+		TInt32 iEvents;
+	};
+
+	
+#endif /*__MDCRESULT_H__*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdcserializationbuffer.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,544 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Serialize and deserialize data between client and server
+*
+*/
+
+#ifndef __MDCSERIALIZATIONBUFFER_H__
+#define __MDCSERIALIZATIONBUFFER_H__
+
+// INCLUDE FILES
+#include <e32base.h>
+#include "mdscommoninternal.h"
+
+class TMdCSerializationType;
+
+typedef TUint16 TSerializedDesLength;
+
+const TUint8 KPadding8 = 0xBD;
+const TInt32 KSerializedDesMaxLength = KMaxTUint16;
+const TUint32 KNoOffset = 0;
+
+/**
+* An automatic serializtion buffer class. 
+* The class provides insertion functionality for multiple variable types.
+*/
+NONSHARABLE_CLASS(CMdCSerializationBuffer): public CBase
+    {
+    public:
+
+		#ifndef _DEBUG
+			const static TUint32 KRequiredSizeForTypeCheck = 0;
+		#else
+			const static TUint32 KRequiredSizeForTypeCheck = sizeof( TUint16 );
+		#endif
+
+    	const static TUint32 KRequiredSizeForTBool   = sizeof( TInt32 ) + 2*KRequiredSizeForTypeCheck;
+    	const static TUint32 KRequiredSizeForTInt8   = sizeof( TInt16 ) + 2*KRequiredSizeForTypeCheck;
+    	const static TUint32 KRequiredSizeForTUint8  = sizeof( TUint16 ) + 2*KRequiredSizeForTypeCheck;
+    	const static TUint32 KRequiredSizeForTInt16  = sizeof( TInt16 ) + KRequiredSizeForTypeCheck;
+    	const static TUint32 KRequiredSizeForTUint16 = sizeof( TUint16 ) + KRequiredSizeForTypeCheck;
+    	const static TUint32 KRequiredSizeForTInt32  = sizeof( TInt32 ) + KRequiredSizeForTypeCheck;
+    	const static TUint32 KRequiredSizeForTUint32 = sizeof( TUint32 ) + KRequiredSizeForTypeCheck;
+    	const static TUint32 KRequiredSizeForTInt64  = sizeof( TInt64 ) + KRequiredSizeForTypeCheck;
+    	const static TUint32 KRequiredSizeForTReal32 = sizeof( TReal32 ) + KRequiredSizeForTypeCheck;
+    	const static TUint32 KRequiredSizeForTReal64 = sizeof( TReal64 ) + KRequiredSizeForTypeCheck;
+    	const static TUint32 KRequiredSizeForTTime   = sizeof( TInt64 ) + KRequiredSizeForTypeCheck;
+
+		// artificial types
+		const static TUint32 KRequiredSizeForTItemId   = sizeof( TItemId ) + KRequiredSizeForTypeCheck;
+		const static TUint32 KRequiredSizeForTDefId    = sizeof( TDefId ) + KRequiredSizeForTypeCheck;
+		const static TUint32 KRequiredSizeForEmptyText = sizeof( TSerializedDesLength ) + KRequiredSizeForTypeCheck;
+		const static TUint32 KRequiredSizeForTMdCValueUnion = sizeof( TMdCValueUnion ) + KRequiredSizeForTypeCheck;
+
+    public: // public definitions
+    	/**
+        * Returns required buffer size for given 8-bit descriptor
+        * @param aDes 8-bit descriptor
+        * @return required size for descriptor (descriptor's length is limited to KSerializedDesMaxLength)
+    	*/
+    	IMPORT_C static TUint32 RequiredSize( const TDesC8& aDes );
+
+    	/**
+        * Returns required buffer size for given 16-bit descriptor
+        * @param aDes 16-bit descriptor
+        * @return required size for descriptor (descriptor's length is limited to KSerializedDesMaxLength)
+    	*/
+    	IMPORT_C static TUint32 RequiredSize( const TDesC16& aDes );
+    
+        /**
+        * Static constructor
+        * @param aSize size of the buffer
+        * @return buffer instance
+        */
+        IMPORT_C static CMdCSerializationBuffer* NewL( TInt32 aSize );
+
+        /**
+        * Static constructor
+        * @param aSize size of the buffer
+        * @return buffer instance
+        */
+        IMPORT_C static CMdCSerializationBuffer* NewLC( TInt32 aSize );
+
+        /**
+         * Static constructor
+         * @param aBuffer pointer to the buffer
+         * @param aSize size of the buffer
+         * @return buffer instance
+         */
+        IMPORT_C static CMdCSerializationBuffer* NewL( TUint8* aBuffer, TInt32 aSize );
+
+        /**
+         * Static constructor
+         * @param aBuffer pointer to the buffer
+         * @param aSize size of the buffer
+         * @return buffer instance
+         */
+        IMPORT_C static CMdCSerializationBuffer* NewLC( TUint8* aBuffer, TInt32 aSize );
+
+        /**
+         * Static constructor
+         * @param aMessage received message
+         * @param aIndex index of wanted message
+         * @return buffer instance
+         */
+        IMPORT_C static CMdCSerializationBuffer* NewL(const RMessage2 &aMsg, TInt aIndex );
+         
+        /**
+         * Static constructor
+         * @param aMessage received message
+         * @param aIndex index of wanted message
+         * @return buffer instance
+         */
+        IMPORT_C static CMdCSerializationBuffer* NewLC(const RMessage2 &aMsg, TInt aIndex);
+
+        /**
+         * Static constructor
+         * @param aBuffer buffer to copy data from
+         * @return buffer instance
+         */
+        IMPORT_C static CMdCSerializationBuffer* NewL( const CMdCSerializationBuffer& aBuffer );
+
+        /**
+         * Static constructor
+         * @param aBuffer buffer to copy data from
+         * @return buffer instance
+         */
+        IMPORT_C static CMdCSerializationBuffer* NewLC( const CMdCSerializationBuffer& aBuffer );
+
+      
+
+        virtual ~CMdCSerializationBuffer();
+
+        /**
+        * Get pointer to serialized buffer.
+        * @return serialized buffer pointer
+        */
+		IMPORT_C TPtr8 Buffer() const;
+
+        /**
+        * Get pointer to serialized buffer.
+        * @return serialized buffer pointer
+        */
+		IMPORT_C TPtr8* BufferPtr() const;
+
+        /**
+        * Get pointer to serialized buffer.
+        * @return serialized buffer pointer
+        */
+		IMPORT_C const TPtr8* BufferConstPtr() const;
+
+    	/**
+    	* Return size of the buffer.
+    	* @return size of the buffer
+    	*/
+    	IMPORT_C TUint32 Size() const;
+
+        /**
+        * Change position of the serialized buffer.
+        * @param aPosition value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C void PositionL( TUint32 aPosition );
+
+        /**
+        * Get current position of the serialized buffer.
+        * @return current buffer position
+        */
+		IMPORT_C TUint32 Position() const;
+
+        /**
+        * Insert TBool value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TBool aValue);
+
+        /**
+        * Insert TInt8 value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TInt8 aValue);
+
+        /**
+        * Insert TUint8 value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TUint8 aValue);
+
+        /**
+        * Insert TInt16 value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TInt16 aValue);
+
+        /**
+        * Insert TUint16 value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TUint16 aValue);
+
+        /**
+        * Insert TInt32 value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TInt32 aValue);
+
+        /**
+        * Insert TUint32 value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TUint32 aValue);
+
+        /**
+        * Insert TUint value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TUint aValue);
+
+        /**
+        * Insert TInt64 value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TInt64 aValue);
+
+        /**
+        * Insert TReal32 value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TReal32 aValue);
+
+        /**
+        * Insert TReal64 value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TReal64 aValue);
+
+        /**
+        * Insert TTime value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TTime aValue);
+
+        /**
+        * Insert TDesC8 value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TDesC8& aValue);
+
+        /**
+        * Insert TDesC16 value to serialized buffer and move buffer's position 
+        * to after inserted value.
+        * @param aValue value to be insert to current position
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 InsertL(TDesC16& aValue);
+
+		/**
+         * Insert TMdCValueUnion value to serialized buffer and move buffer's position 
+         * to after inserted value.
+         * @param aValue value to be insert to current position
+         * @return new buffer position
+         */
+ 		IMPORT_C TUint32 InsertL(TMdCValueUnion& aValue);
+
+		/**
+         * Insert TMdCSerializationType value to serialized buffer and move buffer's position 
+         * to after inserted value.
+         * @param aValue value to be insert to current position
+         * @param aSize size of value
+         * @return new buffer position
+         */
+ 		IMPORT_C TUint32 InsertL(TMdCSerializationType& aValue, TUint32 aSize);
+
+        /**
+        * Receive TBool value from serialized buffer's current position and 
+        * move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TBool& aDestination);
+
+        /**
+        * Receive TInt8 value from serialized buffer's current position and 
+        * move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TInt8& aDestination);
+
+        /**
+        * Receive TUint8 value from serialized buffer's current position and 
+        * move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TUint8& aDestination);
+
+        /**
+        * Receive TInt16 value from serialized buffer's current position and 
+        * move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TInt16& aDestination);
+
+        /**
+        * Receive TUint16 value from serialized buffer's current position and 
+        * move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TUint16& aDestination);
+
+        /**
+        * Receive TInt32 value from serialized buffer's current position and 
+        * move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TInt32& aDestination);
+
+        /**
+        * Receive TUint32 value from serialized buffer's current position and 
+        * move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TUint32& aDestination);
+
+        /**
+        * Receive TInt64 value from serialized buffer's current position and 
+        * move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TInt64& aDestination);
+
+        /**
+        * Receive TUint value from serialized buffer's current position and 
+        * move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TUint& aDestination);
+
+        /**
+        * Receive TReal32 value from serialized buffer's current position and 
+        * move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TReal32& aDestination);
+
+        /**
+        * Receive TReal64 value from serialized buffer's current position and 
+        * move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TReal64& aDestination);
+
+        /**
+        * Receive TTime value from serialized buffer's current position and 
+        * move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TTime& aDestination);
+
+        /**
+         * Receive TMdCValueUnion value from serialized buffer's current position and 
+         * move buffer's position to after received value.
+         * @param aDestination value received from serialized buffer
+         * @return new buffer position
+         */
+ 		IMPORT_C TUint32 ReceiveL(TMdCValueUnion& aDestination);
+
+		/**
+         * Receive TMdCSerializationType value from serialized buffer's current position and 
+         * move buffer's position to after received value.
+         * @param aDestination value received from serialized buffer
+         * @param aSize size of value
+         * @return new buffer position
+         */
+ 		IMPORT_C TUint32 ReceiveL(TMdCSerializationType& aDestination, TUint32 aSize);
+
+        /**
+        * Receive the length of descriptor which is in the current position of
+        * the serialized buffer. (Current position of the buffer will not change.)
+        * @return the length of descriptor
+        */
+		IMPORT_C TSerializedDesLength ReceiveDesciptorLength() const;
+
+        /**
+        * Receive 8-bit descriptor value from serialized buffer's current 
+        * position and move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TDes8& aDestination);
+
+        /**
+        * Receive 16-bit descriptor value from serialized buffer's current 
+        * position and move buffer's position to after received value.
+        * @param aDestination value received from serialized buffer
+        * @return new buffer position
+        */
+		IMPORT_C TUint32 ReceiveL(TDes16& aDestination);
+
+        /**
+        * Receive 8-bit descriptor value from serialized buffer's current 
+        * position and move buffer's position to after received value.
+        * @return descriptor buffer, which must be destroyed by receiver
+        */
+		IMPORT_C HBufC8* ReceiveDes8L();
+
+        /**
+        * Receive 16-bit descriptor value from serialized buffer's current 
+        * position and move buffer's position to after received value.
+        * @return descriptor buffer, which must be destroyed by receiver
+        */
+		IMPORT_C HBufC16* ReceiveDes16L();
+
+        /**
+        * Receive pointer to 8-bit descriptor value from serialized buffer's
+        * current position and move buffer's position to after received value.
+        * @return descriptor pointer
+        */
+		IMPORT_C TPtrC8 ReceivePtr8L();
+
+        /**
+        * Receive pointer to 16-bit descriptor value from serialized buffer's
+        * current position and move buffer's position to after received value.
+        * @return descriptor pointer
+        */
+		IMPORT_C TPtrC16 ReceivePtr16L();
+
+    private:
+
+        /**
+        * Default constructor
+        */
+        CMdCSerializationBuffer();
+
+        /**
+        * 2nd phase constructor
+        * @param aInitialSize size of the buffer
+        */
+        void ConstructL( TInt32 aSize );
+
+        /**
+        * 2nd phase constructor
+        * @param aInitialSize pointer to the buffer
+        * @param aInitialSize size of the buffer
+        */
+        void ConstructL( TUint8* aBuffer, TInt32 aSize );
+
+	#ifdef _DEBUG
+        void InsertTypeL( TUint16 aType );
+		#define INSERTTYPE(A) InsertTypeL( (TUint16)A );
+
+        void CheckTypeL( TUint16 aType );
+		#define CHECKTYPE(A) CheckTypeL( (TUint16)A );
+        
+        const TDesC& GetPropertyName( TUint16 aType );
+	#else
+	#define INSERTTYPE(A)
+	#define CHECKTYPE(A)
+	#endif
+
+    private:
+
+        /**
+        * The heap buffer
+        */
+        HBufC8* iHeapBuffer;
+
+        /**
+        * The pointer to buffer
+        */
+        TPtr8 iBuffer;
+
+        /**
+        * Current position of the buffer
+        */
+        TUint32 iPosition;
+	};
+
+	
+/**
+ * definitions belongs to querycriteria(de)serialization
+ * files: mdsquerycriteriadeserialization.h, mdequerycriteriaserialization.h
+ */
+const TUint32 KOffsetResultMode = 0; // The begin of the buffer
+const TUint32 KOffsetQueryType = KOffsetResultMode + CMdCSerializationBuffer::KRequiredSizeForTInt32;
+const TUint32 KOffsetNamespaceDefId = KOffsetQueryType + CMdCSerializationBuffer::KRequiredSizeForTDefId;
+const TUint32 KOffsetObjectDefId = KOffsetNamespaceDefId + CMdCSerializationBuffer::KRequiredSizeForTDefId;
+const TUint32 KOffsetObjectDefsIds = KOffsetObjectDefId + CMdCSerializationBuffer::KRequiredSizeForTUint32;
+const TUint32 KOffsetLimit = KOffsetObjectDefsIds + CMdCSerializationBuffer::KRequiredSizeForTUint32;
+const TUint32 KOffsetOffset = KOffsetLimit + CMdCSerializationBuffer::KRequiredSizeForTUint32;
+const TUint32 KOffsetOptimizationFlags = KOffsetOffset + CMdCSerializationBuffer::KRequiredSizeForTUint32;
+const TUint32 KOffsetRootCondition = KOffsetOptimizationFlags + CMdCSerializationBuffer::KRequiredSizeForTUint32;
+const TUint32 KOffsetOrderRules = KOffsetRootCondition + CMdCSerializationBuffer::KRequiredSizeForTUint32;
+const TUint32 KOffsetPropertyFilters = KOffsetOrderRules + CMdCSerializationBuffer::KRequiredSizeForTUint32;
+
+	
+
+#endif // __MDCSERIALIZATIONBUFFER_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdcserializationtype.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,87 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  common item type for all MdE objects
+*
+*/
+
+#include "mdscommoninternal.h"
+#include "mdcserializationbuffer.h"
+
+
+#ifndef __MDCSERIALIZATIONTYPE_H__
+#define __MDCSERIALIZATIONTYPE_H__
+
+NONSHARABLE_CLASS(TMdCSerializationType)
+	{
+	protected:
+		enum TMdCStructTypes
+			{
+			//EMdCItem,
+			EMdCObject,
+			EMdCProperty,
+			EMdCRelation,
+			EMdCEvent,
+			EMdCObjectDef,
+			EMdCPropertyDef,
+			EMdCRelationDef,
+			EMdCEventDef,
+			EMdCNamespaceDef,
+			EMdCSchema,
+			EMdCItems,
+			EMdCItemIds,
+			EMdCItemCount,
+			EMdCLogicCondition,
+			EMdCObjectCondition,
+			EMdCEventCondition,
+			EMdCRelationCondition,
+			EMdCPropertyCondition,
+			EMdCSearchCriteria,
+			EMdCOrderRule,
+			};
+	
+		typedef TInt16 TMdCStructType;
+	
+	protected:
+		TMdCSerializationType(TMdCStructTypes aType) : iType( aType )
+			{
+			}
+
+		/**
+		 * Those methods MUST be always use for serializing
+		 */
+		inline void SerializeL(CMdCSerializationBuffer& aBuffer, TUint32 aSize)
+			{
+			aBuffer.InsertL( *this, aSize );
+			}
+
+		inline void DeserializeL(CMdCSerializationBuffer& aBuffer, TUint32 aSize)
+			{
+			const TMdCStructTypes type = iType;
+			
+			aBuffer.ReceiveL( *this, aSize );
+			
+			if( type != iType )
+				{
+				_LIT( KTMdCSerializationType, "TMdCSerializationType" );
+				__ASSERT_DEBUG( EFalse, User::Panic( KTMdCSerializationType, KErrCorrupt ) );
+
+				User::Leave( KErrCorrupt );
+				}
+			}
+		
+	protected:
+		const TMdCStructTypes iType;
+	};
+
+#endif /* __MDCSERIALIZATIONTYPE_H__ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdeharvestersession.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,351 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Metadata engine Harverster Server client session*
+*/
+
+#ifndef __MDEHARVESTERSESSION_H__
+#define __MDEHARVESTERSESSION_H__
+
+
+#include <e32base.h>
+#include <badesca.h>
+
+#include <mdesession.h>
+
+#include "mdscommoninternal.h"
+
+class CMdESessionImpl;
+class CMdCSerializationBuffer;
+
+NONSHARABLE_CLASS(TGetPendingPgckWrapper)
+	{
+private:
+	TDefId iObjectDefId;
+	
+public:
+
+	TPckgC<TDefId> iObjectDefIdPckg;
+	TPckg<TInt> iIdCountPckg;
+	
+	TGetPendingPgckWrapper(TDefId aObjectDefId, TInt& aIdCount) : 
+		iObjectDefId(aObjectDefId), iObjectDefIdPckg(iObjectDefId), 
+		iIdCountPckg(aIdCount)
+		{
+		}
+	
+	TInt GetIdCount()
+		{
+		return iIdCountPckg();
+		}
+	};
+
+/**
+ * Metadata Engine Harvester Server session.
+ */
+NONSHARABLE_CLASS(CMdEHarvesterSession) : public CBase
+	{
+public:
+	/* Constructors and destructor. */
+
+	/**
+	 * Opens a new metadata engine harvester server session.
+	 *
+	 * @param aObserver  observer to notify when opening the session has been 
+	 *                   completed
+	 *
+	 * @return  metadata engine session
+	 */
+	IMPORT_C static CMdEHarvesterSession* NewL(CMdESession& aSession);
+
+	/**
+	 * Opens a new metadata engine harvester server session and leaves the 
+	 * session in the cleanup stack.
+	 *
+	 * @param aObserver  observer to notify when opening the session has been 
+	 *                   completed
+     *
+	 * @return  metadata engine session
+	 */
+	IMPORT_C static CMdEHarvesterSession* NewLC(CMdESession& aSession);
+
+	/**
+	 * Destructor.
+	 */
+	~CMdEHarvesterSession();
+
+	IMPORT_C void SetSession( CMdESession& aSession );
+	
+	IMPORT_C CMdESession& SessionRef();
+
+	// DEPRICATED
+	IMPORT_C CMdESession* Session();
+	
+	/**
+	 * Add memory card with given media ID and current time. If memory card 
+	 * already exist only time is updated to current time.
+	 * 
+	 * @param memory card's media ID
+	 */
+	IMPORT_C void AddMemoryCard(TUint32 aMediaId);
+
+	/**
+	 * Get latest memory card's media ID.
+	 * @param returned memory card's media ID
+	 * @return EFalse if there is no any memory cards added
+	 */
+	IMPORT_C TBool GetMemoryCard(TUint32& aMediaId);
+
+    /**
+	 * Check if there is memory card with given media ID already in DB.
+	 * 
+	 * @param memory card's media ID
+	 * @param returned boolean if memory card exists or not
+	 * 
+	 * @return EFalse if there was error
+	 * 
+     * @depricated
+	 */
+	IMPORT_C TBool CheckMemoryCard(TUint32 aMediaId, TBool& aExist);
+    
+	/**
+	 * Set media's media ID, drive and present state.
+	 * 
+	 * @param aMediaId media's media ID
+	 * @param aDrive media's drive
+	 * @param aPresentState media's present state
+	 */
+	IMPORT_C void SetMediaL(TUint32 aMediaId, TChar aDrive, 
+			TBool aPresentState);
+
+	/**
+	 * Get media's drive and present state by media ID.
+	 * 
+	 * @param aMediaId media's media ID
+	 * @param aDrive returned media's drive
+	 * @param aPresentState returned media's present state
+	 * @return EFalse if there is no media with matching media ID in DB
+	 */
+	IMPORT_C TBool GetMediaL(TUint32 aMediaId, TChar& aDrive, 
+			TBool& aPresentState);
+
+    /**
+	 * Get present medias' media IDs and drives.
+	 * 
+	 * @param aMedias returned present medias' media IDs and drives
+	 */
+	IMPORT_C void GetPresentMediasL(RArray<TMdEMediaInfo>& aMedias);
+	
+    /**
+     * Set file to present state.
+     * 
+     * @param aMediaId file's media ID
+     * @param aUri file's URI
+     * @param aFileInfo file's modified date and byte size
+     *
+     * @return ETrue if file existed and changing to present state was 
+     *               successful
+     * 
+     * @depricated
+     */
+	IMPORT_C TBool SetFileToPresent(TUint32 aMediaId, const TDesC& aUri, 
+	                               TMdSFileInfo& aFileInfo);
+    
+	/**
+	 * Set files to present state.
+	 * 
+	 * @param aMediaId file's media ID
+	 * @param aUris files' URIs
+	 * @param aFileInfos files' modified dates and byte sizes
+	 * @param aResults Values from TFilePresentStates
+	 */
+	IMPORT_C void SetFilesToPresentL(TUint32 aMediaId, 
+			const RArray<TPtrC>& aUris,
+			const RArray<TMdSFileInfo>& aFileInfos, 
+			RArray<TFilePresentStates>& aResults);
+	
+    /**
+     * Set all files, which media ID is given, to not present or start up not 
+     * present state.
+     *
+     * @param aMediaId memory card's media ID
+     * @deprecated
+     */
+	IMPORT_C void SetFilesToNotPresent(TUint32 aMediaId);
+
+    /**
+     * Remove all objects, which are in not present state, with given media ID
+     * 
+     * @param aMediaId memory card's media ID
+     * @deprecated
+     */
+	IMPORT_C void RemoveFilesNotPresent(TUint32 aMediaId);
+	
+	/**
+     * Set all files, which media ID is given, to not present state.
+     * If aMediaId is 0, call is silently ignored.
+     *
+     * @param aMediaId memory card's media ID
+     * @param aStartUp is start up or normal mount
+     */
+	IMPORT_C void SetFilesToNotPresent(TUint32 aMediaId, TBool aStartUp);
+
+    /**
+     * Remove all objects, which are in not present state, with given media ID.
+     * 
+     * @param aMediaId memory card's media ID
+     * @param aStartUp is start up or normal mount
+     */
+	IMPORT_C void RemoveFilesNotPresent(TUint32 aMediaId, TBool aStartUp);
+
+	/**
+	 * Create global harvester prioritization chunk and set it to MdE Server. 
+	 * There can be only one chunk and observer at once. If MdE Server already 
+	 * contains active observer, old observer completes with KErrAbort, chunk 
+	 * is always changed to this new one. Observer is added using 
+	 * DoAddHarvestingPrioritizationObserver.
+	 *
+     * @param aSize   the size of global chunk that will receive object 
+     *                URIs which need to be prioritize
+	 */
+	IMPORT_C void SetHarvestingPrioritizationChunkL( TInt aSize );
+
+	/**
+	 * Add harvester prioritization observer to MdE Server. There can be 
+	 * only one chunk and observer at once. If MdE Server already contains 
+	 * active observer, aStatus completes with KErrAlreadyExists. When MdE 
+	 * Server needs prioritize object, aStatus completes with KErrNone.
+	 *
+     * @param aStatus the asynchronous response status which is changed 
+     *                when there is object URIs to be prioritize
+	 */
+	IMPORT_C void AddHarvestingPrioritizationObserver(TRequestStatus& aStatus);
+
+	/**
+	 * Cancel harvester prioritization observer from MdE Server. 
+	 *
+	 * @return If MdE Server doesn't have outstanding observer method 
+	 *         returns KErrNotFound, otherwise KErrNone is returned.
+	 */
+	IMPORT_C TInt CancelHarvestingPrioritizationObserver();
+
+	/**
+	 * Return harvester prioritization URI count. Data is valid only after 
+	 * AddHarvestingPrioritizationObserver aStatus is completed.
+	 *
+	 * @return harvester prioritization URI count
+	 */
+	IMPORT_C TInt HarvestingPrioritizationUriCountL();
+
+	/**
+	 * Return harvester prioritization URI from index aIndex. Data is valid 
+	 * only after AddHarvestingPrioritizationObserver aStatus is completed.
+	 *
+	 * @return harvester prioritization URI, ownership is transfered to caller
+	 */
+	IMPORT_C HBufC* HarvestingPrioritizationUriL( TInt aIndex );
+
+	/**
+	 * Objects are left locked automatically after those are added to DB. Only 
+	 * properties and freetexts can be modified after those objects are added 
+	 * to DB. Objects' locking must be removed by commiting those to DB or 
+	 * canceling object.
+	 *
+	 * @param aObjects Array of object to be auto locked after adding
+	 */
+	IMPORT_C void AutoLockL( RPointerArray<CMdEObject>& aObjects );
+	
+	/**
+	 * Change path of objects.
+	 * 
+	 * @param aOldPath old path
+	 * @param aNewPath new path
+     * @param aStatus the asynchronous response status which is changed when 
+     *                URIs are changed
+	 */
+	IMPORT_C void ChangePath( const TDesC& aOldPath, const TDesC& aNewPath,
+			TRequestStatus& aStatus );
+	
+	/**
+	 * Update current C-drive media id to all objects in DB that have the old media id.
+	 */
+	void ChangeCDriveMediaId();
+
+	/**
+	 * Set "binary composing to file" pending flag to objects
+	 *
+	 * @param aObjectId object IDs
+	 */
+	IMPORT_C void SetPendingL( const RArray<TItemId>& aObjectIds );
+
+	/**
+	 * Reset "binary composing to file" pending flag from objects
+	 *
+	 * @param aObjectId object IDs
+	 */
+	IMPORT_C void ResetPendingL( const RArray<TItemId>& aObjectIds );
+
+	/**
+	 * Get count of objects with "binary composing to file" pending flag
+	 *
+	 * @param aObjectDef object definition which limits what objects are
+	 *                   returned or NULL when all objects are returned
+	 * 
+	 * @return count of objects
+	 */
+	IMPORT_C TInt GetPendingCount( const CMdEObjectDef* aObjectDef );
+
+	/**
+	 * Get objects with "binary composing to file" pending flag
+	 *
+	 * @param aObjectDef object definition which limits what objects are
+	 *                   returned or NULL when all objects are returned
+	 * @param aObjectIdCount count of returned object IDs
+	 * @param aObjectIdBuffer serialized buffer of returned object IDs
+	 *
+	 * @return If returned value is > 0, buffer is not large enough for 
+	 * 		    objects ID from DB, otherwise error code is returned.
+	 */
+	IMPORT_C TInt GetPending( 
+			const CMdEObjectDef* aObjectDef, TInt& aObjectIdCount, 
+			CMdCSerializationBuffer& aObjectIdBuffer );
+
+	/**
+	 * Reset DB
+	 * only for internal use (works in DEBUG ONLY!!)
+	 */
+	IMPORT_C void ResetDBL();
+
+private:
+	CMdESessionImpl* iSession;
+
+	RChunk iHarvestingPrioritizationChunk;
+
+	CMdCSerializationBuffer* iHarvestingPrioritizationSerializationBuffer;
+	
+protected:
+
+	/* Constructors. */
+
+	/**
+	 * Constructor.
+	 */
+	CMdEHarvesterSession(CMdESession& aSession);
+
+	/**
+	 * Second-phase constructor.
+	 */
+	void ConstructL();
+	};
+
+#endif  // __MDEHARVESTERSESSION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdepanic.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,86 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Panics the current thread with the
+*                Nokia Metadata Engine Client DLL panic category 
+*
+*/
+
+
+#ifndef __MDEPANIC_H__
+#define __MDEPANIC_H__
+
+
+#include <e32base.h>
+
+
+/**
+ * Panic utility class.
+ */
+NONSHARABLE_CLASS(TMdEPanic)
+	{
+public:
+
+	/**
+	 * Panic numbers.
+	 */
+	enum TReason
+		{
+		EInternal = 0,  // Internal error (that is, a bug in the Metadata Engine Client DLL)
+
+		ESessionOpenInProgress,                             // 1
+		ESessionDuplicateSchemaObserver,                    // 2
+		ESessionUnknownSchemaObserver,                      // 3
+		EItemDoesNotBelongToSession,                        // 4
+		EItemNotInDatabase,                                 // 5
+		ESchemaItemInvalidNameSpaceUri,                     // 6
+		ESchemaItemSetDuplicateSchemaItem,                  // 7
+		EQuantifiedPropertyDefSetDuplicatePropertyDef,      // 8
+		EQuantifiedPropertyDefSetIllegalPropertyDefCount,   // 9
+        EPropertyDefInvalidSize,                            // 10
+		EIntPropertyDefInvalidMinAndMaxValues,              // 11
+        ERealPropertyDefInvalidMinAndMaxValues,             // 12
+		EObjectInvalidUri,                                  // 13
+		EObjectInvalidPropertyDefType,                      // 14
+		EObjectPropertyBelongsToAnotherObject,              // 15
+		EPropertyInvalidSourceUri,                          // 16
+		EPropertyReadOnly,                                  // 17
+		ENumberPropertyIllegalTypeSize,                     // 18
+		EEventInvalidSourceUri,                             // 19
+		EEventInvalidParticipantUri,                        // 20
+		EQueryStateIllegalOperation,                        // 21
+        EQueryDoesntOwnResult,                              // 22
+		EQueryDuplicateObserver,                            // 23
+		EQueryUnknownObserver,                              // 24
+		EConditionLocked,                                   // 25
+        ESchemaItemEmptyName,                               // 26
+
+/*		ESessionOpenFailed,
+		EPropertyReadOnly,
+		EPropertyInvalidOriginUri,
+		EIntPropertyInvalidValue
+*/		};
+
+public:
+
+	/**
+	 * Panics the current thread with the Nokia Metadata Engine Client DLL panic category 
+	 * and the specified panic number.
+	 *
+	 * @param aReason  panic number
+	 */
+	static void Panic(TReason aReason);
+	};
+
+
+#endif  // __MDEPANIC_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdscommoninternal.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,327 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Common message definitions and utilities for MDS internal use
+*
+*/
+
+
+#ifndef MDSCOMMONINTERNAL_H
+#define MDSCOMMONINTERNAL_H
+
+#include <mdccommon.h>
+
+
+//                           X:[<UID>]<database-name>.db
+_LIT( KMdsSqlDbDefaultName, "C:[200009f3]metadata.sq" );
+_LIT( KMdsSqlDbDefaultPath, "C:\\private\\10281E17\\[200009f3]metadata.sq" );
+_LIT( KMdsSqlDbBackupPath, "C:\\private\\200009F5\\[200009f3]metadata.sq" );
+
+// default import metadata file
+_LIT( KMdsDefaultImportFile, "C:\\private\\200009f3\\defaultimportfile.mde" );
+_LIT( KMdsDefaultRomImportFile, "Z:\\private\\200009f3\\defaultimportfile.mde" );
+
+// schema file version
+const TInt KSchemaFileMajorVersion = 2;
+const TInt KSchemaFileMinorVersion = 0;
+
+const TDefId KDefaultNamespaceDefId = 1;
+
+const TDefId KBaseObjectDefId = 1;
+
+const TUint32 KBaseObjectBasicValueColumnOffset = 8;
+
+const TInt KMaxUintValueLength   = 10;
+const TInt KMaxUint64ValueLength = 20;
+
+_LIT( KMdSServerName,"MdSServer" ); // Server name
+_LIT( KSchemaChunkName, "MdSSchema" );
+
+_LIT( KCMediaIdKey, "CDriveMediaId" );
+
+// The server version. A version must be specified when
+// creating a session with the server.
+const TUint KMdSServMajorVersionNumber=2;
+const TUint KMdSServMinorVersionNumber=5;
+const TUint KMdSServBuildVersionNumber=0;
+
+
+const TUint32 KNokiaVendorId = 52487775;
+
+// P&S stuff
+static _LIT_SECURITY_POLICY_PASS(KAllowAllPolicy);
+static _LIT_SECURITY_POLICY_C1(KPowerMgmtPolicy,ECapabilityPowerMgmt);
+
+const TUid KMdSPSShutdown = { 0x20022E94 };
+const TUid KHarvesterPSShutdown = { 0x200009F5 };
+const TUid KWatchdogPSShutdown = { 0x20022E93 };
+
+const TInt KShutdown = 0x00000002;
+
+//Locktype for query
+enum TMdCQueryLockType
+	{
+	EGet,
+	ELock	
+	};
+
+//
+// Common enumerations in client/server messages
+//
+// Server requests
+enum TMdEServRqst
+    {
+    EShutdown = 0,         	// shut down the session
+    EAdd,					// add items
+    ERemove,				// remove items
+    EFind,              	// finds in sync
+    EAsyncFind,         	// finds asynchronously
+    EContinueAsyncFind, 	// continues existing asynchronous find, fetches next set
+    ECancelFind,        	// cancels asynchronous find
+    ECancelObject,      	// cancels opened object
+    ECheckObject,			// get object's "base" values
+    EUpdate,		      	// update items
+    ERegister,          	// registers an object to be notified
+    EListen,            	// listens for events for a registered profile
+    EUnregister,        	// unregisters for no more notifications
+    EGetData,           	// (transfers data server->client)
+    EImportMetadata,    	// starts metadata importing
+    EAsyncImportMetadata,	// starts asynchronous metadata importing
+    EExportMetadata,		// starts metadata exporting
+    EAsyncExportMetadata,	// starts asynchronous metadata exporting
+    EImportSchema,      	// starts schema importing
+    EAddRelationDef,		// Add new relation
+    EAddEventDef,			// Add new event
+    EAddMemoryCard,			// Add new memory card's media ID
+    EGetMemoryCard,			// Get latest memory card's media ID
+    ECheckMemoryCard,		// Check if there is already  memory card with given media ID
+    ESetMedia,				// Set media's media ID, drive and present state to DB
+    EGetMedia,				// Get media's drive and present state from DB
+    EGetPresentMedias,		// Get present medias' media IDs, drives and present states from DB
+    ESetFileToPresent,		// Set file to present state
+    ESetFilesToPresent,		// Set files to present state
+    ESetFilesToNotPresent,	// Set all files, which media ID is given, to not present state
+    ERemoveFilesNotPresent,	// Remove all objects, which are in not present state, with given media ID
+    EGetSchemaVersion,		// Get schema version's major and minor version
+    ESetObjectToPresentByGuid,					// Set object to "present" state by GUID
+    ESetHarvestingPrioritizationChunk,			// Set global harvester prioritization chunk
+    EAddHarvestingPrioritizationObserver,		// Add harvester prioritization observer
+    ECancelHarvestingPrioritizationObserver,	// Cancel harvester prioritization observer
+    EChangePath,            // Change path of objects
+    ESetPending,    		// Set pending flag to objects
+    EResetPending,			// Reset pending flag to objects
+    EGetPendingCount,		// Get count of objects with pending flag
+    EGetPending,			// Get objects with pending flag
+    EResetDB,              	// Reset database (works only in DEBUG build)
+    EChangeMediaId,			// Change C-drive media id and update objects
+    EUnknownMdEServRqst     // handle for unknown requests
+    };
+
+// Server request arguments for 
+// EAddRelationDef and EAddEventDef
+enum TMdEServRqstArgsAddDef
+	{
+	EAddDefArgNamespaceId = 0,
+	EAddDefArgDefName     = 1
+	};
+	
+// Server request arguments for 
+// EFind, EAsyncFind, EContinueAsyncFind and ECancelFind
+enum TMdEServRqstArgsFind
+	{
+	EFindArgQueryId         = 0,
+	EFindArgConditions      = 1,
+	EFindArgResulBufferSize = 2,
+	EFindArgNotifyCount     = 3
+	};
+
+enum TMdEServRqstArgsCheckObject
+	{
+	ECheckObjectArgType           = 0,
+	ECheckObjectArgTypeValue      = 1,
+	ECheckObjectArgNamespaceDefId = 2,
+	ECheckObjectArgObject         = 3
+	};
+
+enum TMdECheckObjectType
+	{
+	ECheckObjectByUri,
+	ECheckObjectById,
+	ECheckObjectByIds
+	};
+
+// Server request arguments for 
+// ESetObjectToPresentByGuid
+enum TMdEServRqstArgsSetObjectToPresentByGuid
+	{
+	ESetObjectToPresentByGuidArgGuidHigh = 0,
+	ESetObjectToPresentByGuidArgGuidLow  = 1
+	};
+	
+// Server request responses
+enum TMdEServRqstComplete
+	{
+    EAsyncFindSetReady  = 1000, // set complete
+    EAsyncFindComplete,         // whole find complete
+    ELoadSchema,        		// fetches schema to client
+
+    /*ENotifyAdded,               // notification: item added
+    ENotifyRemoved,             // notification: item removed
+    ENotifyModified,            // notification: item modified
+    ENotifyObjectPresent,       // notification: object set to present
+    ENotifyObjectNotPresent,    // notification: object set to not present
+    ENotifyRelationPresent,     // notification: relation set to present
+    ENotifyRelationNotPresent,  // notification: relation set to not present
+    ENotifySchemaAdded,         // notification: schema added
+    */
+	};
+		
+	
+// MdE user levels
+enum TUserLevel
+    {
+    EUserLevelNone,
+    EUserLevelNormal,
+    EUserLevelDeviceAccess
+    };
+
+enum TMdEObjectFlags
+	{
+	EMdEObjectFlagNone                 = 0x00000000, // no flags set
+	EMdEObjectFlagNotPresent           = 0x00000001, // object is marked as not present
+	EMdEObjectFlagRemoved              = 0x00000002, // object is marked as removed
+	EMdEObjectFlagFreetexts            = 0x00000004, // object has freetext(s)
+	EMdEObjectFlagConfidential         = 0x00000008, // object is confidential
+	EMdEObjectFlagPlaceholder          = 0x00000010, // object is placeholder
+	EMdEObjectFlagStartUpNotPresent    = 0x00000020, // object is marked as start up not present
+	EMdEObjectFlagContext              = 0x00000040, // object is context object
+	EMdEObjectFlagGarbage              = 0x00000080, // object is marked to be removed by garbage collector
+	
+	EMdeObjectFlagPending			   = 0x00000100, // composing to binary is pending for this object
+	
+	EMdEObjectFlagModObject            = 0x00010000, // object modifications
+	EMdEObjectFlagModProperty          = 0x00020000, // one of properties modifications
+	EMdEObjectFlagModFreeText          = 0x00040000, // one of freetext modifications
+	EMdEObjectFlagModOpen              = 0x00080000, // open for modifications
+	
+	EMdEObjectFlagAutoLock             = 0x00100000, // open for modifications
+	};
+
+enum TMdERelationFlags
+	{
+	EMdERelationFlagNone           = 0x00000000, // no flags set
+	EMdERelationFlagNotPresent     = 0x00000001, // relation's object is not present
+	EMdERelationFlagDeleted        = 0x00000002, // relation's object is marked as removed
+	EMdERelationFlagGarbageDeleted = 0x00080000, // relation's object is marked to be removed by garbage collector
+	};
+
+enum TMdEPropertyFlags
+	{
+	EPropertyReadOnly   = 0x01,
+	EPropertyMandatory  = 0x02,
+	};
+
+enum TMdEPropertyModFlags
+	{
+	EMdEPropertyModNone   = 0x00,
+	EMdEPropertyModChange = 0x01,
+	EMdEPropertyModRemove = 0x02,
+	};
+	
+enum TMdSObserverNotificationType
+	{
+	EObjectNotifyAdd          = 0x00000001,
+	EObjectNotifyModify       = 0x00000002,
+	EObjectNotifyRemove       = 0x00000004,
+
+	EObjectNotifyPresent      = 0x00000010,
+	EObjectNotifyNotPresent   = 0x00000020,
+	
+	ERelationNotifyAdd        = 0x00000100,
+	ERelationNotifyModify     = 0x00000200,
+	ERelationNotifyRemove     = 0x00000400,
+
+	ERelationNotifyPresent    = 0x00001000,
+	ERelationNotifyNotPresent = 0x00002000,
+
+	//ERelationItemNotifyAdd    = 0x00010000,
+	//ERelationItemNotifyModify = 0x00020000,
+	ERelationItemNotifyRemove = 0x00040000,
+	
+	
+	EEventNotifyAdd           = 0x00100000,
+	EEventNotifyRemove        = 0x00200000,
+	
+	ESchemaModify             = 0x01000000,
+	
+	// 0x80000000 is not allowed (signed number is negative)
+	};
+
+// File info
+struct TMdSFileInfo
+	{
+	/** Last modification time. */
+	TInt64 iModifiedTime;
+
+	/** File size in bytes. */
+	TUint32 iSize;
+	};
+
+/** Storage state flags.  */
+enum TStoredFlags
+	{
+	EStoredFlagsNone  = 0x0000,
+	EStoredFlagsDB    = 0x0001, // data stored in DB
+	EStoredFlagsTable = 0x0002, // table is stored in DB
+	EStoredFlagsC2P   = 0x0004, // data is stored in Col2Prop table
+	};
+
+/**
+ * Query's internal optimization flags
+ */
+enum TInternalOptimizationFlags
+	{
+	EContainsObjectCondition     = 0x00000001,
+	EContainsRelationCondition   = 0x00000002,
+	EContainsEventCondition      = 0x00000004,
+	EContainsFreetextCondition   = 0x00000008,
+	EContainsNotPresentCondition = 0x00000010,
+	EContainsObjectLocking       = 0x00000020,
+	EContainsPlaceholdersOnly    = 0x00000040
+	};
+
+struct TMdEMediaInfo
+	{
+	TUint32 iMediaId;
+	TChar iDrive;
+	};
+	
+/**
+ * File present states.
+ * Values must be between 0 and 255.
+ */
+enum TFilePresentStates
+	{
+	EMdsNotFound = 0,
+	EMdsNormal,
+	EMdsPlaceholder,
+	EMdsModified
+	};
+	
+struct TMdSMediaIdAndCount
+	{
+	TUint32 iMediaId;
+	TUint32 iCount;
+	};	
+	
+#endif //MDSCOMMONINTERNAL_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdssqlconnection.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Abstract SQL connection class*
+*/
+
+// -----------------------------------
+// RMdsStatement
+// -----------------------------------
+
+inline RMdsStatement::RMdsStatement( )
+    : iPrepared( EFalse )
+    {
+    }
+
+inline void RMdsStatement::Close()
+    {
+    iStatement.Close();
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdssqliteconnection.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,333 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Adaptation layer to SQLite database*
+*/
+
+#ifndef __MDSSQLITECONNECTION_H__
+#define __MDSSQLITECONNECTION_H__
+
+#include <e32base.h>
+#include <sqldb.h>
+
+#include "mdssqlrow.h"
+
+
+// FORWARD DECLARATION
+class RMdsStatement;
+
+
+
+// CLASS DECLARATION
+/**
+* Class represents methods to communication with SQLite database API.
+*/
+NONSHARABLE_CLASS(CMdSSqLiteConnection): public CBase
+	{
+    public: // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        * @param 
+        * @return 
+        */
+        static CMdSSqLiteConnection* NewL();
+        
+        /**
+        * Two-phased constructor.
+        * @param 
+        * @return 
+        */
+        static CMdSSqLiteConnection* NewLC();
+
+        /**
+        * Destructor.
+        */   
+        virtual ~CMdSSqLiteConnection();
+        
+        /**
+         * Deletes database from disc
+         *
+         * @param aName name of database or NULL to delete default one
+         */
+        static void DeleteDb( TDesC16* aName = NULL );
+        
+    private: // Private constructors
+
+        /**
+        * CSqLiteConnection.
+        * C++ default constructor.
+        */        
+        CMdSSqLiteConnection();
+
+        /**
+        * ConstructL.
+        * 2nd phase constructor.
+        */        
+        void ConstructL();
+
+    public: // Methods from CMdSSqLiteConnection
+
+		/**
+		 * Open database (creates if doesn't exist)
+		 * @param aFile Database filename and path
+		 */
+        void OpenDbL( const TDesC& aDbFileName );
+
+        /**
+         * Close opened database
+         */
+        void CloseDb();
+
+        /**
+         * Execute sql command (not a query)
+         * @param aCommand SQL clause to be executed (can include wildcards)
+         * @param aVariables data that will replace wildcards in the command
+         * @return KErrNone, if successful, otherwise one of the error codes.
+         */
+        TInt ExecuteL( const TDesC& aCommand,
+                       const RRowData& aVariables,
+                       RMdsStatement* aStatement = NULL );
+
+        /**
+         * Prepare and execute sql query
+         * @param aQuery the SQL query to perform
+         * @param aStatement ptr to statement id, which must be initially NULL.
+         *        The statement can be used for executing the same query several
+         *        times with different variables. Note that finally the statement
+         *        must be terminated.
+         * @param aVariables data that will replace wildcards in the command
+         */
+        void ExecuteQueryL( const TDesC& aQuery,
+        					RMdsStatement& aStatement,
+            				const RRowData& aVariables );
+
+        /**
+         * Get next row in query
+         * @param aQuery ID of the query
+         * @param aRow specifies target for the data to receive
+         * @return true if there are more rows available
+         */
+        TBool NextRowL( RMdsStatement& aQuery, RRowData& aRow );
+
+        /**
+         * Update the current row in query
+         * (in case some of the datatypes need to change)
+         * @param aQuery ID of the query
+         * @param aRow specifies target for the data to receive
+         * @return true if there are more rows available
+         */
+        void CurrentRowL( const RMdsStatement& aQuery, RRowData& aRow );
+
+        /**
+         * terminates a running query or execution loop
+         * @param aStatement ID of the statement
+         */
+        void Terminate( RMdsStatement& aQuery );
+        
+        /**
+         * Rolls back the transaction explicitly
+         * - possibility to receive leave
+         * eliminates actions on destructor.
+         */
+        void TransactionBeginL();
+
+        /**
+         * Resets the transaction
+         * (does not commit or rollback or do anything)
+         */
+        void TransactionCommitL();
+
+        /**
+         * error within transaction
+         */
+        void TransactionRollbackL();
+
+        /**
+         * Returns DB filename of the connection.
+         */
+        const TDesC& DbFileName() const;
+        
+        void EnableTransaction( TBool aEnable, RMdsStatement& aQuery );
+
+    protected: // Personal methods     
+
+        /**
+        * Binds variables in SQLite interface
+        * @param aStatement SQLite statement handle
+        * @param aVariables the list of variables to bind
+        */
+        void DoBindL( RSqlStatement& aStatement, const RRowData& aVariables );
+
+        /**
+        * Reads row column variables from SQLite interface
+        * @param aStatement SQLite statement handle
+        * @param aRow the row buffer where to read the column data
+        */
+        void ColumnsL( const RSqlStatement& aStatement, RRowData& aRow );
+
+        /**
+        * Saves trace of last SQL error and leaves.
+        * @param aFailedCommand a C-style representation of the failed SqLite command (for logging)
+        * @param aSqliteError the error reported by sqlite
+        */
+        void TraceAndLeaveL( const TDesC& aFailedCommand, TInt aSqliteError );
+
+    private: // Member data
+
+        /**
+         * iMdeSqlDb, interface to the Sqlite database.
+         */
+        RSqlDatabase iMdeSqlDb;
+
+        HBufC* iDbFileName;
+        
+        TBool iEnableTransaction;
+        
+        TBool iTransactionOngoing;
+		
+	    RMdsStatement* iNotFinishFindQuery;
+	};
+
+const TInt KDoNothing = 99;
+
+/**
+* Transaction class
+*/
+class RMdSTransaction
+    {
+    public:
+
+        /**
+        * constructor
+        * creates a transaction to given connection
+        */
+        inline RMdSTransaction( CMdSSqLiteConnection& aConnection )
+            : iConnection( aConnection )
+            {
+            TRAP( iErrorState, iConnection.TransactionBeginL() );
+            }
+
+        /**
+        * cleanup method (from TBase)
+        * according to status does Commit/Rollback/nothing
+        */
+        inline void Close()
+            {
+            if ( iErrorState != KErrNone )
+                {
+                TRAP( iErrorState, iConnection.TransactionRollbackL() );
+                }
+            }
+
+        /**
+        * Commits the transaction explicitly
+        * - possibility to receive leave
+        * eliminates actions on destructor.
+        */
+        inline void CommitL()
+            {
+            iConnection.TransactionCommitL();
+            Reset();
+            }
+
+        /**
+        * Rolls back the transaction explicitly
+        * - possibility to receive leave
+        * eliminates actions on destructor.
+        */
+        inline void RollbackL()
+            {
+            iConnection.TransactionRollbackL();
+            Reset();
+            }
+
+        /**
+        * Resets the transaction
+        * (does not commit or rollback or do anything)
+        */
+        inline void Reset()
+            {
+            iErrorState = KDoNothing;
+            }
+
+        /**
+        * error within transaction
+        */
+        inline TInt Error()
+            {
+            return iErrorState;
+            }
+
+    protected:
+
+
+        /** the connection */
+    	CMdSSqLiteConnection& iConnection;
+
+        /** transaction begin error */
+        TInt iErrorState;
+    };
+
+/**
+* An open statement stack helper
+* ensures a statement gets terminated
+*/
+class RMdsStatement
+    {
+    friend class CMdSSqLiteConnection;
+    public:
+        /** constructor */
+        inline RMdsStatement( )
+            : iPrepared( EFalse )
+            {
+            }
+
+        inline void RMdsStatement::Close()
+            {
+            iStatement.Close();
+            }
+    private:
+
+		/** SQL statement */
+		RSqlStatement iStatement;
+		
+        /** if statement was already prepared */
+        TBool iPrepared;
+    };
+
+/*
+
+  how to use the statement stack helper:
+
+  {
+  RMdsStatement st( connection );
+  CleanupClosePushL( st );
+  connection.ExecuteL( clause, variables1, st ); // prepared and executed
+  connection.ExecuteL( clause, variables2, st ); // executed normally
+  CleanupStack::PopAndDestroy( st );
+  } // statement automatically terminated
+
+  {
+  RMdsStatement st( connection );
+  CleanupClosePushL( st );
+  connection.ExecuteQueryL( query, st, variables1 );
+  connection.NextRowL( st, results1 ); // fetch a result row
+  connection.ExecuteQueryL( query, st, variables2 ); // query with different variable set
+  connection.NextRowL( st, results2 ); // fetch another resut row
+  CleanupStack::PopAndDestroy( st );
+  } // statement automatically terminated
+
+*/
+	
+#endif	// __MDSSQLITECONNECTION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdssqlrow.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,220 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Abstract SQL connection class*
+*/
+
+#ifndef __MDSSQLCONNECTION_H__
+#define __MDSSQLCONNECTION_H__
+
+#include <e32base.h>
+#include "mdccommon.pan"
+
+#include "mdscommoninternal.h"
+
+
+// types of columns
+enum TColumnDataType
+    {
+    EColumnNotUsed,
+    EColumnBool,
+    EColumnInt32,
+    EColumnUint32,
+    EColumnInt64,
+    EColumnReal32,
+    EColumnReal64,
+    EColumnTime,
+    EColumnDes8,
+    EColumnDes16,  // could be used as Unknown, because it checks the
+                   // actual type from sqlite
+    EColumnHBuf8,  // local pointer responsibility
+    EColumnHBuf16, // local pointer responsibility
+    EColumnNullDes8,
+    EColumnNullDes16, // used when db column is null 
+    //EColumnUnknown
+    
+    EColumnTItemId = EColumnUint32, // should be changed according to TItemId definition
+    EColumnTDefId = EColumnUint32, // should be changed according to TDefId definition
+    };
+
+/**
+* A class representing a database column.
+* The column contains a type and an untyped pointer, which can
+* be cast to represent various types.
+*/
+NONSHARABLE_CLASS(TColumn)
+    {
+    public:
+        /** Returns column type. */
+        inline TColumnDataType Type() const;
+
+        /** Constructs a column with data type only. Use for queries. */
+        inline TColumn( TColumnDataType aType = EColumnNotUsed );
+
+        /** frees allocated memory in this column */
+        inline void Free();
+
+        // constructors
+
+        TColumn( TInt32 aVal ) { Set( aVal ); }
+        TColumn( TUint32 aVal ) { Set( aVal ); }
+        TColumn( TBool aVal ) { Set( aVal ); }
+        TColumn( TInt64 aVal ) { Set( aVal ); }
+        TColumn( TReal32 aVal ) { Set( aVal ); }
+        TColumn( TReal64 aVal ) { Set( aVal ); }
+        TColumn( TTime aVal ) { Set( aVal ); }
+        TColumn( const TDesC8& aVal ) { Set( aVal ); }
+        TColumn( const TDesC16& aVal ) { Set( aVal ); }
+        TColumn( const HBufC8* aVal ) { Set( aVal ); }
+        TColumn( const HBufC16* aVal ) { Set( aVal ); }
+
+        // data setters & getters
+        
+        inline void Set( TInt32 aVal );
+
+        inline void Set( TUint32 aVal );
+
+        inline void Set( TBool aVal );
+
+        inline void Set( TInt64 aVal );
+
+        inline void Set( TReal32 aVal );
+
+        inline void Set( TReal64 aVal );
+
+        inline void Set( TTime aVal );
+
+        inline void Set( const TDesC8& aVal );
+
+        inline void Set( const TDesC16& aVal );
+
+        inline void Set( const HBufC8* aVal );
+
+        inline void Set( const HBufC16* aVal );
+
+        inline void NotUsed();
+
+        // data getters
+
+        inline void Get( TInt32& aValue ) const;
+
+        inline void Get( TUint32& aValue ) const;
+
+        inline void Get( TBool& aValue ) const;
+
+        inline void Get( TInt64& aValue ) const;
+
+        inline void Get( TReal32& aValue ) const;
+
+        inline void Get( TReal64& aValue ) const;
+
+        inline void Get( TTime& aValue ) const;
+
+        inline void Get( TPtrC8& aValue ) const;
+
+        inline void Get( TPtrC16& aValue ) const;
+
+        inline TBool IsNull();
+
+        /**
+        * type of data in this column
+        */
+        TColumnDataType iType;
+
+        /**
+        * a structure to store multi-typed data
+        */
+        union TMultiTypeData
+            {
+            /*struct
+                {
+                TUint32 iLow;
+                TUint32 iHigh;
+                } iInt64;*/
+            TInt64 iInt64;
+            
+            TReal32 iReal32;
+            TReal64 iReal64;
+            TInt32 iInt32;
+            TUint32 iUint32;
+            struct
+                {
+                TAny* iPtr;
+                TInt iLen;
+                } iText;
+            };
+
+        /**
+        * multi-use data in this column
+        */
+        TMultiTypeData iData;
+    };
+
+/**
+* A class representing a database row.
+* The class describes each column type and the data in the column.
+* where column data is located. The class is provided during
+* query and is used when each row is read. Note that the
+* buffer class MAY be modified by the user during the query.
+* The same class is also used when replacing wildcards with
+* variable data.
+*/
+class RRowData
+    {
+    public:
+
+        /**
+        * constructor
+        */
+        inline RRowData();
+
+        /** Closes all the resources used by this object */
+        inline void Close();
+
+        /** frees allocated memory in this row */
+        inline void Free();
+
+        /** number of columns or variables */
+        inline TInt Size() const;
+
+        /** returns column by index */
+        inline TColumn& Column( TInt aIndex );
+
+        /** returns column by index */
+        inline const TColumn& Column( TInt aIndex ) const;
+
+        /** Appends a new column in row */
+        inline TColumn& AppendL( const TColumn& aColumn );
+
+        /** Resets the row */
+        inline void Reset();
+
+		/** Copy all columns */
+		void AppendColumnTypesL( RRowData& aColumnTypeRow );
+
+		/** Receive space to row */
+		void ReserveL( TInt aColumnCount );
+		
+    protected:
+
+        /** The array of columns */
+        RArray<TColumn> iColumns;
+    };
+
+
+#include "mdssqlrow.inl" // inline methods
+
+#endif	// __MDSSQLCONNECTION_H__
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdssqlrow.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,336 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Abstract SQL connection class*
+*/
+
+// -----------------------------------
+// TColumn
+// -----------------------------------
+
+inline TColumn::TColumn( TColumnDataType aType ) :
+	iType( aType )
+    {
+    iData.iInt32 = 0;
+    }
+
+inline TColumnDataType TColumn::Type() const
+    {
+    // the HBuf types are internal and hidden.
+    switch ( iType )
+	    {
+	    case EColumnHBuf8:
+	    	return EColumnDes8;
+	    case EColumnHBuf16:
+	    	return EColumnDes16;
+		case EColumnNullDes8:
+			return EColumnDes8;
+		case EColumnNullDes16:
+			return EColumnDes16;
+		default:
+			return iType;
+	    }
+    }
+
+inline void TColumn::Free()
+    {
+    if ( iType == EColumnHBuf8 )
+        {
+        delete (HBufC8*)iData.iText.iPtr;
+        iData.iText.iPtr = 0;
+        }
+    else if ( iType == EColumnHBuf16 )
+        {
+        delete (HBufC16*)iData.iText.iPtr;
+        iData.iText.iPtr = 0;
+        }
+    }
+
+inline void TColumn::Set( TInt32 aVal ) 
+    {
+    iType = EColumnInt32;
+    iData.iInt32 = aVal;
+    }
+
+inline void TColumn::Set( TUint32 aVal ) 
+    {
+    iType = EColumnUint32;
+    iData.iUint32 = aVal;
+    }
+
+inline void TColumn::Set( TBool aVal )
+    {
+    iType = EColumnBool;
+    iData.iInt32 = aVal;
+    }
+
+inline void TColumn::Set( TInt64 aVal )
+    {
+    iType = EColumnInt64;
+    iData.iInt64 = aVal;
+    }
+
+inline void TColumn::Set( TReal32 aVal ) 
+    {
+    iType = EColumnReal32;
+    iData.iReal32 = aVal;
+    }
+
+inline void TColumn::Set( TReal64 aVal ) 
+    {
+    iType = EColumnReal64;
+    iData.iReal64 = aVal;
+    }
+
+inline void TColumn::Set( TTime aVal )
+    {
+    iType = EColumnTime;
+    iData.iInt64 = aVal.Int64();
+    }
+
+inline void TColumn::Set( const TDesC8& aVal )
+    {
+    iType = EColumnDes8;
+    iData.iText.iPtr = (TAny*)aVal.Ptr();
+    iData.iText.iLen = aVal.Length();
+    }
+
+inline void TColumn::Set( const TDesC16& aVal )
+    {
+    iType = EColumnDes16;
+    iData.iText.iPtr = (TAny*)aVal.Ptr();
+    iData.iText.iLen = aVal.Length();
+    }
+
+inline void TColumn::Set( const HBufC8* aVal )
+    {
+    iType = ( aVal ? EColumnHBuf8 : EColumnNullDes8 );
+    iData.iText.iPtr = (TAny*)aVal;
+    }
+
+inline void TColumn::Set( const HBufC16* aVal )
+    {
+    iType = ( aVal ? EColumnHBuf16 : EColumnNullDes16 );
+    iData.iText.iPtr = (TAny*)aVal;
+    }
+
+inline void TColumn::NotUsed()
+    {
+    iType = EColumnNotUsed;
+    iData.iText.iPtr = 0;
+    }
+
+
+inline void TColumn::Get( TInt32& aValue ) const
+    {
+    if( EColumnNullDes16 == iType )
+    	{
+    	aValue = 0;
+    	return;
+    	}
+
+    __ASSERT_DEBUG( iType == EColumnInt32, MMdCCommon::Panic( EDatabaseFault ) );
+    aValue = iData.iInt32;
+    }
+
+inline void TColumn::Get( TUint32& aValue ) const
+    {
+    if( EColumnNullDes16 == iType )
+    	{
+    	aValue = 0;
+    	return;
+    	}
+
+	__ASSERT_DEBUG( iType == EColumnUint32, MMdCCommon::Panic( EDatabaseFault ) );
+    aValue = iData.iUint32;
+    }
+
+inline void TColumn::Get( TBool& aValue ) const 
+    {
+    if( EColumnNullDes16 == iType )
+    	{
+    	aValue = EFalse;
+    	return;
+    	}
+
+	__ASSERT_DEBUG( iType == EColumnBool, MMdCCommon::Panic( EDatabaseFault ) );
+    aValue = iData.iInt32;
+    }
+
+inline void TColumn::Get( TInt64& aValue ) const
+    {
+    if( EColumnNullDes16 == iType )
+    	{
+    	aValue = 0;
+    	return;
+    	}
+
+	__ASSERT_DEBUG( iType == EColumnInt64, MMdCCommon::Panic( EDatabaseFault ) );
+    aValue = iData.iInt64;
+    }
+
+inline void TColumn::Get( TReal32& aValue ) const
+    {
+    if( EColumnNullDes16 == iType )
+    	{
+    	aValue = 0.0f;
+    	return;
+    	}
+
+	__ASSERT_DEBUG( iType == EColumnReal32, MMdCCommon::Panic( EDatabaseFault ) );
+    aValue = iData.iReal32;
+    }
+
+inline void TColumn::Get( TReal64& aValue ) const
+    {
+    if( EColumnNullDes16 == iType )
+    	{
+    	aValue = 0.0f;
+    	return;
+    	}
+
+	__ASSERT_DEBUG( iType == EColumnReal64, MMdCCommon::Panic( EDatabaseFault ) );
+    aValue = iData.iReal64;
+    }
+
+inline void TColumn::Get( TTime& aValue ) const
+    {
+    if( EColumnNullDes16 == iType )
+    	{
+    	aValue = TTime( 0 );
+    	return;
+    	}
+    
+	__ASSERT_DEBUG( iType == EColumnTime, MMdCCommon::Panic( EDatabaseFault ) );
+    aValue = TTime(iData.iInt64);
+    }
+
+inline void TColumn::Get( TPtrC8& aValue ) const
+    {
+    if ( iType == EColumnDes8 )
+        {
+        aValue.Set(
+            (TUint8*)iData.iText.iPtr,
+            iData.iText.iLen );
+        }
+    else if ( iType == EColumnHBuf8 )
+        {
+        aValue.Set(
+            ((HBufC8*)iData.iText.iPtr)->Des() );
+        }
+    else if ( iType == EColumnNullDes8 ||
+        iType == EColumnNullDes16 )
+        {
+        aValue.Set( KNullDesC8().Ptr(), 0 );
+        }
+    else MMdCCommon::Panic( EDatabaseFault );
+    }
+
+inline void TColumn::Get( TPtrC16& aValue ) const
+    {
+    if ( iType == EColumnDes16 )
+        {
+        aValue.Set(
+            (TUint16*)iData.iText.iPtr,
+            iData.iText.iLen );
+        }
+    else if ( iType == EColumnHBuf16 )
+        {
+        aValue.Set(
+            ((HBufC16*)iData.iText.iPtr)->Des() );
+        }
+    else if ( iType == EColumnNullDes16 )
+        {
+        aValue.Set( KNullDesC16().Ptr(), 0 );
+        }
+    else MMdCCommon::Panic( EDatabaseFault );
+    }
+
+inline TBool TColumn::IsNull()
+    {
+    return ( iType == EColumnNullDes8 ||
+        iType == EColumnNullDes16  ||
+        ( iData.iText.iPtr == NULL &&
+          ( iType == EColumnDes8 || iType == EColumnDes16 ||
+            iType == EColumnHBuf8 || iType == EColumnHBuf16 ) ) );
+    }
+
+// -----------------------------------
+// RRowData
+// -----------------------------------
+
+
+inline RRowData::RRowData()
+    : iColumns( 16 )
+    {
+    }
+
+inline void RRowData::Close()
+    {
+    Free();
+    iColumns.Close();
+    }
+
+inline void RRowData::Free()
+    {
+    const TInt count( Size() );
+    for ( TInt i=0; i<count; ++i )
+        {
+        iColumns[i].Free();
+        }
+    }
+
+inline TInt RRowData::Size() const
+    {
+    return iColumns.Count();
+    }
+
+inline TColumn& RRowData::Column( TInt aIndex )
+    {
+    return iColumns[aIndex];
+    }
+
+inline const TColumn& RRowData::Column( TInt aIndex ) const
+    {
+    return iColumns[aIndex];
+    }
+
+inline TColumn& RRowData::AppendL( const TColumn& aColumn )
+    {
+    iColumns.AppendL( aColumn );
+    return iColumns[ Size()-1 ];
+    }
+
+inline void RRowData::Reset()
+    {
+    iColumns.Reset();
+    }
+
+inline void RRowData::AppendColumnTypesL( RRowData& aColumnTypeRow )
+	{
+	Free();
+	Reset();
+	
+	const TInt columnCount = aColumnTypeRow.Size();
+	ReserveL( columnCount );
+
+	for( TInt i = 0; i < columnCount; i++ )
+		{
+	    iColumns.Append( aColumnTypeRow.Column( i ).Type() ); 
+		}
+	}
+
+inline void RRowData::ReserveL( TInt aColumnCount )
+	{
+	iColumns.ReserveL( aColumnCount );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/mdsutils.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,529 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Common utilities for the Metadata System.
+*
+*/
+
+#ifndef MDSUTILS_H
+#define MDSUTILS_H
+
+#include <ecom/implementationinformation.h>
+
+#include <e32math.h>
+
+const TInt KMdEErrHarvestingFailed = 300; 			// Error occured while harvesting - retry in case of this error
+const TInt KMdEErrHarvestingFailedPermanent = 301;  // Error occured while harvesting - do not retry harvesting
+const TInt KMdEErrHarvestingFailedUnknown = 302;    // Unknown error occurred - do not retry harvesting 
+    
+namespace MdsUtils
+    {
+    
+    /**
+     * CleanupPtrArray function is used for cleanup support of locally declared arrays.
+     *
+     * @param aArray  An array to cleanup
+     */
+    template<typename T> inline void CleanupPtrArray( TAny* aArray )
+        {
+        static_cast<RPointerArray<T>*>(aArray)->ResetAndDestroy();
+        static_cast<RPointerArray<T>*>(aArray)->Close();
+        }
+        
+    /**
+     * CleanupEComArray function is used for cleanup support of locally declared arrays.
+     *
+     * @param aArray  An array to cleanup
+     */
+    inline void CleanupEComArray( TAny* aArray )
+        {
+        CleanupPtrArray<CImplementationInformation>( aArray );
+        }
+
+    /**
+     * Get file volume info from the file system.
+     * @param aUri  File URI.
+     * @param aVolumeInfo  Reference to the object where volume info is stored to.
+     */
+    inline TInt GetVolumeInfo(const RFs& aFs, const TDesC& aUri, TVolumeInfo& aVolumeInfo )
+        {
+        if ( aUri.Size() <= 0 )
+            {
+            return KErrArgument;
+            }
+
+        TInt driveNumber( 0 );
+        TInt error( 0 );
+
+        error = aFs.CharToDrive( aUri[0], driveNumber );
+
+        if ( error != KErrNone )
+            {
+            return error;
+            }
+
+        error = aFs.Volume( aVolumeInfo, driveNumber );
+
+        return error;
+        }
+
+    /**
+     * Returns a 32-bit unsigned integer from the location pointed by
+     * the parameter.
+     * @param aPointer  Memory pointer (input).
+     * @return Converted integer.
+     */
+    inline TUint32 ToUInt32L( TUint8* aPointer )
+        {
+        if ( !aPointer )
+            {
+            User::Leave( KErrGeneral );
+            }
+            
+        TUint32 ret = *( aPointer + 3 );
+        ret = ( ret << 8 ) + *( aPointer + 2 );
+        ret = ( ret << 8 ) + *( aPointer + 1 );
+        ret = ( ret << 8 ) + *aPointer;
+        return ret;
+        }
+
+    /**
+     * Returns a 16-bit unsigned integer from the location pointed by
+     * the parameter.
+     * @param aPointer  Memory pointer (input).
+     * @return Converted integer.
+     */
+    inline TUint16 ToUInt16L( TUint8* aPointer )
+        {
+        if ( !aPointer )
+            {
+            User::Leave( KErrGeneral );
+            }
+            
+        TUint16 ret = *( aPointer + 1 );
+        ret = STATIC_CAST( TUint16, ( ret << 8 ) + *aPointer );
+        return ret;
+        }
+
+    /**
+     * Converts GPS coordinates from Exif degrees to decimal representation.
+     * @param aSourceDes  Source descriptor.
+     * @param aCoordinate  Output coordinate (latitude or longitude).
+     */
+    inline void ConvertFromDegreesToDecimalL( const TDes8& aSourceDes, TReal64& aCoordinate )
+        {
+        if ( aSourceDes.MaxSize() < 24 )
+            {
+            User::Leave( KErrArgument );
+            }
+
+        TUint8* ptr = CONST_CAST( TUint8*, aSourceDes.Ptr() );
+
+        TUint32 degrees         = ToUInt32L( ptr );
+        TUint32 deg_denominator = ToUInt32L( ptr + 4 );
+        TUint32 minutes         = ToUInt32L( ptr + 8 );
+        TUint32 min_denominator = ToUInt32L( ptr + 12 );
+        TUint32 seconds         = ToUInt32L( ptr + 16 );
+        TUint32 sec_denominator = ToUInt32L( ptr + 20 );
+
+        // check that coordinate doesn't contain division by zero
+        // in those numerators which are not 0
+        if ( ( deg_denominator == 0 && degrees ) || 
+        	 ( min_denominator == 0 && minutes ) || 
+        	 ( sec_denominator == 0 && seconds ) )
+        	{
+        	User::Leave( KErrCorrupt );
+        	}
+
+        aCoordinate = 0.0;
+
+        if( degrees )
+        	{
+            TReal64 degreesReal = degrees;
+            TReal64 deg_denominatorReal = deg_denominator;
+        	aCoordinate += degreesReal / deg_denominatorReal;
+        	}
+        if( minutes )
+        	{
+            TReal64 minutesReal = minutes;
+            TReal64 min_denominatorReal = min_denominator;
+        	aCoordinate += minutesReal / (min_denominatorReal * 60.0);
+        	}
+        if( seconds )
+        	{
+            TReal64 secondsReal = seconds;
+            TReal64 sec_denominatorReal = sec_denominator;
+        	aCoordinate += secondsReal / (sec_denominatorReal * 3600.0);
+        	}
+        }
+
+    /**
+     * Converts GPS coordinates from decimal to degree representation used by Exif.
+     * Method leaves with KErrArgument if max size of aTgtDes < 24.
+     * @param aCoordinate  Input coordinate (latitude or longitude).
+     * @param aTgtDes  Output descriptor.
+     */
+    inline void ConvertFromDecimalToDegreesL( TReal64 aCoordinate, TDes8& aTgtDes )
+        {
+        if ( aTgtDes.MaxSize() < 24 )
+            {
+            User::Leave( KErrArgument );
+            }
+
+        const TUint32 KDenominator1 = 1;
+        const TUint32 KDenominator10M = 10000000;
+        const TReal64 KDenominator10MReal = KDenominator10M;
+
+        TReal64 degs64 = aCoordinate;
+
+        TReal64 mins64 = 0.0;
+        Math::Frac( mins64, degs64 );
+        mins64 *= 60.0;
+
+        TReal64 secs64 = 0.0;
+        Math::Frac( secs64, mins64 );
+        secs64 *= 60.0 * KDenominator10MReal;
+
+        TUint32 degrees = (TUint32)( degs64 );
+        TUint32 minutes = (TUint32)( mins64 );
+        TUint32 seconds = (TUint32)( secs64 );
+
+        aTgtDes.Append( (TUint8*) &degrees, 4 );
+        aTgtDes.Append( (TUint8*) &KDenominator1, 4 );
+
+        aTgtDes.Append( (TUint8*) &minutes, 4 );
+        aTgtDes.Append( (TUint8*) &KDenominator1, 4 );
+
+        aTgtDes.Append( (TUint8*) &seconds, 4 );
+        aTgtDes.Append( (TUint8*) &KDenominator10M, 4 );
+        }
+
+    inline TBool IsValidProcessId( const TUid aUid )
+        {
+        const TUint32 KMinProcessId = 0x10000000;
+        const TUint32 KMaxProcessId = 0xFFFFFFFF;
+
+        if ( aUid.iUid < KMinProcessId || aUid.iUid > KMaxProcessId )
+            {
+            return EFalse;
+            }
+        return ETrue;    
+        }
+    
+    /**
+     * Converts trap errors to harvesting errors.
+     * @param aTrapError  Trapped error to convert
+     * @param aPluginError  Output error
+     */
+    inline void ConvertTrapError( TInt aTrapError, TInt &aPluginError )
+        {
+        aPluginError = KErrNone;
+        if ( aTrapError == KErrArgument ||        // -6
+            aTrapError == KErrCorrupt ||          // -20
+            aTrapError == KErrAccessDenied ||     // -21
+            aTrapError == KErrPermissionDenied || // -46
+            aTrapError == KErrNotFound ||         // -1
+            aTrapError == KErrNotSupported )      // -5
+            {
+            aPluginError = KMdEErrHarvestingFailedPermanent;    
+            }
+        else if ( aTrapError == KErrGeneral ||       // -2
+        		 aTrapError == KErrNoMemory ||       //-4
+                 aTrapError == KErrInUse ||          // -14
+                 aTrapError == KErrServerBusy ||     // -16
+                 aTrapError == KErrLocked ||         // -22
+                 aTrapError == KErrCouldNotConnect ) // -34
+            {
+            aPluginError = KMdEErrHarvestingFailed;
+            }
+        else
+            {
+            aPluginError = KMdEErrHarvestingFailedUnknown;
+            }
+        }
+
+    /**
+     * Compare descriptors locale-independent
+     * 
+     * @param aDes1 first descriptor to compare
+     * @param aDes2 second descriptor to compare
+     * 
+     * @return Positive, if this descriptor is greater than the specified 
+     *         descriptor. Negative, if this descriptor is less than the 
+     *         specified descriptor. Zero, if both descriptors have the same 
+     *         length and the their contents are the same.
+     */
+    inline TInt Compare(const TDesC& aDes1, const TDesC& aDes2)
+    	{
+    	return aDes1.CompareF( aDes2 );
+    	}
+    
+    /**
+     * Find descriptor locale-independent
+     * 
+     * @param aWhereDes descriptor where to search
+     * @param aWhatDes descriptor what to search
+     * 
+     * @return The offset of the data sequence from the beginning of this 
+     *         descriptor's data. KErrNotFound, if the data sequence cannot be 
+     *         found. Zero, if the length of the search data sequence is zero.
+     */
+    inline TInt Find(const TDesC& aWhereDes, const TDesC& aWhatDes)
+    	{
+    	return aWhereDes.FindF( aWhatDes );
+    	}
+    
+    /**
+     * Check if file exist in file system. Requires AllFiles capability.
+     * 
+     * @param aFs handle to file server session
+     * @param aFilename filename
+     * 
+     * @return Does file exist
+     */
+    inline TBool FileExists(RFs& aFs, const TDesC& aFilename)
+    	{
+    	TUint fileAttributes;
+    	// Att method is used instead of Entry method 
+    	// because smaller stack memory usage (4 bytes vs. 548 bytes).
+    	// There is no performance difference between methods Att and Entry.
+    	return KErrNone == aFs.Att( aFilename, fileAttributes );
+    	}
+
+	/**
+     * Get name from filename. For example 'Test' is returned from 
+     * 'C:\Data\Test.jpg'. aFilename must contain drive letter, path and 
+     * filename (file extension is not required).
+     *
+     * @param aFilename filename
+     * @param aName returned name
+     *
+     * @return Does name exist (if true, lenght of aName is > 0)
+     */
+    inline TBool GetName(const TDesC& aFilename, TPtrC& aName)
+     	{
+     	// find name (everything after last back slash)
+     	TInt pos = aFilename.LocateReverseF( '\\' );
+     	if( pos >= 0 )
+     		{
+     		aName.Set( aFilename.Mid( pos + 1 ) );
+
+     		// remove extension
+     		TInt pos = aName.LocateReverseF( '.' );
+     		if( pos >= 0 )
+     			{
+     			aName.Set( aName.Left( pos ) );
+     			}
+
+     		if( aName.Length() > 0 )
+     			{
+     			return ETrue;
+     			}
+     		}
+     	
+     	return EFalse;
+     	}
+
+	/**
+     * Get name and extension from filename. For example 'Test.jpg' is 
+     * returned from 'C:\Data\Test.jpg'. aFilename must contain drive letter, 
+     * path and filename (file extension is not required).
+     *
+     * @param aFilename filename
+     * @param aNameExt returned name and extension
+     *
+     * @return Does name and extension exist (if true, lenght of aNameExt is > 0)
+     */
+    inline TBool GetNameExt(const TDesC& aFilename, TPtrC& aNameExt)
+     	{
+     	// find name (everything after last back slash)
+		TInt pos = aFilename.LocateReverseF( '\\' );
+		if( pos >= 0 )
+			{
+			aNameExt.Set( aFilename.Mid( pos + 1 ) );
+			
+			if( aNameExt.Length() > 0 )
+				{
+				return ETrue;
+				}
+			}
+
+		return EFalse;
+     	}
+
+	/**
+     * Get extension from filename. For example 'jpg' is returned from 
+     * 'C:\Data\Test.jpg'. aFilename must contain drive letter, path and 
+     * filename (file extension is not required).
+     *
+     * @param aFilename filename
+     * @param aExt returned extension
+     *
+     * @return Does extension exist (if true, lenght of aExt is > 0)
+     */
+    inline TBool GetExt(const TDesC& aFilename, TPtrC& aExt)
+     	{
+     	// find extension (everything after last dot)
+		TInt pos = aFilename.LocateReverseF( '.' );
+		if( pos >= 0 )
+			{
+			aExt.Set( aFilename.Mid( pos + 1 ) );
+
+			if( aExt.Length() > 0 )
+				{
+				return ETrue;				
+				}
+			}
+
+		return EFalse;
+		}
+
+	/**
+     * Get path from filename. For example 'C:\Data\' is returned from 
+     * 'C:\Data\Test.jpg'. aFilename must contain drive letter, path and 
+     * filename (file extension is not required).
+     *
+     * @param aFilename filename
+     * @param aPath returned path
+     *
+     * @return Does path exist (if true, lenght of aPath is > 0)
+     */
+    inline TBool GetPath(const TDesC& aFilename, TPtrC& aPath)
+     	{     	
+     	// find path (everything before last back slash)
+		TInt pos = aFilename.LocateReverseF( '\\' );
+		if( pos >= 0 )
+			{
+			aPath.Set( aFilename.Left( pos + 1 ) );
+			
+			if( aPath.Length() > 0 )
+				{
+				return ETrue;
+				}
+			}
+		
+		return EFalse;
+     	}    
+    }
+
+	/**
+	 * Serialize an array to a newly created descriptor buffer.
+	 * Leaves on error.
+	 * @param aArray  Array to serialize.
+	 * @return  A new output descriptor pointer. Ownership is transferred.
+	 */
+	template<typename T>
+	HBufC8* SerializeArrayL( const RArray<T>& aArray )
+	    {
+	    const TInt KItemCount = aArray.Count();
+	    if ( KItemCount <= 0 )
+	        {
+	        return NULL;
+	        }
+	    const TInt KItemSizeInBytes = sizeof( T );
+	    const TInt KBufferLength = KItemSizeInBytes * KItemCount;
+	
+	    HBufC8* buf = HBufC8::NewL( KBufferLength );
+	    void* ptr = NULL;
+	    for ( TInt i = 0; i < KBufferLength; i += KItemSizeInBytes )
+	        {
+	        const T& item = aArray[ i / KItemSizeInBytes ];
+	        ptr = (void*)( buf->Ptr() + i );
+	        Mem::Copy( ptr, &item, KItemSizeInBytes );
+	        }
+	
+	    buf->Des().SetLength( KBufferLength );
+	    return buf; // ownership is transferred
+	    }
+	
+	/**
+	 * Deserialize an array from a descriptor buffer.
+	 * Leaves on error.
+	 * @param aDesc  Descriptor containing the serialized array.
+	 * @param aArray  Target array.
+	 */
+	template<typename T>
+	void DeserializeArrayL( const TDesC8& aDesc, RArray<T>& aArray )
+	    {
+	    aArray.Reset();
+	    const TInt KItemSizeInBytes = sizeof( T );
+	    const TInt KBufferLength = aDesc.Size();
+	    const TInt KItemCount = KBufferLength / KItemSizeInBytes;
+	    aArray.Reserve( KItemCount );
+	
+	    for ( TInt i = 0; i < KItemCount; ++i )
+	        {
+	        T item;
+	        void* ptr = (void*)( aDesc.Ptr() + i * KItemSizeInBytes );
+	        Mem::Copy( &item, ptr, KItemSizeInBytes );
+	        aArray.Append( item );
+	        }
+	    }
+	
+	
+	
+	/**
+	 * Serialize a pointer array to a newly created descriptor buffer.
+	 * Leaves on error.
+	 * @param aArray  Pointer Array to serialize.
+	 * @return  A new output descriptor pointer. Ownership is transferred.
+	 */
+	template<typename T>
+	HBufC8* SerializePointerArrayL( const RPointerArray<T>& aArray )
+	    {
+	    const TInt KItemCount = aArray.Count();
+	    if ( KItemCount <= 0 )
+	        {
+	        return NULL;
+	        }
+	    const TInt KItemSizeInBytes = sizeof( T );
+	    const TInt KBufferLength = KItemSizeInBytes * KItemCount;
+	
+	    HBufC8* buf = HBufC8::NewL( KBufferLength );
+	    void* ptr = NULL;
+	    for ( TInt i = 0; i < KBufferLength; i += KItemSizeInBytes )
+	        {
+	        const T* item = aArray[ i / KItemSizeInBytes ];  // alkup. oli const T&
+	        ptr = (void*)( buf->Ptr() + i );
+	        Mem::Copy( ptr, &item, KItemSizeInBytes );
+	        }
+	
+	    buf->Des().SetLength( KBufferLength );
+	    return buf; // ownership is transferred
+	    }
+	
+	/**
+	 * Deserialize a pointer array from a descriptor buffer.
+	 * Leaves on error.
+	 * @param aDesc  Descriptor containing the serialized array.
+	 * @param aArray  Target Pointer Array.
+	 */
+	template<typename T>
+	void DeserializePointerArrayL( const TDesC8& aDesc, RPointerArray<T>& aArray )
+	    {
+	    aArray.Reset();
+	    const TInt KItemSizeInBytes = sizeof( T );
+	    const TInt KBufferLength = aDesc.Size();
+	    const TInt KItemCount = KBufferLength / KItemSizeInBytes;
+	    aArray.Reserve( KItemCount );
+	
+	    for ( TInt i = 0; i < KItemCount; ++i )
+	        {
+	        T* item;	// alkup. oli pelkkä T ilman pointteria
+	        void* ptr = (void*)( aDesc.Ptr() + i * KItemSizeInBytes );
+	        Mem::Copy( &item, ptr, KItemSizeInBytes );
+	        aArray.Append( item );
+	        }
+	    }
+
+#endif // MDSUTILS_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/layers.sysdef.50.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,42 @@
+<?xml version="1.0"?>
+<!DOCTYPE SystemDefinition SYSTEM "sysdef_1_4_0.dtd" [
+  <!ENTITY layer_real_source_path "s60/mw/mds" >
+]>
+
+<SystemDefinition name="mds" schema="1.4.0">
+  <systemModel>
+    <layer name="mw_layer">
+      <module name="mds">
+        <unit unitID="imm.mds" mrp="" bldFile="&layer_real_source_path;/group" name="mds" />
+      </module>
+    </layer>
+    
+    <layer name="api_test_layer">
+      <module name="mds_api_tests">
+        <unit unitID="imm.mds.content_listing_framework_collection_manager_api" mrp="" bldFile="s60/mw/mds/mds_plat/content_listing_framework_collection_manager_api/tsrc/group"  name="content_listing_framework_collection_manager_api"  />
+      	<unit unitID="imm.mds.context_engine_plugin_api" mrp="" bldFile="s60/mw/mds/mds_plat/context_engine_plugin_api/tsrc/group"  name="context_engine_plugin_api"  />      	
+      	<unit unitID="imm.mds.harvester_framework_api.composerplugin" mrp="" bldFile="s60/mw/mds/mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/group"  name="harvester_framework_api.composerplugin"  />
+      	<unit unitID="imm.mds.harvester_framework_api.harvesterclient" mrp="" bldFile="s60/mw/mds/mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/group"  name="harvester_framework_api.harvesterclient"  />
+      	<unit unitID="imm.mds.harvester_framework_api.harvesterdata" mrp="" bldFile="s60/mw/mds/mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/group"  name="harvester_framework_api.harvesterdata"  />
+      	<unit unitID="imm.mds.harvester_framework_api.harvesterplugin" mrp="" bldFile="s60/mw/mds/mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/group"  name="harvester_framework_api.harvesterplugin"  />
+      	<unit unitID="imm.mds.harvester_framework_api.monitorplugin" mrp="" bldFile="s60/mw/mds/mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/group"  name="harvester_framework_api.monitorplugin"  />
+        <unit unitID="imm.mds.location_manager_api" mrp="" bldFile="s60/mw/mds/mds_plat/location_manager_api/tsrc/group"  name="location_manager_api"  />
+        <unit unitID="imm.mds.metadata_engine_api" mrp="" bldFile="s60/mw/mds/mds_plat/metadata_engine_api/tsrc/group"  name="metadata_engine_api"  /> 
+        
+        <unit unitID="imm.mds.content_listing_framework" mrp="" bldFile="s60/mw/mds/mds_pub/content_listing_framework_api/tsrc/group"  name="content_listing_framework_api"  />    
+      </module>
+    </layer>
+    
+    <layer name="module_test_layer">
+      <module name="mds_module_tests">
+      <unit unitID="imm.mds.performance_test" mrp="" bldFile="s60/mw/mds/internal/tsrc/MDSPerfTest/group"  name="mds_performance_test"  />	
+      </module>
+    </layer>    
+    
+    <layer name="unit_test_layer">
+      <module name="mds_unit_tests">
+      </module>
+    </layer>
+    
+  </systemModel>
+</SystemDefinition>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/layers.sysdef.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,36 @@
+<?xml version="1.0"?>
+<!DOCTYPE SystemDefinition SYSTEM "sysdef_1_4_0.dtd" [
+  <!ENTITY layer_real_source_path "sf/mw/mds" >
+]>
+
+<SystemDefinition name="mds" schema="1.4.0">
+  <systemModel>
+    <layer name="mw_layer">
+      <module name="mds">
+        <unit unitID="imm.mds" mrp="" bldFile="&layer_real_source_path;/group" name="mds" />
+      </module>
+    </layer>
+    
+    <layer name="api_test_layer">
+      <module name="mds_api_tests">
+        <unit unitID="imm.mds.content_listing_framework_collection_manager_api" mrp="" bldFile="sf/mw/mds/mds_plat/content_listing_framework_collection_manager_api/tsrc/group"  name="content_listing_framework_collection_manager_api"  />
+      	<unit unitID="imm.mds.context_engine_plugin_api" mrp="" bldFile="sf/mw/mds/mds_plat/context_engine_plugin_api/tsrc/group"  name="context_engine_plugin_api"  />
+      	<unit unitID="imm.mds.harvester_framework_api.composerplugin" mrp="" bldFile="sf/mw/mds/mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/group"  name="harvester_framework_api.composerplugin"  />
+      	<unit unitID="imm.mds.harvester_framework_api.harvesterclient" mrp="" bldFile="sf/mw/mds/mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/group"  name="harvester_framework_api.harvesterclient"  />
+      	<unit unitID="imm.mds.harvester_framework_api.harvesterdata" mrp="" bldFile="sf/mw/mds/mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/group"  name="harvester_framework_api.harvesterdata"  />
+      	<unit unitID="imm.mds.harvester_framework_api.harvesterplugin" mrp="" bldFile="sf/mw/mds/mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/group"  name="harvester_framework_api.harvesterplugin"  />
+      	<unit unitID="imm.mds.harvester_framework_api.monitorplugin" mrp="" bldFile="sf/mw/mds/mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/group"  name="harvester_framework_api.monitorplugin"  />
+        <unit unitID="imm.mds.location_manager_api" mrp="" bldFile="sf/mw/mds/mds_plat/location_manager_api/tsrc/group"  name="location_manager_api"  />
+        <unit unitID="imm.mds.metadata_engine_api" mrp="" bldFile="sf/mw/mds/mds_plat/metadata_engine_api/tsrc/group"  name="metadata_engine_api"  />
+        
+        <unit unitID="imm.mds.content_listing_framework" mrp="" bldFile="sf/mw/mds/mds_pub/content_listing_framework_api/tsrc/group"  name="content_listing_framework_api"  />    
+      </module>
+    </layer>
+    
+    <layer name="unit_test_layer">
+      <module name="mds_unit_tests">
+      </module>
+    </layer>
+    
+  </systemModel>
+</SystemDefinition>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/backup/backup_registration.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,10 @@
+<?xml version="1.0" standalone="yes"?>
+<!-- Copyright (c) 2004, Symbian Software Ltd. All Rights Reserved -->
+
+<backup_registration version="1.0">    
+
+    <active_backup process_name="locationutilityserver" requires_delay_to_prepare_data="no" supports_selective="no" supports_incremental="no">
+    </active_backup>
+    <restore requires_reboot = "no"/>
+
+</backup_registration>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/bwincw/bwinscwlocationtrailu.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,18 @@
+EXPORTS
+	??1CLocationRecord@@UAE@XZ @ 1 NONAME ; CLocationRecord::~CLocationRecord(void)
+	??1CNetworkInfo@@UAE@XZ @ 2 NONAME ; CNetworkInfo::~CNetworkInfo(void)
+	??1CPositionInfo@@UAE@XZ @ 3 NONAME ; CPositionInfo::~CPositionInfo(void)
+	?CancelLocationRequest@CLocationRecord@@QAEXXZ @ 4 NONAME ; void CLocationRecord::CancelLocationRequest(void)
+	?GetLocationByTimeL@CLocationRecord@@QAEXVTTime@@AAUTLocationData@RLocationManager@@AAW4TTrailState@RLocationTrail@@@Z @ 5 NONAME ; void CLocationRecord::GetLocationByTimeL(class TTime, struct RLocationManager::TLocationData &, enum RLocationTrail::TTrailState &)
+	?GetNetworkInfo@CLocationRecord@@QAEXAAVTNetworkInfoV1@CTelephony@@@Z @ 6 NONAME ; void CLocationRecord::GetNetworkInfo(class CTelephony::TNetworkInfoV1 &)
+	?LocationTrailState@CLocationRecord@@QAEXAAW4TTrailState@RLocationTrail@@@Z @ 7 NONAME ; void CLocationRecord::LocationTrailState(enum RLocationTrail::TTrailState &)
+	?NewL@CLocationRecord@@SAPAV1@XZ @ 8 NONAME ; class CLocationRecord * CLocationRecord::NewL(void)
+	?NewL@CNetworkInfo@@SAPAV1@PAVMNetworkInfoObserver@@@Z @ 9 NONAME ; class CNetworkInfo * CNetworkInfo::NewL(class MNetworkInfoObserver *)
+	?NewL@CPositionInfo@@SAPAV1@PAVMPositionInfoObserver@@@Z @ 10 NONAME ; class CPositionInfo * CPositionInfo::NewL(class MPositionInfoObserver *)
+	?RequestLocationL@CLocationRecord@@QAEXXZ @ 11 NONAME ; void CLocationRecord::RequestLocationL(void)
+	?SetObserver@CLocationRecord@@QAEXPAVMLocationTrailObserver@@@Z @ 12 NONAME ; void CLocationRecord::SetObserver(class MLocationTrailObserver *)
+	?StartL@CLocationRecord@@QAEXW4TTrailCaptureSetting@RLocationTrail@@@Z @ 13 NONAME ; void CLocationRecord::StartL(enum RLocationTrail::TTrailCaptureSetting)
+	?Stop@CLocationRecord@@QAEXXZ @ 14 NONAME ; void CLocationRecord::Stop(void)
+	??1CTrackLog@@UAE@XZ @ 15 NONAME ; CTrackLog::~CTrackLog(void)
+	?NewL@CTrackLog@@SAPAV1@XZ @ 16 NONAME ; class CTrackLog * CTrackLog::NewL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/bwincw/bwinslocationmanagerclientu.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,28 @@
+EXPORTS
+	??0RLocationManager@@QAE@XZ @ 1 NONAME ; RLocationManager::RLocationManager(void)
+	?AddObserver@RTrackLog@@QAEHPAVMTrackLogObserver@@@Z @ 2 NONAME ; int RTrackLog::AddObserver(class MTrackLogObserver *)
+	?CancelLocationRequest@RLocationTrail@@QAEXXZ @ 3 NONAME ; void RLocationTrail::CancelLocationRequest(void)
+	?CancelNotificationRequest@RLocationTrail@@QAEXXZ @ 4 NONAME ; void RLocationTrail::CancelNotificationRequest(void)
+	?Close@RLocationManager@@QAEXXZ @ 5 NONAME ; void RLocationManager::Close(void)
+	?Close@RTrackLog@@QAEXXZ @ 6 NONAME ; void RTrackLog::Close(void)
+	?Connect@RLocationManager@@QAEHXZ @ 7 NONAME ; int RLocationManager::Connect(void)
+	?CopyLocationData@RLocationObject@@QAEHAAIAAV?$RArray@I@@@Z @ 8 NONAME ; int RLocationObject::CopyLocationData(unsigned int &, class RArray<unsigned int> &)
+	?CopyLocationData@RLocationObject@@QAEHAAVTDesC16@@AAV?$RPointerArray@VTDesC16@@@@@Z @ 9 NONAME ; int RLocationObject::CopyLocationData(class TDesC16 &, class RPointerArray<class TDesC16> &)
+	?CreateLocationObject@RLocationObject@@QAEHAAUTLocationData@RLocationManager@@AAV?$RArray@I@@@Z @ 10 NONAME ; int RLocationObject::CreateLocationObject(struct RLocationManager::TLocationData &, class RArray<unsigned int> &)
+	?CurrentLocation@RLocationTrail@@QAEXAAVTRequestStatus@@AAVTDes8@@1@Z @ 11 NONAME ; void RLocationTrail::CurrentLocation(class TRequestStatus &, class TDes8 &, class TDes8 &)
+	?DeleteTrackLog@RTrackLog@@QAEHAAVTDesC16@@@Z @ 12 NONAME ; int RTrackLog::DeleteTrackLog(class TDesC16 &)
+	?EditLocationObject@RLocationObject@@QAEHAAIAAUTLocationData@RLocationManager@@@Z @ 13 NONAME ; int RLocationObject::EditLocationObject(unsigned int &, struct RLocationManager::TLocationData &)
+	?GetLocationTrailState@RLocationTrail@@QAEHAAW4TTrailState@1@@Z @ 14 NONAME ; int RLocationTrail::GetLocationTrailState(enum RLocationTrail::TTrailState &)
+	?GetStatus@RTrackLog@@QAEHAAHAAVTPositionSatelliteInfo@@@Z @ 15 NONAME ; int RTrackLog::GetStatus(int &, class TPositionSatelliteInfo &)
+	?IsRecording@RTrackLog@@QAEHXZ @ 16 NONAME ; int RTrackLog::IsRecording(void)
+	?MapLocationToLandmarksL@RLandmarkMapping@@QAEXABVTLocality@@AAV?$RPointerArray@VCPosLandmark@@@@@Z @ 17 NONAME ; void RLandmarkMapping::MapLocationToLandmarksL(class TLocality const &, class RPointerArray<class CPosLandmark> &)
+	?NotifyLocationTrailStateChange@RLocationTrail@@QAEXAAVTRequestStatus@@@Z @ 18 NONAME ; void RLocationTrail::NotifyLocationTrailStateChange(class TRequestStatus &)
+	?RemoveLocationObject@RLocationObject@@QAEHAAI@Z @ 19 NONAME ; int RLocationObject::RemoveLocationObject(unsigned int &)
+	?RemoveObserver@RTrackLog@@QAEHPAVMTrackLogObserver@@@Z @ 20 NONAME ; int RTrackLog::RemoveObserver(class MTrackLogObserver *)
+	?RetrieveLocation@RLocationTrail@@QAEHABVTTime@@AAUTLocationData@RLocationManager@@AAW4TTrailState@1@@Z @ 21 NONAME ; int RLocationTrail::RetrieveLocation(class TTime const &, struct RLocationManager::TLocationData &, enum RLocationTrail::TTrailState &)
+	?StartLocationTrail@RLocationTrail@@QAEHW4TTrailCaptureSetting@1@@Z @ 22 NONAME ; int RLocationTrail::StartLocationTrail(enum RLocationTrail::TTrailCaptureSetting)
+	?StartTrackLog@RTrackLog@@QAEHXZ @ 23 NONAME ; int RTrackLog::StartTrackLog(void)
+	?StopLocationTrail@RLocationTrail@@QAEHXZ @ 24 NONAME ; int RLocationTrail::StopLocationTrail(void)
+	?StopTrackLog@RTrackLog@@QAEXXZ @ 25 NONAME ; void RTrackLog::StopTrackLog(void)
+	?TrackLogName@RTrackLog@@QAEHAAVTDes16@@@Z @ 26 NONAME ; int RTrackLog::TrackLogName(class TDes16 &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/client/bwincw/locationmanagerclientwinscw.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,32 @@
+EXPORTS
+	??0RLocationManager@@QAE@XZ @ 1 NONAME ; RLocationManager::RLocationManager(void)
+	??0RLocationTrail@@QAE@XZ @ 2 NONAME ; RLocationTrail::RLocationTrail(void)
+	??0RTrackLog@@QAE@XZ @ 3 NONAME ; RTrackLog::RTrackLog(void)
+	??1RLocationTrail@@QAE@XZ @ 4 NONAME ; RLocationTrail::~RLocationTrail(void)
+	?AddObserver@RTrackLog@@QAEHPAVMTrackLogObserver@@@Z @ 5 NONAME ; int RTrackLog::AddObserver(class MTrackLogObserver *)
+	?CancelLocationRequest@RLocationTrail@@QAEXXZ @ 6 NONAME ; void RLocationTrail::CancelLocationRequest(void)
+	?CancelNotificationRequest@RLocationTrail@@QAEXXZ @ 7 NONAME ; void RLocationTrail::CancelNotificationRequest(void)
+	?Close@RLocationManager@@QAEXXZ @ 8 NONAME ; void RLocationManager::Close(void)
+	?Close@RTrackLog@@QAEXXZ @ 9 NONAME ; void RTrackLog::Close(void)
+	?Connect@RLocationManager@@QAEHXZ @ 10 NONAME ; int RLocationManager::Connect(void)
+	?CopyLocationData@RLocationObjectManipulator@@QAEXAAVTDesC16@@AAV?$RPointerArray@VTDesC16@@@@AAVTRequestStatus@@@Z @ 11 NONAME ; void RLocationObjectManipulator::CopyLocationData(class TDesC16 &, class RPointerArray<class TDesC16> &, class TRequestStatus &)
+	?CopyLocationData@RLocationObjectManipulator@@QAEXKAAV?$RArray@K@@AAVTRequestStatus@@@Z @ 12 NONAME ; void RLocationObjectManipulator::CopyLocationData(unsigned long, class RArray<unsigned long> &, class TRequestStatus &)
+	?CreateLocationObject@RLocationObjectManipulator@@QAEHAAUTLocationData@@K@Z @ 13 NONAME ; int RLocationObjectManipulator::CreateLocationObject(struct TLocationData &, unsigned long)
+	?CurrentLocation@RLocationTrail@@QAEXAAVTRequestStatus@@AAUTLocationData@@@Z @ 14 NONAME ; void RLocationTrail::CurrentLocation(class TRequestStatus &, struct TLocationData &)
+	?DeleteTrackLog@RTrackLog@@QAEHAAVTDesC16@@@Z @ 15 NONAME ; int RTrackLog::DeleteTrackLog(class TDesC16 &)
+	?EditLocationObject@RLocationObjectManipulator@@QAEHKAAUTLocationData@@@Z @ 16 NONAME ABSENT ; int RLocationObjectManipulator::EditLocationObject(unsigned long, struct TLocationData &)
+	?GetLocationTrailState@RLocationTrail@@QAEHAAW4TTrailState@1@@Z @ 17 NONAME ; int RLocationTrail::GetLocationTrailState(enum RLocationTrail::TTrailState &)
+	?GetStatus@RTrackLog@@QAEHAAHAAVTPositionSatelliteInfo@@@Z @ 18 NONAME ; int RTrackLog::GetStatus(int &, class TPositionSatelliteInfo &)
+	?GetTrailCaptureSetting@RLocationTrail@@QAEHAAW4TTrailCaptureSetting@1@@Z @ 19 NONAME ; int RLocationTrail::GetTrailCaptureSetting(enum RLocationTrail::TTrailCaptureSetting &)
+	?IsRecording@RTrackLog@@QAEHXZ @ 20 NONAME ; int RTrackLog::IsRecording(void)
+	?NotifyLocationTrailStateChange@RLocationTrail@@QAEXAAVTRequestStatus@@@Z @ 21 NONAME ; void RLocationTrail::NotifyLocationTrailStateChange(class TRequestStatus &)
+	?RemoveLocationObject@RLocationObjectManipulator@@QAEHK@Z @ 22 NONAME ; int RLocationObjectManipulator::RemoveLocationObject(unsigned long)
+	?RemoveObserver@RTrackLog@@QAEHPAVMTrackLogObserver@@@Z @ 23 NONAME ; int RTrackLog::RemoveObserver(class MTrackLogObserver *)
+	?RetrieveLocation@RLocationTrail@@QAEHABVTTime@@AAUTLocationData@@AAW4TTrailState@1@@Z @ 24 NONAME ; int RLocationTrail::RetrieveLocation(class TTime const &, struct TLocationData &, enum RLocationTrail::TTrailState &)
+	?StartLocationTrail@RLocationTrail@@QAEHW4TTrailCaptureSetting@1@@Z @ 25 NONAME ; int RLocationTrail::StartLocationTrail(enum RLocationTrail::TTrailCaptureSetting)
+	?StartTrackLog@RTrackLog@@QAEHXZ @ 26 NONAME ; int RTrackLog::StartTrackLog(void)
+	?StopLocationTrail@RLocationTrail@@QAEHXZ @ 27 NONAME ; int RLocationTrail::StopLocationTrail(void)
+	?StopTrackLog@RTrackLog@@QAEXXZ @ 28 NONAME ; void RTrackLog::StopTrackLog(void)
+	?TrackLogName@RTrackLog@@QAEHAAVTDes16@@@Z @ 29 NONAME ; int RTrackLog::TrackLogName(class TDes16 &)
+	?LocationSnapshot@RLocationObjectManipulator@@QAEHK@Z @ 30 NONAME ; int RLocationObjectManipulator::LocationSnapshot(unsigned long)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/client/eabi/locationmanagerclientarm.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,38 @@
+EXPORTS
+	_ZN14RLocationTrail15CurrentLocationER14TRequestStatusR13TLocationData @ 1 NONAME
+	_ZN14RLocationTrail16RetrieveLocationERK5TTimeR13TLocationDataRNS_11TTrailStateE @ 2 NONAME
+	_ZN14RLocationTrail17StopLocationTrailEv @ 3 NONAME
+	_ZN14RLocationTrail18StartLocationTrailENS_20TTrailCaptureSettingE @ 4 NONAME
+	_ZN14RLocationTrail21CancelLocationRequestEv @ 5 NONAME
+	_ZN14RLocationTrail21GetLocationTrailStateERNS_11TTrailStateE @ 6 NONAME
+	_ZN14RLocationTrail22GetTrailCaptureSettingERNS_20TTrailCaptureSettingE @ 7 NONAME
+	_ZN14RLocationTrail25CancelNotificationRequestEv @ 8 NONAME
+	_ZN14RLocationTrail30NotifyLocationTrailStateChangeER14TRequestStatus @ 9 NONAME
+	_ZN14RLocationTrailC1Ev @ 10 NONAME
+	_ZN14RLocationTrailC2Ev @ 11 NONAME
+	_ZN14RLocationTrailD1Ev @ 12 NONAME
+	_ZN14RLocationTrailD2Ev @ 13 NONAME
+	_ZN16RLocationManager5CloseEv @ 14 NONAME
+	_ZN16RLocationManager7ConnectEv @ 15 NONAME
+	_ZN16RLocationManagerC1Ev @ 16 NONAME
+	_ZN16RLocationManagerC2Ev @ 17 NONAME
+	_ZN26RLocationObjectManipulator16CopyLocationDataER7TDesC16R13RPointerArrayIS0_ER14TRequestStatus @ 18 NONAME
+	_ZN26RLocationObjectManipulator16CopyLocationDataEmR6RArrayImER14TRequestStatus @ 19 NONAME
+	_ZN26RLocationObjectManipulator18EditLocationObjectEmR13TLocationData @ 20 NONAME ABSENT
+	_ZN26RLocationObjectManipulator20CreateLocationObjectER13TLocationDatam @ 21 NONAME
+	_ZN26RLocationObjectManipulator20RemoveLocationObjectEm @ 22 NONAME
+	_ZN9RTrackLog11AddObserverEP17MTrackLogObserver @ 23 NONAME
+	_ZN9RTrackLog11IsRecordingEv @ 24 NONAME
+	_ZN9RTrackLog12StopTrackLogEv @ 25 NONAME
+	_ZN9RTrackLog12TrackLogNameER6TDes16 @ 26 NONAME
+	_ZN9RTrackLog13StartTrackLogEv @ 27 NONAME
+	_ZN9RTrackLog14DeleteTrackLogER7TDesC16 @ 28 NONAME
+	_ZN9RTrackLog14RemoveObserverEP17MTrackLogObserver @ 29 NONAME
+	_ZN9RTrackLog5CloseEv @ 30 NONAME
+	_ZN9RTrackLog9GetStatusERiR22TPositionSatelliteInfo @ 31 NONAME
+	_ZN9RTrackLogC1Ev @ 32 NONAME
+	_ZN9RTrackLogC2Ev @ 33 NONAME
+	_ZTI19CTrackLogObserverAO @ 34 NONAME ABSENT; #<TI>#
+	_ZTV19CTrackLogObserverAO @ 35 NONAME ABSENT; #<VT>#
+	_ZN26RLocationObjectManipulator16LocationSnapshotEm @ 36 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/client/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+locationmanagerclient.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/client/group/locationmanagerclient.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+#if defined(WINSCW)
+deffile ../bwincw/locationmanagerclientwinscw.def
+#elif defined(ARMCC)
+deffile ../eabi/locationmanagerclientarm.def
+#endif
+nostrictdef
+
+VERSION         10.0
+TARGET          locationmanager.dll
+TARGETTYPE      dll
+UID             0x1000008d 0x200071BF
+
+CAPABILITY 	    CAP_CLIENT_DLL
+VENDORID 	    VID_DEFAULT
+
+USERINCLUDE	    ../inc
+USERINCLUDE	    ../../inc
+USERINCLUDE	    ../../../inc
+
+SOURCEPATH      ../src
+SOURCE          rlocationmanager.cpp
+SOURCE          rlocationtrail.cpp
+SOURCE	    rlocationobjectmanipulator.cpp 
+SOURCE      CTrackLogObserverAO.cpp 
+SOURCE      rtracklog.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY	    euser.lib  
+LIBRARY	    efsrv.lib
+LIBRARY	    lbs.lib
+LIBRARY	    mdccommon.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/client/inc/CTrackLogObserverAO.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef CTRACKLOGOBSERVERAO_H_
+#define CTRACKLOGOBSERVERAO_H_
+
+#include <e32base.h>
+#include "rtracklog.h"
+
+NONSHARABLE_CLASS( CTrackLogObserverAO ) : public CActive
+{
+public:
+	/**
+	 * C++ constructor.
+	 */
+	CTrackLogObserverAO( RTrackLog* aClient );
+	virtual ~CTrackLogObserverAO();
+	
+private: // From CActive
+	void DoCancel();
+	void RunL();
+	
+public:
+	TInt StartObserving();
+	
+private:	
+	/**
+    * 2nd phase constructor.
+    */
+    void ConstructL( RTrackLog* aClient );
+    
+private: // Data
+	RTrackLog* iClient;
+};
+
+#endif /*CTRACKLOGOBSERVERAO_H_*/
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/client/src/CTrackLogObserverAO.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include "CTrackLogObserverAO.h"
+#include "locationmanagerdebug.h"
+
+CTrackLogObserverAO::CTrackLogObserverAO( RTrackLog* aClient ) : 
+	CActive( CActive::EPriorityStandard )
+	{
+	CActiveScheduler::Add( this );
+	iClient = aClient;
+	}
+
+CTrackLogObserverAO::~CTrackLogObserverAO()
+	{
+	Cancel();
+	}
+
+void CTrackLogObserverAO::DoCancel()
+	{
+	
+	}
+
+void CTrackLogObserverAO::RunL()
+	{
+	LOG( "CTrackLogObserverAO::RunL()" );
+	iClient->TrackLogEvent( iStatus.Int() );
+	
+	StartObserving();
+	}
+	
+TInt CTrackLogObserverAO::StartObserving()
+	{
+	iClient->SendNotifyRequest( iStatus );
+	SetActive();
+	
+	return KErrNone;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/client/src/rlocationmanager.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,137 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An interface to Location Manager server
+*
+*/
+
+#include <f32file.h>
+#include <s32mem.h>
+#include <data_caging_path_literals.hrh>
+
+#include <rlocationmanager.h>
+#include <locationeventdef.h>
+#include "locationmanagerdefs.h"
+#include "locationmanagerdebug.h"
+
+// --------------------------------------------------------------------------
+// LaunchServer
+// Launches the server.
+// --------------------------------------------------------------------------
+//
+TInt LaunchServer()
+    {
+    LOG( "RLocationManager::LaunchServer begin" );
+    TParse parser;
+    parser.Set( KLocServerFileName, &KDC_PROGRAMS_DIR, NULL );
+
+    // DLL launch
+    RProcess server;
+    const TInt ret = server.Create( parser.FullName(), KNullDesC );
+
+    if ( ret != KErrNone )  // Loading failed.
+        {
+        return ret;
+        }
+    
+    TRequestStatus status( KErrNone );
+    server.Rendezvous( status );
+
+    if ( status != KRequestPending )
+        {
+        LOG( "RLocationManager::LaunchServer Failed" );
+        server.Kill( 0 );     // Abort startup.
+        server.Close();
+        return KErrGeneral;
+        }
+    else
+        {
+        server.Resume();    // Logon OK - start the server.
+        }
+        
+    User::WaitForRequest( status );
+    server.Close();
+    LOG( "RLocationManager::LaunchServer end" );
+    return status.Int();    
+    }
+
+// --------------------------------------------------------------------------
+// RLocationManager::RLocationManager
+// C++ Constructor
+// --------------------------------------------------------------------------
+//
+EXPORT_C RLocationManager::RLocationManager()
+    {
+    iNameBuf = NULL;
+    }
+
+// --------------------------------------------------------------------------
+// RLocationManager::Connect
+// Creates connection to server
+// --------------------------------------------------------------------------
+//
+EXPORT_C TInt RLocationManager::Connect()
+    {
+    LOG( "RLocationManager::Connect(), begin" );
+    TInt ret = CreateSession( KLocServerName, Version(), KSessionSlotCount);
+    if ( ret != KErrNone )
+        {
+        ret = LaunchServer();
+        if ( ret == KErrNone )
+            {
+            ret = CreateSession( KLocServerName, Version() );    
+            }       
+        }
+    LOG( "RLocationManager::Connect(), end" );
+    return ret;
+    }
+    
+// --------------------------------------------------------------------------
+// RLocationManager::Close
+// --------------------------------------------------------------------------
+//      
+EXPORT_C void RLocationManager::Close()
+    {
+    LOG( "RLocationManager::Close(), begin" );
+    // close session    
+    delete iNameBuf;
+    iNameBuf = NULL;
+    RSessionBase::Close();
+    LOG( "RLocationManager::Close(), end" );
+    }
+
+// --------------------------------------------------------------------------
+// RLocationManager::Version
+// Returns the version of Location Manager.
+// --------------------------------------------------------------------------
+//      
+TVersion RLocationManager::Version() const
+    {
+    return TVersion( KLocationManagerServerMajor, 
+                     KLocationManagerServerMinor, 
+                     KLocationManagerServerBuild );
+    }
+
+// --------------------------------------------------------------------------
+// RLocationManager::CompleteRequest
+// Completes an asynchronous request with an error code.
+// --------------------------------------------------------------------------
+//      
+void RLocationManager::CompleteRequest( TRequestStatus& aStatus, TInt aError )
+	{
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete( status, aError );
+	}
+
+
+//End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/client/src/rlocationobjectmanipulator.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,182 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An interface to Location Object
+*
+*/
+
+#include "locationdatatype.h"
+#include "rlocationobjectmanipulator.h"
+#include "locationmanagerdefs.h"
+#include "locationmanagerdebug.h"
+#include "mdsutils.h"
+#include <locationeventdef.h>
+#include "mdcserializationbuffer.h"
+
+// --------------------------------------------------------------------------
+// RLocationObjectManipulator::CreateLocationObject
+// --------------------------------------------------------------------------
+//
+EXPORT_C TInt RLocationObjectManipulator::CreateLocationObject( TLocationData& aLocationData,
+									TItemId aObjectId )
+	{
+	LOG( "RLocationObject::CreateLocationObject begin" );
+    TInt ret( KErrDisconnected );
+    TPckg<TLocationData> locationData( aLocationData );
+    TPckg<TItemId> objectId( aObjectId );    
+    if ( iHandle )
+        {
+        ret = SendReceive( ELocManCreateLocationObject, TIpcArgs( &locationData,  &objectId) );
+        }
+    LOG( "RLocationObject::CreateLocationObject end" );
+    return ret;
+	}
+
+// --------------------------------------------------------------------------
+// RLocationObjectManipulator::LocationSnapshot
+// --------------------------------------------------------------------------
+//
+EXPORT_C TInt RLocationObjectManipulator::LocationSnapshot(	TItemId aObjectId )
+	{
+	LOG( "RLocationObject::LocationSnapshot begin" );
+    TInt ret( KErrDisconnected );
+    TPckg<TItemId> objectId( aObjectId );    
+    if ( iHandle )
+        {
+        ret = SendReceive( ELocManLocationSnapshot, TIpcArgs( &objectId ) );
+        }
+    LOG( "RLocationObject::LocationSnapshot end" );
+    return ret;
+	}
+
+
+// --------------------------------------------------------------------------
+// RLocationObjectManipulator::RemoveLocationObject
+// --------------------------------------------------------------------------
+//
+EXPORT_C TInt RLocationObjectManipulator::RemoveLocationObject( TItemId aObjId )
+	{
+	LOG( "RLocationObject::RemoveLocationObject begin" );
+	TInt ret( KErrDisconnected );
+	TPckg<TItemId> objId( aObjId );
+	if ( iHandle )
+        {
+        ret = SendReceive( ELocManRemoveLocationObject, TIpcArgs( &objId ));
+        }
+	LOG( "RLocationObject::RemoveLocationObject end" );
+	return ret;
+	}
+// --------------------------------------------------------------------------
+// RLocationObjectManipulator::CopyLocationData
+// --------------------------------------------------------------------------
+//
+EXPORT_C void RLocationObjectManipulator::CopyLocationData (TItemId aSourceId, 
+												RArray<TItemId>& aTargetIds,
+												TRequestStatus& aStatus)
+	{
+	LOG( "RLocationObject::CopyLocationData begin" );
+	
+	TPckg<TItemId> sourceId( aSourceId );
+	// serializing RArray, must deserialize in server side
+
+	HBufC8* paramBuf = NULL;   
+    TRAPD( err, paramBuf = SerializeArrayL( aTargetIds ) );
+    // was serializing failed
+    if ( err != KErrNone )
+    	{
+        LOG1 ( "RLocationObject::CopyLocationData - cannot create serialized objectIds for sending, error: %d", err );
+        delete paramBuf;
+        paramBuf = NULL;
+        CompleteRequest( aStatus, err );
+
+        return;
+    	}
+    
+    if ( iHandle )
+        {
+       	TIpcArgs args( &sourceId, paramBuf );
+        const TInt result = SendReceive( ELocManCopyLocationDataById, args );
+        CompleteRequest( aStatus, result );
+        }
+    else
+        {
+        CompleteRequest( aStatus, KErrDisconnected );
+        }
+    
+    delete paramBuf;
+	LOG( "RLocationObject::CopyLocationData end" );
+	}
+// --------------------------------------------------------------------------
+// RLocationObjectManipulator::CopyLocationData
+// --------------------------------------------------------------------------
+//
+EXPORT_C void RLocationObjectManipulator::CopyLocationData (TDesC& aSourceURI, 
+								RPointerArray<TDesC>& aTargetURIs,
+								TRequestStatus& aStatus)
+	{
+	LOG( "RLocationObject::CopyLocationData begin" );
+
+    TInt32 uriCount = aTargetURIs.Count();
+	
+	// Required size for serialized URI buffer, count
+    TInt urisRequiredSize = CMdCSerializationBuffer::KRequiredSizeForTInt32;
+
+    // and URIs
+    for( TInt i = 0; i < uriCount; i++ )
+    	{
+    	urisRequiredSize += CMdCSerializationBuffer::RequiredSize( *aTargetURIs[i] );
+    	}
+
+   	// serializing URIs
+    CMdCSerializationBuffer* uriBuffer( NULL );
+    TRAPD( error, uriBuffer = CMdCSerializationBuffer::NewL( urisRequiredSize ); 
+                          uriBuffer->InsertL( uriCount ) );
+    
+    if( error != KErrNone )
+        {
+        LOG( "RLocationObject::CopyLocationData CMdCSerializationBuffer creation failed" );
+        delete uriBuffer;
+        CompleteRequest( aStatus, error );
+        return;
+        }
+
+    for( TInt i = 0; i < uriCount; i++ )
+		{
+		TRAPD( err, uriBuffer->InsertL( *aTargetURIs[i] ) );
+		
+	    // was serializing failed
+	    if ( err != KErrNone )
+	    	{
+	        LOG1 ( "RLocationObject::CopyLocationData - cannot create serialized objectIds for sending, error: %d", err );
+	        delete uriBuffer;
+	        uriBuffer = NULL;
+	        CompleteRequest( aStatus, err );
+	        return;
+	    	}
+		}
+    
+    if ( iHandle )
+        {
+        TIpcArgs args( &aSourceURI, uriBuffer->BufferConstPtr() );
+        const TInt result = SendReceive( ELocManCopyLocationDataByUri, args );
+        CompleteRequest( aStatus, result );
+        }
+    else
+        {
+        CompleteRequest( aStatus, KErrDisconnected );
+        }
+    
+    delete uriBuffer;
+    LOG( "RLocationObject::CopyLocationData end" );
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/client/src/rlocationtrail.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,196 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An interface to Location Manager server
+*
+*/
+
+#include <f32file.h>
+#include <s32mem.h>
+#include <data_caging_path_literals.hrh>
+
+#include <locationeventdef.h>
+#include "rlocationtrail.h"
+#include "locationmanagerdefs.h"
+#include "locationmanagerdebug.h"
+
+EXPORT_C RLocationTrail::RLocationTrail() : iCurrentLocData( NULL )
+	{
+	}
+
+EXPORT_C RLocationTrail::~RLocationTrail()
+	{
+	delete iCurrentLocData;
+	}
+
+// --------------------------------------------------------------------------
+// RLocationTrail::StartLocationTrail
+// --------------------------------------------------------------------------
+//
+EXPORT_C TInt RLocationTrail::StartLocationTrail(TTrailCaptureSetting aState)
+    {
+    LOG( "RLocationTrail::StartLocationTrail()" );
+    TInt ret( KErrDisconnected );
+    TPckg<TTrailCaptureSetting> state( aState );
+    
+    if ( aState == RLocationTrail::EOff )
+    	{
+    	return KErrArgument;
+    	}
+    
+    if ( iHandle )
+        {
+        ret = SendReceive( ELocManStartTrail, TIpcArgs( &state ) );
+        }
+    return ret;
+    }
+// --------------------------------------------------------------------------
+// RLocationTrail::StopLocationTrail
+// --------------------------------------------------------------------------
+//
+EXPORT_C TInt RLocationTrail::StopLocationTrail()
+    {
+    LOG( "RLocationTrail::StopLocationTrail()" );
+    TInt ret( KErrNone );
+    if ( iHandle )
+        {
+        Send( ELocManStopTrail );    
+        }
+    else
+        {
+        ret = KErrDisconnected;
+        }
+    
+    return ret;
+    }
+// --------------------------------------------------------------------------
+// RLocationTrail::GetLocationTrailState
+// --------------------------------------------------------------------------
+//
+EXPORT_C TInt RLocationTrail::GetLocationTrailState( TTrailState& aState )
+    {
+    LOG( "RLocationTrail::GetLocationTrailState()" );
+    TInt ret( KErrDisconnected );
+    TPckg<TTrailState> state( aState );
+    
+    if ( iHandle )
+        {
+        ret = SendReceive( ELocManTrailState, TIpcArgs( &state ) );
+        }
+    return ret;
+    }
+// --------------------------------------------------------------------------
+// RLocationTrail::NotifyLocationTrailStateChange
+// --------------------------------------------------------------------------
+//
+EXPORT_C void RLocationTrail::NotifyLocationTrailStateChange( TRequestStatus& aStatus )
+    {
+    LOG( "RLocationTrail::NotifyLocationTrailStateChange()" );
+    if ( iHandle )
+        {
+        SendReceive( ELocManNotifyTrailStateChange, aStatus );
+        }        
+    else
+        {
+        CompleteRequest(aStatus, KErrDisconnected);
+        }
+    }
+
+// --------------------------------------------------------------------------
+// RLocationTrail::CancelNotificationRequest
+// --------------------------------------------------------------------------
+//
+EXPORT_C void RLocationTrail::CancelNotificationRequest()
+    {
+    LOG( "RLocationTrail::CancelNotificationRequest()" );
+    if ( iHandle )
+    	{
+        SendReceive( ELocManCancelNotification );
+    	}
+    }    
+
+// --------------------------------------------------------------------------
+// RLocationTrail::RetrieveLocation
+// --------------------------------------------------------------------------
+//    
+EXPORT_C TInt RLocationTrail::RetrieveLocation( const TTime& aTimeStamp, 
+												TLocationData& aLocationData,
+                                                TTrailState& aState )
+    {
+    TInt ret( KErrDisconnected );
+    TPckg<TTime> timeStamp( aTimeStamp );
+    TPckg<TTrailState> state( aState );
+    TPckg<TLocationData> locationData( aLocationData );
+    if ( iHandle )
+        {
+        ret = SendReceive( ELocManRetrieveLoc, TIpcArgs( &timeStamp, &locationData, &state ) );    
+        }
+    return ret;
+    }
+
+// --------------------------------------------------------------------------
+// RLocationTrail::CurrentLocation
+// --------------------------------------------------------------------------
+//
+EXPORT_C void RLocationTrail::CurrentLocation( TRequestStatus& aStatus, 
+											   TLocationData& aLocationData )
+    {
+    LOG( "RLocationTrail::CurrentLocation(), begin" );
+    
+    delete iCurrentLocData;
+    iCurrentLocData = new TPckg<TLocationData>( aLocationData );
+    
+    if ( iHandle && iCurrentLocData )
+        {
+        SendReceive( ELocManCurrentLoc, TIpcArgs( iCurrentLocData ), aStatus );
+        }
+    else
+        {
+        if ( !iCurrentLocData )
+        	{
+        	CompleteRequest(aStatus, KErrNoMemory);
+        	}
+        else
+        	{
+        	CompleteRequest(aStatus, KErrDisconnected);
+        	}
+        }
+    LOG( "RLocationTrail::CurrentLocation(), end" );
+    }
+
+// --------------------------------------------------------------------------
+// RLocationTrail::CancelLocationRequest
+// --------------------------------------------------------------------------
+//
+EXPORT_C void RLocationTrail::CancelLocationRequest()
+    {
+    if ( iHandle )
+        {
+        SendReceive( ELocManCancelCurrentLoc );
+        }
+    }
+
+EXPORT_C TInt RLocationTrail::GetTrailCaptureSetting( TTrailCaptureSetting& aCaptureSetting )
+	{
+	TPckg<TTrailCaptureSetting> captureSetting( aCaptureSetting );
+	TInt err( KErrDisconnected );
+	
+	if ( iHandle )
+		{
+		err = SendReceive( ELocManGetCaptureSetting, TIpcArgs( &captureSetting ) );
+		}
+	
+	return err;
+	}
+
+//End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/client/src/rtracklog.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,264 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An interface to Track Log API
+*
+*/
+
+#include "rtracklog.h"
+#include "locationmanagerdebug.h"
+#include "CTrackLogObserverAO.h"
+#include "locationmanagerdefs.h"
+
+EXPORT_C RTrackLog::RTrackLog() : RLocationManager(),
+	iWrapQuality( TPckg<TPositionSatelliteInfo>( iFixQuality ) ),
+	iWrapRec( TPckg<TBool>( iRecording ) ),
+	iWrapEventType( TPckg<TEventTypes>( iEventType ) )
+{
+}
+
+// --------------------------------------------------------------------------
+// RTrackLog::StartLocationTrail
+// --------------------------------------------------------------------------
+//
+EXPORT_C TInt RTrackLog::StartTrackLog()
+    {
+    LOG( "RTrackLog::StartTrackLog()" );
+    TInt ret( KErrDisconnected );
+    if ( iHandle )
+        {
+        ret = SendReceive( ELocManStartTrackLog );
+        }
+
+    return ret;
+    }
+
+// --------------------------------------------------------------------------
+// RTrackLog::StopTrackLog
+// --------------------------------------------------------------------------
+//
+EXPORT_C void RTrackLog::StopTrackLog()
+    {
+    LOG( "RTrackLog::StopTrackLog()" );
+    if ( iHandle )
+        {
+        SendReceive( ELocManStopTrackLog);
+        }   
+    }
+
+// --------------------------------------------------------------------------
+// RTrackLog::GetStatus
+// --------------------------------------------------------------------------
+//
+EXPORT_C TInt RTrackLog::GetStatus( TBool& aRecording, TPositionSatelliteInfo& aFixQuality )
+    {
+    LOG( "RTrackLog::GetStatus()" );
+    TInt ret( KErrDisconnected );
+    TPckg<TBool> wrapRec( aRecording );
+    TPckg<TPositionSatelliteInfo> wrapQuality( aFixQuality );
+    
+    if ( iHandle )
+        {
+        ret = SendReceive( ELocManGetTrackLogStatus, TIpcArgs( &wrapRec, &wrapQuality ) );
+        }
+    
+    return ret;
+    }
+
+// --------------------------------------------------------------------------
+// RTrackLog::DeleteTrackLog
+// --------------------------------------------------------------------------
+//
+EXPORT_C TInt RTrackLog::DeleteTrackLog( TDesC& aUri )
+    {
+    LOG( "RTrackLog::DeleteTrackLog()" );
+    TInt ret( KErrDisconnected );
+    if ( iHandle )
+        {
+        ret = SendReceive( ELocManDeleteTrackLog, TIpcArgs( &aUri ) );
+        }
+    return ret;
+    }
+
+// --------------------------------------------------------------------------
+// RTrackLog::IsRecording
+// --------------------------------------------------------------------------
+//
+EXPORT_C TBool RTrackLog::IsRecording()
+    {
+    LOG( "RTrackLog::IsRecording()" );
+    TBool rec = EFalse;
+    TPckg<TBool> wrapRec( rec );
+
+    if ( iHandle )
+        {
+        SendReceive( ELocManIsTrackLogRecording, TIpcArgs( &wrapRec ) );
+        }
+    
+    return rec;
+    }
+
+// --------------------------------------------------------------------------
+// RTrackLog::AddObserver
+// --------------------------------------------------------------------------
+//
+EXPORT_C TInt RTrackLog::AddObserver( MTrackLogObserver* aObserver )
+    {
+    LOG( "RTrackLog::AddObserver()" );
+    
+    TInt err( KErrNone );
+    
+    if ( iSubscribed )
+    	{
+    	return KErrAlreadyExists;
+    	}
+    
+    if ( !iHandle )
+    	{
+    	return KErrDisconnected;
+    	}
+    
+    // add message to observer pointer array    
+    err = iObservers.Append( aObserver );
+    
+    if ( err != KErrNone  )
+    	{
+    	return err;
+    	}
+    
+    if ( !iTrackLogObserverAO )
+    	{
+    	iTrackLogObserverAO = new CTrackLogObserverAO( this );
+    	}
+        
+	if ( iTrackLogObserverAO )
+		{
+		iSubscribed = ETrue;
+		iTrackLogObserverAO->StartObserving();
+		}
+	else 
+		{
+		// If creating observer AO failed, reset the observer list (don't destroy observers in it).
+		iObservers.Reset();
+		err = KErrNoMemory;
+		}
+   
+    return err;
+    }
+
+// --------------------------------------------------------------------------
+// RTrackLog::RemoveObserver
+// --------------------------------------------------------------------------
+//
+EXPORT_C TInt RTrackLog::RemoveObserver( MTrackLogObserver* aObserver )
+    {
+    LOG( "RTrackLog::RemoveObserver()" );
+    TInt err( KErrNotFound  );
+    TInt index( 0 );
+    
+    // remove message from observer pointer array
+    TRAP(err, index = iObservers.FindL(aObserver));
+    if (err == KErrNone)
+    	{
+    	iObservers.Remove(index);
+    	}
+  
+    if ( iObservers.Count() == 0 )
+    	{
+    	if ( iHandle )
+        	{
+            SendReceive( ELocManCancelTrackLogNotify );
+        	}
+    	iSubscribed = EFalse;
+    	delete iTrackLogObserverAO;
+    	iTrackLogObserverAO = NULL;
+    	}
+    
+    return err;
+    }
+
+// --------------------------------------------------------------------------
+// RTrackLog::TrackLogName
+// --------------------------------------------------------------------------
+//
+EXPORT_C TInt RTrackLog::TrackLogName(TDes& aTrackLogName)
+    {
+    LOG( "RTrackLog::TrackLogName()" );
+    TInt ret( KErrDisconnected );
+    
+    if ( iHandle )
+        {
+        ret = SendReceive( ELocManTrackLogName, TIpcArgs( &aTrackLogName ) );
+        }
+    
+    return ret;
+    }
+
+// --------------------------------------------------------------------------
+// RTrackLog::Close
+// --------------------------------------------------------------------------
+//
+EXPORT_C void RTrackLog::Close()
+    {
+    LOG( "RTrackLog::Close()" );
+    
+    if ( iHandle )
+    	{
+        SendReceive( ELocManCancelTrackLogNotify );
+    	}
+    
+    iObservers.Reset();		// Just reset the array, don't destroy observers in it.
+    delete iTrackLogObserverAO;
+    iTrackLogObserverAO = NULL;
+    iSubscribed = EFalse;
+    RLocationManager::Close();
+    }
+
+// --------------------------------------------------------------------------
+// RTrackLog::SendNotifyRequest
+// --------------------------------------------------------------------------
+//
+void RTrackLog::SendNotifyRequest( TRequestStatus& aStatus )
+	{
+    SendReceive( ELocManRegObserver, TIpcArgs( &iWrapRec, &iWrapQuality, &iWrapEventType ), 
+    		aStatus );
+	}
+
+// --------------------------------------------------------------------------
+// RTrackLog::GpsQualityChange
+// --------------------------------------------------------------------------
+//
+void RTrackLog::TrackLogEvent( TInt aError )
+	{
+	TInt count = iObservers.Count();
+	for ( TInt index = 0; index < count; index++ )
+		{
+		switch( iEventType )
+			{
+			case EStarted:
+				{
+				iObservers[index]->TrackLogStarted( aError );
+				}
+				break;
+			case EStopped:
+				{
+				iObservers[index]->TrackLogStopped( aError );
+				}
+				break;
+			case ESignalChanged:
+				{
+				iObservers[index]->GPSFixQualityChanged( iFixQuality, iRecording );
+				}
+			}
+		}
+	}
Binary file locationmanager/conf/200071BE.txt has changed
Binary file locationmanager/conf/locationmanager.confml has changed
Binary file locationmanager/conf/locationmanager_200071BE.crml has changed
Binary file locationmanager/data/200071BE.txt has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/data/Location_Manager_settings.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,15 @@
+<!DOCTYPE Feature SYSTEM "CT_XMLData.dtd">
+<Feature Name="Location Manager settings" Plugin="CRPlugin" Group="Location Manager" Desc="">
+	<Settings>
+		<Setting Name="Location manager storing interval" Key="0x1" Type="Int" ref="Variant/Location_Manager/TrailStoreInterval" Desc="Location Manager store Location Trail items to a memory buffer in defined interval.">5</Setting>
+		<Setting Name="Location manager trail length" Key="0x2" Type="Int" ref="Variant/Location_Manager/TrailBufferLength" Desc="Location Manager uses a memory buffer from where the TrackLog file is created. Value is buffer length in seconds.">600</Setting>
+		<Setting Name="Location trail stop delay" Key="0x3" Type="Int" ref="Variant/Location_Manager/TrailStopDelay" Desc="Delay before location trail actually stops after a call to RLocationTrail.StopLocationTrail(). This delay gives time to MdS to remap GPS locations to captured images without coordinates.">180</Setting>
+		<Setting Name="Tracklog buffer size" Key="0x4" Type="Int" ref="Variant/Location_Manager/TrackLogBufferSize" Desc="How many track points Tracklog keeps in phone memory before writing buffer to a file.">10</Setting>
+		<Setting Name="Same location distance" Key="0x5" Type="Int" ref="Variant/Location_Manager/LocationDelta" Desc="Maximum distance for using existing location object for context snapshot.">10</Setting>
+		<Setting Name="Location remapping time" Key="0x6" Type="Int" ref="Variant/Location_Manager/RemappingTime" Desc="Time in seconds for remapping locations after getting GPS fix.">600</Setting>
+    </Settings>
+	<Rules>
+		<CenRepfile Name1="\epoc32\data\z\private\10202BE9\200071BE.txt">1</CenRepfile>
+		<Ibyfile Name1="\epoc32\rom\include\S60Cenrep_variant.iby">1</Ibyfile>
+	</Rules>
+</Feature>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+#include "../locationtrail/group/bld.inf"
+#include "../server/group/bld.inf"
+#include "../client/group/bld.inf"
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+../data/200071BE.txt /epoc32/data/z/private/10202BE9/200071BE.txt
+../data/200071BE.txt /epoc32/WINSCW/C/private/10202BE9/200071BE.txt
+../sis/locationmanager_stub.sis  /epoc32/data/z/system/install/locationmanager_stub.sis
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/inc/locationmanagerdebug.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,81 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Common trace-information file.
+*
+*/
+
+#ifndef LOCATIONMANAGERDEBUG_H
+#define LOCATIONMANAGERDEBUG_H
+
+/**
+ *  Usage:  LOG(_L("[MODULE_NAME]\t Trace text here"));
+ *          TRACE(Print(_L("[MODULE_NAME]\t Trace text here with parameter %d"), iCount));
+ *
+ *          Trace target can be changed below (file logging needs directory c:\logs\upnp)
+ *          #define __CLOGGING -row uncommented            = Console logging
+ */
+
+// undefine for sure
+#undef __CLOGGING__
+
+// Uncomment this to get memory allocation prints from module
+//#define MEMORY_PRINT
+#ifdef _DEBUG
+// Define one of these flags:
+// CLOGGING = Console logging
+#define __CLOGGING__
+#endif
+
+
+
+// Then actual definitions depending on the 
+// flag values.
+
+#ifdef _DEBUG
+
+    #include <e32std.h>
+
+    #include <f32file.h>
+
+    // Define the top level macros
+    #ifdef MEMORY_PRINT
+        #define LOG(a) {PRINTLOG(a); MemPrint();}
+        #define LOG1(a,b) {PRINTLOG1(a,b); MemPrint();}
+        #define TRACE(a) {a; MemPrint();}
+    #else
+        #define LOG(a) {PRINTLOG(a);}
+        #define LOG1(a,b) {PRINTLOG1(a,b);}
+        #define TRACE(a) {a;}
+    #endif 
+
+    inline void MemPrint();
+
+    // Console Logging on
+    #define PRINTLOG(a) RDebug::Print(_L(a))
+    #define PRINTLOG1(a,b) RDebug::Print(_L(a),b)
+    
+	#include "locationmanagerdebug.inl"  // inline fuctions implementations
+
+#else
+
+    // DEBUG build is not on --> no logging at all
+    #define LOG(a)
+    #define LOG1(a,b)
+    #define TRACE(a)
+
+#endif  // _DEBUG
+
+#endif      // LOCATIONMANAGERDEBUG_H
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/inc/locationmanagerdebug.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,28 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Common trace-information file.
+*
+*/
+
+
+inline void MemPrint()
+    {
+    TUint32 id = RThread().SecureId().iId;
+    TInt allocSize = 0;
+    User::Heap().AllocSize( allocSize );
+    _LIT( KMsg, "[MEMORY] ID: %d\t AllocSize: %d" );
+    RDebug::Print( KMsg, id, allocSize );
+    }
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/inc/locationmanagerdefs.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,67 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition file for Location Manager.
+*
+*/
+
+#ifndef __LOCATIONMANAGERDEFS_H__
+#define __LOCATIONMANAGERDEFS_H__
+
+_LIT( KLocServerFileName, "LocationManagerServer.exe");
+_LIT( KLocServerName,     "LocationManagerServer" );
+
+const TInt KLocationManagerServerMinor = 0;
+const TInt KLocationManagerServerMajor = 1;
+const TInt KLocationManagerServerBuild = 0;
+
+const TInt KSessionSlotCount = -1; // use shared on-demand-pool
+
+enum TLocCommands // Server commands.
+    {
+    ELocManStartTrail,
+    ELocManStopTrail,
+    ELocManTrailState,
+    ELocManNotifyTrailStateChange,
+    ELocManCancelNotification,
+    ELocManRetrieveLoc,
+    ELocManCurrentLoc,
+    ELocManCancelCurrentLoc,
+    ELocManCreateLocationObject,
+    ELocManLocationSnapshot,
+    ELocManRemoveLocationObject,
+    ELocManCopyLocationDataById,
+    ELocManCopyLocationDataByUri,
+    ELocManEditLocationObject,
+    ELocManStartTrackLog,
+    ELocManStopTrackLog,
+    ELocManGetTrackLogStatus,
+    ELocManDeleteTrackLog,
+    ELocManIsTrackLogRecording,
+    ELocManTrackLogName,
+    ELocManRegObserver,
+    ELocManGetCaptureSetting,
+    ELocManCancelTrackLogNotify
+    };
+
+/** Message argument indices */
+enum TArgumentIndices
+    {
+    EArgumentTime = 0,
+    EArgumentLocationData,
+    EArgumentState
+    };
+
+#endif // __LOCATIONMANAGERDEFS_H__
+
+// End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/bwincw/locationtrailwinscw.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,34 @@
+EXPORTS
+	??1CLocationRecord@@UAE@XZ @ 1 NONAME ; CLocationRecord::~CLocationRecord(void)
+	??1CNetworkInfo@@UAE@XZ @ 2 NONAME ; CNetworkInfo::~CNetworkInfo(void)
+	??1CPositionInfo@@UAE@XZ @ 3 NONAME ; CPositionInfo::~CPositionInfo(void)
+	??1CTrackLog@@UAE@XZ @ 4 NONAME ; CTrackLog::~CTrackLog(void)
+	?AddGpxObserver@CTrackLog@@QAEXPAVMGpxConversionObserver@@@Z @ 5 NONAME ; void CTrackLog::AddGpxObserver(class MGpxConversionObserver *)
+	?CancelLocationRequest@CLocationRecord@@QAEXXZ @ 6 NONAME ; void CLocationRecord::CancelLocationRequest(void)
+	?CancelRecording@CTrackLog@@QAEXXZ @ 7 NONAME ; void CTrackLog::CancelRecording(void)
+	?CreateLocationObjectL@CLocationRecord@@QAEXABUTLocationData@@ABI@Z @ 8 NONAME ; void CLocationRecord::CreateLocationObjectL(struct TLocationData const &, unsigned int const &)
+	?CreateLocationTagL@CLocationRecord@@QAEKXZ @ 9 NONAME ABSENT ; unsigned long CLocationRecord::CreateLocationTagL(void)
+	?GetLocationByTimeL@CLocationRecord@@QAEXVTTime@@AAUTLocationData@@AAW4TTrailState@RLocationTrail@@@Z @ 10 NONAME ; void CLocationRecord::GetLocationByTimeL(class TTime, struct TLocationData &, enum RLocationTrail::TTrailState &)
+	?GetNetworkInfo@CLocationRecord@@QAEXAAVTNetworkInfoV1@CTelephony@@@Z @ 11 NONAME ; void CLocationRecord::GetNetworkInfo(class CTelephony::TNetworkInfoV1 &)
+	?GetStatus@CTrackLog@@QAEHAAHAAVTPositionSatelliteInfo@@@Z @ 12 NONAME ; int CTrackLog::GetStatus(int &, class TPositionSatelliteInfo &)
+	?GetTagId@CTrackLog@@QAEKXZ @ 13 NONAME ABSENT ; unsigned long CTrackLog::GetTagId(void)
+	?GetTrackLogName@CTrackLog@@QAEXAAV?$TBuf@$0BAA@@@@Z @ 14 NONAME ; void CTrackLog::GetTrackLogName(class TBuf<256> &)
+	?IsRecording@CTrackLog@@QAEHXZ @ 15 NONAME ; int CTrackLog::IsRecording(void)
+	?LocationTrailState@CLocationRecord@@QAEXAAW4TTrailState@RLocationTrail@@@Z @ 16 NONAME ; void CLocationRecord::LocationTrailState(enum RLocationTrail::TTrailState &)
+	?NewL@CLocationRecord@@SAPAV1@XZ @ 17 NONAME ; class CLocationRecord * CLocationRecord::NewL(void)
+	?NewL@CNetworkInfo@@SAPAV1@PAVMNetworkInfoObserver@@@Z @ 18 NONAME ; class CNetworkInfo * CNetworkInfo::NewL(class MNetworkInfoObserver *)
+	?NewL@CPositionInfo@@SAPAV1@PAVMPositionInfoObserver@@@Z @ 19 NONAME ; class CPositionInfo * CPositionInfo::NewL(class MPositionInfoObserver *)
+	?NewL@CTrackLog@@SAPAV1@XZ @ 20 NONAME ; class CTrackLog * CTrackLog::NewL(void)
+	?RequestLocationL@CLocationRecord@@QAEXXZ @ 21 NONAME ; void CLocationRecord::RequestLocationL(void)
+	?SetAddObserver@CLocationRecord@@QAEXPAVMLocationAddObserver@@@Z @ 22 NONAME ; void CLocationRecord::SetAddObserver(class MLocationAddObserver *)
+	?SetMdeSession@CLocationRecord@@QAEXPAVCMdESession@@@Z @ 23 NONAME ; void CLocationRecord::SetMdeSession(class CMdESession *)
+	?SetObserver@CLocationRecord@@QAEXPAVMLocationTrailObserver@@@Z @ 24 NONAME ; void CLocationRecord::SetObserver(class MLocationTrailObserver *)
+	?StartL@CLocationRecord@@QAEXW4TTrailCaptureSetting@RLocationTrail@@@Z @ 25 NONAME ; void CLocationRecord::StartL(enum RLocationTrail::TTrailCaptureSetting)
+	?StartRecordingL@CTrackLog@@QAEXK@Z @ 26 NONAME ; void CTrackLog::StartRecordingL(unsigned long)
+	?StartRecoveryL@CTrackLog@@QAEXXZ @ 27 NONAME ; void CTrackLog::StartRecoveryL(void)
+	?Stop@CLocationRecord@@QAEXXZ @ 28 NONAME ; void CLocationRecord::Stop(void)
+	?StopRecordingL@CTrackLog@@QAEXXZ @ 29 NONAME ; void CTrackLog::StopRecordingL(void)
+	?SetStateToStopping@CLocationRecord@@QAEXXZ @ 30 NONAME ; void CLocationRecord::SetStateToStopping(void)
+	?LocationSnapshotL@CLocationRecord@@QAEXABI@Z @ 31 NONAME ; void CLocationRecord::LocationSnapshotL(unsigned int const &)
+	?RemappingNeeded@CLocationRecord@@QAEHXZ @ 32 NONAME ; int CLocationRecord::RemappingNeeded(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/eabi/locationtrailarm.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,44 @@
+EXPORTS
+	_ZN12CNetworkInfo4NewLEP20MNetworkInfoObserver @ 1 NONAME
+	_ZN13CPositionInfo4NewLEP21MPositionInfoObserver @ 2 NONAME
+	_ZN15CLocationRecord11SetObserverEP22MLocationTrailObserver @ 3 NONAME
+	_ZN15CLocationRecord14GetNetworkInfoERN10CTelephony14TNetworkInfoV1E @ 4 NONAME
+	_ZN15CLocationRecord14SetAddObserverEP20MLocationAddObserver @ 5 NONAME
+	_ZN15CLocationRecord16RequestLocationLEv @ 6 NONAME
+	_E32Dll @ 7 NONAME ABSENT
+	_ZN15CLocationRecord18GetLocationByTimeLE5TTimeR13TLocationDataRN14RLocationTrail11TTrailStateE @ 8 NONAME
+	_ZN15CLocationRecord18LocationTrailStateERN14RLocationTrail11TTrailStateE @ 9 NONAME
+	_ZN15CLocationRecord21CancelLocationRequestEv @ 10 NONAME
+	_E32Dll @ 11 NONAME ABSENT
+	_ZN15CLocationRecord4NewLEv @ 12 NONAME
+	_ZN15CLocationRecord4StopEv @ 13 NONAME
+	_ZN15CLocationRecord6StartLEN14RLocationTrail20TTrailCaptureSettingE @ 14 NONAME
+	_ZN9CTrackLog11IsRecordingEv @ 15 NONAME
+	_ZN9CTrackLog14StopRecordingLEv @ 16 NONAME
+	_ZN9CTrackLog15CancelRecordingEv @ 17 NONAME
+	_ZN9CTrackLog15GetTrackLogNameER4TBufILi256EE @ 18 NONAME
+	_ZN9CTrackLog4NewLEv @ 19 NONAME
+	_ZN9CTrackLog9GetStatusERiR22TPositionSatelliteInfo @ 20 NONAME
+	_ZTI12CNetworkInfo @ 21 NONAME ; #<TI>#
+	_ZTI13CPositionInfo @ 22 NONAME ; #<TI>#
+	_ZTI15CGpxConverterAO @ 23 NONAME ; #<TI>#
+	_ZTI15CLocationRecord @ 24 NONAME ; #<TI>#
+	_ZTI9CTrackLog @ 25 NONAME ; #<TI>#
+	_ZTV12CNetworkInfo @ 26 NONAME ; #<VT>#
+	_ZTV13CPositionInfo @ 27 NONAME ; #<VT>#
+	_ZTV15CGpxConverterAO @ 28 NONAME ; #<VT>#
+	_ZTV15CLocationRecord @ 29 NONAME ; #<VT>#
+	_ZTV9CTrackLog @ 30 NONAME ; #<VT>#
+	_ZN9CTrackLog14AddGpxObserverEP22MGpxConversionObserver @ 31 NONAME
+	_ZN9CTrackLog14StartRecoveryLEv @ 32 NONAME
+	_ZN9CTrackLog8GetTagIdEv @ 33 NONAME ABSENT
+	_ZN15CLocationRecord13SetMdeSessionEP11CMdESession @ 34 NONAME
+	_ZN15CLocationRecord18CreateLocationTagLEv @ 35 NONAME ABSENT
+	_ZN15CLocationRecord21CreateLocationObjectLERK13TLocationDataRKj @ 36 NONAME
+	_ZTI20CLocationRemappingAO @ 37 NONAME ; #<TI>#
+	_ZTV20CLocationRemappingAO @ 38 NONAME ; #<VT>#
+	_ZN9CTrackLog15StartRecordingLEm @ 39 NONAME
+	_ZN15CLocationRecord18SetStateToStoppingEv @ 40 NONAME
+	_ZN15CLocationRecord17LocationSnapshotLERKj @ 41 NONAME
+	_ZN15CLocationRecord15RemappingNeededEv @ 42 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+locationtrail.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/group/locationtrail.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION         10.0
+TARGET          LocationTrail.dll
+TARGETTYPE      DLL
+UID             0x1000008d 0x200071BD 
+
+VENDORID 	    VID_DEFAULT
+CAPABILITY 	    CAP_GENERAL_DLL
+
+#if defined(WINSCW)
+deffile ../bwincw/locationtrailwinscw.def
+#elif defined(ARMCC)
+deffile ../eabi/locationtrailarm.def
+#endif
+nostrictdef
+
+USERINCLUDE     ../inc
+USERINCLUDE     ../../inc
+
+SOURCEPATH      ../src
+SOURCE          clocationrecord.cpp
+SOURCE          cnetworkinfo.cpp
+SOURCE          cpositioninfo.cpp
+SOURCE          ctracklog.cpp
+SOURCE          cgpxconverterao.cpp
+SOURCE          locationremappingao.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib 
+LIBRARY         efsrv.lib
+LIBRARY         lbs.lib
+LIBRARY         etel3rdparty.lib
+LIBRARY	    mdeclient.lib
+LIBRARY         estor.lib
+LIBRARY	    PlatformEnv.lib
+LIBRARY 	    centralrepository.lib 
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/inc/cgpxconverterao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,190 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Active object for converting internal fileformat to GPX
+*
+*/
+
+
+#ifndef CGPXCONVERTERAO_H_
+#define CGPXCONVERTERAO_H_
+
+#include <e32base.h>
+#include <e32cmn.h>
+#include <e32property.h>
+#include <f32file.h>
+#include <s32file.h>
+#include "ctracklog.h"
+
+const TInt KWriteBufSize = 256;
+
+_LIT( KTagXml, "<?xml version=\"1.0\"?>" );
+_LIT( KTagGpxStart, "<gpx version=\"1.1\" creator=\"Nokia TrackLog\">" );
+_LIT( KTagGpxEnd, "</gpx>" );
+_LIT( KTagMetaStart, "<metadata>" );
+_LIT( KTagMetaEnd, "</metadata>" );
+_LIT( KTagName, "<name>%S</name>" );
+_LIT( KTagBounds, "<bounds minlat=\"%f\" minlon=\"%f\" maxlat=\"%f\" maxlon=\"%f\" />" );
+_LIT( KTagTrackStart, "<trk>" );
+_LIT( KTagTrackEnd, "</trk>" );
+_LIT( KTagSegmentStart, "<trkseg>" );
+_LIT( KTagSegmentEnd, "</trkseg>" );
+_LIT( KTagTrkPointStart, "<trkpt lat=\"%f\" lon=\"%f\">" );
+_LIT( KTagTrkPointEnd, "</trkpt>" );
+_LIT( KTagElevation, "<ele>%f</ele>" );
+_LIT( KTagTimeStamp, "<time>%d-%02d-%02dT%02d:%02d:%02dZ</time>" );
+_LIT( KTagCourse, "<course>%f</course>" );
+_LIT( KTagFix3D, "<fix>3d</fix>" );
+_LIT( KTagFix2D, "<fix>2d</fix>" );
+_LIT( KTagSatellites, "<sat>%d</sat>" );
+_LIT( KTagHdop, "<hdop>%f</hdop>" );
+_LIT( KTagVdop, "<vdop>%f</vdop>" );
+
+class CGpxConverterAO : public CActive
+  	{
+  	private:
+  		enum TProcessingState
+  			{
+  			EIdle,
+  			ENextFile,
+  			ECrashRecovery,
+  			EStartFile,
+  			EProcessing,
+  			ECloseFile
+  			};
+  	
+  	public:
+        /**
+         * Creates and constructs a new instance of CContextBackupSubscriberAO.
+         *
+         * @return A pointer to the new instance.
+         */
+        static CGpxConverterAO* NewL();
+
+        /**
+         * Destructor.
+         */
+        virtual ~CGpxConverterAO();
+
+        /**
+         * From CActive.
+         * This method will be called when Backup & Restore state changes.
+         */
+        void RunL();
+
+        /**
+         * From CActive.
+         * Handles a leave occurring in the request completion event handler RunL().
+         *
+         * @param aError  An error code.
+         * @return An error code.
+         */
+        TInt RunError( TInt aError );
+
+        /**
+         * From CActive.
+         * Cancels.
+         */
+        void DoCancel();
+        
+        /**
+         * Adds temp-file and possible pre-calculated boundaries
+         * into processing queue
+         */
+        void AddToQueueL( const TDesC& aFileName, TBoundaries* aBoundaries = NULL );
+        
+        /**
+         * Adds observer for GPX file creation notifications
+         */
+        void AddObserver( MGpxConversionObserver* aObserver );
+
+    private:
+
+        /**
+         * Default constructor, implicitly called by NewL().
+         */
+    	CGpxConverterAO();
+
+        /**
+         * 2nd phase construction, called by NewL().
+         */
+        void ConstructL();
+        
+        /**
+         * Set next state for RunL
+         */
+        void SetState( TProcessingState aState );
+        
+        /**
+         * Resolve where to save tracklog file
+         */
+        void GetTrackLogPathL( TDes& aFileName );
+        
+        /**
+         * Read Tag Id from temp-file
+         */
+        void ReadTagIdL();
+        
+        /**
+         * Calculate min and max coordinates for tracklog
+         */
+        void CalculateBoundaries();
+        
+        /**
+         * Writes header tags for GPX file
+         */
+        void WriteStartingTags();
+        
+        /**
+         * Writes single trackpoint to GPX file
+         */
+        void WriteItemToFile();
+        
+        /**
+         * Close GPX file 
+         */
+        void WriteClosingTags();
+        
+    private: // data
+    
+    	TInt iState;
+    	
+    	RPointerArray<TFileName> iFileQueue;
+    	RPointerArray<TBoundaries> iBoundQueue;
+    	
+    	TFileName iTempFile;
+    	TBoundaries* iBoundaries;
+    	TCoordinate* iLastCoords;
+    	TFileName iGpxFileName;
+    	TFileName iGpxPath;
+    	
+    	RFs iFs;
+    	RFileReadStream iReader;
+    	RFile64 iGpxFile;
+    	
+    	TTrackLogItem iTempItem;
+    	
+    	HBufC8* iWriteBuf;
+    	HBufC* iFormatBuf;
+    	
+    	TBool iFixLost;
+    	TItemId iTagId;
+    	
+    	TTime iStartTime;
+    	TTime iEndTime;
+    	
+    	RPointerArray<MGpxConversionObserver> iObservers;
+
+    };
+
+#endif /*CGPXCONVERTERAO_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/inc/clocationrecord.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,371 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A class for recording and storing locations.
+*
+*/
+
+#ifndef C_CLOCATIONRECORD_H
+#define C_CLOCATIONRECORD_H
+
+#include <e32base.h>
+#include <e32property.h>
+#include <Lbs.h>
+
+#include "rlocationtrail.h"
+#include "locationdatatype.h"
+#include "cnetworkinfo.h"
+#include "cpositioninfo.h"
+#include "rlocationobjectmanipulator.h"
+
+#include "mdccommon.h"
+#include "mdesession.h"
+#include "mdenamespacedef.h"
+#include "mdeobjectdef.h"
+#include "mdepropertydef.h"
+#include "mderelation.h"
+#include "mdequery.h"
+#include "locationremappingao.h"
+
+typedef RLocationTrail::TTrailState TLocTrailState;
+
+class CTelephony;
+class TPositionSatelliteInfo;
+
+/**
+*  An observer interface, which is used for getting notification when the 
+*  location trail's state changes.    
+*
+*  @since S60 3.1
+*/
+class MLocationTrailObserver
+    {
+public:    
+    /**
+     * This method is used to notify about location trail state changes.
+     */
+    virtual void LocationTrailStateChange() = 0;
+    
+    virtual void CurrentLocation( const TPositionSatelliteInfo& aSatelliteInfo, 
+    							  const CTelephony::TNetworkInfoV1& aNetworkInfo,
+                                  const TInt aError ) = 0;
+    
+    virtual void GPSSignalQualityChanged( const TPositionSatelliteInfo& aSatelliteInfo ) = 0;
+    };
+
+/**
+* Location trail item class.
+*/
+class TLocationTrailItem
+    {
+    public:
+    	TLocationData	iLocationData; // Location info & network info
+        TTime           iTimeStamp;  // Time stamp.
+        TLocTrailState  iTrailState; // Trail state for this item.
+    };
+    
+class MLocationAddObserver
+	{
+public:
+	/**
+	 * This method is used to notify about new locations added to location trail
+	 */
+	virtual void LocationAdded( const TLocationTrailItem& aTrailItem, 
+								const TPositionSatelliteInfo& aSatellites ) = 0;
+	};    
+
+/**
+ *  Location trail collects location information periodically and stores them
+ *  to an array. Stored locations may be searched by time stamp to get 
+ *  a location, which corresponds to certain time.  
+ *
+ *  @since S60 3.1
+ */
+class CLocationRecord : public CBase,
+                        public MNetworkInfoObserver,
+                        public MPositionInfoObserver,
+                        public MMdEQueryObserver
+    {
+public:  
+    /**
+     * 2-phased constructor.
+     * @since S60 3.1
+     */
+    IMPORT_C static CLocationRecord* NewL();
+
+    /**
+     * C++ destructor.
+     * @since S60 3.1
+     */    
+    IMPORT_C virtual ~CLocationRecord();
+
+    
+public:
+    /**
+     * Returns the current state of the location trail.
+     * @since S60 3.1
+     * @param aState, The current state is written to this variable.
+     * @return None.
+     */    
+    IMPORT_C void LocationTrailState( TLocTrailState& aState );
+    
+    /**
+     * Starts collecting locations from Location Acquisition API.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */    
+    IMPORT_C void StartL( RLocationTrail::TTrailCaptureSetting aCaptureSetting );
+    
+    /**
+     * Stops collecting locations.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */    
+    IMPORT_C void Stop();    
+
+    /**
+     * Returns the location info, which is nearest to the given time.
+     * @since S60 3.1
+     * @param aTime, A time stamp to get corresponding location.
+     * @param aPosition, Location info is written to this param.
+     * @param 
+     * @return None.
+     */
+    IMPORT_C void GetLocationByTimeL( const TTime aTime,
+    								  TLocationData& aLocationData,
+                                      /*TLocality& aPosition,
+                                      CTelephony::TNetworkInfoV1& aNetworkInfo,*/
+                                      TLocTrailState& aState );
+
+    /**
+     * Request location info. The result is returned by calllback method.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */
+    IMPORT_C void RequestLocationL();
+
+    /**
+     * Cancel request for location info. 
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */    
+    IMPORT_C void CancelLocationRequest();
+        
+    /**
+     * Get network cell id.
+     * @since S60 3.1
+     * @param aCellId, Network cell is written into this param.
+     * @return None.
+     */
+    IMPORT_C void GetNetworkInfo( CTelephony::TNetworkInfoV1& aNetworkInfo );
+    
+    /**
+     * Set observer for notifying state changes.
+     * @since S60 3.1
+     * @param aObserver, An interface to notify about state changes.
+     * @return None.
+     */
+    IMPORT_C void SetObserver( MLocationTrailObserver* aObserver );
+    
+    /**
+     * Set observer (TrackLog) for notifying new locations in location trail
+     */
+    IMPORT_C void SetAddObserver( MLocationAddObserver* aObserver );    
+    
+    static TInt UpdateNetworkInfo( TAny* aAny );
+    
+    IMPORT_C void CreateLocationObjectL( const TLocationData& aLocationData,
+    		const TUint& aObjectId );
+    
+    IMPORT_C void LocationSnapshotL( const TUint& aObjectId );
+    
+    TItemId DoCreateLocationL( const TLocationData& aLocationData );
+    
+    TItemId CreateRelationL( const TUint& aObjectId, const TUint& aLocationId );
+    
+    IMPORT_C void SetMdeSession( CMdESession* aSession );
+    
+    IMPORT_C void SetStateToStopping();
+    
+    TTime GetMdeObjectTimeL( TItemId aObjectId );
+    
+    IMPORT_C TBool RemappingNeeded();
+
+public: // from MNetworkInfoObserver.
+    /**
+     * 
+     * @since S60 3.1
+     * @param 
+     * @return 
+     */
+    void NetworkInfo( const CTelephony::TNetworkInfoV1 &aNetworkInfo, TInt aError );
+    
+public: // from MPositionInfoObserver    
+    /**
+     * 
+     * @since S60 3.1
+     * @param 
+     * @return  
+     */
+    void Position( const TPositionInfo& aPositionInfo, const TInt aError );
+    
+    
+public: // From MMdEQueryObserver
+
+	void HandleQueryNewResults(CMdEQuery& aQuery, TInt aFirstNewItemIndex, 
+			TInt aNewItemCount);
+	
+	void HandleQueryCompleted(CMdEQuery& aQuery, TInt aError);
+	
+private:    
+    /**
+     * Stores the location info into the array.
+     */
+    void StoreLocation( /*const TPosition& aPosition, const TCourse& aCourse,*/ 
+    		const TPositionSatelliteInfo& aSatelliteInfo );
+    
+    /**
+     * Changes the current state. New state is published in P&S and
+     * possible observer is notified.
+     */    
+    void SetCurrentState( TLocTrailState aState );
+    
+    /**
+     * Returns the requested location via callback method, if the location
+     * is valid. Otherwise new location value is requested until the value
+     * is succesful, or the time out limit has been reached.
+     * 
+     */
+    void HandleLocationRequest( const TPositionSatelliteInfo& aSatelliteInfo /*TLocality& aPosition*/, 
+                                const TInt aError );
+    /**
+     * C++ constructor.
+     */  
+    CLocationRecord();
+    
+    /**
+     * 2nd phase constructor.
+     */
+    void ConstructL();
+    
+    /**
+     * Read interval value from Central repository
+     * @param aKey, Key to item
+     * @param aValue, Read value
+     */ 
+    void ReadCenRepValueL(TInt aKey, TInt& aValue);
+    
+    TBool CheckGPSFix( const TPositionSatelliteInfo& aSatelliteInfo );
+    
+    void StartTimerL();
+
+private:
+	/**
+	 * A session to Metadata Engine for creating and manipulating location objects.
+	 */
+	CMdESession* iMdeSession;
+	
+    /**
+     * An observer interface to notify about state changes.
+     * Not own.
+     */
+    MLocationTrailObserver* iObserver;
+    
+    /**
+     * An observer interface to notify about new locations.
+     * Not own.
+     */
+    MLocationAddObserver* iAddObserver;    
+
+    /**
+     * An array to collect location values.
+     * Own.
+     */
+    RArray<TLocationTrailItem> iTrail;
+
+    /**
+     * P&S key property.
+     * Own.
+     */
+    RProperty iProperty;
+
+    /**
+     * Active class to get network information.
+     * Own.
+     */
+    CNetworkInfo* iNetworkInfo;
+    
+    /**
+     * Active class to get position information.
+     * Own.
+     */
+    CPositionInfo* iPositionInfo;
+    
+	/**
+	 * Class which handles database remapping operations
+	 */ 
+	CLocationRemappingAO* iRemapper;
+    
+    CActiveSchedulerWait   iWait;
+    
+    /**
+     * Timer for capturing network info only
+     */
+    CPeriodic*			   iNetworkInfoTimer;
+
+    TLocTrailState         iState;    
+    TLocationTrailItem     iNewItem;
+    RLocationTrail::TTrailCaptureSetting   iTrailCaptureSetting;
+    CTelephony::TNetworkInfoV1		   iNetwork;
+
+    TInt                   iMaxTrailSize;
+    TInt                   iLocationCounter;
+    
+    /*
+     * Interval value for location trail
+     */
+    TInt iInterval;
+    
+    /**
+     * Buffer size for tracklog
+     */ 
+    TInt iBufferSize;
+    
+    TBool                  iRequestCurrentLoc;
+    TBool                  iTrailStarted;
+    
+    TUint				   iLastNumberOfSatellitesUsed;
+    TReal32				   iLastHDOP;
+    TReal32				   iLastVDOP;
+    TBool				   iLastGPSFixState;
+    
+    TInt                   iLocationDelta;
+    TLocationData          iLastLocation;
+    TItemId                iLastLocationId;
+    
+    TItemId iObjectId;               
+    TLocationData iLocationData;
+    
+    /**
+     * This query object is used to find existing locations
+     */
+    CMdEObjectQuery* iLocationQuery;
+    };
+
+#endif // C_CLOCATIONRECORD_H 
+
+// End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/inc/clocationwrite.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,93 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Writes location info to image's EXIF data.
+*
+*/
+
+#ifndef C_CLOCATIONWRITE_H
+#define C_CLOCATIONWRITE_H
+
+#include <e32base.h>
+
+class CExifModify;
+class CLocationRecord;
+class TPosition;
+/**
+*  This class writes GPS details to image's EXIF data.  
+*
+*  @since S60 3.1
+*/
+class CLocationWrite : public CBase
+    {
+public:  
+    /**
+     * 2-phased constructor.
+     */
+    IMPORT_C static CLocationWrite* NewL( CLocationRecord& aLocRecord );
+    
+    /**
+     * C++ destructor.
+     */
+    IMPORT_C virtual ~CLocationWrite();
+    
+public: 
+    /**
+     * Write location information to the image.
+     * @since S60 3.1
+     * @param aName, The name and path of the image, in which the location
+     *               information will be updated.
+     */
+    IMPORT_C void WriteLocationL( const TDesC& aName );
+            
+private:
+    /**
+     * C++ constructor.
+     */  
+    CLocationWrite( CLocationRecord& aLocRecord );
+    
+    /**
+     * 2nd phase constructor.
+     */
+    void ConstructL();
+    
+private:
+    /**
+     * Write GPS tags to EXIF.
+     */
+    void WriteGPSTagsToExifL( CExifModify& aExif, 
+                              const TPosition& aPosition );
+    
+    /**
+     * Create EXIF tag. 
+     */
+    void CreateTag( const TInt aTagId, 
+                    const TPosition& aPosition, 
+                    TDes8& aTagData );
+    
+    /**
+     * Append integer to descriptor.
+     */
+    void AppendIntegerToDesc( TDes8& aTagDesc, const TUint aValue );
+    
+private:
+    /**
+     * The location trail record class.
+     * Not own.
+     */
+    CLocationRecord& iLocationRecord;
+    };
+
+#endif // C_CLOCATIONWRITE_H
+
+// End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/inc/cnetworkinfo.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,111 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#ifndef C_CNETWORKINFO_H
+#define C_CNETWORKINFO_H
+
+#include <etel3rdparty.h>
+
+/**
+*  An observer interface, which is used for getting current network cell id.
+*
+*  @since S60 3.1
+*/
+class MNetworkInfoObserver
+    {
+public:    
+    /**
+     * This method is used for setting the network cell id to the 
+     * location trail.
+     */
+    virtual void NetworkInfo( const CTelephony::TNetworkInfoV1 &aNetworkInfo, const TInt aError ) = 0;
+    };
+
+/**
+ *  
+ *  @since S60 3.1
+ */
+class CNetworkInfo : public CActive
+    {
+public:  
+    /**
+     * 2-phased constructor.
+     * @since S60 3.1
+     */
+    IMPORT_C static CNetworkInfo* NewL( MNetworkInfoObserver* aTrail );
+
+    /**
+     * C++ destructor.
+     * @since S60 3.1
+     */    
+    IMPORT_C virtual ~CNetworkInfo();
+
+protected:
+    /**
+     * Run error implementation in case of RunL leaving.
+     * @since S60 3.1
+     */
+    TInt RunError( TInt aError );
+    
+private:
+    /**
+     * C++ constructor.
+     */  
+    CNetworkInfo( MNetworkInfoObserver* aTrail );
+    
+    /**
+     * 2nd phase constructor.
+     */
+    void ConstructL();
+    
+private:
+    /**
+    * From CActive.
+    */        
+    void DoCancel();
+    
+    /**
+    * From CActive.
+    */        
+    void RunL(); 
+
+private:
+    /**
+     * An observer interface to set current cell id to the location trail.
+     * Not own.
+     */
+    MNetworkInfoObserver* iTrail;
+    
+    /**
+     * Flag to indicate that we retrieve network info for the first time.
+     */ 
+    TBool iFirstTime;
+    
+    /**
+     * Interface to phone's telephony system to get Cell Id.
+     * Own.
+     */
+    CTelephony* iTelephony;
+    
+    CTelephony::TNetworkInfoV1 iNetworkInfoV1;
+    CTelephony::TNetworkInfoV1Pckg iNetworkInfoV1Pckg;
+    };
+
+#endif // C_CNETWORKINFO_H
+
+// End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/inc/cpositioninfo.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,145 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#ifndef C_CPOSITIONINFO_H
+#define C_CPOSITIONINFO_H
+
+#include <Lbs.h>
+#include <LbsSatellite.h>
+#include "rlocationtrail.h"
+
+/**
+*  An observer interface, which is used for getting current position info.
+*
+*  @since S60 3.1
+*/
+class MPositionInfoObserver
+    {
+public:    
+    /**
+     * This method is used for setting the network cell id to the 
+     * location trail.
+     */
+    virtual void Position( const TPositionInfo& aPositionInfo, 
+                           const TInt aError ) = 0;
+    };
+
+/**
+ *
+ *  @since S60 3.1
+ */
+class CPositionInfo : public CActive
+    {
+public:  
+    /**
+     * 2-phased constructor.
+     * @since S60 3.1
+     */
+    IMPORT_C static CPositionInfo* NewL( MPositionInfoObserver* aTrail );
+
+    /**
+     * C++ destructor.
+     * @since S60 3.1
+     */    
+    IMPORT_C virtual ~CPositionInfo();
+
+public:
+    /**
+     * Start collecing positions.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */    
+    void StartL( RLocationTrail::TTrailCaptureSetting aCaptureSetting, TInt aUpdateInterval );
+    
+    /**
+     * Get next position.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */  
+    void NextPosition();   
+    
+    /**
+     * Stop collecing positions.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */    
+    void Stop();
+        
+protected:
+    /**
+     * Run error implementation in case of RunL leaving.
+     * @since S60 3.1
+     */
+    TInt RunError( TInt aError );
+    
+private:
+    /**
+     * C++ constructor.
+     */  
+    CPositionInfo( MPositionInfoObserver* aTrail );
+    
+    /**
+     * 2nd phase constructor.
+     */
+    void ConstructL();
+    
+private:
+    /**
+    * From CActive.
+    */        
+    void DoCancel();
+    
+    /**
+    * From CActive.
+    */        
+    void RunL(); 
+
+private:
+    /**
+     * An observer interface to set current position to the location trail.
+     * Not own.
+     */
+    MPositionInfoObserver* iTrail;
+    
+    /**
+     * Position server.
+     * Own.
+     */
+    RPositionServer iPosServer;
+
+    /**
+     * Positioner.
+     * Own.
+     */
+    RPositioner iPositioner;
+
+    TPositionSatelliteInfo iPositionInfo; 
+    TPositionUpdateOptions iUpdateOptions;
+    RLocationTrail::TTrailCaptureSetting   iTrailCaptureSetting;
+    
+    TInt iUpdateInterval;
+    
+    TBool iFirstInterval;
+    };
+
+#endif // C_CPOSITIONINFO_H
+
+// End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/inc/ctracklog.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,173 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A class for TrackLog functionality
+ *
+*/
+
+
+#ifndef CTRACKLOG_H_
+#define CTRACKLOG_H_
+
+#include <f32file.h>
+#include <Lbs.h>
+#include "clocationrecord.h"
+#include <LbsSatellite.h>
+
+class MTrackLogObserver;
+class CGpxConverterAO;
+
+/**
+ * class for recording position min/max values
+ */
+class TBoundaries
+{
+public:
+	TReal64 minLatitude;
+	TReal64 maxLatitude;
+	TReal64 minLongitude;
+	TReal64 maxLongitude;
+	TReal32 distance;
+};
+
+/**
+* Location trail item class.
+*/
+class TTrackLogItem
+	{
+public:
+	TTime iTimeStamp;
+	TReal64 iLatitude;
+	TReal64 iLongitude;
+	TReal32 iAltitude;
+	TReal32 iHdop;
+	TReal32 iVdop;
+	TReal32 iCourse;
+	TReal32 iQuality;
+	TUint32 iNumSatellites;
+	void ExternalizeL( RWriteStream& aStream ) const;
+	void InternalizeL( RReadStream& aStream );
+	};
+	
+class MGpxConversionObserver
+	{
+public:
+	/**
+	 * This method is used to notify about converted GPX files
+	 */
+	virtual void GpxFileCreated( const TDesC& aFileName, TItemId aTagId, TReal32 aLength,
+			TTime aStart, TTime aEnd ) = 0;
+	};    
+
+class CTrackLog : public CBase, public MLocationAddObserver
+	{
+
+public:
+	/**
+	 * 2-phased constructor.
+	 */
+	IMPORT_C static CTrackLog* NewL();
+
+	/**
+	 * C++ destructor.
+	 * @since S60 3.1
+	 */
+	IMPORT_C virtual ~CTrackLog();
+	
+	IMPORT_C TInt GetStatus( TBool& aRecording,	TPositionSatelliteInfo& aFixQuality );
+	
+	IMPORT_C TBool IsRecording();
+
+	/**
+	 * Initialize recording
+	 */
+	IMPORT_C void StartRecordingL(TItemId aId);
+	
+	/**
+	 * Stop tracklog recording
+	 */
+	IMPORT_C void StopRecordingL();
+	
+	/**
+	 * stop tracklog recording without saving gpx file
+	 */
+	IMPORT_C void CancelRecording();
+	
+	/**
+	 * get tracklog file name
+	 */
+	IMPORT_C void GetTrackLogName(TFileName& aFileName);
+	
+	/*
+	 * from MLocationAddObserver
+	 */
+	void LocationAdded( const TLocationTrailItem& aTrailItem, const TPositionSatelliteInfo& aSatellites );
+		
+	IMPORT_C void AddGpxObserver( MGpxConversionObserver* aObserver );
+	
+	IMPORT_C void StartRecoveryL();
+	IMPORT_C TInt AddObserver( MTrackLogObserver* aObserver );
+	
+	IMPORT_C TInt RemoveObserver( MTrackLogObserver* aObserver );
+
+private:
+	/**
+	 * C++ constructor.
+	 */
+	CTrackLog();
+
+	/**
+	 * 2nd phase constructor.
+	 */
+	void ConstructL();
+
+	/**
+	 * Write Tracklog data from buffer to temporary file
+	 */
+	void WriteBufferToFileL();
+	
+    /**
+     * Read interval value from Central repository
+     * @param aKey, Key to item
+     * @param aValue, Read value
+     */ 
+    void ReadCenRepValueL(TInt aKey, TInt& aValue);
+	
+private:
+	/**
+	 * Array for storing tracklog items
+	 */
+	RArray<TTrackLogItem> iTrackLogItemArray;
+	
+	/**
+	 * Array of track log observers.
+	 */
+	RPointerArray<MTrackLogObserver> iObservers;
+	
+	TInt iMaxBufferSize;
+	TBool iRecording;
+
+	TPositionSatelliteInfo iSatelliteInfo;
+	
+	TFileName iGpxFileName;
+	TFileName iTmpFileName;
+	TItemId iTagId;
+	
+	CGpxConverterAO* iGpxConverter;
+	TBoundaries* iBoundaries;
+	TCoordinate* lastCoords;
+	
+	RFs iFs;
+	};
+
+#endif /*CTRACKLOG_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/inc/locationremappingao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,247 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Remap location data to location objects*
+*/
+
+
+#ifndef LOCATIONREMAPPINGAO_H_
+#define LOCATIONREMAPPINGAO_H_
+
+#include <e32base.h>
+#include <etel3rdparty.h>
+#include <LbsPosition.h> 
+#include <centralrepository.h>
+
+#include "locationdatatype.h"
+#include "mdesession.h"
+#include "rlocationtrail.h"
+#include "locationmanagerdebug.h"
+#include "locationtraildefs.h"
+
+
+class TRemapItem
+	{
+public: 
+	TRemapItem();
+public:
+	TItemId iObjectId;
+	TItemId iLocationId;
+	TItemId iRelationId;
+	TTime iTime;
+	};
+
+/**
+ * Class is handling remapping operations
+ */ 
+class CLocationRemappingAO : public CActive
+{
+
+public:
+
+	/**
+	 * Remapping Active object states
+	 */
+	enum TMappingState
+     {
+     EIdle = 0,
+     //EGatherObjects,
+     ERemapObjects,
+     ECommitObjects
+     };
+
+	/**
+	* Creates and constructs a new instance of CCameraTrailMonitorAO.
+	*
+	* @return A pointer to the new instance of CCameraTrailMonitorAO
+	*/
+	static CLocationRemappingAO* NewL();
+	
+	/**
+	* Destructor
+	*/
+	virtual ~CLocationRemappingAO();
+	
+	/**
+	* Stops remapping
+	*
+	* @return ETrue if success, EFalse if not
+	*/
+	void StopRemapping();
+	
+	void Append( TRemapItem aItem );
+	
+	void ResetQueue();
+	
+	TBool ItemsInQueue();
+
+	/**
+	 * Check items in remapping queue
+	 * 
+	 * @return ETrue if new location object must be created for remapping
+	 */ 
+	TBool CheckQueue();
+	
+	/**
+	 * Remap location objects between time limits.
+	 */ 
+	void StartRemappingObjects( const TLocationData& aLocationData );
+
+	/**
+	* Inherited from CActive. This method will be called on file server notifying.
+	*/
+	void RunL();
+	
+	/**
+	 * Initialise parameters
+	 * 
+	 * @param aMdEClient, Instance of CMdESession
+	 */ 
+	void InitialiseL(CMdESession* aMdEClient);
+	
+	/**
+	* Inherited from CActive. Handles a leave occurring in the request completion event handler RunL().
+	*
+	* @param aError  An error code.
+	* @return An error code.
+	*/
+	TInt RunError( TInt aError );
+	
+	/**
+	* Inherited from CActive.
+	*/
+	void DoCancel();
+	
+	/**
+	 * Update relations to new location object
+	 * 
+	 * @param aLocationId, locationId for relations 
+	 */ 
+	void UpdateRelationsL( TItemId aLocationId );
+private:
+
+	/**
+	* C++ constructor - not exported;
+	* implicitly called from NewL()
+	*/
+	CLocationRemappingAO();
+	
+	/**
+	* 2nd phase construction, called by NewL()
+	*/
+	void ConstructL();
+	
+	/**
+	 * Set AO next state
+	 */ 
+	void NextState(TMappingState aState);
+
+
+	/**
+	 * Remap objects data
+	 */ 
+	void RemapObjectsL();
+	
+	/**
+	 * Commit remapped objects to database
+	 */ 
+	void CommitObjectsL();
+	
+	/**
+	 * Read time limit value from Central Repository
+	 */ 
+	void ReadTimeFromCenRepL();
+
+private:
+
+	/**
+	 * Active object state
+	 */ 
+	TMappingState iState;
+	
+	/**
+	 * Is there come a new remapping request when 
+	 * AO have been executing earlier request.
+	 */ 
+	TBool iContinue;
+	
+	/**
+	 * Is start time earlier stamped.
+	 */ 
+	TBool iTimed;
+	
+	/**
+	 * Is location data requested from Location Mananger
+	 */ 
+	TBool iRequested;
+	
+	/**
+	 * Instance of MdeClient
+	 */ 
+	CMdESession* iMdEClient;
+
+	/**
+	 * Database definitions.
+	 */
+	CMdENamespaceDef* iNamespaceDef;
+    CMdEObjectDef* iObjImageDef;
+    CMdEObjectDef* iObjVideoDef;
+    CMdEPropertyDef* iPropDateDef;
+    CMdEPropertyDef* iPropModifiedDef;
+	CMdEObjectDef* iObjLocationDef;
+	CMdEPropertyDef* iPropLatDef;
+    CMdEPropertyDef* iPropLongDef;
+    CMdEPropertyDef* iPropAltDef;
+    CMdERelationDef* iContainsLocationRelDef;
+    
+    /**
+     * Object id's which location data will be remapped.
+     */ 
+    RArray<TItemId> iObjectIds; 
+    
+    /**
+     * Location objects which location data will remapped
+     * and it will committed back to Mde.
+     */ 
+    RPointerArray<CMdEObject> iObjects; 
+    
+    /**
+     * Array of Items to be remapped
+     */
+    RArray<TRemapItem> iRemapItems;
+    
+	/**
+	 * When location trail have started.
+	 * Time is compared to time when GPS fix is received.
+	 */ 
+	TTime iStartTime;
+	
+	/**
+	 * When GPS fix is received.
+	 */ 
+	TTime iEndTime;
+	
+	/**
+	 * Time limit for object data mapping (Default is 10min -> 600s)
+	 */ 
+	TTimeIntervalSeconds iTimeLimit;
+	
+	/**
+	 * Location data
+	 */
+	TLocationData iLocationData;
+	
+};
+
+
+#endif /*LOCATIONREMAPPINGAO_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/inc/locationtraildefs.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,121 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition file for Location Trail.
+*
+*/
+
+
+#ifndef __LOCATIONTRAILDEFS_H__
+#define __LOCATIONTRAILDEFS_H__
+
+// Update interval
+const TInt KUpdateInterval = 10000000;  // 10 seconds.
+// Update time out
+const TInt KUpdateTimeOut  = 20000000; // 20 seconds.
+// Max age
+const TInt KMaxAge         = 800000;   // 0.8 second
+
+const TInt KMaxTrailLength = 480000000; // 8 min.
+
+const TInt KIntervalSeconds = KUpdateInterval / 1000000; // 10 seconds
+
+const TInt KCurrentLocTimeoutCount = 48; // 48 * 10 sec -> 8 min timeout.
+
+const TInt KTrackLogBufSize = 10;
+
+const TInt KLocationTrailShutdownDelay = 180;
+
+const TInt KLocationDelta = 30;
+
+const TInt KRemappingTime = 600;
+
+const TInt KFirstInterval = 1000000; // 1 second
+
+//The name of the requestor
+_LIT( KRequestor,         "Location Trail" );
+
+// GPS tag ids.
+const TInt KGPSVersion      = 0x0000;
+const TInt KGPSLatitudeRef  = 0x0001;
+const TInt KGPSLatitude     = 0x0002;
+
+const TInt KGPSLongitudeRef = 0x0003;
+const TInt KGPSLongitude    = 0x0004;
+
+const TInt KGPSAltitudeRef  = 0x0005;
+const TInt KGPSAltitude     = 0x0006;
+
+const TInt KGPSTimeStamp    = 0x0007;
+const TInt KGPSDateStamp    = 0x001d;
+
+
+const TInt KMaxTagSize = 25;
+const TInt KMinutes    = 60;   // Minutes.
+const TInt KSeconds    = 6000; // Seconds * 100.
+const TReal KRounding  = 0.5;  
+
+_LIT8( KDateStampStr, "%04d:%02d:%02d" );  
+
+_LIT8( KLatitudeStr, "%04S%04S%04S%04S%04S%04S" );
+
+_LIT8( KNorthStr, "N" );  // North
+_LIT8( KSouthStr, "S" );  // South
+_LIT8( KEastStr,  "E" );  // East
+_LIT8( KWestStr,  "W" );  // West
+
+/**
+ * UID for using Central Repository 
+ * location managers related data.
+ */ 
+const TUid KRepositoryUid = { 0x200071BE };
+
+/**
+ * Key for reading interval value from 
+ * Central repository.
+ */ 
+const TUint32 KIntervalKey = 0x00000001;
+
+/**
+ * Key for reading trail length value from 
+ * Central repository.
+ */ 
+const TUint32 KTrailLengthKey = 0x00000002;
+
+/**
+ * Key for reading location trail timeout value from 
+ * Central repository.
+ */
+const TUint32 KLocationTrailShutdownTimer = 0x00000003;
+
+/**
+ * Key for reading tracklog buffer size from 
+ * Central repository.
+ */
+const TUint32 KTrackLogSizeKey = 0x00000004;
+
+/**
+ * Key for reading distance for using existing location object from 
+ * Central repository.
+ */
+const TUint32 KLocationDeltaKey = 0x00000005;
+
+/**
+ * Key for reading distance for using existing location object from 
+ * Central repository.
+ */
+const TUint32 KRemappingTimeKey = 0x00000006;
+
+#endif // __LOCATIONTRAILDEFS_H__
+
+// End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/src/cgpxconverterao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,549 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Active object for converting internal fileformat to GPX
+*
+*/
+
+#include <f32file.h>
+#include <s32file.h>
+#include <PathInfo.h>
+#include "cgpxconverterao.h"
+#include "locationmanagerdebug.h"
+
+// ---------------------------------------------------------------------------
+// Default constructor.
+// ---------------------------------------------------------------------------
+//
+CGpxConverterAO::CGpxConverterAO() : CActive( CActive::EPriorityStandard )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// Standard NewL for first phase construction.
+// ---------------------------------------------------------------------------
+//
+CGpxConverterAO* CGpxConverterAO::NewL()
+    {
+    LOG( "CGpxConverterAO::NewL" );
+    CGpxConverterAO* self = new (ELeave) CGpxConverterAO();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// 2nd phase construction.
+// ---------------------------------------------------------------------------
+//
+void CGpxConverterAO::ConstructL()
+    {
+    LOG( "CGpxConverterAO::ConstructL" );
+    CActiveScheduler::Add( this );
+	User::LeaveIfError( iFs.Connect() );
+	
+	iWriteBuf = HBufC8::NewL( KWriteBufSize );
+	iFormatBuf = HBufC::NewL( KWriteBufSize );
+	
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor.
+// ---------------------------------------------------------------------------
+//
+CGpxConverterAO::~CGpxConverterAO()
+    {
+    LOG( "CGpxConverterAO::~CGpxConverterAO" ); // DEBUG INFO
+    Cancel();
+    iFs.Close();
+    
+    iObservers.Reset();
+    
+    delete iWriteBuf;
+    delete iFormatBuf;
+    }
+
+// ---------------------------------------------------------------------------
+// From CActive.
+// ---------------------------------------------------------------------------
+//
+#ifdef _DEBUG
+TInt CGpxConverterAO::RunError( TInt aError )
+#else
+TInt CGpxConverterAO::RunError( TInt )
+#endif
+    {
+    LOG1( "CGpxConverterAO::RunError with error code: %d", aError );
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// From CActive. 
+// ---------------------------------------------------------------------------
+//
+void CGpxConverterAO::DoCancel()
+    {
+    LOG( "CGpxConverterAO::DoCancel" );
+    }
+
+/**
+ * Adds temp-file and possible pre-calculated boundaries
+ * into processing queue
+ */
+void CGpxConverterAO::AddToQueueL( const TDesC& aFileName, TBoundaries* aBoundaries )
+	{
+	LOG("CGpxConverterAO::AddToQueueL");
+	TFileName *filename = new (ELeave) TFileName(aFileName);
+	iFileQueue.Append(filename);
+	iBoundQueue.Append( aBoundaries );
+	
+	if ( iState == EIdle )
+		{
+		SetState( ENextFile );
+		}
+	}
+
+/**
+ * Set next state for RunL
+ */
+void CGpxConverterAO::SetState( TProcessingState aState )
+	{
+    LOG1( "CGpxConverterAO::SetState: %d", aState );
+	iState = aState;
+	if ( !IsActive() )
+		{
+		iStatus = KRequestPending;
+		SetActive();
+		TRequestStatus* ptrStatus = &iStatus;
+		User::RequestComplete( ptrStatus, KErrNone );
+		}
+	}
+
+/**
+ * RunL
+ */
+void CGpxConverterAO::RunL()
+	{
+	switch( iState )
+		{
+		case( EIdle ):
+			{
+			LOG("CGpxConverterAO::RunL - EIdle");
+			// nothing to do here
+			break;
+			}
+		case( ENextFile ):
+			{
+			LOG("CGpxConverterAO::RunL - ENextFile");
+			if( iFileQueue.Count() > 0 )
+				{
+				TInt err;
+				iFixLost = ETrue;
+				// get next temp-file from queue
+				iTempFile = *iFileQueue[0];
+				iBoundaries = iBoundQueue[0];
+				err = iReader.Open( iFs, iTempFile, EFileRead );				
+				// remove from queue				
+				iFileQueue.Remove( 0 );
+				iBoundQueue.Remove( 0 );
+				if ( err != KErrNone )
+					{
+					SetState( ENextFile );
+					}
+				TRAP( err, ReadTagIdL() );
+				
+				if ( !iBoundaries )
+					{
+					SetState( ECrashRecovery );
+					}
+				else
+					{
+					SetState( EStartFile );
+					}
+				}
+			else
+				{
+				// everything done
+				SetState( EIdle );
+				}
+			
+			break;
+			}
+		case( ECrashRecovery ):
+			{
+			LOG("CGpxConverterAO::RunL - ECrashRecovery");
+			TRAPD( readErr, iReader >> iTempItem );
+			if ( readErr == KErrNone )
+				{
+				CalculateBoundaries();
+				SetState( ECrashRecovery );
+				}
+			else
+				{
+				TInt err;
+				iReader.Close();
+				err = iReader.Open( iFs, iTempFile, EFileRead );
+				if( err != KErrNone )
+					{
+					SetState( ENextFile );
+					}
+				TRAP( err, ReadTagIdL() );
+				SetState( EStartFile );
+				}
+			
+			break;
+			}
+		case( EStartFile ):
+			{
+			LOG("CGpxConverterAO::RunL - EStartFile");
+			_LIT( KExtGPX, ".gpx" );
+			TParsePtrC parse( iTempFile );
+			
+			TRAPD(err, GetTrackLogPathL( iGpxPath ));
+			
+			iGpxFileName.Copy( parse.Name() );
+			iGpxFileName.Append( KExtGPX );
+			iGpxPath.Append( iGpxFileName );
+			
+			err = iFs.MkDirAll( iGpxPath );
+			if ( err != KErrAlreadyExists && err != KErrNone )
+				{
+				User::Leave( err );
+				}
+			
+			err = iGpxFile.Create(iFs, iGpxPath, EFileWrite);
+			if ( err != KErrNone )
+				{
+				err = iGpxFile.Open(iFs, iGpxPath, EFileWrite);
+				if ( err != KErrNone )
+					{
+					User::Leave( err );
+					}
+				}
+
+			WriteStartingTags();
+			iStartTime = 0;
+			iEndTime = 0;
+			
+			SetState( EProcessing );
+			break;
+			}
+		
+		case( EProcessing ):
+			{
+			LOG("CGpxConverterAO::RunL - EProcessing");
+			
+			TRAPD( readError, iReader >> iTempItem );
+			if ( readError == KErrNone )
+				{
+				if ( iStartTime == 0 )
+					{
+					iStartTime = iTempItem.iTimeStamp;
+					}
+				iEndTime = iTempItem.iTimeStamp;
+				WriteItemToFile();				
+				SetState( EProcessing );
+				}
+			else
+				{
+				// no items left in file
+				iReader.Close();
+				SetState( ECloseFile );
+				}
+			break;
+			}
+		case( ECloseFile ):
+			{
+			LOG("CGpxConverterAO::RunL - ECloseFile");
+			WriteClosingTags();
+			iGpxFile.Close();
+
+			TReal distance( 0 );
+			if( iBoundaries )
+				{
+				distance = iBoundaries->distance;
+				}
+			
+			TInt count = iObservers.Count();
+			for( TInt i = 0; i < count; i++ )
+				{
+				iObservers[i]->GpxFileCreated( iGpxPath, iTagId, distance, iStartTime, iEndTime );
+				}
+			
+			delete iBoundaries;
+			iFs.Delete( iTempFile );
+			SetState( ENextFile );
+			break;
+			}
+		}
+	}
+
+/**
+ * Read Tag Id from temp-file
+ */
+void CGpxConverterAO::ReadTagIdL()
+	{
+	LOG("CGpxConverterAO::ReadTagIdL");
+	TUint32 low( 0 );
+	TUint32 high( 0 );	
+
+	low = iReader.ReadUint32L();
+	high = iReader.ReadUint32L();
+
+	iTagId = MAKE_TINT64( high, low );
+	}
+
+/**
+ * Calculate min and max coordinates for tracklog
+ */
+void CGpxConverterAO::CalculateBoundaries()
+	{
+	LOG("CGpxConverterAO::CalculateBoundaries start");
+	const TInt KMaxLat = 90;
+	const TInt KMinLat = -90;
+	const TInt KMaxLon = 180;
+	const TInt KMinLon = -180;
+	if ( !iBoundaries )
+		{
+		iBoundaries = new TBoundaries;	
+		iBoundaries->minLatitude = KMaxLat;
+		iBoundaries->maxLatitude = KMinLat;
+		iBoundaries->minLongitude = KMaxLon;
+		iBoundaries->maxLongitude = KMinLon;
+		iBoundaries->distance = 0;
+		}
+	
+	if( !Math::IsNaN( iTempItem.iLatitude ) && !Math::IsNaN( iTempItem.iLongitude ))
+		{
+		TReal32 distance;
+		if ( !iLastCoords ) 
+			{
+			iLastCoords = new TCoordinate( iTempItem.iLatitude, iTempItem.iLongitude );
+			}
+		else
+			{
+			TCoordinate tempCoord( iTempItem.iLatitude, iTempItem.iLongitude );
+			TLocality newCoords( tempCoord, iTempItem.iHdop );
+			TInt err = newCoords.Distance(*iLastCoords, distance);
+			if ( err == KErrNone )
+				{
+				delete iLastCoords;
+				iLastCoords = new TCoordinate( tempCoord );
+				iBoundaries->distance += distance;
+				}
+			}		
+		iBoundaries->maxLatitude = Max( iBoundaries->maxLatitude, iTempItem.iLatitude );
+		iBoundaries->minLatitude = Min( iBoundaries->minLatitude, iTempItem.iLatitude );
+		iBoundaries->maxLongitude = Max( iBoundaries->maxLongitude, iTempItem.iLongitude );
+		iBoundaries->minLongitude = Min( iBoundaries->minLongitude, iTempItem.iLongitude );
+		}
+	LOG("CGpxConverterAO::CalculateBoundaries end");
+	}
+
+/**
+ * Writes header tags for GPX file
+ */
+void CGpxConverterAO::WriteStartingTags()
+	{
+	TPtr8 writePtr = iWriteBuf->Des();
+	TPtr formatter = iFormatBuf->Des();
+	
+	// write starting tags
+	writePtr.Copy( KTagXml );
+	writePtr.Append( KTagGpxStart );
+	iGpxFile.Write( writePtr );
+	
+	writePtr.Copy( KTagMetaStart );
+	formatter.Format( KTagName, &iGpxFileName );
+	writePtr.Append( formatter );
+	iGpxFile.Write( writePtr );
+	
+	TTime timeStamp( 0 );
+	timeStamp.UniversalTime();
+	TDateTime datetime = timeStamp.DateTime();
+	
+	formatter.Format( KTagTimeStamp, datetime.Year(), datetime.Month() + 1, datetime.Day() + 1,
+			datetime.Hour(), datetime.Minute(), datetime.Second() );
+	writePtr.Copy( formatter );
+	iGpxFile.Write( writePtr );
+	
+	if ( iBoundaries )
+		{
+		formatter.Format( KTagBounds, iBoundaries->minLatitude, iBoundaries->minLongitude, 
+				iBoundaries->maxLatitude, iBoundaries->maxLongitude );
+		writePtr.Copy( formatter );
+		iGpxFile.Write( writePtr );
+		}
+	writePtr.Copy( KTagMetaEnd );
+	iGpxFile.Write( writePtr );
+	
+	writePtr.Copy( KTagTrackStart );
+	iGpxFile.Write( writePtr );
+	}
+
+/**
+ * Writes single trackpoint to GPX file
+ */
+void CGpxConverterAO::WriteItemToFile()
+	{
+	TTime timeStamp;
+	
+	TPtr8 writePtr = iWriteBuf->Des();
+	TPtr formatter = iFormatBuf->Des();
+	
+	if ( Math::IsNaN(iTempItem.iLatitude) || Math::IsNaN(iTempItem.iLongitude) )
+		{
+		if ( !iFixLost )
+			{
+			writePtr.Copy( KTagSegmentEnd );
+			iGpxFile.Write( writePtr );
+			iFixLost = ETrue;
+			}
+		}
+	else
+		{
+		if ( iFixLost )
+			{
+			writePtr.Copy( KTagSegmentStart );
+			iGpxFile.Write( writePtr );
+			iFixLost = EFalse;
+			}
+		
+		// write single track point
+		// coordinates
+		formatter.Format( KTagTrkPointStart, iTempItem.iLatitude, iTempItem.iLongitude );
+		writePtr.Copy( formatter );
+		iGpxFile.Write( writePtr );
+		// elevation
+		if ( !Math::IsNaN( iTempItem.iAltitude ))
+			{
+			formatter.Format( KTagElevation, iTempItem.iAltitude );
+			writePtr.Copy( formatter );
+			iGpxFile.Write( writePtr );
+			}
+		// course
+		if ( !Math::IsNaN( iTempItem.iCourse ))
+			{
+			formatter.Format( KTagCourse, iTempItem.iCourse );
+			writePtr.Copy( formatter );
+			iGpxFile.Write( writePtr );
+			}
+
+		timeStamp = iTempItem.iTimeStamp;
+		TDateTime datetime = timeStamp.DateTime();
+		
+		formatter.Format( KTagTimeStamp, datetime.Year(), datetime.Month() + 1, datetime.Day() + 1,
+				datetime.Hour(), datetime.Minute(), datetime.Second() );
+		writePtr.Copy( formatter );
+		iGpxFile.Write( writePtr );
+		
+		if ( !Math::IsNaN( iTempItem.iAltitude ))
+			{
+			writePtr.Copy( KTagFix3D );
+			iGpxFile.Write( writePtr );
+			}
+		else
+			{
+			writePtr.Copy( KTagFix2D );
+			iGpxFile.Write( writePtr );
+			}
+
+		// number of satellites
+		formatter.Format( KTagSatellites, iTempItem.iNumSatellites );
+		writePtr.Copy( formatter );
+		iGpxFile.Write( writePtr );
+
+		// accuracy (hdop, vdop)
+		if ( !Math::IsNaN( iTempItem.iHdop ))
+			{
+			formatter.Format( KTagHdop, iTempItem.iHdop );
+			writePtr.Copy( formatter );
+			iGpxFile.Write( writePtr );
+			}
+		if ( !Math::IsNaN( iTempItem.iVdop ))
+			{
+			formatter.Format( KTagVdop, iTempItem.iVdop );
+			writePtr.Copy( formatter );
+			iGpxFile.Write( writePtr );
+			}
+	
+		// end track point
+		writePtr.Copy( KTagTrkPointEnd );
+		iGpxFile.Write( writePtr );
+		}
+	
+	}
+
+/**
+ * Close GPX file 
+ */
+void CGpxConverterAO::WriteClosingTags()
+	{
+	TPtr8 writePtr = iWriteBuf->Des();
+	
+	// end segment
+	if ( !iFixLost )
+		{
+		writePtr.Copy( KTagSegmentEnd );	
+		iGpxFile.Write( writePtr );
+		}
+
+	// closing tags
+	writePtr.Copy( KTagTrackEnd );
+	writePtr.Append( KTagGpxEnd );
+
+	iGpxFile.Write( writePtr );
+	}
+
+/**
+ * Resolve where to save tracklog file
+ */
+void CGpxConverterAO::GetTrackLogPathL( TDes& aFileName )
+	{
+	LOG("CGpxConverterAO::GetTrackLogPathL start");
+	_LIT( KPathTrackLog, "TrackLog\\" );
+	
+	TFileName* path = new (ELeave) TFileName();
+	CleanupStack::PushL( path );
+	
+	// check for memory card
+	*path = PathInfo::MemoryCardRootPath();
+	TLex lex( *path );
+	TInt drive;
+	iFs.CharToDrive( lex.Get(), drive );
+	TVolumeInfo* volumeinfo = new (ELeave) TVolumeInfo;
+	
+	TInt err = iFs.Volume( *volumeinfo, drive );
+	if( err != KErrNone )
+		{
+		LOG("CGpxConverterAO::GetTrackLogPathL - MMC not available");
+		*path = PathInfo::PhoneMemoryRootPath();
+		}
+	delete volumeinfo;
+	
+	path->Append( KPathTrackLog );
+	
+	aFileName.Copy( *path );
+	CleanupStack::PopAndDestroy( path );
+	LOG("CGpxConverterAO::GetTrackLogPathL end");
+	}
+
+/**
+ * Adds observer for GPX file creation notifications
+ */
+void CGpxConverterAO::AddObserver( MGpxConversionObserver* aObserver )
+	{
+	iObservers.Append( aObserver );
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/src/clocationrecord.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1120 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A class for recording and storing locations.
+*
+*/
+
+#include <e32cmn.h> 
+#include <LbsErrors.h>
+#include <LbsSatellite.h>
+
+#include "rlocationtrail.h"
+#include "clocationrecord.h"
+#include "cnetworkinfo.h"
+#include "locationmanagerdebug.h"
+#include "locationtraildefs.h"
+#include "locationtrailpskeys.h"
+#include "mdeconstants.h"
+#include <centralrepository.h>
+
+
+using namespace MdeConstants;
+
+// --------------------------------------------------------------------------
+// CLocationRecord::NewL
+// --------------------------------------------------------------------------
+//
+EXPORT_C CLocationRecord* CLocationRecord::NewL()
+    {
+    CLocationRecord* self = new (ELeave) CLocationRecord();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+        
+// --------------------------------------------------------------------------
+// CLocationRecord::CLocationRecord
+// --------------------------------------------------------------------------
+//  
+CLocationRecord::CLocationRecord()
+    : iNetworkInfoTimer( NULL ),
+    iState( RLocationTrail::ETrailStopped ),
+    iTrailCaptureSetting( RLocationTrail::ECaptureAll ),
+    iLocationCounter( 0 ),
+    iRequestCurrentLoc( EFalse ),
+    iTrailStarted( EFalse ),
+    iLastGPSFixState( EFalse ),
+    iLastLocationId( 0 )
+    {
+    iMaxTrailSize = KMaxTrailLength / KUpdateInterval;
+    }
+
+// --------------------------------------------------------------------------
+// CLocationRecord::ConstructL
+// --------------------------------------------------------------------------
+//    
+void CLocationRecord::ConstructL()
+    {
+    const TInt KMillion = 1000000;
+    TInt err = iProperty.Define( KPSUidLocationTrail, KLocationTrailState, RProperty::EInt );
+    if ( err != KErrNone && err != KErrAlreadyExists )
+        {
+        User::Leave( err );
+        }
+    User::LeaveIfError( iProperty.Set( KPSUidLocationTrail,
+        KLocationTrailState, (TInt) RLocationTrail::ETrailStopped ) ); 
+
+    iNetworkInfo = CNetworkInfo::NewL( this );
+    iPositionInfo = CPositionInfo::NewL( this );
+	iRemapper = CLocationRemappingAO::NewL();
+    iNetworkInfoTimer = CPeriodic::NewL( CActive::EPriorityStandard );
+    
+    TInt interval( 0 );
+    TRAP(err, ReadCenRepValueL(KIntervalKey, interval));
+    LOG1("CLocationManagerServer::ConstructL, cenrep interval value:%d", interval);
+    
+    if (interval == 0)
+    	{
+        LOG1("CLocationManagerServer::ConstructL, cenrep interval err:%d", err);
+    	iInterval = KUpdateInterval;
+    	}
+    else 
+    	{
+    	iInterval = interval * KMillion;
+    	}
+    
+    TInt trailLength( 0 );
+    TRAP(err, ReadCenRepValueL(KTrailLengthKey, trailLength));
+    LOG1("CLocationManagerServer::ConstructL, cenrep trail length value:%d", trailLength);
+    
+    if ( err != KErrNone )
+    	{
+        LOG1("CLocationManagerServer::ConstructL, cenrep trail length err:%d", err);
+    	iBufferSize = KMaxTrailLength / iInterval;
+    	}
+    else
+    	{
+    	iBufferSize = trailLength * KMillion / iInterval;
+    	}
+
+    TRAP(err, ReadCenRepValueL(KLocationDeltaKey, iLocationDelta));
+    LOG1("CLocationManagerServer::ConstructL, location delta value:%d", iLocationDelta);
+    
+    if (iLocationDelta == 0)
+    	{
+        LOG1("CLocationManagerServer::ConstructL, location delta err:%d", err);
+        iLocationDelta = KLocationDelta;
+    	}
+
+    }
+    
+// --------------------------------------------------------------------------
+// CLocationRecord::~CLocationRecord
+// --------------------------------------------------------------------------
+//    
+CLocationRecord::~CLocationRecord()
+    {
+    Stop();
+    iProperty.Delete( KPSUidLocationTrail, KLocationTrailState );
+    iProperty.Close();
+    iTrail.Close();
+    
+    delete iNetworkInfo;
+    delete iPositionInfo;
+    delete iNetworkInfoTimer;
+	if (iRemapper)
+		{
+		iRemapper->StopRemapping();
+		delete iRemapper;
+		}
+    }
+
+// --------------------------------------------------------------------------
+// CLocationRecord::CurrentState
+// --------------------------------------------------------------------------
+//
+EXPORT_C void CLocationRecord::LocationTrailState( TLocTrailState& aState )
+    {
+    aState = iState;
+    }
+
+// --------------------------------------------------------------------------
+// CLocationRecord::StartL
+// --------------------------------------------------------------------------
+//
+EXPORT_C void CLocationRecord::StartL( RLocationTrail::TTrailCaptureSetting aCaptureSetting )
+    {
+    LOG( "CLocationRecord::StartL(), begin" );
+    iTrailCaptureSetting = aCaptureSetting;
+    if ( aCaptureSetting == RLocationTrail::ECaptureAll && !iPositionInfo->IsActive() )
+        {
+        iPositionInfo->StartL( aCaptureSetting, iInterval );
+        }
+    else if ( aCaptureSetting == RLocationTrail::ECaptureNetworkInfo )
+    	{
+    	// Update and store network info in location trail immediately.
+    	// Timer will trigger the update again later.
+    	UpdateNetworkInfo( this );
+    	
+        if ( iNetworkInfoTimer && iNetworkInfoTimer->IsActive() )
+        	{
+        	iNetworkInfoTimer->Cancel();
+        	}
+        	
+        StartTimerL();
+    	}
+    
+    iLastLocationId = 0;
+    
+    SetCurrentState( RLocationTrail::ETrailStarting );
+    
+    iTrailStarted = ETrue;
+    LOG( "CLocationRecord::StartL(), end" );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationRecord::Stop
+// --------------------------------------------------------------------------
+//
+EXPORT_C void CLocationRecord::Stop()
+    {
+    LOG( "CLocationRecord::StopL(), begin" );
+    iPositionInfo->Stop();
+    iTrailStarted = EFalse;
+    
+    if ( iNetworkInfoTimer && iNetworkInfoTimer->IsActive() )
+    	{
+    	iNetworkInfoTimer->Cancel();
+    	}
+
+    if ( iRemapper )
+    	{
+    	iRemapper->ResetQueue();
+    	}
+    SetCurrentState( RLocationTrail::ETrailStopped );
+    LOG( "CLocationRecord::StopL(), end" );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationRecord::SetStateToStop
+// --------------------------------------------------------------------------
+//
+EXPORT_C void CLocationRecord::SetStateToStopping()
+	{
+	SetCurrentState( RLocationTrail::ETrailStopping );
+	}
+
+// --------------------------------------------------------------------------
+// CLocationRecord::GetLocationByTimeL
+// --------------------------------------------------------------------------
+//
+EXPORT_C void CLocationRecord::GetLocationByTimeL( const TTime aTime, 
+												   TLocationData& aLocationData,
+                                                   TLocTrailState& aState )
+    {
+    LOG( "CLocationRecord::GetLocationByTimeL(), begin" );
+    TInt posFound( EFalse );
+
+#ifdef _DEBUG
+    _LIT( KDateTimeFormat, "%Y/%M/%D %H:%T:%S" );
+    const TInt DateTimeStrMaxLength = 20;
+    LOG1( "CLocationRecord::GetLocationByTimeL - aTime: %Ld", aTime.Int64() );
+    TBuf<DateTimeStrMaxLength> str1;
+    aTime.FormatL( str1, KDateTimeFormat );
+    LOG1( "CLocationRecord::GetLocationByTimeL - aTime: %S", &str1 );
+#endif
+
+    TTimeIntervalSeconds interval;
+    TTimeIntervalSeconds nextInterval;
+    for ( TInt i(iTrail.Count()-1) ; i >= 0 && !posFound ; i-- )
+        {
+        TInt err = iTrail[i].iTimeStamp.SecondsFrom( aTime, interval );
+        
+        TInt timeDiff = Abs( interval.Int() );
+
+#ifdef _DEBUG
+        LOG1( "CLocationRecord::GetLocationByTimeL - Trail timestamp: %Ld", iTrail[i].iTimeStamp.Int64() );
+        TBuf<DateTimeStrMaxLength> str;
+        iTrail[i].iTimeStamp.FormatL( str, KDateTimeFormat );
+        LOG1( "CLocationRecord::GetLocationByTimeL - Trail timestamp: %S", &str );
+        LOG1( "CLocationRecord::GetLocationByTimeL - timeDiff: %d", timeDiff );
+#endif
+
+        if ( err == KErrNone && timeDiff <= KIntervalSeconds )
+            {
+            // The nearest time is in iTrail[i] or in iTrail[i-1].
+            if ( i > 0 )
+                {
+                iTrail[i-1].iTimeStamp.SecondsFrom( aTime, nextInterval );
+                
+                TInt nextDiff = Abs( nextInterval.Int() );
+                    
+                if ( nextDiff < timeDiff )
+                    {
+                    aLocationData = iTrail[i-1].iLocationData;
+                    aState = iTrail[i-1].iTrailState;
+                    }
+                else
+                    {
+                    aLocationData = iTrail[i].iLocationData;
+                    aState = iTrail[i].iTrailState;
+                    }                    
+                }            
+            else
+                {
+                aLocationData = iTrail[i].iLocationData;
+                aState = iTrail[i].iTrailState;
+                }
+            posFound = ETrue;
+            }
+        }
+    if ( !posFound )
+        {
+        User::Leave( KErrNotFound );
+        }
+    LOG( "CLocationRecord::GetLocationByTimeL(), end" );
+    }
+    
+// --------------------------------------------------------------------------
+// CLocationRecord::RequestLocationL
+// --------------------------------------------------------------------------
+//
+EXPORT_C void CLocationRecord::RequestLocationL()
+    {
+    iRequestCurrentLoc = ETrue;
+    if ( iTrailCaptureSetting != RLocationTrail::ECaptureNetworkInfo &&
+    	!iPositionInfo->IsActive() )
+        {
+        iPositionInfo->StartL( iTrailCaptureSetting, iInterval );
+        }
+    else if ( iTrailCaptureSetting == RLocationTrail::ECaptureNetworkInfo )
+    	{
+    	TPositionSatelliteInfo posInfo;
+    	CTelephony::TNetworkInfoV1 network = CTelephony::TNetworkInfoV1();
+    	GetNetworkInfo( network );
+       	iObserver->CurrentLocation( posInfo, network, KErrNone );
+        iRequestCurrentLoc = EFalse;
+    	}
+    }
+
+// --------------------------------------------------------------------------
+// CLocationRecord::CancelLocationRequest
+// --------------------------------------------------------------------------
+//    
+EXPORT_C void CLocationRecord::CancelLocationRequest()
+    {
+    iRequestCurrentLoc = EFalse;
+    if ( !iTrailStarted )
+        {
+        iPositionInfo->Stop();
+        }
+    }
+        
+        
+// --------------------------------------------------------------------------
+// CLocationRecord::GetNetworkInfo
+// --------------------------------------------------------------------------
+//
+EXPORT_C void CLocationRecord::GetNetworkInfo( CTelephony::TNetworkInfoV1& aNetworkInfo )
+    {
+    LOG("CLocationRecord::GetNetworkInfo");
+
+    aNetworkInfo = iNetwork;
+    }
+    
+// --------------------------------------------------------------------------
+// CLocationRecord::SetObserver
+// --------------------------------------------------------------------------
+//
+EXPORT_C void CLocationRecord::SetObserver( MLocationTrailObserver* aObserver)
+    {
+    iObserver = aObserver;
+    }
+
+// --------------------------------------------------------------------------
+// CLocationRecord::SetAddObserver
+// --------------------------------------------------------------------------
+//
+EXPORT_C void CLocationRecord::SetAddObserver( MLocationAddObserver* aObserver)
+    {
+    iAddObserver = aObserver;
+    }
+
+// --------------------------------------------------------------------------
+// From MNetworkInfoObserver.
+// CLocationRecord::Position
+// --------------------------------------------------------------------------
+//    
+void CLocationRecord::Position( const TPositionInfo& aPositionInfo,
+                                const TInt aError  )
+    {    
+    const TPositionSatelliteInfo& positionSatelliteInfo = 
+    	static_cast<const TPositionSatelliteInfo&>(aPositionInfo);
+
+    if ( iRequestCurrentLoc )
+        {
+        HandleLocationRequest( positionSatelliteInfo, aError );
+        }
+    if( iState == RLocationTrail::ETrailStopped )
+    	{
+    	LOG("CLocationRecord::Position - trail stopped");
+    	return;
+    	}
+    
+    if ( !iTrailStarted )
+        {
+        iPositionInfo->NextPosition();
+        return;
+        }
+    switch ( aError )
+        {
+        case KPositionPartialUpdate: // fall through
+        case KPositionQualityLoss: 
+            {
+            // Location is stored, even if it may not be valid.
+            StoreLocation( positionSatelliteInfo ); 
+            LOG("CLocationRecord::Position - partial update");
+            if ( iState != RLocationTrail::EWaitingGPSData && 
+            	 iState != RLocationTrail::ETrailStopping ) 
+                {
+                SetCurrentState( RLocationTrail::EWaitingGPSData );
+            	LOG("CLocationRecord::Position trail waiting for gps");
+                }
+            break;
+            }
+        case KErrNone:
+            {
+            StoreLocation( positionSatelliteInfo );
+            LOG("CLocationRecord::Position - good GPS coordinates");
+            if ( iState != RLocationTrail::ETrailStarted ) 
+                {
+                if ( iRemapper )
+                	{
+                	LOG("CLocationRecord::Position start remapping");
+                	iLastLocationId = 0;
+                	TBool createLocation = iRemapper->CheckQueue();
+                	if( createLocation )
+                		{
+                		TRAP_IGNORE(	
+                		TItemId locationId = DoCreateLocationL( iNewItem.iLocationData );
+                		iRemapper->UpdateRelationsL( locationId );
+                		)
+                		}
+               		iRemapper->StartRemappingObjects( iNewItem.iLocationData );
+                	}
+                if ( iState != RLocationTrail::ETrailStopping )
+                	{
+                    SetCurrentState( RLocationTrail::ETrailStarted );
+                	LOG("CLocationRecord::Position trail started");
+                	}
+                }
+            break;
+            }
+        default:
+            {
+            StoreLocation( positionSatelliteInfo );
+            LOG1("CLocationRecord::Position - searching GPS, aError %d", aError );
+            if ( iState != RLocationTrail::ESearchingGPS &&
+               	 iState != RLocationTrail::ETrailStopping ) 
+                {
+                SetCurrentState( RLocationTrail::ESearchingGPS );
+            	LOG("CLocationRecord::Position trail searching gps");
+                }
+            break;
+            }      
+        }
+    TBool fixState = CheckGPSFix( positionSatelliteInfo );
+    LOG1( "CLocationRecord::Position fixState %d", fixState );
+    LOG1( "CLocationRecord::Position iLastGPSFixState %d", iLastGPSFixState );
+    
+    if ( iObserver && iLastGPSFixState != fixState )
+    	{
+    	LOG("CLocationRecord::Position quality changed");
+    	iObserver->GPSSignalQualityChanged( positionSatelliteInfo );
+    	}
+    
+   	iLastGPSFixState = fixState;
+    
+    iPositionInfo->NextPosition();
+    }
+
+TBool CLocationRecord::CheckGPSFix( const TPositionSatelliteInfo& aSatelliteInfo )
+	{
+	TPosition position;
+	aSatelliteInfo.GetPosition( position );
+	LOG1( "CLocationRecord::CheckGPSFix latitude %f", position.Latitude() );
+	LOG1( "CLocationRecord::CheckGPSFix longitude %f", position.Longitude() );
+	TBool ret = ( Math::IsNaN(position.Latitude()) || Math::IsNaN(position.Longitude()) ) 
+		? EFalse : ETrue;
+   	return ret;
+	}
+    
+// --------------------------------------------------------------------------
+// From MPositionerObserver.
+// CLocationRecord::NetworkInfo
+// --------------------------------------------------------------------------
+//    
+void CLocationRecord::NetworkInfo( const CTelephony::TNetworkInfoV1 &aNetworkInfo, 
+		const TInt aError )
+    {
+    LOG("CLocationRecord::NetworkInfo");
+    if ( aError == KErrNone )
+        {
+        LOG("CLocationRecord::NetworkInfo - KErrNone");
+        iNetwork = aNetworkInfo;
+        if (iNetwork.iAccess == CTelephony::ENetworkAccessUtran)
+        	{
+        	iNetwork.iLocationAreaCode = 0;
+        	}
+        if ( iState == RLocationTrail::ETrailStarting && iTrailStarted )
+        	{
+        	SetCurrentState( RLocationTrail::ETrailStarted );
+        	}
+        }
+    else
+        {
+        LOG1("CLocationRecord::NetworkInfo - %d", aError );
+        iNetwork = CTelephony::TNetworkInfoV1();
+        iNetwork.iAreaKnown = EFalse;
+        iNetwork.iAccess = CTelephony::ENetworkAccessUnknown;
+        iNetwork.iCellId = 0;
+        iNetwork.iLocationAreaCode = 0;
+        iNetwork.iCountryCode.Zero();
+        iNetwork.iNetworkId.Zero();
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CLocationRecord::StoreLocationL
+// --------------------------------------------------------------------------
+//    
+void CLocationRecord::StoreLocation( const TPositionSatelliteInfo& aSatelliteInfo )
+    {
+    aSatelliteInfo.GetPosition( iNewItem.iLocationData.iPosition );
+    aSatelliteInfo.GetCourse( iNewItem.iLocationData.iCourse );
+    iNewItem.iLocationData.iSatellites = aSatelliteInfo.NumSatellitesUsed();
+    iNewItem.iLocationData.iQuality = aSatelliteInfo.HorizontalDoP();
+    
+    // Network info
+    GetNetworkInfo( iNewItem.iLocationData.iNetworkInfo );
+    // Get Universal time
+    iNewItem.iTimeStamp.UniversalTime();
+    iNewItem.iTrailState = iState;
+    
+    TInt error = iTrail.Append( iNewItem );
+    
+    // If appending an item to the trail fails because of OOM, remove oldest trail items
+    // until the new item fits or there's only one item left in the trail.
+    while ( error == KErrNoMemory && iTrail.Count() > 1 )
+		{
+		LOG("CLocationRecord::StoreLocation - Out of memory! Shortening trail!");
+		iTrail.Remove( 0 );
+		error = iTrail.Append( iNewItem );
+		}
+    
+    if ( iTrail.Count() > iMaxTrailSize )
+        {
+        iTrail.Remove( 0 );
+        }
+    
+    if( iAddObserver )
+    	{
+    	iAddObserver->LocationAdded( iNewItem, aSatelliteInfo );
+    	}
+    }
+    
+// --------------------------------------------------------------------------
+// CLocationRecord::SetCurrentState
+// --------------------------------------------------------------------------
+//        
+void CLocationRecord::SetCurrentState( TLocTrailState aState )    
+    {
+    LOG1( "CLocationRecord::SetCurrentState(), begin, state:%d", aState );
+    iState = aState;
+    iProperty.Set( KPSUidLocationTrail, KLocationTrailState, (TInt) aState );
+    if ( iObserver )
+        {
+        iObserver->LocationTrailStateChange();
+        }
+    LOG( "CLocationRecord::SetCurrentState(), end" );
+    }
+    
+// --------------------------------------------------------------------------
+// CLocationRecord::HandleLocationRequest
+// --------------------------------------------------------------------------
+//
+void CLocationRecord::HandleLocationRequest( const TPositionSatelliteInfo& aSatelliteInfo, 
+                                             const TInt aError )    
+    {
+	CTelephony::TNetworkInfoV1 network = CTelephony::TNetworkInfoV1();
+    if ( aError == KErrNone )
+        {
+       	GetNetworkInfo( network );
+        iObserver->CurrentLocation( aSatelliteInfo, network, aError );
+        iRequestCurrentLoc = EFalse;
+        if ( !iTrailStarted )
+            {
+            iPositionInfo->Stop();
+            }
+        }
+    else
+        {
+        iLocationCounter++;
+        if ( iLocationCounter > KCurrentLocTimeoutCount )
+            {
+            iObserver->CurrentLocation( aSatelliteInfo, network, KErrTimedOut );
+            iRequestCurrentLoc = EFalse;
+            iLocationCounter = 0;
+            if ( !iTrailStarted )
+                {
+                iPositionInfo->Stop();
+                }
+            }       
+        }    
+    }
+
+TInt CLocationRecord::UpdateNetworkInfo( TAny* aAny )
+	{
+	TPositionSatelliteInfo nullPositionInfo;
+	CLocationRecord* self = STATIC_CAST( CLocationRecord*, aAny );
+	self->StoreLocation( nullPositionInfo );
+	return KErrNone;
+	}
+
+
+EXPORT_C void CLocationRecord::CreateLocationObjectL( const TLocationData& aLocationData,
+		const TUint& aObjectId )
+	{
+	TItemId locationId = DoCreateLocationL( aLocationData );
+	CreateRelationL( aObjectId, locationId );
+	}
+
+
+EXPORT_C void CLocationRecord::LocationSnapshotL( const TUint& aObjectId )
+	{
+	LOG("CLocationRecord::LocationSnapshotL");
+	
+	TBool previousMatch = EFalse;
+	CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+
+	// get locationdata from trail with object time
+	TTime timestamp = GetMdeObjectTimeL( aObjectId );
+	TLocationData locationData;
+	TLocTrailState state;
+	GetLocationByTimeL( timestamp, locationData, state );
+	
+	iObjectId = aObjectId;
+	iLocationData = locationData;
+
+	// capture only network data
+	if ( iTrailCaptureSetting == RLocationTrail::ECaptureNetworkInfo )
+		{
+		CTelephony::TNetworkInfoV1* net = &locationData.iNetworkInfo;
+		
+		if ( net->iCellId == 0 && 
+				net->iLocationAreaCode == 0 &&
+				net->iCountryCode.Length() == 0 &&
+				net->iNetworkId.Length() == 0 )
+			{
+			// nothing to do
+			LOG("CLocationRecord::LocationSnapshotL - no network info available");
+			}
+		else if ( iLastLocationId != 0 )
+			{
+			CTelephony::TNetworkInfoV1* lastnet = &iLastLocation.iNetworkInfo;
+			
+			// compare to previous network info
+			TItemId locationId = iLastLocationId;
+			if ( lastnet->iCellId != net->iCellId ||
+					lastnet->iLocationAreaCode != net->iLocationAreaCode ||
+					lastnet->iCountryCode != net->iCountryCode ||
+					lastnet->iNetworkId != net->iNetworkId )
+				{
+				LOG("CLocationRecord::LocationSnapshotL - network info changed");
+				locationId = DoCreateLocationL( locationData );
+				}
+			CreateRelationL( aObjectId, locationId );
+			}
+		else 
+			{
+			// new location
+			TItemId locationId = DoCreateLocationL( locationData );
+			CreateRelationL( aObjectId, locationId );
+			}
+		return;
+		}
+	
+	// coordinates empty (will be remapped)
+	if ( Math::IsNaN( locationData.iPosition.Latitude() ) && 
+			Math::IsNaN( locationData.iPosition.Longitude() ))
+		{
+		TRemapItem remapItem;
+		remapItem.iObjectId = aObjectId;
+		remapItem.iTime = timestamp;
+		
+		CTelephony::TNetworkInfoV1* net = &locationData.iNetworkInfo;
+
+		// no network info (offline mode + no GPS fix)
+		if ( net->iCellId == 0 && 
+				net->iLocationAreaCode == 0 &&
+				net->iCountryCode.Length() == 0 &&
+				net->iNetworkId.Length() == 0 )
+			{
+			LOG("CLocationRecord::LocationSnapshotL - empty remap item created");
+			}
+		// check match for last created locationobject
+		else if ( iLastLocationId != 0 )
+			{
+			TItemId locationId;
+			CTelephony::TNetworkInfoV1* lastnet = &iLastLocation.iNetworkInfo;
+
+			// networkinfo changed from last location
+			if ( lastnet->iCellId != net->iCellId ||
+					lastnet->iLocationAreaCode != net->iLocationAreaCode ||
+					lastnet->iCountryCode != net->iCountryCode ||
+					lastnet->iNetworkId != net->iNetworkId )
+				{
+				LOG("CLocationRecord::LocationSnapshotL - remap with new network info");
+				locationId = DoCreateLocationL( locationData );
+				}		
+			else
+				{
+				LOG("CLocationRecord::LocationSnapshotL - remap with previous network info");
+				locationId = iLastLocationId;
+				}
+			TItemId relationId = CreateRelationL( aObjectId, locationId );
+			remapItem.iLocationId = locationId;
+			remapItem.iRelationId = relationId;
+			}
+		else
+			{
+			// new location with only network data
+			TItemId locationId = DoCreateLocationL( locationData );
+			TItemId relationId = CreateRelationL( aObjectId, locationId );
+			remapItem.iLocationId = locationId;
+			remapItem.iRelationId = relationId;
+			}
+		iRemapper->Append( remapItem );
+		return;
+		}
+		
+	// valid coordinates found
+	if ( iLastLocationId != 0 )
+		{
+		CTelephony::TNetworkInfoV1* net = &locationData.iNetworkInfo;
+		CTelephony::TNetworkInfoV1* lastnet = &iLastLocation.iNetworkInfo;
+		
+		// first check if networkinfo matches last created location
+		if ( lastnet->iCellId == net->iCellId &&
+				lastnet->iLocationAreaCode == net->iLocationAreaCode &&
+				lastnet->iCountryCode == net->iCountryCode &&
+				lastnet->iNetworkId == net->iNetworkId )
+			{
+			LOG("CLocationRecord::LocationSnapshotL - network info matches");
+			
+			// if both locations have valid coordinates, calculate distance between points
+			if ( !Math::IsNaN( iLastLocation.iPosition.Latitude() ) && 
+					!Math::IsNaN( iLastLocation.iPosition.Longitude() ) && 
+					!Math::IsNaN( locationData.iPosition.Latitude() ) && 
+					!Math::IsNaN( locationData.iPosition.Longitude() ))
+				{
+				TReal32 distance;
+				TInt err = locationData.iPosition.Distance(iLastLocation.iPosition, distance);
+				
+				if ( distance < iLocationDelta )
+					{
+					LOG("CLocationRecord::LocationSnapshotL - location close to the previous one");
+					previousMatch = ETrue;
+					CreateRelationL( aObjectId, iLastLocationId );
+					LOG("CLocationRecord::CreateLocationObjectL - last location matched");
+					}
+				}
+			}
+		}
+	
+	// last location did not match, find existing one from DB
+	if( !previousMatch )
+		{
+		LOG("CLocationRecord::LocationSnapshotL - query location");
+		const TReal64 KMeterInDegrees = 0.000009;
+		const TReal64 KPi = 3.14159265358979;
+		const TReal32 K180Degrees = 180.0;
+	
+		TReal64 latitude = locationData.iPosition.Latitude();
+		TReal64 longitude = locationData.iPosition.Longitude();
+		// calculate distance in degrees
+		TReal64 cosine;
+		Math::Cos(cosine, locationData.iPosition.Latitude() * KPi / K180Degrees );
+		TReal64 latDelta = iLocationDelta * KMeterInDegrees;
+		TReal64 lonDelta = latDelta * cosine;
+		
+		CMdEObjectDef& locationObjectDef = namespaceDef.GetObjectDefL( Location::KLocationObject );
+		
+		CMdEPropertyDef& latitudeDef = locationObjectDef.GetPropertyDefL(
+				Location::KLatitudeProperty );
+		CMdEPropertyDef& longitudeDef = locationObjectDef.GetPropertyDefL(
+				Location::KLongitudeProperty );
+		CMdEPropertyDef& cellIdDef = locationObjectDef.GetPropertyDefL(
+				Location::KCellIdProperty );
+		CMdEPropertyDef& locationCodeDef = locationObjectDef.GetPropertyDefL( 
+				Location::KLocationAreaCodeProperty );
+		CMdEPropertyDef& countryCodeDef = locationObjectDef.GetPropertyDefL( 
+				Location::KCountryCodeProperty );
+		CMdEPropertyDef& networkCodeDef = locationObjectDef.GetPropertyDefL( 
+				Location::KNetworkCodeProperty );
+		
+		iLocationQuery = iMdeSession->NewObjectQueryL( namespaceDef, locationObjectDef, this );
+		CMdELogicCondition& cond = iLocationQuery->Conditions();
+		cond.SetOperator( ELogicConditionOperatorAnd );
+		
+		LOG1( "CLocationRecord::LocationSnapshotL latitude: %f", latitude);
+		LOG1( "CLocationRecord::LocationSnapshotL latdelta: %f", latDelta);
+		LOG1( "CLocationRecord::LocationSnapshotL longitude: %f", longitude);
+		LOG1( "CLocationRecord::LocationSnapshotL londelta: %f", lonDelta);
+		
+		cond.AddPropertyConditionL( latitudeDef, 
+				TMdERealBetween( latitude - latDelta, latitude + latDelta ));
+		cond.AddPropertyConditionL( longitudeDef, 
+				TMdERealBetween( longitude - lonDelta, longitude + lonDelta ));
+		cond.AddPropertyConditionL( cellIdDef, 
+				TMdEUintEqual( locationData.iNetworkInfo.iCellId) );
+		cond.AddPropertyConditionL( locationCodeDef, 
+				TMdEUintEqual( locationData.iNetworkInfo.iLocationAreaCode) );
+		cond.AddPropertyConditionL( countryCodeDef, ETextPropertyConditionCompareEquals,
+				locationData.iNetworkInfo.iCountryCode );
+		cond.AddPropertyConditionL( networkCodeDef, ETextPropertyConditionCompareEquals,
+				locationData.iNetworkInfo.iNetworkId );
+		
+		iLocationQuery->FindL();			
+		}
+	}
+
+	
+TItemId CLocationRecord::DoCreateLocationL( const TLocationData& aLocationData )
+	{
+	LOG("CLocationRecord::DoCreateLocationL - start");
+	TItemId locationObjectId;
+	
+	CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+
+	CMdEObjectDef& locationObjectDef = namespaceDef.GetObjectDefL( Location::KLocationObject );
+	
+	// required object properties
+	CMdEPropertyDef& creationDef = locationObjectDef.GetPropertyDefL(
+			Object::KCreationDateProperty );
+	CMdEPropertyDef& modifiedDef = locationObjectDef.GetPropertyDefL(
+			Object::KLastModifiedDateProperty );
+	CMdEPropertyDef& sizeDef = locationObjectDef.GetPropertyDefL(
+			Object::KSizeProperty );
+	CMdEPropertyDef& itemTypeDef = locationObjectDef.GetPropertyDefL(
+			Object::KItemTypeProperty );
+	CMdEPropertyDef& offSetDef = locationObjectDef.GetPropertyDefL( 
+			Object::KTimeOffsetProperty );
+
+	// location related properties
+	CMdEPropertyDef& cellIdDef = locationObjectDef.GetPropertyDefL(
+			Location::KCellIdProperty );
+	CMdEPropertyDef& latitudeDef = locationObjectDef.GetPropertyDefL(
+			Location::KLatitudeProperty );
+	CMdEPropertyDef& longitudeDef = locationObjectDef.GetPropertyDefL(
+			Location::KLongitudeProperty );
+	CMdEPropertyDef& altitudeDef = locationObjectDef.GetPropertyDefL(
+			Location::KAltitudeProperty );
+
+	CMdEPropertyDef& directionDef = locationObjectDef.GetPropertyDefL(
+			Location::KDirectionProperty );
+	CMdEPropertyDef& speedDef = locationObjectDef.GetPropertyDefL( 
+			Location::KSpeedProperty );
+	CMdEPropertyDef& locationCodeDef = locationObjectDef.GetPropertyDefL( 
+			Location::KLocationAreaCodeProperty );
+	CMdEPropertyDef& countryCodeDef = locationObjectDef.GetPropertyDefL( 
+			Location::KCountryCodeProperty );
+	CMdEPropertyDef& networkCodeDef = locationObjectDef.GetPropertyDefL( 
+			Location::KNetworkCodeProperty );
+	CMdEPropertyDef& qualityDef = locationObjectDef.GetPropertyDefL( 
+			Location::KQualityProperty );
+
+	// location object
+	CMdEObject* locationObject = NULL;
+
+	locationObject = iMdeSession->NewObjectL( locationObjectDef, Object::KAutomaticUri );
+	CleanupStack::PushL( locationObject );
+
+	TTime timestamp( 0 );
+	timestamp.UniversalTime();
+
+	TTimeIntervalSeconds timeOffset = User::UTCOffset();
+	TTime localTime = timestamp + timeOffset;
+	
+	// required object properties
+	locationObject->AddTimePropertyL( creationDef, localTime );
+	locationObject->AddTimePropertyL( modifiedDef, timestamp );
+	locationObject->AddUint32PropertyL( sizeDef, 0 ); // always zero size for location objects
+	locationObject->AddTextPropertyL( itemTypeDef, Location::KLocationItemType );
+	locationObject->AddInt16PropertyL( offSetDef, timeOffset.Int() / 60 );
+	
+	LOG1( "CLocationRecord::DoCreateLocationL - location created with stamp: %Ld", timestamp.Int64() );
+	
+	// location related properties
+	if ( !Math::IsNaN( aLocationData.iPosition.Latitude() ) && 
+		 !Math::IsNaN( aLocationData.iPosition.Longitude() ))
+		{
+		locationObject->AddReal64PropertyL( latitudeDef, aLocationData.iPosition.Latitude() );
+		locationObject->AddReal64PropertyL( longitudeDef, aLocationData.iPosition.Longitude() );
+		}
+	if ( !Math::IsNaN( aLocationData.iPosition.Altitude() ) )
+		{
+		locationObject->AddReal64PropertyL( altitudeDef, aLocationData.iPosition.Altitude() );
+		}
+	if ( !Math::IsNaN( aLocationData.iCourse.Course() ) )
+		{
+		locationObject->AddReal32PropertyL( directionDef, aLocationData.iCourse.Course() );
+		}
+	if ( !Math::IsNaN( aLocationData.iCourse.Speed() ) )
+		{
+		locationObject->AddReal32PropertyL( speedDef, aLocationData.iCourse.Speed() );
+		}
+	if ( !Math::IsNaN( aLocationData.iQuality ) )
+		{
+		locationObject->AddReal32PropertyL( qualityDef, aLocationData.iQuality );
+		}
+
+	// network related properties
+	if ( aLocationData.iNetworkInfo.iAreaKnown )
+		{
+		if ( aLocationData.iNetworkInfo.iAccess != CTelephony::ENetworkAccessUnknown )
+			{
+			locationObject->AddUint32PropertyL( cellIdDef, aLocationData.iNetworkInfo.iCellId );
+			
+			}
+		if ( aLocationData.iNetworkInfo.iLocationAreaCode != 0 &&
+			aLocationData.iNetworkInfo.iAccess != CTelephony::ENetworkAccessUnknown )
+			{
+			locationObject->AddUint32PropertyL( locationCodeDef, 
+					aLocationData.iNetworkInfo.iLocationAreaCode );
+			
+			}
+		if ( aLocationData.iNetworkInfo.iCountryCode.Length() > 0 )
+			{
+			locationObject->AddTextPropertyL( countryCodeDef, 
+					aLocationData.iNetworkInfo.iCountryCode );
+			
+			}
+		if ( aLocationData.iNetworkInfo.iNetworkId.Length() > 0 )
+			{
+			locationObject->AddTextPropertyL(networkCodeDef, aLocationData.iNetworkInfo.iNetworkId);
+			
+			}
+		}
+
+	// Add the location object to the database.
+	locationObjectId = iMdeSession->AddObjectL( *locationObject );
+
+	iLastLocationId = locationObjectId;
+	iLastLocation = aLocationData;
+
+	CleanupStack::PopAndDestroy( locationObject );
+	
+	LOG("CLocationRecord::DoCreateLocationL - end");
+	
+	return locationObjectId;
+	}
+
+
+TItemId CLocationRecord::CreateRelationL( const TUint& aObjectId, const TUint& aLocationId )
+	{ 
+	LOG("CLocationRecord::CreateRelationL - start");
+	CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+	
+	// "contains" relation definition
+	CMdERelationDef& containsRelDef = namespaceDef.GetRelationDefL( 
+			Relations::KContainsLocation );
+
+	CMdERelation* relationObject = iMdeSession->NewRelationLC( containsRelDef,
+			aObjectId, aLocationId, 0 );
+	if ( !relationObject )
+		{
+		User::Leave( KErrBadHandle );
+		}
+	TItemId relationId = iMdeSession->AddRelationL( *relationObject );
+
+	CleanupStack::PopAndDestroy( relationObject );
+	LOG("CLocationRecord::CreateRelationL - end");
+	
+	return relationId; 
+	}
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::ReadCenRepValueL
+// --------------------------------------------------------------------------
+//
+void CLocationRecord::ReadCenRepValueL(TInt aKey, TInt& aValue)
+	{
+	LOG( "CLocationRecord::::ReadCenRepValueL(), begin" );
+	CRepository* repository;
+	repository = CRepository::NewLC( KRepositoryUid );
+	User::LeaveIfError(repository->Get( aKey, aValue));
+	CleanupStack::PopAndDestroy(repository);
+    LOG( "CLocationRecord::::ReadCenRepValueL(), end" );   
+	}
+
+void CLocationRecord::HandleQueryNewResults(CMdEQuery& /*aQuery*/, TInt /*aFirstNewItemIndex*/, 
+		TInt /*aNewItemCount*/)
+	{
+	}
+
+void CLocationRecord::HandleQueryCompleted(CMdEQuery& aQuery, TInt aError)
+    {
+    LOG("CLocationRecord::HandleQueryCompleted - start");
+    const TInt count = aQuery.Count();
+    LOG1("CLocationRecord::HandleQueryCompleted count: %d", count);
+
+    CMdENamespaceDef* namespaceDef = NULL;
+
+    TRAP_IGNORE( namespaceDef = &iMdeSession->GetDefaultNamespaceDefL() );
+    if ( namespaceDef )
+        {
+        CMdEObjectDef* locationObjectDef = NULL;
+
+        TRAP_IGNORE( locationObjectDef = &namespaceDef->GetObjectDefL( Location::KLocationObject ) );
+        if ( locationObjectDef )
+        	{
+        	CMdEPropertyDef* latitudeDef = NULL;
+        	CMdEPropertyDef* longitudeDef = NULL;
+        	CMdEPropertyDef* altitudeDef = NULL;
+        	
+            TRAP_IGNORE( 
+            		latitudeDef = &locationObjectDef->GetPropertyDefL(
+            				Location::KLatitudeProperty );
+            		longitudeDef = &locationObjectDef->GetPropertyDefL(	
+            				Location::KLongitudeProperty );
+            		altitudeDef = &locationObjectDef->GetPropertyDefL( 
+            				Location::KAltitudeProperty );
+            		);
+
+            if( latitudeDef && longitudeDef && altitudeDef )
+            	{
+	            TBool created = EFalse;
+	            for ( TInt i = 0; i < count; i++ )
+	                {
+	                LOG1("CLocationRecord::HandleQueryCompleted check item: %d", i);
+	                CMdEItem& item = aQuery.ResultItem(i);
+	                CMdEObject& locationObject = static_cast<CMdEObject&>(item);
+	
+	                CMdEProperty* latProp = NULL;
+	                CMdEProperty* lonProp = NULL; 
+	                CMdEProperty* altProp = NULL;
+	
+	                locationObject.Property( *latitudeDef, latProp, 0 );
+	                locationObject.Property( *longitudeDef, lonProp, 0 );
+	                locationObject.Property( *altitudeDef, altProp, 0 );
+	
+	                if ( latProp && lonProp )
+	                    {
+	                    TReal32 distance;
+	                    TCoordinate newCoords;
+	                    if ( altProp )
+	                        {
+	                        TRAP_IGNORE( newCoords = TCoordinate( latProp->Real64ValueL(), lonProp->Real64ValueL(), (TReal32)altProp->Real64ValueL() ) );
+	                        }
+	                    else
+	                        {
+	                        TRAP_IGNORE( newCoords = TCoordinate( latProp->Real64ValueL(), lonProp->Real64ValueL() ) );
+	                        }
+	                    
+	                    const TInt err = iLocationData.iPosition.Distance(newCoords, distance);
+	                    
+	                    if ( distance < iLocationDelta )
+	                        {
+	                        LOG("CLocationRecord::HandleQueryCompleted - match found in db");
+	                        TRAPD( err, CreateRelationL( iObjectId, locationObject.Id() ) );
+	                        if( err == KErrNone)
+	                            {
+	                            created = ETrue;
+	                            i = count;
+	                            }
+	                        else
+	                            {
+	                            aError = err;
+	                            }
+	                        }
+	                    }
+	                }
+
+	            if ( !created && aError == KErrNone )
+	                {
+	                LOG("CLocationRecord::HandleQueryCompleted - no match found in db, create new");
+	                TInt locationId( 0 );
+	                TRAPD( err, locationId = DoCreateLocationL( iLocationData ) );
+	                LOG1("CLocationRecord::HandleQueryCompleted - DoCreateLocationL err: %d", err);
+	                if( err == KErrNone )
+	                    {
+	                    TRAP( err, CreateRelationL( iObjectId, locationId ));
+	                    LOG1("CLocationRecord::HandleQueryCompleted - CreateRelationL err: %d", err);
+	                    }
+	                }
+            	}
+            }
+        }
+
+    LOG("CLocationRecord::HandleQueryCompleted - end");
+    }
+
+EXPORT_C void CLocationRecord::SetMdeSession( CMdESession* aSession )
+	{
+	iMdeSession = aSession;
+	TRAPD(err, iRemapper->InitialiseL( aSession ));
+	if( err != KErrNone )
+		{
+		delete iRemapper;
+		iRemapper = NULL;
+		}
+	}
+
+void CLocationRecord::StartTimerL()
+	{
+	LOG("CLocationRecord::StartTimerL");
+	
+	if( !iNetworkInfoTimer->IsActive() )
+	    {
+	    iNetworkInfoTimer->Start( iInterval, iInterval, TCallBack( UpdateNetworkInfo, this ) );
+	    }
+	}
+
+TTime CLocationRecord::GetMdeObjectTimeL( TItemId aObjectId ) 
+    {
+    CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+
+    CMdEObjectDef& objectDef = namespaceDef.GetObjectDefL( Object::KBaseObject );
+    CMdEPropertyDef& timeDef = objectDef.GetPropertyDefL( Object::KLastModifiedDateProperty );
+
+    CMdEObject* object = NULL;
+    CMdEProperty* property = NULL;
+    
+    object = iMdeSession->GetObjectL( aObjectId );
+    object->Property( timeDef, property, 0 );
+    if ( !property )
+        {
+        User::Leave( KErrNotFound );
+        }
+    return property->TimeValueL();
+    }
+
+EXPORT_C TBool CLocationRecord::RemappingNeeded()
+	{
+	return iRemapper->ItemsInQueue();
+	}
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/src/cnetworkinfo.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,138 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A class for getting network cell id.
+*
+*/
+
+#include <etel3rdparty.h>
+
+#include "cnetworkinfo.h"
+#include "locationmanagerdebug.h"
+
+// --------------------------------------------------------------------------
+// CNetworkInfo::NewL
+// --------------------------------------------------------------------------
+//
+EXPORT_C CNetworkInfo* CNetworkInfo::NewL( MNetworkInfoObserver* aTrail )
+    {
+    LOG( "CNetworkInfo::NewL(), begin" );
+    CNetworkInfo* self = new (ELeave) CNetworkInfo( aTrail );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    LOG( "CNetworkInfo::NewL(), end" );
+    return self;
+    }
+        
+// --------------------------------------------------------------------------
+// CNetworkInfo::CNetworkInfo
+// --------------------------------------------------------------------------
+//  
+CNetworkInfo::CNetworkInfo( MNetworkInfoObserver* aTrail ) 
+    : CActive( CActive::EPriorityStandard ),
+    iFirstTime( EFalse ),
+    iTelephony( NULL ),
+    iNetworkInfoV1Pckg( iNetworkInfoV1 ) 
+    {
+    CActiveScheduler::Add( this );
+    iTrail = aTrail;
+    }
+
+// --------------------------------------------------------------------------
+// CNetworkInfo::ConstructL
+// --------------------------------------------------------------------------
+//    
+void CNetworkInfo::ConstructL()
+    {
+	LOG( "CNetworkInfo::ConstructL(), begin" );
+	iFirstTime = ETrue;
+    iTelephony = CTelephony::NewL();
+    iTelephony->GetCurrentNetworkInfo(iStatus, iNetworkInfoV1Pckg);
+    LOG( "CNetworkInfo::ConstructL(), iTelephony->GetCurrentNetworkInfo called" );
+    
+   	if ( IsActive() )
+    	{
+    	Cancel();
+        }    
+    SetActive();
+    
+    LOG( "CNetworkInfo::ConstructL(), end" );
+    }
+    
+// --------------------------------------------------------------------------
+// CNetworkInfo::~CNetworkInfo
+// --------------------------------------------------------------------------
+//    
+CNetworkInfo::~CNetworkInfo()
+    {
+    Cancel();
+    delete iTelephony;
+    }
+
+// --------------------------------------------------------------------------
+// CNetworkInfo::RunError
+// --------------------------------------------------------------------------
+//
+TInt CNetworkInfo::RunError( TInt /*aError*/ )
+    {
+    return KErrNone;
+    }    
+
+// --------------------------------------------------------------------------
+// CNetworkInfo::RunL
+// --------------------------------------------------------------------------
+//    
+void CNetworkInfo::RunL()
+    { 
+	LOG( "CNetworkInfo::RunL(), begin" );   
+	iFirstTime = EFalse; 
+    iTrail->NetworkInfo( iNetworkInfoV1, iStatus.Int() );
+    LOG( "CNetworkInfo::RunL(), iTrail->NetworkInfo called" );   
+    
+    iTelephony->NotifyChange(iStatus, CTelephony::ECurrentNetworkInfoChange, iNetworkInfoV1Pckg);
+    LOG( "CNetworkInfo::RunL(), iTelephony->NotifyChange called" );
+      
+   	if ( IsActive() )
+    	{
+    	Cancel();
+        }    
+    SetActive();
+    
+    LOG( "CNetworkInfo::RunL(), end" ); 
+    }    
+
+// --------------------------------------------------------------------------
+// CNetworkInfo::DoCancel
+// --------------------------------------------------------------------------
+// 
+void CNetworkInfo::DoCancel()
+    {
+	LOG( "CNetworkInfo::DoCancel(), begin" );
+	if ( IsActive() )
+		{
+    	if ( iFirstTime )    
+        	{
+	    	LOG( "CNetworkInfo::DoCancel(), cancelling CTelephony::EGetCurrentNetworkInfoCancel" );
+        	iTelephony->CancelAsync( CTelephony::EGetCurrentNetworkInfoCancel );
+        	}
+    	else
+    		{
+	    	LOG( "CNetworkInfo::DoCancel(), cancelling CTelephony::ECurrentNetworkInfoChangeCancel" );
+	    	iTelephony->CancelAsync( CTelephony::ECurrentNetworkInfoChangeCancel );	
+    		}
+		}	
+   	LOG( "CNetworkInfo::DoCancel(), end" );
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/src/cpositioninfo.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,191 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A class for getting network cell id.
+*
+*/
+
+#include <etel3rdparty.h>
+
+#include "rlocationtrail.h"
+#include "cpositioninfo.h"
+#include "locationtraildefs.h"
+#include "locationmanagerdebug.h"
+
+// --------------------------------------------------------------------------
+// CPositionInfo::NewL
+// --------------------------------------------------------------------------
+//
+EXPORT_C CPositionInfo* CPositionInfo::NewL( MPositionInfoObserver* aTrail )
+    {
+    LOG( "CPositionInfo::NewL(), begin" );
+    CPositionInfo* self = new (ELeave) CPositionInfo( aTrail );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    LOG( "CPositionInfo::NewL(), end" );
+    return self;
+    }
+        
+// --------------------------------------------------------------------------
+// CPositionInfo::CPositionInfo
+// --------------------------------------------------------------------------
+//  
+CPositionInfo::CPositionInfo( MPositionInfoObserver* aTrail ) 
+    : CActive( CActive::EPriorityStandard ),
+    iFirstInterval( ETrue )
+    {
+    CActiveScheduler::Add( this );
+    iTrail = aTrail;
+    iTrailCaptureSetting = RLocationTrail::ECaptureAll;
+    
+    // Set update interval.
+    iUpdateOptions.SetUpdateInterval( TTimeIntervalMicroSeconds(KFirstInterval) );
+    // Set time out level. 
+    iUpdateOptions.SetUpdateTimeOut( TTimeIntervalMicroSeconds(KUpdateTimeOut) );
+    // Positions which have time stamp below KMaxAge can be reused
+    iUpdateOptions.SetMaxUpdateAge( TTimeIntervalMicroSeconds(KMaxAge) );
+    // Disables location framework to send partial position data
+    iUpdateOptions.SetAcceptPartialUpdates( EFalse );    
+    }
+
+// --------------------------------------------------------------------------
+// CPositionInfo::ConstructL
+// --------------------------------------------------------------------------
+//    
+void CPositionInfo::ConstructL()
+    {
+    
+    }
+    
+// --------------------------------------------------------------------------
+// CPositionInfo::~CPositionInfo
+// --------------------------------------------------------------------------
+//    
+CPositionInfo::~CPositionInfo()
+    {
+    Cancel();
+    iPositioner.Close();
+    iPosServer.Close();
+    }
+
+// --------------------------------------------------------------------------
+// CPositionInfo::RunError
+// --------------------------------------------------------------------------
+//
+TInt CPositionInfo::RunError( TInt /*aError*/ )
+    {
+    return KErrNone;
+    }
+
+// --------------------------------------------------------------------------
+// CPositionInfo::GetCellId
+// --------------------------------------------------------------------------
+//
+void CPositionInfo::StartL( RLocationTrail::TTrailCaptureSetting aCaptureSetting, TInt aUpdateInterval )
+    {
+    LOG( "CPositionInfo::StartL(), begin" );
+
+    iTrailCaptureSetting = aCaptureSetting;
+    iUpdateInterval = aUpdateInterval;
+    
+    if ( aCaptureSetting == RLocationTrail::ECaptureAll ) 
+    	{
+	    User::LeaveIfError( iPosServer.Connect() );
+	    User::LeaveIfError( iPositioner.Open( iPosServer ) );
+	    User::LeaveIfError( iPositioner.SetRequestor( CRequestor::ERequestorService,
+	                        CRequestor::EFormatApplication, KRequestor ) );
+	    User::LeaveIfError( iPositioner.SetUpdateOptions( iUpdateOptions ) );
+	    iPositioner.NotifyPositionUpdate( iPositionInfo, iStatus );
+    	}
+    
+    SetActive();
+    
+    if ( aCaptureSetting == RLocationTrail::ECaptureNetworkInfo ) 
+    	{
+    	TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+    	}
+
+    LOG( "CPositionInfo::StartL(), end" );
+    }
+
+// --------------------------------------------------------------------------
+// CPositionInfo::NextPosition
+// --------------------------------------------------------------------------
+//
+void CPositionInfo::NextPosition()
+    {
+    iPositionInfo = TPositionSatelliteInfo(); // Clear position info.
+    if ( iTrailCaptureSetting == RLocationTrail::ECaptureAll )
+    	{
+    	iPositioner.NotifyPositionUpdate( iPositionInfo, iStatus );
+    	}
+    
+    SetActive();
+    
+    if ( iTrailCaptureSetting == RLocationTrail::ECaptureNetworkInfo ) 
+    	{
+    	TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+    	}
+    }
+    
+// --------------------------------------------------------------------------
+// CPositionInfo::Stop
+// --------------------------------------------------------------------------
+//
+void CPositionInfo::Stop()
+    {
+    Cancel();
+    
+    // Start shutdown timer...
+    iPositioner.Close();
+    iPosServer.Close();
+    }    
+        
+// --------------------------------------------------------------------------
+// CPositionInfo::RunL
+// --------------------------------------------------------------------------
+//
+void CPositionInfo::RunL()
+    { 
+    iTrail->Position( iPositionInfo, iStatus.Int() );
+    if ( iFirstInterval && IsActive() )
+    	{
+    	Cancel();
+    	iUpdateOptions.SetUpdateInterval( iUpdateInterval );
+        if ( iTrailCaptureSetting == RLocationTrail::ECaptureAll ) 
+        	{
+        	User::LeaveIfError( iPositioner.SetUpdateOptions( iUpdateOptions ) );
+        	iPositioner.NotifyPositionUpdate( iPositionInfo, iStatus );
+        	}
+    	SetActive();
+    	
+    	iFirstInterval = EFalse;
+    	}
+    }    
+
+// --------------------------------------------------------------------------
+// CPositionInfo::DoCancel
+// --------------------------------------------------------------------------
+// 
+void CPositionInfo::DoCancel()
+    {
+    if ( !IsActive() )    
+        {
+        iPositioner.CancelRequest( EPositionerNotifyPositionUpdate );
+        }
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/src/ctracklog.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,361 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A class for TrackLog functionality
+*
+*/
+
+#include "ctracklog.h"
+#include "locationmanagerdebug.h"
+#include "locationtraildefs.h"
+#include "rtracklog.h"
+#include <f32file.h>
+#include <s32file.h>
+#include <PathInfo.h>
+#include <centralrepository.h>
+#include <locationeventdef.h>
+#include "cgpxconverterao.h"
+
+EXPORT_C CTrackLog* CTrackLog::NewL()
+	{
+    CTrackLog* self = new (ELeave) CTrackLog();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+	}
+
+void CTrackLog::ConstructL()
+	{
+	LOG("CTrackLog::ConstructL start");
+	
+	iGpxConverter = CGpxConverterAO::NewL();
+	
+    TInt bufSize( 0 );
+    TRAPD( err, ReadCenRepValueL( KTrackLogSizeKey, bufSize ));
+    LOG1("CLocationManagerServer::ConstructL, cenrep bufsize value:%d", bufSize);
+    
+    if ( err != KErrNone )
+    	{
+        LOG1("CTrackLog::ConstructL, cenrep err:%d", err);
+        iMaxBufferSize = KTrackLogBufSize;
+    	}
+    else
+    	{
+    	iMaxBufferSize = bufSize;
+    	}
+	User::LeaveIfError( iFs.Connect() );
+	
+	LOG("CTrackLog::ConstructL end");
+	}
+
+CTrackLog::CTrackLog() :
+	iMaxBufferSize( KTrackLogBufSize ),
+	iRecording( EFalse )
+	{
+	}
+
+CTrackLog::~CTrackLog()
+	{
+	delete iGpxConverter;
+	iFs.Close();
+	}
+
+EXPORT_C void CTrackLog::StartRecordingL(TItemId aId)
+	{
+	LOG("CTrackLog::StartRecording start");
+	_LIT( KExtTmp, ".tmp" );
+	_LIT( KExtGpx, ".gpx" );
+	
+	iTagId = aId;
+	iFs.PrivatePath( iTmpFileName );
+	TInt err;
+	err = iFs.MkDirAll( iTmpFileName );
+	if ( err != KErrAlreadyExists && err != KErrNone )
+		{
+		User::Leave( err );
+		}
+
+	TTime now( 0 );
+	now.HomeTime();
+	TDateTime datetime = now.DateTime();
+	
+	_LIT( KGpxFileName, "tracklog%d%02d%02d%02d%02d%02d" );
+	HBufC* fileName = HBufC::NewL( KMaxFileName );
+	CleanupStack::PushL( fileName );
+	TPtr namePtr = fileName->Des();
+	
+	namePtr.Format(KGpxFileName, datetime.Year(), datetime.Month() + 1, datetime.Day() + 1,
+			datetime.Hour(), datetime.Minute(), datetime.Second() );
+
+	iTrackLogItemArray.Reset();
+	iRecording = ETrue;
+	iGpxFileName.Copy( namePtr );
+	iTmpFileName.Append( iGpxFileName );
+
+	iGpxFileName.Append( KExtGpx );
+	iTmpFileName.Append( KExtTmp );	
+	
+	WriteBufferToFileL();
+	
+	CleanupStack::PopAndDestroy( fileName );
+	LOG("CTrackLog::StartRecording end");
+	}
+
+EXPORT_C void CTrackLog::StopRecordingL()
+	{
+	LOG("CTrackLog::StopRecording start");
+	
+	// "flush" buffer
+	WriteBufferToFileL();
+	iTrackLogItemArray.Reset();
+	// gpx converter will clean up boundaries
+	iGpxConverter->AddToQueueL( iTmpFileName, iBoundaries );
+	
+	iBoundaries = NULL;
+	iRecording = EFalse;
+	LOG("CTrackLog::StopRecording end");
+	}
+
+EXPORT_C void CTrackLog::CancelRecording()
+	{
+	LOG("CTrackLog::CancelRecording start");
+	iRecording = EFalse;
+	iTrackLogItemArray.Reset();
+	iFs.Delete( iTmpFileName );
+	LOG("CTrackLog::CancelRecording end");
+	}
+
+void CTrackLog::LocationAdded( const TLocationTrailItem& aTrailItem, 
+							   const TPositionSatelliteInfo& aSatellites )
+	{
+	LOG("CTrackLog::LocationAdded start");
+
+	const TInt KMaxLat = 90;
+	const TInt KMinLat = -90;
+	const TInt KMaxLon = 180;
+	const TInt KMinLon = -180;
+	if ( !iBoundaries )
+		{
+		iBoundaries = new TBoundaries;	
+		iBoundaries->minLatitude = KMaxLat;
+		iBoundaries->maxLatitude = KMinLat;
+		iBoundaries->minLongitude = KMaxLon;
+		iBoundaries->maxLongitude = KMinLon;
+		iBoundaries->distance = 0;
+		}
+	
+	if ( IsRecording() )
+		{
+		TTrackLogItem newItem;
+		newItem.iTimeStamp = aTrailItem.iTimeStamp;
+		newItem.iLatitude = aTrailItem.iLocationData.iPosition.Latitude();
+		newItem.iLongitude = aTrailItem.iLocationData.iPosition.Longitude();
+		newItem.iAltitude = aTrailItem.iLocationData.iPosition.Altitude();
+		newItem.iHdop = aSatellites.HorizontalDoP();
+		newItem.iVdop = aSatellites.VerticalDoP();
+		newItem.iCourse = aTrailItem.iLocationData.iCourse.Course();
+		newItem.iQuality = aTrailItem.iLocationData.iQuality;
+		newItem.iNumSatellites = aTrailItem.iLocationData.iSatellites;
+
+		iTrackLogItemArray.Append(newItem);
+		
+		// Keep the latest satellite information safe.
+		iSatelliteInfo = aSatellites;
+		
+		// Check if the GPS fix is lost or buffer is full.
+		// If true, then write buffer to a file.
+		if ( Math::IsNaN(newItem.iLatitude) || Math::IsNaN(newItem.iLongitude) ||
+				iTrackLogItemArray.Count() > iMaxBufferSize )
+			{
+			LOG("CTrackLog::LocationAdded - buffer full, writing to file");
+			TRAPD( err, WriteBufferToFileL() );
+			if( err != KErrNone )
+				{
+				LOG1("WriteBufferToFileL leave error: %d", err);
+				}
+			iTrackLogItemArray.Reset();
+			}
+		if( !Math::IsNaN( newItem.iLatitude ) && !Math::IsNaN( newItem.iLongitude ) )
+			{
+			TReal32 distance;
+			if ( !lastCoords )
+				{
+				lastCoords = new TCoordinate( aTrailItem.iLocationData.iPosition );
+				}
+			else
+				{
+				TLocality newCoords(aTrailItem.iLocationData.iPosition,
+						aTrailItem.iLocationData.iPosition.HorizontalAccuracy()	);
+				TInt err = newCoords.Distance(*lastCoords, distance);
+				if ( err == KErrNone )
+					{
+					delete lastCoords;
+					lastCoords = new TCoordinate( aTrailItem.iLocationData.iPosition );
+					iBoundaries->distance += distance;
+					}
+				}
+			iBoundaries->maxLatitude = Max( iBoundaries->maxLatitude, newItem.iLatitude );
+			iBoundaries->minLatitude = Min( iBoundaries->minLatitude, newItem.iLatitude );
+			iBoundaries->maxLongitude = Max( iBoundaries->maxLongitude, newItem.iLongitude );
+			iBoundaries->minLongitude = Min( iBoundaries->minLongitude, newItem.iLongitude );
+			}
+		}
+	LOG("CTrackLog::LocationAdded end");	
+	}
+
+void CTrackLog::WriteBufferToFileL()
+	{
+	LOG("CTrackLog::WriteBufferToFileL start");
+
+	RFile64 file;
+	RFileWriteStream writer;
+	
+	TInt err;
+	err = file.Open( iFs, iTmpFileName, EFileRead );
+	if ( err != KErrNone )
+		{
+		err = writer.Create( iFs, iTmpFileName, EFileWrite );
+		if( err != KErrNone )
+			{
+			User::Leave( err );
+			}
+		writer << I64LOW( iTagId );
+		writer << I64HIGH( iTagId );
+		}
+	else 
+		{
+		CleanupClosePushL( file );
+		TInt64 endpos( 0 );
+		file.Seek( ESeekEnd, endpos );
+		CleanupStack::PopAndDestroy( &file );
+		err = writer.Open( iFs, iTmpFileName, EFileWrite );
+		if( err != KErrNone )
+			{
+			User::Leave( err );
+			}
+		writer.Sink()->SeekL( MStreamBuf::EWrite, TStreamPos( endpos ));
+		}
+	
+	CleanupClosePushL( writer );
+	
+	TInt count = iTrackLogItemArray.Count();
+	
+	for( TInt i = 0; i < count; i++ )
+		{
+		writer << iTrackLogItemArray[i];
+		}
+	
+	writer.CommitL();
+	
+	CleanupStack::PopAndDestroy( &writer );
+	LOG("CTrackLog::WriteBufferToFileL end");
+	}
+
+EXPORT_C TInt CTrackLog::GetStatus( TBool& aRecording, TPositionSatelliteInfo& aFixQuality )
+	{
+	aFixQuality = iSatelliteInfo;
+	aRecording = IsRecording();
+	
+	return KErrNone;
+	}
+
+EXPORT_C TBool CTrackLog::IsRecording()
+	{
+	return iRecording;
+	}
+
+EXPORT_C void CTrackLog::GetTrackLogName(TFileName& aFileName)
+	{
+	aFileName = iGpxFileName;
+	}
+
+EXPORT_C void CTrackLog::AddGpxObserver( MGpxConversionObserver* aObserver )
+	{
+	iGpxConverter->AddObserver( aObserver );
+	}
+
+EXPORT_C void CTrackLog::StartRecoveryL()
+	{
+	_LIT( KWildTmp, "*.tmp" );
+
+	TInt err;
+	CDir* files;
+	TFileName *filename = new (ELeave) TFileName();
+	TFindFile finder( iFs );
+	iFs.PrivatePath( iTmpFileName );
+	err = finder.FindWildByDir( KWildTmp, iTmpFileName, files);
+	if ( err == KErrNone )
+		{
+		TInt count = files->Count();
+		for( TInt i = 0; i < count; i++ )
+			{
+			filename->Copy(iTmpFileName);
+			filename->Append((*files)[i].iName);
+			TRAP_IGNORE( iGpxConverter->AddToQueueL( *filename, NULL ));
+			}
+		}
+	delete filename;
+	delete files;
+	}
+
+void CTrackLog::ReadCenRepValueL(TInt aKey, TInt& aValue)
+	{
+	LOG( "LocationManagerServer::ReadCenRepValueL(), begin" );
+	CRepository* repository;
+	repository = CRepository::NewLC( KRepositoryUid );
+	User::LeaveIfError(repository->Get( aKey, aValue));
+	CleanupStack::PopAndDestroy(repository);
+    LOG( "LocationManagerServer::ReadCenRepValueL(), end" );   
+	}
+
+
+void TTrackLogItem::ExternalizeL( RWriteStream& aStream ) const
+	{
+	aStream.WriteReal64L( iLatitude );
+	aStream.WriteReal64L( iLongitude );
+	aStream.WriteReal32L( iAltitude );
+	aStream.WriteReal32L( iCourse );	
+	aStream.WriteReal32L( iQuality );	
+	aStream.WriteUint32L( iNumSatellites );
+	aStream.WriteReal32L( iHdop );
+	aStream.WriteReal32L( iVdop );
+	aStream.WriteUint32L( I64LOW( iTimeStamp.Int64() ));
+	aStream.WriteUint32L( I64HIGH( iTimeStamp.Int64() ));
+	}
+
+void TTrackLogItem::InternalizeL( RReadStream& aStream )
+	{
+	iLatitude = aStream.ReadReal64L();
+	iLongitude = aStream.ReadReal64L();
+	iAltitude = aStream.ReadReal32L();
+	TReal32 realVal;
+	realVal = aStream.ReadReal32L();
+	iCourse = realVal;
+	realVal = aStream.ReadReal32L();
+	iQuality = realVal;
+	TUint32 satellites;
+	satellites = aStream.ReadUint32L();
+	iNumSatellites = satellites;
+	realVal = aStream.ReadReal32L();
+	iHdop = realVal;
+	realVal = aStream.ReadReal32L();
+	iVdop = realVal;
+	TUint32 low( 0 );
+	TUint32 high( 0 );
+	low = aStream.ReadUint32L();
+	high = aStream.ReadUint32L();
+	TInt64 timestamp( 0 );
+	timestamp = MAKE_TINT64( high, low );
+	iTimeStamp = timestamp;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/locationtrail/src/locationremappingao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,403 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Remap location data to location objects*
+*/
+
+#include "locationremappingao.h"
+#include "mdequery.h"
+#include "mdccommon.h"
+#include "mdeconstants.h"
+#include "mdenamespacedef.h"
+#include "mdeobjectdef.h" 
+#include "mdeobjectquery.h"
+
+using namespace MdeConstants;
+
+CLocationRemappingAO* CLocationRemappingAO::NewL()
+	{
+	LOG( "CLocationRemappingAO::NewL" ); // DEBUG INFO
+	
+	CLocationRemappingAO* self = new (ELeave) CLocationRemappingAO();
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+void CLocationRemappingAO::ConstructL()
+	{
+	LOG( "CLocationRemappingAO::ConstructL" ); // DEBUG INFO
+	CActiveScheduler::Add( this );
+	iMdEClient = NULL;
+	
+	TRAPD(err, ReadTimeFromCenRepL());
+	if (err)
+		{
+		LOG( "CLocationRemappingAO::ConstructL, Can not read timelimit value from CenRep");
+		iTimeLimit = TTimeIntervalSeconds( KRemappingTime );
+		}
+	}
+
+CLocationRemappingAO::~CLocationRemappingAO()
+	{
+	LOG( "CLocationRemappingAO::~CLocationRemappingAO" ); // DEBUG INFO
+
+	StopRemapping();
+	Cancel();
+	
+	iObjects.ResetAndDestroy();
+	}
+
+CLocationRemappingAO::CLocationRemappingAO() : CActive( CActive::EPriorityStandard ),
+	iState ( EIdle ),
+	iContinue( EFalse ),
+	iTimed( EFalse ),
+	iRequested( EFalse ),
+	iStartTime( 0 ),
+	iEndTime( 0 ),
+	iTimeLimit( 0 )
+	{
+	// No implementation required
+	}
+
+
+void CLocationRemappingAO::InitialiseL(CMdESession* aMdEClient)
+	{
+	LOG( "CLocationRemappingAO::Initialise start" ); // DEBUG INFO
+	iMdEClient = aMdEClient;
+	
+	// namespace defaults
+	iNamespaceDef = &iMdEClient->GetDefaultNamespaceDefL();
+	
+	// media object definitions
+    iObjImageDef = &iNamespaceDef->GetObjectDefL( Image::KImageObject );
+    iObjVideoDef = &iNamespaceDef->GetObjectDefL( Video::KVideoObject );
+    iPropDateDef = &iObjImageDef->GetPropertyDefL( Object::KCreationDateProperty );
+    iPropModifiedDef = &iObjImageDef->GetPropertyDefL( Object::KLastModifiedDateProperty );
+	
+    // location object definitions
+	iObjLocationDef = &iNamespaceDef->GetObjectDefL( Location::KLocationObject );
+	iPropLatDef = &iObjLocationDef->GetPropertyDefL( Location::KLatitudeProperty );
+    iPropLongDef = &iObjLocationDef->GetPropertyDefL( Location::KLongitudeProperty );
+	iPropAltDef = &iObjLocationDef->GetPropertyDefL( Location::KAltitudeProperty );
+	
+	iContainsLocationRelDef = &iNamespaceDef->GetRelationDefL( Relations::KContainsLocation );
+	
+	LOG( "CLocationRemappingAO::Initialise end" );
+	}
+
+void CLocationRemappingAO::Append( TRemapItem aItem )
+	{
+	iRemapItems.Append( aItem );
+	}
+
+void CLocationRemappingAO::ResetQueue()
+	{
+	iRemapItems.Reset();
+	}
+
+TBool CLocationRemappingAO::ItemsInQueue()
+	{
+	return iRemapItems.Count() > 0;
+	}
+
+TBool CLocationRemappingAO::CheckQueue()
+	{
+	LOG( "CLocationRemappingAO::CheckQueue - start" );
+	TBool create( EFalse );
+	TInt index = iRemapItems.Count() - 1;
+	TTime startTime( 0 );
+	startTime.UniversalTime();
+	startTime = startTime - iTimeLimit;
+	RArray<TItemId> removeLocations; 
+	
+	for( TInt i = index; i >= 0; i-- )
+		{
+		if( iRemapItems[i].iLocationId == 0 )
+			{
+			create = ETrue;
+			}
+		
+		if( iRemapItems[i].iTime < startTime )
+			{
+			LOG( "CLocationRemappingAO::CheckQueue - old item found" );
+			if ( iRemapItems[i].iLocationId != 0 )
+				{
+				// save old location id 
+				TInt err = removeLocations.Find( iRemapItems[i].iLocationId );
+				if ( err == KErrNotFound )
+					{
+					removeLocations.Append( iRemapItems[i].iLocationId );
+					}
+				}
+			iRemapItems.Remove( i );
+			create = ETrue;
+			}
+		}
+	
+	// clear all "old" location id's from remap items
+	if( removeLocations.Count() < 0 )
+		{
+		index = iRemapItems.Count();
+		for( TInt i = 0; i < index; i++ )
+			{
+			TInt err = removeLocations.Find( iRemapItems[i].iLocationId );
+			if ( err != KErrNotFound )
+				{
+				LOG( "CLocationRemappingAO::CheckQueue - old item found" );
+				iRemapItems[i].iLocationId = 0;
+				}
+			}
+		}
+	
+	removeLocations.Close();
+	LOG( "CLocationRemappingAO::CheckQueue - end" );
+	return create;
+	}
+
+
+void CLocationRemappingAO::StopRemapping()
+	{
+	LOG( "CLocationRemappingAO::StopRemapping" ); // DEBUG INFO
+	NextState(EIdle);
+	}
+
+void CLocationRemappingAO::StartRemappingObjects( const TLocationData& aLocationData )
+	{
+	iLocationData = aLocationData;
+	LOG( "CLocationRemappingAO::StartRemappingObjects" ); // DEBUG INFO
+	TInt count = iRemapItems.Count();
+	if ( count == 0 )
+		{
+		LOG("CLocationRemappingAO::StartRemappingObjects No need to remap location objects");
+		return;
+		}
+	NextState( ERemapObjects );
+	}
+
+void CLocationRemappingAO::NextState(TMappingState aState)
+	{
+	LOG1( "CLocationRemappingAO::NextState - state: %d", aState ); // DEBUG INFO
+	iState = aState;
+	// Request complete if not idling
+	if (iState != EIdle)
+		{
+		TRequestStatus* pStatus = &iStatus;
+		User::RequestComplete( pStatus, KErrNone );
+		SetActive();
+		}	
+	}
+
+void CLocationRemappingAO::DoCancel()
+	{
+	LOG( "CLocationRemappingAO::DoCancel" ); // DEBUG INFO
+	// back to idle
+	NextState(EIdle);
+	}
+
+TInt CLocationRemappingAO::RunError( TInt aError )
+	{
+	if (aError != KErrNone)
+		{
+		LOG1( "CLocationRemappingAO::RunError with error code: %d", aError ); // DEBUG INFO
+		}
+	// back to idle
+	NextState(EIdle);
+	return KErrNone;
+	}
+
+void CLocationRemappingAO::RunL()
+	{
+	LOG1( "CCameraTrailMonitorAO::RunL iStatus: %d", iStatus.Int() ); // DEBUG INFO
+	
+	switch(iState)
+		{
+		case EIdle:			
+			{
+			LOG( "CLocationRemappingAO::RunL() - EIdle" );			
+			break;
+			}
+
+		case ERemapObjects:
+			{
+			// start remapping object data if Location Object request succeed
+			RemapObjectsL();
+			NextState(ECommitObjects);
+			break;			
+			}
+
+		case ECommitObjects:
+			{
+			// commit location object data
+			CommitObjectsL();
+			NextState( EIdle );
+			break;
+			}
+			
+		default:		
+			{
+			User::Leave( KErrUnknown );		
+			break;
+			}
+		}
+	}
+
+
+void CLocationRemappingAO::RemapObjectsL()
+	{	
+	LOG( "CLocationRemappingAO::RemapObjects - start" ); // DEBUG INFO
+	// remap location data to location objects
+	TInt count = iRemapItems.Count();
+	
+	for( TInt i = 0 ; i < count; i++ )
+		{
+		TInt err = iObjectIds.Find( iRemapItems[i].iLocationId );
+		if ( err == KErrNotFound )
+			{
+			iObjectIds.Append( iRemapItems[i].iLocationId );
+			}
+		}
+
+	count = iObjectIds.Count();
+	for (TInt i = 0; i < count; i++)
+		{
+		CMdEObject* location = iMdEClient->OpenObjectL(iObjectIds[i], *iObjLocationDef);
+		CleanupStack::PushL( location );
+		
+		if (location->PropertyCount(*iPropLatDef) == 0)
+			{
+			location->AddReal64PropertyL(*iPropLatDef, iLocationData.iPosition.Latitude());
+			LOG( "CLocationRemappingAO::RemapObjects - wrote latitude" );
+			}
+		if (location->PropertyCount(*iPropLongDef) == 0)
+			{
+			location->AddReal64PropertyL(*iPropLongDef, iLocationData.iPosition.Longitude());
+			LOG( "CLocationRemappingAO::RemapObjects - wrote longitude" );
+			}
+		if (location->PropertyCount(*iPropAltDef) == 0)
+			{
+			location->AddReal64PropertyL(*iPropAltDef, iLocationData.iPosition.Altitude());
+			LOG( "CLocationRemappingAO::RemapObjects - wrote altitude" );
+			}
+		CMdEProperty* modProp = NULL;
+		location->Property( *iPropModifiedDef, modProp, 0 );
+		if ( modProp )
+			{
+			TTime timestamp( 0 );
+			timestamp.UniversalTime();
+			modProp->SetTimeValueL( timestamp );
+			}
+		iObjects.AppendL(location);
+		CleanupStack::Pop( location );
+		}
+	count = iRemapItems.Count();
+	LOG1("CLocationRemappingAO::RemapObjectsL - updating relations, count:%d", count);
+	// update relation timestamp, composer will then update exif data
+	for( TInt i = 0; i < count; i++ )
+		{
+		CMdERelation* relation = NULL;
+		relation = iMdEClient->GetRelationL( iRemapItems[i].iRelationId );
+		
+    	TTime timestamp( 0 );
+    	timestamp.UniversalTime();
+    	relation->SetLastModifiedDate( timestamp );
+    	
+    	iMdEClient->UpdateRelationL( *relation );
+		}
+	LOG("CLocationRemappingAO::RemapObjectsL - relations updated");
+	
+	iObjectIds.Reset();
+	ResetQueue();
+	
+	LOG( "CLocationRemappingAO::RemapObjects - end" );
+	}
+
+void CLocationRemappingAO::CommitObjectsL()
+	{
+	LOG( "CLocationRemappingAO::CommitObjects" ); // DEBUG INFO
+	// commit location objects
+	if( iObjects.Count() > 0 )
+		{
+		iMdEClient->CommitObjectsL(iObjects);
+		iObjects.ResetAndDestroy();
+		}	
+	}
+	    	
+// --------------------------------------------------------------------------
+// CLocationManagerServer::ReadCenRepValueL
+// --------------------------------------------------------------------------
+//
+void CLocationRemappingAO::ReadTimeFromCenRepL()
+	{
+	LOG( "CLocationRemappingAO::ReadTimeFromCenRepL(), begin" );
+	CRepository* repository = CRepository::NewLC( KRepositoryUid ); 
+	TInt value( 0 );
+	User::LeaveIfError( repository->Get(KRemappingTimeKey, value) );
+	CleanupStack::PopAndDestroy(repository);
+
+	LOG1( "CLocationRemappingAO::ReadTimeFromCenRepL(), Using timelimit value:%d seconds", value );
+	iTimeLimit = TTimeIntervalSeconds( value );
+
+    LOG( "CLocationRemappingAO::ReadTimeFromCenRepL(), end" );   
+	}
+
+
+void CLocationRemappingAO::UpdateRelationsL( TItemId aLocationId )
+	{ 
+	LOG("CLocationRemappingAO::UpdateRelationsL - start");
+	CMdENamespaceDef& namespaceDef = iMdEClient->GetDefaultNamespaceDefL();
+	
+	// "contains" relation definition
+	CMdERelationDef& containsRelDef = namespaceDef.GetRelationDefL( 
+			Relations::KContainsLocation );
+
+	TInt count = iRemapItems.Count() - 1;
+	for( TInt i = count; i >= 0; i-- )
+		{
+		if( iRemapItems[i].iLocationId == 0 )
+			{
+			if( iRemapItems[i].iRelationId == 0 )
+				{
+				CMdERelation* relationObject = iMdEClient->NewRelationLC( containsRelDef,
+						iRemapItems[i].iObjectId, aLocationId, 0 );
+				iMdEClient->AddRelationL( *relationObject );
+				CleanupStack::PopAndDestroy( relationObject );
+				LOG("CLocationRemappingAO::UpdateRelationsL - new relation created");
+				}
+			else
+				{
+				CMdERelation* relationObject = iMdEClient->GetRelationL( iRemapItems[i].iRelationId );
+				relationObject->SetRightObjectIdL( aLocationId );
+				iMdEClient->UpdateRelationL( *relationObject );
+				LOG("CLocationRemappingAO::UpdateRelationsL - old relation updated");
+				}
+			iRemapItems.Remove( i );
+			}
+		}
+	LOG("CLocationRemappingAO::UpdateRelationsL - end");
+	}
+
+// --------------------------------------------------------------------------
+// TRemapItem constructor
+// --------------------------------------------------------------------------
+//
+TRemapItem::TRemapItem() :
+	iObjectId( 0 ),
+	iLocationId( 0 ),
+	iRelationId( 0 ),
+	iTime( 0 )
+	{
+	
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/server/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+locationmanagerserver.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/server/group/locationmanagerserver.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION         10.0
+TARGETTYPE      exe
+TARGET          locationmanagerserver.exe
+UID             0 0x200071BE
+
+#ifdef WINS
+EPOCHEAPSIZE    1000 2500000
+#else
+EPOCHEAPSIZE    1000 5000000
+#endif
+
+CAPABILITY 	    CAP_SERVER
+VENDORID 	    VID_DEFAULT
+
+USERINCLUDE     ../inc
+USERINCLUDE     ../../inc
+USERINCLUDE     ../../../inc
+USERINCLUDE     ../../locationtrail/inc
+
+SOURCEPATH      ../src
+SOURCE	    clocationmanagerserver.cpp
+SOURCE	    clocationmanagersession.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY 	    euser.lib 
+LIBRARY         efsrv.lib 
+LIBRARY         locationtrail.lib
+LIBRARY         lbs.lib 
+LIBRARY 	    etel3rdparty.lib 
+LIBRARY 	    centralrepository.lib 
+LIBRARY 	    mdeclient.lib 
+LIBRARY	    	mdccommon.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
+EPOCPROCESSPRIORITY background
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/server/inc/clocationmanagerserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,467 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Header file for Location Manager Server.
+*
+*/
+
+#ifndef C_CLOCATIONMANAGERSERVER_H
+#define C_CLOCATIONMANAGERSERVER_H
+
+
+#include <e32base.h>
+#include <etel3rdparty.h>
+#include <centralrepository.h>
+#include <locationdatatype.h>
+#include <locationeventdef.h>
+
+#include "rlocationtrail.h"
+#include "rlocationobjectmanipulator.h"
+#include "clocationrecord.h"
+#include "ctracklog.h"
+#include "mdeconstants.h"
+#include "mdsutils.h"
+#include "mdesession.h"
+#include "mdequery.h"
+#include "mderelationquery.h"
+#include "locationmanagerdefs.h"
+
+
+class CMdESession;
+
+// Total number of ranges
+const TUint KLocationManagerRangeCount = 1;
+
+// Definition of the ranges of IPC numbers
+const TInt KLocationManagerRanges[KLocationManagerRangeCount] = 
+    {
+    0,
+    }; 
+
+// Policy to implement for each of the above ranges        
+const TUint8 KLocationManagerElementsIndex[KLocationManagerRangeCount] = 
+    {
+    0,
+    };
+
+const CPolicyServer::TPolicyElement KLocationManagerPolicyElements[] = 
+    {
+    { _INIT_SECURITY_POLICY_C3(ECapabilityReadUserData,
+                               ECapabilityWriteUserData,
+                               ECapabilityLocation),
+                               CPolicyServer::EFailClient }
+    };
+
+// Package all the above together into a policy
+const CPolicyServer::TPolicy KLocationManagerPolicy =
+    {
+    CPolicyServer::EAlwaysPass,     // all attempts should pass
+    KLocationManagerRangeCount,     // number of ranges
+    KLocationManagerRanges,         // ranges array
+    KLocationManagerElementsIndex,  // elements<->ranges index
+    KLocationManagerPolicyElements, // array of elements
+    };
+    
+class CLocationRecord;
+//class CLocationWrite;
+
+/**
+*  A server class to initialize server. 
+*
+*  @since S60 3.1
+*/
+class CLocationManagerServer : public CPolicyServer,
+                               public MLocationTrailObserver,
+                               public MMdESessionObserver,
+                               public MMdEQueryObserver,
+                               public MMdEObjectObserver,
+                               public MGpxConversionObserver
+    {
+private:
+	struct TMessageQuery
+		{
+		CMdERelationQuery* iQuery;
+		const RMessage2& iMessage;
+		
+		TMessageQuery( CMdERelationQuery* aQuery, const RMessage2& aMessage ) 
+			:  iQuery ( aQuery ), iMessage( aMessage ) { }
+		};
+    
+public:
+    /**
+    * 2-phased constructor.
+    */
+    static CLocationManagerServer* NewLC();
+    
+    /**
+    * C++ destructor.
+    */ 
+    virtual ~CLocationManagerServer();
+  
+public:
+    /**
+    * From CServer2, creates a new session.
+    */
+    CSession2* NewSessionL( const TVersion& aVersion, 
+                            const RMessage2& aMessage ) const;
+
+public: // From MMdESessionObserver
+	void HandleSessionOpened(CMdESession& aSession, TInt aError);
+    void HandleSessionError(CMdESession& aSession, TInt aError);
+    
+public: // From MMdEQueryObserver
+	void HandleQueryNewResults(CMdEQuery& aQuery, TInt aFirstNewItemIndex, TInt aNewItemCount);
+	void HandleQueryCompleted(CMdEQuery& aQuery, TInt aError);
+
+public:
+    /**
+     * Increase session count.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */
+    void AddSession();
+    
+    /**
+     * Decrease session count, close server if count is zero.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */
+    void RemoveSession();
+
+public:
+    /**
+     * Starts to record locations to the trail.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */     
+    void StartGPSPositioningL( RLocationTrail::TTrailCaptureSetting aCaptureSetting );
+    
+    /**
+     * Stops trail recording.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */     
+    void StopGPSPositioningL();
+    
+    /**
+     * Gets the current state of the location trail.
+     * @since S60 3.1
+     * @param aState, The state of the trail is written to this param.
+     * @return None.
+     */     
+    void GetLocationTrailState( RLocationTrail::TTrailState& aState );
+    
+    /**
+     * Adds client's notification request to the request array.
+     * @since S60 3.1
+     * @param aNotifReq, asynchonous RMessage is stored to be completed
+     *                   when the state of the trail changes.
+     * @return None.
+     */     
+    void AddNotificationRequestL( const RMessage2& aNotifReq );
+    
+    /**
+     * Add client's track log notification request to the request array.
+     * @param aNotifReq, asynchonous RMessage is stored to be completed
+     *                   when the state of the track log changes.
+     * @return None.
+     */
+    void AddTrackLogNotificationRequestL( const RMessage2& aNotifReq );
+    
+    /**
+     * Cancel notification request from client.
+     * @since S60 3.1
+     * @param aHandle, A handle of the request to be cancelled.
+     * @return None.
+     */     
+    void CancelNotificationRequest( const TInt aHandle );
+    
+    /**
+     * Get a location by time stamp.
+     * @since S60 3.1
+     * @param aTimeStamp, A time stamp to get corresponding location.
+     * @param aPosition, Location info is written to this param.
+     * @return None.
+     */     
+    void GetLocationByTimeL( const TTime& aTimeStamp, 
+    						 TLocationData& aLocationData,
+                             /*TLocality& aPosition, 
+                             CTelephony::TNetworkInfoV1& aNetworkInfo,*/
+                             TLocTrailState& aState );
+
+    /**
+     * Get current location.
+     * @since S60 3.1
+     * @param aCurrLocReq 
+     * @return None.
+     */     
+    void RequestCurrentLocationL( const RMessage2& aCurrLocReq ); 
+
+    /**
+     * Cancel location request.
+     * @since S60 3.1
+     * @param aCurrLocReq 
+     * @return None.
+     */     
+    void CancelLocationRequest( const TInt aHandle ); 
+    
+    /**
+     * Cancel tracklog notification request.
+     * @param aHandle
+     * @return None.
+     */
+    void CLocationManagerServer::CancelTrackLogNotificationRequest( const TInt aHandle );
+
+    /**
+     * Get current network cell id.
+     * @since S60 3.1
+     * @param aCurrLocReq 
+     * @return None.
+     */     
+    void GetCurrentNetworkInfo( CTelephony::TNetworkInfoV1& aNetworkInfo );
+    
+    /**
+     * Create a location context object in DB and create relationships to objects
+     * whose id is given in the array.
+     * @param aLocationData
+     * @param aObjectId
+     */
+	void CreateLocationObjectL( const TLocationData& aLocationData, 
+    						   	   const TUint& aObjectId );
+	
+    /**
+     * Create a location context object in DB and create relationships to objects
+     * whose id is given in the array.
+     * Location information is taken from location trail
+     * @param aObjectId
+     */
+	void LocationSnapshotL( const TUint& aObjectId );
+	
+	/**
+	 * Deletes the relationship between an object and 
+	 * the location context object associated with it.
+	 * @since S60 3.2
+	 * @param aObjectId
+	 * @return None.
+	 */ 
+	void RemoveLocationObjectL(TUint& aObjectId);
+	void CopyLocationObjectL( TItemId aSource, const RArray<TItemId>& aTargets, TMessageQuery& aQuery );
+	void CopyLocationObjectL( const TDesC& aSource, const RArray<TPtrC>& aTargets, TMessageQuery& aQuery );
+	
+	TBool IsSessionReady();
+	
+	TItemId StartTrackLogL();
+	
+	void StopTrackLogL();
+	
+	void IsTrackLogRecording( TBool &aRec );
+	
+	TInt GetTrackLogStatus( TBool& aRecording, TPositionSatelliteInfo& aFixQuality);
+	
+	TInt DeleteTrackLogL(const TDesC& aUri);
+	
+	TInt TrackLogName(TFileName& aFileName);
+	
+	void GetCaptureSetting( RLocationTrail::TTrailCaptureSetting& aCaptureSetting );
+	
+	void AddGpxObserver( MGpxConversionObserver* aObserver );
+	
+	void InitCopyLocationByIdL( const RMessage2& aMessage );
+	void InitCopyLocationByURIL( const RMessage2& aMessage );
+
+public: // from MLocationTrailObserver.
+    /**
+     * Callback method to get notification about trail state change.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */
+    void LocationTrailStateChange();
+    
+    /**
+     * Callback method to return current location.
+     * @since S60 3.1
+     * @param aSatelliteInfo, includes position and satellite info.
+     * @param aNetworkInfo, network and cell info.
+     * @param aError.
+     * @return None.
+     */
+    void CurrentLocation( const TPositionSatelliteInfo& aSatelliteInfo,
+    		const CTelephony::TNetworkInfoV1& aNetworkInfo, const TInt aError );
+    
+    /**
+     * Callback method to notify observer of changes in GPS signal quality.
+     * @param aSatelliteInfo, includes position and satellite info
+     * @return None.
+     */
+    void GPSSignalQualityChanged( const TPositionSatelliteInfo& aSatelliteInfo );
+    
+public: // from MMdeObjectObserver
+	/**
+	 * Called to notify the observer that new objects has been
+	 * added/modified/removed in the metadata engine database.
+	 *
+	 * @param aSession session
+	 * @param aType defines if object was added/modified/remove
+	 * @param aObjectIdArray IDs of added object
+	 */
+	void HandleObjectNotification( CMdESession& aSession, 
+						TObserverNotificationType aType,
+						const RArray<TItemId>& aObjectIdArray );
+	
+public: // from MGpxConversionObserver
+
+	void GpxFileCreated( const TDesC& aFileName, TItemId aTagId, TReal32 aLength,
+			TTime aStart, TTime aEnd );
+
+private:    
+    /**
+    * C++ constructor.
+    */
+    CLocationManagerServer();
+    
+    /**
+    * 2nd phase constructor.
+    */
+    void ConstructL();
+    
+    void CopyLocationL( CMdEQuery& aQuery );
+
+    /**
+     * Go through all messages in lists, complete request
+     * with KErrCancel status and remove items from list.
+     */ 
+    void CancelRequests(RArray<RMessage2>& aMessagesList);
+    
+    
+    void CancelCopyRequests(RArray<TMessageQuery>& aMessageList);
+    
+    /**
+     * Create a new tracklog tag object in the database.
+     * @return TItemId tag ID in the database
+     */ 
+    TItemId CreateTrackLogTagL();
+    
+    /**
+     * Create a new tracklog object in the database and link tracklog tag to it.
+     * @param aTagId, tracklog tag id
+     */ 
+    void CreateTrackLogL( TItemId aTagId, const TDesC& aUri, TReal32 aLength,
+    		TTime aStart, TTime aEnd );
+    
+    /**
+     * Start listening for tracklog tag removals.
+     */
+    void StartListeningTagRemovalsL();
+    
+    /**
+     * Start listening for media object creations.
+     */
+    void StartListeningObjectCreationsL();
+    
+    /**
+     * Create a relationship between mediaobject(s) and a tracklog tag.
+     * @param aObjectIdArray, array of media object ids
+     */
+    void LinkObjectToTrackLogTagL( const RArray<TItemId>& aObjectIdArray );
+    
+    /**
+     * Callback function for positioning stop timer.
+     * @param aAny, a pointer to CLocationRecord object
+     * @return Error code
+     */
+    static TInt PositioningStopTimeout( TAny* aAny );
+    
+    /**
+     * Stops location trail and deletes the positioning stop timer.
+     */
+    void StopRecording();
+    
+    void CompleteNotifyRequest( TEventTypes aEventType, TInt aError );
+
+private:
+    /**
+     * A class for recording and storing locations.
+     * Own.
+     */
+    CLocationRecord* iLocationRecord;
+    
+    /**
+     * Pointer to TrackLog
+     * Own.
+     */
+    CTrackLog* iTrackLog;
+    
+    /**
+     * An active scheduler wait loop for waiting a session to MdE to open.
+     */
+    CActiveSchedulerWait* iASW;
+    
+    /**
+     * An array for asynchronous notification requests.
+     * Own.
+     */
+    RArray<RMessage2> iNotifReqs;
+    
+    /**
+     * An array for asynchronous location requests.
+     * Own.
+     */
+    RArray<RMessage2> iLocationReqs;
+    
+    /**
+     * An array for track log notification requests.
+     * Own.
+     */
+    RArray<RMessage2> iTrackLogNotifyReqs;
+    
+    /**
+     * An array for location copy requests.
+     * Own.
+     */
+    RArray<TMessageQuery> iCopyReqs;
+    
+    /**
+     * A session to Metadata Engine for creating and manipulating location objects.
+     */
+    CMdESession* iMdeSession;
+    
+    /** A relation query used to seach for related location objects */
+    CMdERelationQuery* iRelationQuery;
+    
+    /**
+     * A timer to stop location trail.
+     * Own.
+     */
+    CPeriodic* iTimer;
+    
+    TBool iClientSwitch;    
+    TInt iSessionCount;
+    TBool iSessionReady;  
+    
+    RArray<TItemId> iTargetObjectIds;
+    TItemId iTagId;
+    TInt iLocManStopDelay;
+    
+    RLocationTrail::TTrailCaptureSetting iCaptureSetting;
+    TBool iRemoveLocation;    
+    };
+
+
+#endif // C_CLOCATIONMANAGERSERVER_H
+
+// End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/server/inc/clocationmanagersession.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,195 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A session class for LocationManagerServer.
+*
+*/
+
+#ifndef C_CLOCATIONMANAGERSESSION_H
+#define C_CLOCATIONMANAGERSESSION_H
+
+#include <e32base.h>
+#include <etel3rdparty.h>
+
+class CLocationManagerServer;
+
+/**
+*  A session class for LocationManagerServer.
+*
+*  @since S60 3.1
+*/
+class CLocationManagerSession : public CSession2
+    {
+public:
+    /**
+     * C++ constructor.
+     */
+    CLocationManagerSession();
+    
+    /**
+     * From CSession2, passes the request forward to DispatchMessageL.
+     * @since S60 3.1
+     * @param aMessage, a message from client.
+     * @return None.
+     */
+    void ServiceL( const RMessage2& aMessage );
+    
+    /**
+     * Handles the request from client.
+     * @since S60 3.1
+     * @param aMessage, a message from client.
+     * @return None.
+     */
+    void DispatchMessageL( const RMessage2& aMessage );
+    
+    /**
+     * From CSession2 to add session to server's counter.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */
+    void CreateL();    
+
+private:
+    /**
+     * Start location recording.
+     */  
+    void StartLocationTrailL( const RMessage2& aMessage );
+
+    /**
+     * Stop location recordind.
+     */  
+    void StopLocationTrailL( const RMessage2& aMessage );
+
+    /**
+     * Get the current state of the location trail.
+     */
+    void GetLocationTrailStateL( const RMessage2& aMessage );
+
+    /**
+     * Add notification request for location trail's state changes.
+     */    
+    void NotifyLocationTrailStateChangeL( const RMessage2& aMessage );
+    
+    /**
+     * Cancel notification request.
+     */    
+    void CancelNotificationRequest( const RMessage2& aMessage );    
+
+    /**
+     * Get location by time stamp.
+     */
+    void RetrieveLocationL( const RMessage2& aMessage );
+
+    /**
+     * Get current location.
+     */
+    void CurrentLocationL( const RMessage2& aMessage );
+    
+    /**
+     * Cancel request for current location.
+     */
+    void CancelLocationRequest( const RMessage2& aMessage );
+    
+    /**
+     * Cancel request for tracklog notifications.
+     */
+    void CancelTrackLogNotificationRequest( const RMessage2& aMessage );
+    
+    /**
+     * Create new location object with given coordinates.
+     */ 
+    void CreateLocationObjectL( const RMessage2& aMessage );
+    
+    /**
+     * Create new location object from location trail.
+     */ 
+    void LocationSnapshotL( const RMessage2& aMessage );
+    
+    /**
+     * Remove location object by object ID
+     */ 
+    void RemoveLocationObjectL( const RMessage2& aMessage );
+    
+    /**
+     * Copy location data from one meadia object to 
+     * defined media objects by media object Id.
+     */ 
+    void CopyLocationDataByIdL( const RMessage2& aMessage );
+    
+    /**
+     * Copy location data from one media object to 
+     * defined media objects by media object Uri.
+     */ 
+    void CopyLocationDataByURIL( const RMessage2& aMessage );
+    
+    /**
+     * Start Track Log recording.
+     */
+    void StartTrackLogL( const RMessage2& aMessage );
+    
+    /**
+     * Stop Track Log recording.
+     */
+    void StopTrackLogL( const RMessage2& aMessage );
+    
+    /**
+     * Get Track Log recording status and GPS signal quality.
+     */
+    void GetTrackLogStatusL( const RMessage2& aMessage );
+    
+    /**
+     * Delete Track Log file.
+     */
+    void DeleteTrackLogL( const RMessage2& aMessage );
+
+    /**
+     * Get track-log recording status.
+     */
+    void IsTrackLogRecordingL( const RMessage2& aMessage );
+    
+    /**
+     * Get currently track log file name
+     */
+    void TrackLogNameL( const RMessage2& aMessage );
+    
+    /**
+     * Get changed gps quality info when it is really changed
+     */
+    void RegisterTrackLogObserver( const RMessage2& aMessage );
+    
+    void GetCaptureSettingL( const RMessage2& aMessage );
+
+private:
+    /**
+    * C++ destructor.
+    */
+    virtual ~CLocationManagerSession(); 
+
+    /*
+    * Reference to Location Manager Server.
+    */
+    CLocationManagerServer& Server();
+        
+private:
+    CBufFlat* iIdBuffer;
+    RMessage2 iMessage;
+
+    TInt iNotificationHandle;
+    TInt iLocationHandle;
+    TInt iTrackLogNotificationHandle;
+    };
+
+#endif // C_CLOCATIONMANAGERSESSION_H
+
+// End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/server/src/clocationmanagerserver.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1241 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A Server class for LocationManagerServer.
+*
+*/
+
+#include <e32debug.h>
+#include <w32std.h>
+
+#include "clocationmanagerserver.h"
+#include "clocationmanagersession.h"
+
+#include "locationtraildefs.h"
+#include "locationmanagerdebug.h"
+
+#include "mdesession.h"
+#include "mdenamespacedef.h"
+#include "mdeobjectdef.h"
+#include "mdepropertydef.h"
+#include "mdcserializationbuffer.h"
+
+using namespace MdeConstants;
+
+// --------------------------------------------------------------------------
+// RunServerL
+// Initialize and run the server.
+// --------------------------------------------------------------------------
+//
+static void RunServerL()
+    {
+    User::LeaveIfError( RThread().RenameMe( KLocServerName ) );
+
+    CActiveScheduler* scheduler = new (ELeave) CActiveScheduler;
+    CleanupStack::PushL( scheduler );
+    CActiveScheduler::Install( scheduler );
+    
+    CLocationManagerServer* server = CLocationManagerServer::NewLC();
+
+    RProcess::Rendezvous( KErrNone );
+    
+    CActiveScheduler::Start();
+    
+    CleanupStack::PopAndDestroy(server); 
+    CleanupStack::PopAndDestroy(scheduler); 
+    }
+
+// --------------------------------------------------------------------------
+// E32Main
+// Server process entry-point.
+// --------------------------------------------------------------------------
+//
+TInt E32Main()
+    {   
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    TInt ret( KErrNoMemory );
+    if( cleanup )
+        {
+        TRAP( ret, RunServerL() );
+        delete cleanup;
+        }
+    return ret;
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::NewLC
+// 2-phased constructor.
+// --------------------------------------------------------------------------
+//
+CLocationManagerServer* CLocationManagerServer::NewLC()
+    {
+    CLocationManagerServer* self = new (ELeave) CLocationManagerServer();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    return self;
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::CLocationManagerServer()
+// C++ constructor.
+// --------------------------------------------------------------------------
+//
+CLocationManagerServer::CLocationManagerServer() 
+    : CPolicyServer( CActive::EPriorityStandard, 
+                     KLocationManagerPolicy, 
+                     ESharableSessions ),
+                     iTimer( NULL ),
+			         iSessionReady( EFalse ),
+                     iTagId( 0 ),
+                     iLocManStopDelay( 0 ),
+                     iCaptureSetting( RLocationTrail::EOff ),
+                     iRemoveLocation( EFalse )
+    {
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::ConstructL
+// 2nd phase constructor.
+// --------------------------------------------------------------------------
+//
+void CLocationManagerServer::ConstructL()
+    {
+    LOG ("CLocationManagerServer::ConstructL() begin");
+    
+    StartL( KLocServerName );
+    
+    RProcess process;
+    process.SetPriority( EPriorityBackground );
+    process.Close();
+    
+    iASW = new (ELeave) CActiveSchedulerWait();
+    iMdeSession = CMdESession::NewL( *this );
+    iLocationRecord = CLocationRecord::NewL();
+    iTrackLog = CTrackLog::NewL();
+    
+    iASW->Start();
+    
+    iLocationRecord->SetObserver( this );
+    
+    iLocationRecord->SetAddObserver( iTrackLog );
+    
+    iTrackLog->AddGpxObserver( this );
+    
+    CRepository* repository = CRepository::NewLC( KRepositoryUid );
+	TInt err = repository->Get( KLocationTrailShutdownTimer, iLocManStopDelay );
+	CleanupStack::PopAndDestroy( repository );
+	
+    LOG1("CLocationManagerServer::ConstructL, iLocManStopDelay:%d", iLocManStopDelay);
+    
+    if ( err != KErrNone )
+    	{
+        LOG1("CLocationManagerServer::ConstructL, iLocManStopDelay err:%d", err);
+        iLocManStopDelay = KLocationTrailShutdownDelay;
+    	}
+    
+    LOG ("CLocationManagerServer::ConstructL() end");
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::~CLocationManagerServer()
+// C++ destructor.
+// --------------------------------------------------------------------------
+//
+CLocationManagerServer::~CLocationManagerServer()
+    {
+    delete iLocationRecord;    
+    delete iTrackLog;    
+    delete iTimer;
+    //delete iRelationQuery;
+    delete iASW;
+    delete iMdeSession;
+    
+    iTargetObjectIds.Close();
+    CancelRequests(iNotifReqs);
+    iNotifReqs.Close();
+    CancelRequests(iLocationReqs);
+    iLocationReqs.Close();
+    CancelRequests(iTrackLogNotifyReqs);
+    iTrackLogNotifyReqs.Close();
+    CancelCopyRequests(iCopyReqs);
+    iCopyReqs.Close();
+    iSessionCount = 0;
+    }
+// --------------------------------------------------------------------------
+// CLocationManagerServer::CompleteRequests()
+// --------------------------------------------------------------------------
+//
+void CLocationManagerServer::CancelRequests(RArray<RMessage2>& aMessageList)
+	{
+	const TInt count = aMessageList.Count();
+
+    for ( TInt i(0) ; i < count; i++ )
+        {
+        RMessage2& msg = aMessageList[i];
+        
+        if( !msg.IsNull() )
+        	{
+        	msg.Complete( KErrCancel );
+        	}
+        }
+    aMessageList.Reset();
+	}
+
+void CLocationManagerServer::CancelCopyRequests(RArray<TMessageQuery>& aMessageList)
+	{
+	const TInt count = aMessageList.Count();
+
+    for ( TInt i(0) ; i < count; i++ )
+        {
+        const RMessage2& msg = aMessageList[i].iMessage;
+        
+        if( !msg.IsNull() )
+        	{
+        	msg.Complete( KErrCancel );
+        	}
+        }
+    aMessageList.Reset();
+	}
+
+
+void CLocationManagerServer::HandleSessionOpened(CMdESession& /*aSession*/, TInt aError)
+	{
+	if ( iASW->IsStarted() )
+		{
+		iASW->AsyncStop();
+		}
+	
+	if ( KErrNone == aError )
+		{
+		iSessionReady = ETrue;
+		TRAP_IGNORE( iTrackLog->StartRecoveryL() );
+	    iLocationRecord->SetMdeSession( iMdeSession );
+		}
+	else
+		{
+		iSessionReady = EFalse;
+		delete iMdeSession;
+		iMdeSession = NULL;
+		}
+	}
+
+void CLocationManagerServer::HandleSessionError(CMdESession& /*aSession*/, TInt /*aError*/)
+	{
+	iSessionReady = EFalse;
+	delete iMdeSession;
+	iMdeSession = NULL;
+
+	if ( iASW->IsStarted() )
+		{
+		iASW->AsyncStop();
+		}	
+	}
+
+TBool CLocationManagerServer::IsSessionReady()
+	{
+	return iSessionReady;
+	}
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::NewSessionL
+// from CServer2, creates a new session.
+// --------------------------------------------------------------------------
+//
+CSession2* CLocationManagerServer::NewSessionL( const TVersion& aVersion, 
+                                             const RMessage2& /*aMsg*/ ) const
+    {
+    TBool supported = User::QueryVersionSupported( TVersion( 
+                                                KLocationManagerServerMajor,
+                                                KLocationManagerServerMinor,
+                                                KLocationManagerServerBuild ),
+                                                aVersion );
+    if( !supported )
+        {
+        User::Leave( KErrNotSupported );
+        }
+
+    return new (ELeave) CLocationManagerSession();  
+    }   
+    
+// --------------------------------------------------------------------------
+// CLocationManagerServer::AddSession
+// --------------------------------------------------------------------------
+//  
+void CLocationManagerServer::AddSession()  
+    {
+    iSessionCount++;
+    }
+  
+// --------------------------------------------------------------------------
+// CLocationManagerServer::RemoveSession
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerServer::RemoveSession()
+    {
+    iSessionCount--;
+    if ( !iSessionCount )
+        {
+        CActiveScheduler::Stop();
+        }
+    }    
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::StartGPSPositioningL
+// --------------------------------------------------------------------------
+//
+void CLocationManagerServer::StartGPSPositioningL( RLocationTrail::TTrailCaptureSetting aCaptureSetting )
+    {
+    if ( aCaptureSetting == RLocationTrail::EOff )
+    	{
+    	return;
+    	}
+    
+    iCaptureSetting = aCaptureSetting;
+    
+    RLocationTrail::TTrailState state;
+    GetLocationTrailState( state );
+    if ( state != RLocationTrail::ETrailStopped && state != RLocationTrail::ETrailStopping )
+        {
+        User::Leave( KErrAlreadyExists );
+        }
+    if ( iTimer )
+    	{
+    	delete iTimer;
+    	iTimer = NULL;
+    	}
+    
+    iLocationRecord->StartL( aCaptureSetting );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::StopGPSPositioning
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerServer::StopGPSPositioningL()
+    {
+    iCaptureSetting = RLocationTrail::EOff;
+    
+    RLocationTrail::TTrailState state;
+    GetLocationTrailState( state );
+    if( state == RLocationTrail::ETrailStarted || state == RLocationTrail::ETrailStarting )
+    	{
+    	iLocationRecord->Stop();
+    	}
+    else if ( state != RLocationTrail::ETrailStopped && state != RLocationTrail::ETrailStopping )
+        {
+        if ( iLocationRecord->RemappingNeeded() )
+        	{
+        	TRAPD( error, iTimer = CPeriodic::NewL( CActive::EPriorityStandard ) );
+        	if ( error != KErrNone )
+        		{
+        		// If timer can't be created we stop the location trail immediately.
+        		iLocationRecord->Stop();
+        		StopTrackLogL();
+        		return;
+        		}
+        	iLocationRecord->SetStateToStopping();
+        	iTimer->Start( iLocManStopDelay * 1000000, 0, TCallBack( PositioningStopTimeout, this ) );
+        	}
+        else 
+        	{
+        	iLocationRecord->Stop();
+        	}
+        }
+    
+    // Always stop tracklog.
+    StopTrackLogL();
+    }
+
+// --------------------------------------------------------------------------
+// CLocationUtilityServer::StopRecording
+// --------------------------------------------------------------------------
+//
+void CLocationManagerServer::StopRecording()
+	{
+	iLocationRecord->Stop();
+	delete iTimer;
+	iTimer = NULL;
+	}
+
+// --------------------------------------------------------------------------
+// CLocationUtilityServer::PositioningStopTimeout
+// --------------------------------------------------------------------------
+//
+TInt CLocationManagerServer::PositioningStopTimeout( TAny* aAny )
+	{
+	CLocationManagerServer* self = STATIC_CAST( CLocationManagerServer*, aAny );
+	self->StopRecording();
+	
+	return KErrNone;
+	}
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::GetLocationTrailState
+// --------------------------------------------------------------------------
+//
+void CLocationManagerServer::GetLocationTrailState( RLocationTrail::TTrailState& aState )
+    {
+    iLocationRecord->LocationTrailState( aState );
+    }
+    
+// --------------------------------------------------------------------------
+// CLocationManagerServer::AddNotificationRequestL
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerServer::AddNotificationRequestL( const RMessage2& aNotifReq )
+    {
+    LOG( "CLocationManagerServer::AddNotificationRequestL(), begin" );
+    iNotifReqs.AppendL( aNotifReq );
+    LOG( "CLocationManagerServer::AddNotificationRequestL(), end" );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::AddTrackLogNotificationRequestL
+// --------------------------------------------------------------------------
+//
+void CLocationManagerServer::AddTrackLogNotificationRequestL( const RMessage2& aNotifReq )
+	{
+	iTrackLogNotifyReqs.AppendL( aNotifReq );
+	}
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::CancelNotificationRequest
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerServer::CancelNotificationRequest( const TInt aHandle )
+    {
+    LOG( "CLocationManagerServer::CancelNotificationRequest(), begin" );
+    
+    const TInt count = iNotifReqs.Count();
+    for ( TInt i = count; --i >= 0; )
+        {
+        RMessage2& msg = iNotifReqs[i];
+
+        if( msg.IsNull() )
+        	{
+        	iNotifReqs.Remove(i);
+        	continue;
+        	}
+
+        if ( msg.Handle() == aHandle )
+            {
+           	msg.Complete( KErrCancel );
+            iNotifReqs.Remove(i);
+            break;
+            }
+        }
+    LOG( "CLocationManagerServer::CancelNotificationRequest(), end" );
+    }
+ 
+// --------------------------------------------------------------------------
+// CLocationManagerServer::GetLocationByTimeL
+// --------------------------------------------------------------------------
+//   
+void CLocationManagerServer::GetLocationByTimeL( const TTime& aTimeStamp, 
+												 TLocationData& aLocationData,
+                                                 TLocTrailState& aState )
+    {
+    iLocationRecord->GetLocationByTimeL( aTimeStamp,
+    									 aLocationData,
+                                         aState );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::RequestCurrentLocationL
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerServer::RequestCurrentLocationL( const RMessage2& aCurrLocReq )
+    {
+    iLocationReqs.AppendL( aCurrLocReq );
+    iLocationRecord->RequestLocationL();
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::CancelLocationRequest
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerServer::CancelLocationRequest( const TInt aHandle )
+    {
+    LOG( "CLocationManagerServer::CancelLocationRequest(), begin" );
+    
+    const TInt count = iLocationReqs.Count();
+    for ( TInt i = count; --i >= 0; )
+        {
+        RMessage2& msg = iLocationReqs[i];
+        
+        if( msg.IsNull() )
+        	{
+        	iLocationReqs.Remove(i);
+        	continue;
+        	}
+        
+        if ( msg.Handle() == aHandle )
+            {
+            msg.Complete( KErrCancel );
+            iLocationReqs.Remove(i);
+            break;
+            }
+        }
+    if ( !iLocationReqs.Count() )
+        {
+        iLocationRecord->CancelLocationRequest();
+        }
+    LOG( "CLocationManagerServer::CancelLocationRequest(), end" );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::GetCurrentCellId
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerServer::GetCurrentNetworkInfo( CTelephony::TNetworkInfoV1& aNetworkInfo )
+    {
+    iLocationRecord->GetNetworkInfo( aNetworkInfo );
+    }    
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::LocationTrailStateChange
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerServer::LocationTrailStateChange()
+    {
+    LOG( "CLocationManagerServer::LocationTrailStateChange(), begin" );
+
+    for ( TInt i = iNotifReqs.Count(); --i >= 0; )
+        {
+        RMessage2& msg = iNotifReqs[i];
+        
+        if( !msg.IsNull() )
+        	{
+        	msg.Complete( KErrNone );
+        	}
+        }
+    iNotifReqs.Reset();
+    LOG( "CLocationManagerServer::LocationTrailStateChange(), end" );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::CurrentLocation
+// --------------------------------------------------------------------------
+//
+void CLocationManagerServer::CurrentLocation( const TPositionSatelliteInfo& aSatelliteInfo, 
+											  const CTelephony::TNetworkInfoV1& aNetworkInfo,
+                                              const TInt aError )
+    {
+    LOG( "CLocationManagerServer::CurrentLocation(), begin" );
+    const TInt KParamLocationData = 0;
+    
+    TLocationData locationData;
+    aSatelliteInfo.GetPosition( locationData.iPosition );
+    aSatelliteInfo.GetCourse( locationData.iCourse );
+    locationData.iNetworkInfo = aNetworkInfo;
+    locationData.iSatellites = aSatelliteInfo.NumSatellitesUsed();
+    
+    TPckg<TLocationData> wrapLocationData( locationData );
+
+    if ( aError == KErrNone )
+    	{
+    	for ( TInt i = iLocationReqs.Count(); --i >= 0; )
+    		{
+    		RMessage2& msg = iLocationReqs[i];
+
+    		if( !msg.IsNull() )
+    			{
+        		TInt err = msg.Write( KParamLocationData, wrapLocationData );
+        		LOG1( "CLocationManagerServer::CurrentLocation() location data written with error:%d", err);
+        		msg.Complete( err );
+    			}
+    		}
+    	}
+    else
+    	{
+    	for ( TInt i = iLocationReqs.Count(); --i >= 0; )
+    		{
+    		RMessage2& msg = iLocationReqs[i];
+    		
+    		LOG1( "CLocationManagerServer::CurrentLocation() completed with error:%d", aError);
+    		
+    		if( !msg.IsNull() )
+    			{
+    			msg.Complete( aError );
+    			}
+    		}
+    	}        
+
+	iLocationReqs.Reset();
+
+    LOG( "CLocationManagerServer::CurrentLocation(), end" );    
+    }
+
+void CLocationManagerServer::GPSSignalQualityChanged( const TPositionSatelliteInfo& aSatelliteInfo )
+	{
+	LOG( "CLocationManagerServer::GPSSignalQualityChanged" );
+	const TInt KFixParam = 0;
+	const TInt KPositionInfoParam = 1;
+	const TInt KEventTypeParam = 2;
+	TBool fix( ETrue );
+	TPosition tmpPosition;
+	TEventTypes eventType = ESignalChanged;
+	
+	TPckg<TPositionSatelliteInfo> wrapSatelliteInfo( aSatelliteInfo );
+	TPckg<TBool> wrapFix( fix );
+	TPckg<TEventTypes> wrapEventType( eventType );
+	
+	aSatelliteInfo.GetPosition( tmpPosition );
+	if ( Math::IsNaN( tmpPosition.Latitude() ) || Math::IsNaN( tmpPosition.Longitude() ) )
+		{
+		fix = EFalse;
+		LOG( "CLocationManagerServer::GPSSignalQualityChanged - no GPS fix");
+		}
+	
+	TInt error( KErrNone );
+	const TInt count = iTrackLogNotifyReqs.Count();
+	for ( TInt i( count ); --i >= 0; )
+		{
+		RMessage2& msg = iTrackLogNotifyReqs[i];
+		
+		if( !msg.IsNull() )
+			{
+			LOG1( "CLocationManagerServer::GPSSignalQualityChanged request %d", i );
+			error = msg.Write( KFixParam, wrapFix );
+			if( KErrNone == error )
+				{
+				error = msg.Write( KPositionInfoParam, wrapSatelliteInfo );
+				if( KErrNone == error )
+					{
+					error = msg.Write( KEventTypeParam, wrapEventType );
+					}
+				}
+			LOG1( "CLocationManagerServer::GPSSignalQualityChanged error: %d", error );
+			msg.Complete( error );
+			}
+		}
+	iTrackLogNotifyReqs.Reset();
+	}
+
+
+
+void CLocationManagerServer::CancelTrackLogNotificationRequest( const TInt aHandle )
+	{
+	LOG( "CLocationManagerServer::CancelTrackLogNotificationRequest(), begin" );
+    
+    const TInt count = iTrackLogNotifyReqs.Count();
+    for ( TInt i(count); --i >= 0; )
+        {
+        RMessage2& msg = iTrackLogNotifyReqs[i];
+        
+        if( msg.IsNull() )
+        	{
+        	iTrackLogNotifyReqs.Remove(i);
+        	continue;
+        	}
+        
+        if ( msg.Handle() == aHandle )
+            {
+            msg.Complete( KErrCancel );
+            iTrackLogNotifyReqs.Remove(i);
+            break;
+            }
+        }
+
+    LOG( "CLocationManagerServer::CancelTrackLogNotificationRequest(), end" );
+	}
+
+void CLocationManagerServer::CreateLocationObjectL( const TLocationData& aLocationData,
+													const TUint& aObjectId )
+	{
+	if ( !IsSessionReady() )
+		{
+		User::Leave( KErrNotReady );
+		}
+	
+	iLocationRecord->CreateLocationObjectL( aLocationData, aObjectId );
+	}
+
+void CLocationManagerServer::LocationSnapshotL( const TUint& aObjectId )
+	{
+	if ( !IsSessionReady() )
+		{
+		User::Leave( KErrNotReady );
+		}
+	iLocationRecord->LocationSnapshotL( aObjectId );
+	}
+
+// --------------------------------------------------------------------------
+// CLocationManagerServer::RemoveLocationObjectL
+// --------------------------------------------------------------------------
+//
+void CLocationManagerServer::RemoveLocationObjectL(TUint& aObjectId)
+	{
+	if ( !IsSessionReady() )
+		{
+		User::Leave( KErrNotReady );
+		}
+	
+	CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+	
+	iRelationQuery = iMdeSession->NewRelationQueryL( namespaceDef, this );
+    iRelationQuery->SetResultMode( EQueryResultModeId );
+    iRelationQuery->Conditions().SetOperator( ELogicConditionOperatorAnd );
+    
+    CMdERelationCondition& filterCondLeft = iRelationQuery->Conditions().AddRelationConditionL( 
+    		ERelationConditionSideLeft );
+
+    // The left object in relation must have this ID.
+    filterCondLeft.LeftL().AddObjectConditionL( aObjectId );
+    
+    // Right object in relation must be a location object.
+    CMdERelationCondition& filterCondRight = iRelationQuery->Conditions().AddRelationConditionL( 
+    		ERelationConditionSideRight );
+    CMdEObjectDef& rightObjDef = namespaceDef.GetObjectDefL( Location::KLocationObject );
+    filterCondRight.RightL().AddObjectConditionL( rightObjDef );
+	
+    iRemoveLocation = ETrue;
+    iRelationQuery->FindL( 1, 1 );
+	}
+
+void CLocationManagerServer::CopyLocationObjectL( TItemId aSource, 
+		const RArray<TItemId>& aTargets, TMessageQuery& aMessageQuery )
+	{
+	if( aTargets.Count() <= 0 )
+		{
+		aMessageQuery.iMessage.Complete( KErrNotFound );
+		return;
+		}
+	
+	if ( !IsSessionReady() )
+		{
+		User::Leave( KErrNotReady );
+		}
+	
+	CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+	
+	TMdEObject obj;
+	iMdeSession->CheckObjectL( obj, aSource, &namespaceDef );
+
+    aMessageQuery.iQuery = iMdeSession->NewRelationQueryL( namespaceDef, this );
+    aMessageQuery.iQuery->SetResultMode( EQueryResultModeItem );
+    aMessageQuery.iQuery->Conditions().SetOperator( ELogicConditionOperatorAnd );
+    
+    CMdERelationCondition& filterCondLeft = aMessageQuery.iQuery->Conditions()
+    	.AddRelationConditionL( ERelationConditionSideLeft );
+
+    // The left object in relation must have this ID.
+    filterCondLeft.LeftL().AddObjectConditionL( aSource );
+    
+    // Right object in relation must be a location object.
+    CMdERelationCondition& filterCondRight = aMessageQuery.iQuery->Conditions()
+    	.AddRelationConditionL( ERelationConditionSideRight );
+    CMdEObjectDef& rightObjDef = namespaceDef.GetObjectDefL( Location::KLocationObject );
+    filterCondRight.RightL().AddObjectConditionL( rightObjDef );
+	
+    if( iTargetObjectIds.Count() <= 0 )
+    	{
+    	TInt err = 0;
+	    const TInt count = aTargets.Count();
+	    for( TInt i = 0 ; i < count ; i++ )
+	    	{
+	    	TRAP( err, iMdeSession->CheckObjectL( obj, aTargets[i], &namespaceDef ) );
+	    	if ( err == KErrNone )
+	    		{
+		    	iTargetObjectIds.AppendL( aTargets[i] );
+	    		}
+	    	}
+    	}
+    
+    iCopyReqs.AppendL( aMessageQuery );
+    
+    if ( iTargetObjectIds.Count() > 0 )
+    	{
+        aMessageQuery.iQuery->FindL( 1, 1 );
+    	}
+    else
+    	{
+    	aMessageQuery.iMessage.Complete( KErrNotFound );
+    	iCopyReqs.Remove( iCopyReqs.Find( aMessageQuery ) );
+    	}
+	}
+
+void CLocationManagerServer::CopyLocationObjectL( const TDesC& aSource, 
+		const RArray<TPtrC>& aTargets, TMessageQuery& aQuery )
+	{
+	CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+	TMdEObject obj;
+	iMdeSession->CheckObjectL( obj, aSource, &namespaceDef );
+	TItemId source = obj.Id();
+	const TInt count = aTargets.Count();
+	TInt err = 0;
+	for( TInt i = 0; i < count; i++ )
+		{
+		TRAP(err, iMdeSession->CheckObjectL( obj, aTargets[i], &namespaceDef )); 
+		if( err == KErrNone )
+			{
+			iTargetObjectIds.AppendL( obj.Id() );
+			}
+		}
+
+	CopyLocationObjectL( source, iTargetObjectIds, aQuery );
+	}
+
+void CLocationManagerServer::HandleQueryNewResults( CMdEQuery& /*aQuery*/, 
+		TInt /*aFirstNewItemIndex*/, TInt /*aNewItemCount*/ )
+	{
+	}
+
+void CLocationManagerServer::HandleQueryCompleted( CMdEQuery& aQuery, TInt aError )
+	{	
+	if ( iRemoveLocation )
+		{
+		if( aQuery.Count() > 0 && aError == KErrNone )
+			{
+			TRAPD( err, iMdeSession->RemoveRelationL( aQuery.ResultId( 0 ), &aQuery.NamespaceDef() ) );			
+			if ( err != KErrNone )
+				{
+				LOG1( "CLocationManagerServer::HandleQueryCompleted error: %d", err );
+				}
+			}
+		
+		iRemoveLocation = EFalse;
+		}
+	else
+		{
+		// When results CopyLocationL handles completion of message
+		if( aQuery.Count() > 0 && aError == KErrNone )
+			{
+			TRAP_IGNORE( CopyLocationL( aQuery ) );
+			}
+		// otherwise find correct message and complete it
+		else
+			{
+			for ( TInt i = iCopyReqs.Count() - 1; i >= 0; --i  )
+				{
+				if ( iCopyReqs[i].iQuery == &aQuery )
+					{
+					if( aError == KErrNone )
+						{
+						aError = KErrNotFound;
+						}
+					iCopyReqs[i].iMessage.Complete( aError );
+					delete iCopyReqs[i].iQuery;
+					iCopyReqs.Remove( i );
+					break;
+					}
+				}
+			}
+		}
+
+	iTargetObjectIds.Reset();
+	}
+
+void CLocationManagerServer::CopyLocationL( CMdEQuery& aQuery )
+	{
+	CMdEObjectDef& locationDef = aQuery.NamespaceDef().GetObjectDefL( Location::KLocationObject );
+
+    CMdERelation& result = static_cast<CMdERelation&>( aQuery.ResultItem( 0 ) );
+    TItemId rightId = result.RightObjectId();
+    CMdEObject* sourceLocation = iMdeSession->GetObjectL( rightId, locationDef );
+    CleanupStack::PushL( sourceLocation );
+    
+    // "contains" relation definition
+    CMdERelationDef& containsRelDef = aQuery.NamespaceDef().GetRelationDefL( 
+    		Relations::KContainsLocation );
+    
+    const TInt count = iTargetObjectIds.Count();
+    for( TInt i=0;i<count;i++ )
+    	{
+        CMdERelation* relationObject = iMdeSession->NewRelationLC( containsRelDef, iTargetObjectIds[i],
+        		rightId, 0 );
+        
+        iMdeSession->AddRelationL( *relationObject );
+        
+        CleanupStack::PopAndDestroy( relationObject );
+    	}
+    CleanupStack::PopAndDestroy( sourceLocation );
+    
+    for ( TInt i = iCopyReqs.Count() - 1; i >= 0; --i  )
+    	{
+    	if ( iCopyReqs[i].iQuery == &aQuery )
+    		{
+    		iCopyReqs[i].iMessage.Complete( KErrNone );
+    		delete iCopyReqs[i].iQuery;
+    		iCopyReqs.Remove( i );
+    		break;
+    		}
+    	}
+	}
+
+void CLocationManagerServer::InitCopyLocationByIdL( const RMessage2& aMessage )
+	{
+	const TInt KParamSourceId = 0;
+	const TInt KParamTargetIds = 1;
+	TItemId sourceId = 0;
+	RArray<TItemId> targetIds;
+	CleanupClosePushL(targetIds);
+	
+	// read TUint& aSourceId from request
+	TPckg<TItemId> locSourceId( sourceId );	
+	aMessage.ReadL(KParamSourceId, locSourceId);
+	
+	const TInt KParamTargetIdsLength = aMessage.GetDesLength( KParamTargetIds );
+	LOG1("CLocationManagerServer::InitCopyLocationL KParamTargetIdsLength:%d", KParamTargetIdsLength);
+	if ( KParamTargetIdsLength > 0 )
+	    {
+	    HBufC8* paramBuf = HBufC8::NewLC( KParamTargetIdsLength );
+	    TPtr8 ptr( paramBuf->Des() );
+	    aMessage.ReadL( KParamTargetIds, ptr );
+	    
+	    DeserializeArrayL( ptr, targetIds );
+	    
+	    TMessageQuery q( NULL, aMessage );
+	    
+	    LOG1("CLocationManagerServer::InitCopyLocationL ID count:%d", targetIds.Count());
+	    	
+	    CopyLocationObjectL( sourceId, targetIds, q );
+	    
+	    CleanupStack::PopAndDestroy(paramBuf);
+	    }
+	CleanupStack::PopAndDestroy(&targetIds);
+	}
+
+void CLocationManagerServer::InitCopyLocationByURIL( const RMessage2& aMessage )
+	{
+    LOG( "CLocationManagerSession::CopyLocationDataByUriL begin" );
+    const TInt KParamSourceUri = 0;
+    const TInt KParamTargetUris = 1;
+
+    const TInt KParamSourceLength = aMessage.GetDesLength(KParamSourceUri);
+    if (KParamSourceLength > 0)
+    	{
+    	// read TDesC& aSourceURI from request
+	    HBufC* sourceUriBuf = HBufC::NewLC( KParamSourceLength );
+	    TPtr ptrSource( sourceUriBuf->Des() );
+	    aMessage.ReadL( KParamSourceUri, ptrSource );
+	    
+	    const TInt KParamTargetUrisLength = aMessage.GetDesLength( KParamTargetUris );
+	    LOG1("CLocationManagerSession::CopyLocationDataByUriL KParamTargetUrisLength:%d", KParamTargetUrisLength);
+	    if ( KParamTargetUrisLength > 0 )
+	        {
+		    RArray<TPtrC> targetUris;
+		    CleanupClosePushL(targetUris);
+
+		    CMdCSerializationBuffer* uriBuffer = CMdCSerializationBuffer::NewLC( aMessage, KParamTargetUris );
+		    
+		    TInt32 uriCount = 0;
+		    uriBuffer->ReceiveL( uriCount );
+		    
+		    targetUris.ReserveL( uriCount );
+
+		    // deserialize URIs
+		    for( TInt i = 0; i < uriCount; i++ )
+		    	{
+		    	targetUris.Append( uriBuffer->ReceivePtr16L() );
+		    	}
+		    
+	        LOG1("CLocationManagerSession::CopyLocationDataByUriL ID count:%d", targetUris.Count());
+	        
+	        TMessageQuery q( NULL, aMessage );
+
+	        CopyLocationObjectL( sourceUriBuf->Des(), targetUris, q );
+
+		    CleanupStack::PopAndDestroy( uriBuffer );
+	        CleanupStack::PopAndDestroy( &targetUris );
+	        }
+	    CleanupStack::PopAndDestroy( sourceUriBuf );	    
+    	}
+    
+    LOG( "CLocationManagerSession::CopyLocationDataByUriL end" );
+	}
+
+TItemId CLocationManagerServer::StartTrackLogL()
+	{
+	if ( iTrackLog->IsRecording() )
+		{
+		User::Leave( KErrInUse );
+		}
+	
+	iTagId = CreateTrackLogTagL();
+	iTrackLog->StartRecordingL( iTagId );
+	
+	StartListeningObjectCreationsL();	
+	StartListeningTagRemovalsL();
+	
+	CompleteNotifyRequest( EStarted, KErrNone );
+	
+	return iTagId;
+	}
+
+void CLocationManagerServer::StopTrackLogL()
+	{
+	if ( iTrackLog->IsRecording() )
+		{
+		iTrackLog->StopRecordingL();
+		
+		CompleteNotifyRequest( EStopped, KErrNone );
+		
+		// stop observers
+		TRAP_IGNORE( iMdeSession->RemoveObjectObserverL( *this, &iMdeSession->GetDefaultNamespaceDefL()) );
+		TRAP_IGNORE( iMdeSession->RemoveObjectObserverL( *this, &iMdeSession->GetDefaultNamespaceDefL()) );
+		}
+	}
+
+void CLocationManagerServer::CompleteNotifyRequest( TEventTypes aEventType, TInt aError )
+	{
+	const TInt KEventTypeParam = 2;
+	TPckg<TEventTypes> wrapEventType( aEventType );
+	
+	const TInt count = iTrackLogNotifyReqs.Count();
+	for ( TInt i( count ); --i >= 0; )
+		{
+		RMessage2& msg = iTrackLogNotifyReqs[i];
+		
+		if( !msg.IsNull() )
+			{
+			msg.Write( KEventTypeParam, wrapEventType );
+			msg.Complete( aError );
+			}
+		}
+	iTrackLogNotifyReqs.Reset();
+	}
+
+void CLocationManagerServer::IsTrackLogRecording( TBool &aRec )
+	{
+	aRec = iTrackLog->IsRecording();
+	}
+
+void CLocationManagerServer::GpxFileCreated( const TDesC& aFileName, TItemId aTagId,
+		TReal32 aLength, TTime aStart, TTime aEnd )
+	{
+	TRAP_IGNORE( CreateTrackLogL( aTagId, aFileName, aLength, aStart, aEnd ) );
+	}
+
+TItemId CLocationManagerServer::CreateTrackLogTagL()
+	{
+	if ( !IsSessionReady() )
+		{
+		User::Leave( KErrNotReady );
+		}
+	
+	CMdEObjectDef& trackLogTagDef = iMdeSession->GetDefaultNamespaceDefL()
+		.GetObjectDefL( Tag::KTagObject );
+	
+	CMdEObject* trackLogTag = iMdeSession->NewObjectLC( trackLogTagDef, KNullDesC );
+	
+	// Mandatory parameters for any object.
+	CMdEPropertyDef& creationDef = trackLogTagDef.GetPropertyDefL( Object::KCreationDateProperty );
+	CMdEPropertyDef& modifiedDef = trackLogTagDef.GetPropertyDefL( Object::KLastModifiedDateProperty );
+	CMdEPropertyDef& sizeDef = trackLogTagDef.GetPropertyDefL( Object::KSizeProperty );
+	CMdEPropertyDef& itemTypeDef = trackLogTagDef.GetPropertyDefL( Object::KItemTypeProperty );
+	
+	TTime timestamp( 0 );
+	timestamp.UniversalTime();
+
+	// required object properties
+	trackLogTag->AddTimePropertyL( creationDef, timestamp );
+	trackLogTag->AddTimePropertyL( modifiedDef, timestamp );
+	trackLogTag->AddUint32PropertyL( sizeDef, 0 );
+	trackLogTag->AddTextPropertyL( itemTypeDef, Tag::KTagItemType );
+	
+	TItemId tagId = iMdeSession->AddObjectL( *trackLogTag );
+	
+	CleanupStack::PopAndDestroy( trackLogTag );
+	
+	return tagId;
+	}
+
+void CLocationManagerServer::CreateTrackLogL( TItemId aTagId, const TDesC& aUri, TReal32 aLength,
+		TTime aStart, TTime aEnd )
+	{
+	if ( !IsSessionReady() )
+		{
+		User::Leave( KErrNotReady );
+		}
+
+	CMdEObjectDef& trackLogDef = iMdeSession->GetDefaultNamespaceDefL().GetObjectDefL( 
+			TrackLog::KTrackLogObject );
+
+	CMdEObject* trackLog = iMdeSession->NewObjectLC( trackLogDef, aUri );
+
+	// Mandatory parameters for any object.
+	CMdEPropertyDef& creationDef = trackLogDef.GetPropertyDefL( Object::KCreationDateProperty );
+	CMdEPropertyDef& modifiedDef = trackLogDef.GetPropertyDefL( Object::KLastModifiedDateProperty );
+	CMdEPropertyDef& sizeDef = trackLogDef.GetPropertyDefL( Object::KSizeProperty );
+	CMdEPropertyDef& itemTypeDef = trackLogDef.GetPropertyDefL( Object::KItemTypeProperty );
+	
+	// Tracklog specific properties.
+	CMdEPropertyDef& lengthDef = trackLogDef.GetPropertyDefL( TrackLog::KLengthProperty );
+	CMdEPropertyDef& startTimeDef = trackLogDef.GetPropertyDefL( TrackLog::KStartTimeProperty );
+	CMdEPropertyDef& stopTimeDef = trackLogDef.GetPropertyDefL( TrackLog::KStopTimeProperty );
+
+	TTime timestamp( 0 );
+	timestamp.UniversalTime();
+
+	trackLog->AddTimePropertyL( creationDef, timestamp );
+	trackLog->AddTimePropertyL( modifiedDef, timestamp );
+	trackLog->AddUint32PropertyL( sizeDef, 0 );
+	trackLog->AddTextPropertyL( itemTypeDef, TrackLog::KTrackLogItemType );
+	trackLog->AddUint32PropertyL( lengthDef, TUint32( aLength ));
+	trackLog->AddTimePropertyL( startTimeDef, aStart );
+	trackLog->AddTimePropertyL( stopTimeDef, aEnd );
+	
+	TItemId trackLogId = iMdeSession->AddObjectL( *trackLog );
+	
+	CMdERelationDef& containsRelDef = iMdeSession->GetDefaultNamespaceDefL().GetRelationDefL( 
+			Relations::KContains );
+    
+    CMdERelation* relationObject = iMdeSession->NewRelationLC( containsRelDef, aTagId,
+    		trackLogId, 0 );
+    
+    iMdeSession->AddRelationL( *relationObject );
+    
+    CleanupStack::PopAndDestroy( relationObject );
+    CleanupStack::PopAndDestroy( trackLog );
+	}
+
+TInt CLocationManagerServer::GetTrackLogStatus( TBool& aRecording, TPositionSatelliteInfo& aFixQuality)
+	{
+	if ( !iTrackLog )
+		{
+		return KErrNotFound;
+		}
+	
+	iTrackLog->GetStatus( aRecording, aFixQuality );
+	
+	return KErrNone;
+	}
+
+TInt CLocationManagerServer::DeleteTrackLogL( const TDesC& aUri )
+	{
+    LOG( "CLocationManagerServer::DeleteTrackLogL enter" );
+    
+    // remove tracklog mde object 
+    CMdEObject* mdeObject = iMdeSession->GetObjectL( aUri );
+	if ( mdeObject )
+    	{
+    	TItemId objectId = mdeObject->Id();
+	    delete mdeObject;
+	    
+		TTime time( 0 );
+		CMdENamespaceDef& nsDef = iMdeSession->GetDefaultNamespaceDefL();
+		CMdEEventDef& eventDef = nsDef.GetEventDefL( MdeConstants::Events::KDeleted );
+
+		iMdeSession->RemoveObjectL( aUri, &nsDef );
+		time.UniversalTime();
+		CMdEEvent* event = iMdeSession->NewEventL( eventDef, objectId, time,NULL,NULL );
+		CleanupStack::PushL( event );
+		
+		iMdeSession->AddEventL( *event );
+		CleanupStack::PopAndDestroy( event );
+    	}
+	
+	// remove file from filesystem
+	RFs fs;
+	TInt err;
+	err = fs.Connect();
+	if ( err == KErrNone )
+		{	
+		err = fs.Delete( aUri );
+		fs.Close();
+		}
+	
+    LOG( "CLocationManagerServer::DeleteTrackLogL return" );
+	
+    return err;
+	}
+
+TInt CLocationManagerServer::TrackLogName( TFileName& aFileName )
+	{
+	if ( iTrackLog->IsRecording() )
+		{
+		iTrackLog->GetTrackLogName(aFileName);
+		return KErrNone;
+		}
+	return KErrNotFound;
+	}
+
+void CLocationManagerServer::GetCaptureSetting( RLocationTrail::TTrailCaptureSetting& aCaptureSetting )
+	{
+	aCaptureSetting = iCaptureSetting;
+	}
+
+void CLocationManagerServer::HandleObjectNotification( CMdESession& /*aSession*/,
+		TObserverNotificationType aType,
+		const RArray<TItemId>& aObjectIdArray )
+	{
+	// If notification type is remove then someone has deleted a tracklog tag.
+	if ( aType == ENotifyRemove )
+		{	
+		iTrackLog->CancelRecording();
+		return;
+		}
+	
+	TRAP_IGNORE( LinkObjectToTrackLogTagL( aObjectIdArray ) );
+	}
+
+void CLocationManagerServer::StartListeningTagRemovalsL()
+	{
+	if ( !IsSessionReady() )
+		{
+		User::Leave( KErrNotReady );
+		}
+	
+	// start listening to mde track log tag removals
+    CMdELogicCondition* condition = CMdELogicCondition::NewL( ELogicConditionOperatorAnd );
+    CleanupStack::PushL( condition );
+    iMdeSession->AddObjectObserverL( *this, condition, ENotifyRemove, 
+    		&iMdeSession->GetDefaultNamespaceDefL() );
+    CleanupStack::Pop( condition );
+	}
+
+void CLocationManagerServer::StartListeningObjectCreationsL()
+	{
+	if ( !IsSessionReady() )
+		{
+		User::Leave( KErrNotReady );
+		}
+	
+	CMdELogicCondition* condition = CMdELogicCondition::NewL( ELogicConditionOperatorAnd );
+	CleanupStack::PushL( condition );
+	
+	CMdEObjectDef& objDef = iMdeSession->GetDefaultNamespaceDefL().GetObjectDefL( 
+			MediaObject::KMediaObject );
+
+	CMdEPropertyDef& originDef = objDef.GetPropertyDefL( Object::KOriginProperty );
+	condition->AddPropertyConditionL( originDef, TMdEUintEqual( Object::ECamera ));
+	
+	CleanupStack::Pop( condition );
+	iMdeSession->AddObjectObserverL( *this, condition, ENotifyAdd | ENotifyModify,
+			&iMdeSession->GetDefaultNamespaceDefL() );
+	
+	}
+
+void CLocationManagerServer::LinkObjectToTrackLogTagL( const RArray<TItemId>& aObjectIdArray )
+	{
+	CMdERelationDef& containsRelDef = iMdeSession->GetDefaultNamespaceDefL()
+		.GetRelationDefL( Relations::KContains );
+
+	const TInt count = aObjectIdArray.Count();
+	for ( TInt i( 0 ); i < count; i++ )
+		{
+		CMdERelation* relationObject = iMdeSession->NewRelationLC( containsRelDef, 
+				aObjectIdArray[i], iTagId, 0 );
+
+		iMdeSession->AddRelationL( *relationObject );
+
+		CleanupStack::PopAndDestroy( relationObject );
+		}
+	}
+
+void CLocationManagerServer::AddGpxObserver( MGpxConversionObserver* aObserver )
+	{
+	iTrackLog->AddGpxObserver( aObserver );
+	}
+// End of file 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/server/src/clocationmanagersession.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,517 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A session class for LocationManagerServer.
+*
+*/
+
+#include <e32debug.h>
+#include <s32mem.h>
+#include <LbsSatellite.h> 
+#include <locationdatatype.h>
+#include <locationeventdef.h>
+
+#include "clocationmanagerserver.h"
+#include "clocationmanagersession.h"
+#include "locationmanagerdefs.h"
+#include "locationmanagerdebug.h"
+#include "rlocationtrail.h"
+#include "rlocationobjectmanipulator.h"
+#include "rlocationtrail.h"
+#include "mdsutils.h"
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::CLocationManagerSession
+// C++ constructor.
+// --------------------------------------------------------------------------
+//
+CLocationManagerSession::CLocationManagerSession() 
+    {
+    
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::~CLocationManagerSession
+// C++ destructor.
+// --------------------------------------------------------------------------
+//
+CLocationManagerSession::~CLocationManagerSession()
+    {
+    LOG( "CLocationManagerSession::~CLocationManagerSession(), begin" );
+    Server().CancelNotificationRequest( iNotificationHandle );
+    Server().CancelLocationRequest( iLocationHandle );
+    Server().CancelTrackLogNotificationRequest( iTrackLogNotificationHandle );
+    Server().RemoveSession();
+    LOG( "CLocationManagerSession::~CLocationManagerSession(), end" );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::CreateL
+// From CSession2, used to increase server's session count.
+// --------------------------------------------------------------------------
+//
+void CLocationManagerSession::CreateL()
+    {
+    LOG( "CLocationManagerSession::CreateL(), begin" );
+    Server().AddSession();
+    LOG( "CLocationManagerSession::CreateL(), end" );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::Server
+// Reference to server.
+// --------------------------------------------------------------------------
+//
+CLocationManagerServer& CLocationManagerSession::Server()
+    {   
+    return *static_cast<CLocationManagerServer*>
+           ( const_cast<CServer2*>( CSession2::Server() ) );
+    }
+    
+// --------------------------------------------------------------------------
+// CLocationManagerSession::ServiceL
+// From CSession2, passes the request forward to DispatchMessageL.
+// --------------------------------------------------------------------------
+//
+void CLocationManagerSession::ServiceL( const RMessage2& aMessage )
+    {
+    LOG( "CLocationManagerSession::ServiceL" );
+    _LIT( KSemaphore, "LocManSynchSemaphore" );
+    RSemaphore semaphore;
+    TInt result = semaphore.OpenGlobal( KSemaphore );
+    LOG1( "CLocationManagerSession::ServiceL - semaphore open result: %d", result );
+    iMessage = RMessage2( aMessage );
+    if ( result == KErrNone )
+    	{
+    	semaphore.Signal();
+    	semaphore.Close();
+    	}
+    TRAPD( err, DispatchMessageL( aMessage ) );
+    if ( err != KErrNone )
+        {
+        aMessage.Complete( err );
+        }    
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::DispatchMessageL
+// Handles the request from client.
+// --------------------------------------------------------------------------
+//
+void CLocationManagerSession::DispatchMessageL( const RMessage2& aMessage )
+    {
+    LOG( "CLocationManagerSession::DispatchMessageL" );
+    switch( aMessage.Function() )
+        {
+        case ELocManStartTrail:
+            StartLocationTrailL( aMessage );
+            break;        
+        case ELocManStopTrail:
+            StopLocationTrailL( aMessage );
+            break;        
+        case ELocManTrailState:
+            GetLocationTrailStateL( aMessage );
+            break;        
+        case ELocManNotifyTrailStateChange:
+            NotifyLocationTrailStateChangeL( aMessage );
+            break;        
+        case ELocManCancelNotification:
+            CancelNotificationRequest( aMessage );
+            break;
+        case ELocManRetrieveLoc:
+            RetrieveLocationL( aMessage );
+            break;
+        case ELocManCurrentLoc:
+            CurrentLocationL( aMessage );
+            break;
+        case ELocManCancelCurrentLoc:
+            CancelLocationRequest( aMessage );
+            break;
+        case ELocManCreateLocationObject:
+        	CreateLocationObjectL( aMessage );
+        	break;
+        case ELocManLocationSnapshot:
+        	LocationSnapshotL( aMessage );
+        	break;
+        case ELocManRemoveLocationObject:
+        	RemoveLocationObjectL( aMessage );
+        	break;
+        case ELocManCopyLocationDataById:
+        	CopyLocationDataByIdL( iMessage );
+        	break;
+        case ELocManCopyLocationDataByUri:
+	    	CopyLocationDataByURIL( iMessage );
+	    	break;		
+        case ELocManStartTrackLog:
+        	StartTrackLogL( aMessage );
+        	break;
+        case ELocManStopTrackLog:
+        	StopTrackLogL( aMessage );
+        	break;
+        case ELocManGetTrackLogStatus:
+        	GetTrackLogStatusL( aMessage );
+        	break;
+        case ELocManDeleteTrackLog:
+        	DeleteTrackLogL( aMessage );
+        	break;
+        case ELocManIsTrackLogRecording:
+        	IsTrackLogRecordingL( aMessage );
+        	break;
+        case ELocManTrackLogName:
+        	TrackLogNameL( aMessage );
+        	break;
+        case ELocManRegObserver:
+        	RegisterTrackLogObserver( aMessage );
+        	break;
+        case ELocManGetCaptureSetting:
+        	GetCaptureSettingL( aMessage );
+        	break;
+        case ELocManCancelTrackLogNotify:
+        	CancelTrackLogNotificationRequest( aMessage );
+        	break;
+        default:
+            aMessage.Complete( KErrArgument );
+            break;
+        }
+    }
+  
+// --------------------------------------------------------------------------
+// CLocationManagerSession::StartLocationTrailL
+// --------------------------------------------------------------------------
+//
+void CLocationManagerSession::StartLocationTrailL( const RMessage2& aMessage )
+    {
+    const TInt KParamSetting = 0;
+    
+    RLocationTrail::TTrailCaptureSetting setting;
+    TPckg<RLocationTrail::TTrailCaptureSetting> locSetting( setting ); 
+    aMessage.ReadL(KParamSetting, locSetting);    
+    
+    LOG1 ("CLocationManagerSession::StartLocationTrailL TTrailCaptureSetting: %d", setting);
+    
+    Server().StartGPSPositioningL( setting );
+    aMessage.Complete( KErrNone );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::StopLocationTrailL
+// --------------------------------------------------------------------------
+//
+void CLocationManagerSession::StopLocationTrailL( const RMessage2& aMessage )
+    {
+    Server().StopGPSPositioningL();
+    if( !aMessage.IsNull() )
+        {
+        aMessage.Complete( KErrNone );
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::GetLocationTrailStateL
+// --------------------------------------------------------------------------
+//
+void CLocationManagerSession::GetLocationTrailStateL( const RMessage2& aMessage )
+    {
+    RLocationTrail::TTrailState state;
+    Server().GetLocationTrailState( state );
+        
+    TPckg<RLocationTrail::TTrailState> locState( state );    
+    aMessage.WriteL( 0, locState );
+    aMessage.Complete( KErrNone );    
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::NotifyLocationTrailStateChangeL
+// --------------------------------------------------------------------------
+//
+void CLocationManagerSession::NotifyLocationTrailStateChangeL( const RMessage2& aMessage )
+    {
+    iNotificationHandle = aMessage.Handle();
+    Server().AddNotificationRequestL( aMessage );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::CancelNotificationRequest
+// --------------------------------------------------------------------------
+//
+void CLocationManagerSession::CancelNotificationRequest( const RMessage2& aMessage )
+    {
+    Server().CancelNotificationRequest( iNotificationHandle );
+    aMessage.Complete( KErrNone );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::RetrieveLocationL
+// --------------------------------------------------------------------------
+//
+void CLocationManagerSession::RetrieveLocationL( const RMessage2& aMessage )
+    {
+    TTime time( 0 );
+    TPckg<TTime> timeBuf( time );
+    aMessage.ReadL( EArgumentTime, timeBuf );
+    
+    TLocationData locationData;
+    TLocTrailState state;
+    Server().GetLocationByTimeL( time, locationData, state );
+
+    TPckg<TLocationData> locDataBuf( locationData );
+    aMessage.WriteL( EArgumentLocationData, locDataBuf );
+    
+    TPckg<TUint> stateBuf( state );
+    aMessage.WriteL( EArgumentState, stateBuf );
+
+    aMessage.Complete( KErrNone );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::CurrentLocationL
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::CurrentLocationL( const RMessage2& aMessage )
+    {
+    LOG ("CLocationManagerSession::StartLocationTrailL begin");
+    iLocationHandle = aMessage.Handle();
+    // server creates completion after it has received current location data
+    Server().RequestCurrentLocationL( aMessage );
+    LOG ("CLocationManagerSession::StartLocationTrailL end");
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::CancelLocationRequest()
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::CancelLocationRequest( const RMessage2& aMessage )
+    {
+    Server().CancelLocationRequest( iLocationHandle );
+    aMessage.Complete( KErrNone );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::CancelTrackLogNotificationRequest()
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::CancelTrackLogNotificationRequest( const RMessage2& aMessage )
+    {
+    Server().CancelTrackLogNotificationRequest( iTrackLogNotificationHandle );
+    aMessage.Complete( KErrNone );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::CreateLocationObjectL
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::CreateLocationObjectL( const RMessage2& aMessage )
+    {
+    LOG( "CLocationManagerSession::CreateLocationObjectL begin" );
+    const TInt KParamData = 0;
+    const TInt KParamId = 1;
+    
+    TLocationData locationData;
+    TUint objectId;
+	
+    TPckg<TLocationData> locData( locationData );
+    aMessage.ReadL( KParamData, locData );
+    
+    TPckg<TUint> objId( objectId);
+    aMessage.ReadL( KParamId, objId );
+    
+    Server().CreateLocationObjectL( locationData, objectId );
+    
+    aMessage.Complete( KErrNone );
+    LOG( "CLocationManagerSession::CreateLocationObjectL end" );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::LocationSnapshotL
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::LocationSnapshotL( const RMessage2& aMessage )
+    {
+    LOG( "CLocationManagerSession::LocationSnapshotL begin" );
+    const TInt KParamId = 0;
+    
+    TUint objectId;
+	
+    TPckg<TUint> objId( objectId);
+    aMessage.ReadL( KParamId, objId );
+    
+    Server().LocationSnapshotL( objectId );
+    
+    aMessage.Complete( KErrNone );
+    LOG( "CLocationManagerSession::LocationSnapshotL end" );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::RemoveLocationObjectL
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::RemoveLocationObjectL( const RMessage2& aMessage )
+    {
+    LOG( "CLocationManagerSession::RemoveLocationObjectL begin" );
+    const TInt KParamId = 0;
+    TUint objectId;
+    TPckg<TUint> locObjectId( objectId );
+    aMessage.ReadL(KParamId, locObjectId);
+    Server().RemoveLocationObjectL(objectId);
+    aMessage.Complete( KErrNone );
+    LOG( "CLocationManagerSession::RemoveLocationObjectL end" );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::CopyLocationDataByIdL
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::CopyLocationDataByIdL( const RMessage2& aMessage )
+    {
+    Server().InitCopyLocationByIdL( aMessage );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::CopyLocationDataByURIL
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::CopyLocationDataByURIL( const RMessage2& aMessage )
+    {
+    Server().InitCopyLocationByURIL( aMessage );
+    }
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::StartTrackLog
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::StartTrackLogL( const RMessage2& aMessage )
+	{
+	RLocationTrail::TTrailState state;
+	Server().GetLocationTrailState( state );
+	
+	if ( state == RLocationTrail::ETrailStopped )
+		{
+		Server().StartGPSPositioningL( RLocationTrail::ECaptureAll );
+		}
+	
+	Server().StartTrackLogL();
+
+	aMessage.Complete( KErrNone );
+	}
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::StopTrackLog
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::StopTrackLogL( const RMessage2& aMessage )
+	{
+	Server().StopTrackLogL();
+
+	aMessage.Complete( KErrNone );
+	}
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::GetStatus
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::GetTrackLogStatusL(const RMessage2& aMessage)
+	{
+	const TInt KParamRec = 0;
+	const TInt KParamQuality = 1;
+	TBool rec = EFalse;
+	TPositionSatelliteInfo fixQuality;
+	
+	Server().GetTrackLogStatus( rec, fixQuality );
+	
+	TPckg<TBool> wrapRec( rec );
+	aMessage.WriteL( KParamRec, wrapRec );
+	
+	TPckg<TPositionSatelliteInfo> wrapQuality( fixQuality );
+	aMessage.WriteL( KParamQuality, wrapQuality );
+
+	aMessage.Complete( KErrNone );
+	}
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::DeleteTrackLog
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::DeleteTrackLogL(const RMessage2& aMessage)
+	{
+	const TInt KParamUri = 0;
+	const TInt KParamUriLength = aMessage.GetDesLength(KParamUri);
+	
+    TInt err = KErrNone;	
+	if (KParamUriLength > 0)
+    	{
+    	// read TDesC& aURI from request
+	    HBufC* uriBuf = HBufC::NewLC( KParamUriLength );
+	    TPtr ptrUri( uriBuf->Des() );
+	    aMessage.ReadL( KParamUri, ptrUri );  
+
+	    err = Server().DeleteTrackLogL( ptrUri );
+	    CleanupStack::PopAndDestroy( uriBuf );
+    	}
+	aMessage.Complete( err );
+	}
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::IsTrackLogRecordingL
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::IsTrackLogRecordingL(const RMessage2& aMessage)
+	{	
+	const TInt KParamRec = 0;
+	TBool rec = EFalse;
+
+	Server().IsTrackLogRecording( rec );
+	
+	TPckg<TBool> wrapRec( rec );
+	aMessage.WriteL(KParamRec, wrapRec);
+
+	aMessage.Complete( KErrNone );
+	}
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::TrackLogName
+// --------------------------------------------------------------------------
+//    
+void CLocationManagerSession::TrackLogNameL(const RMessage2& aMessage)
+	{	
+	const TInt KParamName = 0;
+	TFileName fileName;
+	TInt err;
+	
+	err = Server().TrackLogName( fileName );
+	aMessage.WriteL(KParamName, fileName);
+	aMessage.Complete( err );
+	}
+
+// --------------------------------------------------------------------------
+// CLocationManagerSession::GpsQualityChange
+// --------------------------------------------------------------------------
+//  
+void CLocationManagerSession::RegisterTrackLogObserver( const RMessage2& aMessage )
+	{
+	iTrackLogNotificationHandle = aMessage.Handle();
+	TRAP_IGNORE( Server().AddTrackLogNotificationRequestL( aMessage ) );
+	}
+
+void CLocationManagerSession::GetCaptureSettingL( const RMessage2& aMessage )
+	{
+	TInt KParamCaptureSetting = 0;
+	RLocationTrail::TTrailCaptureSetting captureSetting = RLocationTrail::EOff;
+	
+	Server().GetCaptureSetting( captureSetting );
+	
+	TPckg<RLocationTrail::TTrailCaptureSetting> setting( captureSetting );
+	aMessage.WriteL( KParamCaptureSetting, setting );
+	aMessage.Complete( KErrNone );
+	}
+    
+// End of file 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/sis/build-sisx.bat	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,20 @@
+rem
+rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+rem All rights reserved.
+rem This component and the accompanying materials are made available
+rem under the terms of "Eclipse Public License v1.0"
+rem which accompanies this distribution, and is available
+rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+rem
+rem Initial Contributors:
+rem Nokia Corporation - initial contribution.
+rem
+rem Contributors:
+rem
+rem Description:
+rem
+
+Echo please copy key files to ROOT before build sis file
+del locutil.sis locutil.sisx
+makesis -v locutil.pkg
+signsis locutil.sis locutil.sisx rd.cer rd-key.pem
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/sis/build-sisx_debug.bat	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,20 @@
+rem
+rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+rem All rights reserved.
+rem This component and the accompanying materials are made available
+rem under the terms of "Eclipse Public License v1.0"
+rem which accompanies this distribution, and is available
+rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+rem
+rem Initial Contributors:
+rem Nokia Corporation - initial contribution.
+rem
+rem Contributors:
+rem
+rem Description:
+rem
+
+Echo please copy key files to ROOT before build sis file
+del locutildebug.sis locutildebug.sisx
+makesis -v locutildebug.pkg
+signsis locutildebug.sis locutildebug.sisx rd.cer rd-key.pem
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/sis/depends.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ad:metadata xmlns="http://nokia.com/arrow/repository/ia_component"
+  xmlns:ad="http://nokia.com/arrow/application_metadata">
+  <appResources>
+     <appResource>
+        <language>1</language>
+        <iacName>MdS Location Manager</iacName>
+        <iacDescription>Upgrade package for MdS Location Manager</iacDescription>
+     </appResource>
+  </appResources>
+  <swPlatformDep>
+     <platform>S60</platform>
+     <versionFrom>
+        <major>5</major>
+        <minor>0</minor>
+        <date>
+           <year>2009</year>
+           <week>16</week>
+        </date>
+     </versionFrom>
+  </swPlatformDep>
+  <interDeps>
+  </interDeps>
+</ad:metadata>
\ No newline at end of file
Binary file locationmanager/sis/locationmanager_stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/sis/locutil.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,34 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Location Utility"},(0x200071BE),0,0,0
+
+; Supports Series 60 v3.0
+(0x101F7961), 0, 0, 0, {"Series60ProductID"}
+
+; Localised vendor name
+%{"Nokia"}
+; Unique vendor name
+;:"Nokia"
+:"Vendor"
+
+"S:\EPOC32\RELEASE\ARMV5\UREL\locationutilityserver.exe" -"!:\sys\bin\locationutilityserver.exe"
+"S:\EPOC32\RELEASE\ARMV5\UREL\LocationTrail.dll" -"!:\sys\bin\LocationTrail.dll"
+"S:\EPOC32\RELEASE\ARMV5\UREL\locationutility.dll" -"!:\sys\bin\locationutility.dll"
+"S:\EPOC32\RELEASE\ARMV5\UREL\Loc.exe" -"!:\sys\bin\Loc.exe"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/sis/locutildebug.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,34 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Location Utility"},(0x200071BE),0,0,0
+
+; Supports Series 60 v3.0
+(0x101F7961), 0, 0, 0, {"Series60ProductID"}
+
+; Localised vendor name
+%{"Nokia"}
+; Unique vendor name
+;:"Nokia"
+:"Vendor"
+
+"S:\EPOC32\RELEASE\ARMV5\UDEB\locationutilityserver.exe" -"!:\sys\bin\locationutilityserver.exe"
+"S:\EPOC32\RELEASE\ARMV5\UDEB\LocationTrail.dll" -"!:\sys\bin\LocationTrail.dll"
+"S:\EPOC32\RELEASE\ARMV5\UDEB\locationutility.dll" -"!:\sys\bin\locationutility.dll"
+"S:\EPOC32\RELEASE\ARMV5\UDEB\Loc.exe" -"!:\sys\bin\Loc.exe"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/sis/package.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Location Manager Patch"},(0x200071BE), 2, 0, 0, TYPE=SA, RU
+
+; Localised vendor name
+%{"Nokia"}
+
+; Unique vendor name
+:"Nokia"
+
+;Files
+"\EPOC32\RELEASE\ARMV5\UREL\LocationTrail.dll" -"c:\sys\bin\LocationTrail.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\locationmanager.dll" -"c:\sys\bin\locationmanager.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\locationmanagerserver.exe" -"c:\sys\bin\locationmanagerserver.exe"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/locationmanager/sis/stub.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,30 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;Header
+# {"Location Manager"}, (0x200071BE), 1, 0, 0, TYPE=SA
+
+;Localised Vendor name
+%{"Nokia"}
+
+;Unique Vendor name
+:"Nokia"
+
+;Files
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/content_listing_framework_collection_manager_api.metaxml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,18 @@
+<?xml version="1.0" ?>
+<api id="0c1008f9a5837c892f6f8d083e894c2a" dataversion="2.0">
+  <name>Content Listing Framework Collection Manager API</name>
+  <description>An interface for managing media collections</description>
+  <type>c++</type>
+  <collection>clfwrapper</collection>
+  <libs>
+    <lib name="MediaCollectionManager.lib" />
+  </libs>
+  <release category="platform"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>no</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+:                Content Listing Framework Collection Manager API
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/mediacollectionmanager.h     MW_LAYER_PLATFORM_EXPORT_PATH(mediacollectionmanager.h)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/inc/mediacollectionmanager.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,340 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*  Description :
+*
+*/
+
+
+#ifndef MMEDIACOLLECTIONMANAGER_H
+#define MMEDIACOLLECTIONMANAGER_H
+
+
+#include <badesca.h>
+
+/// Propertie flags for media collections
+enum TMediaCollectionProperties
+    {
+    /// Collection items are in Phone memory
+    EMCPhoneMemoryCollection = 0x00000001,
+    /// Collection items are in MMC
+    EMCMmcCollection = 0x00000002
+    };
+
+class MMediaCollectionManager;
+class MMediaCollectionInfoExt;
+class MMediaCollectionManagerExt;
+class MMediaCollectionObserverExt;
+
+/**
+ *  Factory for Media Collection Manager
+ *
+ *  @lib MediaCollectionManager.lib
+ *  @since S60 3.2
+ */
+class MediaCollectionManagerFactory
+    {
+public: // New functions
+
+	/**
+	 * Create new instance of Media Collection Manager
+	 * @return New instance of Media Collection Manager.
+	 *         Ownership is transferred to the client application.
+	 */
+	IMPORT_C static MMediaCollectionManager* CreateCollectionManagerL();
+
+private:
+	// Prohibit C++ default constructor.
+	MediaCollectionManagerFactory();
+	// Prohibit Destructor.
+	~MediaCollectionManagerFactory();
+    };
+
+/**
+ *  Media Collection Info interface,
+ *   use MMediaCollectionManager to get collections
+ *
+ *  @lib N/A
+ *  @since S60 3.2
+ */
+class MMediaCollectionInfo
+    {
+public:
+	virtual ~MMediaCollectionInfo() {}
+
+public:
+	/**
+	* Returns the name of the collection
+	* @since S60 3.2
+	* @return Name of the collection
+	*/
+	virtual const TDesC& Name() const = 0;
+
+	/**
+	* Returns the id of the album
+	* @since S60 3.2
+	* @return The id of the album
+	*/
+	virtual TInt Id() const = 0;
+
+	/**
+	* Returns list of media types that are defined for the collection.
+	* See media types from CLFContentListing.hrh TCLFMediaType
+	* @since S60 3.2
+	* @return List of media types that are defined for the collection.
+	*/
+	virtual const RArray<TInt>& CollectionItemTypes() const = 0;
+	
+	/**
+	* Returns collection propertie flags
+	* Properties are defined in TMediaCollectionProperties
+	* Should not be used in 5.0 or later!
+	* @since S60 3.2, depricated in 5.0
+	* @return Properties flags
+	*/
+	virtual TInt32 Properties() const = 0;
+
+private: // Extension interface
+
+	/**
+	* This member is internal and not intended for use.
+	*/
+	virtual MMediaCollectionInfoExt* Extension()
+						{ return NULL; }
+	virtual const MMediaCollectionInfoExt* Extension() const
+						{ return NULL; }
+    };
+
+
+/**
+ *  Observer interface to get notification about changes in
+ *   Media Collection Manager
+ *
+ *  @lib N/A
+ *  @since S60 3.2
+ */
+class MMediaCollectionObserver
+    {
+public:
+	/**
+	* Collection manager uses this method to notify about
+	*  created/deleted/modified collections.
+	* @since 3.2
+	* @param aCollectionIdArray
+	*/
+	virtual void CollectionChangedL(
+						const TArray<TInt>& aCollectionIdArray ) = 0;
+
+	/**
+	* Collection manager uses this method to notify about
+	*  possible errors.
+	* @since 3.2
+	* @param aError Collection manager error status
+	*               KErrCorrupt if collection manager is corrupted and
+	*               possible some data is lost
+	*/
+	virtual void CollectionManagerErrorL(
+						TInt aError ) = 0;
+
+protected:
+
+	/**
+	* Destructor.
+	*/
+	virtual ~MMediaCollectionObserver() {}
+
+private: // Extension interface
+
+	/**
+	* This member is internal and not intended for use.
+	*/
+	virtual MMediaCollectionObserverExt* Extension()
+						{ return NULL; }
+	virtual const MMediaCollectionObserverExt* Extension() const
+						{ return NULL; }
+    };
+
+/**
+ *  Media Collection Manager
+ *
+ *  Use this class to get Media Collections, create new collections,
+ *   delete collections, rename collections, add files to collections,
+ *   remove files from collections.
+ *
+ *  @lib N/A
+ *  @since S60 3.2
+ */
+class MMediaCollectionManager
+    {
+public:
+	virtual ~MMediaCollectionManager() {}
+
+public: // New functions
+
+	/**
+	* Return collection info by index.
+	* @since 3.2
+	* @param aCollectionInfoArray Collection infos are added to this array
+	*/
+	virtual void GetCollectionInfosL(
+						RPointerArray<MMediaCollectionInfo>&
+											aCollectionInfoArray ) const = 0;
+
+	/**
+	* Return collection info by ID.
+	* @since 3.2
+	* @param aId Collection ID
+	* @return Pointer to a MMediaCollectionInfo object
+	*         Ownership is transferred to client
+	*/
+	virtual MMediaCollectionInfo* CollectionInfoByIdLC(
+						TInt aId ) const = 0;
+
+	/**
+	* Create new collection.
+	* @since 3.2
+	* @param aName Name of the collection
+	* @param aCollectionItemTypes List of media types that are
+	*         in the collection.
+	*        Use media types from CLFContentListing.hrh TCLFMediaType.
+	*        NOTE! that collection manager doesn't check is added item defined
+	*              mediatype. This is only for client(s) for grouping different
+	*              type folders.
+	* @param aStorage In 3.2 See TMediaCollectionProperties
+	*        NOTE! If given propertie set is not supported then
+	*              function leaves with KErrNotSupported
+	         NOTE! In 5.0 Drive number where the collection is to be created!
+	* @return ID of the creaded collection
+	*/
+	virtual TInt CreateCollectionL(
+						const TDesC& aName,
+						const TArray<TInt>& aCollectionItemTypes,
+						TInt32 aStorage) = 0;
+
+	/**
+	* Delete collection.
+	* NOTE! this doesn't delete items that are in collection.
+	* @since 3.2
+	* @param aId ID of the collection
+	*/
+	virtual void DeleteCollectionL(
+						TInt aId ) = 0;
+
+	/**
+	* Rename collection.
+	* @since 3.2
+	* @param aId ID of the collection.
+	*            If collection doesn't found then
+	*            function leaves with KErrNotFound
+	* @param aNewName new name of the collection
+	*/
+	virtual void RenameCollectionL(
+						TInt aId,
+						const TDesC& aNewName ) = 0;
+
+	/**
+	* Add item(s) to collection.
+	* @since 3.2
+	* @param aId Collection ID
+	*            If collection doesn't found then
+	*            function leaves with KErrNotFound
+	* @param aItemArray
+	* @param aRemoveFromOtherCollections Is item removed from other
+	*                                    available collections.
+	*/
+	virtual void AddToCollectionL(
+						TInt aId,
+						const MDesCArray& aItemArray,
+						TBool aRemoveFromOtherCollections = ETrue ) = 0;
+
+	/**
+	* Remove item(s) from collection.
+	* @since 3.2
+	* @param aId Collection ID
+	*            If collection doesn't found then
+	*            function leaves with KErrNotFound
+	* @param aItemArray
+	*/
+	virtual void RemoveFromCollectionL(
+						TInt aId,
+						const MDesCArray& aItemArray ) = 0;
+
+	/**
+	* Remove item(s) from all collections.
+	* @since 3.2
+	* @param aItemArray
+	*/
+	virtual void RemoveFromAllCollectionsL(
+						const MDesCArray& aItemArray ) = 0;
+
+
+	/**
+	* Get collection items.
+	* @since 3.2
+	* @param aId Collection ID
+	*            If collection doesn't found then
+	*            function leaves with KErrNotFound
+	* @param aItemArray Item are added to the array
+	*/
+	virtual void GetCollectionItemArrayL(
+						TInt aId,
+						CDesCArray& aItemArray ) const = 0;
+
+	/**
+	* Find collections IDs by item.
+	* @since 3.2
+	* @param aItem
+	* @param aIdArray Possible collection IDs are added to the array
+	*/
+	virtual void GetCollectionIdByItemL(
+						const TDesC& aItem,
+						RArray<TInt>& aIdArray ) const = 0;
+
+	/**
+	* Add collection observer.
+	* @since 3.2
+	* @param aObserver
+	*/
+	virtual void AddCollectionObserverL(
+						MMediaCollectionObserver& aObserver ) = 0;
+
+	/**
+	* Remove collection observer.
+	* @since 3.2
+	* @param aObserver
+	*/
+	virtual void RemoveCollectionObserverL(
+						MMediaCollectionObserver& aObserver ) = 0;
+
+	/**
+	* Get the drivenumber of the drive where collection is located by collection id
+	* @since 5.0
+	* @param aId id of the collection
+	* @return DriveNumber of the drive where collection is located
+	*/						
+	virtual TInt32 GetDriveByIdL( TInt aId ) = 0;
+
+private: // Extension interface
+
+	/**
+	* This member is internal and not intended for use.
+	*/
+	virtual MMediaCollectionManagerExt* Extension()
+						{ return NULL; }
+	virtual const MMediaCollectionManagerExt* Extension() const
+						{ return NULL; }
+
+    };
+
+#endif // MMEDIACOLLECTIONMANAGER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/tsrc/Bmarm/CollectionMangerTestU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,2 @@
+EXPORTS
+	LibEntryL__FR13CTestModuleIf @ 1 NONAME R3UNUSED ; LibEntryL(CTestModuleIf &)
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/tsrc/Bwins/CollectionManagerTestU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,2 @@
+EXPORTS
+	?LibEntryL@@YAPAVCScriptBase@@AAVCTestModuleIf@@@Z @ 1 NONAME ; class CScriptBase * __cdecl LibEntryL(class CTestModuleIf &)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/tsrc/conf/CollectionManagerTest.cfg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,146 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  CLF Collection Manager API tests
+#
+
+// ---------------------------------------------------------------------------
+// CLF Collection Manager API test cases
+// ---------------------------------------------------------------------------
+
+// These should be run in sequential mode if several cases are run at the same
+// time! Be adviced, this API is no longer used or supported, it is present only
+// because of it's association to Content Listing Framework.
+
+[StifSettings]
+TestThreadStackSize= 32768
+TestThreadMinHeap= 4096
+TestThreadMaxHeap= 16777216
+[EndStifSettings]
+
+[Test]
+title Create Collection Manager
+create CollectionManagerTest test
+test CreateCollectionManager
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Get Collection Infos
+create CollectionManagerTest test
+test CreateCollectionManager
+test GetCollectionInfos
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Get Collection Info By ID
+create CollectionManagerTest test
+test CreateCollectionManager
+test CollectionInfoById
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Create Collection
+create CollectionManagerTest test
+test CreateCollectionManager
+test CreateCollection
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Delete Collection
+create CollectionManagerTest test
+test CreateCollectionManager
+test DeleteCollection
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Rename Collection
+create CollectionManagerTest test
+test CreateCollectionManager
+test RenameCollection
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Add to Collection
+create CollectionManagerTest test
+test CreateCollectionManager
+test AddToCollection
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Remove from Collection
+create CollectionManagerTest test
+test CreateCollectionManager
+test RemoveFromCollectionL
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Get collection info array
+create CollectionManagerTest test
+test CreateCollectionManager
+test GetCollectionItemArray
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Get collection ID by Item
+create CollectionManagerTest test
+test CreateCollectionManager
+test GetCollectionIdByItem
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Add collection observer
+create CollectionManagerTest test
+test CreateCollectionManager
+test AddCollectionObserver
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Remove collection observer
+create CollectionManagerTest test
+test CreateCollectionManager
+test RemoveCollectionObserver
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Get drive by ID test
+create CollectionManagerTest test
+test CreateCollectionManager
+test GetDriveById
+test EndTestSession
+delete test
+[Endtest]
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/tsrc/eabi/CollectionManagerTestu.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	_Z9LibEntryLR13CTestModuleIf @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/tsrc/group/CollectionManagerTest.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET          CollectionManagerTest.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E3
+
+CAPABILITY      ALL -TCB
+VENDORID        VID_DEFAULT
+
+DEFFILE         CollectionManagerTest.def
+
+SOURCEPATH      ../src
+SOURCE          CollectionManagerTest.cpp
+SOURCE          CollectionManagerTestBlocks.cpp
+
+SYSTEMINCLUDE     /epoc32/include/ecom
+USERINCLUDE     ../inc ../../../../inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+LIBRARY         mediacollectionmanager.lib
+LIBRARY         efsrv.lib
+LIBRARY         bafl.lib
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/tsrc/group/CollectionManagerTest.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,34 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+; Installation file for API test
+
+; Languages
+&EN
+
+; Header
+#{"CollectionManagerTest"},(0x101FB3E3),1,0,1,TYPE=SA
+
+; Localised Vendor name
+%{"Nokia-EN"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Files
+"\epoc32\release\armv5\urel\CollectionManagerTest.dll"      -"C:\sys\bin\CollectionManagerTest.dll"
+"..\init\CollectionManagerTest.ini"      -"C:\testframework\CollectionManagerTest.ini"
+"..\conf\CollectionManagerTest.cfg"      -"C:\testframework\CollectionManagerTest.cfg"
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/tsrc/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+CollectionManagerTest.mmp
+
+PRJ_TESTEXPORTS
+../conf/CollectionManagerTest.cfg /epoc32/winscw/c/TestFramework/CollectionManagerTest.cfg
+../init/CollectionManagerTest.ini /epoc32/winscw/c/TestFramework/CollectionManagerTest.ini
+
+//  End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/tsrc/inc/CollectionManagerTest.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,107 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef CONTEXTENGINEPLUGINTEST_H
+#define CONTEXTENGINEPLUGINTEST_H
+
+//  INCLUDES
+#include <StifLogger.h>
+#include <TestScripterInternal.h>
+#include <StifTestModule.h>
+#include <mediacollectionmanager.h>
+
+// Logging path
+_LIT( KCollectionManagerTestLogPath, "\\logs\\testframework\\CollectionManagerTest\\" ); 
+// Log file
+_LIT( KCollectionManagerTestLogFile, "CollectionManagerTest.txt" ); 
+_LIT( KCollectionManagerTestLogFileWithTitle, "CollectionManagerTest_[%S].txt" );
+
+// FORWARD DECLARATIONS
+class CCollectionManagerTest;
+
+// CLASS DECLARATION
+NONSHARABLE_CLASS(CCollectionManagerTest) : public CScriptBase,
+                                                                            public MMediaCollectionObserver
+				                              
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCollectionManagerTest* NewL( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCollectionManagerTest();
+
+    public: // Functions from base classes
+
+        virtual TInt RunMethodL( CStifItemParser& aItem );
+        
+        void CollectionChangedL( const TArray<TInt>& aCollectionIdArray );
+        void CollectionManagerErrorL( TInt aError );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CCollectionManagerTest( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Frees all resources allocated from test methods.
+        */
+        void Delete();
+        
+        /**
+        * Test methods are listed below. 
+        */
+
+        // engine
+        virtual TInt CreateCollectionManagerL( CStifItemParser& aItem );
+        virtual TInt GetCollectionInfosL( CStifItemParser& aItem );
+        virtual TInt CollectionInfoByIdL( CStifItemParser& aItem );
+        virtual TInt CreateCollectionL( CStifItemParser& aItem );
+        virtual TInt DeleteCollectionL( CStifItemParser& aItem );
+        virtual TInt RenameCollectionL( CStifItemParser& aItem );
+        virtual TInt AddToCollectionL( CStifItemParser& aItem );
+        virtual TInt RemoveFromCollectionL( CStifItemParser& aItem );
+        virtual TInt RemoveFromAllCollectionsL( CStifItemParser& aItem );
+        virtual TInt GetCollectionItemArrayL( CStifItemParser& aItem );
+        virtual TInt GetCollectionIdByItemL( CStifItemParser& aItem );
+        virtual TInt AddCollectionObserverL( CStifItemParser& aItem );
+        virtual TInt RemoveCollectionObserverL( CStifItemParser& aItem );
+        virtual TInt GetDriveByIdL( CStifItemParser& aItem );
+        virtual TInt EndTestSessionL( CStifItemParser& aItem );
+
+    private:    // Data
+
+        MMediaCollectionManager* iCollectionManager;
+        
+    };
+
+#endif      // CONTEXTENGINEPLUGINTEST_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/tsrc/init/CollectionManagerTest.ini	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,80 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  
+#
+
+[Engine_Defaults]
+
+TestReportMode= FullReport    # Possible values are: 'Empty', 'Summary', 'Environment',
+                                                     'TestCases' or 'FullReport'
+
+CreateTestReport= YES         # Possible values: YES or NO
+
+TestReportFilePath= C:\LOGS\TestFramework\
+TestReportFileName= ContextEnginePluginTestLog
+
+TestReportFormat= TXT         # Possible values: TXT or HTML
+TestReportOutput= FILE        # Possible values: FILE or RDEBUG
+TestReportFileCreationMode= OVERWRITE # Possible values: OVERWRITE or APPEND
+
+DeviceResetDllName= StifResetForNokia.dll # e.g. 'StifHWResetStub.dll' for user specific reseting
+
+DisableMeasurement= stifmeasurementdisablenone  # Possible values are:
+              # 'stifmeasurementdisablenone', 'stifmeasurementdisableall'
+              # 'stifmeasurementplugin01', 'stifmeasurementplugin02',
+              # 'stifmeasurementplugin03', 'stifmeasurementplugin04',
+              # 'stifmeasurementplugin05' or 'stifbappeaprofiler'
+
+Timeout= 600000		            # Default timeout value for each test case. In milliseconds
+#UITestingSupport= YES        # Possible values: YES or NO
+#SeparateProcesses= YES       # Possible values: YES or NO (default: NO)
+[End_Defaults]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[New_Module]
+ModuleName= TestScripter
+TestCaseFile= c:\testframework\CollectionManagerTest.cfg
+[End_Module]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[Logger_Defaults]
+
+#NOTE: If you want to set Logger using next setting(s) remove comment(s)'#'
+#NOTE: TestEngine and TestServer logging settings cannot change here
+
+CreateLogDirectories= YES    # Possible values: YES or NO
+
+#EmulatorBasePath= C:\LOGS\TestFramework\
+#EmulatorFormat= HTML         # Possible values: TXT or HTML
+#EmulatorOutput= FILE         # Possible values: FILE or RDEBUG
+
+HardwareBasePath= C:\
+#HardwareFormat= HTML         # Possible values: TXT or HTML
+#HardwareOutput= FILE         # Possible values: FILE or RDEBUG
+
+#FileCreationMode= OVERWRITE  # Possible values: OVERWRITE or APPEND
+
+#ThreadIdToLogFile= YES       # Possible values: YES or NO
+#WithTimeStamp= YES           # Possible values: YES or NO
+#WithLineBreak= YES           # Possible values: YES or NO
+#WithEventRanking= YES        # Possible values: YES or NO
+
+#FileUnicode= YES             # Possible values: YES or NO
+AddTestCaseTitle= YES        # Possible values: YES or NO
+[End_Logger_Defaults]
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+# End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/tsrc/src/CollectionManagerTest.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,130 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+// INCLUDE FILES
+#include <Stiftestinterface.h>
+#include "CollectionManagerTest.h"
+#include <SettingServerClient.h>
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::CCollectionManagerTest
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCollectionManagerTest::CCollectionManagerTest( 
+    CTestModuleIf& aTestModuleIf ):
+        CScriptBase( aTestModuleIf )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CCollectionManagerTest::ConstructL()
+    {
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        } 
+    // Close Setting server session
+    settingServer.Close();
+
+    TFileName logFileName;
+    
+    if(loggerSettings.iAddTestCaseTitle)
+        {
+        TName title;
+        TestModuleIf().GetTestCaseTitleL(title);
+        logFileName.Format(KCollectionManagerTestLogFileWithTitle, &title);
+        }
+    else
+        {
+        logFileName.Copy(KCollectionManagerTestLogFile);
+        }
+
+    iLog = CStifLogger::NewL( KCollectionManagerTestLogPath, 
+                          logFileName,
+                          CStifLogger::ETxt,
+                          CStifLogger::EFile,
+                          EFalse );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CCollectionManagerTest* CCollectionManagerTest::NewL( 
+    CTestModuleIf& aTestModuleIf )
+    {
+    CCollectionManagerTest* self = new (ELeave) CCollectionManagerTest( aTestModuleIf );
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+
+    }
+
+// Destructor
+CCollectionManagerTest::~CCollectionManagerTest()
+    { 
+
+    // Delete resources allocated from test methods
+    Delete();
+
+    // Delete logger
+    delete iLog; 
+
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point.
+// Returns: CScriptBase: New CScriptBase derived object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScriptBase* LibEntryL( 
+    CTestModuleIf& aTestModuleIf ) // Backpointer to STIF Test Framework
+    {
+
+    return ( CScriptBase* ) CCollectionManagerTest::NewL( aTestModuleIf );
+
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_collection_manager_api/tsrc/src/CollectionManagerTestBlocks.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,709 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// [INCLUDE FILES] - do not remove
+#include <e32svr.h>
+#include <ecom.h>
+#include <StifParser.h>
+#include <StifTestEventInterface.h>
+#include <Stiftestinterface.h>
+#include <mediacollectionmanager.h>
+#include "CollectionManagerTest.h"
+
+#include "mdsutils.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::Delete
+// Delete here all resources allocated and opened from test methods. 
+// Called from destructor. 
+// -----------------------------------------------------------------------------
+//
+void CCollectionManagerTest::Delete() 
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::RunMethodL
+// Run specified method. Contains also table of test mothods and their names.
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::RunMethodL( 
+    CStifItemParser& aItem ) 
+    {
+
+    static TStifFunctionInfo const KFunctions[] =
+        {  
+        // Copy this line for every implemented function.
+        // First string is the function name used in TestScripter script file.
+        // Second is the actual implementation member function. 
+
+        // engine		
+        ENTRY( "CreateCollectionManager", CCollectionManagerTest::CreateCollectionManagerL ),
+        ENTRY( "GetCollectionInfos", CCollectionManagerTest::GetCollectionInfosL ),
+        ENTRY( "CollectionInfoById", CCollectionManagerTest::CollectionInfoByIdL ),
+        ENTRY( "CreateCollection", CCollectionManagerTest::CreateCollectionL ),
+        ENTRY( "DeleteCollection", CCollectionManagerTest::DeleteCollectionL ),
+        ENTRY( "RenameCollection", CCollectionManagerTest::RenameCollectionL ),
+        ENTRY( "AddToCollection", CCollectionManagerTest::AddToCollectionL ),
+        ENTRY( "RemoveFromCollectionL", CCollectionManagerTest::RemoveFromCollectionL ),
+        ENTRY( "GetCollectionItemArray", CCollectionManagerTest::GetCollectionItemArrayL ),
+        ENTRY( "GetCollectionIdByItem", CCollectionManagerTest::GetCollectionIdByItemL ),
+        ENTRY( "AddCollectionObserver", CCollectionManagerTest::AddCollectionObserverL ),
+        ENTRY( "RemoveCollectionObserver", CCollectionManagerTest::RemoveCollectionObserverL ),
+        ENTRY( "GetDriveById", CCollectionManagerTest::GetDriveByIdL ),
+        ENTRY( "EndTestSession", CCollectionManagerTest::EndTestSessionL )
+        };
+
+    const TInt count = sizeof( KFunctions ) / 
+                        sizeof( TStifFunctionInfo );
+
+    return RunInternalL( KFunctions, count, aItem );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::CollectionChangedL
+// -----------------------------------------------------------------------------
+//
+void CCollectionManagerTest::CollectionChangedL( const TArray<TInt>& /*aCollectionIdArray*/ )
+    {
+    // This is not going to be called
+    }    
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::CollectionManagerErrorL
+// -----------------------------------------------------------------------------
+//
+void CCollectionManagerTest::CollectionManagerErrorL( TInt /*aError*/ )
+    {
+    // This is not going to be called
+    }    
+
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::CreateCollectionManagerLL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::CreateCollectionManagerL( CStifItemParser& /* aItem */ )
+    {
+    iCollectionManager = MediaCollectionManagerFactory::CreateCollectionManagerL( );
+    
+    return KErrNone;
+    }    
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::GetCollectionInfosL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::GetCollectionInfosL( CStifItemParser& /* aItem */ )
+	{
+    _LIT( KMsg1, "Enter GetCollectionInfosL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+	
+    TInt error( KErrNone );
+    
+    if( iCollectionManager )
+        {
+        RPointerArray<MMediaCollectionInfo> collectionInfoArray;
+        TRAP( error, iCollectionManager->GetCollectionInfosL( collectionInfoArray ) );
+        if( error != KErrNotSupported && error != KErrNone )
+            {
+            return error;
+            }
+        error = KErrNone;
+        const TInt infoArrayCount( collectionInfoArray.Count() );
+        if( infoArrayCount > 0 )
+            {
+            error = KErrUnknown;
+            }
+        }
+    else
+        {
+        error = KErrUnknown;
+        }
+	
+    _LIT( KMsg2, "Exit GetCollectionInfosL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return error;
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::CollectionInfoByIdL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::CollectionInfoByIdL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "Enter CollectionInfoByIdL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    TInt collectionID( KErrNotFound );
+    TInt error( KErrNone );
+    MMediaCollectionInfo* mci = NULL;
+    if( !iCollectionManager )
+        {
+        return KErrUnknown;
+        }
+    
+    TRAP( error, mci = iCollectionManager->CollectionInfoByIdLC( collectionID ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        return error;
+        }
+    
+    if( mci )
+        {
+        return KErrCorrupt;
+        }
+    
+    TRAP( error, mci = iCollectionManager->CollectionInfoByIdLC( 0 ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        return error;
+        }
+    
+    if( mci )
+        {
+        return KErrCorrupt;
+        }
+    
+    _LIT( KMsg2, "Exit CollectionInfoByIdL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::CreateCollectionL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::CreateCollectionL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter CreateCollectionL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    if( !iCollectionManager )
+        {
+        return KErrUnknown;
+        }
+    
+    _LIT( KTestAlbumName, "TestAlbum" );
+    HBufC* collectionName = KTestAlbumName().AllocL();
+    RArray<TInt> types;
+    types.AppendL( 1 );
+    TInt32 properties = EMCPhoneMemoryCollection;
+
+    TInt collectionId( KErrNotFound );
+    TInt error( KErrNone );
+    TRAP( error, collectionId = iCollectionManager->CreateCollectionL( *collectionName, types.Array(), properties ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        delete collectionName;
+        collectionName = NULL;
+        return error;
+        }
+
+    properties = EMCMmcCollection;
+    TRAP( error, collectionId = iCollectionManager->CreateCollectionL( *collectionName, types.Array(), properties ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        delete collectionName;
+        collectionName = NULL;
+        return error;
+        }
+
+    MMediaCollectionInfo* mci = NULL;
+    TRAP( error, iCollectionManager->CollectionInfoByIdLC( collectionId ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        delete collectionName;
+        collectionName = NULL;
+        return error;
+        }
+
+    if( mci )
+        {
+        delete collectionName;
+        collectionName = NULL;
+        return KErrCorrupt;
+        }
+
+    delete collectionName;
+    collectionName = NULL;
+    
+    _LIT( KMsg2, "Exit CreateCollectionL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::DeleteCollectionL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::DeleteCollectionL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter DeleteCollectionL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    if( !iCollectionManager )
+        {
+        return KErrUnknown;
+        }
+    
+    TInt collectionId( KErrNotFound );
+    TInt error( KErrNone );
+    TRAP( error, iCollectionManager->DeleteCollectionL( collectionId ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        return error;
+        }
+
+    collectionId = 0;
+    TRAP( error, iCollectionManager->DeleteCollectionL( collectionId ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        return error;
+        }
+    
+    _LIT( KMsg2, "Exit DeleteCollectionL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::RenameCollectionL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::RenameCollectionL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter RenameCollectionL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    if( !iCollectionManager )
+        {
+        return KErrUnknown;
+        }
+    
+    TInt collectionId( KErrNotFound );
+    TInt error( KErrNone );
+    
+    _LIT( KTestAlbumName, "NewTestAlbum" );
+    HBufC* collectionNewName = KTestAlbumName().AllocL();
+    
+    TRAP( error, iCollectionManager->RenameCollectionL( collectionId, *collectionNewName ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        delete collectionNewName;
+        collectionNewName = NULL;
+        return error;
+        }
+
+    MMediaCollectionInfo* mci = NULL;
+    
+    TRAP( error, mci= iCollectionManager->CollectionInfoByIdLC( collectionId ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        delete collectionNewName;
+        collectionNewName = NULL;
+        return error;
+        }
+    
+    if( mci )
+        {
+        delete collectionNewName;
+        collectionNewName = NULL;
+        return KErrCorrupt;
+        }
+    
+    delete collectionNewName;
+    collectionNewName = NULL;
+    
+    _LIT( KMsg2, "Exit RenameCollectionL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::AddToCollectionL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::AddToCollectionL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter AddToCollectionL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+
+    if( !iCollectionManager )
+        {
+        return KErrUnknown;
+        }
+    
+    const TInt itemCount( 500 );
+    CDesCArray* newItemArray = new (ELeave) CDesCArrayFlat( itemCount );
+
+    for( TInt i = 0 ; i < itemCount ; ++i )
+        {
+        TBuf<40> b;
+        b.Num( i );
+        b.Append( _L("TestItem") );
+        newItemArray->AppendL( b );
+        }
+    
+    TInt collectionId( KErrNotFound );
+    TInt error( KErrNone );
+    TRAP( error, iCollectionManager->AddToCollectionL( collectionId, *newItemArray, ETrue ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        delete newItemArray;
+        newItemArray = NULL;
+        return error;
+        }
+
+    TRAP( error, iCollectionManager->AddToCollectionL( collectionId, *newItemArray, EFalse ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        delete newItemArray;
+        newItemArray = NULL;
+        return error;
+        }
+
+    delete newItemArray;
+    newItemArray = NULL;
+
+    _LIT( KMsg2, "Exit AddToCollectionL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::RemoveFromCollectionL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::RemoveFromCollectionL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter RemoveFromCollectionL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+
+    if( !iCollectionManager )
+        {
+        return KErrUnknown;
+        }
+    
+    const TInt itemCount( 500 );
+    CDesCArray* removeItemArray = new (ELeave) CDesCArrayFlat( itemCount );
+
+    for( TInt i = 0 ; i < itemCount ; ++i )
+        {
+        TBuf<40> b;
+        b.Num( i );
+        b.Append( _L("TestItem") );
+        removeItemArray->AppendL( b );
+        }
+
+    TInt collectionId( KErrNotFound );
+    TInt error( KErrNone );
+    TRAP( error, iCollectionManager->RemoveFromCollectionL( collectionId, *removeItemArray ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        delete removeItemArray;
+        removeItemArray = NULL;
+        return error;
+        }
+
+    delete removeItemArray;
+    removeItemArray = NULL;
+    
+    _LIT( KMsg2, "Exit RemoveFromCollectionL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::RemoveFromAllCollectionsL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::RemoveFromAllCollectionsL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "Enter RemoveFromAllCollectionsL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    if( !iCollectionManager )
+        {
+        return KErrUnknown;
+        }
+    
+    const TInt itemCount( 500 );
+    CDesCArray* removeItemArray = new (ELeave) CDesCArrayFlat( itemCount );
+
+    for( TInt i = 0 ; i < itemCount ; ++i )
+        {
+        TBuf<40> b;
+        b.Num( i );
+        b.Append( _L("TestItem") );
+        removeItemArray->AppendL( b );
+        }
+    
+    TInt error( KErrNone );
+    TRAP( error, iCollectionManager->RemoveFromAllCollectionsL( *removeItemArray ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        delete removeItemArray;
+        removeItemArray = NULL;
+        return error;
+        }
+    
+    delete removeItemArray;
+    removeItemArray = NULL;
+    
+    _LIT( KMsg2, "Exit RemoveFromAllCollectionsL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::GetCollectionItemArrayL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::GetCollectionItemArrayL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "Enter GetCollectionItemArrayL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+   
+    if( !iCollectionManager )
+        {
+        return KErrUnknown;
+        }
+    
+    CDesCArraySeg* collectionItemArray = new (ELeave) CDesCArraySeg( 4 );
+    CleanupStack::PushL( collectionItemArray );
+
+    TInt collectionId( KErrNotFound );
+    TInt error( KErrNone );
+    TRAP( error, iCollectionManager->GetCollectionItemArrayL( collectionId, *collectionItemArray ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        CleanupStack::PopAndDestroy(collectionItemArray);
+        return error;
+        }
+    
+    if( collectionItemArray->Count() > 0 )
+        {
+        CleanupStack::PopAndDestroy(collectionItemArray);
+        return KErrUnknown;
+        }
+    
+    CleanupStack::PopAndDestroy(collectionItemArray);
+    
+    _LIT( KMsg2, "Exit GetCollectionItemArrayL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::GetCollectionIdByItemL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::GetCollectionIdByItemL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter GetCollectionIdByItemL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+
+    if( !iCollectionManager )
+        {
+        return KErrUnknown;
+        }
+    
+    _LIT( KTestItemName, "GetCollectionIdByItemTestItem");
+    HBufC* getCollectionIdByItemTestItemName = KTestItemName().AllocL();
+    
+    RArray<TInt> idArray;
+    CleanupClosePushL( idArray );
+    TInt error( KErrNone );
+    TRAP( error, iCollectionManager->GetCollectionIdByItemL( *getCollectionIdByItemTestItemName, idArray ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        CleanupStack::PopAndDestroy(&idArray);
+        delete getCollectionIdByItemTestItemName;
+        getCollectionIdByItemTestItemName = NULL;
+        return error;
+        }
+
+    const TInt idArrayCount( idArray.Count() );
+    if( idArrayCount > 0 )
+        {
+        CleanupStack::PopAndDestroy(&idArray);
+        delete getCollectionIdByItemTestItemName;
+        getCollectionIdByItemTestItemName = NULL;
+        return KErrUnknown;
+        }
+
+    CleanupStack::PopAndDestroy(&idArray);
+	
+    delete getCollectionIdByItemTestItemName;
+    getCollectionIdByItemTestItemName = NULL;
+    
+    _LIT( KMsg2, "Enter GetCollectionIdByItemL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::AddCollectionObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::AddCollectionObserverL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter AddCollectionObserverL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+
+    if( !iCollectionManager )
+        {
+        return KErrUnknown;
+        }
+    
+    TInt err( KErrNone );
+    TRAP( err, iCollectionManager->AddCollectionObserverL( *this ) );
+    if( err != KErrNotSupported && err != KErrNone )
+        {
+        return err;
+        }
+    
+    _LIT( KMsg2, "Exit AddCollectionObserverL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::RemoveCollectionObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::RemoveCollectionObserverL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter RemoveCollectionObserverL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+ 
+    if( !iCollectionManager )
+        {
+        return KErrUnknown;
+        }
+    
+    TInt err( KErrNone );
+    TRAP( err, iCollectionManager->AddCollectionObserverL( *this ) );
+    if( err != KErrNotSupported && err != KErrNone )
+        {
+        return err;
+        }
+    
+    TRAP( err, iCollectionManager->RemoveCollectionObserverL( *this ) );
+    if( err != KErrNotSupported && err != KErrNone )
+        {
+        return err;
+        }
+    
+    _LIT( KMsg2, "Exit RemoveCollectionObserverL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::GetDriveByIdL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::GetDriveByIdL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter GetDriveByIdL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    if( !iCollectionManager )
+        {
+        return KErrUnknown;
+        }
+    
+    TInt collectionId( KErrNotFound );
+
+    TInt32 drive( 100 );
+    TInt error( KErrNone );
+    
+    TRAP( error, drive = iCollectionManager->GetDriveByIdL( collectionId ) );
+    if( error != KErrNotSupported && error != KErrNone )
+        {
+        return error;
+        }
+    
+    if( drive != 100 )
+        {
+        return KErrUnknown;
+        }
+    
+    _LIT( KMsg2, "Exit GetDriveByIdL" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCollectionManagerTest::EndTestSessionL
+// -----------------------------------------------------------------------------
+//
+TInt CCollectionManagerTest::EndTestSessionL( CStifItemParser& /* aItem */ )
+    {
+    delete iCollectionManager;
+    iCollectionManager = NULL;
+    
+    return KErrNone;
+    }   
+
+//  [End of File] - Do not remove
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_extended_api/content_listing_framework_extended_api.metaxml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,18 @@
+<?xml version="1.0" ?>
+<api id="2231631539093c174cf16a6a03154c44" dataversion="2.0">
+  <name>Content Listing Framework Extended API</name>
+  <description>An extended interface for Content Listing Framework</description>
+  <type>c++</type>
+  <collection>clfwrapper</collection>
+  <libs>
+    <lib name="ContentListingFramework.lib" />
+  </libs>
+  <release category="platform"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>no</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_extended_api/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+:                Content Listing Framework Extended API
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/CLFContentListingExtended.hrh     MW_LAYER_PLATFORM_EXPORT_PATH(CLFContentListingExtended.hrh)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/content_listing_framework_extended_api/inc/CLFContentListingExtended.hrh	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,69 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  S60 internal CLF field IDs
+*
+*/
+
+
+#ifndef CLFCONTENTLISTINGEXTENDED_HRH
+#define CLFCONTENTLISTINGEXTENDED_HRH
+
+#include <CLFContentListing.hrh>
+
+// DATA TYPES
+
+/**
+*  Content Listing Framework list model media types.
+*  Last default media type is 0x7FFFFFFF,
+*  Custom media type range 0x80000000 0xFFFFFFFF
+*/
+enum TCLFMediaTypeExtended
+    {
+    /// Gallery collections
+    ECLFMediaTypeCollection     = 0x7
+    };
+
+/**
+*  S60 internal Content Listing Framework item field IDs.
+*  Last default field ID is 0x7FFFFFFF,
+*  Custom field ID range 0x80000000 - 0xFFFFFFFF
+*/
+enum TCLFExtendedFieldId
+    {
+    /// Media gallery collection name:
+    /// descriptor
+    ECLFFieldIdCollectionName       = 0x00002000,
+    /// Media gallery collection ID:
+    /// integer
+    ECLFFieldIdCollectionId         = 0x00002001,
+    /// Media gallery collection type:
+    /// integer
+    ECLFFieldIdCollectionType       = 0x00002002,
+    /// Media gallery collection memory:
+    /// integer
+    ECLFFieldIdCollectionMemory     = 0x00002003,
+    /// Media gallery collection properties:
+    /// integer
+    ECLFFieldIdCollectionProperties = 0x00002004,
+    /// Media gallery collection files:
+    /// descriptor
+    ECLFFieldIdCollectionFiles      = 0x00002005,
+    /// Media gallery item count of the collection:
+    /// integer
+    ECLFFieldIdCollectionItemCount  = 0x00002006
+    };
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/context_engine_plugin_api.metaxml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,15 @@
+<?xml version="1.0" ?>
+<api id="9555a94f3da3c949de8bcafcabcb1ce4" dataversion="2.0">
+<name>context engine plugin api</name>
+<description>Context engine plugin api</description>
+<type>c++</type>
+<collection>contextengine</collection>
+<libs><lib name="contextplugininterface.lib"/>
+<lib name="contextengine.lib"/>
+</libs>
+<release category="platform" sinceversion=""/>
+<attributes>
+<htmldocprovided>no</htmldocprovided>
+<adaptation>no</adaptation>
+</attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+../inc/contextplugin.h    MW_LAYER_PLATFORM_EXPORT_PATH(contextplugin.h)
+../inc/contextengine.h    MW_LAYER_PLATFORM_EXPORT_PATH(contextengine.h)
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/inc/contextengine.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,224 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An engine to collect context related metadata.
+*
+*/
+
+// Statically linked dll
+
+#ifndef CCONTEXTENGINE_H
+#define CCONTEXTENGINE_H 
+
+#include <e32cons.h>
+#include <e32cmn.h>
+
+//forward declarations
+
+class CMdEObject; 
+class CContextEngineAO;
+class CContextSnapshotItem;
+class CMdESession;
+class CHarvesterData;
+
+/**
+* An interface for observer that wants to be informed about
+* context engine initialization completion and
+* snapshot completion.
+*/
+class MContextInitializationObserver
+    {
+    public:
+        /**
+         * Pure virtual method. Intended to inform about
+         * context engine initialization completion.
+         *
+         * @param aErrorCode  Error code for error occurred during initialization 
+         */
+        virtual void ContextInitializationStatus( TInt aErrorCode ) = 0;
+    };
+
+/**
+* An interface for observers that want to be informed about context snapshot completion.
+*/
+class MContextSnapshotObserver
+    {
+    public:
+        /**
+         * Pure virtual method. Intended to inform about context snapshot taking completion.
+         *
+         * @param aErrorCode  Error code for error occurred while taking the snapshot.
+         */
+        virtual void ContextSnapshotStatus( CHarvesterData* aHD ) = 0;
+    };
+
+/**
+* An engine to collect context metadata with available context plugins.
+* CContextEngineAO is used to do the actual work.
+* This class is implemented as a Singleton.
+*/
+NONSHARABLE_CLASS( CContextEngine ) : public CBase, public MContextSnapshotObserver
+      {
+    public:
+
+        /**
+         * Destroys the implementation. This is virtual method
+         * and this class is not intended for derivation, so not exported.
+         */
+        virtual ~CContextEngine();
+
+        /**
+         * Gets an instance to CContextEngine singleton.
+         * A new object is created if needed.
+         * If an observer object to notify is given, context plugins are initialized
+         * asyncronously and observer is notified when ready.
+         *
+         * @param aObserver  an interface class for callback or NULL
+         * @return A pointer to the context engine implementation
+         */ 
+        IMPORT_C static CContextEngine* GetInstanceL( MContextInitializationObserver* aObserver = NULL );
+
+        /**
+         * Release an instance of this singleton.
+         */
+        IMPORT_C void ReleaseInstance();
+
+        /**
+         * Ignores the reference count and destroys this singleton.
+         * THINK BEFORE USING! Should be used only instead of reference counting
+         * if clients are not calling ReleaseInstance() (which they should).
+         */
+        IMPORT_C void Destroy();
+
+        /**
+         * Set a pointer to MdESession. The pointer is given forward to context plugins.
+         * Session must be set in order to successfully harvest context data.
+         *
+         * @param aSession Session pointer to set.
+         */
+        IMPORT_C void SetMdeSession( CMdESession* aSession );
+
+        /**
+         * Context snapshot. This takes the snapshot using plug-ins.
+         *
+         * @param aObserver  an interface class for callback.
+         * @param aMetadataObject  MdE object the snapshot is taken to.
+         */
+        IMPORT_C void ContextSnapshot( MContextSnapshotObserver& aObserver,
+            CHarvesterData& aHD );
+        
+        /**
+         * Context snapshot. This takes the snapshot using plug-ins.
+         *
+         * @param aObserver  an interface class for callback.
+         * @param aMetadataObjectArray  An array of MdE objects the snapshot is taken to.
+         */
+        IMPORT_C void ContextSnapshot( MContextSnapshotObserver& aObserver,
+            RPointerArray<CHarvesterData>& aMetadataObjectArray );
+        
+        /**
+         * Method used to clarify amount of plug-ins.
+         *
+         * @return Amount of plug-ins. Intended for test purposes only.
+         */
+        IMPORT_C TInt PluginCount();
+
+        /**
+         * From MContextEngineObserver.
+         * Method is called by CContextEngineAO when a context snapshot is finished
+         * or an error has occured.
+         *
+         * @param aErrorCode  Error code for error occurred during snapshot.
+         */
+        void ContextSnapshotStatus( CHarvesterData* aHD );
+
+    private:
+
+        /**
+         * C++ constructor - not exported;
+         * implicitly called from GetInstance()
+         *
+         */
+        CContextEngine();
+        
+        /**
+         * 2nd phase construction, called by GetInstance()
+         *
+         * @param aObserver object/callback to notify when initialization is ready.
+         */
+        void ConstructL( MContextInitializationObserver* aObserver );
+
+        /**
+         * Add a new observer and metadata items to a queue.
+         * These observers need to be informed when a snapshot is ready
+         * and items need a context snapshot.
+         *
+         * @param aItem  An item to add.
+         */
+        void QueueSnapshotItem( CContextSnapshotItem* aItem );
+
+    private: // data
+
+        /**
+         * This active object is used to handle queued snapshot requests.
+         */
+        CContextEngineAO* iContextEngineAO;
+
+        /**
+         * Array of observers and related metadata objects that need
+         * a context snapshot.
+         * Related observer is informed about snapshot completion.
+         */
+        RPointerArray<CContextSnapshotItem> iSnapshotQueue;
+        
+        /**
+         * In case array of objects for snapshot were passed,
+         * variable to store the amount of items to be processed.
+         */
+        TInt iArrayCount;
+        
+        /**
+         * In case array of objects for snapshot were passed,
+         * variable to store the amount of items that have been processed.
+         */
+        TInt iProcessedArrayCount;
+    };
+
+
+/**
+* A helper class to store this singleton's static data.
+*/
+NONSHARABLE_CLASS( CContextEngineStaticData ): public CBase
+    {
+    friend class CContextEngine;
+        
+    public:
+
+        CContextEngineStaticData( CContextEngine* aContextEngine ) : iContextEngine(aContextEngine)
+            {
+            iRefCount = 1;
+            }
+
+        virtual ~CContextEngineStaticData()
+            {
+            delete iContextEngine;
+            }
+
+    protected:
+
+        CContextEngine* iContextEngine;
+        TInt iRefCount;
+    };
+
+
+#endif // CCONTEXTENGINE_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/inc/contextplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,128 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition of the Context plug-in ECom interface.
+*
+*/
+
+#ifndef CCONTEXTPLUGIN_H
+#define CCONTEXTPLUGIN_H
+
+#include <e32base.h>
+#include <implementationinformation.h>
+
+// forward declarations
+class CMdEObject;
+class CMdESession;
+class CHarvesterData;
+
+/** Uid for this interface */
+const TUid KCContextPluginInterfaceUid = { 0x200009F7 };
+
+class MContextPluginObserver
+	{
+public:
+    /**
+     * A pure virtual method intended to inform about completion of context
+     * plug-in initialization. Symbian error codes are used.
+     *
+     * @param aErrorCode  Error code for error occurred during initialization.
+     */
+    virtual void PluginInitializationStatus( TInt aErrorCode ) = 0;
+
+    /**
+     * A pure virtual method intended to inform about context snapshot taking completion.
+     * Symbian error codes are used.
+     *
+     * @param aErrorCode  Error code for error occurred while taking the snapshot.
+     */
+    virtual void PluginSnapshotStatus( CHarvesterData* aHD ) = 0;
+    };
+
+
+/**
+* This class implements the context plugin interface.
+*/
+class CContextPlugin : public CBase
+    {
+public:
+
+    /**
+     * Creates an implementation of a desired implementation defined by the parameter.
+     *
+     * @param aUid 
+     * @return A pointer to the created plug-in.
+     */
+    IMPORT_C static CContextPlugin* NewL( const TUid& aUid );
+    
+    /**
+     * Destroys the implementation. This is virtual method
+     * and this class is not intended for derivation, so not exported.
+     */
+    IMPORT_C virtual ~CContextPlugin();
+
+    /**
+     * Lists all available implementations which implement this interface.
+     *
+     * @param[out] aImplInfoArray A list of existing implementations of the interface.
+     */
+    IMPORT_C static void ListImplementationsL( RImplInfoPtrArray& aImplInfoArray );
+
+    /**
+     * A pure virtual interface method to initialize the plug-in.
+     *
+     * @param aObserver An interface class to inform about initialization completion.
+     */
+    virtual void Init( MContextPluginObserver& aObserver ) = 0;
+
+    /**
+     * Set a pointer to MdESession.
+     * Session is used to store harvested context data.
+     *
+     * @param aSession Session pointer to set.
+     */
+    virtual void SetMdeSession( CMdESession& aSession ) = 0;
+
+    /**
+     * This pure virtual method takes the context snapshot for one metadata object
+     * and writes the information to the object received as parameter.
+     * The observer will be informed about the status of the operation.
+     *
+     * @param aObserver  An interface class to inform about finishing context snapshot.
+     * @param aMetadataObject An object to take the snapshot for.
+     */
+    virtual void ContextSnapshot( MContextPluginObserver& aObserver, CHarvesterData& aHD ) = 0;
+
+    /**
+     * This pure virtual method takes the context snapshot for several
+     * metadata object and writes the information to the all the objects received as parameter.
+     * The observer will be informed about the status of the operation.
+     *
+     * @param aObserver  An interface class to inform about finishing context snapshot.
+     * @param aMetadataObjectArray Array of objects to take the snapshot for.
+     */
+    virtual void ContextSnapshot( MContextPluginObserver& aObserver,
+                          RPointerArray<CHarvesterData>& aHDArray ) = 0;
+
+private: // data
+
+    /** 
+     * Instance identifier key. When instance of an implementation is created
+     * by ECOM framework, the framework will assign UID for it.
+     * The UID is used in destructor to notify framework that this instance is
+     * being destroyed and resources can be released.
+     */
+    TUid iDtor_ID_Key;
+    };
+
+#endif // CCONTEXTPLUGIN_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/tsrc/Bmarm/ContextEnginePluginTestU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	LibEntryL__FR13CTestModuleIf @ 1 NONAME R3UNUSED ; LibEntryL(CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/tsrc/Bwins/ContextEnginePluginTestU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?LibEntryL@@YAPAVCScriptBase@@AAVCTestModuleIf@@@Z @ 1 NONAME ; class CScriptBase * __cdecl LibEntryL(class CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/tsrc/EABI/ContextEnginePluginTestU.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	_Z9LibEntryLR13CTestModuleIf @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/tsrc/conf/ContextEnginePluginTest.cfg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,207 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  Context Engine Plugin API tests
+#
+
+// ---------------------------------------------------------------------------
+// Context Engine Plugin API test cases
+// ---------------------------------------------------------------------------
+
+// These should be run in sequential mode if several cases are run at the same
+// time!
+
+[StifSettings]
+TestThreadStackSize= 32768
+TestThreadMinHeap= 4096
+TestThreadMaxHeap= 16777216
+[EndStifSettings]
+
+[Test]
+title Get ContextEngine instance with observer
+create ContextEnginePluginTest test
+request Session
+test BeginTestSession
+wait Session
+request Init
+test CreateContextEngineWithObserver
+wait Init
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Get ContextEngine instance without observer
+create ContextEnginePluginTest test
+request Session
+test BeginTestSession
+wait Session
+test CreateContextEngineWithoutObserver
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Release ContextEngine instance
+create ContextEnginePluginTest test
+request Session
+test BeginTestSession
+wait Session
+test CreateContextEngineWithoutObserver
+test ReleaseContextEngineInstance
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Set MdE session test
+create ContextEnginePluginTest test
+request Session
+test BeginTestSession
+wait Session
+request Init
+test SetMdESessionTest
+wait Init
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Context Engine Snapshots
+create ContextEnginePluginTest test
+request Session
+test BeginTestSession
+wait Session
+test CreateObjects 3 e:\testing\data\Jpg.jpg e:\testing\data\Animated.gif e:\testing\data\H263.3gp
+request Init
+test CreateContextEngineWithObserver
+wait Init
+request Snapshot
+test ContextSnapshots engine
+wait Snapshot
+wait Snapshot
+wait Snapshot
+wait Snapshot
+wait Snapshot
+wait Snapshot
+wait Snapshot
+wait Snapshot
+wait Snapshot
+test DeleteObjects
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Context Engine Multiple Snapshots
+create ContextEnginePluginTest test
+request Session
+test BeginTestSession
+wait Session
+test CreateObjects 3 e:\testing\data\Jpg.jpg e:\testing\data\Animated.gif e:\testing\data\H263.3gp
+request Init
+test CreateContextEngineWithObserver
+wait Init
+request Snapshot
+test MultipleSnapshots engine
+wait Snapshot
+wait Snapshot
+test DeleteObjects
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Context Engine Plugin Count
+create ContextEnginePluginTest test
+request Session
+test BeginTestSession
+wait Session
+request Init
+test CreateContextEngineWithObserver
+wait Init
+test PluginCount
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Context Engine Static Data
+create ContextEnginePluginTest test
+request Session
+test BeginTestSession
+wait Session
+test CreateContextEngineWithoutObserver
+test ContextEngineStaticData
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Context Plugin Startup/Shutdown
+create ContextEnginePluginTest test
+request Session
+test BeginTestSession
+wait Session
+request Init
+test LoadPlugin
+wait Init
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Context Plugin Snapshots
+create ContextEnginePluginTest test
+request Session
+test BeginTestSession
+wait Session
+test CreateObjects 3 e:\testing\data\Jpg.jpg e:\testing\data\Animated.gif e:\testing\data\H263.3gp
+request Init
+test LoadPlugin
+wait Init
+test ContextSnapshots plugin
+test DeleteObjects
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Context Plugin Array Snapshots
+create ContextEnginePluginTest test
+request Session
+test BeginTestSession
+wait Session
+test CreateObjects 3 e:\testing\data\Jpg.jpg e:\testing\data\Animated.gif e:\testing\data\H263.3gp
+request Init
+test LoadPlugin
+wait Init
+test MultipleSnapshots plugin
+test DeleteObjects
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Context Engine Destroy
+create ContextEnginePluginTest test
+request Session
+test BeginTestSession
+wait Session
+request Init
+test CreateContextEngineWithObserver
+wait Init
+test Destroy
+test EndTestSession
+delete test
+[Endtest]
\ No newline at end of file
Binary file mds_plat/context_engine_plugin_api/tsrc/data/mmc/ContextEnginePluginTest/Animated.gif has changed
Binary file mds_plat/context_engine_plugin_api/tsrc/data/mmc/ContextEnginePluginTest/H263.3gp has changed
Binary file mds_plat/context_engine_plugin_api/tsrc/data/mmc/ContextEnginePluginTest/Jpg.jpg has changed
Binary file mds_plat/context_engine_plugin_api/tsrc/data/mmc/ContextEnginePluginTest/Thumbs.db has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/tsrc/group/ContextEnginePluginTest.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET          ContextEnginePluginTest.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E3
+
+CAPABILITY      ALL -TCB
+VENDORID        VID_DEFAULT
+
+DEFFILE         ContextEnginePluginTest.DEF
+
+SOURCEPATH      ../src
+SOURCE          ContextEnginePluginTest.cpp
+SOURCE          ContextEnginePluginTestBlocks.cpp
+
+SYSTEMINCLUDE     /epoc32/include/ecom
+USERINCLUDE     ../inc ../../../../inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+LIBRARY         contextengine.lib
+LIBRARY         contextplugininterface.lib
+LIBRARY         mdeclient.lib
+LIBRARY	    ecom.lib
+LIBRARY	    harvesterdata.lib
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/tsrc/group/ContextEnginePluginTest.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,38 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+; Installation file for API test
+
+; Languages
+&EN
+
+; Header
+#{"ContextEnginePluginTest"},(0x101FB3E3),1,0,1,TYPE=SA
+
+; Localised Vendor name
+%{"Nokia-EN"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Files
+"\epoc32\release\armv5\urel\ContextEnginePluginTest.dll"      -"C:\sys\bin\ContextEnginePluginTest.dll"
+"..\init\ContextEnginePluginTest.ini"      -"C:\testframework\ContextEnginePluginTest.ini"
+"..\conf\ContextEnginePluginTest.cfg"      -"C:\testframework\ContextEnginePluginTest.cfg"
+
+"..\data\mmc\ContextEnginePluginTest\Jpg.jpg"      -"E:\testing\data\Jpg.jpg"
+"..\data\mmc\ContextEnginePluginTest\Animated.gif"      -"E:\testing\data\Animated.gif"
+"..\data\mmc\ContextEnginePluginTest\H263.3gp"      -"E:\testing\data\H263.3gp"
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/tsrc/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+ContextEnginePluginTest.mmp
+
+PRJ_TESTEXPORTS
+../conf/ContextEnginePluginTest.cfg /epoc32/winscw/c/TestFramework/ContextEnginePluginTest.cfg
+../init/ContextEnginePluginTest.ini /epoc32/winscw/c/TestFramework/ContextEnginePluginTest.ini
+../data/mmc/ContextEnginePluginTest/Jpg.jpg /epoc32/WINSCW/C/Data/Jpg.jpg
+../data/mmc/ContextEnginePluginTest/Jpg.jpg /epoc32/WINSCW/C/Data/Animated.gif
+../data/mmc/ContextEnginePluginTest/H263.3gp /epoc32/WINSCW/C/Data/H263.3gp
+
+//  End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/tsrc/inc/ContextEnginePluginTest.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,140 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef CONTEXTENGINEPLUGINTEST_H
+#define CONTEXTENGINEPLUGINTEST_H
+
+//  INCLUDES
+#include <StifLogger.h>
+#include <TestScripterInternal.h>
+#include <StifTestModule.h>
+
+#include <mdesession.h>
+#include <contextengine.h>
+#include <contextplugin.h>
+
+// Logging path
+_LIT( KContextEnginePluginTestLogPath, "\\logs\\testframework\\ContextEnginePluginTest\\" ); 
+// Log file
+_LIT( KContextEnginePluginTestLogFile, "ContextEnginePluginTest.txt" ); 
+_LIT( KContextEnginePluginTestLogFileWithTitle, "ContextEnginePluginTest_[%S].txt" );
+
+// FORWARD DECLARATIONS
+class CContextEnginePluginTest;
+
+// CLASS DECLARATION
+NONSHARABLE_CLASS(CContextEnginePluginTest) : public CScriptBase,
+											  public MMdESessionObserver,
+				                              public MContextInitializationObserver,
+				                              public MContextSnapshotObserver,
+				                              public MContextPluginObserver
+				                              
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CContextEnginePluginTest* NewL( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CContextEnginePluginTest();
+
+    public: // Functions from base classes
+
+        virtual TInt RunMethodL( CStifItemParser& aItem );
+
+    private: // Functions from base classes
+    	
+    	void HandleSessionOpened(CMdESession& aSession, TInt aError);
+    	void HandleSessionError(CMdESession& aSession, TInt aError);
+        void ContextInitializationStatus( TInt aError );
+        void ContextSnapshotStatus( CHarvesterData* aHD );        
+        void PluginInitializationStatus( TInt aError );
+        void PluginSnapshotStatus( CHarvesterData* aHD );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CContextEnginePluginTest( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Frees all resources allocated from test methods.
+        */
+        void Delete();
+
+        void ActiveWait( TInt aTimeout );
+        
+        /**
+        * Test methods are listed below. 
+        */
+
+        // engine
+        virtual TInt BeginTestSessionL( CStifItemParser& aItem );
+        virtual TInt EndTestSession( CStifItemParser& aItem );
+        virtual TInt CreateObjectsL( CStifItemParser& aItem );
+        virtual TInt DeleteObjectsL( CStifItemParser& aItem );
+        virtual TInt CreateContextEngine1L( CStifItemParser& aItem );
+        virtual TInt CreateContextEngine2L( CStifItemParser& aItem );
+        virtual TInt ReleaseInstanceL( CStifItemParser& aItem );
+        virtual TInt SetMdeSessionL( CStifItemParser& aItem );
+        virtual TInt ContextSnapshotsL( CStifItemParser& aItem );
+        virtual TInt MultipleSnapshotsL( CStifItemParser& aItem );
+        virtual TInt PluginCount( CStifItemParser& aItem );
+        virtual TInt Destroy( CStifItemParser& aItem );
+        virtual TInt ContextEngineStaticData( CStifItemParser& aItem );
+        
+        // plugin
+        virtual TInt LoadPluginL( CStifItemParser& aItem );
+
+    private:    // Data
+        
+        CMdESession* iMdEClient;
+        CContextEngine* iContextEngine;
+        CHarvesterData* iHD;
+        
+        RPointerArray<CHarvesterData> iObjectArray;
+        RArray<TInt> iIds;
+        
+        CContextPlugin* iPlugin;
+        CContextPlugin* iLocationPlugin;
+        CContextPlugin* iCalendarPlugin;
+
+        TInt iErrorCode;
+        
+        TInt iInitCount;
+        TInt iSnapshotCount;
+        TInt iInitTarget;
+        TInt iSnapshotTarget;
+        
+        TBool iPluginSet;
+
+    };
+
+#endif      // CONTEXTENGINEPLUGINTEST_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/tsrc/init/ContextEnginePluginTest.ini	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,81 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  
+#
+
+
+[Engine_Defaults]
+
+TestReportMode= FullReport    # Possible values are: 'Empty', 'Summary', 'Environment',
+                                                     'TestCases' or 'FullReport'
+
+CreateTestReport= YES         # Possible values: YES or NO
+
+TestReportFilePath= C:\LOGS\TestFramework\
+TestReportFileName= ContextEnginePluginTestLog
+
+TestReportFormat= TXT         # Possible values: TXT or HTML
+TestReportOutput= FILE        # Possible values: FILE or RDEBUG
+TestReportFileCreationMode= OVERWRITE # Possible values: OVERWRITE or APPEND
+
+DeviceResetDllName= StifResetForNokia.dll # e.g. 'StifHWResetStub.dll' for user specific reseting
+
+DisableMeasurement= stifmeasurementdisablenone  # Possible values are:
+              # 'stifmeasurementdisablenone', 'stifmeasurementdisableall'
+              # 'stifmeasurementplugin01', 'stifmeasurementplugin02',
+              # 'stifmeasurementplugin03', 'stifmeasurementplugin04',
+              # 'stifmeasurementplugin05' or 'stifbappeaprofiler'
+
+Timeout= 600000		            # Default timeout value for each test case. In milliseconds
+#UITestingSupport= YES        # Possible values: YES or NO
+#SeparateProcesses= YES       # Possible values: YES or NO (default: NO)
+[End_Defaults]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[New_Module]
+ModuleName= TestScripter
+TestCaseFile= c:\testframework\ContextEnginePluginTest.cfg
+[End_Module]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[Logger_Defaults]
+
+#NOTE: If you want to set Logger using next setting(s) remove comment(s)'#'
+#NOTE: TestEngine and TestServer logging settings cannot change here
+
+CreateLogDirectories= YES    # Possible values: YES or NO
+
+#EmulatorBasePath= C:\LOGS\TestFramework\
+#EmulatorFormat= HTML         # Possible values: TXT or HTML
+#EmulatorOutput= FILE         # Possible values: FILE or RDEBUG
+
+HardwareBasePath= C:\
+#HardwareFormat= HTML         # Possible values: TXT or HTML
+#HardwareOutput= FILE         # Possible values: FILE or RDEBUG
+
+#FileCreationMode= OVERWRITE  # Possible values: OVERWRITE or APPEND
+
+#ThreadIdToLogFile= YES       # Possible values: YES or NO
+#WithTimeStamp= YES           # Possible values: YES or NO
+#WithLineBreak= YES           # Possible values: YES or NO
+#WithEventRanking= YES        # Possible values: YES or NO
+
+#FileUnicode= YES             # Possible values: YES or NO
+AddTestCaseTitle= YES        # Possible values: YES or NO
+[End_Logger_Defaults]
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+# End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/tsrc/src/ContextEnginePluginTest.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,130 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+// INCLUDE FILES
+#include <StifTestInterface.h>
+#include "ContextEnginePluginTest.h"
+#include <SettingServerClient.h>
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::CContextEnginePluginTest
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CContextEnginePluginTest::CContextEnginePluginTest( 
+    CTestModuleIf& aTestModuleIf ):
+        CScriptBase( aTestModuleIf )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CContextEnginePluginTest::ConstructL()
+    {
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        } 
+    // Close Setting server session
+    settingServer.Close();
+
+    TFileName logFileName;
+    
+    if(loggerSettings.iAddTestCaseTitle)
+        {
+        TName title;
+        TestModuleIf().GetTestCaseTitleL(title);
+        logFileName.Format(KContextEnginePluginTestLogFileWithTitle, &title);
+        }
+    else
+        {
+        logFileName.Copy(KContextEnginePluginTestLogFile);
+        }
+
+    iLog = CStifLogger::NewL( KContextEnginePluginTestLogPath, 
+                          logFileName,
+                          CStifLogger::ETxt,
+                          CStifLogger::EFile,
+                          EFalse );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CContextEnginePluginTest* CContextEnginePluginTest::NewL( 
+    CTestModuleIf& aTestModuleIf )
+    {
+    CContextEnginePluginTest* self = new (ELeave) CContextEnginePluginTest( aTestModuleIf );
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+
+    }
+
+// Destructor
+CContextEnginePluginTest::~CContextEnginePluginTest()
+    { 
+
+    // Delete resources allocated from test methods
+    Delete();
+
+    // Delete logger
+    delete iLog; 
+
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point.
+// Returns: CScriptBase: New CScriptBase derived object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScriptBase* LibEntryL( 
+    CTestModuleIf& aTestModuleIf ) // Backpointer to STIF Test Framework
+    {
+
+    return ( CScriptBase* ) CContextEnginePluginTest::NewL( aTestModuleIf );
+
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/context_engine_plugin_api/tsrc/src/ContextEnginePluginTestBlocks.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,981 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// [INCLUDE FILES] - do not remove
+#include <e32svr.h>
+#include <ecom.h>
+#include <StifParser.h>
+#include <StifTestEventInterface.h>
+#include <StifTestInterface.h>
+#include "ContextEnginePluginTest.h"
+
+#include <harvesterdata.h>
+#include "mdsutils.h"
+#include "mdeconstants.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::Delete
+// Delete here all resources allocated and opened from test methods. 
+// Called from destructor. 
+// -----------------------------------------------------------------------------
+//
+void CContextEnginePluginTest::Delete() 
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::RunMethodL
+// Run specified method. Contains also table of test mothods and their names.
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::RunMethodL( 
+    CStifItemParser& aItem ) 
+    {
+
+    static TStifFunctionInfo const KFunctions[] =
+        {  
+        // Copy this line for every implemented function.
+        // First string is the function name used in TestScripter script file.
+        // Second is the actual implementation member function. 
+
+        // engine		
+        ENTRY( "BeginTestSession", CContextEnginePluginTest::BeginTestSessionL ),
+        ENTRY( "EndTestSession", CContextEnginePluginTest::EndTestSession ),
+        ENTRY( "CreateObjects", CContextEnginePluginTest::CreateObjectsL ),
+        ENTRY( "DeleteObjects", CContextEnginePluginTest::DeleteObjectsL ),
+        ENTRY( "CreateContextEngineWithObserver", CContextEnginePluginTest::CreateContextEngine1L ),
+        ENTRY( "CreateContextEngineWithoutObserver", CContextEnginePluginTest::CreateContextEngine2L ),
+        ENTRY( "ReleaseContextEngineInstance", CContextEnginePluginTest::ReleaseInstanceL ),
+        ENTRY( "SetMdESessionTest", CContextEnginePluginTest::SetMdeSessionL ),
+        ENTRY( "PluginCount", CContextEnginePluginTest::PluginCount ),
+        ENTRY( "Destroy", CContextEnginePluginTest::Destroy ),
+        ENTRY( "ContextEngineStaticData", CContextEnginePluginTest::ContextEngineStaticData ),
+
+        ENTRY( "ContextSnapshots", CContextEnginePluginTest::ContextSnapshotsL ),
+        ENTRY( "MultipleSnapshots", CContextEnginePluginTest::MultipleSnapshotsL ),
+        
+        // plugin
+        ENTRY( "LoadPlugin", CContextEnginePluginTest::LoadPluginL ),
+
+        };
+
+    const TInt count = sizeof( KFunctions ) / 
+                        sizeof( TStifFunctionInfo );
+
+    return RunInternalL( KFunctions, count, aItem );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::HandleSessionOpened
+// -----------------------------------------------------------------------------
+//
+void CContextEnginePluginTest::HandleSessionOpened( CMdESession& /*aClient*/, TInt aError )
+    {
+    _LIT( KMsg, "CallBck HandleSessionOpened - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );     
+    RDebug::Print( msg );
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::HandleSessionError
+// -----------------------------------------------------------------------------
+//
+void CContextEnginePluginTest::HandleSessionError( CMdESession& /*aClient*/, TInt aError )
+    {
+    _LIT( KMsg, "CallBck HandleSessionError - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );
+    RDebug::Print( msg );
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+    }   
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::ContextInitializationStatus
+// -----------------------------------------------------------------------------
+//
+void CContextEnginePluginTest::ContextInitializationStatus( TInt aError )
+    {
+    _LIT( KMsg, "CallBck ContextInitializationStatus - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );
+    RDebug::Print( msg );
+    
+    iInitCount++;
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Init") );
+    TestModuleIf().Event( event );
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::ContextSnapshotStatus
+// -----------------------------------------------------------------------------
+//
+void CContextEnginePluginTest::ContextSnapshotStatus( CHarvesterData* aHD )
+    {
+    _LIT( KMsg1, "Enter ContextSnapshotStatus" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    _LIT( KMsg, "CallBck ContextSnapshotStatus - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aHD->ErrorCode());
+    iLog->Log( msg );
+    RDebug::Print( msg );
+    
+    if( !aHD )
+        {
+        iErrorCode = KErrUnknown;
+        }
+    
+    if( aHD && iErrorCode == KErrNone )
+        {
+        iErrorCode = aHD->ErrorCode();
+        }
+    
+    iSnapshotCount++;
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Snapshot") );
+    TestModuleIf().Event( event );
+    
+    _LIT( KMsg2, "Exit ContextSnapshotStatus" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::PluginInitializationStatus
+// -----------------------------------------------------------------------------
+//
+void CContextEnginePluginTest::PluginInitializationStatus( TInt aError )
+    {
+    _LIT( KMsg, "CallBck PluginInitializationStatus - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );
+    RDebug::Print( msg );
+    
+    iInitCount++;
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Init") );
+    TestModuleIf().Event( event );
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::PluginSnapshotStatus
+// -----------------------------------------------------------------------------
+//
+void CContextEnginePluginTest::PluginSnapshotStatus( CHarvesterData* aHD )
+    {
+    _LIT( KMsg1, "Enter PluginSnapshotStatus" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    _LIT( KMsg, "CallBck PluginSnapshotStatus - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aHD->ErrorCode());
+    iLog->Log( msg );
+    RDebug::Print( msg );
+    
+    if( !aHD )
+        {
+        iErrorCode = KErrUnknown;
+        }
+    
+    if( aHD && iErrorCode == KErrNone )
+        {
+        iErrorCode = aHD->ErrorCode();
+        }
+    
+    iSnapshotCount++;
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Snapshot") );
+    TestModuleIf().Event( event );
+    
+    _LIT( KMsg2, "Exit PluginSnapshotStatus" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::ActiveWait
+// -----------------------------------------------------------------------------
+//
+void CContextEnginePluginTest::ActiveWait( TInt aTimeout )
+    {
+    _LIT( KMsg1, "Enter ActiveWait" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+
+    TTimeIntervalMicroSeconds32 timeout( aTimeout );
+    RTimer timer;
+    TRequestStatus status;
+
+    timer.CreateLocal();
+    timer.After(status,timeout);
+
+    User::WaitForAnyRequest();
+    
+    timer.Close();
+    
+    _LIT( KMsg2, "Exit ActiveWait" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::BeginTestSessionL
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::BeginTestSessionL( CStifItemParser& /* aItem */ )
+    {
+    iMdEClient = NULL;
+    TRAPD( error, iMdEClient = CMdESession::NewL( *this ) );
+    iErrorCode = KErrNone;
+
+    _LIT( KMsg, "Exit BeginTestSession - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, error);
+    iLog->Log( msg );
+    RDebug::Print( msg );
+    
+    iInitCount = 0;
+    iSnapshotCount = 0;
+    iInitTarget = 0;
+    iSnapshotTarget = 0;
+    
+    iPluginSet = EFalse;
+    
+    User::LeaveIfError( error );
+    
+    return KErrNone;
+    }    
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::EndTestSession
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::EndTestSession( CStifItemParser& /* aItem */ )
+	{
+    _LIT( KMsg1, "Enter EndTestSession" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+	
+	iIds.Close();
+	iObjectArray.Close();
+	    
+    if ( iContextEngine )
+        {
+        iContextEngine->ReleaseInstance();
+        iContextEngine = NULL;
+        }
+    
+    if ( iPlugin )
+        {
+        delete iPlugin;
+        iPlugin = NULL;
+        }
+    
+    if ( iLocationPlugin && !iPluginSet )
+        {
+        delete iLocationPlugin;
+        iLocationPlugin = NULL;
+        }
+    
+    if ( iCalendarPlugin )
+        {
+        delete iCalendarPlugin;
+        iCalendarPlugin = NULL;
+        }
+	
+	if ( iMdEClient )
+		{
+	    delete iMdEClient;
+	    iMdEClient = NULL;
+	    }
+	
+	iHD = NULL;
+    
+    REComSession::FinalClose();
+	
+    if( iInitCount != iInitTarget )
+        {
+        return KErrUnknown;
+        }
+    
+    if( iSnapshotCount != iSnapshotTarget )
+        {
+        return KErrUnknown;
+        }
+    
+    _LIT( KMsg2, "Exit EndTestSession" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	
+    return iErrorCode;
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::CreateObjects
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::CreateObjectsL( CStifItemParser& aItem )
+    {
+	CMdENamespaceDef& defaultNamespace = iMdEClient->GetDefaultNamespaceDefL();
+	CMdEObjectDef& imageDef = defaultNamespace.GetObjectDefL( MdeConstants::Image::KImageObject );
+	
+	// Mandatory parameters for any object.
+	CMdEPropertyDef& creationDef = imageDef.GetPropertyDefL( MdeConstants::Object::KCreationDateProperty );
+	CMdEPropertyDef& modifiedDef = imageDef.GetPropertyDefL( MdeConstants::Object::KLastModifiedDateProperty );
+	CMdEPropertyDef& sizeDef = imageDef.GetPropertyDefL( MdeConstants::Object::KSizeProperty );
+	CMdEPropertyDef& itemTypeDef = imageDef.GetPropertyDefL( MdeConstants::Object::KItemTypeProperty );
+	
+	CMdEPropertyDef& descriptionPropertyDef = imageDef.GetPropertyDefL( MdeConstants::MediaObject::KDescriptionProperty );
+	CMdEPropertyDef& widthDef = imageDef.GetPropertyDefL( MdeConstants::MediaObject::KWidthProperty ); 
+	CMdEPropertyDef& heightDef = imageDef.GetPropertyDefL( MdeConstants::MediaObject::KHeightProperty ); 
+	CMdEPropertyDef& makeDef = imageDef.GetPropertyDefL( MdeConstants::Image::KMakeProperty );
+	CMdEPropertyDef& modelDef = imageDef.GetPropertyDefL( MdeConstants::Image::KModelProperty );
+    
+	CMdEObject* object = NULL;
+	TItemId objectId(0);
+	TTime currTime;
+	TPtrC inputFile;
+	TInt count(0);
+	TBuf <100> msg;
+	
+	iIds.Reset();
+	
+	User::LeaveIfError( aItem.GetNextInt( count ));
+	
+	for ( TInt i = 0; i < count; ++i )
+		{			
+		User::LeaveIfError( aItem.GetNextString( inputFile ));
+		
+		// create object
+		iMdEClient->RemoveObjectL(inputFile);
+		object = iMdEClient->NewObjectLC(imageDef, inputFile);
+		
+		currTime.HomeTime();
+		object->AddTimePropertyL(creationDef, currTime);
+		object->AddTimePropertyL(modifiedDef, currTime);
+		object->AddUint32PropertyL( sizeDef, 0 );
+		object->AddTextPropertyL( itemTypeDef, MdeConstants::Image::KImageObject );
+		
+		objectId = iMdEClient->AddObjectL(*object);
+		iIds.Append(objectId);
+		
+		CleanupStack::PopAndDestroy(object);
+		object = NULL;
+		
+		// open object for modification
+		TRAPD( openError, object = iMdEClient->OpenObjectL(objectId) );
+			
+		if ( !object || openError != KErrNone )
+			{
+			_LIT( KOpenErr, "        ModifyObjects - Open error : %d" );
+		    msg.Format(KOpenErr, openError);
+		    iLog->Log( msg );
+		    RDebug::Print(msg);
+		    
+		    User::LeaveIfError(openError);
+			}
+
+		CleanupStack::PushL( object );		
+		
+		// add properties
+   		CMdEProperty* property = NULL;
+   		
+   		// Description
+   		_LIT( KDesc, "Description" );
+		object->Property( descriptionPropertyDef, property );
+		
+		if ( property )
+			{					
+			property->SetTextValueL( KDesc );
+			}
+		else
+			{
+			object->AddTextPropertyL( descriptionPropertyDef, KDesc );
+			}
+		
+		property = NULL;
+		
+		// Width
+		object->Property( widthDef, property );
+		
+		if ( property )
+			{
+			property->SetUint16ValueL( 100 );
+			}
+		else
+			{
+			object->AddUint16PropertyL( widthDef, 100 );
+			}
+		
+		property = NULL;
+			
+		// Height
+		object->Property( heightDef, property );
+		
+		if ( property )
+			{
+			property->SetUint16ValueL( 100 );
+			}
+		else
+			{
+			object->AddUint16PropertyL( heightDef, 100 );
+			}
+		
+		property = NULL;
+		
+		// Maker
+		object->Property( makeDef, property );
+		
+        _LIT( KOnkia, "Maker" );
+		if ( property )
+			{
+			property->SetTextValueL( KOnkia );
+			}
+		else
+			{
+			object->AddTextPropertyL( makeDef, KOnkia );
+			}
+			
+		property = NULL;
+			
+		// Model
+		object->Property( modelDef, property );
+        _LIT( KModel, "Model" );
+		if ( property )
+			{					
+			property->SetTextValueL( KModel );
+			}
+		else
+			{
+			object->AddTextPropertyL( modelDef, KModel );
+			}
+		
+		// Commit object
+		TRAPD( commitError, iMdEClient->CommitObjectL(*object) );
+		if ( commitError != KErrNone )
+			{		
+			_LIT( KCommErr, "        CreateObjects - Commit error : %d" );
+		    msg.Format(KCommErr, commitError);
+		    iLog->Log( msg );
+		    RDebug::Print(msg);
+		    
+		    User::LeaveIfError(commitError);
+			}
+		
+		CleanupStack::PopAndDestroy(object);
+		object = NULL;
+		}
+	
+    _LIT( KMsg, "Exit    EndCreateObjects" );
+    iLog->Log( KMsg );  
+    RDebug::Print( KMsg );
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::DeleteObjects
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::DeleteObjectsL( CStifItemParser& /* aItem */ )
+    {
+    ActiveWait( 2000000 );
+    
+    _LIT( KMsg1, "Enter EndDeleteObjects" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+	TInt count(0);
+    count = iIds.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		TInt id = iIds[i];
+	    iMdEClient->RemoveObjectL( id );
+		}
+	
+	iIds.Reset();
+    
+    _LIT( KMsg2, "Exit EndDeleteObjects" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::CreateContextEngine1L
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::CreateContextEngine1L( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter CreateContextEngine" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    iInitTarget = 1;
+    
+    iContextEngine = NULL;
+    iContextEngine = CContextEngine::GetInstanceL( this );
+    
+    if( !iContextEngine )
+        {
+        User::Leave( KErrUnknown );
+        }
+    
+    _LIT( KMsg2, "Exit CreateContextEngine" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::CreateContextEngine2L
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::CreateContextEngine2L( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter CreateContextEngine" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    iContextEngine = NULL;
+    iContextEngine = CContextEngine::GetInstanceL();
+    
+    // 4 seconds
+    TTimeIntervalMicroSeconds32 timeout(4000000);
+    RTimer timer;
+    TRequestStatus status;
+
+    timer.CreateLocal();
+    timer.After( status,timeout );
+
+    User::WaitForAnyRequest();
+    
+    timer.Close();
+    
+    if( !iContextEngine )
+        {
+        User::Leave( KErrUnknown );
+        }
+    
+    _LIT( KMsg2, "Exit CreateContextEngine" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::CreateContextEngine2L
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::ReleaseInstanceL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter ReleaseInstanceL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    if( !iContextEngine )
+        {
+        User::Leave( KErrUnknown );
+        }
+    
+    iContextEngine->ReleaseInstance();
+    
+    iContextEngine = NULL;
+    
+    _LIT( KMsg2, "Exit ReleaseInstanceL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::CreateContextEngine2L
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::SetMdeSessionL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter SetMdeSessionL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    iInitTarget = 1;
+    
+    iContextEngine = NULL;
+    iContextEngine = CContextEngine::GetInstanceL( this );
+    
+    if( !iContextEngine )
+        {
+        User::Leave( KErrUnknown );
+        }
+    
+    iContextEngine->SetMdeSession( iMdEClient );
+    
+    if( !iContextEngine || !iMdEClient )
+        {
+        User::Leave( KErrUnknown );
+        }
+    
+    iContextEngine->SetMdeSession( NULL );
+    
+    if( !iContextEngine )
+        {
+        User::Leave( KErrUnknown );
+        }
+    
+    _LIT( KMsg2, "Exit SetMdeSessionL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::ContextSnapshots
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::ContextSnapshotsL( CStifItemParser& aItem )
+    {
+    _LIT( KMsg1, "Enter ContextSnapshots" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    iSnapshotTarget = 9;
+    
+    const TInt KLoopCount = 3;
+    TInt count = iIds.Count();
+    
+    CMdEObject* mdeObject;
+    iObjectArray.Reset();
+    
+    // choose if plugin tested, otherwise engine
+    TPtrC testPlugin;
+    TBool plugin = EFalse;
+    User::LeaveIfError( aItem.GetNextString( testPlugin ));
+    _LIT( pluginString, "plugin" );
+    if( testPlugin == pluginString )
+    	{
+    	plugin = ETrue;
+    	}
+    
+    // get object
+    mdeObject = iMdEClient->GetObjectL( iIds[0] );
+
+    HBufC* uriBuf = mdeObject->Uri().AllocLC();
+    iHD = CHarvesterData::NewL( uriBuf );
+    iHD->SetMdeObject( mdeObject );
+    CleanupStack::Pop( uriBuf );
+    
+    // snapshots
+    for ( TInt i = 0; i < KLoopCount; i++ )
+        {
+        if (plugin)
+        	{
+        	iPlugin->ContextSnapshot( *this, *iHD );
+        	}
+        else
+        	{
+        	iContextEngine->ContextSnapshot( *this, *iHD );
+        	}
+        }
+    mdeObject = NULL;
+    
+    mdeObject = iMdEClient->GetObjectL( iIds[1] );
+    uriBuf = mdeObject->Uri().AllocLC();
+    iHD = CHarvesterData::NewL( uriBuf );
+    iHD->SetMdeObject( mdeObject );
+    CleanupStack::Pop( uriBuf );
+    
+    // snapshots
+    for ( TInt i = 0; i < KLoopCount; i++ )
+        {
+        if (plugin)
+        	{
+        	iPlugin->ContextSnapshot( *this, *iHD );
+        	}
+        else
+        	{
+        	iContextEngine->ContextSnapshot( *this, *iHD );
+        	}
+        }    
+    mdeObject = NULL;
+    
+    mdeObject = iMdEClient->GetObjectL( iIds[2] );
+    uriBuf = mdeObject->Uri().AllocLC();
+    iHD = CHarvesterData::NewL( uriBuf );
+    iHD->SetMdeObject( mdeObject );
+    CleanupStack::Pop( uriBuf );
+    
+    // snapshots
+    for ( TInt i = 0; i < KLoopCount; i++ )
+        {
+        if (plugin)
+        	{
+        	iPlugin->ContextSnapshot( *this, *iHD );
+        	}
+        else
+        	{
+        	iContextEngine->ContextSnapshot( *this, *iHD );
+        	}
+        }  
+    
+    _LIT( KMsg2, "Exit ContextSnapshots" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::MultipleSnapshots
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::MultipleSnapshotsL( CStifItemParser& aItem )
+    {
+    _LIT( KMsg1, "Enter MultipleSnapshots" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    iSnapshotTarget = 3;
+    
+    TInt count = iIds.Count();
+    
+    CMdEObject* mdeObject;
+    iObjectArray.Reset();
+    
+    // choose if plugin tested, otherwise engine
+    TPtrC testPlugin;
+    TBool plugin = EFalse;
+    User::LeaveIfError( aItem.GetNextString( testPlugin ));
+    _LIT( pluginString, "plugin" );
+    if( testPlugin == pluginString )
+    	{
+    	plugin = ETrue;
+    	}
+    
+    // multiple objects
+	for ( TInt i = 0; i < count; ++i )
+		{
+	    iHD = NULL;
+	    mdeObject = NULL;
+		
+	    mdeObject = iMdEClient->GetObjectL( iIds[i] );
+	    HBufC* uriBuf = mdeObject->Uri().AllocLC();
+	    iHD = CHarvesterData::NewL( uriBuf );
+	    iHD->SetMdeObject( mdeObject );
+	    CleanupStack::Pop( uriBuf );
+	    
+	    iObjectArray.Append( iHD );
+		}
+	
+	// snapshots
+    if( plugin )
+		{
+		iPlugin->ContextSnapshot( *this, iObjectArray );
+		}
+	else
+		{
+		iContextEngine->ContextSnapshot( *this, iObjectArray );
+		}
+    
+    _LIT( KMsg2, "Exit MultipleSnapshots" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::PluginCount
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::PluginCount( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter PluginCount" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    TInt count(0);
+    count = iContextEngine->PluginCount();
+    
+    if( count != 2 )
+        {
+        return KErrNotFound;
+        }
+    
+    _LIT( KMsg, "Exit PluginCount : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, count);
+    iLog->Log( msg );
+    RDebug::Print(msg);
+	
+    _LIT( KMsg2, "Enter PluginCount" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::Destroy
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::Destroy( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter Destroy" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    iContextEngine->Destroy();
+	
+    _LIT( KMsg2, "Exit Destroy" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::ContextEngineStaticData
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::ContextEngineStaticData( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter ContextEngineStaticData" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    const TInt KContextEngineTLSKey = 0x200009f6;
+    
+    CContextEngineStaticData* data = static_cast<CContextEngineStaticData*>(
+            UserSvr::DllTls(KContextEngineTLSKey) );
+    
+    if( !data )
+        {
+        return KErrUnknown;
+        }
+    
+    _LIT( KMsg2, "Exit ContextEngineStaticData" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CContextEnginePluginTest::LoadPluginL
+// -----------------------------------------------------------------------------
+//
+TInt CContextEnginePluginTest::LoadPluginL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter LoadPlugins" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    iInitTarget = 2;
+    
+    TUid calendarContextUID = { 0x102823CB }; // calendar context plugin uid
+    TUid locationContextUID = { 0x200071D0 }; // location context plugin uid
+    
+    RImplInfoPtrArray infoArray;
+    	
+	TCleanupItem cleanupItem( MdsUtils::CleanupEComArray, &infoArray );
+	CleanupStack::PushL( cleanupItem );
+	
+	CContextPlugin::ListImplementationsL( infoArray );
+	TInt count( 0 );
+	count = infoArray.Count();
+	
+	TBool locationPluginFound( EFalse );
+	TBool calendarPluginFound( EFalse );
+	for ( TInt i=0; i < count; i++ )
+		{
+		TUid uid = infoArray[i]->ImplementationUid();
+		
+		// context plugin found
+		if( uid == locationContextUID )
+			{
+			iLocationPlugin = CContextPlugin::NewL( uid );
+			iLocationPlugin->SetMdeSession(*iMdEClient);
+			iLocationPlugin->Init(*this);
+			locationPluginFound = ETrue;
+			iPlugin = iLocationPlugin;
+			iPluginSet = ETrue;
+			}		
+		else if( uid == calendarContextUID )
+	        {
+	        iCalendarPlugin = CContextPlugin::NewL( uid );
+	        iCalendarPlugin->SetMdeSession(*iMdEClient);
+	        iCalendarPlugin->Init(*this);
+	        calendarPluginFound = ETrue;
+	        }   
+		}
+	
+	CleanupStack::PopAndDestroy( &infoArray ); // infoArray, results in a call to CleanupEComArray
+    
+	if( !locationPluginFound )
+	    {
+	    _LIT( KLocation, "Location context plugin not found" );
+	    iLog->Log( KLocation );
+	    RDebug::Print( KLocation );
+	    return KErrNotFound;
+	    }
+	
+    if( !calendarPluginFound )
+        {
+        _LIT( KCalendar, "Calendar context plugin not found" );
+        iLog->Log( KCalendar );
+        RDebug::Print( KCalendar );
+        return KErrNotFound;
+        }
+    
+    _LIT( KMsg2, "Exit LoadPlugins" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+//  [End of File] - Do not remove
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+#include "../context_engine_plugin_api/group/bld.inf"
+#include "../harvester_framework_api/group/bld.inf"
+#include "../location_manager_api/group/bld.inf"
+#include "../metadata_engine_api/group/bld.inf"
+#ifdef RD_MDS_2_5
+#include "../content_listing_framework_collection_manager_api/group/bld.inf"
+#include "../content_listing_framework_extended_api/group/bld.inf"
+#endif
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,40 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+../inc/composerplugin.h    MW_LAYER_PLATFORM_EXPORT_PATH(composerplugin.h)
+../inc/harvesterclient.h     MW_LAYER_PLATFORM_EXPORT_PATH(harvesterclient.h)
+../inc/harvesterclientdata.h     MW_LAYER_PLATFORM_EXPORT_PATH(harvesterclientdata.h)
+../inc/placeholderdata.h     MW_LAYER_PLATFORM_EXPORT_PATH(placeholderdata.h)
+../inc/harvesterdata.h     MW_LAYER_PLATFORM_EXPORT_PATH(harvesterdata.h)
+../inc/harvesterplugin.h     MW_LAYER_PLATFORM_EXPORT_PATH(harvesterplugin.h)
+../inc/monitorplugin.h     MW_LAYER_PLATFORM_EXPORT_PATH(monitorplugin.h)
+../inc/harvestereventenum.h     MW_LAYER_PLATFORM_EXPORT_PATH(harvestereventenum.h)
+../inc/harvesterpauseps.h	MW_LAYER_PLATFORM_EXPORT_PATH(harvesterpauseps.h)
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/harvester_framework_api.metaxml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,17 @@
+<?xml version="1.0" ?>
+<api id="172c24dcf2b83d8b9c0cb5cec106cd7d" dataversion="2.0">
+<name>harvester_framework_api</name>
+<description>harvester framework api</description>
+<type>c++</type>
+<collection>harvester</collection>
+<libs><lib name="harvesterclient.lib"/>
+<lib name="harvesterdata.lib"/>
+<lib name="harvesterplugininterface.lib"/>
+<lib name="monitorplugininterface.lib"/>
+</libs>
+<release category="platform" sinceversion=""/>
+<attributes>
+<htmldocprovided>no</htmldocprovided>
+<adaptation>no</adaptation>
+</attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/inc/composerplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,151 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Composer Plug-in ECom interface
+*
+*/
+
+#ifndef __CCOMPOSERPLUGIN_H__
+#define __CCOMPOSERPLUGIN_H__
+
+#include <e32base.h>
+#include <ecom.h>
+#include <badesca.h>
+
+#include <mdesession.h>
+
+/** @var Uid for this interface */
+const TUid KCComposerPluginInterfaceUid = { 0x2000717E };
+
+ /**
+ * Composer Plug-in ECom interface definition. Composer plug-in implementation
+ * needs to inherit this class and implement the pure virtual methods which exist 
+ * in this interface.
+ *
+ * Example:
+ *
+ * class CMyVideoComposerPlugin: public CComposerPlugin
+ *     {
+ *     protected:
+ *         void SetObservers();    
+ *         void RemoveObservers();
+ * 
+ *         // Because CComposerPlugin inherits MMdEObjectObserver
+ *         void HandleObjectNotification(CMdESession& aSession, 
+ *				TObserverNotificationType aType,
+ *				const RArray<TItemId>& aObjectIdArray);
+ *     
+ *     private:
+ *         // Active object which does the actual binary writing
+ *         // so that this interface and its observers remain responsive
+ *         CMyVideoComposerAO* iVideoComposerAO;       
+ *     }
+ *
+ * void SetObservers()
+ *     {
+ *	   // We want to listen to changes in Video metadata objects
+ *     // and setup an observer for this  
+ *     CMdENamespaceDef& defaultNamespace = iSession->GetDefaultNamespaceDefL();
+ *     CMdEObjectDef& videoDef = 
+ *        defaultNamespace.GetObjectDefL( MdeConstants::Video::KVideoObject );
+ *     CMdELogicCondition* condition = CMdELogicCondition::NewL( ELogicConditionOperatorAnd );
+ *     condition->AddObjectConditionL( videoDef );
+ *       
+ *     // iSession is reference to CMdESession which is always set in CComposerPlugin::SetSession()
+ *     iSession->AddObjectObserverL( *this, condition, ENotifyModify, &defaultNamespace );
+ *     }
+ * 
+ * void RemoveObservers()
+ *     {
+ *     iSession->RemoveObjectObserverL( *this )
+ *     }
+ *
+ * void CComposerImagePlugin::HandleObjectNotification(CMdESession& aSession, 
+ *		TObserverNotificationType aType, const RArray<TItemId>& aObjectIdArray)
+ *     {
+ *     // We give ID-array of changed Video objects to our active object
+ *     // which adds then to a its internal queue and processes them one-by-one 
+ *     // with different RunL-calls so that we don't stuck the thread by composing
+ *     // for example 1000 binary files in a row.
+ *     iVideoComposerAO->AddToQueue( aObjectIdArray );
+ *     }
+ */
+class CComposerPlugin : public CBase, public MMdEObjectObserver
+    {
+    public:
+
+        /**
+         * Construction.
+         *
+         * @param aUid  Implementation UID which plug-in to invoke.
+         */
+        IMPORT_C static CComposerPlugin* NewL( const TUid& aUid );
+
+        /**
+         * Lists all available implementations which satisfy this given interface.
+         * 
+         * @param aImplInfoArray  Reference to a list which will be populated with 
+         *                        plug-in implementation details. 
+         */
+        IMPORT_C static void ListImplementationsL(RImplInfoPtrArray& aImplInfoArray);
+
+        /**
+         * Destructor.
+         */ 
+        IMPORT_C virtual ~CComposerPlugin();
+
+        /**
+         * Sets Mde session to be used.
+         * 
+         * @param aSession  Open MdE session to utilize in the Composer plug-in
+         */
+        IMPORT_C void SetSession( CMdESession& aSession );
+
+        /**
+         * Unsets Mde session.
+         */
+        IMPORT_C void RemoveSession();
+
+        /**
+         * Checks if composing is completed.
+         *
+         * @return  Whether composing is on-going
+         */
+        virtual TBool IsComposingComplete() = 0;
+
+    protected:
+    
+        /**
+         * Sets observers to be notified. Called by the interface itself when
+         * SetSession method is called from Harvester server side.
+         */
+        virtual void SetObservers() = 0;
+
+        /**
+         * Unsets observers. Called by the interface itself when
+         * RemoveSession method is called from Harvester server side.
+         */
+        virtual void RemoveObservers() = 0;
+
+    protected:
+
+        /* Pointer to Mde session used by the plugin */
+    CMdESession* iSession;
+
+    private:
+
+        /* Identification on cleanup */
+        TUid iDtor_ID_Key;
+    };
+
+#endif // __CCOMPOSERPLUGIN_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/inc/harvesterclient.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,351 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Harvester client header
+*
+*/
+
+
+#ifndef __HARVESTER_CLIENT_H__
+#define __HARVESTER_CLIENT_H__
+
+#include <e32base.h>
+
+#include <mdccommon.h>
+#include <mdeconstants.h>
+#include <harvestereventenum.h>
+
+// forward declarations
+class CHarvesterClientAO;
+class CHarvesterSessionAsyncHandler;
+class CHarvesterEventObserverAO;
+class MHarvesterEventObserver;
+class CHarvesterRequestActive;
+class CHarvesterRequestQueue;
+
+// default event interval for MHarvesterEventObserver
+const TInt KHarvesterEventInterval = 20;
+
+/**
+ * Observer interface to inform when fast harvesting is completed
+ * with the HarvestingComplete callback.
+ *
+ * Example of MHarvestObserver and RHarvesterClient::HarvestFile usage:
+ *
+ * Client application (like Camera) which wants to observe the completion of 
+ * harvesting requests (issued with RHarvesterClient::Harvestile method) needs
+ * implement the interface MHarvestObserver::HarvestingComplete. Callback 
+ * HarvestingComplete provides the name of the harvested file (aURI) and also possible 
+ * error code (aError).
+ *
+ * class CHarvestingObserver : public MHarvestObserver
+ *     {
+ *     void HarvestingComplete( TDesC& aURI, TInt aError ); // from MHarvestObserver
+ *     void IssueHarvestingRequests();
+ * 
+ *     RHarvesterClient iHClient;	
+ *     }
+ *
+ * void CHarvestObserver::ConstructL()
+ *     {
+ *     // connecting to Harvester server
+ *	   iHClient.Connect();
+ *     }
+ * 
+ * void CHarvestObserver::IssueHarvestingRequests()
+ *     {
+ *     // new harvesting request data
+ * 	   _LIT( KNewFile, "C:\\Data\\ThisIsANewFile1.jpg" );
+ *     RArray<TItemId> defaultPhotoAlbums;
+ *	   defaultPhotoAlbums.Append( 123 );
+ *     defaultPhotoAlbums.Append( 456 );
+ *     defaultPhotoAlbums.Append( 789 );
+ *
+ *     // setting this class as the observer for the fast harvesting calls
+ *      iHClient.SetObserver(this);
+ *        
+ *     // issué new harvesting request and requesting location data to be harvested
+ *     iHClient.HarvestFile( KNewFile, defaultPhotoAlbums, ETrue );   
+ *     }
+ *
+ * void CHarvestObserver::HarvestingComplete( TDesC& aURI, TInt aError )
+ *     {
+ *     _LIT( KExpectedFile, "C:\\Data\\ThisIsANewFile1.jpg" );
+ *
+ *     // Checking if an error occurred and if this was the expected file
+ *     if ((aError == KErrNone) && (aURI.CompareC(KExpectedFile) == 0))
+ *         {
+ *         // do something
+ *         }
+ *     }
+ *
+ */
+class MHarvestObserver
+	{
+public:
+    /**
+     * Callback to inform when fast harvesting of a file is complete.
+     * 
+     * @param aURI    URI of the harvested file.
+     * @param aError  Error code of the fast harvesting. <code>KErrNone</code> is
+     *                expected if fast harvesting succeeded. Otherwise some
+     *                system wide error code. 
+     *
+     */
+	virtual void HarvestingComplete( TDesC& aURI, TInt aError ) = 0;
+	};
+
+/**
+ * Observer interface to inform about events that happen inside the observer framework
+ *
+ * Example of MHarvesterEventObserver, RHarvesterClient::AddHarvesterEventObserver and
+ * RHarvesterClient::RemoveHarvesterEventObserver usage:
+ *
+ * void CHarvestObserver::ConstructL()
+ *     {
+ *     // iHClient is instance of RHarvesterClient
+ *	   iHClient.Connect();
+ *
+ *     // Listen to placeholder changes to "full" metadata objects - request notification
+ *     // after 100 items have changed.
+ *     TInt err = iHClient.AddHarvesterEventObserver( *this, EHEObserverTypePlaceholder, 100 );
+ *     if (err == KErrNone)
+ *         {
+ *         // do something now that event observer is setup
+ *         }
+ *     }
+ *
+ * void CHarvestObserver::HarvestingUpdated( HarvesterEventObserverType aHEObserverType, 
+ *			HarvesterEventState aHarvesterEventState, TInt aItemsLeft )
+ *     {
+ *     // Check the observer notification type
+ *     if (aHEObserverType == EHEObserverTypePlaceholder)
+ *         {
+ *         // Checking if there are more than 1000 items left to process 
+ *         if (aItemsLeft > 1000)
+ *             {
+ *             // do something since there are some many items still placeholders
+ *             }
+ *         if (aItemsLeft == 0)
+ *             {
+	           // all placeholders changed to "full" objects - do something...
+ *             }
+ *         }   
+ *     }
+ *
+ * CHarvestObserver::~CHarvestObserver()
+ *     {
+ *     // Removing the observer in destructor
+ *     iHClient.RemoveHarvesterEventObserver( *this );   
+ *     }
+ */
+
+
+class MHarvesterEventObserver
+	{
+public:
+    /**
+     * Callback interface which informs about harvesting changes based on the observers
+     * that the end user has setup/registered.
+     * 
+     * @param aHEObserverType       Defines the observer type to which this events is related 
+     * @param aHarvesterEventState  Event that occurred
+     * @param aItemsLeft            Number of items left regarding the harvesting procedure (defined
+     *                              by aHEObserverType)
+     * @see RHarvesterClient::AddHarvesterEventObserver
+     * @see RHarvesterClient::RemoveHarvesterEventObserver
+     */
+	virtual void HarvestingUpdated( 
+			HarvesterEventObserverType aHEObserverType, 
+			HarvesterEventState aHarvesterEventState,
+			TInt aItemsLeft ) = 0;
+	};
+
+/**
+ * Harvester client session class which provides also means to:
+ * - Pause/resume the Harvesting framework
+ * - Fast harvest files and observe when they have been harvested
+ * - Setup observers to observe the harvesting progress
+ */
+NONSHARABLE_CLASS( RHarvesterClient ) : public RSessionBase
+	{
+	friend class CHarvesterSessionAsyncHandler;
+	friend class CHarvesterEventObserverAO;
+
+	public:
+		
+        /**
+         * Constructor
+         */
+        IMPORT_C RHarvesterClient();
+
+        /**
+         * Public method to connect Harvester server.
+         * 
+         * @return Symbian OS error code.
+         */
+        IMPORT_C TInt Connect();
+         
+        /**
+         * Public method to pause the operation
+         * of the Harvester framework.
+         *
+         * @return  Symbian OS error code.
+         */
+        IMPORT_C TInt Pause();
+
+        /**
+         * Public method to resume the operation
+         * of the Harvester framework.
+         *
+         * @return  Symbian OS error code.
+         */    
+        IMPORT_C TInt Resume();
+
+        /**
+         * Public method to close session to Harvester server.
+         */
+        IMPORT_C void Close();
+            
+        /**
+         * Public method to set observer for fast harvesting.
+         * Only one observer is currently supported.
+         *
+         * @param aObserver  Pointer to the observer
+         */     
+        IMPORT_C void SetObserver( MHarvestObserver* aObserver);
+
+        /**
+         * Public method to remove observer for fast harvesting.
+         *
+         * @param aObserver  Pointer to the observer
+         */     
+        IMPORT_C void RemoveObserver( MHarvestObserver* aObserver);
+        
+        /**
+         * Public method for doing fast harvesting. These files
+         * are handled first before the ones that are in the harvesting 
+         * queue inside the Harvesting framework.
+         *
+         * @param aURI          Uri of the file to be harvested
+         * @param aAlbumIds     Array of album id's that the harvested file 
+         *                      will be included in
+         * @param aAddLocation  Should location information be added to item
+         */ 
+    	IMPORT_C void HarvestFile( const TDesC& aURI, RArray<TItemId> &aAlbumIds, TBool aAddLocation );
+        
+        /**
+         * Method for adding observer for harvester framework events
+         *
+         * @param aHarvesterEventObserver  class to implement MHarvesterEventObserver interface
+         * @param aHEObserverType          Harvester event observer type (EPlaceholderState, 
+         *                                 EMMCState, EOverallState)
+         * @param aEventInterval           Interval of harvester events as item amount
+         * 
+         * @return  Symbian OS wide error code.
+         */
+        IMPORT_C TInt AddHarvesterEventObserver( 
+        		MHarvesterEventObserver& aHarvesterEventObserver, 
+        		TInt aHEObserverType,
+        		TInt aEventInterval = KHarvesterEventInterval );
+        
+        /**
+         * Method for removing observer for harvester framework events. Please note that
+         * removing any of the event observers will remove all observers which are registered
+         * by the given parameter aHarvesterEventObserver (= observer class).
+         *
+         * @param aHarvesterEventObserver class to implement MHarvesterEventObserver interface
+         *
+         * @return  Symbian OS wide error code.
+         */
+        IMPORT_C TInt RemoveHarvesterEventObserver( MHarvesterEventObserver& aHarvesterEventObserver );
+        
+		/**
+         * Public method for doing fast harvesting. These files
+         * are handled first before the ones that are in the harvesting 
+         * queue. 
+         *
+         * @param aURI          Uri of the file to be harvested
+         * @param aAlbumIds     Array of album id's that the harvested file will be included in
+         * @param aAddLocation  Should location information be added to image
+		 * @param aUid          Uid of the originating application for the object
+         */ 
+    	IMPORT_C void HarvestFileWithUID( const TDesC& aURI, 
+		                                  RArray<TItemId> &aAlbumIds, 
+										  TBool aAddLocation,
+										  TUid aUid );
+		
+        /**
+         * Requests a harvest complete event from harvester server.
+		 * On return, aURI is the URI of the harvested file.
+         *
+         * @param aURI  Harvested image uri what server
+         * @param aStatus    Reference to a request indicator
+         */ 
+        void RegisterHarvestComplete( TDes& aURI, TRequestStatus& aStatus );
+        
+        /**
+         * Cancels the harvest complete notification request.
+         */ 
+        void UnregisterHarvestComplete( );
+        
+        /**
+         * Private method for doing fast harvesting. These files
+         * are handled first before the ones that are in the harvesting 
+         * queue.
+         * 
+         * @param aService  Service request which to execute on server side
+         * @param aArgs     Parameters for harvesting
+         * @param aStatus   Status of the asunchronous call
+         */ 
+        void HarvestFile( TInt& aService, TIpcArgs& aArgs, TRequestStatus& aStatus  );
+
+        /**
+         * Restricted method for doing fast harvesting. These files
+         * are handled first before the ones that are in the harvesting 
+         * queue. This version forces the file to be harvested immidiately.
+         * 
+         * @param aService  Service request which to execute on server side
+         * @param aArgs     Parameters for harvesting
+         */ 
+        void ForceHarvestFile( TInt& aService, TIpcArgs& aArgs );
+        
+	private: 
+
+	    /**
+	     * Observer of the class
+	     */ 
+	     MHarvestObserver* iObserver;
+	
+        /**
+         * Private method for version.
+         */      
+        TVersion Version() const;
+
+        /**
+         * Harvester client active object.
+         */    
+        CHarvesterClientAO* iHarvesterClientAO;
+        
+        /** 
+         * Pointer to Harvester event observer active object.
+         */
+        CHarvesterEventObserverAO* iHEO;
+        
+        /**
+         * Request queue processor.
+         */
+        CHarvesterRequestQueue* iRequestQueue;
+    	};
+
+#endif // __HARVESTER_CLIENT_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/inc/harvesterclientdata.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,76 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Data transfer object for harvest client data
+ *
+*/
+
+
+#ifndef HARVESTERCLIENTDATA_H
+#define HARVESTERCLIENTDATA_H
+
+// INCLUDES
+#include <e32base.h>
+#include <e32cmn.h>
+
+#include <mdccommon.h>
+
+// FORWARD DECLARATIONS
+
+// ENUMERATIONS
+
+
+/**
+ * CHarvestClientData
+ */
+NONSHARABLE_CLASS( CHarvestClientData ) : public CBase
+	{
+    public:
+        /**
+         * New.
+         * @return Pointer to newly created object.
+         */
+        IMPORT_C static CHarvestClientData* New();
+        
+        /**
+         * NewL.
+         * Leaving version of New().
+         *
+         * @return Pointer to newly created object.
+         */
+        IMPORT_C static CHarvestClientData* NewL();
+
+        /**
+         * Destructor.
+         */
+        ~CHarvestClientData();
+
+        /**
+         * Set album ids.
+         *
+         * @param aAlbumIds Array of album ids to set.
+         */
+        IMPORT_C void SetAlbumIds( const RArray<TItemId>& aAlbumIds );
+
+    private:
+        /**
+         * Constructor.
+         */
+        CHarvestClientData();
+        
+    public: // data
+        RArray<TItemId> iAlbumIds;
+    };
+
+#endif // HARVESTERCLIENTDATA_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/inc/harvesterdata.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,382 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Data transfer object for harvest data
+ *
+*/
+
+
+#ifndef HARVESTERDATA_H
+#define HARVESTERDATA_H
+
+// INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <badesca.h>
+#include <mdccommon.h>
+#include <locationdatatype.h>
+
+#include <harvesterclientdata.h>
+#include <placeholderdata.h>
+
+#include "mdeconstants.h"
+
+// FORWARD DECLARATIONS
+class CContextEngine;
+class CHarvesterBlacklist;
+class CMdEObject;
+class CHarvesterPluginInfo;
+class CHarvesterData;
+
+// ENUMERATIONS
+enum THarvesterEventType
+	{
+	EHarvesterAdd,      // New item to harvest
+	EHarvesterEdit,     // Re-harvest existing item
+	EHarvesterDelete,   // Delete item
+	EHarvesterUnknown   // Unknown command
+	};
+
+enum THarvesterObjectType
+	{
+	ENormal,           // Normal harvesting
+	EPlaceholder,      // Placeholder harvesting
+	EFastHarvest       // Fast harvesting - Harvester client request
+	};
+
+/**
+ * Observer interface for notifications of harvesting completion from Harvesting
+ * plug-ins to Harvester server side
+ */
+class MHarvesterPluginObserver
+	{
+    public:
+    	/**
+	    * Called when harvesting of a file/item is completed
+	    *
+	    * @param aHarvesterData  Pointer to harvesting related data/harvesting request data
+	    */
+    	virtual void HarvestingCompleted( CHarvesterData* aHarvesterData ) = 0;
+	};
+
+/**
+ * Observer interface for adding new harvesting requests to Harvester server queue from
+ * Monitor plug-ins
+ */
+class MMonitorPluginObserver
+	{
+    public:
+    	/**
+    	 * Method which is called by the monitor plug-in when event is monitored/
+    	 * new harvesting request inserted to Harvester server queue.
+    	 *
+    	 * @param aHarvesterData  harvester data type
+    	 */
+    	virtual void MonitorEvent( CHarvesterData* aHarvesterData ) = 0;
+    	
+    	/**
+    	 * Method which is called by the monitor plug-in when event is monitored/
+    	 * new harvesting request inserted to Harvester server queue.
+    	 * 
+    	 * @param aHarvesterDataArray  Pointer to an array of harvesting related 
+    	 *                             data/harvesting request data
+    	 */
+    	virtual void MonitorEvent( RPointerArray<CHarvesterData>& aHarvesterDataArray ) = 0;
+	};
+
+/**
+ *  Class that encapsulates harvesting related data/harvesting request data. These instances
+ *  are moved around the MdS Harvesting framework and this class encapsulates all information
+ *  needed when harvesting a file/item.
+ * 
+ */
+NONSHARABLE_CLASS( CHarvesterData ) : public CBase
+	{
+    public:
+    
+    	/**
+    	 * Destructor.
+    	 */
+    	~CHarvesterData();
+    
+    	/**
+    	 * Two-phased constructor.
+    	 * 
+    	 * @param aUri  URI of the file, usually filename. With messages can be messageID.
+    	 */
+    	IMPORT_C static CHarvesterData* NewL(const HBufC* aUri);
+    	
+    	/**
+    	 * Two-phased constructor.
+    	 *
+    	 * @param aUri  URI of the file, usually filename. With messages can be messageID.
+    	 */
+    	IMPORT_C static CHarvesterData* NewLC(const HBufC* aUri);
+    
+    	/**
+    	 * Method returns the URI.
+    	 *
+    	 * @return  URI.
+    	 */
+    	IMPORT_C const TDesC& Uri();
+  
+    	/**
+    	 * Method returns error code of harvesting.
+    	 *
+    	 * @return  harvesting error code.
+    	 */    	  
+    	IMPORT_C TInt ErrorCode();
+
+    	/**
+    	 * Method sets the error code for harvesting.
+    	 * 
+    	 * @param aErrorCode  Error code for harvesting 
+    	 */    	    	
+    	IMPORT_C void SetErrorCode(TInt aErrorCode);
+
+    	/**
+    	 * Method sets harvesting type.
+    	 * 
+    	 * @param aEventType  Harvesting type
+    	 */    	    
+    	IMPORT_C void SetEventType(THarvesterEventType aEventType);
+
+    	/**
+    	 * Method returns harvesting type.
+    	 * 
+    	 * @return  Harvesting type
+    	 */ 
+      	IMPORT_C THarvesterEventType EventType();
+
+    	/**
+    	 * Method sets observer for this harvesting request (Harvester server)
+    	 * 
+    	 * @param aObserver  Pointer to the harvesting observer in the harvesting FW
+    	 */     	
+    	IMPORT_C void SetPluginObserver(MHarvesterPluginObserver& aObserver);
+
+    	/**
+    	 * Method returns pointer to the harvesting observer (Harvester server).
+    	 * 
+    	 * @return  Pointer to harvesting observer
+    	 */     
+    	IMPORT_C MHarvesterPluginObserver* PluginObserver();
+    	
+    	/**
+    	 * Method sets the origin information for the file/item.
+    	 * 
+    	 * @param aOrigin  Origin of the file/item.
+    	 */     	
+    	IMPORT_C void SetOrigin(TOrigin aOrigin);
+
+    	/**
+    	 * Method returns origin of the file/item.
+    	 * 
+    	 * @return  Origin of the file/item.
+    	 */ 
+      	IMPORT_C TOrigin Origin();
+
+    	/**
+    	 * Method sets flag whether Context snapshot (with Context Engine)
+    	 * is required during harvesting.
+    	 * 
+    	 * @param aTakeSnapshot  Whether Context snapshot is required or not.
+    	 */       	    	
+    	IMPORT_C void SetTakeSnapshot(TBool aTakeSnapshot);
+
+    	/**
+    	 * Method returns whether Context snapshot is required or not.
+    	 * 
+    	 * @return  Whether Context snapshot is required or not.
+    	 */     	
+    	IMPORT_C TBool TakeSnapshot();
+  
+    	/**
+    	 * Method sets (object) type of the harvesting procedure.
+    	 * 
+    	 * @param aObjectType  Type of the harvesting procedure. 
+    	 */     	  	
+    	IMPORT_C void SetObjectType(THarvesterObjectType aObjectType);
+    	
+    	/**
+         * Method retursn the (object) type of the harvesting procedure.
+         *
+         * @return  Type of the harvesting procedure.
+    	 */     	
+    	IMPORT_C THarvesterObjectType ObjectType();
+    
+    	/**
+    	 * Method sets the custom harvesting data from client.
+    	 * 
+    	 * @param aClientData  Custom harvesting data from client.
+    	 */     	
+    	IMPORT_C void SetClientData(CBase* aClientData);
+    	
+    	/**
+         * Method returns the custom harvesting data (received from client)
+         *
+         * @return  Custom harvesting data (received from client)
+    	 */     	
+    	IMPORT_C CBase* ClientData();
+    	
+    	/**
+    	 * Method sets metadata object which will be used to store the metadata
+    	 * in the harvesting plug-in.
+    	 * 
+    	 * @param aMdeObject  Pointer to the metadata object that will be used 
+    	 *                    to store the metadata from the file/item.
+    	 */     	
+    	IMPORT_C void SetMdeObject( CMdEObject* aMdeObject );
+
+    	/**
+         * Method returns the metadata objects which is used to store the metadata
+         * from the file/item that is harvested.
+         *
+         * @return  Metadata object that is used to store the metadata.
+    	 */     	    	
+    	IMPORT_C CMdEObject& MdeObject();
+
+    	/**
+    	 * Method sets location metadadata (GPS).
+    	 * 
+    	 * @param aLD  Pointer to the location metadata structure.
+    	 */     	    	
+    	IMPORT_C void SetLocationData( TLocationData* aLD );
+    	
+    	/**
+         * Method returns the location metadata structure.
+         *
+         * @return  Location metadata structure.
+    	 */     	
+    	IMPORT_C TLocationData* LocationData();
+    
+    	/**
+    	 * Method sets the client application UID.
+    	 * 
+    	 * @param aClientId  Client application UID.
+    	 */     	
+        IMPORT_C void SetClientId(TUid aClientId);
+    	
+    	/**
+         * Method returns the client application UID.
+         *
+         * @return  Client application UID.
+    	 */         
+        IMPORT_C TUid ClientId();
+    	
+    	/**
+         * Method returns whether location data should be added to
+         * MdE DB or not.
+         *
+         * @return  Flag which defines whether location data needs to 
+         *          be added or not.
+    	 */ 		
+        IMPORT_C TBool AddLocation();
+		
+    	/**
+    	 * Method sets a flag which defines whether location data
+    	 * should be added to MdE DB or not.
+    	 * 
+    	 * @param aAdd  Client application UID.
+    	 */         
+        IMPORT_C void SetAddLocation( TBool aAdd );
+		
+    	/**
+    	 * Method sets harvesting plug-in information which
+    	 * is needed to carry out the harvesting procedure
+    	 * 
+    	 * @param aPluginInfo  Pointer to harvester plug-in info structure.
+    	 */         
+		IMPORT_C void SetHarvesterPluginInfo( CHarvesterPluginInfo* aPluginInfo );
+		
+    	/**
+         * Method returns harvester plug-in info structure.
+         *
+         * @return  Harvester plug-in info structure.
+    	 */ 		
+		IMPORT_C CHarvesterPluginInfo* HarvesterPluginInfo();
+		
+    	/**
+         * Method returns whether item in harvesting is a binary file.
+         *
+         * @return  Whether item in harvesting is a binary file.
+    	 */ 		
+		IMPORT_C TBool IsBinary();
+
+    	/**
+    	 * Method sets a flag determinning 
+    	 * 
+    	 * @param aPluginInfo  Pointer to harvester plug-in info structure.
+    	 */    		
+		IMPORT_C void SetBinary( TBool aValue );
+
+    
+    private:
+    
+    	/**
+    	 * Constructor for performing 1st stage construction
+    	 * 
+    	 * @param aUri  URI of the item ie. filename.
+    	 */
+    	CHarvesterData(const HBufC* aUri);
+    
+    	/**
+    	 * Default constructor for performing 2nd stage construction
+    	 */
+    	void ConstructL();
+    
+    	/* URI descriptor */
+    	const HBufC* iUri;
+    	
+    	/* Harvesting error code */
+    	TInt iErrorCode;
+    	
+    	/* Harvesting event type */
+    	THarvesterEventType iEventType;
+    	
+    	/* Harvesting observer ie. Harvester server */
+    	MHarvesterPluginObserver* iObserver;
+    	
+    	/* Origin of the file/item */
+    	TOrigin iOrigin;
+    	
+    	/* Whether Context snapshot is needed */
+    	TBool iTakeSnapshot;
+    	
+    	/* Object type for harvesting */
+    	THarvesterObjectType iObjectType;
+    	
+    	/* Custom client data */
+    	CBase* iClientData;
+    	
+    	/* Pointer to metadata object */
+    	CMdEObject* iMdeObject;
+    	
+    	/* Harvesting plug-in info */
+    	CHarvesterPluginInfo* iPluginInfo;
+    	
+    	/* GPS and other location related data */
+    	TLocationData* iLocationData;
+    	
+    	/* Whether location data needs to be added to DB */
+    	TBool iAddLocation;
+    	
+    	/* Whether item to harvest is a binary file */
+    	TBool iIsBinary;
+    	
+    	/* Executable UID which created the binary file */
+		TUid iClientId;
+	};
+
+#endif // HARVESTERDATA_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/inc/harvestereventenum.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#ifndef HARVESTEREVENTENUM_H_
+#define HARVESTEREVENTENUM_H_
+
+enum HarvesterEventObserverType
+	{
+	EHEObserverTypePlaceholder = 1,  // Observing placeholder changes to normal object
+	EHEObserverTypeMMC = 2,          // Observing MMC handling start and stop
+	EHEObserverTypeOverall = 4       // Observing overall status of the harvesting
+	};
+
+enum HarvesterEventState
+	{
+	EHEStateStarted,                 // Harvesting starting
+	EHEStateHarvesting,              // Harvesting on-going
+	EHEStateFinished,                // Harvesting finished
+	EHEStateUninitialized,           // Harvesting not initialized
+	EHEStatePaused,                  // Harvesting paused
+	EHEStateResumed                  // Harvesting resumed
+	};
+
+#endif /*HARVESTEREVENTENUM_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/inc/harvesterpauseps.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  P&S key for harvester server pause
+*
+*/
+
+#ifndef HARVESTERPAUSEPS_H_
+#define HARVESTERPAUSEPS_H_
+
+const TUid KPsHarvesterPauseCategory = { 0x200009F5 };
+
+// observed by harvester server
+const TUint KPsHarvesterPauseKey            = 0x00000001;
+
+enum TPsHarvesterPauseState
+	{
+	EPsHarvesterPauseResume = 0,  // Resume harvesting
+	EPsHarvesterPausePause        // Pause harvesting
+	};
+
+#endif /*HARVESTERPAUSEPS_H_*/
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/inc/harvesterplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,245 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition of the Harvester plug-in ECom interface.*
+*/
+
+#ifndef __CHARVESTERPLUGIN_H__
+#define __CHARVESTERPLUGIN_H__
+
+#include <e32base.h>
+#include <ecom.h>
+
+// forward declarations
+class CMdESession;
+class CHarvesterBlacklist;
+class CHarvesterData;
+class CMdEPropertyDef;
+
+// Uid for this interface
+const TUid KCHarvesterPluginInterfaceUid = { 0x200009F8 };
+
+struct THarvestResult
+    {
+    HBufC16* iUri;   // URI of the file/item
+    TInt iErrorCode; // Harvesting error code
+    };
+
+/**
+ * Harvester Plug-in ECom interface definition. Harvester plug-in implementation
+ * needs to inherit this class and implement the pure virtual method (HarvestL) which exist 
+ * in this interface.
+ *
+ * Example:
+ * 
+ * class CMyHarvesterPlugin:  public CHarvesterPlugin
+ *     {
+ *     public:
+ *
+ *         // This method should also be overwritten in the plug-in
+ *         void GetObjectType( const TDesC& aUri, TDes& aObjectType );
+ *
+ *         void HarvestL( CHarvesterData* aHD );
+ *     }
+ *
+ * void GetObjectType( const TDesC& aUri, TDes& aObjectType )
+ *     {
+ *      // Idea in this method is that it MUST return one of the object types
+ *	    // supported by the MdE DB - for example "Image", "Video" or "Audio".
+ * 	    // If plug-in supports only one type of objects then it can just return
+ * 	    // always that like:  
+ * 	    // TPtrC ptrImage( KImage );
+ * 	    // aObjectType.Copy( KImage ); return;
+ * 	    //
+ * 	    // However if multiple MdE object types are supported then file content
+ * 	    // needs to be checked for example from file MIME-type like here:
+ * 	  
+ *	   	TRAPD( err, content = CContent::NewL( aUri ) );
+ *	    if (err == KErrNone) 
+ *		    {
+ *		    err = content->GetStringAttribute( EMimeType, mime );
+ *		    delete content;
+ *		    }
+ *
+ *	    TPtrC ptrImage( KImage );
+ *	    
+ *	    // MdsUtils::Find tries to find word "image" from the MIME-type
+ *      // so that we know the file is an image
+ *		if( MdsUtils::Find( mime, ptrImage ) != KErrNotFound )
+ *			{
+ *			WRITELOG1( "CHarvesterOMADRMPlugin::GetObjectType - mimetype %S. Object type changed to Image", &mime );
+ *			aObjectType.Copy( KImage );
+ *			return;
+ *			}
+ *		
+ *		TPtrC ptrVideo( KVideo );
+ *		if( MdsUtils::Find( mime, ptrVideo ) != KErrNotFound )
+ *			{
+ *			WRITELOG1( "CHarvesterOMADRMPlugin::GetObjectType - mimetype %S. Object type changed to Video", &mime );
+ *			aObjectType.Copy( KVideo );
+ *			return;
+ *			}
+ *     }
+ *
+ * void HarvestL( CHarvesterData* aHD )
+ *     {
+ *     CMdEObject& mdeObject = aHD->MdeObject();
+ *      
+ *     CMdeObjectWrapper* wrapper = CMdeObjectWrapper::NewL();
+ *     }	 
+ */
+class CHarvesterPlugin : public CActive
+    {
+public:
+	    
+	enum THarvesterState
+	    {
+	    EHarvesterIdle = 0,   // No harvesting requests to process
+	    EHarvesterGathering,  // Harvesting a file
+	    };
+	
+	/** 
+	 * Construction 
+	 */
+	IMPORT_C static CHarvesterPlugin* NewL( const TUid& aUid );
+	
+    /**
+     * Lists all available implementations which satisfy this given interface.
+     * 
+     * @param aImplInfoArray  Reference to a list which will be populated with 
+     *                        plug-in implementation details. 
+     */
+	IMPORT_C static void ListImplementationsL( RImplInfoPtrArray& aImplInfoArray );
+	
+	/**
+	 * Destructor - virtual and class not intended
+	 * for derivation, so not exported.
+	 */
+	IMPORT_C virtual ~CHarvesterPlugin();
+	
+	/**
+	 *  Method sets the Harvesting queue to the plug-in.
+	 * 
+	 * @param aQueue  Queue which contains harvesting requests.
+	 */
+	IMPORT_C virtual void SetQueue( RPointerArray<CHarvesterData>& aQueue );
+	
+	/** 
+	 * Method which starts the harvesting of the file. Called by the 
+	 * harvesting framework from CHarvesterPluginFactory::HarvestL.
+	 */
+	IMPORT_C virtual void StartHarvest();
+	
+	/** 
+	 * Method which returns the MdE object type to harvesting FW when passing the file
+	 * name to this method (aURI). The harvesting plug-in should overwrite method. In the
+	 * case there are more than one plug-ins which support same file extension atleast
+	 * one of these plug-ins needs to read the binary file for determining the valid MdE
+	 * object type for the file.
+	 *
+	 * @param aUri         URI of the file/item.
+	 * @param aObjectType  Reference to an object type which will returned to the FW 
+	 *                     from the plug-in
+	 */
+	IMPORT_C virtual void GetObjectType( const TDesC& aUri, TDes& aObjectType );
+	
+	/** 
+	 * Method for setting the blacklisting functionality for the plug-in.
+	 * 
+	 * @param aBlacklist  Reference to blacklisting component.
+	 */
+	IMPORT_C virtual void SetBlacklist( CHarvesterBlacklist& aBlacklist );
+
+protected:
+    
+	/** 
+	 * The method which does the actual harvesting. Harvesting plug-in MUST
+	 * implelemt this method.
+	 * 
+	 * @param aHD  Pointer to harvesting data/request.
+	 */
+	IMPORT_C virtual void HarvestL( CHarvesterData* aHD ) = 0;
+	
+	/** 
+	 * Active object RunL implementation.
+	 */
+	IMPORT_C virtual void RunL();
+	  
+	/** 
+	 * Active object DoCancel implementation.
+	 */
+	IMPORT_C virtual void DoCancel();
+	  
+	/** 
+	 * Active object RunError implementation.
+	 */
+	IMPORT_C virtual TInt RunError( TInt aError );
+	
+	 /** 
+	  * Construction of the interface class
+	  */
+	 void ConstructL();
+	
+	 /** 
+	  * Constuctor 
+	  */
+	 IMPORT_C CHarvesterPlugin();
+         
+private:
+    
+	/** 
+	 * Sets next state for the active object
+	 *
+	 * @param aState  Next state to execute with RunL.
+	 */
+	void SetNextRequest( THarvesterState aState );
+		
+	/** 
+	 * Method sets some default properties to the metadata object
+	 * 
+	 * @param aData  Pointer to harvesting data/request.
+	 */
+	void SetDefaultPropertiesL(CHarvesterData& aData);
+	
+protected:
+	
+	/** 
+	 * Handle to File server session.
+	 */
+	RFs iFs;
+	
+	/**
+	 *  State of this active object.
+	*/
+	THarvesterState iState;
+	     
+	/** 
+	 * Pointer to Harvesting request queue.
+	 */
+	RPointerArray<CHarvesterData>* iQueue;
+	
+	/** 
+	 * Pointer to blacklisting functionality
+	 */
+	CHarvesterBlacklist* iBlacklist;
+	
+private:
+	
+	/* Identification on cleanup */ 
+	TUid iDtor_ID_Key;
+
+	CMdEPropertyDef* iOriginPropertyDef;
+	CMdEPropertyDef* iTitlePropertyDef;
+    };
+
+#endif // __CHARVESTERPLUGIN_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/inc/monitorplugin.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,191 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition of the Monitor plug-in ECom interface.*
+*/
+
+#ifndef __MONITORPLUGIN_H__
+#define __MONITORPLUGIN_H__
+
+#include <e32base.h>
+#include <ecom.h>
+
+#include <harvesterdata.h>
+
+// FORWARD DECLARATION
+class CMdESession;
+class CContextEngine;
+class CHarvesterPluginFactory;
+
+// Uid for this interface
+const TUid KMonitorPluginInterfaceUid = { 0x20007181 };
+
+class TMountData
+	{
+	public:
+	enum TMountType
+		{
+		EMount,   // Drive was mounted 
+		EUnmount, // Drive was unmounted
+		EFormat   // Drive was formatted
+		};
+		
+	TMountType iMountType;  // See above
+	TUint32 iMediaID;       // Storage MediaID - TVolumeInfo::iUniqueID
+	TBuf<2> iDrivePath;     // Drive letter
+	};
+
+/**
+ * Monitor Plug-in ECom interface definition. Monitor plug-in implementation
+ * needs to inherit this class and implement the pure virtual methods which exist 
+ * in this interface. All monitor plug-ins are provided a reference to the Harvester 
+ * server (MMonitorPluginObserver) which hanles the new harvesting requests, open session 
+ * to MdE for DB maintenance operations, pointer to ContextEngine and a pointer Harvester 
+ * plug-in factory.  
+ *
+ * Example:
+ * 
+ * // interface for notifying Monitor plug-in about new files
+ * class MMonitorNotifier
+ *	{
+ *   public:
+ *   	/**
+ *	    * Called when we notice a new file/item
+ *	    *
+ *	    * @param aHarvesterData  Pointer to harvesting related data/harvesting request data
+ *	    *
+ *   	virtual void NewFile( CHarvesterData* aHarvesterData ) = 0;
+ *  }
+ * 
+ * // Monitor plug-in implementation
+ * class CMyMonitorPlugin: public CMonitorPlugin, public MMonitorNotifier
+ *     {
+ *     public:
+ *         TBool StartMonitoring(MMonitorPluginObserver& aObserver, CMdESession* aMdEClient,
+ *				CContextEngine* aCtxEngine, CHarvesterPluginFactory* aHarvesterPluginFactory );
+ *	       TBool StopMonitoring();
+ *	       TBool ResumeMonitoring( MMonitorPluginObserver& aObserver, CMdESession* aMdEClient,
+ *				CContextEngine* aCtxEngine, CHarvesterPluginFactory* aHarvesterPluginFactory );				
+ *	       TBool PauseMonitoring();
+ *         void NewFile( CHarvesterData* aHarvesterData );
+ *
+ *     private:
+ *          MMonitorPluginObserver* iObserver;
+ *          CMyActiveObjectNotifier* iNotifier;
+ *     }
+ *
+ * TBool CMyMonitorPlugin::StartMonitoring(MMonitorPluginObserver& aObserver, CMdESession* aMdEClient,
+ *				CContextEngine* aCtxEngine, CHarvesterPluginFactory* aHarvesterPluginFactory )
+ *     {
+ *     iObserver = &aObserver;  
+ *     
+ *     // Active object which observes the system and notices new files/items in the system
+ *     iNotifier = CMyActiveObjectNotifier::NewL(*this);
+ *     }   	       
+ * TBool CMyMonitorPlugin::StopMonitoring()
+ *     {
+ *	   iNotifier->StopNotifying();	
+ *     }
+ *	       
+ * TBool CMyMonitorPlugin::ResumeMonitoring( MMonitorPluginObserver& aObserver, CMdESession* aMdEClient,
+ *				CContextEngine* aCtxEngine, CHarvesterPluginFactory* aHarvesterPluginFactory )
+ *     {
+ *     // Do what needs to be done when operation is resumed - for example handle
+ *     // events received through callback CMyMonitorPlugin::NewFile during pause. 
+ *     }	      				
+ *	       
+ * TBool CMyMonitorPlugin::PauseMonitoring()
+ *     {
+ *     // Do what needs to be done during pause - for example buffer all events coming 
+ *     // through callback CMyMonitorPlugin::NewFile
+ *     }
+ *
+ * void CMyMonitorPlugin::NewFile( CHarvesterData* aHarvesterData )
+ *    {
+ *	  // Our CMyActiveObjectNotifier notifies us about new file and we notify the Harvester server about it.
+ *	  // Before this CMyActiveObjectNotifier has filled the need data to aHarvesterData like:
+ *	  // aHarvesterData->SetEventType( EHarvesterAdd );
+ *    // aHarvesterData->SetOrigin( aOrigin );
+ *    iObserver->MonitorEvent( aHarvesterData );
+ *    }
+ */
+class CMonitorPlugin : public CBase
+  	{
+	public:
+		/**
+		* Creates and constructs a new instance of CMonitorPlugin.
+		*
+		* @param aUid  An UID of desired implementation.
+		* @return A pointer to the new instance of CMonitorPlugin.
+		*/
+		IMPORT_C static CMonitorPlugin* NewL(const TUid& aUid);
+	
+		/**
+		* A static method which list all available implementations which satisfy this given interface.
+		*
+		* @param aImplInfoArray  On return this contains information about all available implementations.
+		*/
+		IMPORT_C static void ListImplementationsL(RImplInfoPtrArray& aImplInfoArray);
+		
+		/**
+		* Destructor
+		*/
+		IMPORT_C virtual ~CMonitorPlugin();
+		
+		/**
+		* A pure virtual method which starts the monitoring.
+		*
+		* @param aObserver  All events are notified via the aObserver.
+		* @param aMdEClient  A pointer to MdE client.
+		* @param aCtxEngine  A pointer to context engine.
+		* @param aHarvesterPluginFactory  A pointer to harvester plugin factory.
+		* @return ETrue if success, EFalse if not.
+		*/
+		virtual TBool StartMonitoring(MMonitorPluginObserver& aObserver, CMdESession* aMdEClient,
+				CContextEngine* aCtxEngine, CHarvesterPluginFactory* aHarvesterPluginFactory ) = 0;
+		
+		/**
+		* A pure virtual method which stops the monitoring.
+		*
+		* @return ETrue if success, EFalse if not.
+		*/
+		virtual TBool StopMonitoring() = 0;
+		
+		/**
+		* A pure virtual method which resumes the paused plug-in.
+		*
+		* @param aObserver  All events are notified via the aObserver.
+		* @param aMdEClient  A pointer to MdE client.
+		* @param aCtxEngine  A pointer to context engine.
+		* @param aHarvesterPluginFactory  A pointer to harvester plugin factory.
+		* @return ETrue if success, EFalse if not.
+		*/
+		virtual TBool ResumeMonitoring(MMonitorPluginObserver& aObserver, CMdESession* aMdEClient, 
+				CContextEngine* aCtxEngine, CHarvesterPluginFactory* aHarvesterPluginFactory ) = 0;
+		
+		/**
+		* A pure virtual method which pauses the plug-in.
+		*
+		* @return ETrue if success, EFalse if not.
+		*/
+		virtual TBool PauseMonitoring() = 0;
+
+	private:
+		
+		/**
+		* Identification on cleanup.
+		*/
+		TUid iDtor_ID_Key;
+	};
+
+#endif // __MONITORPLUGIN_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/inc/placeholderdata.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,163 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Data transfer object for placeholder data
+*
+*/
+
+
+#ifndef PLACEHOLDERDATA_H
+#define PLACEHOLDERDATA_H
+
+// INCLUDES
+#include <e32std.h>
+#include <e32cmn.h>
+#include <e32def.h>
+#include <e32base.h>
+
+
+/**
+ * A helper class which encapsulates data needed for 
+ * creating placeholder objects.
+ */
+NONSHARABLE_CLASS( CPlaceholderData ) : public CBase
+	{
+	public:
+
+	    /**
+	     * Second phase construction
+	     */
+		IMPORT_C static CPlaceholderData* NewL();
+
+	    /**
+	     * Destructor.
+	     */
+		virtual ~CPlaceholderData();
+
+	    /**
+	     * Returns modification time - equals RFs::Modified()
+	     * 
+	     * @param  Last modification time
+	     */				
+		IMPORT_C TTime Modified();
+		
+	    /**
+	     * Sets modification time - should be RFs::Modified()
+	     * for binary files
+	     * 
+	     * @return  Last modification time
+	     */		
+		IMPORT_C void SetModified( TTime aModified );
+		
+	    /**
+	     * Returns URI of the file/item.
+	     * 
+	     * @return  URI
+	     */			
+		IMPORT_C TPtr16 Uri();
+
+	    /**
+	     * Sets URI of the file/item.
+	     * 
+	     * @param aUri  URI of the file
+	     */		
+		IMPORT_C void SetUri( const TDesC& aUri );
+		
+	    /**
+	     * Returns file size bytes.
+	     * 
+	     * @return  File size in bytes.
+	     */					
+		IMPORT_C TUint32 FileSize();
+
+	    /**
+	     * Sets file size bytes.
+	     * 
+	     * @param aUri  File size bytes.
+	     */	
+		IMPORT_C void SetFileSize( TUint32 aFileSize );
+		
+	    /**
+	     * Returns MediaID which identifies the volume/drive where
+	     * the file is located. Equals to TVolumeInfo::iUniqueID.
+	     * 
+	     * @return  MediaID
+	     */				
+		IMPORT_C TUint MediaId();
+		
+	    /**
+	     * Sets MediaID which identifies the volume/drive where
+	     * the file is located. Equals to TVolumeInfo::iUniqueID.
+	     * 
+	     * @param aMediaId  MediaID of the volume.
+	     */	
+		IMPORT_C void SetMediaId( TUint aMediaId );
+		
+	    /**
+	     * Returns present state for the file.
+	     * 
+	     * @return  Present state.
+	     */		
+		IMPORT_C TInt PresentState();
+
+	    /**
+	     * Sets present state for the file
+	     * 
+	     * @param aState  Present state.
+	     */			
+		IMPORT_C void SetPresentState( TInt aState );
+
+	    /**
+	     * Returns whether file is pre-installed or not.
+	     * 
+	     * @return  Whether file is pre-installed or not.
+	     */		
+		IMPORT_C TInt Preinstalled();
+
+	    /**
+	     * Sets whether file is pre-installed or not.
+	     * 
+	     * @param aValue  Whether file is pre-installed or not.
+	     */	
+		IMPORT_C void SetPreinstalled( TInt aValue );
+		
+	protected:
+	
+	    /**
+	     * Constructor
+	     */	
+		void ConstructL();
+	
+	private:
+		
+		/* URI of the placeholder */
+		HBufC* iUri;
+		
+		/* Last modified time - RFs::Modified() */ 
+		TTime iModified;
+		
+		/* File size in bytes */
+		TUint32 iFileSize;
+		
+		/* Volume/Drive ID where file - TVolumeInfo::iUniqueID*/
+		TUint32 iMediaId;
+		
+		/* Present/not present state */
+		TInt iPresentState;
+		
+		/* Whether file is pre-installed or not */
+		TInt iPreinstalled;
+	};
+
+#endif // PLACEHOLDERDATA_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/Bmarm/ComposerPluginTestU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	LibEntryL__FR13CTestModuleIf @ 1 NONAME R3UNUSED ; LibEntryL(CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/Bwins/ComposerPluginTestU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?LibEntryL@@YAPAVCScriptBase@@AAVCTestModuleIf@@@Z @ 1 NONAME ; class CScriptBase * __cdecl LibEntryL(class CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/EABI/ComposerPluginTestU.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	_Z9LibEntryLR13CTestModuleIf @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/conf/ComposerPluginTest.cfg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,122 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  Composer Plugin API tests
+#
+
+// ---------------------------------------------------------------------------
+// Composer Plugin API test cases
+// ---------------------------------------------------------------------------
+
+// These should be run in sequential mode if several cases are run at the same
+// time! 
+
+[StifSettings]
+TestThreadStackSize= 32768
+TestThreadMinHeap= 4096
+TestThreadMaxHeap= 16777216
+[EndStifSettings]
+
+[Test]
+title Startup and Shutdown
+create ComposerPluginTest test
+request Session
+test BeginComposerSession
+wait Session
+test LoadPlugins
+test SetSessions
+test ActiveWait
+test RemoveSessions
+test EndComposerSession
+delete test
+[Endtest]
+
+[Test]
+title Modify Object 1
+create ComposerPluginTest test
+request Session
+test BeginComposerSession
+wait Session
+test LoadPlugins
+test SetSessions
+test ModifyObjects 1 e:\testing\data\Jpg.jpg
+test WaitComposingComplete
+test DeleteObject e:\testing\data\Jpg.jpg
+test RemoveSessions
+test EndComposerSession
+delete test
+[Endtest]
+
+[Test]
+title Modify Object 2
+create ComposerPluginTest test
+request Session
+test BeginComposerSession
+wait Session
+test LoadPlugins
+test SetSessions
+test ModifyObjects 1 e:\testing\data\Animated.gif
+test WaitComposingComplete
+test DeleteObject e:\testing\data\Animated.gif
+test RemoveSessions
+test EndComposerSession
+delete test
+[Endtest]
+
+[Test]
+title Modify Object 3
+create ComposerPluginTest test
+request Session
+test BeginComposerSession
+wait Session
+test LoadPlugins
+test SetSessions
+test ModifyObjects 1 e:\testing\data\H263.3gp
+test WaitComposingComplete
+test DeleteObject e:\testing\data\H263.3gp
+test RemoveSessions
+test EndComposerSession
+delete test
+[Endtest]
+
+[Test]
+title Modify Object 4
+create ComposerPluginTest test
+request Session
+test BeginComposerSession
+wait Session
+test LoadPlugins
+test SetSessions
+test ModifyObjects 1 e:\testing\data\Wtf.wtf
+test WaitComposingComplete
+test DeleteObject e:\testing\data\Wtf.wtf
+test RemoveSessions
+test EndComposerSession
+delete test
+[Endtest]
+
+[Test]
+title Modify Multiple Objects
+create ComposerPluginTest test
+request Session
+test BeginComposerSession
+wait Session
+test LoadPlugins
+test SetSessions
+test ModifyObjects 100
+test WaitComposingComplete
+test DeleteObjects 100
+test RemoveSessions
+test EndComposerSession
+delete test
+[Endtest]
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/group/ComposerPluginTest.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET          ComposerPluginTest.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E3
+
+CAPABILITY      ALL -TCB
+VENDORID        VID_DEFAULT
+
+DEFFILE         ComposerPluginTest.DEF
+
+SOURCEPATH      ../src
+SOURCE          ComposerPluginTest.cpp
+SOURCE          ComposerPluginTestBlocks.cpp
+
+USERINCLUDE     ../inc 
+USERINCLUDE     ../../../../../inc
+SYSTEMINCLUDE 	/epoc32/include/ecom
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+LIBRARY	        ecom.lib
+LIBRARY         composerplugininterface.lib
+LIBRARY         mdeclient.lib
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/group/ComposerPluginTest.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,56 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:  Installation file for API test
+;
+
+; Languages
+&EN
+
+; Header
+#{"ComposerPluginTest"},(0x101FB3E3),1,0,0,TYPE=SA
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Install files
+"\epoc32\release\armv5\urel\ComposerPluginTest.dll" - "c:\sys\bin\ComposerPluginTest.dll"
+"..\conf\ComposerPluginTest.cfg" - "c:\TestFramework\ComposerPluginTest.cfg"
+"..\init\ComposerPluginTest.ini" - "c:\TestFramework\ComposerPluginTest.ini"
+
+"..\..\data\mmc\HarvesterTest\Jpg.jpg"      -"E:\testing\data\Jpg.jpg"
+"..\..\data\mmc\HarvesterTest\Animated.gif"      -"E:\testing\data\Animated.gif"
+"..\..\data\mmc\HarvesterTest\Temp1.jpg"      -"E:\testing\data\Temp1.jpg"
+"..\..\data\mmc\HarvesterTest\Temp2.jpg"      -"E:\testing\data\Temp2.jpg"
+"..\..\data\mmc\HarvesterTest\Temp3.jpg"      -"E:\testing\data\Temp3.jpg"
+"..\..\data\mmc\HarvesterTest\H263.3gp"      -"E:\testing\data\H263.3gp"
+"..\..\data\mmc\HarvesterTest\bmp_burst.bmp"      -"E:\testing\data\bmp_burst.bmp"
+"..\..\data\mmc\HarvesterTest\GIF87testimage.gif"      -"E:\testing\data\GIF87testimage.gif"
+"..\..\data\mmc\HarvesterTest\gif89a_onemeg.gif"      -"E:\testing\data\gif89a_onemeg.gif"
+"..\..\data\mmc\HarvesterTest\Liverpool.jpg"      -"E:\testing\data\Liverpool.jpg"
+"..\..\data\mmc\HarvesterTest\MBMtestimage.mbm"      -"E:\testing\data\MBMtestimage.mbm"
+"..\..\data\mmc\HarvesterTest\wbmp_skull.wbmp"      -"E:\testing\data\wbmp_skull.wbmp"
+"..\..\data\mmc\HarvesterTest\ota_bmpiso.ota"      -"E:\testing\data\ota_bmpiso.ota"
+"..\..\data\mmc\HarvesterTest\PNGtestimage.png"      -"E:\testing\data\PNGtestimage.png"
+"..\..\data\mmc\HarvesterTest\G4.TIF"      -"E:\testing\data\G4.TIF"
+"..\..\data\mmc\HarvesterTest\G31D.TIF"      -"E:\testing\data\G31D.TIF"
+"..\..\data\mmc\HarvesterTest\PSRETRO.WMF"      -"E:\testing\data\PSRETRO.WMF"
+"..\..\data\mmc\HarvesterTest\Animated.gif"      -"E:\testing\data\Animated.gif"
+"..\..\data\mmc\HarvesterTest\Mbm.mbm"      -"E:\testing\data\Mbm.mbm"
+"..\..\data\mmc\HarvesterTest\MPEG4.3gp"      -"E:\testing\data\MPEG4.3gp"
+"..\..\data\mmc\HarvesterTest\MPEG4.mp4"      -"E:\testing\data\MPEG4.mp4"
+"..\..\data\mmc\HarvesterTest\00001.mp3"      -"E:\testing\data\00001.mp3"
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+ComposerPluginTest.mmp
+
+PRJ_TESTEXPORTS
+
+../conf/ComposerPluginTest.cfg /epoc32/winscw/c/TestFramework/ComposerPluginTest.cfg
+../init/ComposerPluginTest.ini /epoc32/winscw/c/TestFramework/ComposerPluginTest.ini
+
+../../data/mmc/HarvesterTest/bmp_burst.bmp /epoc32/WINSCW/C/Data/bmp_burst.bmp
+../../data/mmc/HarvesterTest/G31D.TIF /epoc32/WINSCW/C/Data/G31D.TIF
+../../data/mmc/HarvesterTest/G4.TIF /epoc32/WINSCW/C/Data/G4.TIF
+../../data/mmc/HarvesterTest/GIF87testimage.gif /epoc32/WINSCW/C/Data/GIF87testimage.gif
+../../data/mmc/HarvesterTest/gif89a_onemeg.gif /epoc32/WINSCW/C/Data/gif89a_onemeg.gif
+../../data/mmc/HarvesterTest/Liverpool.jpg /epoc32/WINSCW/C/Data/Liverpool.jpg
+../../data/mmc/HarvesterTest/MBMtestimage.mbm /epoc32/WINSCW/C/Data/MBMtestimage.mbm
+../../data/mmc/HarvesterTest/ota_bmpiso.ota /epoc32/WINSCW/C/Data/ota_bmpiso.ota
+../../data/mmc/HarvesterTest/PNGtestimage.png /epoc32/WINSCW/C/Data/PNGtestimage.png
+../../data/mmc/HarvesterTest/PSRETRO.WMF /epoc32/WINSCW/C/Data/PSRETRO.WMF
+../../data/mmc/HarvesterTest/wbmp_skull.wbmp /epoc32/WINSCW/C/Data/wbmp_skull.wbmp
+../../data/mmc/HarvesterTest/Jpg.jpg /epoc32/WINSCW/C/Data/Jpg.jpg
+../../data/mmc/HarvesterTest/Animated.gif /epoc32/WINSCW/C/Data/Animated.gif
+../../data/mmc/HarvesterTest/Mbm.mbm /epoc32/WINSCW/C/Data/Mbm.mbm
+../../data/mmc/HarvesterTest/H263.3gp /epoc32/WINSCW/C/Data/H263.3gp
+../../data/mmc/HarvesterTest/MPEG4.mp4 /epoc32/WINSCW/C/Data/MPEG4.mp4
+../../data/mmc/HarvesterTest/MPEG4.3gp /epoc32/WINSCW/C/Data/MPEG4.3gp
+../../data/mmc/HarvesterTest/Temp1.jpg /epoc32/WINSCW/C/Data/Temp1.jpg
+../../data/mmc/HarvesterTest/Temp2.jpg /epoc32/WINSCW/C/Data/Temp2.jpg
+../../data/mmc/HarvesterTest/Temp3.jpg /epoc32/WINSCW/C/Data/Temp3.jpg
+../../data/mmc/HarvesterTest/00001.mp3 /epoc32/WINSCW/C/Data/00001.mp3
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/inc/ComposerPluginTest.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,106 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef COMPOSERPLUGINTEST_H
+#define COMPOSERPLUGINTEST_H
+
+//  INCLUDES
+#include <StifLogger.h>
+#include <TestScripterInternal.h>
+#include <StifTestModule.h>
+
+#include <mdesession.h>
+#include <composerplugin.h>
+
+// CONSTANTS
+
+_LIT( KComposerPluginTestLogPath, "\\logs\\testframework\\ComposerPluginTest\\" ); 
+// Log file
+_LIT( KComposerPluginTestLogFile, "ComposerPluginTest.txt" ); 
+_LIT( KComposerPluginTestLogFileWithTitle, "ComposerPluginTest_[%S].txt" );
+
+// FORWARD DECLARATIONS
+class CComposerPluginTest;
+
+// CLASS DECLARATION
+NONSHARABLE_CLASS(CComposerPluginTest) : public CScriptBase,
+									     public MMdESessionObserver
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CComposerPluginTest* NewL( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CComposerPluginTest();
+
+    public: // Functions from base classes
+
+        virtual TInt RunMethodL( CStifItemParser& aItem );
+
+    private: // Functions from base classes
+    	
+    	void HandleSessionOpened(CMdESession& aSession, TInt aError);
+    	void HandleSessionError(CMdESession& aSession, TInt aError);
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CComposerPluginTest( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Frees all resources allocated from test methods.
+        */
+        void Delete();
+        
+        /**
+        * Test methods are listed below. 
+        */
+        //[TestMethods] - Do not remove
+        virtual TInt ActiveWait( CStifItemParser& aItem );
+        virtual TInt BeginComposerSessionL( CStifItemParser& aItem );
+        virtual TInt EndComposerSession( CStifItemParser& aItem );
+        virtual TInt LoadPluginsL( CStifItemParser& aItem );
+        virtual TInt SetSessions( CStifItemParser& aItem );
+        virtual TInt RemoveSessions( CStifItemParser& aItem );
+        virtual TInt ModifyObjectsL( CStifItemParser& aItem );
+        virtual TInt DeleteObjectL( CStifItemParser& aItem );
+        virtual TInt DeleteObjectsL( CStifItemParser& aItem );
+        virtual TInt WaitComposingComplete( CStifItemParser& aItem );
+
+    private:    // Data
+        
+        CMdESession* iMdEClient;
+        
+        RPointerArray<CComposerPlugin> iPluginArray;
+    };
+
+#endif      // COMPOSERPLUGINTEST_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/init/ComposerPluginTest.ini	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,81 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  
+#
+
+
+[Engine_Defaults]
+
+TestReportMode= FullReport    # Possible values are: 'Empty', 'Summary', 'Environment',
+                                                     'TestCases' or 'FullReport'
+
+CreateTestReport= YES         # Possible values: YES or NO
+
+TestReportFilePath= C:\LOGS\TestFramework\
+TestReportFileName= ComposerPluginTestLog
+
+TestReportFormat= TXT         # Possible values: TXT or HTML
+TestReportOutput= FILE        # Possible values: FILE or RDEBUG
+TestReportFileCreationMode= OVERWRITE # Possible values: OVERWRITE or APPEND
+
+DeviceResetDllName= StifResetForNokia.dll # e.g. 'StifHWResetStub.dll' for user specific reseting
+
+DisableMeasurement= stifmeasurementdisablenone  # Possible values are:
+              # 'stifmeasurementdisablenone', 'stifmeasurementdisableall'
+              # 'stifmeasurementplugin01', 'stifmeasurementplugin02',
+              # 'stifmeasurementplugin03', 'stifmeasurementplugin04',
+              # 'stifmeasurementplugin05' or 'stifbappeaprofiler'
+
+Timeout= 600000		            # Default timeout value for each test case. In milliseconds
+#UITestingSupport= YES        # Possible values: YES or NO
+#SeparateProcesses= YES       # Possible values: YES or NO (default: NO)
+[End_Defaults]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[New_Module]
+ModuleName= TestScripter
+TestCaseFile= c:\testframework\ComposerPluginTest.cfg
+[End_Module]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[Logger_Defaults]
+
+#NOTE: If you want to set Logger using next setting(s) remove comment(s)'#'
+#NOTE: TestEngine and TestServer logging settings cannot change here
+
+CreateLogDirectories= YES    # Possible values: YES or NO
+
+#EmulatorBasePath= C:\LOGS\TestFramework\
+#EmulatorFormat= HTML         # Possible values: TXT or HTML
+#EmulatorOutput= FILE         # Possible values: FILE or RDEBUG
+
+HardwareBasePath= C:\
+#HardwareFormat= HTML         # Possible values: TXT or HTML
+#HardwareOutput= FILE         # Possible values: FILE or RDEBUG
+
+#FileCreationMode= OVERWRITE  # Possible values: OVERWRITE or APPEND
+
+#ThreadIdToLogFile= YES       # Possible values: YES or NO
+#WithTimeStamp= YES           # Possible values: YES or NO
+#WithLineBreak= YES           # Possible values: YES or NO
+#WithEventRanking= YES        # Possible values: YES or NO
+
+#FileUnicode= YES             # Possible values: YES or NO
+AddTestCaseTitle= YES        # Possible values: YES or NO
+[End_Logger_Defaults]
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+# End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/src/ComposerPluginTest.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+// INCLUDE FILES
+#include <StifTestInterface.h>
+#include "ComposerPluginTest.h"
+#include <SettingServerClient.h>
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::CComposerPluginTest
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CComposerPluginTest::CComposerPluginTest( 
+    CTestModuleIf& aTestModuleIf ):
+        CScriptBase( aTestModuleIf )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CComposerPluginTest::ConstructL()
+    {
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        } 
+    // Close Setting server session
+    settingServer.Close();
+
+    TFileName logFileName;
+    
+    if(loggerSettings.iAddTestCaseTitle)
+        {
+        TName title;
+        TestModuleIf().GetTestCaseTitleL(title);
+        logFileName.Format(KComposerPluginTestLogFileWithTitle, &title);
+        }
+    else
+        {
+        logFileName.Copy(KComposerPluginTestLogFile);
+        }
+
+    iLog = CStifLogger::NewL( KComposerPluginTestLogPath, 
+                          logFileName,
+                          CStifLogger::ETxt,
+                          CStifLogger::EFile,
+                          EFalse );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CComposerPluginTest* CComposerPluginTest::NewL( 
+    CTestModuleIf& aTestModuleIf )
+    {
+    CComposerPluginTest* self = new (ELeave) CComposerPluginTest( aTestModuleIf );
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+
+    }
+
+// Destructor
+CComposerPluginTest::~CComposerPluginTest()
+    { 
+
+    // Delete resources allocated from test methods
+    Delete();
+
+    // Delete logger
+    delete iLog; 
+
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point.
+// Returns: CScriptBase: New CScriptBase derived object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScriptBase* LibEntryL( 
+    CTestModuleIf& aTestModuleIf ) // Backpointer to STIF Test Framework
+    {
+
+    return ( CScriptBase* ) CComposerPluginTest::NewL( aTestModuleIf );
+
+    }
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/ComposerPluginTest/src/ComposerPluginTestBlocks.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1035 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+// [INCLUDE FILES] - do not remove
+#include <e32svr.h>
+#include <StifParser.h>
+#include <StifTestEventInterface.h>
+#include <StifTestInterface.h>
+#include "ComposerPluginTest.h"
+
+#include "mdsutils.h"
+#include "mdeconstants.h"
+
+using namespace MdeConstants;
+
+_LIT( KOpenErr, "        ModifyObjects - Open error : %d" );
+_LIT( KCommErr, "        ModifyObjects - Commit error : %d" );
+_LIT( KNull, "        ModifyObjects - NULL object" );
+_LIT( KCommit, "        ModifyObjects - Object committed" );
+_LIT( KUri, "C:\\Data\\Images\\Temp%d.jpg" );
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::Delete
+// Delete here all resources allocated and opened from test methods. 
+// Called from destructor. 
+// -----------------------------------------------------------------------------
+//
+void CComposerPluginTest::Delete() 
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::RunMethodL
+// Run specified method. Contains also table of test mothods and their names.
+// -----------------------------------------------------------------------------
+//
+TInt CComposerPluginTest::RunMethodL( 
+    CStifItemParser& aItem ) 
+    {
+
+    static TStifFunctionInfo const KFunctions[] =
+        {  
+        // Copy this line for every implemented function.
+        // First string is the function name used in TestScripter script file.
+        // Second is the actual implementation member function. 
+
+        ENTRY( "ActiveWait", CComposerPluginTest::ActiveWait ),
+        ENTRY( "BeginComposerSession", CComposerPluginTest::BeginComposerSessionL ),
+        ENTRY( "EndComposerSession", CComposerPluginTest::EndComposerSession ),
+        ENTRY( "LoadPlugins", CComposerPluginTest::LoadPluginsL ),
+        ENTRY( "SetSessions", CComposerPluginTest::SetSessions ),
+        ENTRY( "RemoveSessions", CComposerPluginTest::RemoveSessions ),
+        ENTRY( "ModifyObjects", CComposerPluginTest::ModifyObjectsL ),
+        ENTRY( "DeleteObject", CComposerPluginTest::DeleteObjectL ),
+        ENTRY( "DeleteObjects", CComposerPluginTest::DeleteObjectsL ),
+        ENTRY( "WaitComposingComplete", CComposerPluginTest::WaitComposingComplete ),
+
+        };
+
+    const TInt count = sizeof( KFunctions ) / 
+                        sizeof( TStifFunctionInfo );
+
+    return RunInternalL( KFunctions, count, aItem );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::HandleSessionOpened
+// -----------------------------------------------------------------------------
+//
+void CComposerPluginTest::HandleSessionOpened( CMdESession& /*aClient*/, TInt aError )
+    {
+    _LIT( KMsg, "CallBck HandleSessionOpened - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );     
+    RDebug::Print(msg);
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+    }
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::HandleSessionError
+// -----------------------------------------------------------------------------
+//
+void CComposerPluginTest::HandleSessionError( CMdESession& /*aClient*/, TInt aError )
+    {
+    _LIT( KMsg, "CallBck HandleSessionError - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );
+    RDebug::Print(msg);
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+    }   
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::ActiveWait
+// -----------------------------------------------------------------------------
+//
+TInt CComposerPluginTest::ActiveWait( CStifItemParser& /* aItem */ )
+    {
+    TTimeIntervalMicroSeconds32 timeout(2500000);
+    RTimer timer;
+    TRequestStatus status;
+
+    timer.CreateLocal();
+    timer.After(status,timeout);
+
+    User::WaitForAnyRequest();
+    
+    timer.Close();
+    
+    _LIT( KMsg1, "Exit ActiveWait" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::BeginComposerSessionL
+// -----------------------------------------------------------------------------
+//
+TInt CComposerPluginTest::BeginComposerSessionL( CStifItemParser& /* aItem */ )
+    {
+    iMdEClient = NULL;
+    TRAPD( error, iMdEClient = CMdESession::NewL( *this ) );
+
+    _LIT( KMsg, "Exit    BeginComposerSession - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, error);
+    iLog->Log( msg );
+    RDebug::Print(msg);
+    
+    User::LeaveIfError(error);
+    
+    return KErrNone;
+    }    
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::EndComposerSession
+// -----------------------------------------------------------------------------
+//
+TInt CComposerPluginTest::EndComposerSession( CStifItemParser& /* aItem */ )
+	{    
+	iPluginArray.ResetAndDestroy();
+	iPluginArray.Close();
+	    
+	if ( iMdEClient )
+		{
+	    delete iMdEClient;
+	    iMdEClient = NULL;
+	    }
+    
+	REComSession::FinalClose();
+	
+    _LIT( KMsg, "Exit EndComposerSession" );
+    iLog->Log( KMsg );  
+    RDebug::Print( KMsg );
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::LoadPluginsL
+// -----------------------------------------------------------------------------
+//
+TInt CComposerPluginTest::LoadPluginsL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter LoadPlugins" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TUid imageComposerUID = { 0x20007185 }; // MDS image composer plugin
+    
+    RImplInfoPtrArray infoArray;
+    	
+	TCleanupItem cleanupItem( MdsUtils::CleanupEComArray, &infoArray );
+	CleanupStack::PushL( cleanupItem );
+	
+	CComposerPlugin::ListImplementationsL( infoArray );
+	TInt count( 0 );
+	count = infoArray.Count();
+	
+	for ( TInt i=0; i < count; i++ )
+		{
+		TUid uid = infoArray[i]->ImplementationUid();    // Create the plug-ins
+		if( uid == imageComposerUID )
+		    {
+		    iPluginArray.AppendL( CComposerPlugin::NewL( uid ) ); // and add them to array
+		    }
+		}
+		
+	CleanupStack::PopAndDestroy( &infoArray ); // infoArray, results in a call to CleanupEComArray
+    
+	if( iPluginArray.Count() == 0 )
+	    {
+	    return KErrNotFound;
+	    }
+
+	
+    _LIT( KMsg2, "Exit LoadPlugins" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::SetSessions
+// -----------------------------------------------------------------------------
+//
+TInt CComposerPluginTest::SetSessions( CStifItemParser&  /*aItem*/ )
+	{    
+    _LIT( KMsg1, "Enter SetSessions" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    if( !iMdEClient )
+        {
+        return KErrUnknown;
+        }
+    
+	for ( TInt i = 0; i < iPluginArray.Count(); ++i )
+		{
+		iPluginArray[i]->SetSession( *iMdEClient );
+		}
+	
+    _LIT( KMsg2, "Exit SetSessions" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::RemoveSessions
+// -----------------------------------------------------------------------------
+//
+TInt CComposerPluginTest::RemoveSessions( CStifItemParser& /* aItem */ )
+	{    
+    _LIT( KMsg1, "Enter RemoveSessions" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+	
+	for(TInt i = 0; i < iPluginArray.Count(); ++i)
+		{
+		iPluginArray[i]->RemoveSession();
+		}
+	
+    _LIT( KMsg2, "Exit RemoveSessions" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::ModifyObjectsL
+// -----------------------------------------------------------------------------
+//
+TInt CComposerPluginTest::ModifyObjectsL( CStifItemParser&  aItem  )
+	{   	
+    _LIT( KMsg1, "Enter ModifyObjects" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+	
+	CMdENamespaceDef& defaultNamespace = iMdEClient->GetDefaultNamespaceDefL();
+	CMdEObjectDef& imageDef = defaultNamespace.GetObjectDefL( Image::KImageObject );
+	
+	// Mandatory parameters for any object.
+	CMdEPropertyDef& creationDef = imageDef.GetPropertyDefL( Object::KCreationDateProperty );
+	CMdEPropertyDef& modifiedDef = imageDef.GetPropertyDefL( Object::KLastModifiedDateProperty );
+	CMdEPropertyDef& sizeDef = imageDef.GetPropertyDefL( Object::KSizeProperty );
+	CMdEPropertyDef& itemTypeDef = imageDef.GetPropertyDefL( Object::KItemTypeProperty );	
+	
+	CMdEPropertyDef& descriptionPropertyDef = imageDef.GetPropertyDefL( MediaObject::KDescriptionProperty );
+	CMdEPropertyDef& widthDef = imageDef.GetPropertyDefL( MediaObject::KWidthProperty ); 
+	CMdEPropertyDef& heightDef = imageDef.GetPropertyDefL( MediaObject::KHeightProperty ); 
+	CMdEPropertyDef& commentDef = imageDef.GetPropertyDefL( MediaObject::KCommentProperty );
+	CMdEPropertyDef& lastModifiedDateDef = imageDef.GetPropertyDefL( Image::KDateTimeProperty );
+	CMdEPropertyDef& dateTimeDigitizedDef = imageDef.GetPropertyDefL( Image::KDateTimeDigitizedProperty );
+	CMdEPropertyDef& makeDef = imageDef.GetPropertyDefL( Image::KMakeProperty );
+	CMdEPropertyDef& modelDef = imageDef.GetPropertyDefL( Image::KModelProperty );
+	CMdEPropertyDef& artistDef = imageDef.GetPropertyDefL( MediaObject::KArtistProperty ); // Ei toimi
+	CMdEPropertyDef& orientationDef = imageDef.GetPropertyDefL( Image::KOrientationProperty );
+	CMdEPropertyDef& yCbCrPosDef = imageDef.GetPropertyDefL( Image::KYCbCrPositioningProperty );
+	CMdEPropertyDef& resolutionDef = imageDef.GetPropertyDefL( MediaObject::KResolutionUnitProperty );
+	CMdEPropertyDef& isoSpeedDef = imageDef.GetPropertyDefL( Image::KISOSpeedRatingsProperty );
+	CMdEPropertyDef& soundFileDef = imageDef.GetPropertyDefL( Image::KRelatedSoundFileProperty );
+	CMdEPropertyDef& exposureTimeDef = imageDef.GetPropertyDefL( Image::KExposureTimeProperty );
+	CMdEPropertyDef& apertureDef = imageDef.GetPropertyDefL(  Image::KApertureValueProperty );
+	CMdEPropertyDef& colourSpaceDef = imageDef.GetPropertyDefL( Image::KColourSpaceProperty );
+	CMdEPropertyDef& exposureBiasDef = imageDef.GetPropertyDefL( Image::KExposureBiasValueProperty );
+	CMdEPropertyDef& meteringDef = imageDef.GetPropertyDefL( Image::KMeteringModeProperty );
+	CMdEPropertyDef& exifVersionDef = imageDef.GetPropertyDefL( Image::KExifVersionProperty );
+	CMdEPropertyDef& flashPixVersionDef = imageDef.GetPropertyDefL( Image::KFlashPixVersionProperty );
+	CMdEPropertyDef& thumbXDef = imageDef.GetPropertyDefL( Image::KThumbXResolutionProperty );
+	CMdEPropertyDef& thumbYDef = imageDef.GetPropertyDefL( Image::KThumbYResolutionProperty );
+	CMdEPropertyDef& thumbResolutionUnitDef = imageDef.GetPropertyDefL( Image::KThumbResolutionUnitProperty );
+	CMdEPropertyDef& thumbCompressionDef = imageDef.GetPropertyDefL( Image::KThumbCompressionProperty );
+	CMdEPropertyDef& shutterSpeedDef = imageDef.GetPropertyDefL( Image::KShutterSpeedValueProperty );
+	CMdEPropertyDef& componentsDef = imageDef.GetPropertyDefL( Image::KComponentsConfigurationProperty );
+	CMdEPropertyDef& xResolutionDef = imageDef.GetPropertyDefL( Image::KXResolutionProperty );
+	CMdEPropertyDef& yResolutionDef = imageDef.GetPropertyDefL( Image::KYResolutionProperty );
+	CMdEPropertyDef& fNumberDef =  imageDef.GetPropertyDefL( Image::KFNumberProperty );
+	CMdEPropertyDef& focalLengthDef = imageDef.GetPropertyDefL( Image::KFocalLengthProperty );
+	CMdEPropertyDef& focalIn35Def = imageDef.GetPropertyDefL( Image::KFocalLengthIn35mmFilmProperty );
+    
+	TBuf <100> msg;
+
+	TInt count( 0 );
+	
+	User::LeaveIfError( aItem.GetNextInt( count ) );
+	
+	if ( count == 1 )
+		{	
+		TItemId objectId(0);
+		TTime currTime;
+		currTime.HomeTime();
+		TPtrC inputFile;
+		    	
+		User::LeaveIfError( aItem.GetNextString( inputFile ));
+		
+		// create object
+		iMdEClient->RemoveObjectL(inputFile);
+		CMdEObject* object = iMdEClient->NewObjectLC(imageDef, inputFile);
+		
+		object->AddTimePropertyL(creationDef, currTime);
+		object->AddTimePropertyL(modifiedDef, currTime);
+		object->AddUint32PropertyL( sizeDef, 0 );
+		object->AddTextPropertyL( itemTypeDef, Image::KImageObject );
+		
+		objectId = iMdEClient->AddObjectL(*object);
+		
+		CleanupStack::PopAndDestroy( object );
+		object = NULL;
+		
+		// open object for modification
+		TRAPD( openError, object = iMdEClient->OpenObjectL(objectId) );
+			
+		if ( !object || openError != KErrNone )
+			{
+		    msg.Format(KOpenErr, openError);
+		    iLog->Log( msg );
+		    RDebug::Print(msg);
+		    
+		    User::LeaveIfError(openError);
+			}
+
+		CleanupStack::PushL( object );
+
+   		CMdEProperty* property = NULL;
+   		
+   		
+   		// Modified date
+   		object->Property( lastModifiedDateDef, property );
+   		
+   		if ( property )
+   			{
+   			CMdETimeProperty* modTimeProperty = (CMdETimeProperty*)property;
+   			
+   			modTimeProperty->SetValueL( 1 );
+   			}
+   		else
+   			{
+   			object->AddTimePropertyL( lastModifiedDateDef, 1 );
+   			}
+   			
+   		property = NULL;		
+   		
+   		// Date & time digitized
+   		object->Property( dateTimeDigitizedDef, property );
+   			
+		if ( property )
+			{
+			CMdETimeProperty* digiTimeProperty = (CMdETimeProperty*)property;
+			
+			digiTimeProperty->SetValueL( 9959267210000000 );
+			}
+		else
+			{
+			object->AddTimePropertyL( dateTimeDigitizedDef, 9959267210000000 );
+			}
+   		
+   		property = NULL;
+   		
+   		// Title
+		_LIT( KDesc, "Description" );
+		object->Property( descriptionPropertyDef, property );
+
+		if ( property )
+			{					
+			property->SetTextValueL( KDesc );
+			}
+		else
+			{
+			object->AddTextPropertyL( descriptionPropertyDef, KDesc );
+			}
+  		
+   		property = NULL;
+   			
+		// Comment
+        _LIT( KNoComment, "Comment" );
+		object->Property( commentDef, property );
+		
+		if ( property )
+			{					
+			property->SetTextValueL( KNoComment );
+			}
+		else
+			{
+			object->AddTextPropertyL( commentDef, KNoComment );
+			}
+		
+		property = NULL;
+		
+		// Maker
+		object->Property( makeDef, property );
+		
+        _LIT( KOnkia, "Maker" );
+		if ( property )
+			{
+			property->SetTextValueL( KOnkia );
+			}
+		else
+			{
+			object->AddTextPropertyL( makeDef, KOnkia );
+			}
+			
+		property = NULL;
+			
+		// Model
+		object->Property( modelDef, property );
+        _LIT( KModel, "Model" );
+		if ( property )
+			{					
+			property->SetTextValueL( KModel );
+			}
+		else
+			{
+			object->AddTextPropertyL( modelDef, KModel );
+			}
+			
+		property = NULL;
+			
+		// Width
+		object->Property( widthDef, property );
+		
+		if ( property )
+			{
+			property->SetUint16ValueL( 100 );
+			}
+		else
+			{
+			object->AddUint16PropertyL( widthDef, 100 );
+			}
+		
+		property = NULL;
+			
+		// Height
+		object->Property( heightDef, property );
+		
+		if ( property )
+			{
+			property->SetUint16ValueL( 100 );
+			}
+		else
+			{
+			object->AddUint16PropertyL( heightDef, 100 );
+			}
+			
+		property = NULL;
+			
+		// Orientation
+		object->Property( orientationDef, property );
+		
+		if ( property )
+			{
+			property->SetUint16ValueL( 8 );
+			}
+		else
+			{
+			object->AddUint16PropertyL( orientationDef, 8 );
+			}
+			
+		property = NULL;
+			
+		// YCbCr positioning
+		object->Property( yCbCrPosDef, property );
+		
+		if ( property )
+			{
+			property->SetUint16ValueL( 2 );
+			}
+		else
+			{
+			object->AddUint16PropertyL( yCbCrPosDef, 2 );
+			}
+			
+		property = NULL;
+			
+		// ISO speed
+		object->Property( isoSpeedDef, property );
+		
+		if ( property )
+			{
+			property->SetUint16ValueL( 1600 );
+			}
+		else
+			{
+			object->AddUint16PropertyL( isoSpeedDef, 1600 );
+			}
+			
+		property = NULL;
+		
+		// Related soundfile
+		_LIT(KWavName, "Wav.wav");
+		object->Property( soundFileDef, property);
+		
+		if(property)
+			{					
+			property->SetTextValueL( KWavName );
+			}
+		else
+			{
+			object->AddTextPropertyL( soundFileDef, KWavName );
+			}
+		
+		property = NULL;
+		
+		// Exposure time
+		object->Property( exposureTimeDef, property);
+		
+		if(property)
+			{					
+			property->SetReal32ValueL( 99.1f );
+			}
+		else
+			{
+			object->AddReal32PropertyL( exposureTimeDef, 99.1f );
+			}
+			
+		property = NULL;
+		
+		// Aperture
+		object->Property( apertureDef, property);
+		
+		if(property)
+			{					
+			property->SetReal32ValueL( 5.0f );
+			}
+		else
+			{
+			object->AddReal32PropertyL( apertureDef, 5.0f );
+			}
+			
+		property = NULL;
+			
+		// Colour space
+		object->Property( colourSpaceDef, property);
+		
+		if (property)
+			{
+			property->SetUint16ValueL( 65535 );
+			}
+		else
+			{
+			object->AddUint16PropertyL( colourSpaceDef, 65535 );
+			}
+			
+		property = NULL;
+			
+		// Exposure bias
+		object->Property( exposureBiasDef, property);
+		
+		if(property)
+			{					
+			property->SetReal32ValueL( 0.0f );
+			}
+		else
+			{
+			object->AddReal32PropertyL( exposureBiasDef, 0.0f );
+			}
+			
+		property = NULL;
+			
+		// Metering mode
+		object->Property( meteringDef, property);
+		
+		if (property)
+			{
+			property->SetUint16ValueL( 4 );
+			}
+		else
+			{
+			object->AddUint16PropertyL( meteringDef, 4 );
+			}
+			
+		property = NULL;
+		
+		// Thumb X
+		object->Property( thumbXDef, property);
+		
+		if(property)
+			{					
+			property->SetUint32ValueL( 64 );
+			}
+		else
+			{
+			object->AddUint32PropertyL( thumbXDef, 64 );
+			}
+			
+		property = NULL;
+		
+		// Thumb Y
+		object->Property( thumbYDef, property);
+		
+		if(property)
+			{					
+			property->SetUint32ValueL( 64 );
+			}
+		else
+			{
+			object->AddUint32PropertyL( thumbYDef, 64 );
+			}
+			
+		property = NULL;
+			
+		// Thumbnail resolution unit
+		object->Property( thumbResolutionUnitDef, property );
+		
+		if ( property )
+			{
+			property->SetUint16ValueL( 2 );
+			}
+		else
+			{
+			object->AddUint16PropertyL( thumbResolutionUnitDef, 2 );
+			}
+			
+		property = NULL;
+			
+		// Thumbnail compression
+		object->Property( thumbCompressionDef, property );
+		
+		if ( property )
+			{
+			property->SetUint16ValueL( 6 );
+			}
+		else
+			{
+			object->AddUint16PropertyL( thumbCompressionDef, 6 );
+			}
+			
+		property = NULL;
+			
+		// Shutter speed
+		object->Property( shutterSpeedDef, property );
+		
+		if ( property )
+			{					
+			property->SetReal32ValueL( 9.0f );
+			}
+		else
+			{
+			object->AddReal32PropertyL( shutterSpeedDef, 9.0f );
+			}
+			
+		property = NULL;
+			
+		// Components configuration
+		object->Property( componentsDef, property );
+		
+		if ( property )
+			{					
+			property->SetUint32ValueL( 197121 );
+			}
+		else
+			{
+			object->AddUint32PropertyL( componentsDef, 197121 );
+			}
+			
+		property = NULL;
+			
+		// X resolution
+		object->Property( xResolutionDef, property );
+		
+		if ( property )
+			{					
+			property->SetReal32ValueL( 300.0f );
+			}
+		else
+			{
+			object->AddReal32PropertyL( xResolutionDef, 300.0f );
+			}
+			
+		property = NULL;
+			
+		// Y resolution
+		object->Property( yResolutionDef, property );
+		
+		if ( property )
+			{					
+			property->SetReal32ValueL( 300.0f );
+			}
+		else
+			{
+			object->AddReal32PropertyL( yResolutionDef, 300.0f );
+			}
+			
+		property = NULL;
+		
+		// F number
+		object->Property( fNumberDef, property );
+		
+		if ( property )
+			{					
+			property->SetReal32ValueL( 2.8f );
+			}
+		else
+			{
+			object->AddReal32PropertyL( fNumberDef, 2.8f );
+			}
+			
+		property = NULL;
+			
+		// Focal length
+		object->Property( focalLengthDef, property );
+		
+		if ( property )
+			{					
+			property->SetReal32ValueL( 9.0f );
+			}
+		else
+			{
+			object->AddReal32PropertyL( focalLengthDef, 9.0f );
+			}
+			
+		property = NULL;
+		
+		// Focal length in 35 mm film
+		object->Property( focalIn35Def, property );
+		
+		if ( property )
+			{
+			property->SetUint16ValueL( 120 );
+			}
+		else
+			{
+			object->AddUint16PropertyL( focalIn35Def, 120 );
+			}
+						
+		// Commit object
+		TRAPD( commitError, iMdEClient->CommitObjectL(*object) );
+		if ( commitError != KErrNone )
+			{		
+		    msg.Format(KCommErr, commitError);
+		    iLog->Log( msg );
+		    RDebug::Print(msg);
+		    
+		    User::LeaveIfError(commitError);
+			}
+		
+		iLog->Log( KCommit );
+		RDebug::Print(KCommit);
+		
+		CleanupStack::PopAndDestroy( object );
+		}
+	
+	// modify more than one object
+	else if ( count > 1 )
+		{
+		RPointerArray<CMdEObject> objectArray;
+		CleanupClosePushL( objectArray );
+
+		CMdEObject* object = NULL;
+		TItemId objectId(0);
+		TTime currTime;
+	    TBuf <100> uri;
+		
+		for ( TInt i = 0; i < count; ++i )
+			{			
+		    uri.Format(KUri, i+1);
+			
+			// create object
+		    iMdEClient->RemoveObjectL(uri);
+			object = iMdEClient->NewObjectLC(imageDef, uri);
+			
+			currTime.HomeTime();
+			object->AddTimePropertyL(creationDef, currTime);
+			object->AddTimePropertyL(modifiedDef, currTime);
+			object->AddUint32PropertyL( sizeDef, 0 );
+			object->AddTextPropertyL( itemTypeDef, Image::KImageObject );
+			
+			objectId = iMdEClient->AddObjectL(*object);
+			
+			CleanupStack::PopAndDestroy(object);
+			object = NULL;
+			
+			// open for modification
+			TRAPD( openError, object = iMdEClient->OpenObjectL(objectId) )
+			
+			if ( !object || openError != KErrNone )
+				{
+				
+				if (openError != KErrNone)
+					{
+				    msg.Format(KOpenErr, openError);
+				    iLog->Log( msg );
+				    RDebug::Print(msg);
+				    
+				    User::LeaveIfError(openError);
+					}
+				else 
+					{
+				    iLog->Log( KNull );
+				    RDebug::Print(KNull);
+					}
+
+			    continue;
+				}
+
+	   		CMdEProperty* property = NULL;
+	   		
+	   		// Description
+	   		_LIT( KDesc, "Description" );
+			object->Property( descriptionPropertyDef, property );
+			
+			if ( property )
+				{					
+				property->SetTextValueL( KDesc );
+				}
+			else
+				{
+				object->AddTextPropertyL( descriptionPropertyDef, KDesc );
+				}
+			
+			property = NULL;
+			
+			// Width
+			object->Property( widthDef, property );
+			
+			if ( property )
+				{
+				property->SetUint16ValueL( 100 );
+				}
+			else
+				{
+				object->AddUint16PropertyL( widthDef, 100 );
+				}
+			
+			property = NULL;
+				
+			// Height
+			object->Property( heightDef, property );
+			
+			if ( property )
+				{
+				property->SetUint16ValueL( 100 );
+				}
+			else
+				{
+				object->AddUint16PropertyL( heightDef, 100 );
+				}
+			
+			property = NULL;
+			
+			// Maker
+			object->Property( makeDef, property );
+			
+	        _LIT( KOnkia, "Maker" );
+			if ( property )
+				{
+				property->SetTextValueL( KOnkia );
+				}
+			else
+				{
+				object->AddTextPropertyL( makeDef, KOnkia );
+				}
+				
+			property = NULL;
+				
+			// Model
+			object->Property( modelDef, property );
+	        _LIT( KModel, "Model" );
+			if ( property )
+				{					
+				property->SetTextValueL( KModel );
+				}
+			else
+				{
+				object->AddTextPropertyL( modelDef, KModel );
+				}
+
+			objectArray.Append( object );
+			}
+
+		TRAPD( commitError, iMdEClient->CommitObjectsL(objectArray) );
+		if ( commitError != KErrNone )
+			{			
+		    msg.Format(KCommErr, commitError);
+		    iLog->Log( msg );
+		    RDebug::Print(msg);
+		    
+		    User::LeaveIfError(commitError);
+			}
+			
+		iLog->Log( KCommit );
+		RDebug::Print(KCommit);
+		
+		objectArray.ResetAndDestroy();
+		CleanupStack::PopAndDestroy( &objectArray );
+		}
+	
+    _LIT( KMsg2, "Exit ModifyObjects" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::DeleteObject
+// -----------------------------------------------------------------------------
+//
+TInt CComposerPluginTest::DeleteObjectL( CStifItemParser& aItem )
+	{  
+    _LIT( KMsg1, "Enter DeleteObject" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+	
+	TPtrC inputFile;
+	User::LeaveIfError( aItem.GetNextString( inputFile ));
+	
+	iMdEClient->RemoveObjectL(inputFile);
+	
+    _LIT( KMsg2, "Exit DeleteObject" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+	
+    return KErrNone;
+	}
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::DeleteObjects
+// -----------------------------------------------------------------------------
+//
+TInt CComposerPluginTest::DeleteObjectsL( CStifItemParser& aItem )
+	{  
+	TInt count(0);
+    TBuf <100> uri;
+	
+	User::LeaveIfError( aItem.GetNextInt( count ) );
+	
+	for ( TInt i = 0; i < count; ++i )
+		{			
+	    uri.Format(KUri, i+1);
+	    
+	    iMdEClient->RemoveObjectL(uri);
+		}
+	
+    _LIT( KMsg, "Exit    DeleteObjects" );
+    iLog->Log( KMsg );
+    RDebug::Print(KMsg);
+	
+    return KErrNone;
+	}
+
+// -----------------------------------------------------------------------------
+// CComposerPluginTest::WaitComposingComplete
+// -----------------------------------------------------------------------------
+//
+TInt CComposerPluginTest::WaitComposingComplete( CStifItemParser& aItem )
+	{    
+    _LIT( KMsg1, "Enter WaitComposingComplete" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+	TBool complete = ETrue;
+	TBool waitingForComposingToEnd = ETrue;
+	
+	while( waitingForComposingToEnd )
+		{
+		complete = ETrue;
+		
+		for(TInt i = 0; i < iPluginArray.Count(); ++i)
+			{
+			if( iPluginArray[i]->IsComposingComplete() == EFalse )
+				{
+				complete = EFalse;
+				}
+			}
+	
+		if( complete )
+			{
+			waitingForComposingToEnd = EFalse;
+			}
+		else 
+			{
+			ActiveWait( aItem );
+			}
+		}
+	
+    _LIT( KMsg2, "Exit WaitComposingComplete" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+	
+    return KErrNone;
+    }
+
+//  [End of File] - Do not remove
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/Bmarm/HarvesterClientTestScripterU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	LibEntryL__FR13CTestModuleIf @ 1 NONAME R3UNUSED ; LibEntryL(CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/Bwins/HarvesterClientTestScripterU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?LibEntryL@@YAPAVCScriptBase@@AAVCTestModuleIf@@@Z @ 1 NONAME ; class CScriptBase * __cdecl LibEntryL(class CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/EABI/HarvesterClientTestScripterU.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	_Z9LibEntryLR13CTestModuleIf @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/conf/HarvesterClientTestScripter.cfg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,367 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  Harvester Client API tests
+#
+
+// ---------------------------------------------------------------------------
+// Harvester Client API test cases
+// ---------------------------------------------------------------------------
+
+// These should be run in sequential mode if several cases are run at the same
+// time! 
+
+[StifSettings]
+TestThreadStackSize= 32768
+TestThreadMinHeap= 4096
+TestThreadMaxHeap= 16777216
+[EndStifSettings]
+
+[Test]
+title Harvester Client Connect/Disconnect
+timeout 180000
+create HarvesterClientTestScripter test
+request Session
+test SetUp
+wait Session
+test HarvesterClientConnect
+test HarvesterClientClose
+test TearDown
+delete test
+[Endtest]
+
+[Test]
+title Harvester Client Pause/Resume
+timeout 180000
+create HarvesterClientTestScripter test
+request Session
+test SetUp
+wait Session
+test HarvesterClientConnect
+test HarvesterClientPause
+test HarvesterClientResume
+test HarvesterClientPause
+test HarvesterClientResume
+test HarvesterClientClose
+test TearDown
+delete test
+[Endtest]
+
+[Test]
+title Set/Remove Harvester Observer
+timeout 180000
+create HarvesterClientTestScripter test
+request Session
+test SetUp
+wait Session
+test HarvesterClientConnect
+test SetHarvesterObserver
+test RemoveHarvesterObserver
+test SetHarvesterObserver
+test SetHarvesterObserver
+test RemoveHarvesterObserver
+test HarvesterClientClose
+test TearDown
+delete test
+[Endtest]
+
+[Test]
+title Add/Remove Harvester Event Observer
+timeout 180000
+create HarvesterClientTestScripter test
+request Session
+test SetUp
+wait Session
+test HarvesterClientConnect
+test AddHarvesterEventObserver 3
+test AddHarvesterEventObserver 6
+test RemoveHarvesterEventObserver 5
+test HarvesterClientClose
+test TearDown
+delete test
+[Endtest]
+
+[Test]
+title HarvestFile 1
+timeout 180000
+create HarvesterClientTestScripter test
+request Session
+test SetUp
+wait Session
+test HarvesterClientConnect
+test SetHarvesterObserver
+test AddHarvesterEventObserver 1
+test AddObjectObserver
+test SetUpHarvesting e:\testing\data\bmp_burst.bmp
+request Continue
+test HarvestFile e:\testing\data\bmp_burst.bmp
+wait Continue
+test EndHarvesterSession
+request Query
+test QueryImageObjectByIdIndex 0
+wait Query
+test RemoveObject e:\testing\data\bmp_burst.bmp
+test Results
+test RemoveHarvesterEventObserver 1
+test RemoveHarvesterObserver
+test RemoveObjectObserver
+test HarvesterClientClose
+test TearDown
+delete test
+[Endtest]
+
+[Test]
+title HarvestFile 2
+timeout 180000
+create HarvesterClientTestScripter test
+request Session
+test SetUp
+wait Session
+test HarvesterClientConnect
+test SetHarvesterObserver
+test AddHarvesterEventObserver 1
+test AddObjectObserver
+test SetUpHarvesting e:\testing\data\G4.TIF
+request Continue
+test HarvestFile e:\testing\data\G4.TIF
+wait Continue
+test EndHarvesterSession
+request Query
+test QueryImageObjectByIdIndex 0
+wait Query
+test RemoveObject e:\testing\data\G4.TIF
+test Results
+test RemoveHarvesterEventObserver 1
+test RemoveHarvesterObserver
+test RemoveObjectObserver
+test HarvesterClientClose
+test TearDown
+delete test
+[Endtest]
+
+[Test]
+title HarvestFile 3
+timeout 180000
+create HarvesterClientTestScripter test
+request Session
+test SetUp
+wait Session
+test HarvesterClientConnect
+test SetHarvesterObserver
+test AddHarvesterEventObserver 1
+test AddObjectObserver
+test SetUpHarvesting e:\testing\data\GIF87testimage.gif
+request Continue
+test HarvestFile e:\testing\data\GIF87testimage.gif
+wait Continue
+test EndHarvesterSession
+request Query
+test QueryImageObjectByIdIndex 0
+wait Query
+test RemoveObject e:\testing\data\GIF87testimage.gif
+test Results
+test RemoveHarvesterEventObserver 1
+test RemoveHarvesterObserver
+test RemoveObjectObserver
+test HarvesterClientClose
+test TearDown
+delete test
+[Endtest]
+
+[Test]
+title HarvestFile 4
+timeout 200000
+create HarvesterClientTestScripter test
+request Session
+test SetUp
+wait Session
+test HarvesterClientConnect
+test SetHarvesterObserver
+test AddHarvesterEventObserver 1
+test AddObjectObserver
+test SetUpHarvesting e:\testing\data\Liverpool.jpg
+test SetLocationInfo
+request Continue
+test HarvestFile e:\testing\data\Liverpool.jpg
+wait Continue
+test EndHarvesterSession
+request Query
+test QueryImageObjectByIdIndex 0
+wait Query
+test RemoveObject e:\testing\data\Liverpool.jpg
+test Results
+test RemoveHarvesterEventObserver 1
+test RemoveHarvesterObserver
+test RemoveObjectObserver
+test HarvesterClientClose
+test TearDown
+delete test
+[Endtest]
+
+[Test]
+title HarvestFile 5
+timeout 180000
+create HarvesterClientTestScripter test
+request Session
+test SetUp
+wait Session
+test HarvesterClientConnect
+test SetHarvesterObserver
+test AddHarvesterEventObserver 1
+test AddObjectObserver
+test SetUpHarvesting e:\testing\data\MBMtestimage.mbm
+request Continue
+test HarvestFile e:\testing\data\MBMtestimage.mbm
+wait Continue
+test EndHarvesterSession
+request Query
+test QueryImageObjectByIdIndex 0
+wait Query
+test RemoveObject e:\testing\data\MBMtestimage.mbm
+test Results
+test RemoveHarvesterEventObserver 1
+test RemoveHarvesterObserver
+test RemoveObjectObserver
+test HarvesterClientClose
+test TearDown
+delete test
+[Endtest]
+
+[Test]
+title HarvestFile 6
+timeout 180000
+create HarvesterClientTestScripter test
+request Session
+test SetUp
+wait Session
+test HarvesterClientConnect
+test SetHarvesterObserver
+test AddHarvesterEventObserver 1
+test AddObjectObserver
+test SetUpHarvesting e:\testing\data\PNGtestimage.png
+request Continue
+test HarvestFile e:\testing\data\PNGtestimage.png
+wait Continue
+test EndHarvesterSession
+request Query
+test QueryImageObjectByIdIndex 0
+wait Query
+test RemoveObject e:\testing\data\PNGtestimage.png
+test Results
+test RemoveHarvesterEventObserver 1
+test RemoveHarvesterObserver
+test RemoveObjectObserver
+test HarvesterClientClose
+test TearDown
+delete test
+[Endtest]
+
+[Test]
+title HarvestFileWithUID 1
+timeout 180000
+create HarvesterClientTestScripter test
+request Session
+test SetUp
+wait Session
+test HarvesterClientConnect
+test SetHarvesterObserver
+test AddHarvesterEventObserver 1
+test AddObjectObserver
+test SetUpHarvesting e:\testing\data\ota_bmpiso.ota
+test SetLocationInfo
+request Continue
+test HarvestFileWithUID e:\testing\data\ota_bmpiso.ota
+wait Continue
+test EndHarvesterSession
+request Query
+test QueryImageObjectByIdIndex 0
+wait Query
+test RemoveObject e:\testing\data\ota_bmpiso.ota
+test Results
+test RemoveHarvesterEventObserver 1
+test RemoveHarvesterObserver
+test RemoveObjectObserver
+test HarvesterClientClose
+test TearDown
+delete test
+[Endtest]
+
+[Test]
+title HarvestFileWithUID 2
+timeout 180000
+create HarvesterClientTestScripter test
+request Session
+test SetUp
+wait Session
+test HarvesterClientConnect
+test SetHarvesterObserver
+test AddHarvesterEventObserver 1
+test AddObjectObserver
+test SetUpHarvesting e:\testing\data\00001.mp3
+request Continue
+test HarvestFileWithUID e:\testing\data\00001.mp3
+wait Continue
+test EndHarvesterSession
+request Query
+test QueryAudioObjectByIdIndex 0
+wait Query
+test RemoveObject e:\testing\data\00001.mp3
+test Results
+test RemoveHarvesterEventObserver 1
+test RemoveHarvesterObserver
+test RemoveObjectObserver
+test HarvesterClientClose
+test TearDown
+delete test
+[Endtest]
+
+[Test]
+title Harvester Event Basic Test
+timeout 180000
+create HarvesterClientTestScripter test
+request Session
+test SetUp
+wait Session
+test HarvesterClientConnect
+test AddHarvesterEventObserver 1
+test SetUpHarvesting e:\testing\data\bmp_burst.bmp
+test SetUpHarvesting e:\testing\data\G4.TIF
+test SetUpHarvesting e:\testing\data\PNGtestimage.png
+test SetUpHarvesting e:\testing\data\GIF87testimage.gif
+test SetUpHarvesting e:\testing\data\ota_bmpiso.ota
+test SetUpHarvesting e:\testing\data\MBMtestimage.mbm
+test SetUpHarvesting e:\testing\data\Liverpool.jpg
+test SetUpHarvesting e:\testing\data\00001.mp3
+test HarvestFile e:\testing\data\bmp_burst.bmp
+test HarvestFile e:\testing\data\G4.TIF
+test HarvestFile e:\testing\data\PNGtestimage.png
+test HarvestFile e:\testing\data\GIF87testimage.gif
+test HarvestFile e:\testing\data\ota_bmpiso.ota
+test HarvestFile e:\testing\data\MBMtestimage.mbm
+test HarvestFile e:\testing\data\Liverpool.jpg
+test HarvestFileWithUID e:\testing\data\00001.mp3
+test EndHarvesterSession
+test RemoveObject e:\testing\data\bmp_burst.bmp
+test RemoveObject e:\testing\data\G4.TIF
+test RemoveObject e:\testing\data\PNGtestimage.png
+test RemoveObject e:\testing\data\GIF87testimage.gif
+test RemoveObject e:\testing\data\ota_bmpiso.ota
+test RemoveObject e:\testing\data\MBMtestimage.mbm
+test RemoveObject e:\testing\data\Liverpool.jpg
+test RemoveObject e:\testing\data\00001.mp3
+test RemoveHarvesterEventObserver 1
+test HarvesterClientClose
+test TearDown
+delete test
+[Endtest]
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/group/HarvesterClientTestScripter.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET          HarvesterClientTestScripter.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E7
+
+CAPABILITY      ALL -TCB
+VENDORID        VID_DEFAULT
+
+DEFFILE         HarvesterClientTestScripter.DEF
+
+SOURCEPATH      ../src
+SOURCE          HarvesterClientTestScripter.cpp
+SOURCE          HarvesterClientTestScripterBlocks.cpp
+
+USERINCLUDE     ../inc
+USERINCLUDE     ../../../../../inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         harvesterclient.lib
+LIBRARY         mdeclient.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/group/HarvesterClientTestScripter.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,56 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:  Installation file for API test
+;
+
+; Languages
+&EN
+
+; Header
+#{"HarvesterClientTestScripter"},(0x101FB3E3),1,0,0,TYPE=SA
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Install files
+"\epoc32\release\armv5\urel\HarvesterClientTestScripter.dll" - "c:\sys\bin\HarvesterClientTestScripter.dll"
+"..\conf\HarvesterClientTestScripter.cfg" - "c:\TestFramework\HarvesterClientTestScripter.cfg"
+"..\init\HarvesterClientTestScripter.ini" - "c:\TestFramework\HarvesterClientTestScripter.ini"
+
+"..\..\data\mmc\HarvesterTest\Jpg.jpg"      -"E:\testing\data\Jpg.jpg"
+"..\..\data\mmc\HarvesterTest\Animated.gif"      -"E:\testing\data\Animated.gif"
+"..\..\data\mmc\HarvesterTest\Temp1.jpg"      -"E:\testing\data\Temp1.jpg"
+"..\..\data\mmc\HarvesterTest\Temp2.jpg"      -"E:\testing\data\Temp2.jpg"
+"..\..\data\mmc\HarvesterTest\Temp3.jpg"      -"E:\testing\data\Temp3.jpg"
+"..\..\data\mmc\HarvesterTest\H263.3gp"      -"E:\testing\data\H263.3gp"
+"..\..\data\mmc\HarvesterTest\bmp_burst.bmp"      -"E:\testing\data\bmp_burst.bmp"
+"..\..\data\mmc\HarvesterTest\GIF87testimage.gif"      -"E:\testing\data\GIF87testimage.gif"
+"..\..\data\mmc\HarvesterTest\gif89a_onemeg.gif"      -"E:\testing\data\gif89a_onemeg.gif"
+"..\..\data\mmc\HarvesterTest\Liverpool.jpg"      -"E:\testing\data\Liverpool.jpg"
+"..\..\data\mmc\HarvesterTest\MBMtestimage.mbm"      -"E:\testing\data\MBMtestimage.mbm"
+"..\..\data\mmc\HarvesterTest\wbmp_skull.wbmp"      -"E:\testing\data\wbmp_skull.wbmp"
+"..\..\data\mmc\HarvesterTest\ota_bmpiso.ota"      -"E:\testing\data\ota_bmpiso.ota"
+"..\..\data\mmc\HarvesterTest\PNGtestimage.png"      -"E:\testing\data\PNGtestimage.png"
+"..\..\data\mmc\HarvesterTest\G4.TIF"      -"E:\testing\data\G4.TIF"
+"..\..\data\mmc\HarvesterTest\G31D.TIF"      -"E:\testing\data\G31D.TIF"
+"..\..\data\mmc\HarvesterTest\PSRETRO.WMF"      -"E:\testing\data\PSRETRO.WMF"
+"..\..\data\mmc\HarvesterTest\Animated.gif"      -"E:\testing\data\Animated.gif"
+"..\..\data\mmc\HarvesterTest\Mbm.mbm"      -"E:\testing\data\Mbm.mbm"
+"..\..\data\mmc\HarvesterTest\MPEG4.3gp"      -"E:\testing\data\MPEG4.3gp"
+"..\..\data\mmc\HarvesterTest\MPEG4.mp4"      -"E:\testing\data\MPEG4.mp4"
+"..\..\data\mmc\HarvesterTest\00001.mp3"      -"E:\testing\data\00001.mp3"
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+HarvesterClientTestScripter.mmp
+
+PRJ_TESTEXPORTS
+
+../conf/HarvesterClientTestScripter.cfg /epoc32/winscw/c/TestFramework/HarvesterClientTestScripter.cfg
+../init/HarvesterClientTestScripter.ini /epoc32/winscw/c/TestFramework/HarvesterClientTestScripter.ini
+
+../../data/mmc/HarvesterTest/bmp_burst.bmp /epoc32/WINSCW/C/Data/bmp_burst.bmp
+../../data/mmc/HarvesterTest/G31D.TIF /epoc32/WINSCW/C/Data/G31D.TIF
+../../data/mmc/HarvesterTest/G4.TIF /epoc32/WINSCW/C/Data/G4.TIF
+../../data/mmc/HarvesterTest/GIF87testimage.gif /epoc32/WINSCW/C/Data/GIF87testimage.gif
+../../data/mmc/HarvesterTest/gif89a_onemeg.gif /epoc32/WINSCW/C/Data/gif89a_onemeg.gif
+../../data/mmc/HarvesterTest/Liverpool.jpg /epoc32/WINSCW/C/Data/Liverpool.jpg
+../../data/mmc/HarvesterTest/MBMtestimage.mbm /epoc32/WINSCW/C/Data/MBMtestimage.mbm
+../../data/mmc/HarvesterTest/ota_bmpiso.ota /epoc32/WINSCW/C/Data/ota_bmpiso.ota
+../../data/mmc/HarvesterTest/PNGtestimage.png /epoc32/WINSCW/C/Data/PNGtestimage.png
+../../data/mmc/HarvesterTest/PSRETRO.WMF /epoc32/WINSCW/C/Data/PSRETRO.WMF
+../../data/mmc/HarvesterTest/wbmp_skull.wbmp /epoc32/WINSCW/C/Data/wbmp_skull.wbmp
+../../data/mmc/HarvesterTest/Jpg.jpg /epoc32/WINSCW/C/Data/Jpg.jpg
+../../data/mmc/HarvesterTest/Animated.gif /epoc32/WINSCW/C/Data/Animated.gif
+../../data/mmc/HarvesterTest/Mbm.mbm /epoc32/WINSCW/C/Data/Mbm.mbm
+../../data/mmc/HarvesterTest/H263.3gp /epoc32/WINSCW/C/Data/H263.3gp
+../../data/mmc/HarvesterTest/MPEG4.mp4 /epoc32/WINSCW/C/Data/MPEG4.mp4
+../../data/mmc/HarvesterTest/MPEG4.3gp /epoc32/WINSCW/C/Data/MPEG4.3gp
+../../data/mmc/HarvesterTest/Temp1.jpg /epoc32/WINSCW/C/Data/Temp1.jpg
+../../data/mmc/HarvesterTest/Temp2.jpg /epoc32/WINSCW/C/Data/Temp2.jpg
+../../data/mmc/HarvesterTest/Temp3.jpg /epoc32/WINSCW/C/Data/Temp3.jpg
+../../data/mmc/HarvesterTest/00001.mp3 /epoc32/WINSCW/C/Data/00001.mp3
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/inc/HarvesterClientTestScripter.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,169 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef HARVESTERCLIENTTESTSCRIPTER_H
+#define HARVESTERCLIENTTESTSCRIPTER_H
+
+//  INCLUDES
+#include <StifLogger.h>
+#include <TestScripterInternal.h>
+#include <StifTestModule.h>
+#include "harvesterclient.h"
+#include "mdccommon.h"
+#include "mdesession.h"
+#include "mdequery.h"
+
+// CONSTANTS
+
+// MACROS
+// Logging path
+_LIT( KHarvesterClientTestScripterLogPath, "\\logs\\testframework\\HarvesterClientTestScripter\\" ); 
+// Log file
+_LIT( KHarvesterClientTestScripterLogFile, "HarvesterClientTestScripter.txt" ); 
+_LIT( KHarvesterClientTestScripterLogFileWithTitle, "HarvesterClientTestScripter_[%S].txt" );
+
+// FORWARD DECLARATIONS
+class CMdEHarvesterSession;
+class CHarvesterClientTestScripter;
+
+// CLASS DECLARATION
+
+/**
+*  CHarvesterClientTestScripter test class for STIF Test Framework TestScripter.
+*  ?other_description_lines
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+NONSHARABLE_CLASS(CHarvesterClientTestScripter) : public CScriptBase,
+                                                  public MMdESessionObserver,
+                                                  public MHarvestObserver,
+                                                  public MMdEQueryObserver,
+                                                  public MMdEObjectObserver,
+                                                  public MHarvesterEventObserver
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CHarvesterClientTestScripter* NewL( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CHarvesterClientTestScripter();
+
+    public: // Functions from base classes
+
+        /**
+        * From CScriptBase Runs a script line.
+        * @since ?Series60_version
+        * @param aItem Script line containing method name and parameters
+        * @return Symbian OS error code
+        */
+        virtual TInt RunMethodL( CStifItemParser& aItem );
+
+    private:  // Functions from base classes
+		void HandleSessionOpened(CMdESession& aSession, TInt aError);
+		void HandleSessionError(CMdESession& aSession, TInt aError);
+		void HandleObjectNotification(CMdESession& aSession, 
+	                                  TObserverNotificationType aType,
+	                                  const RArray<TItemId>& aObjectIdArray);
+	    void HandleQueryNewResults(CMdEQuery& aQuery,
+	                               TInt aFirstNewItemIndex,
+	                               TInt aNewItemCount);
+	    void HandleQueryCompleted(CMdEQuery& aQuery, TInt aError);
+		
+        void HarvestingComplete( TDesC& aURI, TInt aError );
+        void HarvestingUpdated( HarvesterEventObserverType aHEObserverType, 
+        				HarvesterEventState aHarvesterEventState,
+        				TInt aItemsLeft );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CHarvesterClientTestScripter( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Frees all resources allocated from test methods.
+        * @since ?Series60_version
+        */
+        void Delete();
+
+		void CheckComplete();
+        /**
+        * Test helper methods are listed below. 
+        */
+        virtual TInt AddObjectObserverL( CStifItemParser& aItem );
+        virtual TInt RemoveObjectObserverL( CStifItemParser& aItem );
+        virtual TInt BeginHarvesterSessionL( CStifItemParser& aItem );
+        virtual TInt EndHarvesterSessionL( CStifItemParser& aItem );
+
+        /**
+        * Test methods are listed below. 
+        */
+		virtual TInt SetUp( CStifItemParser& aItem );
+		virtual TInt TearDown( CStifItemParser& aItem );
+		virtual TInt HarvesterClientConnectL( CStifItemParser& aItem );
+		virtual TInt HarvesterClientCloseL( CStifItemParser& aItem );
+		virtual TInt HarvesterClientPauseL( CStifItemParser& aItem );
+		virtual TInt HarvesterClientResumeL( CStifItemParser& aItem );
+		virtual TInt SetHarvesterObserverL( CStifItemParser& aItem );
+		virtual TInt RemoveHarvesterObserverL( CStifItemParser& aItem );
+		virtual TInt SetLocationInfoL( CStifItemParser& aItem );
+        virtual TInt HarvestFileL( CStifItemParser& aItem );
+        virtual TInt HarvestFileWithUIDL( CStifItemParser& aItem );
+        virtual TInt QueryImageObjectByIdIndexL( CStifItemParser& aItem );
+        virtual TInt QueryAudioObjectByIdIndexL( CStifItemParser& aItem );
+        virtual TInt RemoveObjectL( CStifItemParser& aItem );
+        virtual TInt Results( CStifItemParser& aItem );
+        virtual TInt AddHarvesterEventObserverL( CStifItemParser& aItem );
+        virtual TInt RemoveHarvesterEventObserverL( CStifItemParser& aItem );
+        
+    private:    // Data
+        // Status booleans
+		TBool iHarvestingComplete;
+		TBool iPlaceholderComplete;
+		TBool iNewObjectComplete;
+		TBool iQuerySuccess;
+		TBool iObjectNotification;
+        TBool iSetLocation;
+
+        // Test helper classes
+		CMdESession* iMdeSession;
+		CMdEHarvesterSession* iHarvesterSession;
+		CMdEQuery* iQuery;
+
+        RHarvesterClient iHc;
+        RArray<TItemId> iAlbumIds;
+        RArray<TItemId> iObjectIdArray;
+        
+        TFileName iUri;
+    };
+
+#endif      // HARVESTERCLIENTTESTSCRIPTER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/init/HarvesterClientTestScripter.ini	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,81 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  
+#
+
+
+[Engine_Defaults]
+
+TestReportMode= FullReport    # Possible values are: 'Empty', 'Summary', 'Environment',
+                                                     'TestCases' or 'FullReport'
+
+CreateTestReport= YES         # Possible values: YES or NO
+
+TestReportFilePath= C:\LOGS\TestFramework\
+TestReportFileName= HarvesterClientTestScripterLog
+
+TestReportFormat= TXT         # Possible values: TXT or HTML
+TestReportOutput= FILE        # Possible values: FILE or RDEBUG
+TestReportFileCreationMode= OVERWRITE # Possible values: OVERWRITE or APPEND
+
+DeviceResetDllName= StifResetForNokia.dll # e.g. 'StifHWResetStub.dll' for user specific reseting
+
+DisableMeasurement= stifmeasurementdisablenone  # Possible values are:
+              # 'stifmeasurementdisablenone', 'stifmeasurementdisableall'
+              # 'stifmeasurementplugin01', 'stifmeasurementplugin02',
+              # 'stifmeasurementplugin03', 'stifmeasurementplugin04',
+              # 'stifmeasurementplugin05' or 'stifbappeaprofiler'
+
+Timeout= 600000		            # Default timeout value for each test case. In milliseconds
+#UITestingSupport= YES        # Possible values: YES or NO
+#SeparateProcesses= YES       # Possible values: YES or NO (default: NO)
+[End_Defaults]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[New_Module]
+ModuleName= TestScripter
+TestCaseFile= c:\testframework\HarvesterClientTestScripter.cfg
+[End_Module]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[Logger_Defaults]
+
+#NOTE: If you want to set Logger using next setting(s) remove comment(s)'#'
+#NOTE: TestEngine and TestServer logging settings cannot change here
+
+CreateLogDirectories= YES    # Possible values: YES or NO
+
+#EmulatorBasePath= C:\LOGS\TestFramework\
+#EmulatorFormat= HTML         # Possible values: TXT or HTML
+#EmulatorOutput= FILE         # Possible values: FILE or RDEBUG
+
+HardwareBasePath= C:\
+#HardwareFormat= HTML         # Possible values: TXT or HTML
+#HardwareOutput= FILE         # Possible values: FILE or RDEBUG
+
+#FileCreationMode= OVERWRITE  # Possible values: OVERWRITE or APPEND
+
+#ThreadIdToLogFile= YES       # Possible values: YES or NO
+#WithTimeStamp= YES           # Possible values: YES or NO
+#WithLineBreak= YES           # Possible values: YES or NO
+#WithEventRanking= YES        # Possible values: YES or NO
+
+#FileUnicode= YES             # Possible values: YES or NO
+AddTestCaseTitle= YES        # Possible values: YES or NO
+[End_Logger_Defaults]
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+# End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/src/HarvesterClientTestScripter.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,116 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+// INCLUDE FILES
+#include <StifTestInterface.h>
+#include "HarvesterClientTestScripter.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTestScripter::CHarvesterClientTestScripter
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CHarvesterClientTestScripter::CHarvesterClientTestScripter( 
+    CTestModuleIf& aTestModuleIf ):
+        CScriptBase( aTestModuleIf )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTestScripter::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CHarvesterClientTestScripter::ConstructL()
+    {
+    iLog = CStifLogger::NewL( KHarvesterClientTestScripterLogPath, 
+                          KHarvesterClientTestScripterLogFile,
+                          CStifLogger::ETxt,
+                          CStifLogger::EFile,
+                          EFalse );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTestScripter::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CHarvesterClientTestScripter* CHarvesterClientTestScripter::NewL( 
+    CTestModuleIf& aTestModuleIf )
+    {
+    CHarvesterClientTestScripter* self = new (ELeave) CHarvesterClientTestScripter( aTestModuleIf );
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+
+    }
+
+// Destructor
+CHarvesterClientTestScripter::~CHarvesterClientTestScripter()
+    { 
+
+    // Delete resources allocated from test methods
+    Delete();
+
+    // Delete logger
+    delete iLog; 
+
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point.
+// Returns: CScriptBase: New CScriptBase derived object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScriptBase* LibEntryL( 
+    CTestModuleIf& aTestModuleIf ) // Backpointer to STIF Test Framework
+    {
+
+    return ( CScriptBase* ) CHarvesterClientTestScripter::NewL( aTestModuleIf );
+
+    }
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterClientTest/src/HarvesterClientTestScripterBlocks.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,669 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+// INCLUDE FILES
+#include <e32svr.h>
+#include <StifParser.h>
+#include <StifTestEventInterface.h>
+#include <StifTestInterface.h>
+#include "HarvesterClientTestScripter.h"
+#include "mdcserializationbuffer.h"
+#include "mdeharvestersession.h"
+#include "mdsutils.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTestScripter::Delete
+// Delete here all resources allocated and opened from test methods. 
+// Called from destructor. 
+// -----------------------------------------------------------------------------
+//
+void CHarvesterClientTestScripter::Delete() 
+    {
+    
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTestScripter::RunMethodL
+// Run specified method. Contains also table of test mothods and their names.
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::RunMethodL( 
+    CStifItemParser& aItem ) 
+    {
+    static TStifFunctionInfo const KFunctions[] =
+        {  
+        // Copy this line for every implemented function.
+        // First string is the function name used in TestScripter script file.
+        // Second is the actual implementation member function. 
+
+		ENTRY( "SetUp", CHarvesterClientTestScripter::SetUp ),
+		ENTRY( "TearDown", CHarvesterClientTestScripter::TearDown ),
+
+        // Test helper methods
+        ENTRY( "AddObjectObserver", CHarvesterClientTestScripter::AddObjectObserverL ),
+        ENTRY( "RemoveObjectObserver", CHarvesterClientTestScripter::RemoveObjectObserverL ),
+        ENTRY( "SetUpHarvesting", CHarvesterClientTestScripter::BeginHarvesterSessionL ),
+        ENTRY( "EndHarvesterSession", CHarvesterClientTestScripter::EndHarvesterSessionL ),
+
+        // Harvester tests
+        ENTRY( "HarvesterClientConnect", CHarvesterClientTestScripter::HarvesterClientConnectL ),
+        ENTRY( "HarvesterClientClose", CHarvesterClientTestScripter::HarvesterClientCloseL ),
+        ENTRY( "HarvesterClientPause", CHarvesterClientTestScripter::HarvesterClientPauseL ),
+        ENTRY( "HarvesterClientResume", CHarvesterClientTestScripter::HarvesterClientResumeL ),
+        ENTRY( "SetHarvesterObserver", CHarvesterClientTestScripter::SetHarvesterObserverL ),
+        ENTRY( "RemoveHarvesterObserver", CHarvesterClientTestScripter::RemoveHarvesterObserverL ),
+        ENTRY( "SetLocationInfo", CHarvesterClientTestScripter::SetLocationInfoL ),
+        ENTRY( "HarvestFile", CHarvesterClientTestScripter::HarvestFileL ),
+        ENTRY( "HarvestFileWithUID", CHarvesterClientTestScripter::HarvestFileWithUIDL ),
+        ENTRY( "QueryImageObjectByIdIndex", CHarvesterClientTestScripter::QueryImageObjectByIdIndexL ),
+        ENTRY( "QueryAudioObjectByIdIndex", CHarvesterClientTestScripter::QueryAudioObjectByIdIndexL ),
+        ENTRY( "RemoveObject", CHarvesterClientTestScripter::RemoveObjectL ),
+        ENTRY( "Results", CHarvesterClientTestScripter::Results ),     
+        ENTRY( "AddHarvesterEventObserver", CHarvesterClientTestScripter::AddHarvesterEventObserverL ),
+        ENTRY( "RemoveHarvesterEventObserver", CHarvesterClientTestScripter::RemoveHarvesterEventObserverL ),
+        };
+
+    const TInt count = sizeof( KFunctions ) / sizeof( TStifFunctionInfo );
+
+    return RunInternalL( KFunctions, count, aItem );
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::SetUp
+// Set up test.
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::SetUp( CStifItemParser& /* aItem */ )
+	{
+    _LIT( KMsg1, "SetUp" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+	
+	iHarvestingComplete = EFalse;
+	iPlaceholderComplete = EFalse;
+	iNewObjectComplete = EFalse;
+	iObjectNotification = EFalse;
+	iSetLocation = EFalse;
+	iObjectIdArray.Reset();
+	TRAP_IGNORE( iMdeSession = CMdESession::NewL( *this ) );
+
+    return KErrNone;
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::TearDown
+// Tear down test.
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::TearDown( CStifItemParser& /* aItem */ )
+	{
+    _LIT( KMsg1, "TearDown" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+	
+	delete iHarvesterSession;
+	iHarvesterSession = NULL;
+	delete iMdeSession;
+	iMdeSession = NULL;
+
+    return KErrNone;
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HarvesterClientConnectL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::HarvesterClientConnectL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "HarvesterClientConnectL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    User::LeaveIfError( iHc.Connect() );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HarvesterClientCloseL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::HarvesterClientCloseL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "HarvesterClientCloseL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    iHc.Close();
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HarvesterClientPauseL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::HarvesterClientPauseL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "Enter HarvesterClientPauseL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    User::LeaveIfError( iHc.Pause() );
+
+    _LIT( KMsg2, "Exit HarvesterClientPauseL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HarvesterClientResumeL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::HarvesterClientResumeL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "Enter HarvesterClientResumeL" );
+     iLog->Log( KMsg1 );  
+     RDebug::Print( KMsg1 );
+    
+    User::LeaveIfError( iHc.Resume() );
+
+    _LIT( KMsg2, "Exit HarvesterClientResumeL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::SetHarvesterObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::SetHarvesterObserverL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "SetHarvesterObserverL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    iHc.SetObserver( this );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::RemoveHarvesterObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::RemoveHarvesterObserverL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "RemoveHarvesterObserverL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    iHc.RemoveObserver( this );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::AddObjectObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::AddObjectObserverL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "AddObjectObserverL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    iMdeSession->AddObjectObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::AddObjectObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::RemoveObjectObserverL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "RemoveObjectObserverL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TRAP_IGNORE( iMdeSession->RemoveObjectObserverL( *this ) );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::AddObjectObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::SetLocationInfoL( CStifItemParser& /* aItem */ )
+    {
+    iSetLocation = ETrue;
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::StartHarvesterSessionL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::BeginHarvesterSessionL( CStifItemParser& aItem )
+    {
+    _LIT( KMsg1, "Enter BeginHarvesterSessionL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TPtrC inputFile;
+    User::LeaveIfError( aItem.GetNextString( inputFile ));
+    
+    TRAP_IGNORE( iMdeSession->RemoveObjectL(inputFile) );
+    
+    _LIT( KMsg2, "Exit BeginHarvesterSessionL" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HarvestFileTestL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::HarvestFileL( CStifItemParser& aItem )
+    {
+    _LIT( KMsg1, "Enter HarvestFileL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+  
+	TPtrC inputFile;
+	User::LeaveIfError( aItem.GetNextString( inputFile ));
+    iAlbumIds.Append( 1 );
+    iQuerySuccess = EFalse;
+    
+    iUri = inputFile;
+    iHc.HarvestFile( inputFile, iAlbumIds, iSetLocation );
+
+    _LIT( KMsg2, "Exit HarvestFileL" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HarvestFileTestL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::HarvestFileWithUIDL( CStifItemParser& aItem )
+    {
+    _LIT( KMsg1, "Enter HarvestFileWithUIDL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TUid uid( KNullUid );
+    
+    TPtrC inputFile;
+    User::LeaveIfError( aItem.GetNextString( inputFile ));
+    iAlbumIds.Append( 1 );
+    iQuerySuccess = EFalse;
+    
+    iUri = inputFile;
+    iHc.HarvestFileWithUID( inputFile, iAlbumIds, EFalse, uid );
+
+    _LIT( KMsg2, "Exit HarvestFileWithUIDL" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HarvestingCompleteL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::EndHarvesterSessionL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "EndHarvesterSessionL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    iAlbumIds.Close();
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::QueryObjectByIdIndexL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::QueryImageObjectByIdIndexL( CStifItemParser& aItem )
+    {
+    _LIT( KMsg1, "QueryImageObjectByIdIndexL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TInt index;
+    User::LeaveIfError( aItem.GetNextInt( index ));
+
+    CMdENamespaceDef& defNS = iMdeSession->GetDefaultNamespaceDefL();
+    CMdEObjectDef& objDef = defNS.GetObjectDefL( MdeConstants::Image::KImageObject );
+    iQuery = iMdeSession->NewObjectQueryL( defNS, objDef, this );
+            
+    iQuery->SetResultMode( EQueryResultModeItem );
+            
+    iQuery->FindL();
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::QueryObjectByIdIndexL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::QueryAudioObjectByIdIndexL( CStifItemParser& aItem )
+    {
+    _LIT( KMsg1, "QueryAudioObjectByIdIndexL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TInt index;
+    User::LeaveIfError( aItem.GetNextInt( index ));
+
+    CMdENamespaceDef& defNS = iMdeSession->GetDefaultNamespaceDefL();
+    CMdEObjectDef& objDef = defNS.GetObjectDefL( MdeConstants::Audio::KAudioObject );
+    iQuery = iMdeSession->NewObjectQueryL( defNS, objDef, this );
+            
+    iQuery->SetResultMode( EQueryResultModeItem );
+            
+    iQuery->FindL();
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::RemoveObjectL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::RemoveObjectL( CStifItemParser& aItem )
+    {
+    _LIT( KMsg1, "RemoveObjectL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TPtrC inputFile;
+    User::LeaveIfError( aItem.GetNextString( inputFile ));
+
+    TRAP_IGNORE( iMdeSession->RemoveObjectL( inputFile ) );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::Results
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::Results( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "Enter Results" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    if( !iQuerySuccess )
+        {
+        return KErrNotFound;
+        }
+    
+    if( !iHarvestingComplete )
+        {
+        return KErrUnknown;
+        }
+    
+    _LIT( KMsg2, "Enter Results" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::AddHarvesterEventObserver
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::AddHarvesterEventObserverL( CStifItemParser& aItem )
+    {
+    _LIT( KMsg1, "AddHarvesterEventObserverL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TInt testCount( 0 );
+    User::LeaveIfError( aItem.GetNextInt( testCount ) );
+    for( TInt i = 0; i < testCount; i++ )
+    	{
+    	TInt err = iHc.AddHarvesterEventObserver( *this, EHEObserverTypePlaceholder, 3 );
+	    TL( err == KErrNone );
+    	}
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::RemoveHarvesterEventObserver
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterClientTestScripter::RemoveHarvesterEventObserverL( CStifItemParser& aItem )
+    {
+    _LIT( KMsg1, "RemoveHarvesterEventObserverL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TInt testCount( 0 );
+    User::LeaveIfError( aItem.GetNextInt( testCount ) );
+    
+    for( TInt i = 0; i < testCount; i++ )
+		{
+		TInt err = iHc.RemoveHarvesterEventObserver( *this );
+	    TL( err == KErrNone );
+		}
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HarvestingUpdated
+// -----------------------------------------------------------------------------
+//
+void CHarvesterClientTestScripter::HarvestingUpdated( 
+	HarvesterEventObserverType /*aHEObserverType*/, 
+	HarvesterEventState /*aHarvesterEventState*/,
+	TInt /*aItemsLeft*/ )
+	{
+    _LIT( KMsg1, "CallBck HarvestingUpdated" );
+    iLog->Log( KMsg1 );     
+    RDebug::Print( KMsg1 );
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HarvestingComplete
+// -----------------------------------------------------------------------------
+//
+void CHarvesterClientTestScripter::HarvestingComplete( TDesC& aURI, TInt aError )
+	{
+    _LIT( KMsg, "CallBck HarvestingComplete - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );     
+    RDebug::Print( msg );
+    
+    if( MdsUtils::Compare( aURI, iUri ) == 0 )
+        {
+        if( iObjectNotification )
+            {
+            iHarvestingComplete = ETrue;
+            // session event
+            TEventIf event( TEventIf::ESetEvent, _L("Continue") );
+            TestModuleIf().Event( event );
+            }
+        else
+            {
+            iHarvestingComplete = ETrue;
+            }
+        }
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HandleSessionOpened
+// -----------------------------------------------------------------------------
+//
+void CHarvesterClientTestScripter::HandleSessionOpened( CMdESession& /* aSession */, TInt aError )
+	{
+    _LIT( KMsg, "CallBck HandleSessionOpened - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );     
+    RDebug::Print( msg );
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HandleSessionError
+// -----------------------------------------------------------------------------
+//
+void CHarvesterClientTestScripter::HandleSessionError( CMdESession& /* aSession */, TInt aError )
+    {
+    _LIT( KMsg, "CallBck HandleSessionError - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );
+    RDebug::Print( msg );
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HandleObjectNotification
+// -----------------------------------------------------------------------------
+//
+void CHarvesterClientTestScripter::HandleObjectNotification(
+		CMdESession& /* aSession */, 
+		TObserverNotificationType aType,
+		const RArray<TItemId>& aObjectIdArray )
+	{
+    _LIT( KMsg1, "CallBck HandleObjectNotification" );
+    iLog->Log( KMsg1 );     
+    RDebug::Print( KMsg1 );
+
+	switch( aType )
+		{
+		case ENotifyAdd:
+			{
+			iPlaceholderComplete = ETrue;
+			break;
+			}
+		case ENotifyModify:
+			{
+			iNewObjectComplete = ETrue;
+			break;
+			}
+		case ENotifyRemove:
+			{
+			break;
+			}		
+		}
+	
+	CMdEObject* temp = NULL;
+	TRAP_IGNORE( temp = iMdeSession->GetObjectL( iUri ) );
+	if( temp && iHarvestingComplete )
+	    {
+	    for ( TInt i = 0; i < aObjectIdArray.Count(); ++i )
+	        {
+	        iObjectIdArray.Append( aObjectIdArray[i] );
+	        }
+	    // session event
+	    TEventIf event( TEventIf::ESetEvent, _L("Continue") );
+	    TestModuleIf().Event( event );
+	    iObjectNotification = ETrue;
+	    }
+	else if( temp )
+	    {
+	    for ( TInt i = 0; i < aObjectIdArray.Count(); ++i )
+	        {
+	        iObjectIdArray.Append( aObjectIdArray[i] );
+	        }
+	    iObjectNotification = ETrue;
+	    }
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HandleQueryNewResults
+// -----------------------------------------------------------------------------
+//
+void CHarvesterClientTestScripter::HandleQueryNewResults( CMdEQuery& /* aQuery */,
+        TInt /* aFirstNewItemIndex */,
+        TInt /* aNewItemCount */ )
+	{
+    _LIT( KMsg1, "CallBck HandleQueryNewResults" );
+    iLog->Log( KMsg1 );     
+    RDebug::Print( KMsg1 );
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterClientTest::HandleQueryCompleted
+// -----------------------------------------------------------------------------
+//
+void CHarvesterClientTestScripter::HandleQueryCompleted( CMdEQuery& aQuery, TInt aError)
+	{
+    _LIT( KMsg, "CallBck HandleQueryCompleted - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );     
+    RDebug::Print( msg );
+	
+	if( iQuery && iQuery == &aQuery )
+		{
+		for( TInt i = 0; i < aQuery.Count(); i++ )
+		    {
+		    TInt id = aQuery.ResultItem( i ).Id();
+		    CMdEObject* temp = NULL;
+		    TRAP_IGNORE( temp = iMdeSession->GetFullObjectL( id ) );
+		    if( MdsUtils::Compare( temp->Uri(), iUri ) == 0 )
+		        {
+		        iQuerySuccess = ETrue;
+		        break;
+		        }
+		    }
+		}
+	
+	if( iQuerySuccess )
+	    {
+        // session event
+        TEventIf event( TEventIf::ESetEvent, _L("Query") );
+        TestModuleIf().Event( event );
+	    }
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/Bmarm/HarvesterDataTestU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	LibEntryL__FR13CTestModuleIf @ 1 NONAME R3UNUSED ; LibEntryL(CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/Bwins/HarvesterDataTestU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?LibEntryL@@YAPAVCScriptBase@@AAVCTestModuleIf@@@Z @ 1 NONAME ; class CScriptBase * __cdecl LibEntryL(class CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/EABI/HarvesterDataTestU.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	_Z9LibEntryLR13CTestModuleIf @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/conf/HarvesterDataTest.cfg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,61 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  Harvester Data API tests
+#
+
+// ---------------------------------------------------------------------------
+// Harvester Data API test cases
+// ---------------------------------------------------------------------------
+
+// These should be run in sequential mode if several cases are run at the same
+// time! 
+
+[StifSettings]
+TestThreadStackSize= 32768
+TestThreadMinHeap= 4096
+TestThreadMaxHeap= 16777216
+[EndStifSettings]
+
+[Test]
+title Harvest Client Data Tests
+create HarvesterDataTest test
+request Session
+test BeginTestSession
+wait Session
+test HarvestClientDataTests
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Placeholder Data Tests
+create HarvesterDataTest test
+request Session
+test BeginTestSession
+wait Session
+test PlaceholderDataTests
+test EndTestSession
+delete test
+[Endtest]
+
+[Test]
+title Harvester Data Tests
+create HarvesterDataTest test
+request Session
+test BeginTestSession
+wait Session
+test HarvesterDataTests
+test EndTestSession
+delete test
+[Endtest]
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/group/HarvesterDataTest.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET          HarvesterDataTest.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E3
+
+CAPABILITY      ALL -TCB
+VENDORID        VID_DEFAULT
+
+DEFFILE         HarvesterDataTest.DEF
+
+SOURCEPATH      ../src
+SOURCE          HarvesterDataTest.cpp
+SOURCE          HarvesterDataTestBlocks.cpp
+
+USERINCLUDE     ../inc 
+USERINCLUDE     ../../../../../inc 
+USERINCLUDE     ../../../../../locationmanager/locationtrail/inc
+SYSTEMINCLUDE 	/epoc32/include/ecom
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+LIBRARY	        ecom.lib
+LIBRARY	        harvesterdata.lib
+LIBRARY         mdeclient.lib
+LIBRARY         etel3rdparty.lib
+LIBRARY 	      Lbs.lib
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/group/HarvesterDataTest.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,56 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:  Installation file for API test
+;
+
+; Languages
+&EN
+
+; Header
+#{"HarvesterDataTest"},(0x101FB3E3),1,0,0,TYPE=SA
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Install files
+"\epoc32\release\armv5\urel\HarvesterDataTest.dll" - "c:\sys\bin\HarvesterDataTest.dll"
+"..\conf\HarvesterDataTest.cfg" - "c:\TestFramework\HarvesterDataTest.cfg"
+"..\init\HarvesterDataTest.ini" - "c:\TestFramework\HarvesterDataTest.ini"
+
+"..\..\data\mmc\HarvesterTest\Jpg.jpg"      -"E:\testing\data\Jpg.jpg"
+"..\..\data\mmc\HarvesterTest\Animated.gif"      -"E:\testing\data\Animated.gif"
+"..\..\data\mmc\HarvesterTest\Temp1.jpg"      -"E:\testing\data\Temp1.jpg"
+"..\..\data\mmc\HarvesterTest\Temp2.jpg"      -"E:\testing\data\Temp2.jpg"
+"..\..\data\mmc\HarvesterTest\Temp3.jpg"      -"E:\testing\data\Temp3.jpg"
+"..\..\data\mmc\HarvesterTest\H263.3gp"      -"E:\testing\data\H263.3gp"
+"..\..\data\mmc\HarvesterTest\bmp_burst.bmp"      -"E:\testing\data\bmp_burst.bmp"
+"..\..\data\mmc\HarvesterTest\GIF87testimage.gif"      -"E:\testing\data\GIF87testimage.gif"
+"..\..\data\mmc\HarvesterTest\gif89a_onemeg.gif"      -"E:\testing\data\gif89a_onemeg.gif"
+"..\..\data\mmc\HarvesterTest\Liverpool.jpg"      -"E:\testing\data\Liverpool.jpg"
+"..\..\data\mmc\HarvesterTest\MBMtestimage.mbm"      -"E:\testing\data\MBMtestimage.mbm"
+"..\..\data\mmc\HarvesterTest\wbmp_skull.wbmp"      -"E:\testing\data\wbmp_skull.wbmp"
+"..\..\data\mmc\HarvesterTest\ota_bmpiso.ota"      -"E:\testing\data\ota_bmpiso.ota"
+"..\..\data\mmc\HarvesterTest\PNGtestimage.png"      -"E:\testing\data\PNGtestimage.png"
+"..\..\data\mmc\HarvesterTest\G4.TIF"      -"E:\testing\data\G4.TIF"
+"..\..\data\mmc\HarvesterTest\G31D.TIF"      -"E:\testing\data\G31D.TIF"
+"..\..\data\mmc\HarvesterTest\PSRETRO.WMF"      -"E:\testing\data\PSRETRO.WMF"
+"..\..\data\mmc\HarvesterTest\Animated.gif"      -"E:\testing\data\Animated.gif"
+"..\..\data\mmc\HarvesterTest\Mbm.mbm"      -"E:\testing\data\Mbm.mbm"
+"..\..\data\mmc\HarvesterTest\MPEG4.3gp"      -"E:\testing\data\MPEG4.3gp"
+"..\..\data\mmc\HarvesterTest\MPEG4.mp4"      -"E:\testing\data\MPEG4.mp4"
+"..\..\data\mmc\HarvesterTest\00001.mp3"      -"E:\testing\data\00001.mp3"
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+HarvesterDataTest.mmp
+
+PRJ_TESTEXPORTS
+
+../conf/HarvesterDataTest.cfg /epoc32/winscw/c/TestFramework/HarvesterDataTest.cfg
+../init/HarvesterDataTest.ini /epoc32/winscw/c/TestFramework/HarvesterDataTest.ini
+
+../../data/mmc/HarvesterTest/bmp_burst.bmp /epoc32/WINSCW/C/Data/bmp_burst.bmp
+../../data/mmc/HarvesterTest/G31D.TIF /epoc32/WINSCW/C/Data/G31D.TIF
+../../data/mmc/HarvesterTest/G4.TIF /epoc32/WINSCW/C/Data/G4.TIF
+../../data/mmc/HarvesterTest/GIF87testimage.gif /epoc32/WINSCW/C/Data/GIF87testimage.gif
+../../data/mmc/HarvesterTest/gif89a_onemeg.gif /epoc32/WINSCW/C/Data/gif89a_onemeg.gif
+../../data/mmc/HarvesterTest/Liverpool.jpg /epoc32/WINSCW/C/Data/Liverpool.jpg
+../../data/mmc/HarvesterTest/MBMtestimage.mbm /epoc32/WINSCW/C/Data/MBMtestimage.mbm
+../../data/mmc/HarvesterTest/ota_bmpiso.ota /epoc32/WINSCW/C/Data/ota_bmpiso.ota
+../../data/mmc/HarvesterTest/PNGtestimage.png /epoc32/WINSCW/C/Data/PNGtestimage.png
+../../data/mmc/HarvesterTest/PSRETRO.WMF /epoc32/WINSCW/C/Data/PSRETRO.WMF
+../../data/mmc/HarvesterTest/wbmp_skull.wbmp /epoc32/WINSCW/C/Data/wbmp_skull.wbmp
+../../data/mmc/HarvesterTest/Jpg.jpg /epoc32/WINSCW/C/Data/Jpg.jpg
+../../data/mmc/HarvesterTest/Animated.gif /epoc32/WINSCW/C/Data/Animated.gif
+../../data/mmc/HarvesterTest/Mbm.mbm /epoc32/WINSCW/C/Data/Mbm.mbm
+../../data/mmc/HarvesterTest/H263.3gp /epoc32/WINSCW/C/Data/H263.3gp
+../../data/mmc/HarvesterTest/MPEG4.mp4 /epoc32/WINSCW/C/Data/MPEG4.mp4
+../../data/mmc/HarvesterTest/MPEG4.3gp /epoc32/WINSCW/C/Data/MPEG4.3gp
+../../data/mmc/HarvesterTest/Temp1.jpg /epoc32/WINSCW/C/Data/Temp1.jpg
+../../data/mmc/HarvesterTest/Temp2.jpg /epoc32/WINSCW/C/Data/Temp2.jpg
+../../data/mmc/HarvesterTest/Temp3.jpg /epoc32/WINSCW/C/Data/Temp3.jpg
+../../data/mmc/HarvesterTest/00001.mp3 /epoc32/WINSCW/C/Data/00001.mp3
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/inc/HarvesterDataTest.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,117 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef HARVESTERDATATEST_H
+#define HARVESTERDATATEST_H
+
+//  INCLUDES
+#include <StifLogger.h>
+#include <TestScripterInternal.h>
+#include <StifTestModule.h>
+
+#include <harvesterdata.h>
+#include <mdesession.h>
+#include <mdccommon.h>
+
+// Logging path
+_LIT( KHarvesterDataTestLogPath, "\\logs\\testframework\\HarvesterDataTest\\" ); 
+// Log file
+_LIT( KHarvesterDataTestLogFile, "HarvesterDataTest.txt" ); 
+_LIT( KHarvesterDataTestLogFileWithTitle, "HarvesterDataTest_[%S].txt" );
+
+// FORWARD DECLARATIONS
+class CHarvesterDataTest;
+
+// CLASS DECLARATION
+NONSHARABLE_CLASS(CHarvesterDataTest) : public CScriptBase,
+										public MMdESessionObserver,
+										public MHarvesterPluginObserver,
+										public MMonitorPluginObserver
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CHarvesterDataTest* NewL( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CHarvesterDataTest();
+
+    public: // Functions from base classes
+
+        /**
+        * From CScriptBase Runs a script line.
+        * @since ?Series60_version
+        * @param aItem Script line containing method name and parameters
+        * @return Symbian OS error code
+        */
+        virtual TInt RunMethodL( CStifItemParser& aItem );
+
+    private: // Functions from base classes
+    	
+    	void HandleSessionOpened(CMdESession& aSession, TInt aError);
+    	void HandleSessionError(CMdESession& aSession, TInt aError);
+    	void HarvestingCompleted( CHarvesterData* aHarvesterData );
+    	void MonitorEvent( CHarvesterData* aHarvesterData );
+    	void MonitorEvent( RPointerArray<CHarvesterData>& aHarvesterDataArray );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CHarvesterDataTest( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Frees all resources allocated from test methods.
+        * @since ?Series60_version
+        */
+        void Delete();
+
+        /**
+        * Test methods are listed below. 
+        */
+
+        virtual TInt ActiveWait( CStifItemParser& aItem );
+        virtual TInt BeginTestSessionL( CStifItemParser& aItem );
+        virtual TInt EndTestSession( CStifItemParser& aItem );
+        virtual TInt HarvestClientDataTestsL( CStifItemParser& aItem );
+        virtual TInt PlaceholderDataTestsL( CStifItemParser& aItem );
+        virtual TInt HarvesterDataTestsL( CStifItemParser& aItem );
+        
+        //[TestMethods] - Do not remove
+
+    private:    // Data
+        
+        CMdESession* iMdEClient;
+    	
+    	RArray<TItemId> iAlbumIds;
+    };
+
+#endif      // HARVESTERDATATEST_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/init/HarvesterDataTest.ini	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,81 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  
+#
+
+
+[Engine_Defaults]
+
+TestReportMode= FullReport    # Possible values are: 'Empty', 'Summary', 'Environment',
+                                                     'TestCases' or 'FullReport'
+
+CreateTestReport= YES         # Possible values: YES or NO
+
+TestReportFilePath= C:\LOGS\TestFramework\
+TestReportFileName= HarvesterDataTestLog
+
+TestReportFormat= TXT         # Possible values: TXT or HTML
+TestReportOutput= FILE        # Possible values: FILE or RDEBUG
+TestReportFileCreationMode= OVERWRITE # Possible values: OVERWRITE or APPEND
+
+DeviceResetDllName= StifResetForNokia.dll # e.g. 'StifHWResetStub.dll' for user specific reseting
+
+DisableMeasurement= stifmeasurementdisablenone  # Possible values are:
+              # 'stifmeasurementdisablenone', 'stifmeasurementdisableall'
+              # 'stifmeasurementplugin01', 'stifmeasurementplugin02',
+              # 'stifmeasurementplugin03', 'stifmeasurementplugin04',
+              # 'stifmeasurementplugin05' or 'stifbappeaprofiler'
+
+Timeout= 600000		            # Default timeout value for each test case. In milliseconds
+#UITestingSupport= YES        # Possible values: YES or NO
+#SeparateProcesses= YES       # Possible values: YES or NO (default: NO)
+[End_Defaults]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[New_Module]
+ModuleName= TestScripter
+TestCaseFile= c:\testframework\HarvesterDataTest.cfg
+[End_Module]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[Logger_Defaults]
+
+#NOTE: If you want to set Logger using next setting(s) remove comment(s)'#'
+#NOTE: TestEngine and TestServer logging settings cannot change here
+
+CreateLogDirectories= YES    # Possible values: YES or NO
+
+#EmulatorBasePath= C:\LOGS\TestFramework\
+#EmulatorFormat= HTML         # Possible values: TXT or HTML
+#EmulatorOutput= FILE         # Possible values: FILE or RDEBUG
+
+HardwareBasePath= C:\
+#HardwareFormat= HTML         # Possible values: TXT or HTML
+#HardwareOutput= FILE         # Possible values: FILE or RDEBUG
+
+#FileCreationMode= OVERWRITE  # Possible values: OVERWRITE or APPEND
+
+#ThreadIdToLogFile= YES       # Possible values: YES or NO
+#WithTimeStamp= YES           # Possible values: YES or NO
+#WithLineBreak= YES           # Possible values: YES or NO
+#WithEventRanking= YES        # Possible values: YES or NO
+
+#FileUnicode= YES             # Possible values: YES or NO
+AddTestCaseTitle= YES        # Possible values: YES or NO
+[End_Logger_Defaults]
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+# End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/src/HarvesterDataTest.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include <StifTestInterface.h>
+#include "HarvesterDataTest.h"
+#include <SettingServerClient.h>
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::CHarvesterDataTest
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CHarvesterDataTest::CHarvesterDataTest( 
+    CTestModuleIf& aTestModuleIf ):
+        CScriptBase( aTestModuleIf )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CHarvesterDataTest::ConstructL()
+    {
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        } 
+    // Close Setting server session
+    settingServer.Close();
+
+    TFileName logFileName;
+    
+    if(loggerSettings.iAddTestCaseTitle)
+        {
+        TName title;
+        TestModuleIf().GetTestCaseTitleL(title);
+        logFileName.Format(KHarvesterDataTestLogFileWithTitle, &title);
+        }
+    else
+        {
+        logFileName.Copy(KHarvesterDataTestLogFile);
+        }
+
+    iLog = CStifLogger::NewL( KHarvesterDataTestLogPath, 
+                          logFileName,
+                          CStifLogger::ETxt,
+                          CStifLogger::EFile,
+                          EFalse );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CHarvesterDataTest* CHarvesterDataTest::NewL( 
+    CTestModuleIf& aTestModuleIf )
+    {
+    CHarvesterDataTest* self = new (ELeave) CHarvesterDataTest( aTestModuleIf );
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+
+    }
+
+// Destructor
+CHarvesterDataTest::~CHarvesterDataTest()
+    { 
+
+    // Delete resources allocated from test methods
+    Delete();
+
+    // Delete logger
+    delete iLog; 
+
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point.
+// Returns: CScriptBase: New CScriptBase derived object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScriptBase* LibEntryL( 
+    CTestModuleIf& aTestModuleIf ) // Backpointer to STIF Test Framework
+    {
+
+    return ( CScriptBase* ) CHarvesterDataTest::NewL( aTestModuleIf );
+
+    }
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterDataTest/src/HarvesterDataTestBlocks.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,568 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// [INCLUDE FILES] - do not remove
+#include <e32svr.h>
+#include <ecom.h>
+#include <StifParser.h>
+#include <StifTestEventInterface.h>
+#include <StifTestInterface.h>
+#include "HarvesterDataTest.h"
+
+#include <etel3rdparty.h>
+#include "cnetworkinfo.h"
+#include "mdsutils.h"
+#include "mdeconstants.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::Delete
+// Delete here all resources allocated and opened from test methods. 
+// Called from destructor. 
+// -----------------------------------------------------------------------------
+//
+void CHarvesterDataTest::Delete() 
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::RunMethodL
+// Run specified method. Contains also table of test mothods and their names.
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterDataTest::RunMethodL( 
+    CStifItemParser& aItem ) 
+    {
+
+    static TStifFunctionInfo const KFunctions[] =
+        {  
+        // Copy this line for every implemented function.
+        // First string is the function name used in TestScripter script file.
+        // Second is the actual implementation member function. 
+
+        ENTRY( "ActiveWait", CHarvesterDataTest::ActiveWait ),
+        ENTRY( "BeginTestSession", CHarvesterDataTest::BeginTestSessionL ),
+        ENTRY( "EndTestSession", CHarvesterDataTest::EndTestSession ),
+        ENTRY( "HarvestClientDataTests", CHarvesterDataTest::HarvestClientDataTestsL ),
+        ENTRY( "PlaceholderDataTests", CHarvesterDataTest::PlaceholderDataTestsL ),
+        ENTRY( "HarvesterDataTests", CHarvesterDataTest::HarvesterDataTestsL ),
+
+        };
+
+    const TInt count = sizeof( KFunctions ) / 
+                        sizeof( TStifFunctionInfo );
+
+    return RunInternalL( KFunctions, count, aItem );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::HandleSessionOpened
+// -----------------------------------------------------------------------------
+//
+void CHarvesterDataTest::HandleSessionOpened( CMdESession& /*aClient*/, TInt aError )
+    {
+    _LIT( KMsg, "CallBck HandleSessionOpened - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );     
+    RDebug::Print(msg);
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::HandleSessionError
+// -----------------------------------------------------------------------------
+//
+void CHarvesterDataTest::HandleSessionError( CMdESession& /*aClient*/, TInt aError )
+    {
+    _LIT( KMsg, "CallBck HandleSessionError - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );
+    RDebug::Print(msg);
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+    } 
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::HarvestingCompleted
+// -----------------------------------------------------------------------------
+//
+void CHarvesterDataTest::HarvestingCompleted( CHarvesterData* /* aHarvesterData */ )
+	{ 
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::MonitorEvent
+// -----------------------------------------------------------------------------
+//
+void CHarvesterDataTest::MonitorEvent( CHarvesterData* /* aHarvesterData */ )
+	{ 
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::MonitorEvent
+// -----------------------------------------------------------------------------
+//
+void CHarvesterDataTest::MonitorEvent( RPointerArray<CHarvesterData>& /* aHarvesterDataArray */ )
+	{ 
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::ActiveWait
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterDataTest::ActiveWait( CStifItemParser& /* aItem */ )
+    {
+    // 2,5 seconds
+    TTimeIntervalMicroSeconds32 timeout(2500000);
+    RTimer timer;
+    TRequestStatus status;
+
+    timer.CreateLocal();
+    timer.After(status,timeout);
+
+    User::WaitForAnyRequest();
+    
+    timer.Close();
+    
+    _LIT( KMsg, "Exit    ActiveWait" );
+    iLog->Log( KMsg );
+    RDebug::Print(KMsg);
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::BeginTestSessionL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterDataTest::BeginTestSessionL( CStifItemParser& /* aItem */ )
+    {
+    TRAPD( error, iMdEClient = CMdESession::NewL( *this ) );
+
+    _LIT( KMsg, "Exit BeginTestSession - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, error);
+    iLog->Log( msg );
+    RDebug::Print(msg);
+    
+    User::LeaveIfError(error);
+    
+    return KErrNone;
+    }    
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::EndTestSession
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterDataTest::EndTestSession( CStifItemParser& /* aItem */ )
+	{    
+	iAlbumIds.Close();
+    
+	REComSession::FinalClose();
+	    
+	if ( iMdEClient )
+		{
+	    delete iMdEClient;
+	    iMdEClient = NULL;
+	    }
+	
+    _LIT( KMsg, "Exit    EndTestSession" );
+    iLog->Log( KMsg );  
+    RDebug::Print(KMsg);
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::HarvestClientDataTests
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterDataTest::HarvestClientDataTestsL( CStifItemParser& /* aItem */ )
+	{ 
+    _LIT( KMsg1, "Enter HarvestClientDataTestsL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+	
+	CHarvestClientData* data = NULL;
+	data = CHarvestClientData::NewL();
+	
+    iAlbumIds.Reset();
+    iAlbumIds.Append(55555);
+    iAlbumIds.Append(1);
+    iAlbumIds.Append(22);
+    iAlbumIds.Append(333);
+    iAlbumIds.Append(4444);
+    
+    data->SetAlbumIds( iAlbumIds );
+	
+	delete data;
+	data = NULL;
+	
+	data = CHarvestClientData::New();
+	
+	if( !data )
+	    {
+	    User::Leave( KErrUnknown );
+	    }
+	
+	iAlbumIds.Reset();
+	iAlbumIds.Append(1);
+	iAlbumIds.Append(22);
+	iAlbumIds.Append(333);
+	iAlbumIds.Append(4444);
+	iAlbumIds.Append(55555);
+	
+	data->SetAlbumIds( iAlbumIds );
+	
+	delete data;
+	data = NULL;
+	
+    _LIT( KMsg2, "Exit HarvestClientDataTestsL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	
+    return KErrNone;
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::PlaceholderDataTests
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterDataTest::PlaceholderDataTestsL( CStifItemParser& /* aItem */ )
+	{ 
+    _LIT( KMsg1, "Enter PlaceholderDataTestsL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+	
+	TTime time;
+	TUint32 size;
+	TUint id;
+	TBuf<100> tmp;
+	TInt state;
+	TInt preinstalled;
+	_LIT( KUri, "C:\\Data\\Images\\Jpg.jpg" );
+	
+	CPlaceholderData* data = CPlaceholderData::NewL();
+    CleanupStack::PushL( data );
+	
+	// modified
+    _LIT( KMsg2, "modified" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	time.HomeTime();
+	data->SetModified( time );
+	TTime time2 = data->Modified();
+    if( time != time2 )
+        {
+        return KErrBadDescriptor;
+        }
+	
+	// uri
+    _LIT( KMsg3, "uri" );
+    iLog->Log( KMsg3 );  
+    RDebug::Print( KMsg3 );
+	data->SetUri( KUri );
+	tmp = data->Uri();
+    if( !(MdsUtils::Compare( tmp, KUri ) == 0) )
+        {
+        return KErrBadDescriptor;
+        }
+	
+	// filesize
+    _LIT( KMsg4, "filesize" );
+    iLog->Log( KMsg4 );  
+    RDebug::Print( KMsg4 );
+	size = 8192;
+	data->SetFileSize( size );
+	TUint32 size2 = data->FileSize();
+    if( size != size2 )
+        {
+        return KErrBadDescriptor;
+        }
+	
+	// mediaid
+    _LIT( KMsg5, "mediaid" );
+    iLog->Log( KMsg5 );  
+    RDebug::Print( KMsg5 );
+	id = 64;
+	data->SetMediaId( id );
+	TUint32 id2 = data->MediaId();
+    if( id != id2 )
+        {
+        return KErrBadDescriptor;
+        }
+	
+    // state
+    _LIT( KMsg6, "state" );
+    iLog->Log( KMsg6 );  
+    RDebug::Print( KMsg6 );
+    state = 0;
+    data->SetPresentState( state );
+    TInt state2 = data->PresentState();
+    if( state != state2 )
+        {
+        return KErrBadDescriptor;
+        }
+    
+    // preinstalled
+    _LIT( KMsg7, "preinstalled" );
+    iLog->Log( KMsg7 );  
+    RDebug::Print( KMsg7 );
+    preinstalled = 0;
+    data->SetPreinstalled( preinstalled );
+    TInt preinstalled2 = data->Preinstalled();
+    if( preinstalled != preinstalled2 )
+        {
+        return KErrBadDescriptor;
+        }
+    
+    CleanupStack::PopAndDestroy( data );
+
+    _LIT( KMsg8, "Exit PlaceholderDataTestsL" );
+    iLog->Log( KMsg8 );  
+    RDebug::Print( KMsg8 );
+	
+    return KErrNone;
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterDataTest::HarvestClientDataTests
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterDataTest::HarvesterDataTestsL( CStifItemParser& /* aItem */ )
+	{ 
+    _LIT( KMsg1, "Enter HarvesterDataTestsL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+	
+	TInt errorcode;
+	THarvesterEventType event;
+	MHarvesterPluginObserver* pluginobs;
+	TOrigin origin;
+	TBool snap;
+	THarvesterObjectType type;
+	TAny* client;
+	CMdEObject* object;
+	TLocationData* location;
+	TUid uid;
+	TBool add;
+	CHarvesterPluginInfo* pluginInfo;
+	TBool binary;
+	
+	_LIT( KUri, "C:\\Data\\Images\\Jpg.jpg" );
+	
+	// mdeobject
+	CMdENamespaceDef& defaultNamespace = iMdEClient->GetDefaultNamespaceDefL();
+	CMdEObjectDef& imageDef = defaultNamespace.GetObjectDefL( MdeConstants::Image::KImageObject );
+	
+	iMdEClient->RemoveObjectL( KUri );
+	object = iMdEClient->NewObjectL( imageDef, KUri );
+	
+	// harvesterdata object
+	HBufC* uriBuf = object->Uri().AllocLC();
+	CHarvesterData* data = CHarvesterData::NewL( uriBuf );
+	CleanupStack::Pop( uriBuf );
+	
+	// uri
+    _LIT( KMsg2, "uri" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	TDesC uri2 = data->Uri();
+
+	
+	// errorcode
+    _LIT( KMsg3, "errorcode" );
+    iLog->Log( KMsg3 );  
+    RDebug::Print( KMsg3 );
+	errorcode = -1;
+	data->SetErrorCode( errorcode );
+	TInt ret = data->ErrorCode();
+	if( ret != errorcode )
+	    {
+	    return KErrBadDescriptor;
+	    }
+	
+	// eventtype
+    _LIT( KMsg4, "eventtype" );
+    iLog->Log( KMsg4 );  
+    RDebug::Print( KMsg4 );
+	event = EHarvesterAdd;
+	data->SetEventType(event);
+	THarvesterEventType event2 = data->EventType();
+    if( event2 != event )
+        {
+        return KErrBadDescriptor;
+        }
+	
+	// pluginobserver
+    _LIT( KMsg5, "pluginobserver" );
+    iLog->Log( KMsg5 );  
+    RDebug::Print( KMsg5 );
+	pluginobs = this;
+	data->SetPluginObserver( *pluginobs );
+	MHarvesterPluginObserver* pluginobs2 = data->PluginObserver();
+    if( pluginobs != pluginobs2 )
+        {
+        return KErrBadDescriptor;
+        }
+	pluginobs = NULL;
+	
+	// origin
+    _LIT( KMsg6, "origin" );
+    iLog->Log( KMsg6 );  
+    RDebug::Print( KMsg6 );
+	origin = MdeConstants::Object::EDownloaded;
+	data->SetOrigin( origin );
+	TOrigin origin2 = data->Origin();
+    if( origin != origin2 )
+        {
+        return KErrBadDescriptor;
+        }
+	
+	// takesnapshot
+    _LIT( KMsg7, "takesnapshot" );
+    iLog->Log( KMsg7 );  
+    RDebug::Print( KMsg7 );
+	snap = ETrue;
+	data->SetTakeSnapshot( snap );
+	TBool snap2 = data->TakeSnapshot();
+    if( !(snap && snap2) )
+        {
+        return KErrBadDescriptor;
+        }
+	
+	// objecttype
+    _LIT( KMsg8, "objecttype" );
+    iLog->Log( KMsg8 );  
+    RDebug::Print( KMsg8 );
+	type = ENormal;
+	data->SetObjectType(type);
+	THarvesterObjectType type2 = data->ObjectType();
+    if( type != type2 )
+        {
+        return KErrBadDescriptor;
+        }
+	
+	// clientdata
+    _LIT( KMsg9, "clientdata" );
+    iLog->Log( KMsg9 );  
+    RDebug::Print( KMsg9 );
+	client = NULL;
+	data->SetClientData( NULL );
+	TAny* client2 = data->ClientData();
+    if( client != client2 )
+        {
+        return KErrBadDescriptor;
+        }
+	client = NULL;
+	
+	// mdeobject
+    _LIT( KMsg10, "mdeobject" );
+    iLog->Log( KMsg10 );  
+    RDebug::Print( KMsg10 );
+	data->SetMdeObject( object );
+	CMdEObject* object2 = &data->MdeObject();
+    if( object != object2 )
+        {
+        return KErrBadDescriptor;
+        }
+	data->SetMdeObject( NULL );
+	
+	// locationdata
+    _LIT( KMsg11, "locationdata" );
+    iLog->Log( KMsg11 );  
+    RDebug::Print( KMsg11 );
+	location = new ( ELeave ) TLocationData;
+	location->iQuality = 0;
+	data->SetLocationData( location );
+	TLocationData* location2 = data->LocationData();
+    if( location != location2 )
+        {
+        return KErrBadDescriptor;
+        }
+
+    // clientid
+    _LIT( KMsg12, "clientid" );
+    iLog->Log( KMsg12 );  
+    RDebug::Print( KMsg12 );
+    uid = KNullUid;
+    data->SetClientId( uid );
+    TUid uid2 = data->ClientId();
+    if( uid2 != uid )
+        {
+        return KErrBadDescriptor;
+        }    
+    
+    // add location
+    _LIT( KMsg13, "add location" );
+    iLog->Log( KMsg13 );  
+    RDebug::Print( KMsg13 );
+    add = ETrue;
+    data->SetAddLocation( add );
+    TBool add2 = data->AddLocation();
+    if( !(add && add2) )
+        {
+        return KErrBadDescriptor;
+        }    
+    
+    // harvesterplugininfo
+    _LIT( KMsg14, "pluginobserver" );
+    iLog->Log( KMsg14 );  
+    RDebug::Print( KMsg14 );
+    pluginInfo = NULL;
+    data->SetHarvesterPluginInfo( pluginInfo );
+    CHarvesterPluginInfo* pluginInfo2 = data->HarvesterPluginInfo();
+    if( pluginInfo != pluginInfo2 )
+        {
+        return KErrBadDescriptor;
+        }
+    pluginInfo = NULL;
+
+    // binary
+    _LIT( KMsg15, "binary" );
+    iLog->Log( KMsg15 );  
+    RDebug::Print( KMsg15 );
+    binary = ETrue;
+    data->SetBinary( binary );
+    TBool binary2 = data->IsBinary();
+    if( !(binary && binary2) )
+        {
+        return KErrBadDescriptor;
+        }   
+    
+	delete data;
+	data = NULL;
+	
+    _LIT( KMsg16, "Exit HarvesterDataTestsL" );
+    iLog->Log( KMsg16 );  
+    RDebug::Print( KMsg16 );
+	
+    return KErrNone;
+	}
+
+//  [End of File] - Do not remove
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/Bmarm/HarvesterPluginTestU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	LibEntryL__FR13CTestModuleIf @ 1 NONAME R3UNUSED ; LibEntryL(CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/Bwins/HarvesterPluginTestU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?LibEntryL@@YAPAVCScriptBase@@AAVCTestModuleIf@@@Z @ 1 NONAME ; class CScriptBase * __cdecl LibEntryL(class CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/EABI/HarvesterPluginTestU.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	_Z9LibEntryLR13CTestModuleIf @ 1 NONAME
+	_ZTI17CMdeObjectHandler @ 2 NONAME ; #<TI>#
+	_ZTV17CMdeObjectHandler @ 3 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/conf/HarvesterPluginTest.cfg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,54 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  Harvester Plugin API tests
+#
+
+// ---------------------------------------------------------------------------
+// Harvester Plugin API test cases
+// ---------------------------------------------------------------------------
+
+// These should be run in sequential mode if several cases are run at the same
+// time! 
+
+[StifSettings]
+TestThreadStackSize= 32768
+TestThreadMinHeap= 4096
+TestThreadMaxHeap= 16777216
+[EndStifSettings]
+
+[Test]
+title Test Harvester Plugins
+create HarvesterPluginTest test
+request Session
+test BeginTestSession
+wait Session
+test LoadPlugins
+request Harvest
+test TestFunctions e:\testing\data\Jpg.jpg
+wait Harvest
+test TestFunctions e:\testing\data\Animated.gif
+wait Harvest
+test TestFunctions e:\testing\data\Mbm.mbm
+wait Harvest
+test TestFunctions e:\testing\data\H263.3gp
+wait Harvest
+test TestFunctions e:\testing\data\MPEG4.3gp
+wait Harvest
+test TestFunctions e:\testing\data\MPEG4.mp4
+wait Harvest
+test TestFunctions e:\testing\data\00001.mp3
+wait Harvest
+test EndTestSession
+delete test
+[Endtest]
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/group/HarvesterPluginTest.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET          HarvesterPluginTest.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E3
+
+CAPABILITY      ALL -TCB
+VENDORID        VID_DEFAULT
+
+DEFFILE         HarvesterPluginTest.DEF
+
+SOURCEPATH      ../src
+SOURCE          HarvesterPluginTest.cpp
+SOURCE          HarvesterPluginTestBlocks.cpp
+
+SOURCEPATH        ../../../../../harvester/server/src
+SOURCE            mdeobjecthandler.cpp
+
+SYSTEMINCLUDE   /epoc32/include/ecom
+USERINCLUDE     ../inc 
+USERINCLUDE     ../../../../../inc
+USERINCLUDE			../../../../../harvester/common/inc
+USERINCLUDE			../../../../../harvester/server/inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY			    efsrv.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+LIBRARY         mdeclient.lib
+LIBRARY			    ecom.lib
+LIBRARY         contextengine.lib
+LIBRARY         contextplugininterface.lib
+LIBRARY			    harvesterplugininterface.lib
+LIBRARY			    harvesterdata.lib
+LIBRARY         mdccommon.lib
+LIBRARY         harvestercommon.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/group/HarvesterPluginTest.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,56 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:  Installation file for API test
+;
+
+; Languages
+&EN
+
+; Header
+#{"HarvesterPluginTest"},(0x101FB3E3),1,0,0,TYPE=SA
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Install files
+"\epoc32\release\armv5\urel\HarvesterPluginTest.dll" - "c:\sys\bin\HarvesterPluginTest.dll"
+"..\conf\HarvesterPluginTest.cfg" - "c:\TestFramework\HarvesterPluginTest.cfg"
+"..\init\HarvesterPluginTest.ini" - "c:\TestFramework\HarvesterPluginTest.ini"
+
+"..\..\data\mmc\HarvesterTest\Jpg.jpg"      -"E:\testing\data\Jpg.jpg"
+"..\..\data\mmc\HarvesterTest\Animated.gif"      -"E:\testing\data\Animated.gif"
+"..\..\data\mmc\HarvesterTest\Temp1.jpg"      -"E:\testing\data\Temp1.jpg"
+"..\..\data\mmc\HarvesterTest\Temp2.jpg"      -"E:\testing\data\Temp2.jpg"
+"..\..\data\mmc\HarvesterTest\Temp3.jpg"      -"E:\testing\data\Temp3.jpg"
+"..\..\data\mmc\HarvesterTest\H263.3gp"      -"E:\testing\data\H263.3gp"
+"..\..\data\mmc\HarvesterTest\bmp_burst.bmp"      -"E:\testing\data\bmp_burst.bmp"
+"..\..\data\mmc\HarvesterTest\GIF87testimage.gif"      -"E:\testing\data\GIF87testimage.gif"
+"..\..\data\mmc\HarvesterTest\gif89a_onemeg.gif"      -"E:\testing\data\gif89a_onemeg.gif"
+"..\..\data\mmc\HarvesterTest\Liverpool.jpg"      -"E:\testing\data\Liverpool.jpg"
+"..\..\data\mmc\HarvesterTest\MBMtestimage.mbm"      -"E:\testing\data\MBMtestimage.mbm"
+"..\..\data\mmc\HarvesterTest\wbmp_skull.wbmp"      -"E:\testing\data\wbmp_skull.wbmp"
+"..\..\data\mmc\HarvesterTest\ota_bmpiso.ota"      -"E:\testing\data\ota_bmpiso.ota"
+"..\..\data\mmc\HarvesterTest\PNGtestimage.png"      -"E:\testing\data\PNGtestimage.png"
+"..\..\data\mmc\HarvesterTest\G4.TIF"      -"E:\testing\data\G4.TIF"
+"..\..\data\mmc\HarvesterTest\G31D.TIF"      -"E:\testing\data\G31D.TIF"
+"..\..\data\mmc\HarvesterTest\PSRETRO.WMF"      -"E:\testing\data\PSRETRO.WMF"
+"..\..\data\mmc\HarvesterTest\Animated.gif"      -"E:\testing\data\Animated.gif"
+"..\..\data\mmc\HarvesterTest\Mbm.mbm"      -"E:\testing\data\Mbm.mbm"
+"..\..\data\mmc\HarvesterTest\MPEG4.3gp"      -"E:\testing\data\MPEG4.3gp"
+"..\..\data\mmc\HarvesterTest\MPEG4.mp4"      -"E:\testing\data\MPEG4.mp4"
+"..\..\data\mmc\HarvesterTest\00001.mp3"      -"E:\testing\data\00001.mp3"
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+HarvesterPluginTest.mmp
+
+PRJ_TESTEXPORTS
+
+../conf/HarvesterPluginTest.cfg /epoc32/winscw/c/TestFramework/HarvesterPluginTest.cfg
+../init/HarvesterPluginTest.ini /epoc32/winscw/c/TestFramework/HarvesterPluginTest.ini
+
+../../data/mmc/HarvesterTest/bmp_burst.bmp /epoc32/WINSCW/C/Data/bmp_burst.bmp
+../../data/mmc/HarvesterTest/G31D.TIF /epoc32/WINSCW/C/Data/G31D.TIF
+../../data/mmc/HarvesterTest/G4.TIF /epoc32/WINSCW/C/Data/G4.TIF
+../../data/mmc/HarvesterTest/GIF87testimage.gif /epoc32/WINSCW/C/Data/GIF87testimage.gif
+../../data/mmc/HarvesterTest/gif89a_onemeg.gif /epoc32/WINSCW/C/Data/gif89a_onemeg.gif
+../../data/mmc/HarvesterTest/Liverpool.jpg /epoc32/WINSCW/C/Data/Liverpool.jpg
+../../data/mmc/HarvesterTest/MBMtestimage.mbm /epoc32/WINSCW/C/Data/MBMtestimage.mbm
+../../data/mmc/HarvesterTest/ota_bmpiso.ota /epoc32/WINSCW/C/Data/ota_bmpiso.ota
+../../data/mmc/HarvesterTest/PNGtestimage.png /epoc32/WINSCW/C/Data/PNGtestimage.png
+../../data/mmc/HarvesterTest/PSRETRO.WMF /epoc32/WINSCW/C/Data/PSRETRO.WMF
+../../data/mmc/HarvesterTest/wbmp_skull.wbmp /epoc32/WINSCW/C/Data/wbmp_skull.wbmp
+../../data/mmc/HarvesterTest/Jpg.jpg /epoc32/WINSCW/C/Data/Jpg.jpg
+../../data/mmc/HarvesterTest/Animated.gif /epoc32/WINSCW/C/Data/Animated.gif
+../../data/mmc/HarvesterTest/Mbm.mbm /epoc32/WINSCW/C/Data/Mbm.mbm
+../../data/mmc/HarvesterTest/H263.3gp /epoc32/WINSCW/C/Data/H263.3gp
+../../data/mmc/HarvesterTest/MPEG4.mp4 /epoc32/WINSCW/C/Data/MPEG4.mp4
+../../data/mmc/HarvesterTest/MPEG4.3gp /epoc32/WINSCW/C/Data/MPEG4.3gp
+../../data/mmc/HarvesterTest/Temp1.jpg /epoc32/WINSCW/C/Data/Temp1.jpg
+../../data/mmc/HarvesterTest/Temp2.jpg /epoc32/WINSCW/C/Data/Temp2.jpg
+../../data/mmc/HarvesterTest/Temp3.jpg /epoc32/WINSCW/C/Data/Temp3.jpg
+../../data/mmc/HarvesterTest/00001.mp3 /epoc32/WINSCW/C/Data/00001.mp3
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/inc/HarvesterPluginTest.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,141 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef HARVESTERPLUGINTEST_H
+#define HARVESTERPLUGINTEST_H
+
+//  INCLUDES
+#include <StifLogger.h>
+#include <TestScripterInternal.h>
+#include <StifTestModule.h>
+
+#include "contextengine.h"
+#include <mdccommon.h>
+#include <harvesterdata.h>
+#include "mdeharvestersession.h"
+#include <harvesterplugin.h>
+#include "harvesterplugininfo.h"
+
+// CONSTANTS
+
+_LIT( KBlacklistDatabaseName, "C:[200009f5]blacklistdb.sq" );
+
+// Logging path
+_LIT( KHarvesterPluginTestLogPath, "\\logs\\testframework\\HarvesterPluginTest\\" ); 
+// Log file
+_LIT( KHarvesterPluginTestLogFile, "HarvesterPluginTest.txt" ); 
+_LIT( KHarvesterPluginTestLogFileWithTitle, "HarvesterPluginTest_[%S].txt" );
+
+// FORWARD DECLARATIONS
+class CHarvesterPluginTest;
+class CHarvesterBlacklist;
+class CMdeObjectHandler;
+
+// CLASS DECLARATION
+NONSHARABLE_CLASS(CHarvesterPluginTest) : public CScriptBase,
+										  MMdESessionObserver,
+										  MHarvesterPluginObserver
+									
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CHarvesterPluginTest* NewL( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CHarvesterPluginTest();
+
+    public: // Functions from base classes
+
+        /**
+        * From CScriptBase Runs a script line.
+        * @since ?Series60_version
+        * @param aItem Script line containing method name and parameters
+        * @return Symbian OS error code
+        */
+        virtual TInt RunMethodL( CStifItemParser& aItem );
+
+    private: // Functions from base classes
+        	
+        void HandleSessionOpened(CMdESession& aSession, TInt aError);
+        void HandleSessionError(CMdESession& aSession, TInt aError);      
+        void HarvestingCompleted( CHarvesterData* aHarvesterData );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CHarvesterPluginTest( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Frees all resources allocated from test methods.
+        * @since ?Series60_version
+        */
+        void Delete();
+
+        /**
+        * Test methods are listed below. 
+        */
+
+        virtual TInt BeginTestSessionL( CStifItemParser& aItem );
+        virtual TInt EndTestSession( CStifItemParser& aItem );
+        virtual TInt LoadPluginsL( CStifItemParser& aItem );
+        virtual TInt TestFunctionsL( CStifItemParser& aItem );
+
+        // helper methods
+        TBool GetObjectDef(const TDesC& aUri, TDes& aObjectDef, TBool aCheck);
+        TInt HarvestL( CHarvesterData* aHD );
+        void AddNewPluginL( const TDesC8& aType, const TDesC8& aOpaque, TUid aPluginUid );
+        CHarvesterPluginInfo* GetHPIFromFileNameL(const TDesC& aFileName);
+        CHarvesterPluginInfo* GetFromNormalFileL( TDesC& aExt );
+        
+    public:     // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    protected:  // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    private:    // Data
+        
+    	CMdESession* iMdeSession;
+    	CMdEHarvesterSession* iSession;
+    	
+    	CContextEngine* iCtxEngine;
+    	CHarvesterBlacklist* iBlacklist;
+    	CMdeObjectHandler* iMdeObjectHandler;
+    	
+    	CHarvesterPlugin* iPlugin;
+    	RPointerArray<CHarvesterPluginInfo> iPluginInfoArray;
+
+    };
+
+#endif      // HARVESTERPLUGINTEST_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/init/HarvesterPluginTest.ini	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,81 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  
+#
+
+
+[Engine_Defaults]
+
+TestReportMode= FullReport    # Possible values are: 'Empty', 'Summary', 'Environment',
+                                                     'TestCases' or 'FullReport'
+
+CreateTestReport= YES         # Possible values: YES or NO
+
+TestReportFilePath= C:\LOGS\TestFramework\
+TestReportFileName= HarvesterPluginTestLog
+
+TestReportFormat= TXT         # Possible values: TXT or HTML
+TestReportOutput= FILE        # Possible values: FILE or RDEBUG
+TestReportFileCreationMode= OVERWRITE # Possible values: OVERWRITE or APPEND
+
+DeviceResetDllName= StifResetForNokia.dll # e.g. 'StifHWResetStub.dll' for user specific reseting
+
+DisableMeasurement= stifmeasurementdisablenone  # Possible values are:
+              # 'stifmeasurementdisablenone', 'stifmeasurementdisableall'
+              # 'stifmeasurementplugin01', 'stifmeasurementplugin02',
+              # 'stifmeasurementplugin03', 'stifmeasurementplugin04',
+              # 'stifmeasurementplugin05' or 'stifbappeaprofiler'
+
+Timeout= 600000		            # Default timeout value for each test case. In milliseconds
+#UITestingSupport= YES        # Possible values: YES or NO
+#SeparateProcesses= YES       # Possible values: YES or NO (default: NO)
+[End_Defaults]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[New_Module]
+ModuleName= TestScripter
+TestCaseFile= c:\testframework\HarvesterPluginTest.cfg
+[End_Module]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[Logger_Defaults]
+
+#NOTE: If you want to set Logger using next setting(s) remove comment(s)'#'
+#NOTE: TestEngine and TestServer logging settings cannot change here
+
+CreateLogDirectories= YES    # Possible values: YES or NO
+
+#EmulatorBasePath= C:\LOGS\TestFramework\
+#EmulatorFormat= HTML         # Possible values: TXT or HTML
+#EmulatorOutput= FILE         # Possible values: FILE or RDEBUG
+
+HardwareBasePath= C:\
+#HardwareFormat= HTML         # Possible values: TXT or HTML
+#HardwareOutput= FILE         # Possible values: FILE or RDEBUG
+
+#FileCreationMode= OVERWRITE  # Possible values: OVERWRITE or APPEND
+
+#ThreadIdToLogFile= YES       # Possible values: YES or NO
+#WithTimeStamp= YES           # Possible values: YES or NO
+#WithLineBreak= YES           # Possible values: YES or NO
+#WithEventRanking= YES        # Possible values: YES or NO
+
+#FileUnicode= YES             # Possible values: YES or NO
+AddTestCaseTitle= YES        # Possible values: YES or NO
+[End_Logger_Defaults]
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+# End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/src/HarvesterPluginTest.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+// INCLUDE FILES
+#include <StifTestInterface.h>
+#include "HarvesterPluginTest.h"
+#include <SettingServerClient.h>
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTest::CHarvesterPluginTest
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CHarvesterPluginTest::CHarvesterPluginTest( 
+    CTestModuleIf& aTestModuleIf ):
+        CScriptBase( aTestModuleIf )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTest::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CHarvesterPluginTest::ConstructL()
+    {
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        } 
+    // Close Setting server session
+    settingServer.Close();
+
+    TFileName logFileName;
+    
+    if(loggerSettings.iAddTestCaseTitle)
+        {
+        TName title;
+        TestModuleIf().GetTestCaseTitleL(title);
+        logFileName.Format(KHarvesterPluginTestLogFileWithTitle, &title);
+        }
+    else
+        {
+        logFileName.Copy(KHarvesterPluginTestLogFile);
+        }
+
+    iLog = CStifLogger::NewL( KHarvesterPluginTestLogPath, 
+                          logFileName,
+                          CStifLogger::ETxt,
+                          CStifLogger::EFile,
+                          EFalse );
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTest::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CHarvesterPluginTest* CHarvesterPluginTest::NewL( 
+    CTestModuleIf& aTestModuleIf )
+    {
+    CHarvesterPluginTest* self = new (ELeave) CHarvesterPluginTest( aTestModuleIf );
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+
+    }
+
+// Destructor
+CHarvesterPluginTest::~CHarvesterPluginTest()
+    { 
+
+    // Delete resources allocated from test methods
+    Delete();
+
+    // Delete logger
+    delete iLog; 
+
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point.
+// Returns: CScriptBase: New CScriptBase derived object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScriptBase* LibEntryL( 
+    CTestModuleIf& aTestModuleIf ) // Backpointer to STIF Test Framework
+    {
+
+    return ( CScriptBase* ) CHarvesterPluginTest::NewL( aTestModuleIf );
+
+    }
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/HarvesterPluginTest/src/HarvesterPluginTestBlocks.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,493 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+// [INCLUDE FILES] - do not remove
+#include <e32svr.h>
+#include <StifParser.h>
+#include <StifTestEventInterface.h>
+#include <StifTestInterface.h>
+#include "HarvesterPluginTest.h"
+
+#include "mdsutils.h"
+#include "harvesterblacklist.h"
+#include "mdeobject.h"
+#include "mdeobjecthandler.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTest::Delete
+// Delete here all resources allocated and opened from test methods. 
+// Called from destructor. 
+// -----------------------------------------------------------------------------
+//
+void CHarvesterPluginTest::Delete() 
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTest::RunMethodL
+// Run specified method. Contains also table of test mothods and their names.
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterPluginTest::RunMethodL( 
+    CStifItemParser& aItem ) 
+    {
+
+    static TStifFunctionInfo const KFunctions[] =
+        {  
+        // Copy this line for every implemented function.
+        // First string is the function name used in TestScripter script file.
+        // Second is the actual implementation member function. 
+
+        ENTRY( "BeginTestSession", CHarvesterPluginTest::BeginTestSessionL ),
+        ENTRY( "EndTestSession", CHarvesterPluginTest::EndTestSession ),
+        ENTRY( "LoadPlugins", CHarvesterPluginTest::LoadPluginsL ),
+        ENTRY( "TestFunctions", CHarvesterPluginTest::TestFunctionsL ),
+        		
+        };
+
+    const TInt count = sizeof( KFunctions ) / 
+                        sizeof( TStifFunctionInfo );
+
+    return RunInternalL( KFunctions, count, aItem );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTest::HandleSessionOpened
+// -----------------------------------------------------------------------------
+//
+void CHarvesterPluginTest::HandleSessionOpened( CMdESession& /*aClient*/, TInt aError )
+    {
+    _LIT( KMsg, "CallBck HandleSessionOpened - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );     
+    RDebug::Print(msg);
+    
+    TRAP_IGNORE( iMdeObjectHandler = CMdeObjectHandler::NewL( *iMdeSession ) );
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTest::HandleSessionError
+// -----------------------------------------------------------------------------
+//
+void CHarvesterPluginTest::HandleSessionError( CMdESession& /*aClient*/, TInt aError )
+    {
+    _LIT( KMsg, "CallBck HandleSessionError - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );
+    RDebug::Print(msg);
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTest::HarvestingCompleted
+// -----------------------------------------------------------------------------
+//
+void CHarvesterPluginTest::HarvestingCompleted( CHarvesterData* /* aHarvesterData */ )
+	{ 
+    // harvest event
+    TEventIf event( TEventIf::ESetEvent, _L("Harvest") );
+    TestModuleIf().Event( event );
+	}
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTest::BeginTestSessionL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterPluginTest::BeginTestSessionL( CStifItemParser& /* aItem */ )
+    {
+    TRAPD( error, iMdeSession = CMdESession::NewL( *this ) );
+
+    iSession = CMdEHarvesterSession::NewL( *iMdeSession );
+    
+    iCtxEngine = NULL;
+    	
+    iBlacklist = CHarvesterBlacklist::NewL();
+    
+    _LIT( KMsg, "Exit BeginTestSession - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, error);
+    iLog->Log( msg );
+    RDebug::Print( msg );
+    
+    User::LeaveIfError( error );
+    
+    return KErrNone;
+    }    
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTest::EndTestSession
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterPluginTest::EndTestSession( CStifItemParser& /* aItem */ )
+	{       
+	iPluginInfoArray.ResetAndDestroy();
+	iPluginInfoArray.Close();
+	
+	REComSession::FinalClose();
+    
+    if ( iCtxEngine )
+    	{
+    	iCtxEngine->ReleaseInstance();
+    	iCtxEngine = NULL;
+    	}
+
+    if ( iBlacklist )
+        {
+        iBlacklist->CloseDatabase();
+        delete iBlacklist;
+        }
+    
+    if ( iSession )
+    	{
+    	delete iSession;
+    	iSession = NULL;
+    	}
+    
+    if ( iMdeObjectHandler )
+    	{
+    	delete iMdeObjectHandler;
+    	iMdeObjectHandler = NULL;
+    	}
+
+    if( iMdeSession )
+    	{
+    	delete iMdeSession;
+    	iMdeSession = NULL;
+    	}
+    
+    _LIT( KMsg, "Exit    EndTestSession" );
+    iLog->Log( KMsg );  
+    RDebug::Print(KMsg);
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTest::LoadPluginsL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterPluginTest::LoadPluginsL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter LoadPlugins" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    RImplInfoPtrArray infoArray;
+    	
+	TCleanupItem cleanupItem( MdsUtils::CleanupEComArray, &infoArray );
+	CleanupStack::PushL( cleanupItem );
+	
+	CHarvesterPlugin::ListImplementationsL( infoArray );
+	TInt count( 0 );
+	count = infoArray.Count();
+	
+	if( count == 0 )
+	    {
+	    return KErrNotFound;
+	    }
+	
+	for ( TInt i=0; i < count; i++ )
+		{
+		// Parse the file extensions and resolve plug-in's uids from infoArray to iDataTypeArray
+        TBufC8<256> type;
+        TBufC8<256> opaque;
+        
+        type = infoArray[i]->DataType();
+        opaque = infoArray[i]->OpaqueData();
+        TUid implUID = infoArray[i]->ImplementationUid(); 
+                
+        AddNewPluginL(type, opaque, implUID);
+		}
+	
+	CleanupStack::PopAndDestroy( &infoArray ); // infoArray, results in a call to CleanupEComArray
+    
+    _LIT( KMsg2, "Exit    LoadPlugins" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTest::TestFunctionsL
+// -----------------------------------------------------------------------------
+//
+TInt CHarvesterPluginTest::TestFunctionsL( CStifItemParser& aItem )
+    {
+    _LIT( KMsg1, "Enter TestFunctions" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+	TPtrC inputFile;
+	User::LeaveIfError( aItem.GetNextString( inputFile ) );
+	
+	iMdeSession->RemoveObjectL( inputFile );
+	
+	TBuf<100> aObjectDef;
+	
+	GetObjectDef( inputFile, aObjectDef, EFalse );
+    
+	// harvesterdata object
+	HBufC* uriBuf = inputFile.AllocLC();
+	CHarvesterData* data = CHarvesterData::NewL( uriBuf );
+	data->SetPluginObserver( *this );
+	CMdEObject* mdeObject = NULL;
+	_LIT( string, "Image" );
+	mdeObject = iMdeObjectHandler->GetMetadataObjectL( *data, string );
+	data->SetMdeObject( mdeObject );
+	CleanupStack::Pop( uriBuf );
+	
+	HarvestL( data );
+	
+    _LIT( KMsg2, "Exit TestFunctions" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// GetObjectDef
+// ---------------------------------------------------------------------------
+//
+TBool CHarvesterPluginTest::GetObjectDef(const TDesC& aUri, TDes& aObjectDef, TBool aCheck)
+	{
+	CHarvesterPluginInfo* hpi = NULL; 
+
+	TRAPD( err, hpi = GetHPIFromFileNameL(aUri) );
+	if ( err != KErrNone )
+		{
+		aObjectDef.Zero();
+		return EFalse;
+		}
+
+	if ( !hpi )
+		{
+		aObjectDef.Zero();
+		}
+	else
+		{
+		if( hpi->iObjectTypes.Count() > 1)
+			{
+			if( aCheck )
+				{
+				aObjectDef.Zero();
+				return ETrue;
+				}
+			
+			if ( ! hpi->iPlugin )
+	    		{
+	    		TRAPD( error, hpi->iPlugin = CHarvesterPlugin::NewL( hpi->iPluginUid ) );
+	             if( error )
+	                    {
+	                    aObjectDef.Zero();
+	                    return EFalse;
+	                    }
+	             else
+	                 {
+	                 hpi->iPlugin->SetQueue( hpi->iQueue );
+	                 }
+	    		}
+			hpi->iPlugin->GetObjectType( aUri, aObjectDef );
+			}
+		else
+			{
+			aObjectDef.Copy( *(hpi->iObjectTypes[0]) );
+			}
+		}
+	
+	return EFalse;
+	}
+
+// ---------------------------------------------------------------------------
+// HarvestL
+// ---------------------------------------------------------------------------
+//
+TInt CHarvesterPluginTest::HarvestL( CHarvesterData* aHD )
+	{
+    _LIT( KMsg1, "Enter HarvestL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+	
+	CHarvesterPluginInfo* hpi = aHD->HarvesterPluginInfo();
+	
+	if ( !hpi ) 
+		{
+		 hpi = GetHPIFromFileNameL( aHD->Uri() );
+		}
+	
+	if ( hpi )
+		{
+		if ( ! hpi->iPlugin )
+    		{
+    		hpi->iPlugin = CHarvesterPlugin::NewL( hpi->iPluginUid );
+    		hpi->iPlugin->SetQueue( hpi->iQueue );
+    		hpi->iPlugin->SetBlacklist( *iBlacklist );
+    		}
+		
+	    if( aHD->ObjectType() == EFastHarvest || aHD->Origin() == MdeConstants::Object::ECamera )
+	    	{
+	    	hpi->iQueue.Insert( aHD, 0 );
+	    	}
+	    else
+			{
+			hpi->iQueue.AppendL( aHD );
+			}
+	    
+		hpi->iPlugin->StartHarvest();
+	
+	    _LIT( KMsg2, "Exit HarvestL" );
+	    iLog->Log( KMsg2 );
+	    RDebug::Print( KMsg2 );
+		
+		return KErrNone;
+		}
+	
+	return KErrNotFound;
+	}
+
+// -----------------------------------------------------------------------------
+// AddNewPluginL
+// -----------------------------------------------------------------------------
+//
+void CHarvesterPluginTest::AddNewPluginL( const TDesC8& aType, const TDesC8& aOpaque, TUid aPluginUid )
+    {      
+    CHarvesterPluginInfo* pluginInfo = new (ELeave) CHarvesterPluginInfo;
+    CleanupStack::PushL( pluginInfo );
+
+    // get file extensions
+    TLex8 lex( aOpaque );
+    while ( !lex.Eos() )
+        {
+        /* Tokenizing file extensions using TLex8 */
+        lex.SkipSpaceAndMark();
+
+        TPtrC8 extToken = lex.NextToken();
+
+        HBufC* str = HBufC::NewLC( extToken.Length() );
+        str->Des().Copy( extToken );
+        pluginInfo->iExtensions.AppendL( str );
+        CleanupStack::Pop( str );
+        }
+
+    // get object types
+    TLex8 lexObjectTypes( aType );
+    while ( !lexObjectTypes.Eos() )
+        {
+        /* Tokenizing object types using TLex8 */
+        lexObjectTypes.SkipSpaceAndMark();
+        
+        TPtrC8 objectTypeToken = lexObjectTypes.NextToken();
+
+        HBufC* str = HBufC::NewLC( objectTypeToken.Length() );
+        str->Des().Copy( objectTypeToken );
+        pluginInfo->iObjectTypes.AppendL( str );
+        CleanupStack::Pop( str );
+        }
+
+    /* We set plugin as NULL - we only load them when needed */
+    pluginInfo->iPlugin = NULL;
+    pluginInfo->iPluginUid = aPluginUid;
+    iPluginInfoArray.AppendL( pluginInfo );
+    CleanupStack::Pop( pluginInfo );
+    }
+
+// ---------------------------------------------------------------------------
+// GetHPIFromFileNameL
+// ---------------------------------------------------------------------------
+//
+CHarvesterPluginInfo* CHarvesterPluginTest::GetHPIFromFileNameL(const TDesC& aFileName)
+	{
+    _LIT( KMsg1, "Enter GetHPIFromFileNameL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+	
+	TParsePtrC parser( aFileName );
+    
+    // without trailing dot "."
+    TPtrC ptr = parser.Ext();
+    if ( ptr.Length() > 1 )
+    	{
+    	ptr.Set( ptr.Mid( 1 ) );
+    	}
+
+    _LIT( KMsg2, "Exit GetHPIFromFileNameL" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+	return GetFromNormalFileL( ptr );
+	}
+
+// ---------------------------------------------------------------------------
+// GetFromNormalFile
+// ---------------------------------------------------------------------------
+//
+CHarvesterPluginInfo* CHarvesterPluginTest::GetFromNormalFileL( TDesC& aExt )
+	{
+    _LIT( KMsg1, "Enter GetFromNormalFileL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+	
+	CHarvesterPluginInfo* retVal = NULL;
+
+	for ( TInt i = iPluginInfoArray.Count(); --i >= 0; )
+        {
+        CHarvesterPluginInfo* info = iPluginInfoArray[i];
+        TBool found = EFalse;
+        
+        for ( TInt k = info->iExtensions.Count(); --k >= 0; )
+            {
+            TDesC* ext = info->iExtensions[k];
+            
+            // checking against supported plugin file extensions
+            TInt result = ext->CompareF( aExt );
+            if ( result == 0 )
+                {
+                retVal = info;
+                found = ETrue;
+                break;
+                }
+            }
+        if ( found )
+        	{
+        	break;
+        	}
+        }
+
+    _LIT( KMsg2, "Exit GetFromNormalFileL" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+	
+	return retVal;
+	}
+
+//  [End of File] - Do not remove
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/Bmarm/MonitorPluginTestU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	LibEntryL__FR13CTestModuleIf @ 1 NONAME R3UNUSED ; LibEntryL(CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/Bwins/MonitorPluginTestU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?LibEntryL@@YAPAVCScriptBase@@AAVCTestModuleIf@@@Z @ 1 NONAME ; class CScriptBase * __cdecl LibEntryL(class CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/EABI/MonitorPluginTestU.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	_Z9LibEntryLR13CTestModuleIf @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/conf/MonitorPluginTest.cfg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,81 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  Monitor Plugin API tests
+#
+
+// ---------------------------------------------------------------------------
+// Monitor Plugin API test cases
+// ---------------------------------------------------------------------------
+
+// These should be run in sequential mode if several cases are run at the same
+// time! 
+
+[StifSettings]
+TestThreadStackSize= 32768
+TestThreadMinHeap= 4096
+TestThreadMaxHeap= 16777216
+[EndStifSettings]
+
+[Test]
+title Monitor Plugin Startup Shutdown
+timeout 60000
+create MonitorPluginTest test
+request Session
+test BeginMonitorSession
+wait Session
+test LoadPlugins
+test StartMonitoring
+test ActiveWait
+test StopMonitoring
+test EndMonitorSession
+delete test
+[Endtest]
+
+[Test]
+title Monitor Plugin Events
+timeout 60000
+create MonitorPluginTest test
+request Session
+test BeginMonitorSession
+wait Session
+test LoadPlugins
+test StartMonitoring
+request Monitor
+test CreateEvents
+test CreateEventsDelete
+wait Monitor
+test StopMonitoring
+test EndMonitorSession
+delete test
+[Endtest]
+
+[Test]
+title Monitor Events Pause Resume
+timeout 60000
+create MonitorPluginTest test
+request Session
+test BeginMonitorSession
+wait Session
+test LoadPlugins
+test StartMonitoring
+test CreateEvents
+test PauseMonitoring
+test ActiveWait
+test ResumeMonitoring
+test ActiveWait
+test ActiveWait
+test StopMonitoring
+test EndMonitorSession
+delete test
+[Endtest]
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/group/MonitorPluginTest.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET          MonitorPluginTest.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E3
+
+CAPABILITY      ALL -TCB
+VENDORID        VID_DEFAULT
+
+DEFFILE         MonitorPluginTest.DEF
+
+SOURCEPATH      ../src
+SOURCE          MonitorPluginTest.cpp
+SOURCE          MonitorPluginTestBlocks.cpp
+
+USERINCLUDE     ../inc 
+USERINCLUDE     ../../../../../inc
+SYSTEMINCLUDE 	/epoc32/include/ecom
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+LIBRARY	        ecom.lib
+LIBRARY	        harvesterdata.lib
+LIBRARY         mdeclient.lib
+LIBRARY         harvestercommon.lib
+LIBRARY         monitorplugininterface.lib bafl.lib efsrv.lib
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/group/MonitorPluginTest.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,56 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:  Installation file for API test
+;
+
+; Languages
+&EN
+
+; Header
+#{"MonitorPluginTest"},(0x101FB3E3),1,0,0,TYPE=SA
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Install files
+"\epoc32\release\armv5\urel\MonitorPluginTest.dll" - "c:\sys\bin\MonitorPluginTest.dll"
+"..\conf\MonitorPluginTest.cfg" - "c:\TestFramework\MonitorPluginTest.cfg"
+"..\init\MonitorPluginTest.ini" - "c:\TestFramework\MonitorPluginTest.ini"
+
+"..\..\data\mmc\HarvesterTest\Jpg.jpg"      -"E:\testing\data\Jpg.jpg"
+"..\..\data\mmc\HarvesterTest\Animated.gif"      -"E:\testing\data\Animated.gif"
+"..\..\data\mmc\HarvesterTest\Temp1.jpg"      -"E:\testing\data\Temp1.jpg"
+"..\..\data\mmc\HarvesterTest\Temp2.jpg"      -"E:\testing\data\Temp2.jpg"
+"..\..\data\mmc\HarvesterTest\Temp3.jpg"      -"E:\testing\data\Temp3.jpg"
+"..\..\data\mmc\HarvesterTest\H263.3gp"      -"E:\testing\data\H263.3gp"
+"..\..\data\mmc\HarvesterTest\bmp_burst.bmp"      -"E:\testing\data\bmp_burst.bmp"
+"..\..\data\mmc\HarvesterTest\GIF87testimage.gif"      -"E:\testing\data\GIF87testimage.gif"
+"..\..\data\mmc\HarvesterTest\gif89a_onemeg.gif"      -"E:\testing\data\gif89a_onemeg.gif"
+"..\..\data\mmc\HarvesterTest\Liverpool.jpg"      -"E:\testing\data\Liverpool.jpg"
+"..\..\data\mmc\HarvesterTest\MBMtestimage.mbm"      -"E:\testing\data\MBMtestimage.mbm"
+"..\..\data\mmc\HarvesterTest\wbmp_skull.wbmp"      -"E:\testing\data\wbmp_skull.wbmp"
+"..\..\data\mmc\HarvesterTest\ota_bmpiso.ota"      -"E:\testing\data\ota_bmpiso.ota"
+"..\..\data\mmc\HarvesterTest\PNGtestimage.png"      -"E:\testing\data\PNGtestimage.png"
+"..\..\data\mmc\HarvesterTest\G4.TIF"      -"E:\testing\data\G4.TIF"
+"..\..\data\mmc\HarvesterTest\G31D.TIF"      -"E:\testing\data\G31D.TIF"
+"..\..\data\mmc\HarvesterTest\PSRETRO.WMF"      -"E:\testing\data\PSRETRO.WMF"
+"..\..\data\mmc\HarvesterTest\Animated.gif"      -"E:\testing\data\Animated.gif"
+"..\..\data\mmc\HarvesterTest\Mbm.mbm"      -"E:\testing\data\Mbm.mbm"
+"..\..\data\mmc\HarvesterTest\MPEG4.3gp"      -"E:\testing\data\MPEG4.3gp"
+"..\..\data\mmc\HarvesterTest\MPEG4.mp4"      -"E:\testing\data\MPEG4.mp4"
+"..\..\data\mmc\HarvesterTest\00001.mp3"      -"E:\testing\data\00001.mp3"
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+MonitorPluginTest.mmp
+
+PRJ_TESTEXPORTS
+
+../conf/MonitorPluginTest.cfg /epoc32/winscw/c/TestFramework/MonitorPluginTest.cfg
+../init/MonitorPluginTest.ini /epoc32/winscw/c/TestFramework/MonitorPluginTest.ini
+
+../../data/mmc/HarvesterTest/bmp_burst.bmp /epoc32/WINSCW/C/Data/bmp_burst.bmp
+../../data/mmc/HarvesterTest/G31D.TIF /epoc32/WINSCW/C/Data/G31D.TIF
+../../data/mmc/HarvesterTest/G4.TIF /epoc32/WINSCW/C/Data/G4.TIF
+../../data/mmc/HarvesterTest/GIF87testimage.gif /epoc32/WINSCW/C/Data/GIF87testimage.gif
+../../data/mmc/HarvesterTest/gif89a_onemeg.gif /epoc32/WINSCW/C/Data/gif89a_onemeg.gif
+../../data/mmc/HarvesterTest/Liverpool.jpg /epoc32/WINSCW/C/Data/Liverpool.jpg
+../../data/mmc/HarvesterTest/MBMtestimage.mbm /epoc32/WINSCW/C/Data/MBMtestimage.mbm
+../../data/mmc/HarvesterTest/ota_bmpiso.ota /epoc32/WINSCW/C/Data/ota_bmpiso.ota
+../../data/mmc/HarvesterTest/PNGtestimage.png /epoc32/WINSCW/C/Data/PNGtestimage.png
+../../data/mmc/HarvesterTest/PSRETRO.WMF /epoc32/WINSCW/C/Data/PSRETRO.WMF
+../../data/mmc/HarvesterTest/wbmp_skull.wbmp /epoc32/WINSCW/C/Data/wbmp_skull.wbmp
+../../data/mmc/HarvesterTest/Jpg.jpg /epoc32/WINSCW/C/Data/Jpg.jpg
+../../data/mmc/HarvesterTest/Animated.gif /epoc32/WINSCW/C/Data/Animated.gif
+../../data/mmc/HarvesterTest/Mbm.mbm /epoc32/WINSCW/C/Data/Mbm.mbm
+../../data/mmc/HarvesterTest/H263.3gp /epoc32/WINSCW/C/Data/H263.3gp
+../../data/mmc/HarvesterTest/MPEG4.mp4 /epoc32/WINSCW/C/Data/MPEG4.mp4
+../../data/mmc/HarvesterTest/MPEG4.3gp /epoc32/WINSCW/C/Data/MPEG4.3gp
+../../data/mmc/HarvesterTest/Temp1.jpg /epoc32/WINSCW/C/Data/Temp1.jpg
+../../data/mmc/HarvesterTest/Temp2.jpg /epoc32/WINSCW/C/Data/Temp2.jpg
+../../data/mmc/HarvesterTest/Temp3.jpg /epoc32/WINSCW/C/Data/Temp3.jpg
+../../data/mmc/HarvesterTest/00001.mp3 /epoc32/WINSCW/C/Data/00001.mp3
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/inc/MonitorPluginTest.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,124 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+* ============================================================================
+*/
+
+
+#ifndef MONITORPLUGINTEST_H
+#define MONITORPLUGINTEST_H
+
+//  INCLUDES
+#include <StifLogger.h>
+#include <TestScripterInternal.h>
+#include <StifTestModule.h>
+
+//#include <f32file.h>
+#include <monitorplugin.h>
+#include "mdeharvestersession.h"
+#include <harvesterdata.h>
+
+// CONSTANTS
+// Logging path
+_LIT( KMonitorPluginTestLogPath, "\\logs\\testframework\\MonitorPluginTest\\" ); 
+// Log file
+_LIT( KMonitorPluginTestLogFile, "MonitorPluginTest.txt" ); 
+_LIT( KMonitorPluginTestLogFileWithTitle, "MonitorPluginTest_[%S].txt" );
+
+
+// FORWARD DECLARATIONS
+class CMonitorPluginTest;
+
+// CLASS DECLARATION
+NONSHARABLE_CLASS(CMonitorPluginTest) : public CScriptBase,
+										public MMonitorPluginObserver,
+										public MMdESessionObserver
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CMonitorPluginTest* NewL( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CMonitorPluginTest();
+
+    public: // Functions from base classes
+
+        /**
+        * From CScriptBase Runs a script line.
+        * @since ?Series60_version
+        * @param aItem Script line containing method name and parameters
+        * @return Symbian OS error code
+        */
+        virtual TInt RunMethodL( CStifItemParser& aItem );
+        
+    private: // Functions from base classes        
+        
+        void MonitorEvent( CHarvesterData* aHarvesterData );
+        void MonitorEvent( RPointerArray<CHarvesterData>& aHDArray );
+        
+    	void HandleSessionOpened(CMdESession& aClient, TInt aError);
+    	void HandleSessionError(CMdESession& aClient, TInt aError);
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CMonitorPluginTest( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Frees all resources allocated from test methods.
+        * @since ?Series60_version
+        */
+        void Delete();
+        
+        void ActiveWait2();
+
+        /**
+        * Test methods are listed below. 
+        */
+
+        virtual TInt ActiveWait( CStifItemParser& aItem );
+        virtual TInt BeginMonitorSessionL( CStifItemParser& aItem );
+        virtual TInt EndMonitorSession( CStifItemParser& aItem );
+        virtual TInt LoadPluginsL( CStifItemParser& aItem );
+        virtual TInt StartMonitoring( CStifItemParser& aItem );
+        virtual TInt PauseMonitoring( CStifItemParser& aItem );
+        virtual TInt ResumeMonitoring( CStifItemParser& aItem );
+        virtual TInt StopMonitoring( CStifItemParser& aItem );
+        virtual TInt CreateEventsL( CStifItemParser& aItem );
+        virtual TInt CreateEventsDeleteL( CStifItemParser& aItem );
+
+        //[TestMethods] - Do not remove
+
+    private:    // Data
+        
+        RPointerArray<CMonitorPlugin> iPluginArray;
+        CMdESession* iMdEClient;
+    };
+
+#endif      // MONITORPLUGINTEST_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/init/MonitorPluginTest.ini	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,81 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  
+#
+
+
+[Engine_Defaults]
+
+TestReportMode= FullReport    # Possible values are: 'Empty', 'Summary', 'Environment',
+                                                     'TestCases' or 'FullReport'
+
+CreateTestReport= YES         # Possible values: YES or NO
+
+TestReportFilePath= C:\LOGS\TestFramework\
+TestReportFileName= MonitorPluginTestLog
+
+TestReportFormat= TXT         # Possible values: TXT or HTML
+TestReportOutput= FILE        # Possible values: FILE or RDEBUG
+TestReportFileCreationMode= OVERWRITE # Possible values: OVERWRITE or APPEND
+
+DeviceResetDllName= StifResetForNokia.dll # e.g. 'StifHWResetStub.dll' for user specific reseting
+
+DisableMeasurement= stifmeasurementdisablenone  # Possible values are:
+              # 'stifmeasurementdisablenone', 'stifmeasurementdisableall'
+              # 'stifmeasurementplugin01', 'stifmeasurementplugin02',
+              # 'stifmeasurementplugin03', 'stifmeasurementplugin04',
+              # 'stifmeasurementplugin05' or 'stifbappeaprofiler'
+
+Timeout= 600000		            # Default timeout value for each test case. In milliseconds
+#UITestingSupport= YES        # Possible values: YES or NO
+#SeparateProcesses= YES       # Possible values: YES or NO (default: NO)
+[End_Defaults]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[New_Module]
+ModuleName= TestScripter
+TestCaseFile= c:\testframework\MonitorPluginTest.cfg
+[End_Module]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[Logger_Defaults]
+
+#NOTE: If you want to set Logger using next setting(s) remove comment(s)'#'
+#NOTE: TestEngine and TestServer logging settings cannot change here
+
+CreateLogDirectories= YES    # Possible values: YES or NO
+
+#EmulatorBasePath= C:\LOGS\TestFramework\
+#EmulatorFormat= HTML         # Possible values: TXT or HTML
+#EmulatorOutput= FILE         # Possible values: FILE or RDEBUG
+
+HardwareBasePath= C:\
+#HardwareFormat= HTML         # Possible values: TXT or HTML
+#HardwareOutput= FILE         # Possible values: FILE or RDEBUG
+
+#FileCreationMode= OVERWRITE  # Possible values: OVERWRITE or APPEND
+
+#ThreadIdToLogFile= YES       # Possible values: YES or NO
+#WithTimeStamp= YES           # Possible values: YES or NO
+#WithLineBreak= YES           # Possible values: YES or NO
+#WithEventRanking= YES        # Possible values: YES or NO
+
+#FileUnicode= YES             # Possible values: YES or NO
+AddTestCaseTitle= YES        # Possible values: YES or NO
+[End_Logger_Defaults]
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+# End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/src/MonitorPluginTest.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,132 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+// INCLUDE FILES
+#include <StifTestInterface.h>
+#include "MonitorPluginTest.h"
+#include <SettingServerClient.h>
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::CMonitorPluginTest
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CMonitorPluginTest::CMonitorPluginTest( 
+    CTestModuleIf& aTestModuleIf ):
+        CScriptBase( aTestModuleIf )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CMonitorPluginTest::ConstructL()
+    {
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        } 
+    // Close Setting server session
+    settingServer.Close();
+
+    TFileName logFileName;
+    
+    if(loggerSettings.iAddTestCaseTitle)
+        {
+        TName title;
+        TestModuleIf().GetTestCaseTitleL(title);
+        logFileName.Format(KMonitorPluginTestLogFileWithTitle, &title);
+        }
+    else
+        {
+        logFileName.Copy(KMonitorPluginTestLogFile);
+        }
+
+    iLog = CStifLogger::NewL( KMonitorPluginTestLogPath, 
+                          logFileName,
+                          CStifLogger::ETxt,
+                          CStifLogger::EFile,
+                          EFalse );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CMonitorPluginTest* CMonitorPluginTest::NewL( 
+    CTestModuleIf& aTestModuleIf )
+    {
+    CMonitorPluginTest* self = new (ELeave) CMonitorPluginTest( aTestModuleIf );
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+
+    }
+
+// Destructor
+CMonitorPluginTest::~CMonitorPluginTest()
+    { 
+
+    // Delete resources allocated from test methods
+    Delete();
+
+    // Delete logger
+    delete iLog; 
+
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point.
+// Returns: CScriptBase: New CScriptBase derived object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScriptBase* LibEntryL( 
+    CTestModuleIf& aTestModuleIf ) // Backpointer to STIF Test Framework
+    {
+
+    return ( CScriptBase* ) CMonitorPluginTest::NewL( aTestModuleIf );
+
+    }
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/MonitorPluginTest/src/MonitorPluginTestBlocks.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,580 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// [INCLUDE FILES] - do not remove
+#include <e32svr.h>
+#include <f32file.h>
+#include <bautils.h>
+#include <StifParser.h>
+#include <StifTestEventInterface.h>
+#include <StifTestInterface.h>
+#include "MonitorPluginTest.h"
+
+#include "mdsutils.h"
+
+
+_LIT( KFile1Src, "C:\\Data\\Jpg.jpg" );
+_LIT( KFile1Dst, "E:\\Images\\Jpg_copy.jpg" );
+_LIT( KFile1Dst2, "C:\\Data\\Images\\Pictures\\Jpg_copy2.jpg" );
+_LIT( KFile1Dst3, "C:\\Data\\Images\\Pictures\\Jpg_tmp.jpg" );
+_LIT( KFile1Dst4, "T:\\Images\\Jpg_copy.jpg" );
+
+_LIT( KFile2Src, "C:\\Data\\Animated.gif" );
+_LIT( KFile2Dst, "E:\\Images\\Animated_copy.gif" );
+_LIT( KFile2Dst2, "C:\\Data\\Images\\Pictures\\Animated_copy2.gif" );
+_LIT( KFile2Dst3, "C:\\Data\\Images\\Pictures\\Animated_tmp.gif" );
+_LIT( KFile2Dst4, "T:\\Images\\Animated_copy.gif" );
+
+_LIT( KFile3Src, "C:\\Data\\H263.3gp" );
+_LIT( KFile3Dst, "E:\\Videos\\H263_copy.3gp" );
+_LIT( KFile3Dst2, "C:\\Data\\H263_copy2.3gp" );
+_LIT( KFile3Dst3, "C:\\Data\\H263_tmp.3gp" );
+_LIT( KFile3Dst4, "T:\\Videos\\H263_copy.3gp" );
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::Delete
+// Delete here all resources allocated and opened from test methods. 
+// Called from destructor. 
+// -----------------------------------------------------------------------------
+//
+void CMonitorPluginTest::Delete() 
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::RunMethodL
+// Run specified method. Contains also table of test mothods and their names.
+// -----------------------------------------------------------------------------
+//
+TInt CMonitorPluginTest::RunMethodL( 
+    CStifItemParser& aItem ) 
+    {
+    TestModuleIf().SetBehavior( CTestModuleIf::ETestLeaksHandles );
+    
+    static TStifFunctionInfo const KFunctions[] =
+        {  
+        // Copy this line for every implemented function.
+        // First string is the function name used in TestScripter script file.
+        // Second is the actual implementation member function. 
+
+        ENTRY( "ActiveWait", CMonitorPluginTest::ActiveWait ),
+        ENTRY( "BeginMonitorSession", CMonitorPluginTest::BeginMonitorSessionL ),
+        ENTRY( "EndMonitorSession", CMonitorPluginTest::EndMonitorSession ),
+        ENTRY( "LoadPlugins", CMonitorPluginTest::LoadPluginsL ),
+        ENTRY( "StartMonitoring", CMonitorPluginTest::StartMonitoring ),
+        ENTRY( "PauseMonitoring", CMonitorPluginTest::PauseMonitoring ),
+        ENTRY( "ResumeMonitoring", CMonitorPluginTest::ResumeMonitoring ),
+        ENTRY( "StopMonitoring", CMonitorPluginTest::StopMonitoring ),
+        ENTRY( "CreateEvents", CMonitorPluginTest::CreateEventsL ),
+        ENTRY( "CreateEventsDelete", CMonitorPluginTest::CreateEventsDeleteL ),
+
+        };
+
+    const TInt count = sizeof( KFunctions ) / 
+                        sizeof( TStifFunctionInfo );
+
+    return RunInternalL( KFunctions, count, aItem );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::MonitorEvent
+// -----------------------------------------------------------------------------
+//
+void CMonitorPluginTest::MonitorEvent( CHarvesterData* aHarvesterData )
+    {
+    _LIT( KMsg, "CallBck MonitorEvent");
+    iLog->Log( KMsg );
+    RDebug::Print( KMsg );
+
+    switch ( aHarvesterData->EventType() )
+        {
+        case EHarvesterAdd:
+            {
+            _LIT( KAdded, "File added" );
+            iLog->Log( KAdded );
+            RDebug::Print( KAdded );
+            }
+        break;
+        
+        case EHarvesterEdit:
+            {
+            _LIT( KEdited, "File edited" );
+            iLog->Log( KEdited );
+            RDebug::Print( KEdited );
+            }
+        break;
+        
+        case EHarvesterDelete:
+            {
+            _LIT( KDeleted, "File deleted" );
+            iLog->Log( KDeleted );
+            RDebug::Print( KDeleted );
+            }
+        break;
+        
+        case EHarvesterUnknown:
+            {
+            _LIT( KUnknown, "Unknown event" );
+            iLog->Log( KUnknown );
+            RDebug::Print( KUnknown );
+            }
+        break;
+        }
+    
+    // monitor event
+    TEventIf event( TEventIf::ESetEvent, _L("Monitor") );
+    TestModuleIf().Event( event );
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::MonitorEvent
+// -----------------------------------------------------------------------------
+//
+void CMonitorPluginTest::MonitorEvent( RPointerArray<CHarvesterData>& aHDArray )
+    {
+    _LIT( KMsg, "CallBck MonitorEvent");
+    iLog->Log( KMsg );
+    RDebug::Print( KMsg );
+    
+    for( TInt i = 0; i < aHDArray.Count(); i++ )
+    	{
+    	CHarvesterData* hd = aHDArray[i];
+	    switch ( hd->EventType() )
+	        {
+	        case EHarvesterAdd:
+	            {
+	            _LIT( KAdded, " Files added." );
+	            iLog->Log( KAdded );
+	            RDebug::Print( KAdded );
+	            }
+	        break;
+	        
+	        case EHarvesterEdit:
+	            {
+	            _LIT( KEdited, " Files edited." );
+	            iLog->Log( KEdited );
+	            RDebug::Print( KEdited );
+	            }
+	        break;
+	        
+	        case EHarvesterDelete:
+	            {
+	            _LIT( KDeleted, " Files deleted." );
+	            iLog->Log( KDeleted );
+	            RDebug::Print( KDeleted );
+	            }
+	        break;
+	        
+	        case EHarvesterUnknown:
+	            {
+	            _LIT( KUnknown, "Unknown event." );
+	            iLog->Log( KUnknown );
+	            RDebug::Print( KUnknown );
+	            }
+	        break;
+	        }
+        }
+    
+    // monitor event
+    TEventIf event( TEventIf::ESetEvent, _L("Monitor") );
+    TestModuleIf().Event( event );
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::HandleSessionOpened
+// -----------------------------------------------------------------------------
+//
+void CMonitorPluginTest::HandleSessionOpened( CMdESession& /*aClient*/, TInt aError )
+    {
+    _LIT( KMsg, "CallBck HandleSessionOpened - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );     
+    RDebug::Print(msg);
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::HandleSessionError
+// -----------------------------------------------------------------------------
+//
+void CMonitorPluginTest::HandleSessionError( CMdESession& /*aClient*/, TInt aError )
+    {
+    _LIT( KMsg, "CallBck HandleSessionError - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );
+    RDebug::Print(msg);
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::ActiveWait
+// -----------------------------------------------------------------------------
+//
+TInt CMonitorPluginTest::ActiveWait( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter ActiveWait" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    // 2,5 seconds
+    TTimeIntervalMicroSeconds32 timeout( 2500000 );
+    RTimer timer;
+    TRequestStatus status;
+
+    timer.CreateLocal();
+    timer.After(status,timeout);
+
+    User::WaitForAnyRequest();
+    
+    timer.Close();
+    
+    _LIT( KMsg2, "Exit ActiveWait" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::ActiveWait
+// -----------------------------------------------------------------------------
+//
+void CMonitorPluginTest::ActiveWait2()
+    {
+    _LIT( KMsg1, "Enter ActiveWait2" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    // 2,5 seconds
+    TTimeIntervalMicroSeconds32 timeout( 2500000 );
+    RTimer timer;
+    TRequestStatus status;
+
+    timer.CreateLocal();
+    timer.After(status,timeout);
+
+    User::WaitForRequest( status);
+    
+    timer.Close();
+    
+    _LIT( KMsg2, "Exit ActiveWait2" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::BeginMonitorSessionL
+// -----------------------------------------------------------------------------
+//
+TInt CMonitorPluginTest::BeginMonitorSessionL( CStifItemParser& /* aItem */ )
+    {
+    iMdEClient = NULL;
+    TRAPD( error, iMdEClient = CMdESession::NewL( *this ) );
+
+    _LIT( KMsg, "Exit BeginMonitorSession - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format( KMsg, error);
+    iLog->Log( msg );
+    RDebug::Print( msg );
+    
+    User::LeaveIfError( error );
+    
+    return KErrNone;
+    }  
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::EndMonitorSession
+// -----------------------------------------------------------------------------
+//
+TInt CMonitorPluginTest::EndMonitorSession( CStifItemParser& /* aItem */ )
+	{
+    _LIT( KMsg1, "Enter EndMonitorSession" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+	iPluginArray.ResetAndDestroy();
+	iPluginArray.Close();
+	
+	if ( iMdEClient )
+		{
+	    delete iMdEClient;
+	    iMdEClient = NULL;
+	    }
+	
+	REComSession::FinalClose();
+	
+    _LIT( KMsg2, "Exit EndMonitorSession" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::LoadPluginsL
+// -----------------------------------------------------------------------------
+//
+TInt CMonitorPluginTest::LoadPluginsL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter LoadPlugins" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    RImplInfoPtrArray infoArray;
+    
+    TCleanupItem cleanupItem(MdsUtils::CleanupEComArray, &infoArray);
+    CleanupStack::PushL(cleanupItem);
+    
+    CMonitorPlugin::ListImplementationsL(infoArray);
+    TInt count( 0 );
+    count = infoArray.Count();
+    
+    for (TInt i=0; i < count; i++)
+        {
+        TUid uid = infoArray[i]->ImplementationUid();    // Create the plug-ins
+        iPluginArray.AppendL( CMonitorPlugin::NewL( uid ) ); // and add them to array
+        }
+        
+    CleanupStack::PopAndDestroy(&infoArray); // infoArray, results in a call to CleanupEComArray
+    
+    if( iPluginArray.Count() == 0 )
+        {
+        return KErrNotFound;
+        }
+    
+    _LIT( KMsg2, "Exit LoadPlugins" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::StartMonitoring
+// -----------------------------------------------------------------------------
+//
+TInt CMonitorPluginTest::StartMonitoring( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter StartMonitoring" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TInt count( iPluginArray.Count() );
+    
+    for (TInt i=0; i < count; i++)
+        {
+        iPluginArray[i]->StartMonitoring( *this, iMdEClient, NULL, NULL );
+        }
+    
+    _LIT( KMsg2, "Exit StartMonitoring" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::PauseMonitoring
+// -----------------------------------------------------------------------------
+//
+TInt CMonitorPluginTest::PauseMonitoring( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter PauseMonitoring" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TInt count( iPluginArray.Count() );
+    
+    for (TInt i = 0; i < count; i++ )
+        {
+        iPluginArray[i]->PauseMonitoring();
+        }
+    
+    _LIT( KMsg2, "Exit PauseMonitoring" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::ResumeMonitoring
+// -----------------------------------------------------------------------------
+//
+TInt CMonitorPluginTest::ResumeMonitoring( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter ResumeMonitoring" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TInt count( iPluginArray.Count() );
+    
+    for (TInt i=0; i < count; i++)
+        {
+        iPluginArray[i]->ResumeMonitoring( *this, iMdEClient, NULL, NULL );
+        }
+    
+    _LIT( KMsg2, "Exit ResumeMonitoring" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::StopMonitoring
+// -----------------------------------------------------------------------------
+//
+TInt CMonitorPluginTest::StopMonitoring( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter StopMonitoring" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TInt count( iPluginArray.Count() );
+    
+    for (TInt i=0; i < count; i++)
+        {
+        iPluginArray[i]->StopMonitoring();
+        }
+    
+    ActiveWait2();
+    
+    _LIT( KMsg2, "Exit StopMonitoring" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::CreateEvents
+// -----------------------------------------------------------------------------
+//
+TInt CMonitorPluginTest::CreateEventsL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter CreateEvents" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    RFs fs;
+    User::LeaveIfError( fs.Connect() );   
+    
+    BaflUtils::CopyFile( fs, KFile1Src, KFile1Dst2 );
+    BaflUtils::CopyFile( fs, KFile2Src, KFile2Dst2 );
+    BaflUtils::CopyFile( fs, KFile3Src, KFile3Dst2 ); 
+    
+    fs.Rename( KFile1Dst2, KFile1Dst3 );
+    fs.Rename( KFile2Dst2, KFile2Dst3 );
+    fs.Rename( KFile3Dst2, KFile3Dst3 );
+    
+    fs.Replace( KFile1Dst3, KFile1Dst2 );
+    fs.Replace( KFile2Dst3, KFile2Dst2 );
+    fs.Replace( KFile3Dst3, KFile3Dst2 );
+    
+    // MMC stuff
+    if( fs.IsValidDrive( EDriveE ) )
+    	{
+        fs.RemountDrive( EDriveE, NULL ,80000000 );
+        
+        iMdEClient->RemoveObjectL( KFile1Dst );
+        iMdEClient->RemoveObjectL( KFile2Dst );
+        iMdEClient->RemoveObjectL( KFile3Dst );
+        BaflUtils::DeleteFile( fs, KFile1Dst );
+        BaflUtils::DeleteFile( fs, KFile2Dst );
+        BaflUtils::DeleteFile( fs, KFile3Dst );
+        
+        BaflUtils::CopyFile( fs, KFile1Src, KFile1Dst );
+        BaflUtils::CopyFile( fs, KFile2Src, KFile2Dst );
+        BaflUtils::CopyFile( fs, KFile3Src, KFile3Dst );
+    	}
+
+    if( fs.IsValidDrive( EDriveT ) )
+        {
+        fs.RemountDrive( EDriveT, NULL ,80000000 );
+        
+        iMdEClient->RemoveObjectL( KFile1Dst4 );
+        iMdEClient->RemoveObjectL( KFile2Dst4 );
+        iMdEClient->RemoveObjectL( KFile3Dst4 );
+        BaflUtils::DeleteFile( fs, KFile1Dst4 );
+        BaflUtils::DeleteFile( fs, KFile2Dst4 );
+        BaflUtils::DeleteFile( fs, KFile3Dst4 );
+        
+        BaflUtils::CopyFile( fs, KFile1Src, KFile1Dst4 );
+        BaflUtils::CopyFile( fs, KFile2Src, KFile2Dst4 );
+        BaflUtils::CopyFile( fs, KFile3Src, KFile3Dst4 );
+        }
+    
+    fs.Close();
+    
+    _LIT( KMsg2, "Exit CreateEvents" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMonitorPluginTest::CreateEventsDelete
+// -----------------------------------------------------------------------------
+//
+TInt CMonitorPluginTest::CreateEventsDeleteL( CStifItemParser& /* aItem */ )
+    {
+    _LIT( KMsg1, "Enter CreateEventsDelete" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    RFs fs;
+    User::LeaveIfError(fs.Connect());
+    
+    iMdEClient->RemoveObjectL( KFile1Src );
+    iMdEClient->RemoveObjectL( KFile2Src );
+    iMdEClient->RemoveObjectL( KFile3Src );
+    iMdEClient->RemoveObjectL( KFile1Dst2 );
+    iMdEClient->RemoveObjectL( KFile2Dst2 );
+    iMdEClient->RemoveObjectL( KFile3Dst2 );
+    
+    BaflUtils::DeleteFile( fs, KFile1Dst2 );
+    BaflUtils::DeleteFile( fs, KFile2Dst2 );
+    BaflUtils::DeleteFile( fs, KFile3Dst2 );
+    BaflUtils::DeleteFile( fs, KFile1Dst3 );
+    BaflUtils::DeleteFile( fs, KFile2Dst3 );
+    BaflUtils::DeleteFile( fs, KFile3Dst3 );
+    
+    fs.Close();
+    
+    _LIT( KMsg2, "Exit CreateEventsDelete" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+//  [End of File] - Do not remove
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/00001.mp3 has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Animated.gif has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/G31D.TIF has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/G4.TIF has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/GIF87testimage.gif has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/H263.3gp has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Jpg.jpg has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Liverpool.jpg has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/MBMtestimage.mbm has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/MPEG4.3gp has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/MPEG4.mp4 has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Mbm.mbm has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/PNGtestimage.png has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/PSRETRO.WMF has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Temp1.jpg has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Temp2.jpg has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/Temp3.jpg has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/bmp_burst.bmp has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/gif89a_onemeg.gif has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/ota_bmpiso.ota has changed
Binary file mds_plat/harvester_framework_api/tsrc/data/mmc/HarvesterTest/wbmp_skull.wbmp has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/harvester_framework_api/tsrc/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,65 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+../ComposerPluginTest/group/ComposerPluginTest.mmp
+../HarvesterClientTest/group/HarvesterClientTestScripter.mmp
+../HarvesterDataTest/group/HarvesterDataTest.mmp
+../HarvesterPluginTest/group/HarvesterPluginTest.mmp
+../MonitorPluginTest/group/MonitorPluginTest.mmp
+
+PRJ_TESTEXPORTS
+../conf/ComposerPluginTest.cfg /epoc32/winscw/c/TestFramework/ComposerPluginTest.cfg
+../conf/HarvesterClientTestScripter.cfg /epoc32/winscw/c/TestFramework/HarvesterClientTestScripter.cfg
+../conf/HarvesterDataTest.cfg /epoc32/winscw/c/TestFramework/HarvesterDataTest.cfg
+../conf/HarvesterPluginTest.cfg /epoc32/winscw/c/TestFramework/HarvesterPluginTest.cfg
+../conf/MonitorPluginTest.cfg /epoc32/winscw/c/TestFramework/MonitorPluginTest.cfg
+
+../init/ComposerPluginTest.ini /epoc32/winscw/c/TestFramework/ComposerPluginTest.ini
+../init/HarvesterClientTestScripter.ini /epoc32/winscw/c/TestFramework/HarvesterClientTestScripter.ini
+../init/HarvesterDataTest.ini /epoc32/winscw/c/TestFramework/HarvesterDataTest.ini
+../init/HarvesterPluginTest.ini /epoc32/winscw/c/TestFramework/HarvesterPluginTest.ini
+../init/MonitorPluginTest.ini /epoc32/winscw/c/TestFramework/MonitorPluginTest.ini
+
+../data/mmc/HarvesterTest/bmp_burst.bmp /epoc32/WINSCW/C/Data/bmp_burst.bmp
+../data/mmc/HarvesterTest/G31D.TIF /epoc32/WINSCW/C/Data/G31D.TIF
+../data/mmc/HarvesterTest/G4.TIF /epoc32/WINSCW/C/Data/G4.TIF
+../data/mmc/HarvesterTest/GIF87testimage.gif /epoc32/WINSCW/C/Data/GIF87testimage.gif
+../data/mmc/HarvesterTest/gif89a_onemeg.gif /epoc32/WINSCW/C/Data/gif89a_onemeg.gif
+../data/mmc/HarvesterTest/Liverpool.jpg /epoc32/WINSCW/C/Data/Liverpool.jpg
+../data/mmc/HarvesterTest/MBMtestimage.mbm /epoc32/WINSCW/C/Data/MBMtestimage.mbm
+../data/mmc/HarvesterTest/ota_bmpiso.ota /epoc32/WINSCW/C/Data/ota_bmpiso.ota
+../data/mmc/HarvesterTest/PNGtestimage.png /epoc32/WINSCW/C/Data/PNGtestimage.png
+../data/mmc/HarvesterTest/PSRETRO.WMF /epoc32/WINSCW/C/Data/PSRETRO.WMF
+../data/mmc/HarvesterTest/wbmp_skull.wbmp /epoc32/WINSCW/C/Data/wbmp_skull.wbmp
+../data/mmc/HarvesterTest/Jpg.jpg /epoc32/WINSCW/C/Data/Jpg.jpg
+../data/mmc/HarvesterTest/Animated.gif /epoc32/WINSCW/C/Data/Animated.gif
+../data/mmc/HarvesterTest/Mbm.mbm /epoc32/WINSCW/C/Data/Mbm.mbm
+../data/mmc/HarvesterTest/H263.3gp /epoc32/WINSCW/C/Data/H263.3gp
+../data/mmc/HarvesterTest/MPEG4.mp4 /epoc32/WINSCW/C/Data/MPEG4.mp4
+../data/mmc/HarvesterTest/MPEG4.3gp /epoc32/WINSCW/C/Data/MPEG4.3gp
+../data/mmc/HarvesterTest/Temp1.jpg /epoc32/WINSCW/C/Data/Temp1.jpg
+../data/mmc/HarvesterTest/Temp2.jpg /epoc32/WINSCW/C/Data/Temp2.jpg
+../data/mmc/HarvesterTest/Temp3.jpg /epoc32/WINSCW/C/Data/Temp3.jpg
+../data/mmc/HarvesterTest/00001.mp3 /epoc32/WINSCW/C/Data/00001.mp3
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+../inc/rlocationtrail.h     MW_LAYER_PLATFORM_EXPORT_PATH(rlocationtrail.h)
+../inc/rlocationmanager.h	MW_LAYER_PLATFORM_EXPORT_PATH(rlocationmanager.h)
+../inc/locationtrailpskeys.h MW_LAYER_PLATFORM_EXPORT_PATH(locationtrailpskeys.h)
+../inc/rtracklog.h	MW_LAYER_PLATFORM_EXPORT_PATH(rtracklog.h)
+../inc/rlocationobjectmanipulator.h MW_LAYER_PLATFORM_EXPORT_PATH(rlocationobjectmanipulator.h)
+../inc/locationdatatype.h MW_LAYER_PLATFORM_EXPORT_PATH(locationdatatype.h)
+../inc/locationeventdef.h MW_LAYER_PLATFORM_EXPORT_PATH(locationeventdef.h)
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/inc/locationdatatype.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef LOCATIONDATATYPE_H_
+#define LOCATIONDATATYPE_H_
+
+#include <LbsPosition.h>
+#include <etel3rdparty.h>
+
+/*
+ * TLocationData encapsulates all location data.
+ */
+struct TLocationData
+    {
+    TPosition iPosition;
+    CTelephony::TNetworkInfoV1 iNetworkInfo;
+    TCourse iCourse;
+    TBuf<100> iCountry;
+    TUint iSatellites;
+    TReal32 iQuality;
+    };
+	    
+#endif /*LOCATIONDATATYPE_H_*/
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/inc/locationeventdef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition file for Location Manager.
+*
+*/
+
+#ifndef __LOCATIONEVENTDEF_H__
+#define __LOCATIONEVENTDEF_H__
+    
+enum TEventTypes
+	{
+	EStarted = 0,
+	EStopped,
+	ESignalChanged
+	};
+
+#endif // __LOCATIONEVENTDEF_H__
+
+// End of file.
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/inc/locationtrailpskeys.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition file for Location Trail PS keys.
+*
+*/
+
+#ifndef __LOCATIONTRAILPSKEYS_H__
+#define __LOCATIONTRAILPSKEYS_H__
+
+const TUid KPSUidLocationTrail = { 0x200071BE };
+
+/**
+ * Used by location trail, indicating location trail state changes.
+ *
+ * Possible values:
+ * 0: Location trail stopped.
+ * 1: Location trail started, waiting for valid GPS data.
+ * 2: Location trail started, searching GPS device.
+ * 3: Location trail started.
+ */
+const TUint32 KLocationTrailState = 0x00000001;
+
+
+#endif // __LOCATIONTRAILPSKEYS_H__
+
+// End of file.
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/inc/rlocationmanager.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An interface to Location Manager
+*
+*/
+
+#ifndef R_RLOCATIONMANAGER_H
+#define R_RLOCATIONMANAGER_H
+
+#include <e32base.h>
+#include <LbsPosition.h>
+#include <etel3rdparty.h>
+
+/**
+ *  Base class for Location Manager client interfaces.
+ *  @lib LocationManager.lib
+ *  @since S60 3.1
+ */
+NONSHARABLE_CLASS( RLocationManager ) : public RSessionBase
+    {
+public:
+
+    /**
+     * C++ default constructor.
+     * @since S60 3.1
+     */
+    IMPORT_C RLocationManager();
+    
+    /**
+     * Creates new session to Location Manager Server.
+     * @since S60 3.1
+     * @param None.
+     * @return KErrNone if successful.
+     */
+    IMPORT_C TInt Connect();
+    
+    /**
+     * Closes the connection with Location Manager Server
+     * @since S60 3.1
+     * @param None.
+     */
+    IMPORT_C void Close();
+
+private:
+    /**
+     * Returns the version of Location Manager.
+     */
+    TVersion Version() const;
+
+protected:
+	/**
+	 * Completes an asynchronous request with an error code.
+	 * @param aError Symbian error code
+	 */
+	void CompleteRequest(TRequestStatus& aStatus, TInt aError);
+       
+protected:
+    /**
+     * Buffer for names.
+     * Own.
+     */    
+    CBufFlat* iNameBuf;
+    };
+    
+#endif // R_RLOCATIONMANAGER_H
+
+//End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/inc/rlocationobjectmanipulator.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,106 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An interface to Location Object Manipulator.
+*
+*/
+
+#ifndef R_RLOCATIONOBJECTMANIPULATOR_H
+#define R_RLOCATIONOBJECTMANIPULATOR_H
+
+#include <locationdatatype.h>
+#include <etel3rdparty.h>
+#include <rlocationmanager.h>
+#include <LbsPosition.h> 
+
+#include "mdccommon.h"
+
+/**
+ *  RLocationObjectManipulator class is used to create, edit, copy and delete 
+ *  location context objects and tags and relationships between them 
+ *  and media items in the MdE database.
+ *
+ *  @lib LocationManager.lib
+ *  @since S60 3.2
+ */
+NONSHARABLE_CLASS( RLocationObjectManipulator ) : public RLocationManager
+    {
+
+public:	
+	/**
+	 * Creates a new location object in MdE database with given 
+	 * location data. Relationship is created between the location 
+	 * object and objects whose ID is given in the ID array.
+	 * @since S60 3.2
+     * @param aLocationData, Location data consist info for GPS 
+     * 		  and network data
+     * @param aObjectId, Create relationships with location data and 
+     * 		  given media object ID
+     * @return KErrNone if successful, otherwise one of the other 
+     *         system-wide error codes.
+	 */
+	IMPORT_C TInt CreateLocationObject( TLocationData& aLocationData,
+										TItemId aObjectId );
+	
+	/**
+	 * Creates a new location object in MdE database.
+	 * Relationship is created between the location objects whose ID is given.
+	 * Location data is taken from location trail.
+	 * @since S60 3.2
+     * @param aObjectId, Create relationships with location data and 
+     * 		  given media object ID
+     * @return KErrNone if successful, otherwise one of the other 
+     *         system-wide error codes.
+	 */
+	IMPORT_C TInt LocationSnapshot( TItemId aObjectId );
+	
+	/**
+	 * Deletes the relationship between an object and 
+	 * the location context object associated with it.
+ 	 * @since S60 3.2
+     * @param aObjId, Remove relationship from given media object ID
+     * @return KErrNone if successful, otherwise one of the other 
+     *         system-wide error codes.
+	 */
+	IMPORT_C TInt RemoveLocationObject( TItemId aObjId );
+	
+	/**
+	 * Copies location data of a media object to one or more 
+	 * media objects. If the target media object doesn’t have 
+	 * a location object associated to it, one will be created.
+ 	 * @since S60 3.2
+     * @param aSourceId, source media object ID
+     * @param aTargetIds, target media object ID
+     * @param aStatus Asynchronous request status
+	 */
+	IMPORT_C void CopyLocationData (TItemId aSourceId, 
+									RArray<TItemId>& aTargetIds,
+									TRequestStatus& aStatus);
+	/**
+	 * Copies location data of a media object to one or more 
+	 * media objects. If the target media object doesn’t have 
+	 * a location object associated to it, one will be created.
+  	 * @since S60 3.2
+     * @param aSourceURI, source media object URI
+     * @param aTargetURIs, target media object URI
+     * @param aStatus Asynchronous request status
+	 */
+	IMPORT_C void CopyLocationData (TDesC& aSourceURI, 
+									RPointerArray<TDesC>& aTargetURIs,
+									TRequestStatus& aStatus);
+    };
+    
+    
+#endif // R_RLOCATIONOBJECTMANIPULATOR_H
+
+//End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/inc/rlocationtrail.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,158 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An interface to Location Trail.
+*
+*/
+
+#ifndef R_RLOCATIONTRAIL_H
+#define R_RLOCATIONTRAIL_H
+
+#include <e32base.h>
+#include <etel3rdparty.h>
+#include <LbsPosition.h>
+#include <rlocationmanager.h>
+#include <locationdatatype.h>
+
+typedef TPckg<TLocality> TLocalityPckg;
+
+/**
+ *  RLocationManager class is used for creating a Location Manager session.
+ *  Location Manager is used to start and stop the location trail, retrieve 
+ *  location information and write the location information to images.
+ *
+ *  @lib LocationManager.lib
+ *  @since S60 3.1
+ */
+NONSHARABLE_CLASS( RLocationTrail ) : public RLocationManager
+    {
+public:
+    /**
+     * Location trail states.
+     */
+    enum TTrailState
+        {
+        ETrailStopped,
+        EWaitingGPSData,
+        ESearchingGPS,
+        ETrailStarted,
+        ETrailStopping,
+        ETrailStarting
+        };
+    enum TTrailCaptureSetting
+    	{
+    	EOff,
+    	ECaptureNetworkInfo,
+    	ECaptureAll 
+    	};
+        
+public:
+	IMPORT_C RLocationTrail();
+	
+	IMPORT_C ~RLocationTrail();
+
+    /**
+     * Starts recording location information to location trail.
+     * @since S60 3.2
+     * @param aState, an enumeration of ECaptureNetworkInfo  
+     * (only cell ID stored) and ECaptureAll 
+     * (GPS coordinates and cell ID stored).
+     * @return KErrNone if successful, otherwise one of the other 
+     *         system-wide error codes.
+     */
+    IMPORT_C TInt StartLocationTrail(TTrailCaptureSetting aState);
+    
+    /**
+     * Stops recording location information to location trail.
+     * @since S60 3.1
+     * @param None.
+     * @return KErrNone if successful, otherwise one of the other 
+     *         system-wide error codes.
+     */
+    IMPORT_C TInt StopLocationTrail();
+    
+    /**
+     * Retuns the current state of the location trail.
+     * @since S60 3.1
+     * @param aState, The state of the trail is returned.
+     * @return KErrNone if successful, otherwise one of the other 
+     *         system-wide error codes.
+     */
+    IMPORT_C TInt GetLocationTrailState( TTrailState& aState );
+    
+    /**
+     * Get notification when the location trail state changes.
+     * @since S60 3.1
+     * @param aStatus, The request status. 
+     * @return None.
+     */
+    IMPORT_C void NotifyLocationTrailStateChange( TRequestStatus& aStatus ); 
+    
+    /**
+     * Cancel notification request for the location trail state change.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */
+    IMPORT_C void CancelNotificationRequest();    
+    
+    /**
+     * Get location by time stamp. If the TLocality for given time stamp is 
+     * found from the trail, it is returned even if the data in it wouldn't 
+     * be valid.
+     * @since S60 3.1
+     * @param aTimeStamp, Time stamp to get corresponding location.
+     * @param aPosition, Position value returned.
+     * @param aNetworkInfo, Network value returned.
+     * @param aState, State of the trail at given time.
+     * @return KErrNone if successful, otherwise one of the other 
+     *         system-wide error codes.
+     */                                
+    IMPORT_C TInt RetrieveLocation( const TTime& aTimeStamp, 
+    								TLocationData& aLocationData,
+                                    TTrailState& aState );
+
+    /**
+     * Retrieve current location. If request is completed successfully, the 
+     * result is returned via the aLocationInfo and aNetworkInfo arguments. 
+     * The function is asynchronous, because it may take 
+     * several minutes to get location information. 
+     * @since S60 3.2
+     * @param aStatus, The request status.
+     * @param aLocationData, locationData encapsulates all location data
+     * @return None.
+     */
+    IMPORT_C void CurrentLocation( TRequestStatus& aStatus, 
+    							   TLocationData& aLocationData);					
+                                   
+    /**
+     * Cancel asynchronous location request.
+     * @since S60 3.1
+     * @param None.
+     * @return None.
+     */
+    IMPORT_C void CancelLocationRequest();
+
+    /**
+     * Get current trail capture setting.
+     * @return EOff, ECaptureNetworkInfo or ECaptureAll
+     */
+    IMPORT_C TInt GetTrailCaptureSetting( TTrailCaptureSetting& aCaptureSetting );
+    
+private:
+	TPckg<TLocationData>* iCurrentLocData;
+    };
+    
+#endif // R_RLOCATIONTRAIL_H
+
+//End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/inc/rtracklog.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,199 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An interface to Track Log.
+*
+*/
+
+#ifndef RTRACKLOG_H_
+#define RTRACKLOG_H_
+
+#include <LbsSatellite.h> 
+#include <rlocationmanager.h>
+#include <locationeventdef.h>
+
+// forward declaration
+class MTrackLogObserver;
+class CTrackLogObserverAO;
+
+/*
+ *  TrackLog API is used to start, stop and delete track-logs, 
+ *  to get track-log status and to get track-log in GPX format. 
+ * 
+ *  @lib LocationManager.lib
+ *  @since S60 3.2
+ */
+NONSHARABLE_CLASS( RTrackLog ) : public RLocationManager
+{
+
+public:
+	IMPORT_C RTrackLog();
+	
+	/**
+	 * Starts track-log recording. Also starts location trail recording 
+	 * if it is not already running.
+	 * @since S60 3.2
+	 * @param None.
+	 * @return KErrNone if successful, otherwise one of the other 
+     *       system-wide error codes.
+	 */ 
+	IMPORT_C TInt StartTrackLog();
+	
+	/**
+	 * Stops track-log recording.
+	 * @since S60 3.2
+	 * @param None.
+	 * @return None.
+	 */ 
+	IMPORT_C void StopTrackLog();
+	
+	/**
+	 * Gets the status of track-log recording and GPS signal quality.
+	 * @since S60 3.2
+	 * @param aRecording, indicating track log recording status
+	 * @param aFixQuality, GPS signal quality
+	 * @return KErrNone if successful, otherwise one of the other 
+     *       system-wide error codes.
+	 */ 
+	IMPORT_C TInt GetStatus(TBool& aRecording, TPositionSatelliteInfo& aFixQuality);
+
+	/**
+	 * Deletes a track-log file
+	 * @since S60 3.2
+	 * @param aUri, Track log URI
+	 * @return KErrNone if successful, otherwise one of the other 
+     *       system-wide error codes.
+	 */ 
+	IMPORT_C TInt DeleteTrackLog(TDesC& aUri);
+	
+	/**
+	 * Returns a boolean indicating track-log recording status.
+	 * @since S60 3.2
+	 * @param None.
+	 * @return KErrNone if successful, otherwise one of the other 
+     *       system-wide error codes.
+	 */ 
+	IMPORT_C TBool IsRecording();
+	
+	/**
+	 * Registers a new track-log observer.
+	 * @since S60 3.2
+	 * @param aObserver, observer which is added.
+	 * @return KErrNone if successful, otherwise one of the other 
+     *       system-wide error codes.
+	 */
+	IMPORT_C TInt AddObserver(MTrackLogObserver* aObserver );
+	
+	/**
+	 * Removes a registered track-log observer.
+	 * @since S60 3.2
+	 * @param aObserver, observer which is removed.
+	 * @return KErrNone if successful, otherwise one of the other 
+     *       system-wide error codes.
+	 */
+	IMPORT_C TInt RemoveObserver(MTrackLogObserver* aObserver);
+	
+	/**
+	 * Returns the name of the current track-log file.
+	 * @since S60 3.2
+	 * @param aTrackLogName, track log file name
+	 * @return KErrNone if successful, otherwise one of the other 
+     *       system-wide error codes.
+	 */
+	IMPORT_C TInt TrackLogName(TDes& aTrackLogName);
+	
+	/**
+	 * Overrides inherited class close.
+	 * Close observers array and calls main class close.
+	 * @since S60 3.2
+	 * @param None.
+	 * @return None.
+	 */ 
+	IMPORT_C void Close();
+	
+public:
+	
+	/**
+	 * @param aStatus, the request status of the active object
+	 * @return None.
+	 */	
+	void SendNotifyRequest( TRequestStatus& aStatus );
+	
+	/**
+	 * Notifies of an event in tracklog. The event can be of type EStarted/EStopped/ESignalChanged.
+	 * @param aError error code
+	 * @return None.
+	 */
+	void TrackLogEvent( TInt aError );
+
+	
+private:
+	/**
+	 * Array of observers
+	 */ 
+	RPointerArray<MTrackLogObserver> iObservers;
+	
+	TBool iSubscribed;
+	/**
+	 * An active object that observes tracklog events (starting/stopping/GPS fix quality changes).
+	 */
+	CTrackLogObserverAO* iTrackLogObserverAO;
+	
+	TPositionSatelliteInfo iFixQuality;
+	TBool iRecording;
+	TEventTypes iEventType;
+	TPckg<TPositionSatelliteInfo> iWrapQuality;
+	TPckg<TBool> iWrapRec;
+	TPckg<TEventTypes> iWrapEventType;
+};
+
+/**
+ * Track log Observer interface class for receiving track-log events.
+ */ 
+class MTrackLogObserver
+{
+
+public:
+	/**
+	 * Called to notify the observer that the 
+	 * Track-log recording has started.
+	 * 
+	 * @param aError, KErrNone if successful, otherwise one of the other 
+     *       system-wide error codes.
+	 * @return None.
+	 */ 
+	virtual void TrackLogStarted(TInt aError) = 0;
+	
+	/**
+	 * Called to notify the observer that the 
+	 * Track-log recording was stopped.
+	 * 
+	 * @param aError, KErrNone if successful, otherwise one of the other 
+     *       system-wide error codes.
+	 * @return None.
+	 */ 
+	virtual void TrackLogStopped(TInt aError) = 0;
+	
+	/**
+	 * Called to notify the observer that the 
+	 * GPS fix quality has changed.
+	 * 
+	 * @param aFixQuality, GPS signal quality
+	 * @param aTrackingActive, Is Tracking active
+	 * @return None.
+	 */ 
+	virtual void GPSFixQualityChanged(TPositionSatelliteInfo& aFixQuality, TBool& aTrackingActive) = 0;
+	
+private:
+};
+#endif /*RTRACKLOG_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/location_manager_api.metaxml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,14 @@
+<?xml version="1.0" ?>
+<api id="7d59f9853e37a9240848507a1fc9562d" dataversion="2.0">
+<name>location_manager_api</name>
+<description>location manager api</description>
+<type>c++</type>
+<collection>locationmanager</collection>
+<libs><lib name="locationmanager.lib"/>
+</libs>
+<release category="platform" sinceversion=""/>
+<attributes>
+<htmldocprovided>no</htmldocprovided>
+<adaptation>no</adaptation>
+</attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/tsrc/Bmarm/LocationManagerTestScripterU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	LibEntryL__FR13CTestModuleIf @ 1 NONAME R3UNUSED ; LibEntryL(CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/tsrc/Bwins/LocationManagerTestScripterU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?LibEntryL@@YAPAVCScriptBase@@AAVCTestModuleIf@@@Z @ 1 NONAME ; class CScriptBase * __cdecl LibEntryL(class CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/tsrc/EABI/LocationManagerTestScripterU.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	_Z9LibEntryLR13CTestModuleIf @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/tsrc/conf/LocationManagerTestScripter.cfg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,272 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  Location Manager API tests
+#
+
+// ---------------------------------------------------------------------------
+// Location Manager API test cases
+// ---------------------------------------------------------------------------
+
+// These should be run in sequential mode if several cases are run at the same
+// time! 
+
+[StifSettings]
+TestThreadStackSize= 32768
+TestThreadMinHeap= 4096
+TestThreadMaxHeap= 16777216
+[EndStifSettings]
+
+[Test]
+title Location Manager Connect Disconnect
+timeout 60000
+create LocationManagerTestScripter test
+test Connect
+test Close
+delete test
+[Endtest] 
+
+[Test]
+title Location Trail Connect Disconnect
+timeout 60000
+create LocationManagerTestScripter test
+test TrailConnect
+test TrailClose
+delete test
+[Endtest] 
+
+[Test]
+title Start-Stop Location Trail
+timeout 60000
+create LocationManagerTestScripter test
+test TrailConnect
+test StartTrailTests
+test TrailClose
+delete test
+[Endtest] 
+
+[Test]
+title Get Location Trail State
+timeout 60000
+create LocationManagerTestScripter test
+test TrailConnect
+test StartTrail
+test GetTrailState
+test StopTrail
+test TrailClose
+delete test
+[Endtest] 
+
+[Test]
+title Location Trail Notification Basic Test
+timeout 60000
+create LocationManagerTestScripter test
+test TrailConnect
+test StartTrail
+test LocationTrailNotifyTest
+test StopTrail
+test TrailClose
+delete test
+[Endtest] 
+
+[Test]
+title Retrieve Location Basic Test
+timeout 60000
+create LocationManagerTestScripter test
+test TrailConnect
+test StartTrail
+test RetrieveLocation
+test StopTrail
+test TrailClose
+delete test
+[Endtest] 
+
+[Test]
+title Current Location Basic Test
+timeout 60000
+create LocationManagerTestScripter test
+test TrailConnect
+test StartTrail
+test CurrentLocation
+test StopTrail
+test TrailClose
+delete test
+[Endtest] 
+
+[Test]
+title Create Location Object Manipulator
+timeout 60000
+create LocationManagerTestScripter test
+request Session
+test PrepareSession
+wait Session
+test TearDownOM
+delete test
+[Endtest] 
+
+[Test]
+title Create Location Object 
+timeout 60000
+create LocationManagerTestScripter test
+request Session
+test PrepareSession
+wait Session
+test SetupOM
+test TearDownOM
+delete test
+[Endtest] 
+
+[Test]
+title Location Snapshot
+timeout 60000
+create LocationManagerTestScripter test
+request Session
+test PrepareSession
+wait Session
+test SetupOM
+test TearDownOM
+delete test
+[Endtest] 
+
+[Test]
+title Remove Location Object 
+timeout 60000
+create LocationManagerTestScripter test
+request Session
+test PrepareSession
+wait Session
+test SetupOM
+test TearDownOM
+delete test
+[Endtest] 
+
+[Test]
+title Copy By ID
+timeout 60000
+create LocationManagerTestScripter test
+request Session
+test PrepareSession
+wait Session
+test SetupOM
+test CopyByID
+test CloseOM
+test CopyByIDDisco
+test TearDownOM
+delete test
+[Endtest]
+
+[Test]
+title Copy By URI
+timeout 60000
+create LocationManagerTestScripter test
+request Session
+test PrepareSession
+wait Session
+test SetupOM
+test CopyByURI
+test CloseOM
+test CopyByURIDisco
+test TearDownOM
+delete test
+[Endtest]
+
+[Test]
+title Tracklog Connect Disconnect
+timeout 60000
+create LocationManagerTestScripter test
+test SetupTrackLog
+test TearDownTrackLog
+delete test
+[Endtest] 
+
+[Test]
+title Tracklog Observer test
+timeout 60000
+create LocationManagerTestScripter test
+test SetupTrackLog
+test AddObserver
+test AddObserver
+test AddObserver
+test RemoveObserver
+test RemoveObserver
+test TearDownTrackLog
+delete test
+[Endtest]
+
+[Test]
+title Start Stop Tracklog Recording
+timeout 60000
+create LocationManagerTestScripter test
+test SetupTrackLog
+test AddObserver
+request Recording
+test StartTrackLog
+wait Recording
+test Recording
+request StopRecording
+test StopTrackLog
+wait StopRecording
+test NotRecording
+test RemoveObserver
+test TearDownTrackLog
+delete test
+[Endtest] 
+
+[Test]
+title Start Stop Tracklog Recording 2
+timeout 60000
+create LocationManagerTestScripter test
+test SetupTrackLog
+test AddObserver
+request Recording
+test StartTrackLog
+wait Recording
+test Recording
+test GetFile
+test GetStatus
+request StopRecording
+test StopTrackLog
+wait StopRecording
+test NotRecording
+test DeleteFile
+test GetStatus2
+test RemoveObserver
+test TearDownTrackLog
+delete test
+[Endtest] 
+
+[Test]
+title Tracklog Crash Test
+timeout 60000
+create LocationManagerTestScripter test
+test SetupTrackLog
+test AddObserver
+request Recording
+test StartTrackLog
+wait Recording
+test CrashLocationManager
+test RemoveObserver
+test TearDownTrackLog
+delete test
+create LocationManagerTestScripter test2
+test2 SetupTrackLog
+test2 AddObserver
+request Recording
+test2 StartTrackLog
+wait Recording
+test2 StopTrackLog
+test2 RemoveObserver
+test2 TearDownTrackLog
+delete test2
+[Endtest]
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/tsrc/group/LocationManagerTestScripter.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET          LocationManagerTestScripter.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E3
+
+CAPABILITY      ALL -TCB
+VENDORID        VID_DEFAULT
+
+DEFFILE         LocationManagerTestScripter.DEF
+
+SOURCEPATH      ../src
+SOURCE          LocationManagerTestScripter.cpp
+SOURCE          LocationManagerTestScripterBlocks.cpp
+SOURCE	    RTrackLogTest.cpp
+SOURCE	    RLocationObjectManipulatorTest.cpp
+
+USERINCLUDE     ../inc 
+USERINCLUDE		../../../../locationmanager/inc
+USERINCLUDE		../../../../locationmanager/server/inc
+USERINCLUDE		../../../../locationmanager/locationtrail/inc
+USERINCLUDE		../../../../inc
+USERINCLUDE		../../../../mds_plat/location_manager_api/inc
+USERINCLUDE		../../../../metadataengine/server/inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         	euser.lib
+LIBRARY         	stiftestinterface.lib
+LIBRARY         	stiftestengine.lib
+LIBRARY		  locationmanager.lib 
+LIBRARY     mdeclient.lib 
+LIBRARY     mdccommon.lib 
+LIBRARY     etel3rdparty.lib 
+LIBRARY     lbs.lib
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/tsrc/group/LocationManagerTestScripter.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,33 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:  Installation file for API test
+;
+
+; Languages
+&EN
+
+; Header
+#{"LocationManagerTest"},(0x101FB3E3),1,0,0,TYPE=SA
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Install files
+"\epoc32\release\armv5\urel\LocationManagerTestScripter.dll" - "c:\sys\bin\LocationManagerTestScripter.dll"
+"..\conf\LocationManagerTestScripter.cfg" - "c:\TestFramework\LocationManagerTestScripter.cfg"
+"..\init\LocationManagerTestScripter.ini" - "c:\TestFramework\LocationManagerTestScripter.ini"
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/tsrc/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+LocationManagerTestScripter.mmp
+
+PRJ_TESTEXPORTS
+../conf/LocationManagerTestScripter.cfg /epoc32/winscw/c/TestFramework/LocationManagerTestScripter.cfg
+../init/LocationManagerTestScripter.ini /epoc32/winscw/c/TestFramework/LocationManagerTestScripter.ini
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/tsrc/inc/LocationManagerTestScripter.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,163 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef LOCATIONMANAGERTESTSCRIPTER_H
+#define LOCATIONMANAGERTESTSCRIPTER_H
+
+//  INCLUDES
+#include <StifLogger.h>
+#include <TestScripterInternal.h>
+#include <StifTestModule.h>
+#include <locationeventdef.h>
+#include <rlocationtrail.h>
+#include <rtracklog.h>
+#include "locationmanagerdefs.h"
+#include "rlocationobjectmanipulator.h"
+#include "mdccommon.h"
+#include "mdesession.h"
+
+// CONSTANTS
+// Logging path
+_LIT( KLocationManagerTestScripterLogPath, "\\logs\\testframework\\LocationManagerTestScripter\\" ); 
+// Log file
+_LIT( KLocationManagerTestScripterLogFile, "LocationManagerTestScripter.txt" ); 
+_LIT( KLocationManagerTestScripterLogFileWithTitle, "LocationManagerTestScripter_[%S].txt" );
+
+
+// FORWARD DECLARATIONS
+class CMdEObject;
+class CLocationManagerTestScripter;
+
+
+// CLASS DECLARATION
+NONSHARABLE_CLASS(CLocationManagerTestScripter) : public CScriptBase,
+												  public MTrackLogObserver,
+												  public MMdESessionObserver
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CLocationManagerTestScripter* NewL( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CLocationManagerTestScripter();
+
+    public: // Functions from base classes
+
+        /**
+        * From CScriptBase Runs a script line.
+        * @since ?Series60_version
+        * @param aItem Script line containing method name and parameters
+        * @return Symbian OS error code
+        */
+        virtual TInt RunMethodL( CStifItemParser& aItem );
+ 
+    public: // From MdESessionObserver
+		virtual void HandleSessionOpened(CMdESession& aSession, TInt aError);
+		virtual void HandleSessionError(CMdESession& aSession, TInt aError);
+		
+		virtual void GPSFixQualityChanged(TPositionSatelliteInfo& aFixQuality, 
+		                                                        TBool& aTrackingActive );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CLocationManagerTestScripter( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Frees all resources allocated from test methods.
+        */
+        void Delete();
+
+        CMdEObject* CreateMetadataObjectL();
+        void TestLocationData( TLocationData& aLocationData );
+        
+        TInt PrepareSessionL( CStifItemParser& aItem );
+        TInt SetupOML( CStifItemParser& aItem );
+        TInt LocationSnapshotL( CStifItemParser& aItem );
+        TInt RemoveLocationObjectL( CStifItemParser& aItem );
+        TInt TearDownOML( CStifItemParser& aItem );
+        TInt CloseOML( CStifItemParser& aItem );
+        virtual TInt RLocationObjectManipulatorTest_CopyByIDL( CStifItemParser& aItem );
+        virtual TInt RLocationObjectManipulatorTest_CopyByURIL( CStifItemParser& aItem );
+        TInt RLocationObjectManipulatorTest_CopyByURI_DisconnectedL( CStifItemParser& aItem );
+        TInt RLocationObjectManipulatorTest_CopyByID_DisconnectedL( CStifItemParser& aItem );
+        
+        virtual TInt ConnectL( CStifItemParser& aItem );
+        virtual TInt CloseL( CStifItemParser& aItem );
+        virtual TInt TrailConnectL( CStifItemParser& aItem );
+        virtual TInt TrailCloseL( CStifItemParser& aItem );
+        virtual TInt StartTrailL( CStifItemParser& aItem );
+        virtual TInt StopTrailL( CStifItemParser& aItem );
+        virtual TInt StartTrailTestsL( CStifItemParser& aItem );
+        virtual TInt GetTrailStateL( CStifItemParser& aItem );
+        virtual TInt LocationTrailNotifyTestL( CStifItemParser& aItem );
+        virtual TInt RetrieveLocationL( CStifItemParser& aItem );
+        virtual TInt CurrentLocationL( CStifItemParser& aItem );
+        
+        TInt SetupTrackLogL( CStifItemParser& aItem );
+        TInt TearDownTrackLog( CStifItemParser& aItem );
+        TInt RTrackLogTest_AddObserverL( CStifItemParser& aItem );
+        TInt RTrackLogTest_RemoveObserverL( CStifItemParser& aItem );
+        virtual TInt RTrackLogTest_StartTrackLogL( CStifItemParser& aItem );
+        virtual TInt RTrackLogTest_RecordingL( CStifItemParser& aItem );
+        virtual TInt RTrackLogTest_StopTrackLogL( CStifItemParser& aItem );
+        virtual TInt RTrackLogTest_NotRecordingL( CStifItemParser& aItem );
+        TInt CrashLocationManagerL( CStifItemParser& aItem );
+        TInt GetFileL( CStifItemParser& aItem );
+        TInt DeleteFileL( CStifItemParser& aItem );
+        TInt GetStatusL( CStifItemParser& aItem );
+        TInt GetStatus2L( CStifItemParser& aItem );
+        //ADD NEW METHOD DEC HERE
+        //[TestMethods] - Do not remove
+        
+    public: // From MTrackLogObserver
+    	void TrackLogStarted(TInt aError);
+    	void TrackLogStopped(TInt aError);
+
+    private:    // Data
+        
+        RLocationManager iLocationManager;
+        RLocationTrail iLocationTrail;
+        
+     	TBool iRunning;
+     	RTrackLog iTrackLog;
+     	RLocationObjectManipulator iOM;
+     	
+     	CMdEObject* iSourceObject;
+     	CMdEObject* iTargetObject;
+     	CMdESession* iMdeSession;
+     	
+     	CActiveSchedulerWait* iASW;
+
+    };
+
+#endif      // LOCATIONMANAGERTESTSCRIPTER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/tsrc/init/LocationManagerTestScripter.ini	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,81 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  
+#
+
+
+[Engine_Defaults]
+
+TestReportMode= FullReport    # Possible values are: 'Empty', 'Summary', 'Environment',
+                                                     'TestCases' or 'FullReport'
+
+CreateTestReport= YES         # Possible values: YES or NO
+
+TestReportFilePath= C:\LOGS\TestFramework\
+TestReportFileName= LocationManagerTestScripterLog
+
+TestReportFormat= TXT         # Possible values: TXT or HTML
+TestReportOutput= FILE        # Possible values: FILE or RDEBUG
+TestReportFileCreationMode= OVERWRITE # Possible values: OVERWRITE or APPEND
+
+DeviceResetDllName= StifResetForNokia.dll # e.g. 'StifHWResetStub.dll' for user specific reseting
+
+DisableMeasurement= stifmeasurementdisablenone  # Possible values are:
+              # 'stifmeasurementdisablenone', 'stifmeasurementdisableall'
+              # 'stifmeasurementplugin01', 'stifmeasurementplugin02',
+              # 'stifmeasurementplugin03', 'stifmeasurementplugin04',
+              # 'stifmeasurementplugin05' or 'stifbappeaprofiler'
+
+Timeout= 600000		            # Default timeout value for each test case. In milliseconds
+#UITestingSupport= YES        # Possible values: YES or NO
+#SeparateProcesses= YES       # Possible values: YES or NO (default: NO)
+[End_Defaults]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[New_Module]
+ModuleName= TestScripter
+TestCaseFile= c:\testframework\LocationManagerTestScripter.cfg
+[End_Module]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[Logger_Defaults]
+
+#NOTE: If you want to set Logger using next setting(s) remove comment(s)'#'
+#NOTE: TestEngine and TestServer logging settings cannot change here
+
+CreateLogDirectories= YES    # Possible values: YES or NO
+
+#EmulatorBasePath= C:\LOGS\TestFramework\
+#EmulatorFormat= HTML         # Possible values: TXT or HTML
+#EmulatorOutput= FILE         # Possible values: FILE or RDEBUG
+
+HardwareBasePath= C:\
+#HardwareFormat= HTML         # Possible values: TXT or HTML
+#HardwareOutput= FILE         # Possible values: FILE or RDEBUG
+
+#FileCreationMode= OVERWRITE  # Possible values: OVERWRITE or APPEND
+
+#ThreadIdToLogFile= YES       # Possible values: YES or NO
+#WithTimeStamp= YES           # Possible values: YES or NO
+#WithLineBreak= YES           # Possible values: YES or NO
+#WithEventRanking= YES        # Possible values: YES or NO
+
+#FileUnicode= YES             # Possible values: YES or NO
+AddTestCaseTitle= YES        # Possible values: YES or NO
+[End_Logger_Defaults]
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+# End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/tsrc/src/LocationManagerTestScripter.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,132 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+// INCLUDE FILES
+#include <StifTestInterface.h>
+#include "LocationManagerTestScripter.h"
+#include <SettingServerClient.h>
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::CLocationManagerTestScripter
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CLocationManagerTestScripter::CLocationManagerTestScripter( 
+    CTestModuleIf& aTestModuleIf ):
+        CScriptBase( aTestModuleIf )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CLocationManagerTestScripter::ConstructL()
+    {
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        } 
+    // Close Setting server session
+    settingServer.Close();
+
+    TFileName logFileName;
+    
+    if(loggerSettings.iAddTestCaseTitle)
+        {
+        TName title;
+        TestModuleIf().GetTestCaseTitleL(title);
+        logFileName.Format(KLocationManagerTestScripterLogFileWithTitle, &title);
+        }
+    else
+        {
+        logFileName.Copy(KLocationManagerTestScripterLogFile);
+        }
+
+    iLog = CStifLogger::NewL( KLocationManagerTestScripterLogPath, 
+                          logFileName,
+                          CStifLogger::ETxt,
+                          CStifLogger::EFile,
+                          EFalse );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CLocationManagerTestScripter* CLocationManagerTestScripter::NewL( 
+    CTestModuleIf& aTestModuleIf )
+    {
+    CLocationManagerTestScripter* self = new (ELeave) CLocationManagerTestScripter( aTestModuleIf );
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+
+    }
+
+// Destructor
+CLocationManagerTestScripter::~CLocationManagerTestScripter()
+    { 
+
+    // Delete resources allocated from test methods
+    Delete();
+
+    // Delete logger
+    delete iLog; 
+
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point.
+// Returns: CScriptBase: New CScriptBase derived object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScriptBase* LibEntryL( 
+    CTestModuleIf& aTestModuleIf ) // Backpointer to STIF Test Framework
+    {
+
+    return ( CScriptBase* ) CLocationManagerTestScripter::NewL( aTestModuleIf );
+
+    }
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/tsrc/src/LocationManagerTestScripterBlocks.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,347 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+// [INCLUDE FILES] - do not remove
+#include <e32svr.h>
+#include <StifParser.h>
+#include <StifTestInterface.h>
+#include "LocationManagerTestScripter.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::Delete
+// Delete here all resources allocated and opened from test methods. 
+// Called from destructor. 
+// -----------------------------------------------------------------------------
+//
+void CLocationManagerTestScripter::Delete() 
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::RunMethodL
+// Run specified method. Contains also table of test mothods and their names.
+// -----------------------------------------------------------------------------
+//
+TInt CLocationManagerTestScripter::RunMethodL( 
+    CStifItemParser& aItem ) 
+    {
+
+    TestModuleIf().SetBehavior( CTestModuleIf::ETestLeaksRequests );
+    
+    static TStifFunctionInfo const KFunctions[] =
+        {  
+        // Copy this line for every implemented function.
+        // First string is the function name used in TestScripter script file.
+        // Second is the actual implementation member function. 
+        ENTRY( "Connect", CLocationManagerTestScripter::ConnectL ),
+        ENTRY( "Close", CLocationManagerTestScripter::CloseL ),     
+        ENTRY( "TrailConnect", CLocationManagerTestScripter::TrailConnectL ),
+        ENTRY( "TrailClose", CLocationManagerTestScripter::TrailCloseL ),    
+        ENTRY( "StartTrail", CLocationManagerTestScripter::StartTrailL ),
+        ENTRY( "StopTrail", CLocationManagerTestScripter::StopTrailL ),    
+        ENTRY( "StartTrailTests", CLocationManagerTestScripter::StartTrailTestsL ),    
+        ENTRY( "GetTrailState", CLocationManagerTestScripter::GetTrailStateL ), 
+        ENTRY( "LocationTrailNotifyTest", CLocationManagerTestScripter::LocationTrailNotifyTestL ),  
+        ENTRY( "RetrieveLocation", CLocationManagerTestScripter::RetrieveLocationL ),  
+        ENTRY( "CurrentLocation", CLocationManagerTestScripter::CurrentLocationL ),  
+                
+        ENTRY( "PrepareSession", CLocationManagerTestScripter::PrepareSessionL ),
+        ENTRY( "SetupOM", CLocationManagerTestScripter::SetupOML ),
+        ENTRY( "LocationSnapshot", CLocationManagerTestScripter::LocationSnapshotL ),
+        ENTRY( "RemoveLocationObject", CLocationManagerTestScripter::RemoveLocationObjectL ),
+        ENTRY( "TearDownOM", CLocationManagerTestScripter::TearDownOML ),
+        ENTRY( "CloseOM", CLocationManagerTestScripter::CloseOML ),
+        ENTRY( "CopyByID", CLocationManagerTestScripter::RLocationObjectManipulatorTest_CopyByIDL ),
+        ENTRY( "CopyByURI", CLocationManagerTestScripter::RLocationObjectManipulatorTest_CopyByURIL ),
+        ENTRY( "CopyByIDDisco", CLocationManagerTestScripter::RLocationObjectManipulatorTest_CopyByID_DisconnectedL),
+        ENTRY( "CopyByURIDisco", CLocationManagerTestScripter::RLocationObjectManipulatorTest_CopyByURI_DisconnectedL),
+        
+        ENTRY( "SetupTrackLog", CLocationManagerTestScripter::SetupTrackLogL ),
+        ENTRY( "TearDownTrackLog", CLocationManagerTestScripter::TearDownTrackLog ),
+        ENTRY( "AddObserver", CLocationManagerTestScripter::RTrackLogTest_AddObserverL ),
+        ENTRY( "RemoveObserver", CLocationManagerTestScripter::RTrackLogTest_RemoveObserverL ),
+        ENTRY( "StartTrackLog", CLocationManagerTestScripter::RTrackLogTest_StartTrackLogL ),
+        ENTRY( "Recording", CLocationManagerTestScripter::RTrackLogTest_RecordingL ),
+        ENTRY( "StopTrackLog", CLocationManagerTestScripter::RTrackLogTest_StopTrackLogL ),
+        ENTRY( "NotRecording", CLocationManagerTestScripter::RTrackLogTest_NotRecordingL ),
+        ENTRY( "CrashLocationManager" , CLocationManagerTestScripter::CrashLocationManagerL ),
+        ENTRY( "GetFile" , CLocationManagerTestScripter::GetFileL ),
+        ENTRY( "DeleteFile" , CLocationManagerTestScripter::DeleteFileL ),
+        ENTRY( "GetStatus" , CLocationManagerTestScripter::GetStatusL ),
+        ENTRY( "GetStatus2" , CLocationManagerTestScripter::GetStatus2L )
+        //ADD NEW ENTRY HERE
+        // [test cases entries] - Do not remove
+
+        };
+
+    const TInt count = sizeof( KFunctions ) / 
+                        sizeof( TStifFunctionInfo );
+
+    return RunInternalL( KFunctions, count, aItem );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::Connect
+// -----------------------------------------------------------------------------
+//
+TInt CLocationManagerTestScripter::ConnectL( CStifItemParser& /* aItem */ ) 
+    {
+    _LIT( KMsg1, "ConnectL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    User::LeaveIfError( iLocationManager.Connect() );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::Close
+// -----------------------------------------------------------------------------
+//
+TInt CLocationManagerTestScripter::CloseL( CStifItemParser& /* aItem */ ) 
+    {
+    _LIT( KMsg1, "CloseL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    iLocationManager.Close();
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::Connect
+// -----------------------------------------------------------------------------
+//
+TInt CLocationManagerTestScripter::TrailConnectL( CStifItemParser& /* aItem */ ) 
+    {
+    _LIT( KMsg1, "ConnectL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    User::LeaveIfError( iLocationTrail.Connect() );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::Close
+// -----------------------------------------------------------------------------
+//
+TInt CLocationManagerTestScripter::TrailCloseL( CStifItemParser& /* aItem */ ) 
+    {
+    _LIT( KMsg1, "CloseL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    iLocationTrail.Close();
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::StartTrailL
+// -----------------------------------------------------------------------------
+//
+TInt CLocationManagerTestScripter::StartTrailL( CStifItemParser& /* aItem */ ) 
+    {
+    _LIT( KMsg1, "StopTrailL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    TInt error = iLocationTrail.StartLocationTrail( RLocationTrail::ECaptureAll );
+    User::LeaveIfError( error );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::StopTrailL
+// -----------------------------------------------------------------------------
+//
+TInt CLocationManagerTestScripter::StopTrailL( CStifItemParser& /* aItem */ ) 
+    {
+    _LIT( KMsg1, "StopTrailL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    User::LeaveIfError( iLocationTrail.StopLocationTrail() );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::StartTrailTestsL
+// -----------------------------------------------------------------------------
+//
+TInt CLocationManagerTestScripter::StartTrailTestsL( CStifItemParser& /* aItem */ ) 
+    {
+    _LIT( KMsg1, "StartTrailTestsL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    TInt error( KErrNone );
+    
+    error = iLocationTrail.StartLocationTrail( RLocationTrail::EOff );
+    if( error != KErrArgument )
+        {
+        User::LeaveIfError( error );
+        }
+    RLocationTrail::TTrailCaptureSetting setting;
+    User::LeaveIfError( iLocationTrail.GetTrailCaptureSetting( setting ) );
+    if( setting != RLocationTrail::EOff )
+        {
+        return KErrUnknown;
+        }
+    
+    _LIT( KMsg2, "StartTrailTestsL, test 1 - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format( KMsg2, error );
+    iLog->Log( msg );     
+    RDebug::Print( msg );
+    
+    User::LeaveIfError( iLocationTrail.StopLocationTrail() );
+    
+    error = iLocationTrail.StartLocationTrail( RLocationTrail::ECaptureNetworkInfo );
+    User::LeaveIfError( error );
+    User::LeaveIfError( iLocationTrail.GetTrailCaptureSetting( setting ) );
+    if( setting != RLocationTrail::ECaptureNetworkInfo )
+        {
+        return KErrUnknown;
+        }
+    
+    _LIT( KMsg3, "StartTrailTestsL, test 2 - Error code : %d" );
+    msg.Format( KMsg3, error );
+    iLog->Log( msg );     
+    RDebug::Print( msg ); 
+    
+    User::LeaveIfError( iLocationTrail.StopLocationTrail() );
+    
+    error = iLocationTrail.StartLocationTrail( RLocationTrail::ECaptureAll );
+    User::LeaveIfError( error );
+    User::LeaveIfError( iLocationTrail.GetTrailCaptureSetting( setting ) );
+    if( setting != RLocationTrail::ECaptureAll )
+        {
+        return KErrUnknown;
+        }
+    
+    _LIT( KMsg4, "StartTrailTestsL, test 2 - Error code : %d" );
+    msg.Format( KMsg4, error );
+    iLog->Log( msg );     
+    RDebug::Print( msg );
+    
+    User::LeaveIfError( iLocationTrail.StopLocationTrail() );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::GetTrailStateL
+// -----------------------------------------------------------------------------
+//
+TInt CLocationManagerTestScripter::GetTrailStateL( CStifItemParser& /*aItem*/ ) 
+    {
+    _LIT( KMsg1, "GetTrailStateL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    RLocationTrail::TTrailState state;
+    iLocationTrail.GetLocationTrailState( state );
+    if( state != RLocationTrail::ETrailStarting )
+        {
+        return KErrUnknown;
+        }
+    
+    _LIT( KMsg, "GetTrailStateL - state : %d" );
+    TBuf <100> msg;
+    msg.Format( KMsg, state );
+    iLog->Log( msg );     
+    RDebug::Print( msg );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::LocationTrailNotifyTestL
+// -----------------------------------------------------------------------------
+//
+TInt CLocationManagerTestScripter::LocationTrailNotifyTestL( CStifItemParser& /*aItem*/ ) 
+    {
+    _LIT( KMsg1, "LocationTrailNotifyTestL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+
+    TRequestStatus status;
+    iLocationTrail.NotifyLocationTrailStateChange( status );
+    iLocationTrail.CancelNotificationRequest();
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::RetrieveLocationL
+// -----------------------------------------------------------------------------
+//
+TInt CLocationManagerTestScripter::RetrieveLocationL( CStifItemParser& /*aItem*/ ) 
+    {
+    _LIT( KMsg1, "RetrieveLocationL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+
+    TTime time;
+    time.UniversalTime();
+    
+    TLocationData data;
+    RLocationTrail::TTrailState state;
+    
+    TInt error = iLocationTrail.RetrieveLocation( time, data, state );
+    
+    _LIT( KMsg, "RetrieveLocationL - error : %d" );
+    TBuf <100> msg;
+    msg.Format( KMsg, error );
+    iLog->Log( msg );     
+    RDebug::Print( msg );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CLocationManagerTestScripter::CurrentLocationL
+// -----------------------------------------------------------------------------
+//
+TInt CLocationManagerTestScripter::CurrentLocationL( CStifItemParser& /*aItem*/ ) 
+    {
+    _LIT( KMsg1, "CurrentLocationL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    TRequestStatus status; 
+    TLocationData data;
+    iLocationTrail.CurrentLocation( status, data );
+    iLocationTrail.CancelLocationRequest();
+    
+    return KErrNone;
+    }
+
+//  [End of File] - Do not remove
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/tsrc/src/RLocationObjectManipulatorTest.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,338 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#include "LocationManagerTestScripter.h"
+#include "mdeobject.h"
+#include "mdenamespacedef.h"
+#include "mdeobjectdef.h"
+#include "mdepropertydef.h"
+#include "mdeconstants.h"
+#include "locationdatatype.h"
+#include "mdsutils.h"
+#include <etel3rdparty.h>
+#include <StifTestEventInterface.h>
+#include <StifParser.h>
+#include <StifTestEventInterface.h>
+#include <StifTestInterface.h>
+
+using namespace MdeConstants;
+
+TInt CLocationManagerTestScripter::PrepareSessionL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "PrepareSessionL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    User::LeaveIfError( iOM.Connect() );
+    iMdeSession = CMdESession::NewL( *this );
+    
+    return KErrNone;
+    }
+
+TInt CLocationManagerTestScripter::SetupOML( CStifItemParser& /*aItem*/ )
+	{
+    _LIT( KMsg1, "Enter SetupOM" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+	
+	iSourceObject = CreateMetadataObjectL();
+	TLocationData locationData;
+	TestLocationData( locationData );
+	TInt error( KErrNone );
+	error = iOM.CreateLocationObject( locationData, iSourceObject->Id() );
+	if( error != KErrNone )
+	    {
+	    return error;
+	    }
+	iTargetObject = CreateMetadataObjectL();	
+	
+    _LIT( KMsg2, "Exit SetupOM" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	
+	return KErrNone;
+	}
+
+TInt CLocationManagerTestScripter::LocationSnapshotL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "Enter LocationSnapshotL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    iSourceObject = CreateMetadataObjectL();
+    TInt error( KErrNone );
+    error = iOM.LocationSnapshot( iSourceObject->Id() );
+    
+    _LIT( KMsg2, "Exit LocationSnapshotL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return error;
+    }
+
+TInt CLocationManagerTestScripter::RemoveLocationObjectL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "Enter RemoveLocationObjectL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+
+    TInt error( KErrNone );
+    error = iOM.RemoveLocationObject( iSourceObject->Id() );
+    
+    _LIT( KMsg2, "Exit RemoveLocationObjectL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+    
+    return error;
+    }
+
+TInt CLocationManagerTestScripter::TearDownOML( CStifItemParser& /*aItem*/ )
+	{
+    _LIT( KMsg1, "Enter TearDownOM" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+	
+	iOM.Close();
+	
+	if( iSourceObject && iMdeSession )
+	    {
+	    TRAP_IGNORE( iMdeSession->RemoveObjectL( iSourceObject->Id() ) );
+	    }
+	delete iSourceObject;
+	iSourceObject = NULL;
+    if( iTargetObject && iMdeSession )
+        {
+        TRAP_IGNORE( iMdeSession->RemoveObjectL( iTargetObject->Id() ) );
+        }
+	delete iTargetObject;
+	iTargetObject = NULL;
+	delete iMdeSession;
+	iMdeSession = NULL;
+	
+    _LIT( KMsg2, "Exit TearDownOM" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	
+	return KErrNone;
+	}
+
+TInt CLocationManagerTestScripter::CloseOML( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "CloseOML" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    iOM.Close();
+    
+    return KErrNone;
+    }
+
+TInt CLocationManagerTestScripter::RLocationObjectManipulatorTest_CopyByIDL( CStifItemParser& /*aItem*/ )
+	{
+    _LIT( KMsg1, "Enter RLocationObjectManipulatorTest_CopyByIDL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+	
+	TRequestStatus status = KRequestPending;
+	RArray<TItemId> items;
+	items.Append( iTargetObject->Id() );
+	iOM.CopyLocationData( iSourceObject->Id(), items, status );
+	User::WaitForRequest( status );
+	TL( status.Int() == KErrNone );
+	
+	status = KRequestPending;
+	iOM.CopyLocationData( TItemId(12345678), items, status );
+	User::WaitForRequest( status );
+	TL( status.Int() == KErrNotFound );
+	
+	items.Reset();
+	items.Append(TItemId(12345678));
+	status = KRequestPending;
+	iOM.CopyLocationData( iSourceObject->Id(), items, status );
+	User::WaitForRequest( status );
+	TL( status.Int() == KErrNotFound );
+	
+	status = KRequestPending;
+	iOM.CopyLocationData( TItemId(12345678), items, status );
+	User::WaitForRequest( status );
+	TL( status.Int() == KErrNotFound );
+	
+	items.Close();
+	
+    _LIT( KMsg2, "Exit RLocationObjectManipulatorTest_CopyByIDL" );
+    iLog->Log( KMsg2 );  
+    RDebug::Print( KMsg2 );
+	
+	return KErrNone;
+	}
+
+TInt CLocationManagerTestScripter::RLocationObjectManipulatorTest_CopyByURIL( CStifItemParser& /*aItem*/ )
+	{
+	_LIT(KURIThatDoesNotExist, "qwerty");
+	
+	TRequestStatus status = KRequestPending;
+	RPointerArray<TDesC> items;
+	items.AppendL( &iTargetObject->Uri() );
+	TBuf<256> source( iSourceObject->Uri() );
+	iOM.CopyLocationData( source, items, status );
+	User::WaitForRequest( status );
+	TL( status.Int() == KErrNone );
+	
+	source.Copy( KURIThatDoesNotExist );
+	status = KRequestPending;
+	iOM.CopyLocationData( source, items, status );
+	User::WaitForRequest( status );
+	TL( status.Int() == KErrNotFound );
+	
+	items.Reset();
+    HBufC* nouri = source.AllocL();
+	items.Append( nouri );
+	source.Copy( iSourceObject->Uri() );
+	status = KRequestPending;
+    iOM.CopyLocationData( source, items, status );
+	User::WaitForRequest( status );
+	TL( status.Int() == KErrNotFound );
+	
+	status = KRequestPending;
+	source.Copy( KURIThatDoesNotExist );
+	iOM.CopyLocationData( source, items, status );
+	User::WaitForRequest( status );
+	TL( status.Int() == KErrNotFound );
+	
+	items.ResetAndDestroy();
+	
+	return KErrNone;
+	}
+
+TInt CLocationManagerTestScripter::RLocationObjectManipulatorTest_CopyByID_DisconnectedL( 
+		CStifItemParser& /*aItem*/ )
+	{
+	TRequestStatus status = KRequestPending;
+	RArray<TItemId> items;
+	items.Append( 97976479 );
+	iOM.CopyLocationData( iSourceObject->Id(), items, status );
+	User::WaitForRequest( status );
+	TL( status.Int() == KErrDisconnected );
+	
+	return KErrNone;
+	}
+
+TInt CLocationManagerTestScripter::RLocationObjectManipulatorTest_CopyByURI_DisconnectedL( 
+		CStifItemParser& /*aItem*/ )
+	{
+	_LIT(KURIThatDoesNotExist, "notexistinganywhere");
+	
+	TRequestStatus status = KRequestPending;
+	RPointerArray<TDesC> items;
+	items.AppendL( &KURIThatDoesNotExist );
+	TBuf<256> source( iSourceObject->Uri() );
+	iOM.CopyLocationData( source, items, status );
+	User::WaitForRequest( status );
+	TL( status.Int() == KErrDisconnected );
+	
+	return KErrNone;
+	}	
+
+CMdEObject* CLocationManagerTestScripter::CreateMetadataObjectL( )
+	{	
+	CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+	CMdEObjectDef& objectDef = namespaceDef.GetObjectDefL( Image::KImageObject );
+	CMdEObject *obj = iMdeSession->NewObjectLC( objectDef, Object::KAutomaticUri );
+	
+	// required object properties
+	CMdEPropertyDef& creationDef = objectDef.GetPropertyDefL( Object::KCreationDateProperty );
+	CMdEPropertyDef& modifiedDef = objectDef.GetPropertyDefL( Object::KLastModifiedDateProperty );
+	CMdEPropertyDef& sizeDef = objectDef.GetPropertyDefL( Object::KSizeProperty );
+	CMdEPropertyDef& itemTypeDef = objectDef.GetPropertyDefL( Object::KItemTypeProperty );
+	
+	TTime timestamp( 0 );
+	timestamp.UniversalTime();
+
+	// required object properties
+	obj->AddTimePropertyL( creationDef, timestamp );
+	obj->AddTimePropertyL( modifiedDef, timestamp );
+	obj->AddUint32PropertyL( sizeDef, 0 ); // always zero size for location objects
+	obj->AddTextPropertyL( itemTypeDef, Location::KLocationItemType );
+	
+	iMdeSession->AddObjectL( *obj );
+	CMdEObject* obj2 = iMdeSession->GetObjectL( obj->Id() );
+	CleanupStack::Pop( obj );
+	
+	return obj2;
+	}
+
+void CLocationManagerTestScripter::HandleSessionOpened(CMdESession& /*aSession*/, TInt aError)
+	{
+    _LIT( KMsg, "CallBck HandleSessionOpened - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );     
+    RDebug::Print(msg);
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+	}
+
+void CLocationManagerTestScripter::HandleSessionError(CMdESession& /*aSession*/, TInt aError)
+	{
+    _LIT( KMsg, "CallBck HandleSessionError - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );
+    RDebug::Print(msg);
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Session") );
+    TestModuleIf().Event( event );
+	}
+
+void CLocationManagerTestScripter::TestLocationData( TLocationData& aLocationData )
+	{
+	_LIT( temp, "XXX" );
+	TBuf<3> countryTxt( temp );
+
+	TPosition testLocality;
+	testLocality.SetCoordinate( (TReal64)Math::Random()/KMaxTUint*180.0, (TReal64)Math::Random()/KMaxTUint*90.0, 10.0 );
+	testLocality.SetAccuracy( 2.0, 2.0 );
+
+	CTelephony::TNetworkInfoV1 networkInfo;
+	networkInfo.iAccess = CTelephony::ENetworkAccessGsm;
+	networkInfo.iAreaKnown = ETrue;
+	networkInfo.iBandInfo = CTelephony::E800BandA;
+	networkInfo.iCellId = 1;
+	networkInfo.iLocationAreaCode = 1;
+	networkInfo.iMode = CTelephony::ENetworkModeGsm;
+	networkInfo.iStatus = CTelephony::ENetworkStatusCurrent;
+	networkInfo.iCountryCode = countryTxt;
+	networkInfo.iNetworkId = countryTxt;
+
+	TCourse kurssi;
+	kurssi.SetCourse( 1.0 );
+	kurssi.SetCourseAccuracy( 1.0 );
+	kurssi.SetHeading( 10.0 );
+	kurssi.SetSpeed( 10.0 );
+
+	aLocationData.iPosition = testLocality;
+	aLocationData.iCountry = countryTxt;
+	aLocationData.iNetworkInfo = networkInfo;
+	aLocationData.iSatellites = 4;
+	aLocationData.iCourse = kurssi;
+	aLocationData.iQuality = 1;
+	}
+
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/location_manager_api/tsrc/src/RTrackLogTest.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,253 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include "LocationManagerTestScripter.h"
+#include "mdsutils.h"
+#include <etel3rdparty.h>
+#include <StifTestEventInterface.h>
+#include <StifParser.h>
+#include <StifTestEventInterface.h>
+#include <StifTestInterface.h>
+#include <e32cmn.h>
+
+TInt CLocationManagerTestScripter::SetupTrackLogL( CStifItemParser& /*aItem*/ )
+	{
+    _LIT( KMsg1, "SetupTrackLog" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+	
+	User::LeaveIfError( iTrackLog.Connect() );
+	
+	return KErrNone;
+	}
+
+TInt CLocationManagerTestScripter::TearDownTrackLog( CStifItemParser& /*aItem*/ )
+	{
+    _LIT( KMsg1, "TearDownTrackLog" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+	
+	if ( iTrackLog.IsRecording() )
+		{
+		iTrackLog.StopTrackLog();
+		}
+	
+	iTrackLog.Close();
+	
+	return KErrNone;
+	}
+
+TInt CLocationManagerTestScripter::RTrackLogTest_AddObserverL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "RTrackLogTest_AddObserver" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+   
+    TInt error( KErrNone );
+    error = iTrackLog.AddObserver( this );
+    if( error != KErrNone && error != KErrAlreadyExists )
+        {
+        return error;
+        }
+    
+    return KErrNone;
+    }
+
+TInt CLocationManagerTestScripter::RTrackLogTest_RemoveObserverL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "RTrackLogTest_RemoveObserver" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    TInt error( KErrNone );
+    error = iTrackLog.RemoveObserver( this );
+    if( error != KErrNone && error != KErrNotFound )
+        {
+        return error;
+        }
+    
+    return KErrNone;
+    }
+
+void CLocationManagerTestScripter::TrackLogStarted(TInt aError)
+    {
+    _LIT( KMsg, "CallBck HandleSessionOpened - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );     
+    RDebug::Print(msg);
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("Recording") );
+    TestModuleIf().Event( event );
+    }
+
+void CLocationManagerTestScripter::TrackLogStopped(TInt aError)
+    {
+    _LIT( KMsg, "CallBck HandleSessionOpened - Error code : %d" );
+    TBuf <100> msg;
+    msg.Format(KMsg, aError);
+    iLog->Log( msg );     
+    RDebug::Print(msg);
+    
+    // session event
+    TEventIf event( TEventIf::ESetEvent, _L("StopRecording") );
+    TestModuleIf().Event( event );
+    }
+
+void CLocationManagerTestScripter::GPSFixQualityChanged(TPositionSatelliteInfo& /*aFixQuality*/, 
+                                                        TBool& /*aTrackingActive*/ )
+    {
+    _LIT( KMsg1, "CallBck GPSFixQualityChanged" );
+    iLog->Log( KMsg1 );     
+    RDebug::Print( KMsg1 );
+    }
+
+TInt CLocationManagerTestScripter::RTrackLogTest_StartTrackLogL( CStifItemParser& /*aItem*/ )
+	{
+    _LIT( KMsg1, "RTrackLogTest_StartTrackLogL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+	
+    User::LeaveIfError( iTrackLog.StartTrackLog() );
+	
+	return KErrNone;
+	}
+
+TInt CLocationManagerTestScripter::RTrackLogTest_RecordingL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "RTrackLogTest_RecordingL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    if ( !iTrackLog.IsRecording() )
+        {
+        return KErrUnknown;
+        }
+    
+    return KErrNone;
+    }
+
+TInt CLocationManagerTestScripter::RTrackLogTest_StopTrackLogL( CStifItemParser& /*aItem*/ )
+	{
+    _LIT( KMsg1, "RTrackLogTest_StopTrackLogL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+	
+	iTrackLog.StopTrackLog();
+	
+	return KErrNone;
+	}
+
+TInt CLocationManagerTestScripter::RTrackLogTest_NotRecordingL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "RTrackLogTest_NotRecordingL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    if ( iTrackLog.IsRecording() )
+        {
+        return KErrUnknown;
+        }
+    
+    return KErrNone;
+    }
+
+TInt CLocationManagerTestScripter::CrashLocationManagerL( CStifItemParser& /*aItem*/ )
+	{
+	_LIT( name, "LocationManagerServ*" );
+	TFindProcess findProcess( name );
+	
+	RProcess locManProcess;
+	TFullName result;
+	findProcess.Next( result );
+	User::LeaveIfError( locManProcess.Open( findProcess ) );
+	locManProcess.Kill( KErrNone );
+	locManProcess.Close();
+
+	return KErrNone;
+	}
+
+TInt CLocationManagerTestScripter::GetFileL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "GetFileL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+
+    TFileName name;
+    User::LeaveIfError( iTrackLog.TrackLogName( name ) );
+    if( name.Length() <= 0 )
+        {
+        return KErrNotFound;
+        }
+    
+    return KErrNone;
+    }
+
+TInt CLocationManagerTestScripter::DeleteFileL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "DeleteFileL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+    
+    TFileName name;
+    TInt error( KErrNone );
+    error = iTrackLog.TrackLogName( name );
+    if( error != KErrNotFound )
+        {
+        return KErrUnknown;
+        }
+    error = iTrackLog.DeleteTrackLog( name );
+    if( error != KErrNone )
+        {
+        return error;
+        }
+
+    return KErrNone;
+    }
+
+TInt CLocationManagerTestScripter::GetStatusL( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "GetStatusL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+
+    TPositionSatelliteInfo info;
+    TBool recording;
+    User::LeaveIfError( iTrackLog.GetStatus( recording, info ) );
+    
+    return KErrNone;
+    }
+
+TInt CLocationManagerTestScripter::GetStatus2L( CStifItemParser& /*aItem*/ )
+    {
+    _LIT( KMsg1, "GetStatusL" );
+    iLog->Log( KMsg1 );  
+    RDebug::Print( KMsg1 );
+
+    TPositionSatelliteInfo info;
+    TBool recording;
+    User::LeaveIfError( iTrackLog.GetStatus( recording, info ) );
+    if( recording )
+        {
+        return KErrUnknown;
+        }
+    
+    return KErrNone;
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,68 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+../inc/mdccommon.h    MW_LAYER_PLATFORM_EXPORT_PATH(mdccommon.h)
+../inc/mdeerror.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeerror.h)
+../inc/mdeinternalerror.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeinternalerror.h)
+../inc/mdedatabuffer.h    MW_LAYER_PLATFORM_EXPORT_PATH(mdedatabuffer.h)
+../inc/mdequery.h     MW_LAYER_PLATFORM_EXPORT_PATH(mdequery.h)
+../inc/mdesession.h     MW_LAYER_PLATFORM_EXPORT_PATH(mdesession.h)
+../inc/mdeboolpropertycondition.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeboolpropertycondition.h)
+../inc/mdecondition.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdecondition.h)
+../inc/mdeconstants.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeconstants.h)
+../inc/mdeevent.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeevent.h)
+../inc/mdeeventcondition.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeeventcondition.h)
+../inc/mdeeventdef.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeeventdef.h)
+../inc/mdeeventquery.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeeventquery.h)
+../inc/mdeinstanceitem.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeinstanceitem.h)
+../inc/mdeitem.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeitem.h)
+../inc/mdelogiccondition.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdelogiccondition.h)
+../inc/mdenamespacedef.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdenamespacedef.h)
+../inc/mdeobject.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeobject.h)
+../inc/mdeobjectcondition.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeobjectcondition.h)
+../inc/mdeobjectdef.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeobjectdef.h)
+../inc/mdeobjectquery.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeobjectquery.h)
+../inc/mdeorderrule.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeorderrule.h)
+../inc/mdeproperty.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeproperty.h)
+../inc/mdepropertycondition.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdepropertycondition.h)
+../inc/mdepropertydef.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdepropertydef.h)
+../inc/mderange.h   MW_LAYER_PLATFORM_EXPORT_PATH(mderange.h)
+../inc/mderange.inl   MW_LAYER_PLATFORM_EXPORT_PATH(mderange.inl)
+../inc/mderangepropertycondition.h   MW_LAYER_PLATFORM_EXPORT_PATH(mderangepropertycondition.h)
+../inc/mderelation.h   MW_LAYER_PLATFORM_EXPORT_PATH(mderelation.h)
+../inc/mderelationcondition.h   MW_LAYER_PLATFORM_EXPORT_PATH(mderelationcondition.h)
+../inc/mderelationdef.h   MW_LAYER_PLATFORM_EXPORT_PATH(mderelationdef.h)
+../inc/mderelationquery.h   MW_LAYER_PLATFORM_EXPORT_PATH(mderelationquery.h)
+../inc/mdetextpropertycondition.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdetextpropertycondition.h)
+../inc/mdetextproperty.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdetextproperty.h)
+../inc/mdetextproperty.inl   MW_LAYER_PLATFORM_EXPORT_PATH(mdetextproperty.inl)
+../inc/mdenumberproperty.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdenumberproperty.h)
+../inc/mdenumberproperty.inl   MW_LAYER_PLATFORM_EXPORT_PATH(mdenumberproperty.inl)
+../inc/mdeversioncenrepkey.h   MW_LAYER_PLATFORM_EXPORT_PATH(mdeversioncenrepkey.h)
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdccommon.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,381 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Common message definitions and utilities
+*
+*/
+
+#ifndef __MDCCOMMON_H__
+#define __MDCCOMMON_H__
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <mdeerror.h>
+
+// MDS version
+#define MDS_VERSION_2_5
+
+// Item id
+typedef TUint32 TItemId;
+typedef TUint32 TDefId;
+typedef TUint32 TMdCOffset;
+
+const TItemId KNoId = 0;
+const TDefId KNoDefId = 0;
+
+// CONSTANTS
+_LIT( KMdEDefaultNameSpace, "http://sw.nokia.com/MdE" );
+
+// Type of property
+enum TPropertyType
+    {
+    EPropertyBool   = 0,
+    EPropertyInt8   = 1,
+    EPropertyUint8  = 2,
+    EPropertyInt16  = 3,
+    EPropertyUint16 = 4,
+    EPropertyInt32  = 5,
+    EPropertyUint32 = 6,
+    EPropertyInt64  = 7,
+    EPropertyReal32 = 8,
+    EPropertyReal64 = 9,
+    EPropertyTime   = 10,
+    EPropertyText   = 11,
+    };
+
+/**
+ * Query types.
+ */
+enum TQueryType
+    {
+    EQueryTypeFirst = 0,    // must always be the first one
+
+    /** Query that returns CMdEObject items, IDs, count or distinct property values. */
+    EQueryTypeObject,
+
+    /** Query that returns CMdERelation items, IDs or count. */
+    EQueryTypeRelation,
+
+    /** Query that returns CMdEEvent items, IDs or count. */
+    EQueryTypeEvent,
+
+    EQueryTypeLast   // must always be the last one
+    };  
+
+/** 
+ * Query's result type.
+ */
+enum TQueryResultMode
+    {
+    EQueryResultModeFirst = 0, // must always be the first one
+
+    /** Query returns whole items (objects are returned without freetexts). */
+    EQueryResultModeItem,
+
+    /** Query returns set of IDs. */
+    EQueryResultModeId,
+
+    /** Query returns count of items */
+    EQueryResultModeCount,
+
+	/** Query returns distinct values from specified property definition. 
+	 *  Query's type must be EQueryTypeObject. */
+    EQueryResultModeDistinctValues,
+
+	/** Query returns whole items with freetexts. */
+	EQueryResultModeObjectWithFreetexts,
+
+    EQueryResultModeLast // must always be the last one
+    };
+
+/** Types of sort order. */
+enum TMdESortOrder
+	{
+	ESortAscending = ETrue, 
+	ESortDescending = EFalse
+	};
+
+/** Types of result ordering rules. */
+enum TOrderRuleType
+    {
+    EOrderRuleTypeFirst = 0,
+
+    /** Sort results with item ID. */
+    EOrderRuleTypeItemID,
+
+    /** Sort results by object URI. */
+    EOrderRuleTypeObjectURI,
+
+    /** Sort results by object definition. */
+    EOrderRuleTypeObjectDef,
+
+    /** Sort results by the value of a property. */
+    EOrderRuleTypeProperty,
+
+    /** Sort objects by usage count. */
+    EOrderRuleTypeUsageCount,
+
+    /** Sort events by creation time. */
+    EOrderRuleTypeCreationTime,
+
+    /** Sort events by source URI. */
+    EOrderRuleTypeSourceURI,
+
+    /** Sort events by participant URI. */
+    EOrderRuleTypeParticipantURI,
+
+    /** Sort events by target object's ID. */
+    EOrderRuleTypeTargetObjectID,
+
+    /** Sort events by event definition. */
+    EOrderRuleTypeEventDef,
+
+    /** Sort relations by last modified date. */
+    EOrderRuleTypeLastModifiedDate,
+
+    /** Sort relations by parameter. */
+    EOrderRuleTypeParameterValue,
+
+    /** Sort relations by left object's ID. */
+    EOrderRuleTypeLeftObjectID,
+
+    /** Sort relations by right object's ID. */
+    EOrderRuleTypeRightObjectID,
+
+    /** Sort relations by relation definition. */
+    EOrderRuleTypeRelationDef,
+            
+    EOrderRuleTypeLast
+    };
+
+
+/**
+ * Condition types.
+ */
+enum TConditionType
+	{
+	EConditionTypeFirst	= 0x0000,   // must always be the first one
+    
+    /** logic conditions combine other conditions with logic operators */
+    EConditionTypeLogic,
+
+    /** conditions for object ID, URI, definition */
+    EConditionTypeObject,            
+
+    /** conditions for the property definition */
+    EConditionTypeProperty,          
+    
+    /** condition for the value of a int property */
+    EConditionTypePropertyIntRange,  
+    
+    /** condition for the value of a int64 property */
+    EConditionTypePropertyInt64Range,
+
+    /** condition for the value of a uint property */
+    EConditionTypePropertyUintRange,  
+
+    /** condition for the value of a real property */
+    EConditionTypePropertyRealRange, 
+
+    /** condition for the value of a time property */
+    EConditionTypePropertyTimeRange, 
+
+    /** condition for the value of a string property */
+    EConditionTypePropertyText,    
+
+    /** condition for the value of a boolean property */
+    EConditionTypePropertyBool,      
+
+    /** conditions for relation items */
+    EConditionTypeRelation,          
+
+    /** conditions for an event */
+    EConditionTypeEvent,             
+
+	EConditionTypeLast				// must always be the last one
+	};
+
+/**
+ * Observer notification types
+ */
+enum TObserverNotificationType
+	{
+	ENotifyAdd    = 0x0001,
+	ENotifyModify = 0x0002,
+	ENotifyRemove = 0x0004,
+	};
+
+/** Logic condition operators. */
+enum TLogicConditionOperator
+    {
+    ELogicConditionOperatorFirst = 0x0000,
+
+    /** Boolean AND operator. */
+    ELogicConditionOperatorAnd,
+
+    /** Boolean OR operator. */
+    ELogicConditionOperatorOr,
+
+    ELogicConditionOperatorLast
+    };
+
+/** Methods of comparing object data. */
+enum TObjectConditionCompareMethod 
+    {
+    EObjectConditionCompareFirst = 0,
+
+    /** NONE. Just for sending condition flags */
+    EObjectConditionCompareNone,
+
+    /** Object ID. */
+    EObjectConditionCompareId,
+
+    /** Object IDs. */
+    EObjectConditionCompareIds,
+
+	/** Object GUID. */
+	EObjectConditionCompareGuid,
+
+    /** Object definition. */
+    EObjectConditionCompareObjectDef,
+
+    /** Object URI. */
+    EObjectConditionCompareUri,
+
+	/** Object URI begins with specified string. */
+    EObjectConditionCompareUriBeginsWith,
+    
+    /** Free text keyword associated with the object must be an 
+        exact match. */
+    EObjectConditionCompareFreeText,
+
+    /** Free text keyword associated with the object contains 
+        specified string. */
+    EObjectConditionCompareFreeTextContains,
+
+    /** Free text keyword associated with the object begins with 
+        specified string. */
+    EObjectConditionCompareFreeTextBeginsWith,
+
+    /** Free text keyword associated with the object ends with 
+        specified string. */
+    EObjectConditionCompareFreeTextEndsWith,
+
+    /** Usage count */
+    EObjectConditionCompareUsageCount,
+
+    EObjectConditionCompareLast
+    };
+
+/** Methods of filtering confidential and non-confidential objects. */
+enum TObjectConditionConfidentialityLevel
+    {
+    EObjectConditionLevelFirst = 0,
+
+    /** Both confidential and non-confidential objects */
+    EObjectConditionLevelIgnoreConfidentiality,
+
+    /** Selects ONLY non-confidential objects */
+    EObjectConditionLevelNormal,
+
+    /** Selects ONLY confidential objects. */
+    EObjectConditionLevelConfidential,
+
+    EObjectConditionLevelLast
+    };
+
+/** Methods of comparing event data. */
+enum TEventConditionCompareMethod 
+    {
+    EEventConditionCompareFirst = 0x0000,
+    
+    /** No comparison specified. */
+    EEventConditionCompareNone,
+    
+    /** Specified string must match the source URI. */
+    EEventConditionCompareSourceURI,
+    
+    /** Specified string must match the participant URI. */
+    EEventConditionCompareParticipantURI,
+    
+    /**Specified id must match events id*/
+    EEventConditionCompareId,
+
+    //ECompareSourceURIBeginsWith,
+    //ECompareParticipantRIBeginsWith,
+    
+    EEventConditionCompareLast
+    };
+
+/** Side on which the relation must be in relation to a matched object. */
+enum TRelationConditionSide
+    {
+    /** Object must be on either the left or the right side of 
+        the relation. */
+    ERelationConditionSideEither,
+
+    /** Object must be on the left side of the relation. */
+    ERelationConditionSideLeft,
+
+    /** Object must be on the right side of the relation. */
+    ERelationConditionSideRight
+    };
+
+/** Text value comparison methods. */
+enum TTextPropertyConditionCompareMethod
+    {
+    ETextPropertyConditionCompareFirst = 0x0000,
+    ETextPropertyConditionCompareEquals,          // LIKE "str"
+    ETextPropertyConditionCompareContains,        // LIKE "%str%"
+    ETextPropertyConditionCompareBeginsWith,      // LIKE "str%"
+    ETextPropertyConditionCompareEndsWith,        // LIKE "%str"
+    ETextPropertyConditionCompareLast
+    };
+
+
+/**
+ * Min and max value
+ * There are used like:
+ * for Real types:   iMinValue.iReal, iMaxValue.iReal
+ * for Int64 types:  iMinValue.iInt64, iMaxValue.iInt64
+ * for Uint32 types: iMinValue.iUint32, iMaxValue.iUint32
+ * (!!) others:      iMinValue.iInt32, iMaxValue.iInt32
+ */
+union TMdCValueUnion 
+	{
+	TInt32   iInt32;
+	TUint32  iUint32;
+	TInt64   iInt64;
+	TReal64  iReal;
+	HBufC16* iText;
+
+	struct
+		{
+		TUint32 iCount;
+		TMdCOffset iOffset;
+		} iPtr;
+	};
+
+/**
+* Common utilities.
+* Used as a static function library -
+* This class is not to be instantiated.
+*/
+class MMdCCommon
+    {
+    public: // public definitions
+        /** Creates a panic */
+        IMPORT_C static void Panic( TInt aPanicCode );
+    };
+        
+#endif // __MDCCOMMON_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeboolpropertycondition.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,106 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Property conditions for boolean property values
+*
+*/
+
+
+#ifndef __MDEBOOLPROPERTYCONDITION_H__
+#define __MDEBOOLPROPERTYCONDITION_H__
+
+
+#include <mdepropertycondition.h>
+
+/* Forward declarations. */
+class CMdEPropertyDef;
+class CMdCSerializationBuffer;
+
+/**
+ * Property conditions for boolean property values. The condition is true 
+ * when the property's value matches the condition's boolean value.
+ */
+NONSHARABLE_CLASS(CMdEBoolPropertyCondition) : public CMdEPropertyCondition
+	{
+	public:
+
+	/**
+	 *  First-phase constructor
+	 */
+	static CMdEBoolPropertyCondition* NewL( const CMdEPropertyDef& aPropertyDef, 
+            TBool aValue );
+
+	/**
+	 *  First-phase constructor
+	 */
+	static CMdEBoolPropertyCondition* NewLC( const CMdEPropertyDef& aPropertyDef, 
+            TBool aValue );
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEBoolPropertyCondition();
+
+
+	/* Methods. */
+
+    /**
+     * Returns the boolean condition value.
+     */
+    IMPORT_C TBool Value() const;
+
+    /**
+     * Get possible query's internal optimization flags from condition.
+     *
+     * @param aFlaga query's internal optimization flags
+     * @return last level internal optimization flags
+     */
+    TUint32 InternalQueryOptimizationFlags(TUint32& aFlags);
+
+    /**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+    TUint32 RequiredBufferSize() const;
+
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling) and return new position of serialized buffer.
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    void SerializeL(CMdCSerializationBuffer& aBuffer,
+    		TMdCOffset& aFreespaceOffset) const;
+    
+private:
+	/**
+	 * Constructor. 
+	 *
+	 * @param aValue  boolean value
+	 */
+	CMdEBoolPropertyCondition(const CMdEPropertyDef& aPropertyDef, 
+                              TBool aValue);
+
+	/**
+	 * Second-phase constructor.
+	 */
+	void ConstructL();
+
+private:
+
+    /** The boolean value to compare against. */
+    TBool iValue;
+    };
+
+#endif  // __MDEBOOLPROPERTYCONDITION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdecondition.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,151 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Base class for all search condition tree nodes.
+*
+*/
+
+
+#ifndef __MDECONDITION_H__
+#define __MDECONDITION_H__
+
+
+#include <e32base.h>
+
+#include <mdccommon.h>
+
+// Forward declaration
+class CMdCSerializationBuffer;
+
+/**
+ * Base class for all search condition tree nodes.
+ */
+NONSHARABLE_CLASS(CMdECondition) : public CBase
+	{
+public:
+
+	/* Destructor. */
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdECondition();
+
+
+	/* Methods. */
+
+    /**
+	 * Returns the type of the condition.
+	 *
+	 * @return  Condition type.
+	 */
+	IMPORT_C TConditionType Type() const;
+
+    /**
+	 * Determines whether the condition is negated.
+	 *
+	 * @return  <code>ETrue</code>, if the condition is negated.  
+     *          Otherwise <code>EFalse</code>.
+	 */
+	IMPORT_C TBool Negate() const;
+
+    /**
+	 * Sets the negate flag. The negate flag negates the meaning of the 
+     * condition like a boolean NOT operator.
+	 *
+	 * @param aNegate  <code>ETrue</code> to negate.
+	 */
+	IMPORT_C void SetNegate(TBool aNegate);
+
+    /**
+     * Determines whether the condition node has been locked. Attempting to 
+     * modify locked conditions causes a panic.
+     *
+     * @return  <code>ETrue</code>, if the condition is locked. Otherwise
+     *          <code>EFalse</code>.
+     */
+    IMPORT_C TBool Locked() const;     
+
+    /**
+     * Locks the condition to prevent changes. Attempting to change a locked
+     * condition causes a panic.
+     *
+     * @param aLocked  <code>ETrue</code> to lock; <code>EFalse</code> to 
+     *                 unlock.
+     */
+    IMPORT_C virtual void SetLocked(TBool aLocked = ETrue);
+    
+    /**
+     * Get possible query's internal optimization flags from condition.
+     *
+     * @param aFlaga query's internal optimization flags
+     * @return last level internal optimization flags
+     */
+    virtual TUint32 InternalQueryOptimizationFlags(TUint32& aFlags) = 0;
+
+    /**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+    virtual TUint32 RequiredBufferSize() const = 0;
+
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling).
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    virtual void SerializeL(CMdCSerializationBuffer& aBuffer, 
+    		TMdCOffset& aFreespaceOffset) const = 0;
+
+	/* Constructors. */
+
+	/**
+	 * Constructor. 
+	 *
+	 * @param aType  Type of the condition node.
+	 */
+	CMdECondition(TConditionType aType);
+	
+protected:
+	/**
+	 * Second-phase constructor.
+	 */
+	void ConditionConstruct();
+
+
+	/* Utility methods. */
+     
+    /**
+     * Panics if the condition is not locked.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition is locked against
+     *         changes.
+     */
+    void AssertNotLocked() const;
+
+protected:
+
+    /** Type of the condition. */
+    TConditionType iType;
+
+    /** The negate flag negates the result of the condition: if the 
+        condition evaluates to True, the result will really be False. */
+    TBool iNegated;
+    
+    /** Locked conditions can't be modified. */
+    TBool iLocked;
+    };
+
+#endif  // __MDECONDITION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeconstants.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,280 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Metadata Engine's literals.
+*
+*/
+
+// conforms to Metadata schema version 1.6
+
+#ifndef MDECONSTANTS_H
+#define MDECONSTANTS_H
+
+namespace MdeConstants
+    {
+    namespace Object
+        {
+        _LIT( KBaseObject, "Object" );
+        _LIT( KAutomaticUri, "" );
+
+        _LIT( KSizeProperty, "Size" );
+        _LIT( KOriginProperty, "Origin" );
+        _LIT( KUsageCountProperty, "UsageCount" );
+        _LIT( KCreationDateProperty, "CreationDate" );
+        _LIT( KLastModifiedDateProperty, "LastModifiedDate" );
+        _LIT( KItemTypeProperty, "ItemType" );
+        _LIT( KTitleProperty, "Title" );
+        _LIT( KTimeOffsetProperty, "TimeOffset" );
+
+        enum TOrigin
+            {
+            EOther      = 0,
+            ECamera     = 1,
+            EDownloaded = 2,
+            ESideLoaded = 3,
+            ERecorded   = 4
+            };
+        }
+        typedef MdeConstants::Object::TOrigin Origin; // deprecated
+
+    namespace Location
+        {
+        _LIT( KLocationObject, "Location" );
+        _LIT( KLocationItemType, "application/vnd.nokia.mde.locationcontext" );
+
+        _LIT( KCellIdProperty, "CellID" );
+        _LIT( KCountryCodeProperty, "CountryCodeStr" );
+        _LIT( KNetworkCodeProperty, "NetworkCodeStr" );
+        _LIT( KLocationAreaCodeProperty, "LocationAreaCode" );
+        _LIT( KSpeedProperty, "Speed" );
+        _LIT( KDirectionProperty, "Direction" );
+        _LIT( KQualityProperty, "Quality" );
+        _LIT( KLatitudeProperty, "Latitude" );
+        _LIT( KLongitudeProperty, "Longitude" );
+        _LIT( KAltitudeProperty, "Altitude" );
+        _LIT( KSatellitesProperty, "Satellites" );
+        _LIT( KCountryProperty, "Country" );
+        _LIT( KCellNameProperty, "CellName" );
+        }
+
+    namespace Calendar
+        {
+        _LIT( KCalendarObject, "Calendar" );
+        _LIT( KCalendarItemType, "application/vnd.nokia.mde.calendarcontext" );
+
+        _LIT( KCalendarTypeProperty, "CalendarType" );
+        _LIT( KStartTimeProperty, "StartTime" );
+        _LIT( KEndTimeProperty, "EndTime" );
+        _LIT( KLocationProperty, "Location" );
+        _LIT( KvCalendarProperty, "vCalendar" );
+        _LIT( KLocalUidProperty, "LocalUid" );
+        }
+
+    namespace Contact
+        {
+        _LIT( KContactObject, "Contact" );
+        _LIT( KContactItemType, "application/vnd.nokia.mde.contactcontext" );
+
+        _LIT( KNumberProperty, "Number" );
+        _LIT( KEmailAddressProperty, "EmailAddress" );
+        _LIT( KCompanyProperty, "Company" );
+        _LIT( KJobTitleProperty, "JobTitle" );
+        _LIT( KAddressProperty, "Address" );
+        _LIT( KURLProperty, "ContactURL" );
+        _LIT( KvCardProperty, "vCard" );
+        }
+
+    namespace Message
+        {
+        _LIT( KMessageObject, "Message" );
+        _LIT( KSMSItemType, "application/vnd.nokia.mde.sms" );
+        _LIT( KMMSItemType, "application/vnd.nokia.mde.mms" );
+
+        _LIT( KReceivedProperty, "Received" );
+        _LIT( KSenderProperty, "Sender" );
+        _LIT( KToWhomProperty, "ToWhom" );
+        }
+
+    namespace Album
+        {
+        _LIT( KAlbumObject, "Album" );
+        _LIT( KAlbumItemType, "application/vnd.nokia.mde.album" );
+
+        _LIT( KOrderedProperty, "Ordered" );
+        _LIT( KTypeProperty, "Type" );
+        _LIT( KPropertiesProperty, "Properties" );
+        _LIT( KSlideshowWallpaperProperty, "SlideshowWallpaper" );
+
+        enum TAlbumType
+            {
+            EAlbumUser            = 0,
+            EAlbumUserPredefined  = 1,
+            EAlbumSystemFavourite = 2,
+            EAlbumSystemCamera  = 3,
+            };
+        typedef MdeConstants::Album::TAlbumType AlbumType; // deprecated
+        }
+
+    namespace Tag
+        {
+        _LIT( KTagObject, "Tag" );
+        _LIT( KTagItemType, "application/vnd.nokia.mde.tag" );
+        }
+
+    namespace MediaObject
+        {
+        _LIT( KMediaObject, "MediaObject" );
+
+        _LIT( KProtectedProperty, "Protected" );
+        _LIT( KDRMProperty, "DRM" );
+        _LIT( KThumbnailPresentProperty, "ThumbnailPresent" );
+        _LIT( KResizedProperty, "Resized" );
+        _LIT( KSampleProperty, "Sample" );
+        _LIT( KRatingProperty, "Rating" );
+        _LIT( KPrivacyProperty, "Privacy" );
+        _LIT( KResolutionUnitProperty, "ResolutionUnit" );
+        _LIT( KBitrateProperty, "Bitrate" );
+        _LIT( KWidthProperty, "Width" );
+        _LIT( KHeightProperty, "Height" );
+        _LIT( KPreinstalledProperty, "Preinstalled" );
+        _LIT( KAccessCountProperty, "AccessCount" );
+        _LIT( KDownloadIdProperty, "DownloadID" );
+        _LIT( KDurationProperty, "Duration" );
+        _LIT( KReleaseDateProperty, "ReleaseDate" );
+        _LIT( KCaptureDateProperty, "CaptureDate" );
+        _LIT( KArtistProperty, "Artist" );
+        _LIT( KAuthorProperty, "Author" );
+        _LIT( KCopyrightProperty, "Copyright" );
+        _LIT( KLegalProperty, "Legal" );
+        _LIT( KDescriptionProperty, "Description" );
+        _LIT( KCommentProperty, "Comment" );
+        _LIT( KGenreProperty, "Genre" );
+        _LIT( KTrackProperty, "Track" );
+        _LIT( KAudioFourCCProperty, "AudioFourCC" );
+        
+        enum TPreinstalledFlag
+        	{
+        	ENotPreinstalled = 0,
+        	EPreinstalled    = 1
+        	};
+        }
+
+    namespace Video // derived from MediaObject
+        {
+        _LIT( KVideoObject, "Video" );
+
+        _LIT( KAgeProfileProperty, "AgeProfile" );
+        _LIT( KRecordingFlagsProperty, "RecordingFlags" );
+        _LIT( KLastPlayPositionProperty, "LastPlayPosition" );
+        _LIT( KFramerateProperty, "Framerate" );
+        _LIT( KAudioLanguageProperty, "AudioLanguage" );
+        }
+
+    namespace Image // derived from MediaObject
+        {
+        _LIT( KImageObject, "Image" );
+
+        _LIT( KDraftProperty, "Draft" );
+        _LIT( KFocalPlaneResolutionUnitProperty, "FocalPlaneResolutionUnit" );
+        _LIT( KExposureProgramProperty, "ExposureProgram" );
+        _LIT( KFocalLengthIn35mmFilmProperty, "FocalLengthIn35mmFilm" );
+        _LIT( KISOSpeedRatingsProperty, "ISOSpeedRatings" );
+        _LIT( KMeteringModeProperty, "MeteringMode" );
+        _LIT( KWhiteBalanceProperty, "WhiteBalance" );
+        _LIT( KFlashProperty, "Flash" );
+        _LIT( KColourSpaceProperty, "ColourSpace" );
+        _LIT( KOrientationProperty, "Orientation" );
+        _LIT( KSamplesPerPixelProperty, "SamplesPerPixel" );
+        _LIT( KBitsPerSampleProperty, "BitsPerSample" );
+        _LIT( KYCbCrPositioningProperty, "YCbCrPositioning" );
+        _LIT( KThumbCompressionProperty, "ThumbCompression" );
+        _LIT( KThumbResolutionUnitProperty, "ThumbResolutionUnit" );
+        _LIT( KThumbOrientationProperty, "ThumbOrientation" );
+        _LIT( KFrameCountProperty, "FrameCount" );
+        _LIT( KPixelXDimensionProperty, "PixelXDimension" );
+        _LIT( KPixelYDimensionProperty, "PixelYDimension" );
+        _LIT( KExifVersionProperty, "ExifVersion" );
+        _LIT( KComponentsConfigurationProperty, "ComponentsConfiguration" );
+        _LIT( KFlashPixVersionProperty, "FlashPixVersion" );
+        _LIT( KThumbXResolutionProperty, "ThumbXResolution" );
+        _LIT( KThumbYResolutionProperty, "ThumbYResolution" );
+        _LIT( KFocalPlaneXResolutionProperty, "FocalPlaneXResolution" );
+        _LIT( KFocalPlaneYResolutionProperty, "FocalPlaneYResolution" );
+        _LIT( KExposureTimeProperty, "ExposureTime" );
+        _LIT( KExposureBiasValueProperty, "ExposureBiasValue" );
+        _LIT( KFNumberProperty, "FNumber" );
+        _LIT( KFocalLengthProperty, "FocalLength" );
+        _LIT( KApertureValueProperty, "ApertureValue" );
+        _LIT( KMaxApertureProperty, "MaxAperture" );
+        _LIT( KShutterSpeedValueProperty, "ShutterSpeedValue" );
+        _LIT( KXResolutionProperty, "XResolution" );
+        _LIT( KYResolutionProperty, "YResolution" );
+        _LIT( KDateTimeProperty, "DateTime" );
+        _LIT( KDateTimeDigitizedProperty, "DateTimeDigitized" );
+        _LIT( KDateTimeOriginalProperty, "DateTimeOriginal" );
+        _LIT( KPixelFormatProperty, "PixelFormat" );
+        _LIT( KModelProperty, "Model" );
+        _LIT( KMakeProperty, "Make" );
+        _LIT( KRelatedSoundFileProperty, "RelatedSoundFile" );
+        }
+
+    namespace Audio // derived from MediaObject
+        {
+        _LIT( KAudioObject, "Audio" );
+
+        _LIT( KSamplingFrequencyProperty, "SamplingFrequency" );
+        _LIT( KAlbumProperty, "Album" );
+        _LIT( KComposerProperty, "Composer" );
+        _LIT( KOriginalArtistProperty, "OriginalArtist" );
+        _LIT( KAlbumArtistProperty, "AlbumArtist" );
+        }
+
+    namespace Events
+        {
+        _LIT( KCreated, "Created" );
+        _LIT( KDeleted, "Deleted" );
+        _LIT( KOpened, "Opened" );
+        _LIT( KPlayed, "Played" );
+        _LIT( KEdited, "Edited" );
+        _LIT( KSent, "Sent" );
+        _LIT( KReceived, "Received" );
+        }
+
+    namespace Relations
+        {
+        _LIT( KContains, "Contains" );
+        _LIT( KReplaces, "Replaces" );
+        _LIT( KIsVersionOf, "IsVersionOf" );
+        _LIT( KRequires, "Requires" );
+        _LIT( KUses, "Uses" );
+        _LIT( KReferences, "References" );
+        _LIT( KSummarises, "Summarises" );
+        _LIT( KContainsLocation, "ContainsLocation" );
+        }
+
+    namespace TrackLog
+    	{
+    	_LIT( KTrackLogObject, "TrackLog" );
+    	_LIT( KTrackLogItemType, "application/vnd.nokia.mde.tracklog" );
+    	_LIT( KLengthProperty, "Length" );
+    	_LIT( KStartTimeProperty, "StartTime" );
+    	_LIT( KStopTimeProperty, "StopTime" );
+    	}
+    }
+
+// type definitions
+
+typedef MdeConstants::Object::TOrigin TOrigin;
+
+
+#endif // MDECONSTANTS_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdedatabuffer.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Serializard data buffer container
+*
+*/
+
+#ifndef _MDEDATABUFFER_H_
+#define _MDEDATABUFFER_H_
+
+#include <e32def.h>
+
+// forward declaration
+class CMdCSerializationBuffer;
+
+class RMdEDataBuffer
+{
+public:
+	IMPORT_C RMdEDataBuffer();
+
+	IMPORT_C void Close();
+
+	/**
+	 * Set buffer to data buffer. Data buffer takes the ownership of the 
+	 * buffer.
+	 * 
+	 * @param aBuffer serialization buffer
+	 */
+	void SetBufferL(CMdCSerializationBuffer* aBuffer);
+	
+	CMdCSerializationBuffer* GetBufferLC();
+
+private:
+	RMdEDataBuffer(const RMdEDataBuffer&);
+	
+private:
+	CMdCSerializationBuffer* iBuffer;
+};
+
+#endif /*_MDEDATABUFFER_H_*/
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeerror.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Common error code definitions
+*
+*/
+
+
+#ifndef MDEERROR_H
+#define MDEERROR_H
+
+#include <e32def.h>
+
+/**
+ * Canceled or commited object is not locked.
+ */
+const TInt KErrMdENotLocked = -36200;
+
+/**
+ * Property's type is different than expected.
+ */
+const TInt KErrMdEIncorrectType = -36201;
+
+/**
+ * Mandatory property is missing from object.
+ */
+const TInt KErrMdEMandatoryPropertyMissing = -36202;
+
+/**
+ * Property's value is not between allowed minimum and maximum value.
+ */
+const TInt KErrMdEPropertyValueNotBetweenAllowedMinMax = -36203;
+
+/**
+ * First MdE's internal error code.
+ * 
+ * All MdE's internal error codes (defined in mdeinternalerror.h) are be 
+ * between KErrMdEFirstInternalError and KErrMdELastInternalError.
+ */
+const TInt KErrMdEFirstInternalError = -36240;
+
+/**
+ * Last MdE's internal error code.
+ * 
+ * All MdE's internal error codes (defined in mdeinternalerror.h) are be 
+ * between KErrMdEFirstInternalError and KErrMdELastInternalError.
+ */
+const TInt KErrMdELastInternalError  = -36299;
+
+#endif /*MDEERROR_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeevent.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,174 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Representation of single event
+*
+*/
+
+
+#ifndef __MDEEVENT_H__
+#define __MDEEVENT_H__
+
+
+#include <mdeinstanceitem.h>
+
+class CMdEEventDef;
+class CMdCSerializationBuffer;
+class CMdENamespaceDef;
+
+/**
+ * Event.
+ */
+NONSHARABLE_CLASS(CMdEEvent) : public CMdEInstanceItem
+	{
+public:
+	
+	/**
+	 * Create new event from serialized buffer
+	 *
+	 * @param aBuffer serialized relation
+	 * @return new event
+	 */
+	static CMdEEvent* NewL(CMdESession* aSession, CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef );
+
+	/**
+	 * Create new event from serialized buffer and leaves it on stack
+	 *
+	 * @param aBuffer serialized relation
+	 * @return new event
+	 */
+	static CMdEEvent* NewLC(CMdESession* aSession, CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef );
+
+	/**
+	 * Create new event from serialized buffer
+	 *
+	 * @param aDef       Definition of the new event.
+	 * @param aObjectId  Identifier of the object that the new event is related to.
+	 * @param aTime      Time when the new event occurred.
+	 * @param aSource       Source of the new event. Ownership of the pointed object remains on caller.
+	 * @param aParticipant  Participant of the new event. Ownership of the pointed object remains on caller.
+	 * @return new event
+	 */
+	static CMdEEvent* NewL(CMdEEventDef& aDef, TItemId aObjectId, TTime aTime,
+			const TDesC* aSource, const TDesC* aParticipant);
+
+	/**
+	 * Create new event from serialized buffer and leaves it on stack
+	 *
+	 * @param aDef       Definition of the new event.
+	 * @param aObjectId  Identifier of the object that the new event is related to.
+	 * @param aTime      Time when the new event occurred.
+	 * @param aSource       Source of the new event. Ownership of the pointed object remains on caller.
+	 * @param aParticipant  Participant of the new event. Ownership of the pointed object remains on caller.
+	 * @return new event
+	 */
+	static CMdEEvent* NewLC(CMdEEventDef& aDef, TItemId aObjectId, TTime aTime,
+			const TDesC* aSource, const TDesC* aParticipant );
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEEvent();
+
+
+	/* Methods. */
+
+	/**
+	 * Returns the definition of the event.
+	 *
+	 * @return  Event definition.
+	 */
+	IMPORT_C CMdEEventDef& Def() const;
+
+	/**
+	 * Returns the identifier of the object that the event is related to.
+	 *
+	 * @return  Object identifier.
+	 */
+	IMPORT_C TItemId ObjectId() const;
+
+	/**
+	 * Returns the time when the event occurred.
+	 *
+	 * @return  Time.
+	 */
+	IMPORT_C TTime Time() const;
+
+	/**
+	 * Returns the source of the event.
+	 *
+	 * @return  Source.
+	 */
+	IMPORT_C const TDesC* Source() const;
+
+	/**
+	 * Returns the participant of the event.
+	 *
+	 * @return  Participant.
+	 */
+	IMPORT_C const TDesC* Participant() const;
+
+	/**
+	 * Calculates required size for buffer to serialize event
+	 *
+	 * @return necessary buffer size
+	 */
+	TUint32 RequiredBufferSize() const;
+
+	/**
+	 * Serialize event
+	 *
+	 * @param aBuffer buffer where serialized event should go
+	 */
+	TMdCOffset SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreespaceOffset) const;
+
+	TMdEInstanceType InstanceType() const;
+
+private:
+	/**
+	 * Constructs a new event.
+	 *
+	 * @param aDef       Definition of the new event.
+	 * @param aObjectId  Identifier of the object that the new event is related to.
+	 * @param aTime      Time when the new event occurred.
+	 */
+	CMdEEvent(CMdESession* aSession, TItemId aId, CMdEEventDef& aDef, TItemId aObjectId, TTime aTime);
+
+	/**
+	 * Second-phase constructor.
+	 *
+	 * @param aSource       Source of the new event. Ownership of the pointed object remains on caller.
+	 * @param aParticipant  Participant of the new event. Ownership of the pointed object remains on caller.
+	 */
+	void ConstructL(const TDesC* aSource, const TDesC* aParticipant);
+
+
+private:
+
+	/** Event definition. */
+	CMdEEventDef& iDef;
+
+	/** Object identifier. */
+	TItemId iObjectId;
+
+	/** Time when the event occurred. */
+	TTime iTime;
+
+	/** Source descriptor. */
+	HBufC* iSource;
+
+	/** Participant descriptor. */
+	HBufC* iParticipant;
+	};
+
+#endif  // __MDEEVENT_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeeventcondition.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,202 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Representation of query event condition
+*
+*/
+
+#ifndef __MDEEVENTCONDITION_H__
+#define __MDEEVENTCONDITION_H__
+
+
+#include <mdecondition.h>
+#include <mderange.h>
+
+
+/* Forward declarations. */
+class CMdELogicCondition;
+class CMdEEventDef;
+class CMdEEventDef;
+
+
+/**
+ * Query condition for events. 
+ */
+NONSHARABLE_CLASS(CMdEEventCondition) : public CMdECondition
+	{
+public:
+    
+	/* Constructors and destructor. */
+
+	/**
+	 * Create new CMdEEventCondition from serialized buffer
+	 *
+	 * @return new CMdEEventCondition
+	 */
+	static CMdEEventCondition* NewL( TItemId aEventId = KNoId,
+			const CMdEEventDef* aEventDef = NULL,
+			const TMdETimeRange* aCreationTimeRange = NULL,
+			TEventConditionCompareMethod aCompareMethod  = EEventConditionCompareNone,
+            const TDesC* aString = NULL );
+	
+	/**
+	 * Create new CMdEEventCondition from serialized buffer and leaves it on stack
+	 *
+	 * @return new CMdEEventCondition
+	 */
+	static CMdEEventCondition* NewLC( TItemId aEventId = KNoId,
+			const CMdEEventDef* aEventDef = NULL,
+			const TMdETimeRange* aCreationTimeRange = NULL,
+			TEventConditionCompareMethod aCompareMethod  = EEventConditionCompareNone,
+            const TDesC* aString = NULL );
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEEventCondition();
+
+
+	/* Methods. */
+
+    /**
+     * Returns the logic condition root node of the conditions defined for
+     * the object which the event is attached to.
+     *
+     * @return  Logic condition.
+     */
+    IMPORT_C CMdELogicCondition& ObjectConditionsL();
+
+    /**
+     * Returns the logic condition root node of the condition defined for
+     * the object whose URI matches the source URI of the event.
+     */
+    IMPORT_C CMdELogicCondition& SourceObjectConditionsL();
+
+    /**
+     * Returns the logic condition root node of the condition defined for
+     * the object whose URI matches the source URI of the event.
+     */
+    IMPORT_C CMdELogicCondition& ParticipantObjectConditionsL();
+
+    /**
+     * Returns the event ID that the condition matches against.
+     *
+     * @return  Event ID.
+     */
+    IMPORT_C TItemId EventId() const;
+
+    /**
+     * Returns the event definition that the condition matches against.
+     *
+     * @return  Event definition. <code>NULL</code>, if not defined.
+     */
+    IMPORT_C const CMdEEventDef* EventDef() const;
+    
+    /** 
+     * Returns the creation time range of the condition. 
+     *
+     * @return  Pointer to the time range. <code>NULL</code>, 
+     *          if not defined.
+     */
+    IMPORT_C const TMdETimeRange* TimeRange() const;
+
+    /** 
+     * Returns the source URI the condition matches against.
+     * 
+     * @return  Source URI. <code>NULL</code>, if not defined. 
+     */
+    IMPORT_C const TDesC* SourceURI() const;
+
+    /** 
+     * Returns the participant URI the condition matches against.
+     * 
+     * @return  Participant URI. <code>NULL</code>, if not defined. 
+     */
+    IMPORT_C const TDesC* ParticipantURI() const;
+
+    /**
+     * Get possible query's internal optimization flags from condition.
+     *
+     * @param aFlaga query's internal optimization flags
+     * @return last level internal optimization flags
+     */
+    TUint32 InternalQueryOptimizationFlags(TUint32& aFlags);
+
+	/**
+     * Get required size of serialized buffer when it is serialized.
+     *
+     * @return required serialized buffer size
+     */
+	TUint32 RequiredBufferSize() const;
+	
+	/**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling) and return new position of serialized buffer.
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    void SerializeL(CMdCSerializationBuffer& aBuffer,
+    		TMdCOffset& aFreespaceOffset) const;
+
+private:
+
+    /* Private methods. */
+
+  	/**
+	 * Constructor for a condition that requires that the event ID a 
+     * certain ID or event is of a certain type.
+     *
+     * @param aEventId  Event ID.
+     * @param aEventDef  Event definition.
+	 */
+	CMdEEventCondition(TItemId aEventId, const CMdEEventDef* aEventDef);
+
+    /**
+	 * Second-phase constructor. Pass <code>NULL</code> in parameters that
+	 * are not needed.
+     *
+     * @param aCreationTimeRange  Range for the creation time.
+     * @param aCompareMethod      Comparison method for the string.
+     * @param aString             Text string to match.
+	 */
+    void ConstructL(const TMdETimeRange* aCreationTimeRange,
+                    TEventConditionCompareMethod aCompareMethod = EEventConditionCompareNone, 
+                    const TDesC* aString = 0);
+
+private:
+
+	const TItemId iEventId;
+
+    /** Event definition to match. <code>NULL</code>, if not defined. */
+    const CMdEEventDef* iEventDef;
+
+    /** Conditions for the object which the event is associated with. */
+    CMdELogicCondition* iObjectConditions;
+
+    /** Creation time range. <code>NULL</code>, if not defined. */
+    TMdETimeRange* iCreationTimeRange;
+
+    /** Source of participant URI to match. <code>NULL</code>, if not defined. */
+    HBufC* iURI;
+
+    /** Conditions for the object whose URI matches the source URI. */
+    CMdELogicCondition* iSourceConditions;
+
+    /** Conditions for the object whose URI matches the participant URI. */
+    CMdELogicCondition* iParticipantConditions;
+
+	/** Method of comparison. */
+	TEventConditionCompareMethod iCompareMethod;
+    };
+
+#endif  // __MDEEVENTCONDITION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeeventdef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,86 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDEEVENTDEF_H__
+#define __MDEEVENTDEF_H__
+
+#include <e32base.h>
+
+#include <mdccommon.h>
+
+// Forward declaration
+class CMdCSerializationBuffer;
+class CMdENamespaceDef;
+class TMdCEventDef;
+
+/**
+ * Event definition.
+ */
+NONSHARABLE_CLASS(CMdEEventDef) : public CBase
+	{
+public:	
+	/**
+	 * Returns the name of the item.
+	 *
+	 * @return  name
+	 */
+	IMPORT_C const TDesC& Name() const;
+	
+	/**
+	 * Compare this event definition with other event definition.
+	 *
+	 * @param aEventDef other event definition
+	 *
+	 * @return  0 if events are same, 1 or more if this is greater than other 
+	 *          and -1 or less if this is less than other.
+	 */
+	IMPORT_C TInt Compare(const CMdEEventDef& aEventDef) const;	
+	
+	/**
+	Returns namespacedef which is associated with eventdef
+	@return namespacedef which is associated with eventdef
+	*/
+	IMPORT_C CMdENamespaceDef& NamespaceDef() const;
+	
+public:
+	static CMdEEventDef* NewL(const TMdCEventDef& aEventDef, CMdCSerializationBuffer& aSchemaBuffer,
+			CMdENamespaceDef& aNamespaceDef);
+
+	static CMdEEventDef* NewLC(const TMdCEventDef& aEventDef, CMdCSerializationBuffer& aSchemaBuffer,
+			CMdENamespaceDef& aNamespaceDef);
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEEventDef();
+
+	TDefId Id() const;	
+
+private:
+	CMdEEventDef(const TMdCEventDef& aEventDef, CMdENamespaceDef& aNamespaceDef);
+
+	void ConstructL(CMdCSerializationBuffer& aSchemaBuffer);
+
+private:
+	const TMdCEventDef& iEventDef;
+	CMdENamespaceDef& iNamespaceDef;
+
+	TPtrC16 iName;
+	};
+
+#endif  // __MDEEVENTDEF_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeeventquery.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,76 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Represents event query
+*
+*/
+
+
+#ifndef __MDEEVENTQUERY_H__
+#define __MDEEVENTQUERY_H__
+
+
+#include <mdequery.h>
+
+
+/* Forward declarations. */
+class CMdEEvent;
+class CMdENamespaceDef;
+
+/**
+ * A query that retrieves a set of events from the metadata engine database.
+ * Most functionality is provided by the CMdEQuery base class.
+ */
+NONSHARABLE_CLASS(CMdEEventQuery) : public CMdEQuery
+	{
+public:
+	
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEEventQuery();
+
+
+	/* Methods. */
+
+    /**
+	 * Returns one of the result events.
+     * 
+     * @param aIndex  Index number of the result item.
+	 *
+	 * @return  The result event that was requested. The query retains 
+     *          ownership of the returned event item.
+	 */
+	IMPORT_C CMdEEvent& Result(TInt aIndex) const;
+
+
+protected:
+
+	/* Constructors. */
+
+	/**
+	 * Constructor. 
+	 *
+	 * @param aSession  Session.
+	 */
+	CMdEEventQuery(CMdESession& aSession, CMdENamespaceDef& aNamespaceDef);
+
+	/**
+	 * Second-phase constructor.
+	 */
+	void EventQueryConstructL();
+	
+    virtual void DoCancel();
+    };
+
+#endif  // __MDEEVENTQUERY_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeinstanceitem.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,67 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDEINSTANCEITEM_H__
+#define __MDEINSTANCEITEM_H__
+
+
+#include <mdeitem.h>
+
+enum TMdEInstanceType
+	{
+	EMdETypeObject = 1,
+	EMdETypeRelation,
+	EMdETypeEvent,
+	EMdETypeProperty
+	};
+
+/**
+ * Abstract base class for all instance items stored in the metadata engine database.
+ */
+NONSHARABLE_CLASS(CMdEInstanceItem) : public CMdEItem
+	{
+public:
+	
+	/* Destructor. */
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEInstanceItem();
+
+
+	/* Methods. */
+
+	virtual TMdEInstanceType InstanceType() const = 0;
+	
+protected:
+
+	/* Constructors. */
+
+	/**
+	 * Constructor.
+	 */
+	CMdEInstanceItem(CMdESession* aSession, TItemId aId);
+
+	/**
+	 * Second-phase constructor.
+	 */
+	void InstanceItemBaseConstruct();
+	};
+
+#endif  // __MDEINSTANCEITEM_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeinternalerror.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,113 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Common internal error code definitions
+*
+*/
+
+#ifndef MDEINTERNALERROR_H
+#define MDEINTERNALERROR_H
+
+#include <e32def.h>
+
+/*
+ * Internal error. Unknown namespace definition.
+ */
+const TInt KErrMdEUnknownNamespaceDef = -36240;
+
+/*
+ * Internal error. Unknown object definition.
+ */
+const TInt KErrMdEUnknownObjectDef = -36241;
+
+/*
+ * Internal error. Unknown property definition.
+ */
+const TInt KErrMdEUnknownPropertyDef = -36242;
+
+/*
+ * Internal error. Unknown relation definition.
+ */
+const TInt KErrMdEUnknownRelationDef = -36243;
+
+/*
+ * Internal error. Unknown event definition.
+ */
+const TInt KErrMdEUnknownEventDef = -36244;
+
+/*
+ * Internal error. Unknown property type.
+ */
+const TInt KErrMdEUnknownPropertyType = -36245;
+
+/*
+ * Internal error. Unknown confidentiality level.
+ */
+const TInt KErrMdEUnknownConfidentialityLevel = -36246;
+
+/*
+ * Internal error. Unknown compare method.
+ */
+const TInt KErrMdEUnknownCompareMethod = -36247;
+
+/*
+ * Internal error. Unknown query type.
+ */
+const TInt KErrMdEUnknownQueryType = -36248;
+
+/*
+ * Internal error. Unknown query result mode.
+ */
+const TInt KErrMdEUnknownQueryResultMode = -36249;
+
+/*
+ * Internal error. Range type is not expected.
+ */
+const TInt KErrMdEUnknownRangeType = -36250;
+
+/*
+ * Internal error. Unknown condition type.
+ */
+const TInt KErrMdEUnknownConditionType = -36251;
+
+/*
+ * Internal error. Unknown condition compare method.
+ */
+const TInt KErrMdEUnknownConditionCompareMethod = -36252;
+
+/*
+ * Internal error. Condition operator is not expected.
+ */
+const TInt KErrMdEIncorrectConditionOperator = -36253;
+
+/*
+ * Internal error. Serialized type is not expected.
+ */
+const TInt KErrMdEIncorrectSerializedType = -36254;
+
+/*
+ * Internal error. Size of serialized type is not expected.
+ */
+const TInt KErrMdEIncorrectSerializedTypeSize = -36255;
+
+/*
+ * Internal error. Schema contains illegal character.
+ */
+const TInt KErrMdESchemaContainsIllegalCharacter = -36256;
+
+/*
+ * Internal error. Schema contains reserved word.
+ */
+const TInt KErrMdESchemaContainsReservedWord = -36257;
+
+#endif /*MDEINTERNALERROR_H*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeitem.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,135 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDEITEM_H__
+#define __MDEITEM_H__
+
+
+#include <e32base.h>
+
+#include <mdccommon.h>
+
+/** 
+ * Internal identifier for metadata engine database items. Must always be
+ * different from 0.
+ */
+class CMdESession;
+
+/**
+ * Abstract base class for all items stored in the metadata engine database.
+ */
+NONSHARABLE_CLASS(CMdEItem) : public CBase
+	{
+public:
+	
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEItem();
+
+
+	/* Methods. */
+
+	/**
+	 * Returns whether the item belongs to a session.
+	 *
+	 * @return  <code>ETrue</code>, if the item belongs to a session;
+	 *          <code>EFalse</code>, otherwise
+	 */
+	IMPORT_C TBool BelongsToSession() const;
+
+	/**
+	 * Returns the session the item belongs to. Panics if
+	 * the item does not belong to any session.
+	 *
+	 * @return  session that the item belongs to
+	 */
+	IMPORT_C CMdESession& Session() const;
+
+	/**
+	 * Returns whether the item is stored in the database.
+	 *
+	 * @return  <code>ETrue</code>, if the item is in the database;
+	 *          <code>EFalse</code>, otherwise
+	 */
+	IMPORT_C TBool InDatabase() const;
+
+	/**
+	 * Returns the internal database identifier of the item. 
+	 *
+	 * @return  internal database identifier or <code>KNoId</code> if item is not stored in database.
+	 */
+	IMPORT_C TItemId Id() const;
+
+	/**
+	 * Sets that the internal database identifier of the object.
+	 *
+	 * @param aId  internal database identifier
+	 */
+	void SetId(TItemId aId);
+
+	/**
+	 * Sets the session the item belongs to. 
+	 *
+	 * @param aSession  session
+	 */
+	void SetSession(CMdESession& aSession);
+
+protected:
+
+	/* Constructors and destructor. */
+	
+	/**
+	 * Constructor. Note that if the new item is in the database
+	 * (i.e., it has an internal database identifier), it must also belong 
+	 * to a session.
+	 *
+	 * @param aSession  session that the new item belongs to;
+	 *                  or 0, if the new item does not belong to any session
+	 * @param aId		internal database identifier of the new item,
+	 *                  if the item is in the database (note that then also 
+	 *                  <code>aSession</code> must be different from 0);
+	 *					or 0, if the item is not in the database
+	 */
+	CMdEItem(CMdESession* aSession, TItemId aId);
+	
+	/**
+	 * Second-phase constructor.
+	 */
+	void ItemBaseConstruct();
+	
+	/* Utility methods. */
+
+	/**
+	 * Panics if the item does not belong to any session.
+	 */
+	void CheckSession() const;
+
+
+private:
+
+	/** Session. */
+	CMdESession* iSession;
+
+	/** Internal database identifier. */
+	TItemId iId;
+	
+	friend class CMdESession;
+	};
+
+#endif  // __MDEITEM_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdelogiccondition.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,656 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDELOGICCONDITION_H__
+#define __MDELOGICCONDITION_H__
+
+
+#include <e32std.h>
+
+#include <mdecondition.h>
+#include <mderange.h>
+#include <mderangepropertycondition.h>
+#include <mdetextpropertycondition.h>
+
+
+/* Forward declarations. */
+class CMdEBoolPropertyCondition;
+class CMdEObjectDef;
+class CMdEPropertyDef;
+class CMdERelationDef;
+class CMdEEventDef;
+class CMdCSerializationBuffer;
+class CMdEEventCondition;
+class CMdEObjectCondition;
+class CMdEPropertyCondition;
+class CMdERelationCondition;
+
+/**
+ * Logic conditions are used for combining other conditions with boolean
+ * AND or OR operators. Each logic condition can have an unlimited number of
+ * child conditions. The same operator is applied to all of the child 
+ * conditions: (X and Y and Z), (X or Y or Z).
+ *
+ * CMdELogicCondition provides a number of factory methods for creating and
+ * adding new nodes as children of the logic condition node. Always use the
+ * factory methods when constructing a query condition tree.
+ *
+ * A logic condition node owns all of its children.
+ */
+NONSHARABLE_CLASS(CMdELogicCondition) : public CMdECondition
+	{
+public:
+
+	/* Constructors and destructor. */
+
+    /**
+     * Constructs a new logic condition node.
+     *
+     * @param aOperator  Operator to use for the child conditions.
+     */
+    IMPORT_C static CMdELogicCondition* NewL(TLogicConditionOperator aOperator);
+
+    /**
+     * Constructs a new logic condition node, leaving the node on the 
+     * cleanup stack.
+     *
+     * @param aOperator  Operator to use for the child conditions.
+     */
+    IMPORT_C static CMdELogicCondition* NewLC(TLogicConditionOperator aOperator);
+
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdELogicCondition();
+
+
+	/* Methods. */
+
+    /**
+     * Returns the operator of the logic condition.
+     *
+     * @return  Logic operator.
+     */
+    IMPORT_C TLogicConditionOperator Operator() const;
+
+    /**
+     * Changes the operator of the logic condition.
+     *
+     * @param aLogicOperator  The new logic operator for the condition.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C void SetOperator(TLogicConditionOperator aLogicOperator);
+
+    /**
+     * Determines the number of child conditions.
+     *
+     * @return  Number of conditions in the logic operation.
+     */
+    IMPORT_C TInt Count() const;
+
+    /**
+     * Returns a child condition node.
+     *
+     * @param aIndex  Index of the condition to return.
+     *
+     * @return  Condition node at the specified index.
+     */
+    IMPORT_C CMdECondition& Condition(TInt aIndex) const;
+
+    /**
+     * Removes a condition node from the logic condition.
+     *
+     * @param aIndex  Index of the condition to remove.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C void Remove(TInt aIndex);
+    
+
+    /* Factory methods for creating and adding new condition nodes into 
+     * the tree. */
+
+    /** 
+     * Creates a new logic condition and makes it a child condition of this
+     * logic condition node.
+     *
+     * @param aLogicOperator  Operator of the new logic condition.
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdELogicCondition& AddLogicConditionL(TLogicConditionOperator aLogicOperator);
+
+    /** 
+     * Creates a new object condition and makes it a child condition of this
+     * logic condition node. The object condition node sets a requirement for
+     * the object class.
+     *
+     * Example:
+     *   // We want the condition to match with image objects.
+     *   CMdELogicCondition* condition = CMdELogicCondition::NewL( ELogicConditionOperatorAnd );
+     *   CleanupStack::PushL( condition );
+     *
+     *   CMdENamespaceDef& defaultNamespace = iMdeSession->GetDefaultNamespaceDefL();
+     *   CMdEObjectDef& imageDef = defaultNamespace.GetObjectDefL( MdeConstants::Image::KImageObject );
+     *   condition->AddObjectConditionL( imageDef );
+     * 
+     * @param aObjectDef     Object definition.
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEObjectCondition& 
+        AddObjectConditionL(const CMdEObjectDef& aObjectDef);
+
+    /**
+     * Creates a new object condition and makes it a child condition of this
+     * logic condition node. The object condition node sets a requirement for
+     * the object's ID number.
+     *
+     * Example:
+     *   CMdERelationQuery* relationQuery = iMdeSession->NewRelationQueryL( defNamespace, this );
+     *   CMdERelationCondition& filterCond = relationQuery->Conditions().
+     *	     AddRelationConditionL( ERelationConditionSideRight );
+     *   // Left object in relation must have this ID.
+     *   filterCond.LeftL().AddObjectConditionL( aObjectId );
+     * 
+     * @param aObjectId  ID number of the object.
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEObjectCondition& AddObjectConditionL(TItemId aObjectId);
+
+    /**
+     * Creates a new object condition and makes it a child condition of this
+     * logic condition node. The object condition node sets a requirement for
+     * the objects' ID numbers.
+     *
+     * @param aObjectId  ID numbers of objects.
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     * 
+     */
+    IMPORT_C CMdEObjectCondition& AddObjectConditionL(
+    		const RArray<TItemId>& aObjectIds);
+
+    /**
+     * Creates a new object condition and makes it a child condition of this
+     * logic condition node. The object condition node sets a requirement for
+     * the object's GUID.
+     *
+     * @param aObjectGuidHigh  GUID high part of the object.
+     * @param aObjectGuidLow  GUID low part of the object.
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEObjectCondition& AddObjectConditionL(
+    		TInt64 aObjectGuidHigh, TInt64 aObjectGuidLow);
+
+    /**
+     * Creates a new object condition and makes it a child condition of this
+     * logic condition node. 
+     *
+     * @param aCompareMethod  Comparison method.
+     * @param aString         Text string to look for.
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEObjectCondition& AddObjectConditionL(
+    		TObjectConditionCompareMethod aCompareMethod, 
+    		const TDesC& aString);
+
+    /**
+     * Creates a new object condition and makes it a child condition of this
+     * logic condition node. 
+     *
+     * @param aRange  range for usage count
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEObjectCondition& AddObjectConditionL(
+    		const TMdEUintRange& aRange);
+
+    /**
+     * Creates a new property condition and makes it a child condition of this
+     * logic condition node. The property condition tests if a property 
+     * exists in an object.
+     *	
+     * Example:
+	 *   CMdEPropertyDef& commentDef = objDef.GetPropertyDefL( MdeConstants::MediaObject::KCommentProperty );
+	 *   iQuery->Conditions().AddPropertyConditionL( commentDef );				
+	 *
+     * @param aPropertyDef  The property to look for.
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEPropertyCondition& AddPropertyConditionL(
+    		const CMdEPropertyDef& aPropertyDef);
+
+    /**
+     * Creates a new boolean property condition and makes it a child 
+     * condition of this logic condition node. The property condition
+     * tests the value of a boolean property.
+     *
+     * Example:
+	 *   CMdEPropertyDef& commentDef = objDef.GetPropertyDefL( MdeConstants::MediaObject::KProtectedProperty );
+	 *   iQuery->Conditions().AddPropertyConditionL( commentDef, ETrue );	
+     * 
+     * @param aPropertyDef  Property definition.
+     * @param aBoolValue    Boolean value.
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEBoolPropertyCondition& AddPropertyConditionL(
+    		const CMdEPropertyDef& aPropertyDef, TBool aBoolValue);
+
+    /**
+     * Creates a new integer property condition and makes it a child 
+     * condition of this logic condition node. The property condition defines
+     * a range of integer values. If the property's value is within the range
+     * the condition evaluates to True.
+     *
+     * Example:
+	 *   CMdEPropertyDef& frameCountDef = objDef.GetPropertyDefL( MdeConstants::Image::FrameCount );
+	 *   iQuery->Conditions().AddPropertyConditionL( frameCountDef, TMdEIntRange(0, 5, rangeType) );
+     *
+     * @param aPropertyDef  Property definition.
+     * @param aIntRange     Range of integer values.
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEIntRangePropertyCondition& AddPropertyConditionL(
+    		const CMdEPropertyDef& aPropertyDef, 
+    		const TMdEIntRange& aIntRange);
+
+    /**
+     * Creates a new 64 bit integer property condition and makes it a child 
+     * condition of this logic condition node. The property condition defines
+     * a range of integer values. If the property's value is within the range
+     * the condition evaluates to True.
+     *
+     * @param aPropertyDef  Property definition.
+     * @param aInt64Range     Range of 64 bit integer values.
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEInt64RangePropertyCondition& AddPropertyConditionL(
+    		const CMdEPropertyDef& aPropertyDef,
+    		const TMdEInt64Range& aIntRange);
+
+    /**
+     * Creates a new unsigned integer property condition and makes it a child 
+     * condition of this logic condition node. The property condition defines
+     * a range of unsigned integer values. If the property's value is within 
+     * the range the condition evaluates to True.
+     *
+     * @param aPropertyDef  Property definition.
+     * @param aUintRange    Range of unsigned integer values.
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEUintRangePropertyCondition& AddPropertyConditionL(
+    		const CMdEPropertyDef& aPropertyDef,
+            const TMdEUintRange& aUintRange);
+
+    /**
+     * Creates a new floating-point property condition and makes it a child 
+     * condition of this logic condition node. The property condition defines
+     * a range of floating-point values. If the property's value is within 
+     * the range the condition evaluates to True.
+     *
+     * @param aPropertyDef  Property definition.
+     * @param aRealRange    Range of floating-point values.
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdERealRangePropertyCondition& AddPropertyConditionL(
+    		const CMdEPropertyDef& aPropertyDef,
+            const TMdERealRange& aRealRange);
+
+    /**
+     * Creates a new time property condition and makes it a child 
+     * condition of this logic condition node. The property condition defines
+     * a range of time values. If the property's value is within the range
+     * the condition evaluates to True.
+     *
+     * @param aPropertyDef  Property definition.
+     * @param aTimeRange    Range of time values.
+     *
+     * @return  Reference to the new condition node.
+     *
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdETimeRangePropertyCondition& AddPropertyConditionL(
+    		const CMdEPropertyDef& aPropertyDef,
+            const TMdETimeRange& aTimeRange);
+
+    /**
+     * Creates a new text property condition and makes it a child condition 
+     * of this logic condition node.
+     *
+     * @param aPropertyDef   Property definition.
+     * @param aCompareMethod Comparison method.
+     * @param aText          Text string to look for.
+     * 
+     * @return Reference to the new condition node.
+     * 
+     * @panic TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdETextPropertyCondition& AddPropertyConditionL(
+    		const CMdEPropertyDef& aPropertyDef,
+    		TTextPropertyConditionCompareMethod aCompareMethod,
+            const TDesC& aText);
+
+    /**
+     * Creates a new relation condition and makes it a child condition of this
+     * logic condition node. The new relation condition contains no parameters
+     * by default. It is assumed that the relation condition is augmented
+     * with further conditions for the objects to which the relation is 
+     * attached.
+     *
+     * Example:
+     *   TItemId relationId( 1 );
+     *   CMdERelationCondition& relationCond = relationQuery->Conditions().
+     *		AddRelationConditionL( relationId, ERelationConditionSideRight );
+     * 
+     * @param aRelationId  Relation ID.
+     * @param aSide The side on which an object must be.
+     * 
+     * @return Reference to the new condition node.
+     * 
+     * @panic TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdERelationCondition& AddRelationConditionL(TItemId aRelationId, 
+    		TRelationConditionSide aSide = ERelationConditionSideEither);
+
+    /**
+     * Creates a new relation condition and makes it a child condition of this
+     * logic condition node. The new relation condition contains no parameters
+     * by default. It is assumed that the relation condition is augmented
+     * with further conditions for the objects to which the relation is 
+     * attached.
+     * 
+     * Example:
+     *   RArray<TItemId> arrayOfIds;
+     *   arrayOfIds.Append( TItemId( 1 ) );
+     *   arrayOfIds.Append( TItemId( 2 ) );
+     *   CMdERelationCondition& relationCond = relationQuery->Conditions().
+     *		AddRelationConditionL( arrayOfIds, ERelationConditionSideRight );
+     *
+     * @param aRelationIds Array of Relation IDs.
+     * @param aSide The side on which an object must be.
+     * 
+     * @return Reference to the new condition node.
+     * 
+     * @panic TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdERelationCondition& AddRelationConditionL(
+    		RArray<TItemId>& aRelationIds, 
+        	TRelationConditionSide aSide = ERelationConditionSideEither);
+    
+    /**
+     * Creates a new relation condition and makes it a child condition of this
+     * logic condition node. The new relation condition contains no parameters
+     * by default. It is assumed that the relation condition is augmented
+     * with further conditions for the objects to which the relation is 
+     * attached.
+     * 
+     * Example:
+     *   CMdERelationCondition& relationCond = relationQuery->Conditions().
+     *		AddRelationConditionL( ERelationConditionSideRight );
+     *
+     * @param aSide The side on which an object must be.
+     *
+     * @return Reference to the new condition node.
+     * 
+     * @panic TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdERelationCondition& AddRelationConditionL(
+        		TRelationConditionSide aSide = ERelationConditionSideEither);
+
+    /**
+     * Creates a new relation condition and makes it a child condition of this
+     * logic condition node. The new relation condition tests the relation's 
+     * type. The relation condition can be augmented with further conditions
+     * for the objects to which the relation is attached.
+     *
+	 * @param aRelationDef  relation definition
+     * @param aSide The side on which an object must be. Defaults to 
+     *              ERelationConditionSideEither.
+     * 
+     * @return Reference to the new condition node.
+     * 
+     * @panic TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdERelationCondition& AddRelationConditionL(
+    		const CMdERelationDef& aRelationDef, 
+    		TRelationConditionSide aSide = ERelationConditionSideEither);
+
+    /**
+     * Creates a new relation condition and makes it a child condition of this
+     * logic condition node. The new relation condition tests the relation's 
+     * type. The relation condition can be augmented with further conditions
+     * for the objects to which the relation is attached.
+     *
+	 * @param aRelationDef  relation definition
+     * @param aIntRange parameter range conditions
+     * @param aSide  The side on which an object must be.
+     * 
+     * @return  Reference to the new condition node.
+     * 
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdERelationCondition& AddRelationConditionL(
+    		const CMdERelationDef& aRelationDef, const TMdEIntRange& aIntRange,
+    		TRelationConditionSide aSide = ERelationConditionSideEither);
+
+
+    /**
+     * Creates a new event condition and makes it a child condition of this
+     * logic condition node. The new event condition contains no parameters
+     * by default. It is assumed that the event condition is augmented
+     * with further conditions for the object to which the event is attached.
+     * 
+     * @return  Reference to the new condition node.
+     * 
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEEventCondition& AddEventConditionL();
+
+    /**
+     * Creates a new event condition and makes it a child condition of this
+     * logic condition node. The new event condition tests the event's type.
+     * The event condition can be augmented with further conditions
+     * for the object to which the event is attached.
+     * 
+     * @param aEventId  Event ID.
+     *
+     * @return  Reference to the new condition node.
+     * 
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEEventCondition& AddEventConditionL(TItemId aEventId);
+
+    /**
+     * Creates a new event condition and makes it a child condition of this
+     * logic condition node. The new event condition tests the event's type.
+     * The event condition can be augmented with further conditions
+     * for the object to which the event is attached.
+     * 
+     * @param aEventDef  Event definition.
+     *
+     * @return  Reference to the new condition node.
+     * 
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEEventCondition& AddEventConditionL(
+    		const CMdEEventDef& aEventDef);
+
+    /**
+     * Creates a new event condition and makes it a child condition of this
+     * logic condition node. The new event condition tests the event's 
+     * creation time. The event condition can be augmented with further 
+     * conditions for the object to which the event is attached.
+     * 
+     * @param aCreationTimeRange  Time range.
+     *
+     * @return  Reference to the new condition node.
+     * 
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEEventCondition& AddEventConditionL(
+    		const TMdETimeRange& aCreationTimeRange);
+
+    /**
+     * Creates a new event condition and makes it a child condition of this
+     * logic condition node. The new event condition tests the event's 
+     * source or participant. The event condition can be augmented with 
+     * further conditions for the object to which the event is attached.
+     * 
+     * @param aCompareMethod  Comparison method.
+     * @param aString         Text string to look for.
+     *
+     * @return  Reference to the new condition node.
+     * 
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEEventCondition& AddEventConditionL(
+    		TEventConditionCompareMethod aCompareMethod, const TDesC& aString);
+
+    /**
+     * Creates a new event condition and makes it a child condition of this
+     * logic condition node. The new event condition tests the event's 
+     * creation time. The new event condition also tests the event's 
+     * source or participant. The event condition can be augmented with 
+     * further conditions for the object to which the event is attached.
+     * 
+     * @param aCreationTimeRange  Time range.
+     * @param aCompareMethod      Comparison method.
+     * @param aString             Text string to look for.
+     *
+     * @return  Reference to the new condition node.
+     * 
+     * @panic  TMdEPanic::EConditionLocked  Condition node is locked.
+     */
+    IMPORT_C CMdEEventCondition& AddEventConditionL(
+    		const TMdETimeRange& aCreationTimeRange,
+            TEventConditionCompareMethod aCompareMethod, const TDesC& aString);
+
+    /**
+     * Locking a logic condition causes all children to be locked as well.
+     * Attempting to modify a locked condition causes a panic.
+     *
+     * @param aLocked  <code>ETrue</code> to lock; 
+     *                 <code>EFalse</code> to unlock.
+     */
+    void SetLocked(TBool aLocked = ETrue);
+    
+    /**
+     * Get possible query's internal optimization flags from condition.
+     *
+     * @param aFlaga query's internal optimization flags
+     * @return last level internal optimization flags
+     */
+    TUint32 InternalQueryOptimizationFlags(TUint32& aFlags);
+
+    /**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+    TUint32 RequiredBufferSize() const;
+
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling).
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    void SerializeL(CMdCSerializationBuffer& aBuffer, 
+    		TMdCOffset& aFreespaceOffset) const;
+
+protected:
+
+	/* Constructors. */
+
+	/**
+	 * Constructor. 
+	 *
+	 * @param aOperator  Logic operator.
+	 */
+	CMdELogicCondition(TLogicConditionOperator aOperator);
+
+	/**
+	 * Second-phase constructor.
+	 */
+	void ConstructL();
+
+
+	/* Utility methods. */
+
+    /**
+     * Makes an existing condition node a child node of this logic condition.
+     * The logic condition takes ownership of the node.
+     *
+     * @param aCondition  Condition node.
+     *
+     * @return  Reference to the added node (aCondition).
+     */
+    CMdECondition& AddL(CMdECondition* aCondition);
+
+
+private:
+
+    /** Type of the condition. */
+    TLogicConditionOperator iOperator;
+
+    /** Children of the condition. The logic condition owns all the 
+        child nodes. */
+    RPointerArray<CMdECondition> iChildren;
+
+	TUint32 iOptimizationFlags;
+    };
+
+#endif  // __MDELOGICCONDITION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdenamespacedef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,222 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+#ifndef __MDENAMESPACEDEF_H__
+#define __MDENAMESPACEDEF_H__
+
+
+#include <mdccommon.h>
+
+class CMdESession;
+class CMdCSerializationBuffer;
+class CMdERelationDef;
+class CMdEEventDef;
+class CMdEObjectDef;
+
+class TMdCNamespaceDef;
+
+
+/**
+ * Namespace definition.
+ */
+NONSHARABLE_CLASS(CMdENamespaceDef) : public CBase
+	{
+public:
+	/**
+	 * Returns whether the namespace is read only.
+	 *
+	 * @return  <code>ETrue</code>, if the namespace is read only;
+	 *          <code>EFalse</code>, otherwise
+	 */
+	IMPORT_C TBool ReadOnly() const;
+
+	/**
+	 * Returns the name of the item.
+	 *
+	 * @return  name
+	 */
+	IMPORT_C const TDesC& Name() const;
+
+	/**
+	 * Compare this namespace definition with other namespace definition.
+	 *
+	 * @param aNamespaceDef other namespace definition
+	 *
+	 * @return  0 if namespaces are same, 1 or more if this is greater than other 
+	 *          and -1 or less if this is less than other.
+	 */
+	IMPORT_C TInt Compare(const CMdENamespaceDef& aNamespaceDef) const;
+	
+	/**
+	 * Returns the number of object definitions.
+	 *
+	 * @return  number of object definitions
+	 */
+	IMPORT_C TInt ObjectDefCount() const;
+
+	/**
+	 * Returns the object definition at the specified index.
+	 *
+	 * @param aIndex  index
+	 *
+	 * @return  object definition or leave, if there is no object definition
+	 *          with the specified name.	
+	 *
+	 * @panics if aIndex is out of bounds	 
+	 */
+	IMPORT_C CMdEObjectDef& ObjectDefL(TInt aIndex);
+
+	/**
+	 * Returns the object definition with the specified name.
+	 *
+	 * @param aName       name
+	 *
+	 * @return  object definition or leave, if there is no object definition
+	 *          with the specified name.	 
+	 */
+	IMPORT_C CMdEObjectDef& GetObjectDefL(const TDesC& aName);
+		
+	/**
+	 * Returns the number of relation definitions.
+	 *
+	 * @return  number of relation definitions
+	 */
+	IMPORT_C TInt RelationDefCount() const;
+
+	/**
+	 * Returns the relation definition at the specified index.
+	 *
+	 * @param aIndex  index
+	 *
+	 * @return  relation definition or leave, if there is no object definition
+	 *          with the specified name.	
+	 */
+	IMPORT_C CMdERelationDef& RelationDefL(TInt aIndex);
+
+	/**
+	 * Returns the relation definition with the specified name.
+	 *
+	 * @param aName       name
+	 *
+	 * @return  relation definition or leave, if there is no object definition
+	 *          with the specified name.	
+	 *
+	 * @panics if aIndex is out of bounds	 
+	 */
+	IMPORT_C CMdERelationDef& GetRelationDefL(const TDesC& aName);
+
+	/**
+	 * Returns the number of event definitions. 
+	 *
+	 * @return  number of event definitions
+	 */
+	IMPORT_C TInt EventDefCount() const;
+
+	/**
+	 * Returns the event definition at the specified index.
+	 *
+	 * @param aIndex  index
+	 *
+	 * @return  event definition or leave, if there is no object definition
+	 *          with the specified name.	
+	 * 
+	 * @panics if aIndex is out of bounds
+	 */
+	IMPORT_C CMdEEventDef& EventDefL(TInt aIndex);
+
+	/**
+	 * Returns the event definition with the specified name.
+	 *
+	 * @param aName       name
+	 *
+	 * @return  event definition or leave, if there is no object definition
+	 *          with the specified name.	
+	 */
+	IMPORT_C CMdEEventDef& GetEventDefL(const TDesC& aName);
+
+public:
+	static CMdENamespaceDef* NewL(const CMdESession& aMdeSession, 
+			const TMdCNamespaceDef& aNamespaceDef, 
+			CMdCSerializationBuffer& aSchemaBuffer);
+
+	static CMdENamespaceDef* NewLC(const CMdESession& aMdeSession, 
+			const TMdCNamespaceDef& aNamespaceDef, 
+			CMdCSerializationBuffer& aSchemaBuffer);
+		
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdENamespaceDef();
+	
+	TDefId Id() const;		
+	
+	/**
+	 * Returns the object definition with the specified id.
+	 *
+	 * @param aId       id
+	 *
+	 * @return  object definition; or 0, if there is no object definition
+	 *          with the specified id
+	 */
+	CMdEObjectDef* GetObjectDefL(TDefId aId);	
+
+	/**
+	 * Returns the relation definition with the specified id.
+	 *
+	 * @param aId       id
+	 *
+	 * @return  relation definition; or 0, if there is no relation definition
+	 *          with the specified id
+	 */
+	CMdERelationDef* GetRelationDefL(TDefId aId);
+
+	/**
+	 * Returns the event definition with the specified id.
+	 *
+	 * @param aId       id
+	 *
+	 * @return  event definition; or 0, if there is no event definition
+	 *          with the specified id
+	 */
+	CMdEEventDef* GetEventDefL(TDefId aId);
+	
+	/**
+	 * Returns the MdE session where namespace definition belongs.
+	 *
+	 * @return MdE session
+	 */
+	const CMdESession& Session() const;
+
+private:
+	CMdENamespaceDef(const CMdESession& aMdeSession, 
+			const TMdCNamespaceDef& aNamespaceDef);
+
+	void ConstructL(CMdCSerializationBuffer& aSchemaBuffer);
+
+private:
+	const CMdESession& iMdeSession;
+
+	const TMdCNamespaceDef& iNamespaceDef;
+
+	TPtrC16 iName;
+
+	RPointerArray<CMdEObjectDef> iObjectDefs;
+	RPointerArray<CMdERelationDef> iRelationDefs;
+	RPointerArray<CMdEEventDef> iEventDefs;
+	};
+
+#endif  // __MDENAMESPACEDEF_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdenumberproperty.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,61 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CMdENumberPropertys' compatible wrapper to CMdEProperty
+*
+*/
+
+#ifndef __MDENUMBERPROPERTY_H__
+#define __MDENUMBERPROPERTY_H__
+
+#include <mdeproperty.h>
+
+/**
+ * Template for number property compatibility wrappers to property.
+ */
+template< class T >
+class CMdENumberProperty : public CMdEProperty
+	{
+public:
+	/**
+	 * Returns the value of the property.
+	 *
+	 * @return  value
+	 */
+	T Value() const;
+
+	/**
+	 * Sets the value of the property.
+	 *
+	 * @param aValue       New value.
+	 */
+	void SetValueL(T aValue);
+	};
+
+/* Typedefs for numeric properties. */
+typedef CMdENumberProperty<TBool>   CMdEBoolProperty;
+typedef CMdENumberProperty<TInt8>   CMdEInt8Property;
+typedef CMdENumberProperty<TUint8>  CMdEUint8Property;
+typedef CMdENumberProperty<TInt16>  CMdEInt16Property;
+typedef CMdENumberProperty<TUint16> CMdEUint16Property;
+typedef CMdENumberProperty<TInt32>  CMdEInt32Property;
+typedef CMdENumberProperty<TUint32> CMdEUint32Property;
+typedef CMdENumberProperty<TInt64>  CMdEInt64Property;
+typedef CMdENumberProperty<TReal32> CMdEReal32Property;
+typedef CMdENumberProperty<TReal64> CMdEReal64Property;
+typedef CMdENumberProperty<TTime>   CMdETimeProperty;
+
+
+#include <mdenumberproperty.inl>
+
+#endif  // __MDENUMBERPROPERTY_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdenumberproperty.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CMdENumberPropertys' compatible wrapper to CMdEProperty
+*
+*/
+
+
+#include <mdepropertydef.h>
+
+#define MDE_DEFINE_NUMBER_PROPERTY(PropertyType) \
+template<> inline T##PropertyType CMdENumberProperty< T##PropertyType >::Value() const \
+    { \
+    T##PropertyType value = NULL; \
+    TRAPD( err, value = PropertyType##ValueL() ); \
+	if( err != KErrNone ) \
+		{ \
+		_LIT( KCMdEPropertyGetValuePanic, "CMdE##PropertyType##Property::Value" ); \
+		User::Panic( KCMdEPropertyGetValuePanic, KErrNotSupported ); \
+		} \
+    return value; \
+    } \
+    template<> inline void CMdENumberProperty<T##PropertyType>::SetValueL(T##PropertyType aValue) \
+    { \
+    TRAPD( err, Set##PropertyType##ValueL( aValue ) ); \
+	if( err != KErrNone ) \
+		{ \
+		_LIT( KCMdEPropertySetValuePanic, "CMdE##PropertyType##Property::SetValueL" ); \
+		User::Panic( KCMdEPropertySetValuePanic, KErrNotSupported ); \
+		} \
+    }
+
+MDE_DEFINE_NUMBER_PROPERTY(Bool)
+MDE_DEFINE_NUMBER_PROPERTY(Int8)
+MDE_DEFINE_NUMBER_PROPERTY(Uint8)
+MDE_DEFINE_NUMBER_PROPERTY(Int16)
+MDE_DEFINE_NUMBER_PROPERTY(Uint16)
+MDE_DEFINE_NUMBER_PROPERTY(Int32)
+MDE_DEFINE_NUMBER_PROPERTY(Uint32)
+MDE_DEFINE_NUMBER_PROPERTY(Int64)
+MDE_DEFINE_NUMBER_PROPERTY(Real32)
+MDE_DEFINE_NUMBER_PROPERTY(Real64)
+MDE_DEFINE_NUMBER_PROPERTY(Time)
+
+#undef MDE_DEFINE_NUMBER_PROPERTY
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeobject.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,745 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDEOBJECT_H__
+#define __MDEOBJECT_H__
+
+//#include <uri16.h>
+
+#include <mdeinstanceitem.h>
+
+// CMdEProperty compatibility wrappers
+#include <mdetextproperty.h>
+#include <mdenumberproperty.h>
+
+/* Forward declarations. */
+class CMdEObjectDef;
+class CMdEPropertyDef;
+class CMdEProperty;
+class CMdCSerializationBuffer;
+class CMdENamespaceDef;
+
+NONSHARABLE_CLASS( TMdEObject )
+	{
+public:
+	/* Constructors and destructor. */
+
+	/**
+	 * Constructs a new object.
+	 */
+	IMPORT_C TMdEObject();
+
+	/**
+	 * Returns the ID of the object.
+	 *
+	 * @return  Object ID.
+	 */
+	IMPORT_C TItemId Id() const;
+
+	/**
+	 * Returns the definition of the object. Leaves with error code 
+	 * KErrNotFound if object definition is missing.
+	 *
+	 * @return Object definition.
+	 */
+	IMPORT_C const CMdEObjectDef& DefL() const;
+	
+	/**
+	 * Returns whether object is confidential or not.
+	 *
+	 * @return  <code>ETrue</code>, if the object has been set to confidential.
+	 *          <code>EFalse</code>, otherwise.
+	 */
+	IMPORT_C TBool Confidential() const;
+	
+	/**
+	 * Returns whether object is placeholder or not.
+	 *
+	 * @return  <code>ETrue</code>, if the object has been set to placeholder.
+	 *          <code>EFalse</code>, otherwise.
+	 */
+	IMPORT_C TBool Placeholder() const;
+
+	/**
+	 * Returns whether object is removed or not.
+	 *
+	 * @return  <code>ETrue</code>, if the object has been set to removed.
+	 *          <code>EFalse</code>, otherwise.
+	 */
+	IMPORT_C TBool Removed() const;
+	
+	/**
+	 * Returns whether object is present or not.
+	 *
+	 * @return  <code>ETrue</code>, if the object has been set to not present.
+	 *          <code>EFalse</code>, otherwise.
+	 */
+	IMPORT_C TBool NotPresent() const;
+	
+public:
+	/**
+	 * Calculates required size for buffer to serialize object
+	 *
+	 * @return necessary buffer size
+	 */
+	static TUint32 RequiredBufferSize();
+
+	/**
+	 * Retrieve object from serialized buffer
+	 *
+	 * @param aBuffer buffer where serialized object is
+	 * @param aNamespaceDef namespace definition of namespace where object is 
+	 *                      located
+	 */
+	void DeSerializeL(CMdCSerializationBuffer& aBuffer, 
+			CMdENamespaceDef& aNamespaceDef);
+
+protected:
+	/** object ID */
+	TItemId iId;
+
+	/** Pointer to object definition, this doesn't own it. */
+	CMdEObjectDef* iDef;
+
+	/** various flags */
+	TUint32 iFlags;
+	};
+
+/**
+ * Object.
+ */
+NONSHARABLE_CLASS(CMdEObject) : public CMdEInstanceItem
+	{
+public:
+
+	/* Constructors and destructor. */
+
+	/**
+	 * Constructs a new object from serialized buffer
+	 *
+	 * @param aBuffer  buffer which contains serialized object
+	 * @param aNamespaceDef  reference to namespace where to object is created
+	 */
+	static CMdEObject* NewL( CMdESession* aSession, CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef );
+
+	/**
+	 * Constructs a new object from serialized buffer and leave it on stack
+	 *
+	 * @param aBuffer  buffer which contains serialized object
+	 * @param aNamespaceDef  reference to namespace where to object is created
+	 */
+	static CMdEObject* NewLC( CMdESession* aSession, CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef );
+
+	/**
+	 * Constructs a new object.
+	 *
+	 * @param aDef  Definition of the new object.
+	 * @param aUri URI of the new object.
+	 * @param aMediaId mediaid of object. Defaults to 0.
+	 */
+
+	static CMdEObject* NewL( CMdEObjectDef& aDef, const TDesC& aUri, TUint32 aMediaId = 0 );
+
+	/**
+	 * Constructs a new object.
+	 *
+	 * @param aDef  Definition of the new object.
+	 * @param aUri URI of the new object.
+	 * @param aMediaId mediaid of object. Defaults to 0.
+	 */
+	static CMdEObject* NewLC( CMdEObjectDef& aDef, const TDesC& aUri, TUint32 aMediaId = 0 );
+
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEObject();
+
+	/* Methods. */
+
+	/**
+	 * Returns the definition of the object.
+	 *
+	 * @return  Object definition.
+	 */
+	IMPORT_C CMdEObjectDef& Def() const;
+
+	/**
+	 * Sets the definition of the object. Object's old object definition must 
+	 * be "Object" and object must not belong to any session, otherwise method 
+	 * leaves with error code KErrNotSupported.
+	 * 
+	 * @param aDef  New object definition.
+	 */
+	IMPORT_C void SetDefL(CMdEObjectDef& aDef);
+
+	/**
+	 * Returns the URI of the object.
+	 *
+	 * @return  URI.
+	 */
+	IMPORT_C const TDesC& Uri() const;
+
+	/**
+	 * Sets the URI of the object.
+	 *
+	 * @param aUri  New URI.
+	 */
+	IMPORT_C void SetUriL(const TDesC& aUri);
+
+	/**
+	 * Returns whether object is confidential or not.
+	 *
+	 * @return  <code>ETrue</code>, if the object has been set to confidential.
+	 *          <code>EFalse</code>, otherwise.
+	 */
+	IMPORT_C TBool Confidential() const;
+
+	/**
+	 * Returns whether object is confidential or not.
+	 *
+	 * @param aValue  <code>ETrue</code>, if the object is confidential.
+	 *                <code>EFalse</code>, otherwise.
+	 */
+	IMPORT_C void SetConfidential(TBool aValue);
+
+	/**
+	 * Returns whether object is placeholder or not.
+	 *
+	 * @return  <code>ETrue</code>, if the object has been set to placeholder.
+	 *          <code>EFalse</code>, otherwise.
+	 */
+	IMPORT_C TBool Placeholder() const;
+
+	/**
+	 * Returns whether object is placeholder or not.
+	 *
+	 * @param aValue  <code>ETrue</code>, if the object is placeholder.
+	 *                <code>EFalse</code>, otherwise.
+	 */
+	IMPORT_C void SetPlaceholder(TBool aValue);
+
+	
+	/**
+	 * Returns the Media ID of the object.
+	 *
+	 * @return  Media ID.
+	 */
+	IMPORT_C TUint32 MediaId() const;
+	
+	/**
+	 * Sets the Media ID of the object.
+	 *
+	 * @param aMediaId  New Media ID.
+	 */
+	IMPORT_C void SetMediaId(TUint32 aMediaId);
+
+	/**
+	 * Returns the usage count of the object.
+	 *
+	 * @return usage count
+	 */
+	IMPORT_C TUint32 UsageCount() const;
+	
+	/**
+	 * Returns the Guid of the object.
+	 *
+	 * @param aGuidHigh reference where GuidHigh will be stored
+	 * @param aGuidLow reference where GuidLow will be stored
+	 */
+	IMPORT_C void Guid( TInt64& aGuidHigh, TInt64& aGuidLow ) const;
+
+	/**
+	 * Sets the Guid of the object.
+	 *
+	 * @param aGuidHigh new GuidHigh value
+	 * @param aGuidLow new GuidLow value
+	 */
+	IMPORT_C void SetGuid( const TInt64& aGuidHigh, const TInt64& aGuidLow );
+
+	/**
+	 * Returns whether the object is open for modifications or not.
+	 *
+	 * @return  <code>ETrue</code>, if the object is open for modifications.
+	 *          <code>EFalse</code>, otherwise.
+	 */
+	IMPORT_C TBool OpenForModifications() const;
+
+	/* Methods for accessing properties. */
+
+	/**
+	 * Returns the number of properties.
+	 *
+	 * @return  number of properties
+	 */
+	IMPORT_C TInt PropertyCount() const;
+
+	/**
+	 * Returns the property at the specified index.
+	 *
+	 * @param aIndex  index
+	 *
+	 * @return  property
+	 */
+	IMPORT_C CMdEProperty& PropertyL(TInt aIndex) const;
+
+	/**
+	 * Returns the property by given property def
+	 *
+	 * Example:
+	 *  CMdENamespaceDef& defaultNamespace = iMdeSession->GetDefaultNamespaceDefL();
+     *	CMdEObjectDef& imageDef = defaultNamespace.GetObjectDefL( MdeConstants::Image::KImageObject );
+	 *  CMdEObject* image = iMdESession->OpenObjectL( 17, imageDef );
+	 * 
+	 *  CMdEPropertyDef& lastModDatePropDef = imageDef.GetPropertyDefL(
+     *   		Object::KLastModifiedDateProperty );
+     * 
+     *  CMdEProperty* lastModDateProp = NULL;
+     *  image->Property( lastModDatePropDef, lastModDateProp );
+	 * 
+	 * @param aDef      property definition
+	 * @param aProperty ref to pointer that will receive property address, if such is found.
+	 * @param aStartAt  index where to begin search(by default starts from beginning)
+	 *
+	 * @return  Index, or <code>KErrNotFound</code>.
+	 */
+    IMPORT_C TInt Property(const CMdEPropertyDef& aDef, CMdEProperty*& aProperty, TInt aStartAt=0) const;
+
+	/**
+	 * Returns the number of properties of the specified definition.
+	 *
+	 * @param aDef  property definition
+	 *
+	 * @return  number of properties
+	 */
+	IMPORT_C TInt PropertyCount(const CMdEPropertyDef& aDef) const;
+
+	/**
+	 * Adds a new bool property to the object. If property definition doesn't 
+	 * match with value, method leaves with error code KErrArgument.
+	 * 
+	 * Example:
+	 *   CMdEPropertyDef& receivedDef = objectDef.GetPropertyDefL( MdeConstants::Message::KReceivedProperty );
+	 *   metadataObject.AddBoolPropertyL( receivedDef, ETrue );
+	 *
+	 * @param aDef         Definition of the new property.
+	 * @param aValue       Value of the new property.
+	 *
+	 * @return  New property.
+	 */
+	IMPORT_C CMdEProperty& AddBoolPropertyL(CMdEPropertyDef& aDef, TBool aValue);
+
+	/**
+	 * Adds a new signed 8-bit integer property to the object. If property 
+	 * definition doesn't match with value, method leaves with error code 
+	 * KErrArgument.
+	 * 
+	 * Example:
+	 *   CMdEPropertyDef& eightBitDef = objectDef.GetPropertyDefL( MdeConstants::Object::KProperty );
+	 *   metadataObject.AddInt8PropertyL( eightBitDef, value );
+	 *
+	 * @param aDef         Definition of the new property.
+	 * @param aValue       Value of the new property.
+	 *
+	 * @return  New property.
+	 */
+	IMPORT_C CMdEProperty& AddInt8PropertyL(CMdEPropertyDef& aDef, TInt8 aValue);
+
+	/**
+	 * Adds a new unsigned 8-bit integer property to the object. If property 
+	 * definition doesn't match with value, method leaves with error code 
+	 * KErrArgument.
+	 *
+	 * Example:
+	 *   CMdEPropertyDef& eightBitDef = objectDef.GetPropertyDefL( MdeConstants::Object::KProperty );
+	 *   metadataObject.AddUint8PropertyL( eightBitDef, value );
+	 * 
+	 * @param aDef         Definition of the new property.
+	 * @param aValue       Value of the new property.
+	 *
+	 * @return  New property.
+	 */
+	IMPORT_C CMdEProperty& AddUint8PropertyL(CMdEPropertyDef& aDef, TUint8 aValue);
+
+	/**
+	 * Adds a new signed 16-bit integer property to the object. If property 
+	 * definition doesn't match with value, method leaves with error code 
+	 * KErrArgument.
+	 *
+	 * Example:
+	 *   CMdEPropertyDef& propertyDef = objectDef.GetPropertyDefL( MdeConstants::Object::KProperty );
+	 *   metadataObject.AddInt16PropertyL( propertyDef, value ); 
+	 *
+	 * @param aDef         Definition of the new property.
+	 * @param aValue       Value of the new property.
+	 *
+	 * @return  New property.
+	 */
+	IMPORT_C CMdEProperty& AddInt16PropertyL(CMdEPropertyDef& aDef, TInt16 aValue);
+
+	/**
+	 * Adds a new unsigned 16-bit integer property to the object. If property 
+	 * definition doesn't match with value, method leaves with error code 
+	 * KErrArgument.
+	 *
+	 * Example:
+	 *   CMdEPropertyDef& propertyDef = objectDef.GetPropertyDefL( MdeConstants::Object::KProperty );
+	 *   metadataObject.AddUint16PropertyL( propertyDef, value );
+	 * 
+	 * @param aDef         Definition of the new property.
+	 * @param aValue       Value of the new property.
+	 *
+	 * @return  New property.
+	 */	 
+	IMPORT_C CMdEProperty& AddUint16PropertyL(CMdEPropertyDef& aDef, TUint16 aValue);
+
+	/**
+	 * Adds a new signed 32-bit integer property to the object. If property 
+	 * definition doesn't match with value, method leaves with error code 
+	 * KErrArgument.
+	 * 
+	 * Example:
+	 *   CMdEPropertyDef& propertyDef = objectDef.GetPropertyDefL( MdeConstants::Object::KProperty );
+	 *   metadataObject.AddInt32PropertyL( propertyDef, value );
+	 *
+	 * @param aDef         Definition of the new property.
+	 * @param aValue       Value of the new property.
+	 *
+	 * @return  New property.
+	 */
+	IMPORT_C CMdEProperty& AddInt32PropertyL(CMdEPropertyDef& aDef, TInt32 aValue);
+
+	/**
+	 * Adds a new unsigned 32-bit integer property to the object. If property 
+	 * definition doesn't match with value, method leaves with error code 
+	 * KErrArgument.
+	 * 
+	 * Example:
+	 *   CMdEPropertyDef& propertyDef = objectDef.GetPropertyDefL( MdeConstants::Object::KProperty );
+	 *   metadataObject.AddUint32PropertyL( propertyDef, value );
+	 *
+	 * @param aDef         Definition of the new property. If property definition doesn't 
+	 * match with value, method leaves with error code KErrArgument.
+	 * @param aValue       Value of the new property.
+	 *
+	 * @return  New property.
+	 */
+	IMPORT_C CMdEProperty& AddUint32PropertyL(CMdEPropertyDef& aDef, TUint32 aValue);
+
+	/**
+	 * Adds a new 64-bit integer property to the object. If property definition 
+	 * doesn't match with value, method leaves with error code KErrArgument.
+	 *
+	 * Example:
+	 *   CMdEPropertyDef& propertyDef = objectDef.GetPropertyDefL( MdeConstants::Object::KProperty );
+	 *   metadataObject.AddInt64PropertyL( propertyDef, value );
+	 * 
+	 * @param aDef         Definition of the new property.
+	 * @param aValue       Value of the new property.
+	 *
+	 * @return  New property.
+	 */
+	IMPORT_C CMdEProperty& AddInt64PropertyL(CMdEPropertyDef& aDef, TInt64 aValue);
+
+	/**
+	 * Adds a new 32-bit real property to the object. If property definition 
+	 * doesn't match with value, method leaves with error code KErrArgument.
+	 *
+	 * Example:
+	 *   CMdEPropertyDef& propertyDef = objectDef.GetPropertyDefL( MdeConstants::Object::KProperty );
+	 *   metadataObject.AddReal32PropertyL( propertyDef, realValue );
+	 * 
+	 * @param aDef         Definition of the new property.
+	 * @param aValue       Value of the new property.
+	 *
+	 * @return  New property.
+	 */
+	IMPORT_C CMdEProperty& AddReal32PropertyL(CMdEPropertyDef& aDef, TReal32 aValue);
+
+	/**
+	 * Adds a new 64-bit real property to the object. If property definition 
+	 * doesn't match with value, method leaves with error code KErrArgument.
+	 *
+	 * Example:
+	 *   CMdEPropertyDef& propertyDef = objectDef.GetPropertyDefL( MdeConstants::Object::KProperty );
+	 *   metadataObject.AddReal64PropertyL( propertyDef, realValue );
+	 * 
+	 * @param aDef         Definition of the new property.
+	 * @param aValue       Value of the new property.
+	 *
+	 * @return  New property.
+	 */
+	IMPORT_C CMdEProperty& AddReal64PropertyL(CMdEPropertyDef& aDef, TReal64 aValue);
+
+	/**
+	 * Adds a new text property to the object. If property definition doesn't 
+	 * match with value, method leaves with error code KErrArgument.
+	 *
+	 * Example:
+	 *   CMdEPropertyDef& propertyDef = objectDef.GetPropertyDefL( MdeConstants::Object::KProperty );
+	 *   metadataObject.AddTextPropertyL( propertyDef, text );
+	 * 
+	 * @param aDef         Definition of the new property.
+	 * @param aValue       Value of the new property.
+	 *
+	 * @return  New property.
+	 */
+	IMPORT_C CMdEProperty& AddTextPropertyL(CMdEPropertyDef& aDef, const TDesC& aValue);
+
+	/**
+	 * Adds a new time property to the object. If property definition doesn't 
+	 * match with value, method leaves with error code KErrArgument.
+	 *
+	 * Example:
+	 *   CMdEPropertyDef& propertyDef = objectDef.GetPropertyDefL( MdeConstants::Object::KProperty );
+	 *   metadataObject.AddTimePropertyL( propertyDef, time );
+	 * 
+	 * @param aDef         Definition of the new property.
+	 * @param aValue       Value of the new property.
+	 *
+	 * @return  New property.
+	 */
+	IMPORT_C CMdEProperty& AddTimePropertyL(CMdEPropertyDef& aDef, TTime aValue);
+
+	/**
+	 * Removes the property at the specified index.
+	 *
+	 * @param aIndex  index
+	 */
+	IMPORT_C void RemoveProperty(TInt aIndex);
+
+
+	/* Methods for accessing free text keywords. */
+
+	/**
+	 * Returns the number of free text keywords.
+	 *
+	 * @return  number of free text keywords
+	 */
+	IMPORT_C TInt FreeTextCount() const;
+
+	/**
+	 * Returns the free text keyword at the specified index
+	 *
+	 * @param aIndex  index
+	 *
+	 * @return  free text keyword
+	 */
+	IMPORT_C TPtrC FreeText(TInt aIndex) const;
+    
+    /**
+     * Returns the index of the specified free text.
+     *
+     * @param aFreeText  Free text.
+     *
+     * @return  Index, or <code>KErrNotFound</code>.
+     */
+    IMPORT_C TInt FreeTextIndex(const TDesC& aFreeText) const;
+
+	/**
+	 * Adds a new free text keyword.
+	 *
+	 * @param aFreeText  free text keyword
+	 */
+	IMPORT_C void AddFreeTextL(const TDesC& aFreeText);
+
+	/**
+	 * Removes the free text keyword at the specified index.
+	 *
+	 * @param aIndex  index
+	 */
+	IMPORT_C void RemoveFreeText(TInt aIndex);
+
+	/**
+	 * Move all properties from object which is given as a paremeter to this object
+	 *
+	 * @param aObject object from where move properties
+	 */
+	IMPORT_C void MovePropertiesL(CMdEObject& aObject);
+
+	/**
+	 * Returns whether the object has been modified or not.
+	 *
+	 * @return  <code>ETrue</code>, if the URI, MediaId or Guids  has been modified.
+	 *          <code>EFalse</code>, otherwise.
+	 */
+	TBool ObjectModified() const;
+
+	/**
+	 * Returns whether the free text array has been modified or not.
+	 *
+	 * @return  <code>ETrue</code>, if FreeTexts has been modified.
+	 *          <code>EFalse</code>, otherwise.
+	 */
+	TBool FreeTextModified() const;
+
+	/**
+	 * Returns whether one of the properties has been modified or not.
+	 *
+	 * @return  Are properties modified.
+	 */
+	TBool PropertyModified() const;
+
+	/*
+	 * clear all modification flags and removes removed properties
+	 */
+	void ClearObject( TBool aClearFlags = ETrue );
+
+	/**
+	 * Sets that the object is not open for modifications.
+	 */
+	void SetNotOpenForModifications();
+
+	/**
+	 * Left locked automatically after it's added to DB.
+	 */
+	void AutoLockL() const;
+	
+	/**
+	 * Calculates required size for buffer to serialize object
+	 *
+	 * @return necessary buffer size
+	 */
+	TUint32 RequiredBufferSize() const;
+
+	/**
+	 * Serialize object
+	 * RequiredBufferSize() MUST be always called before this function!
+	 *
+	 * @param aBuffer buffer where serialized object should go
+	 */
+	TMdCOffset SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreespaceOffset) const;
+
+protected:
+
+	virtual TMdEInstanceType InstanceType() const;
+
+private:
+
+	/**
+	 * Constructs a new object.
+	 *
+	 * @param aSession session owner
+	 * @param aId object id
+	 * @param aDef  Definition of the new object.
+	 */
+	CMdEObject( CMdESession* aSession, TItemId aId, CMdEObjectDef& aDef );
+	
+	/**
+	 * Second-phase constructor.
+	 * @param aUri URI of the new object.
+	 * @param aMediaId mediaid of object. Defaults to 0.
+	 */
+	void ConstructL( const TDesC& aUri, TUint32 aMediaId = 0 );
+	
+	/**
+	 * Sets the URI of the object.
+	 *
+	 * @param aUri  New URI.
+	 */
+	void DoSetUriL(const TDesC& aUri);
+
+	/**
+	 * Adds a new property to the object.
+	 *
+	 * @param aProperty  New property.
+	 * @param aState     Modification state of the new property.
+	 */
+	void DoAddPropertyL(CMdEProperty& aProperty);
+	
+	/**
+	 * Compares two properties.
+	 *
+	 * @param aFirst   First property.
+	 * @param aSecond  Second property.
+	 *
+	 * @return  0, if the properties are equal;
+	 *		    a negative value, if the first property is less than the second;
+	 *			a positive value, if the first property is greater than the second.
+	 */
+	static TInt CompareProperties(const CMdEProperty& aFirst, 
+						          const CMdEProperty& aSecond);
+
+	/**
+	 * Adds a new free text to the object.
+	 *
+	 * @param aFreeText  New free text.
+	 */
+	TInt DoAddFreeTextL(const HBufC& aFreeText);
+
+	/**
+	 * Compares two free texts.
+	 *
+	 * @param aFirst   First free text.
+	 * @param aSecond  Second free text.
+	 *
+	 * @return  0, if the texts are equal;
+	 *		    a negative value, if the first text is less than the second;
+	 *			a positive value, if the first text is greater than the second.
+	 */
+	static TInt CompareFreeTexts(const HBufC& aFirst, const HBufC& aSecond);
+
+	/**
+	 * Returns how many properties is modified and should be send to server
+	 */
+	TUint32 ModifiedPropertiesCount() const;
+
+    /**
+     * Compares two properties.
+     *
+     * @param aFirst   First property.
+     * @param aSecond  Second property.
+     *
+     * @return  0, if the properties are equal;
+     *          a negative value, if the first property is less than the second;
+     *          a positive value, if the first property is greater than the second.
+     */
+	static TInt CompareProperties(const CMdEPropertyDef* aPropertyDef, const CMdEProperty& aProperty);
+	
+private:
+
+	/** Object definition.
+	 * This pointer must be initialized in constructor and 
+	 * not must be NULL in any point. */
+	CMdEObjectDef* iDef;
+
+	/** Array for properties. */
+	RPointerArray<CMdEProperty> iPropertyArray;	
+
+	/** Array for free text. */
+	RPointerArray<HBufC> iFreeTextArray;	
+
+	/** various flags */
+	mutable TUint32 iFlags;
+	
+	/** memory card Id */
+	TUint32 iMediaId;
+
+	/** usage count (read-only) */
+	TUint32 iUsageCount;
+	
+	/** Guid Low and High */
+	TInt64 iGuidHigh;
+	TInt64 iGuidLow;
+
+	/** URI descriptor. */
+	HBufC* iUri;
+	};
+
+
+#endif  // __MDEOBJECT_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeobjectcondition.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,279 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDEOBJECTCONDITION_H__
+#define __MDEOBJECTCONDITION_H__
+
+
+#include <mdecondition.h>
+#include <mderange.h>
+
+/* Forward declarations. */
+class CMdEObjectDef;
+
+
+/**
+ * Query condition for objects.
+ */
+NONSHARABLE_CLASS(CMdEObjectCondition) : public CMdECondition
+	{
+public:
+
+	/* Constructors and destructor. */
+/**
+ * Two-phased constructor.
+ */
+
+	static CMdEObjectCondition* NewL( TObjectConditionCompareMethod aCompareMethod,
+			TItemId aObjectId = KNoId, 
+			const CMdEObjectDef* aObjectDef = NULL,
+			TInt64 aObjectGuidHigh = 0, TInt64 aObjectGuidLow = 0 );
+
+	static CMdEObjectCondition* NewLC( TObjectConditionCompareMethod aCompareMethod,
+			TItemId aObjectId = KNoId,
+			const CMdEObjectDef* aObjectDef = NULL,
+			TInt64 aObjectGuidHigh = 0, TInt64 aObjectGuidLow = 0 );
+
+	static CMdEObjectCondition* NewL( TObjectConditionCompareMethod aCompareMethod,
+			const RArray<TItemId>* aObjectIds = NULL,
+			const TDesC* aString = NULL,
+			const TMdEUintRange* aRange = NULL );
+
+	static CMdEObjectCondition* NewLC( TObjectConditionCompareMethod aCompareMethod,
+			const RArray<TItemId>* aObjectIds = NULL,
+			const TDesC* aString = NULL,
+			const TMdEUintRange* aRange = NULL );
+
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEObjectCondition();
+
+	/* Methods. */
+
+    /**
+     * Returns the object definition of the condition.
+     *
+     * @return  Object definition. <code>NULL</code>, if not defined.
+     */
+	IMPORT_C const CMdEObjectDef* ObjectDef() const;
+
+    /**
+     * Returns the object ID number of the condition.
+     *
+     * @return  Object ID. Zero, if not defined.
+     */
+    IMPORT_C TItemId ObjectId() const;
+
+    /**
+     * Returns the object ID numbers of the condition.
+     *
+     * @return  Object IDs. <code>NULL</code>, if not defined.
+     */
+    IMPORT_C const RArray<TItemId>* ObjectIds() const;
+
+    /**
+     * Returns the string of the condition.
+     *
+     * @return  String descriptor. <code>NULL</code>, if not defined.
+     */
+    IMPORT_C const TDesC* String() const;
+
+    /**
+     * Returns the comparison method of the condition.
+     *
+     * @return  Comparison method.
+     */
+    IMPORT_C TObjectConditionCompareMethod CompareMethod() const;
+
+    /**
+     * Returns the level of confidentiality of the condition.
+     *
+     * @return  Confidentiality level of condition.
+     */
+    IMPORT_C TObjectConditionConfidentialityLevel ConfidentialityLevel() const;
+
+    /**
+     * Sets the confidentiality level for the condition.
+     * Default level is ELevelNormal.
+     *
+     * @param  aLevel focuses the search to confidential or
+     *         non-confidential  objects or both of them.
+     */
+    IMPORT_C void SetConfidentialityLevel( TObjectConditionConfidentialityLevel aLevel );
+
+    /**
+     * Determines whether the condition requires the object
+     * to be a present object or not.
+     *
+     * @return  <code>ETrue</code>, if not present objects are requested;
+     *          <code>EFalse</code> otherwise.
+     */
+    IMPORT_C TBool NotPresent() const;
+
+    /** 
+     * Sets whether the condition requires the object
+     * to be a present object or not.
+     *
+     * @param aNotPresent  <code>ETrue</code>, if the object should 
+     *                                         be a not present object.
+     *                     <code>EFalse</code> otherwise.
+     */
+    IMPORT_C void SetNotPresent(TBool aNotPresent);
+
+    /**
+     * Determines whether the condition requires the object
+     * to be a not placeholder object.
+     *
+     * @return  <code>ETrue</code>, if not placeholder objects are excluded;
+     *          <code>EFalse</code> otherwise.
+     */
+    IMPORT_C TBool NotPlaceholder() const;
+
+    /** 
+     * Sets whether the condition requires the object
+     * to be a not placeholder object.
+     *
+     * @param aNotPlaceholder  <code>ETrue</code>, if the object should 
+     *                                             be a not placeholder object.
+     *                         <code>EFalse</code> otherwise.
+     */
+    IMPORT_C void SetNotPlaceholder(TBool aNotPlaceholder);
+
+    /**
+     * Get possible query's internal optimization flags from condition.
+     *
+     * @param aFlaga query's internal optimization flags
+     * @return last level internal optimization flags
+     */
+    TUint32 InternalQueryOptimizationFlags(TUint32& aFlags);
+
+    /**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+    TUint32 RequiredBufferSize() const;
+
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling) and return new position of serialized buffer.
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    void SerializeL(CMdCSerializationBuffer& aBuffer,
+    		TMdCOffset& aFreespaceOffset) const;
+    
+    /**
+     * Determines whether the condition requires the object
+     * to be a not placeholder object.
+     *
+     * @return  <code>ETrue</code>, if not placeholder objects are excluded;
+     *          <code>EFalse</code> otherwise.
+     */
+    IMPORT_C TBool PlaceholderOnly() const;
+
+    /** 
+     * Sets whether the condition requires the object
+     * to be a not placeholder object.
+     *
+     * @param aNotPlaceholder  <code>ETrue</code>, if the object should 
+     *                                             be a not placeholder object.
+     *                         <code>EFalse</code> otherwise.
+     */
+    IMPORT_C void SetPlaceholderOnly( TBool aPlaceholderOnly );
+
+private:
+
+	/**
+	 * Constructor.
+	 *
+     * @param aCompareMethod  Comparison method.
+     * @param aObjectId  ID number of an object.
+	 * @param aObjectDef     Object definition.
+     * @param aObjectGuidHigh  object's GUID high part.
+     * @param aObjectGuidLow   object's GUID low part.
+	 */
+	CMdEObjectCondition( TObjectConditionCompareMethod aCompareMethod,
+				TItemId aObjectId, const CMdEObjectDef* aObjectDef,
+				TInt64 aObjectGuidHigh, TInt64 aObjectGuidLow );
+
+	/**
+	 * Constructor.
+	 *
+     * @param aCompareMethod  Comparison method.
+	 */
+	CMdEObjectCondition( TObjectConditionCompareMethod aCompareMethod );
+
+    /**
+     * Second-phase constructor.
+     */
+    void ConstructL();
+
+    /**
+     * Second-phase constructor.
+     * 
+     * @param aString         Text string to look for.
+     * @param aObjectIds      object IDs to look for.
+     */
+    void CMdEObjectCondition::ConstructL( const RArray<TItemId>* aObjectIds,
+    		const TDesC* aString, const TMdEUintRange* aRange );
+
+private:
+
+    /** Object definition to match. <code>NULL</code>, if not applicable. */
+    const CMdEObjectDef* iObjectDef;
+
+    /** The object's ID. */
+    TItemId iObjectId;
+
+    /** The objects' ID. */
+    RArray<TItemId>* iObjectIds;
+
+    /** String to match. <code>NULL</code>, if not applicable. */
+    HBufC* iString;
+
+    /** Compare method for the string. */
+    TObjectConditionCompareMethod iCompareMethod;
+
+    /** 
+     * Object condition flags 
+     * not present 
+     * not placeholder
+     */
+    TUint32 iFlags;
+
+    /** 
+     * Determines confidentiality level of result object.
+     * By default level is ELevelNormal, which means that
+     * query returns only non-confidential objects as result.
+     */
+    TObjectConditionConfidentialityLevel iConfidentialityLevel;
+
+    /** Object's GUID high part. */
+    TInt64 iGuidHigh;
+
+    /** Object's GUID low part. */
+    TInt64 iGuidLow;
+    
+    TMdEUintRange* iRange;
+    TBool iPlaceholdersOnly;
+    };
+
+#endif  // __MDEOBJECTCONDITION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeobjectdef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,129 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDEOBJECTDEF_H__
+#define __MDEOBJECTDEF_H__
+
+
+#include <e32base.h>
+//#include <uri16.h>
+
+#include <mdccommon.h>
+
+// Forward declaration
+class CMdEPropertyDef;
+class CMdCSerializationBuffer;
+class CMdENamespaceDef;
+class TMdCObjectDef;
+
+/**
+ * Object definition.
+ */
+NONSHARABLE_CLASS(CMdEObjectDef) : public CBase
+	{
+public:	
+	IMPORT_C CMdEObjectDef* ParentL();
+	
+	/**
+	 * Returns the name of the item.
+	 *
+	 * @return  name
+	 */
+	IMPORT_C const TDesC& Name() const;
+
+	/**
+	 * Returns the number of property definitions.
+	 *
+	 * @return  number of property definitions
+	 */
+	IMPORT_C TInt PropertyDefCount() const;
+
+	/**
+	 * Returns the property definition at the specified index.
+	 *
+	 * @return  property definition
+	 */
+	IMPORT_C CMdEPropertyDef& PropertyDefL(TInt aIndex);
+
+	/**
+	 * Returns the property definition with the specified name.
+	 *
+	 * @param aName         name
+	 *
+	 * @return  property definition; 
+	 *          or 0 if there is no property definition with the specified name
+	 */
+	IMPORT_C CMdEPropertyDef& GetPropertyDefL(const TDesC& aName);
+
+	/**
+	 * Compare this object definition with other object definition.
+	 *
+	 * @param aObjectDef other object definition
+	 *
+	 * @return  0 if objects are same, 1 or more if this is greater than other 
+	 *          and -1 or less if this is less than other.
+	 */
+	IMPORT_C TInt Compare(const CMdEObjectDef& aObjectDef) const;
+	
+	/**
+	* Returns namespacedef where this objectdef belongs to.
+	* @Return namespacedef where this objectdef belongs to.
+	*/
+	IMPORT_C CMdENamespaceDef& NamespaceDef() const;
+	
+public:
+	static CMdEObjectDef* NewL(const TMdCObjectDef& aObjectDef, CMdCSerializationBuffer& aSchemaBuffer, CMdENamespaceDef& aNamespaceDef );
+
+	static CMdEObjectDef* NewLC(const TMdCObjectDef& aObjectDef, CMdCSerializationBuffer& aSchemaBuffer, CMdENamespaceDef& aNamespaceDef );
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEObjectDef();
+
+	TDefId Id() const;	
+	
+	/**
+	 * Returns the property definition with the specified id
+	 *
+	 * @param aId         id
+	 *
+	 * @return  property definition; 
+	 *          or <code>NULL</code> if there is no property definition with the specified id
+	 */
+	CMdEPropertyDef* GetPropertyDefL(TDefId aId, CMdEObjectDef* aChild = NULL);
+
+private:
+	CMdEObjectDef(const TMdCObjectDef& aObjectDef, CMdENamespaceDef& aNamespaceDef);
+
+	CMdEPropertyDef* PropertyDefL(TInt aIndex, CMdEObjectDef* aChild);
+
+	CMdEPropertyDef* GetPropertyDefL(const TDesC& aName, CMdEObjectDef* aChild);
+
+	void ConstructL(CMdCSerializationBuffer& aSchemaBuffer);
+
+private:
+	const TMdCObjectDef& iObjectDef;
+	CMdENamespaceDef& iNamespaceDef;
+
+	TPtrC16 iName;
+		
+	RPointerArray<CMdEPropertyDef> iPropertyDefs;
+	};
+
+#endif  // __MDEOBJECTDEF_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeobjectquery.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,134 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface for object query
+*
+*/
+
+
+#ifndef __MDEOBJECTQUERY_H__
+#define __MDEOBJECTQUERY_H__
+
+
+#include <mdequery.h>
+
+/* Forward declarations. */
+class CMdEObject;
+class CMdEObjectDef;
+class CMdEPropertyDef;
+class CMdEObjectDef;
+class CMdESession;
+
+/**
+ * A query that fetches a set of objects from the metadata engine database.
+ */
+NONSHARABLE_CLASS(CMdEObjectQuery) : public CMdEQuery
+	{
+public:
+	
+	/* Constructors and destructor. */
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEObjectQuery();
+
+
+	/* Methods. */
+
+    
+    /**
+    * Adds new propertyfilter. Propertyfilters determines which properties
+    * are included in result.
+    
+    * @param aPropertyDef property definition of property which is wanted to
+      be part of result.
+    */
+    IMPORT_C void AddPropertyFilterL( const CMdEPropertyDef* aPropertyDef );
+    
+    /**
+    Clears propertyfilters. After call to this function all properties are 
+    returned unless call to <code>AddPropertyFilterL</code> is done.
+    */
+    
+    IMPORT_C void ResetPropertyFilter();
+
+    /**
+	 * Returns one of the result objects.
+	 *
+	 * @return  The result object that was requested. The query retains 
+     *          ownership of the returned object.
+	 */
+	IMPORT_C CMdEObject& Result(TInt aIndex) const;
+
+    /**
+	 * Returns query's object definition.
+	 *
+	 * @return  object definition.
+	 */
+	IMPORT_C CMdEObjectDef& ObjectDef() const;
+
+public:
+	RPointerArray<CMdEPropertyDef>& PropertyFilter();	
+
+	RPointerArray<CMdEObjectDef>* ObjectDefs() const;
+
+protected:
+
+	/* Constructors. */
+
+    /**
+     * Constuctor.
+     *
+     * @param aSession  Session.
+     */
+    CMdEObjectQuery(CMdESession& aSession, CMdENamespaceDef& aNamespaceDef, 
+    		CMdEObjectDef& aObjectDef, RPointerArray<CMdEObjectDef>* aObjectDefs);
+
+	/**
+	 * Second-phase constructor.
+	 */
+	void ObjectQueryConstructL();
+
+    virtual void DoCancel();
+
+private:
+
+    /* Private methods. */
+
+
+private:
+
+    /** 
+     * Properties to include when fetching results. Empty, if
+     * all available properties should be fetched. 
+     */
+    RPointerArray<CMdEPropertyDef> iPropertyFilters;
+
+	/**
+	 * Query's object definition.
+	 */
+	CMdEObjectDef& iObjectDef;
+
+	/**
+	 * Query's object definition.
+	 */
+	RPointerArray<CMdEObjectDef>* iObjectDefs;
+	
+	/**
+	 * Speed optimization to drop freetexts from results.
+	 */
+	TBool iFreetextsInResult;
+    };
+
+#endif  // __MDEOBJECTQUERY_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeorderrule.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,156 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDEORDERRULE_H__
+#define __MDEORDERRULE_H__
+
+
+#include <e32base.h>
+
+#include <mdccommon.h>
+
+/* Forward declarations. */
+class CMdEPropertyDef;
+class CMdCSerializationBuffer;
+
+/**
+ * TMdEOrderRule defines a rule that is used for sorting the results of a
+ * query. A query may use multiple order rules.
+ */
+class TMdEOrderRule
+    {
+public:
+
+    /* Constructors. */
+
+    /**
+     * Constructor.
+     *
+     * @param aType       Type of the order rule.
+     * @param aAscending  <code>ETrue</code>, if the rule order is 
+     *                    ascending.
+     */        
+    IMPORT_C TMdEOrderRule(TOrderRuleType aType, TBool aAscending = ETrue);   
+
+    /**
+     * Constructor.
+     *
+     * @param aPropertyDef  Property definition.
+     * @param aAscending    <code>ETrue</code>, if the rule order is 
+     *                      ascending.
+     */        
+    IMPORT_C TMdEOrderRule(const CMdEPropertyDef& aPropertyDef, 
+                           TBool aAscending = ETrue);
+
+
+    /* Methods. */
+
+    /**
+     * Returns the type of the order rule.
+     *
+     * @return  Order rule type constant.
+     */
+    IMPORT_C TOrderRuleType Type() const;
+
+    /**
+     * Sets the type of the order rule.
+     *
+     * @param aType  Order rule type constant.
+     */
+    IMPORT_C void SetType(TOrderRuleType aType);
+
+    /**
+     * Determines whether the ordering is ascending.
+     *
+     * @return  <code>ETrue</code> ascending order,
+     *          <code>EFalse</code> descending order.
+     */
+    IMPORT_C TBool Ascending() const;
+
+    /**
+     * Sets the order rule to ascending or descending order.
+     *
+     * @param aAscending  <code>ETrue</code> ascending order,
+     *                    <code>EFalse</code> descending order.
+     */
+    IMPORT_C void SetAscending(TBool aAscending = ETrue);
+
+    /**
+     * Returns the property definition associated with the order rule.
+     *
+     * @return  Property definition.  <code>NULL</code>, if no property
+     *          definition has been associated with the rule.
+     */
+    IMPORT_C const CMdEPropertyDef* PropertyDef() const;
+
+    /**
+     * Associates a property definition with the order rule.
+     *
+     * @param aPropertyDef  Property definition.
+     */
+    IMPORT_C void SetPropertyDef(const CMdEPropertyDef& aPropertyDef);
+
+    /**
+     * Sets text sorting case sensitive or case insensitive.
+     *
+     * @param aCaseSensitive <code>ETrue</code> case sensitive sort.
+                             <code>EFalse</code> case insensitive sort.
+     */
+    IMPORT_C void SetCaseSensitive(TBool aCaseSensitive);
+
+    /**
+     * Returns type of text comparison, whether case sensitive
+     * or case insensitive.
+     *
+     * @return <code>ETrue</code> case sensitive sort.
+     *         <code>EFalse</code> case insensitive sort.
+     */
+    IMPORT_C TBool CaseSensitive();
+
+	/**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+	TUint32 RequiredBufferSize() const;
+
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling) and return new position of serialized buffer.
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    void SerializeL(CMdCSerializationBuffer& aBuffer, 
+    		TMdCOffset& aFreespaceOffset) const;
+
+private:
+
+    /** Type of the order rule. */
+    TOrderRuleType iType;
+    
+    /** Optional. */
+    const CMdEPropertyDef* iPropertyDef;
+    
+    /** Flag for ascending order. */
+    TBool iAscending;
+
+    /** Flag for text sorting. Default value is EFalse */
+    TBool iCaseSensitive;
+   };        
+
+#endif  // __MDEORDERRULE_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeproperty.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,330 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDEPROPERTY_H__
+#define __MDEPROPERTY_H__
+
+#include <e32base.h>
+
+#include <mdeinstanceitem.h>
+
+
+/* Forward declarations. */
+class CMdEObject;
+class CMdEPropertyDef;
+class CMdCSerializationBuffer;
+
+/**
+ * Abstract base class for properties.
+ */
+NONSHARABLE_CLASS(CMdEProperty) : public CMdEInstanceItem
+	{
+	friend class CMdEObject;
+public:
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEProperty();
+
+
+	/* Methods. */
+
+	/**
+	 * Constructs a new property.
+	 *
+	 * @param aObject owner object of property
+	 * @param aBuffer buffer where property was serialized
+	 * @return new numeric property
+	 */
+	static CMdEProperty* NewL( const CMdEObject& aObject, CMdCSerializationBuffer& aBuffer );
+
+	/**
+	 * Constructs a new property and leave it on the cleanup stack.
+	 *
+	 * @param aObject owner object of property
+	 * @param aBuffer buffer where property was serialized
+	 * @return new numeric property
+	 */
+	static CMdEProperty* NewLC( const CMdEObject& aObject, CMdCSerializationBuffer& aBuffer );
+
+	/**
+	 * Constructs a new property.
+	 *
+	 * @param aDef property definition
+	 * @param aObject owner object of property
+	 * @return new numeric property
+	 */
+	static CMdEProperty* CMdEProperty::NewL(const CMdEPropertyDef& aDef, const CMdEObject& aObject);
+
+	/**
+	 * Constructs a new property.
+	 *
+	 * @param aDef property definition
+	 * @param aObject owner object of property
+	 * @return new numeric property
+	 */
+	static CMdEProperty* CMdEProperty::NewLC(const CMdEPropertyDef& aDef, const CMdEObject& aObject);
+
+
+	/**
+	 * Returns the definition of the integer property.
+	 *
+	 * @return  property definition
+	 */
+	IMPORT_C const CMdEPropertyDef& Def() const;
+
+	/**
+	 * Returns the object which the property belongs to.
+	 *
+	 * @return  Object.
+	 */
+	IMPORT_C const CMdEObject& Object() const;
+
+	/**
+	 * @return ETrue if property was modified,
+	 *         EFalse otherwise
+	 */
+	IMPORT_C TBool Modified() const;
+
+	
+	/** value getters */
+
+	/**
+	 * Returns the TBool value of the property.
+	 * @return  value
+	 */
+	IMPORT_C TBool BoolValueL() const;
+
+	/**
+	 * Returns the TInt8 value of the property.
+	 * @return  value
+	 */
+	IMPORT_C TInt8 Int8ValueL() const;
+
+	/**
+	 * Returns the TUint8 value of the property.
+	 * @return  value
+	 */
+
+	IMPORT_C TUint8 Uint8ValueL() const;
+	
+	/**
+	 * Returns the TInt16 value of the property.
+	 * @return  value
+	 */
+	IMPORT_C TInt16 Int16ValueL() const;
+	
+	/**
+	 * Returns the TUint16 value of the property.
+	 * @return  value
+	 */
+	IMPORT_C TUint16 Uint16ValueL() const;
+	
+	/**
+	 * Returns the TInt32 value of the property.
+	 * @return  value
+	 */
+	IMPORT_C TInt32 Int32ValueL() const;
+	
+	/**
+	 * Returns the TUint32 value of the property.
+	 * @return  value
+	 */
+	IMPORT_C TUint32 Uint32ValueL() const;
+	
+	/**
+	 * Returns the TInt64 value of the property.
+	 * @return  value
+	 */
+	IMPORT_C TInt64 Int64ValueL() const;
+	
+	/**
+	 * Returns the TReal32 value of the property.
+	 * @return  value
+	 */
+	IMPORT_C TReal32 Real32ValueL() const;
+	
+	/**
+	 * Returns the TReal64 value of the property.
+	 * @return  value
+	 */
+	IMPORT_C TReal64 Real64ValueL() const;
+	
+	/**
+	 * Returns the TTime value of the property.
+	 * @return  value
+	 */
+	IMPORT_C TTime TimeValueL() const;
+
+	/**
+	 * Returns the text value of the property.
+	 *
+	 * @return  value
+	 */
+	IMPORT_C const TDesC& TextValueL() const;
+	
+
+	/** setter methods */
+	/**
+	 * Sets the TBool value of the property.
+	 * @param aValue       New value.
+	 */
+	IMPORT_C void SetBoolValueL(TBool aValue);
+
+	/**
+	 * Sets the TInt8 value of the property.
+	 * @param aValue       New value.
+	 */
+	IMPORT_C void SetInt8ValueL(TInt8 aValue);
+
+	/**
+	 * Sets the TUint8 value of the property.
+	 * @param aValue       New value.
+	 */
+	IMPORT_C void SetUint8ValueL(TUint8 aValue);
+
+	/**
+	 * Sets the TInt16 value of the property.
+	 * @param aValue       New value.
+	 */
+	IMPORT_C void SetInt16ValueL(TInt16 aValue);
+
+	/**
+	 * Sets the TUint16 value of the property.
+	 * @param aValue       New value.
+	 */
+	IMPORT_C void SetUint16ValueL(TUint16 aValue);
+
+	/**
+	 * Sets the TInt32 value of the property.
+	 * @param aValue       New value.
+	 */
+	IMPORT_C void SetInt32ValueL(TInt32 aValue);
+
+	/**
+	 * Sets the TUint32 value of the property.
+	 * @param aValue       New value.
+	 */
+	IMPORT_C void SetUint32ValueL(TUint32 aValue);
+
+	/**
+	 * Sets the TInt64 value of the property.
+	 * @param aValue       New value.
+	 */
+	IMPORT_C void SetInt64ValueL(TInt64 aValue);
+
+	/**
+	 * Sets the TReal32 value of the property.
+	 * @param aValue       New value.
+	 */
+	IMPORT_C void SetReal32ValueL(TReal32 aValue);
+
+	/**
+	 * Sets the TReal64 value of the property.
+	 * @param aValue       New value.
+	 */
+	IMPORT_C void SetReal64ValueL(TReal64 aValue);
+
+	/**
+	 * Sets the TTime value of the property.
+	 * @param aValue       New value.
+	 */
+	IMPORT_C void SetTimeValueL(const TTime& aValue);
+
+	/**
+	 * Sets the text value of the property.
+	 *
+	 * @param aValue       New value.
+	 */
+	IMPORT_C void SetTextValueL(const TDesC& aValue);
+
+	
+	/**
+	 * Return required size for property serialization
+	 *
+	 * @return size of serialized property
+	 */
+	TUint32 RequiredBufferSize() const;
+
+	/**
+	 * Serialize object
+	 *
+	 * @param aBuffer buffer where serialized object should go
+	 */
+	TMdCOffset SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreespaceOffset) const;
+	
+private:
+
+	TUint8 ModFlags() const;
+
+	void SetRemoved();
+	TBool Removed();
+
+	void ClearFlags();
+
+	void SetModified();
+
+
+	/* Constructors. */
+
+	/**
+	 * Constructor.
+	 *
+	 * @param aDef         Definition of the new property.	 
+	 * @param aObject object where this property belongs to.
+	 */
+	CMdEProperty(const CMdEPropertyDef& aDef, const CMdEObject& aObject);
+
+	/**
+	 * Second-phase constructor.
+	 *
+	 * @param aSource  Source of the new property.
+	 */
+	void BaseConstructL();
+
+
+	/* Methods. */
+
+	/**
+	 * Check if property has value is between min and max
+	 * and leave if not!
+	 */
+#ifdef _DEBUG
+	void CheckValueMinMaxL( const TMdCValueUnion& aValue ) const;
+#endif
+	
+	void DoSetTextValueL(const TDesC& aValue);
+
+	TMdEInstanceType InstanceType() const;
+
+protected:
+	/** property modifications flags */
+	TUint8 iModFlags;
+
+private:
+	/** Property definition. */
+	const CMdEPropertyDef& iDef;
+
+	/** Object this property belongs to. */
+	const CMdEObject& iObject;
+
+	/** Value. */
+	TMdCValueUnion iValue;
+	};
+
+#endif  // __MDEPROPERTY_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdepropertycondition.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,116 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Represent property condition
+*
+*/
+
+#ifndef __MDEPROPERTYCONDITION_H__
+#define __MDEPROPERTYCONDITION_H__
+
+#include <mdecondition.h>
+
+/* Forward declarations. */
+class CMdEPropertyDef;
+class CMdCSerializationBuffer;
+
+/**
+ * CMdEPropertyCondition is the base class for all property conditions.
+ * Instances of CMdEPropertyCondition and its subclasses are always associated
+ * with a property definition.
+ */
+NONSHARABLE_CLASS(CMdEPropertyCondition) : public CMdECondition
+	{
+public:
+
+    /* Types. */
+    
+	/**
+	 * Two-phased constructor.
+	 */
+	static CMdEPropertyCondition* NewL( const CMdEPropertyDef& aPropertyDef );
+
+   /**
+    * Two-phased constructor.
+    */
+   static CMdEPropertyCondition* NewLC( const CMdEPropertyDef& aPropertyDef );
+
+    
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEPropertyCondition();
+
+
+	/* Methods. */
+
+    /** 
+     * Returns the property definition of the condition.
+     *
+     * @return  Property definition.
+     */
+    IMPORT_C const CMdEPropertyDef& PropertyDef() const;
+
+    /**
+     * Get possible query's internal optimization flags from condition.
+     *
+     * @param aFlaga query's internal optimization flags
+     * @return last level internal optimization flags
+     */
+    TUint32 InternalQueryOptimizationFlags(TUint32& aFlags);
+
+    /**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+    virtual TUint32 RequiredBufferSize() const;
+   
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling) and return new position of serialized buffer.
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    virtual void SerializeL(CMdCSerializationBuffer& aBuffer,
+    		TMdCOffset& aFreespaceOffset) const;
+   
+protected:
+
+	/**
+	 * Constructor for a condition that tests the existence of properties.
+	 *
+	 * @param aPropertDef  Property definition.
+	 */
+	CMdEPropertyCondition(const CMdEPropertyDef& aPropertyDef);
+
+    /**
+     * Second-phase constructor.
+     */
+    void ConstructL();
+
+    /**
+	 * Constructor that sets the condition type as well.
+	 *
+	 * @param aType  Type of the condition node.
+	 */
+	CMdEPropertyCondition(TConditionType aConditionType, 
+                          const CMdEPropertyDef& aPropertyDef);
+
+protected:
+
+    /** The property this condition operates on. */
+    const CMdEPropertyDef& iPropertyDef;
+    };
+
+#endif  // __MDEPROPERTYCONDITION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdepropertydef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,135 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDEPROPERTYDEF_H__
+#define __MDEPROPERTYDEF_H__
+
+#include <mdccommon.h>
+
+// Forward declaration
+class CMdCSerializationBuffer;
+class CMdEObjectDef;
+class CMdENamespaceDef;
+class TMdCPropertyDef;
+
+/**
+ * Class for property definitions.
+ */
+NONSHARABLE_CLASS(CMdEPropertyDef) : public CBase
+	{
+public:	
+	/**
+	 * Returns the name of the item.
+	 *
+	 * @return  name
+	 */
+	IMPORT_C const TDesC& Name() const;
+	
+	/**
+	 * Returns the type of the property.
+	 *
+	 * @return  property type
+	 */
+	IMPORT_C TPropertyType PropertyType() const;
+
+	/**
+	 * Returns whether the property is read only.
+	 *
+	 * @return  <code>ETrue</code>, if the property is read only;
+	 *          <code>EFalse</code>, otherwise
+	 */
+	IMPORT_C TBool ReadOnly() const;
+
+	/**
+	 * Returns whether the property is mandatory.
+	 *
+	 * @return  <code>ETrue</code>, if the property is mandatory;
+	 *          <code>EFalse</code>, otherwise
+	 */
+	IMPORT_C TBool Mandatory() const;
+
+	/**
+	 * Compare this property definition with other property definition.
+	 *
+	 * @param aPropertyDef other property definition
+	 *
+	 * @return  0 if properties are same, 1 or more if this is greater than other 
+	 *          and -1 or less if this is less than other.
+	 */
+	IMPORT_C TInt Compare(const CMdEPropertyDef& aPropertyDef) const;
+	
+
+	IMPORT_C CMdEObjectDef& ObjectDef() const;
+
+	IMPORT_C TInt32 MinInt32ValueL() const;
+
+	IMPORT_C TInt32 MaxInt32ValueL() const;
+
+	IMPORT_C TUint32 MinUint32ValueL() const;
+
+	IMPORT_C TUint32 MaxUint32ValueL() const;
+
+	IMPORT_C TInt64 MinInt64ValueL() const;
+
+	IMPORT_C TInt64 MaxInt64ValueL() const;
+
+	IMPORT_C TReal MinRealValueL() const;
+
+	IMPORT_C TReal MaxRealValueL() const;
+
+	IMPORT_C TTime MinTimeValueL() const;
+
+	IMPORT_C TTime MaxTimeValueL() const;	
+
+	IMPORT_C TInt MinTextLengthL() const;
+
+	IMPORT_C TInt MaxTextLengthL() const;
+	
+	IMPORT_C CMdENamespaceDef& NamespaceDef() const;
+
+public:
+	static CMdEPropertyDef* NewL(const TMdCPropertyDef& aPropertyDef, CMdCSerializationBuffer& aSchemaBuffer, CMdEObjectDef& aObjectDef);
+
+	static CMdEPropertyDef* NewLC(const TMdCPropertyDef& aPropertyDef, CMdCSerializationBuffer& aSchemaBuffer, CMdEObjectDef& aObjectDef);
+	
+	void SerializeL(CMdCSerializationBuffer& aBuffer) const;
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEPropertyDef();
+
+	TDefId Id() const;
+	void SetId(TDefId aId);
+		
+	TDefId ObjectDefId() const;
+	
+private:
+	CMdEPropertyDef(const TMdCPropertyDef& aPropertyDef, CMdEObjectDef& aObjectDef);
+
+	void ConstructL(CMdCSerializationBuffer& aSchemaBuffer );
+
+private:	
+
+	const TMdCPropertyDef& iPropertyDef;
+	CMdEObjectDef& iObjectDef;
+
+	TPtrC16 iName;
+    };
+
+#endif  // __MDEPROPERTYDEF_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdequery.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,677 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Query base class
+*
+*/
+
+
+#ifndef __MDEQUERY_H__
+#define __MDEQUERY_H__
+
+
+#include <e32base.h>
+#include <badesca.h>
+
+#include <mdccommon.h>
+
+
+/* Forward declarations. */
+class CMdESession;
+class CMdEQuery;
+class CMdELogicCondition;
+class TMdEOrderRule;
+class CMdENamespaceDef;
+class CMdEItem;
+class CMdEInstanceItem;
+
+
+/**
+ * Observer interface for MdE database queries.
+ * 
+ * Example of doing a query to metadata database:
+ * 
+ * A class needs to implement MMdEQueryObserver interface if it is going to do a query to MdE database.
+ * 
+ * class CMdEQueryExample : public MMdEQueryObserver
+ * {
+ *		void HandleQueryNewResults(CMdEQuery& aQuery, TInt aFirstNewItemIndex, TInt aNewItemCount);
+ *		void HandleQueryCompleted(CMdEQuery& aQuery, TInt aError);
+ * 		...
+ * 		CMdESession* iMdeSession; // session to MdE, created before trying to do the query
+ * 		CMdEQuery* iQuery;
+ * };
+ * 
+ * void CMdEQueryExample::DoQuery()
+ * {
+ * 		CMdENamespaceDef& defNS = iMdeSession->GetDefaultNamespaceDefL();
+ *	    
+ *	    // In this function we create a query with following conditions:
+ *	    // 		Right object in relation must be a location object.
+ *	    // 		Left object in relation must have id 6.
+ * 
+ * 		// First create an object query. We want to find location objects so let's give that
+ * 		// as a condition to the query. 
+ *	    CMdEObjectDef& rightObjDef = defNS.GetObjectDefL(
+ *	        MdeConstants::Location::KLocationObject );
+ *	    iQuery = iMdeSession->NewObjectQueryL( defNS, rightObjDef, this );
+ *			    
+ * 		// Result mode EQueryResultModeItem means we want the query to return items.
+ * 		// Other options are: EQueryResultModeId, EQueryResultModeCount, 
+ * 		// EQueryResultModeDistinctValues and EQueryResultModeObjectWithFreetexts.
+ *	    iQuery->SetResultMode( EQueryResultModeItem );
+ * 
+ * 		// ELogicConditionOperatorAnd means we want all conditions to be true.
+ *	    iQuery->Conditions().SetOperator( ELogicConditionOperatorAnd );
+ *	
+ * 		// Add a relation condition to the query. The location object is the right side object of
+ * 		// the relation.
+ *	    CMdERelationCondition& filterCond = iQuery->Conditions().
+ *	        AddRelationConditionL( ERelationConditionSideRight );
+ *			        
+ *		// The object on the left side of the relation must have ID 6.
+ *	    filterCond.LeftL().AddObjectConditionL( 6 );
+ *			    
+ *	    iQuery->FindL( 10, 1 ); // Start the query! The first parameter is maximum number of result items. 
+ * 								// The second parameter is number of results per observer
+ *								// notification. This query returns maximum of 10 location items
+ * 								// and gives a notification (HandleQueryNewResults) for each.
+ * }
+ * 
+ * void CMdEQueryExample::HandleQueryCompleted( CMdEQuery& aQuery, TInt aError )
+ * {
+ * 		// query is completed
+ * 		if( aQuery.Count() > 0 && aError == KErrNone )
+ *		{
+ *		// some items were found!
+ *		}
+ * }
+ * 
+ * void CMdEQueryExample::HandleQueryNewResults(CMdEQuery& aQuery, TInt aFirstNewItemIndex,
+ *                                       TInt aNewItemCount)
+ * {
+ * 		// query is not yet completed but new results were found
+ * }
+ * 
+ * @see CMdEQuery::FindL
+ */
+class MMdEQueryObserver 
+    {
+public:
+
+    /**
+     * Called to notify the observer that new results have been received 
+     * in the query.
+     *
+     * @param aQuery              Query instance that received new results.
+     * @param aFirstNewItemIndex  Index of the first new item that was added
+     *                            to the result item array.
+     * @param aNewItemCount       Number of items added to the result item 
+     *                            array.
+     */
+    virtual void HandleQueryNewResults(CMdEQuery& aQuery,
+                                       TInt aFirstNewItemIndex,
+                                       TInt aNewItemCount) = 0;
+
+
+            
+    /**
+     * Called to notify the observer that the query has been completed,
+     * or that an error has occured.
+     *
+     * @param aQuery  Query instance.
+     * @param aError  <code>KErrNone</code>, if the query was completed
+     *                successfully. Otherwise one of the system-wide error 
+     *                codes.
+     */
+    virtual void HandleQueryCompleted(CMdEQuery& aQuery, TInt aError) = 0;
+    
+    };
+
+
+/** Default count for finding items. */
+static const TUint KMdEQueryDefaultMaxCount = KMaxTUint;
+
+
+/**
+ * MdE database query. This is the abstract base class for all metadata engine
+ * database queries. Instances of a query class own all the result items 
+ * fetched from the database; when the query instance is destroyed, the 
+ * results will be destroyed as well.
+ *
+ * If a query is restarted by calling FindL() after a previous query operation 
+ * has been completed, any new results are appended to the end of the result 
+ * item list. The previous results are not affected by subsequent calls to 
+ * FindL().
+ *
+ * The query parameters (order rules, search conditions, property filters) 
+ * must be configured before FindL() is called. FindL() may be called several
+ * times, but the query parameters that were in effect for the first Find()
+ * are used for all FindL()s.
+ */
+
+NONSHARABLE_CLASS(CMdEQuery) : public CBase
+	{
+public: 
+
+    /** 
+     * Query states.
+     */
+    enum TState
+        {
+        EStateFirst = 0x0000,
+        
+        /** The query has been created. The query parameters are specified
+            during this state. */
+        EStateNew,
+        
+        /** The query has been started with Find(). All the results received
+            so far are available to the user. */
+        EStateSearching,
+        
+        /** All the results have been found and they are available to 
+            the user. */
+        EStateCompleted,
+        
+        /** An error has occured. */
+        EStateError,
+        
+        EStateLast
+        };
+
+    /* Constants. */
+	
+	/* Constructors and destructor. */
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEQuery();
+
+
+    /* Methods. */
+
+    /**
+	 * Returns the type of the query.
+	 *
+	 * @return  Query type.
+	 */
+	IMPORT_C TQueryType Type() const;
+
+    /**
+	 * Returns the namespace definition of the query.
+	 *
+	 * @return  Namespace definition.
+	 */
+	IMPORT_C CMdENamespaceDef& NamespaceDef() const;
+
+    /**
+	 * Returns the session of the query.
+	 *
+	 * @return  Session.
+	 */
+    IMPORT_C CMdESession& Session() const;
+
+    /**
+     * Returns the root of the condition tree.
+     *
+     * @return  Logic condition that acts as the root of the search conditions
+     *          tree.
+     */
+    IMPORT_C CMdELogicCondition& Conditions() const;
+    
+    /**
+     * Appends a new result ordering rule into the end of list of order rules.
+     *
+     * Example:
+     *   CMdEObjectDef& objdef = iDefaultNamespaceDef->GetObjectDefL( MdeConstants::Object::KBaseObject );
+     *   CMdEPropertyDef& propDef = objdef.GetPropertyDefL( MdeConstants::Object::KCreationDateProperty );
+     *   TMdEOrderRule rule( *propDef, ETrue );
+	 *   iQuery->AppendOrderRuleL( rule ); // iQuery is CMdEQuery*
+     * 
+     * @param aRule  Order rule.
+     */
+    IMPORT_C void AppendOrderRuleL(const TMdEOrderRule& aRule);
+
+    /**
+     * Insert a new result ordering rule into the list of order rules. 
+     * The first rule is at position zero.
+     * 
+     * Example:
+     *   CMdEObjectDef& objdef = iDefaultNamespaceDef->GetObjectDefL( MdeConstants::Object::KBaseObject );
+     *   CMdEPropertyDef& propDef = objdef.GetPropertyDefL( MdeConstants::Object::KCreationDateProperty );
+     *   TMdEOrderRule rule( *propDef, ETrue );
+	 *   iQuery->InsertOrderRuleL( rule, 0 ); // iQuery is CMdEQuery*
+     *
+     * @param aRule  Order rule.
+     * @param aPos   Position in the list of rules to insert into.
+     */
+    IMPORT_C void InsertOrderRuleL(const TMdEOrderRule& aRule, TInt aPos);
+    
+    /**
+     * Returns the number of order rules currently defined.
+     *
+     * @return  Number of order rules.
+     */
+    IMPORT_C TInt OrderRuleCount() const;
+    
+    /**
+     * Removes an order rule.
+     *
+     * @param aIndex  Index of the rule to remove.
+     */
+    IMPORT_C void RemoveOrderRule(TInt aIndex);
+
+    /**
+     * Gets an order rule.
+     *
+     * @param aIndex  Index of the rule to return.
+     * @param aRule   Reference to the TMdEOrderRule where the rule is stored.
+     */
+    IMPORT_C TMdEOrderRule OrderRule(TInt aIndex) const;
+
+    /**
+	 * Starts a query operation and returns immediately. The observers of 
+     * the query instance will be notified when the query is completed, or 
+     * if it fails. The query parameters (order rules, search conditions, 
+     * property filters) must be configured before FindL() is called. FindL() 
+     * may be called several times, but the query parameters that were in 
+     * effect for the first FindL() are used for all subsequent calls. Any 
+     * previously fetched query results remain in the query instance's
+     * list of result items; any new result items are appended to the end of
+     * the list.
+     *
+     * The caller can perform a find operation in several steps by using a
+     * sufficiently small maximum number of result items. Subsequent calls to
+     * FindL() work incrementally, continuing the previously started find 
+     * operation.
+     *
+     * @param aMaxCount     Maximum number of result items. Defaults to 
+     *                      unlimited. 
+     * @param aNotifyCount  Maximum number of results per observer
+     *                      notification. Defaults to unlimited.
+     *
+     * @leave  KErrNotReady  The query is in the Searching state.
+     *
+     * @panic  TMdEPanic::EQueryStateIllegalOperation  
+     *         Query is in a state that prohibits calling this method.
+	 */
+    IMPORT_C void FindL(TUint aMaxCount = KMdEQueryDefaultMaxCount,
+                        TUint aNotifyCount = KMdEQueryDefaultMaxCount);
+
+    /**
+	 * Cancels the currently running query operation. Does nothing if the 
+     * query is not currently running. 
+	 */
+    IMPORT_C void Cancel();
+
+    /**
+     * Returns whether the query has been completed.
+     *
+     * @return  <code>ETrue</code>, if the query is not currently running.
+     *          Otherwise <code>EFalse</code>.
+     */
+    IMPORT_C TBool IsComplete() const;
+
+    /**
+     * Returns the error code of the latest completed query. The same error
+     * code has been passed to the query observer.
+     *
+     * @return  Error code.
+     */
+    IMPORT_C TInt Error() const;
+
+	/**
+	 * Returns the current state of the query.
+	 *
+	 * @return  Query state.
+	 */
+	IMPORT_C TState State() const;
+
+    /**
+	 * Returns the number of received result items. This can be called at any
+     * time during the query instance's lifetime.
+	 *
+	 * @return  The number of results.
+	 */
+	IMPORT_C TInt Count() const;
+	
+    
+    /**
+	 * Returns one of the result items. 
+	 * 
+	 * Example:
+	 *   void CExampleClass::HandleQueryCompleted( CMdEQuery& aQuery, TInt aError )
+	 *   {
+	 *     CMdEItem& mdeItem = aQuery.ResultItem( 0 );
+	 *     ...
+	 *   }
+	 * 
+	 * @param aIndex index of the returned item. 
+	 * @panics if aIndex is out of bounds
+	 * @return  Result item. 
+	 */
+    IMPORT_C CMdEItem& ResultItem(TInt aIndex) const;
+
+    /**
+	 * Returns one of the result ids. 
+	 * 
+	 * Example:
+	 *   void CExampleClass::HandleQueryCompleted( CMdEQuery& aQuery, TInt aError )
+	 *   {
+	 *     TItemId mdeItemId = aQuery.ResultId( 0 );
+	 *     ...
+	 *   }
+	 * 
+	 * @param aIndex index of the returned id.
+	 * @panics if aIndex is out of bounds
+	 * @return  Result id.
+	 */
+    IMPORT_C TItemId ResultId(TInt aIndex) const;
+
+    /**
+	 * Returns all of the result ids.
+	 *
+	 * @return  Result ids.
+	 */
+    IMPORT_C const RArray<TItemId>& ResultIds() const;
+
+    /**
+     * Returns one of the result items. Ownership of the item is transferred 
+     * to the caller. The results array element at the specified index will 
+     * still point to the result item.
+     *
+     * @param aIndex  Result index.
+     *
+     * @return  Pointer to result item.
+     */
+    IMPORT_C CMdEItem* TakeOwnershipOfResult(TInt aIndex);
+
+    /**
+     * Determines whether the query owns a result item.
+     * @param aIndex index of the result item which ownership is checked.
+     * @panics if aIndex is out of bounds
+     * @return  <code>ETrue</code>, if the query owns the item. Otherwise
+     *          <code>EFalse</code>.
+     */        
+    IMPORT_C TBool OwnsResult(TInt aIndex);
+	
+	
+    /**
+     * Adds a new observer.
+     *
+     * @param  aObserver to add.
+     */
+    IMPORT_C void AddObserverL(MMdEQueryObserver& aObserver);
+
+    /**
+     * Removes an observer.
+     *
+     * @param  aObserver to remove.
+     */
+    IMPORT_C void RemoveObserver(MMdEQueryObserver& aObserver);
+
+    /**
+     * Sets type of query results. Whether whole items or only IDs.
+     * Default value is EModeItem.
+     *
+     * @param  aMode Determines type of query results. Can be set of
+     *         instance items or set of item IDs
+     */
+    IMPORT_C void SetResultMode( TQueryResultMode aMode );
+    
+    /**
+     * Returns type of query results, whether whole items or only IDs.
+     *
+     * @return Type of query results.
+     */
+    IMPORT_C TQueryResultMode ResultMode() const;
+    
+    /**
+	 * Returns result object item
+	 *
+	 * @return  Result object item.
+	 */
+    IMPORT_C CMdEItem& ResultObjectItem() const;
+
+    /**
+	 * Returns one of the result distinct values
+	 *
+	 * @return  Result distinct value
+	 */
+    IMPORT_C TPtrC16 ResultDistinctValue(TInt aIndex) const;
+
+	/**
+	 * Returns order rules
+	 *
+	 * @return  Order rules
+	 */
+	RArray<TMdEOrderRule>& OrderRules();
+
+	void SetQueryId( TUint32 aQueryId ) const
+		{
+		iQueryId = aQueryId;
+		}
+
+	TUint32 GetQueryId() const
+		{
+		return iQueryId;
+		}
+
+protected:
+
+	/* Constructors. */
+
+	/**
+	 * Constructor. Note that new queries should be created using the factory
+	 * methods in CMdESession.
+	 *
+	 * @param aType     Type of the query.
+     * @param aSession
+	 */
+	CMdEQuery(TQueryType aType, CMdESession& aSession, CMdENamespaceDef& aNamespaceDef);
+
+	/**
+	 * Second-phase constructor. Creates the root node of the conditions tree.
+	 */
+	void QueryConstructL();
+
+
+    /* Implementation methods. */
+
+    /**
+     * As Find().
+     */
+    virtual void DoFindL(TUint aMaxCount, TUint aNotifyCount) = 0;
+
+    /**
+     * As Cancel().
+     */
+    virtual void DoCancel();
+
+
+    /* Notification methods. */
+
+    /**
+     * Appends new item results to the results array. This query instance takes 
+     * ownership of the items. 
+	 *
+	 * If a leave occurs, the query won't take ownership of any of the new 
+     * result items. The caller is responsible for destroying the result
+     * items in this case.
+     *
+     * This operation is atomic: either all of the new results are added to
+     * the results array and the query takes ownership of them, or none of
+     * results are added to the results array.
+     *
+     * @param aNewResults contains result items
+     */
+    virtual void NotifyNewResultsL(const RPointerArray<CMdEInstanceItem>& aNewResults);
+
+    /**
+     * Appends new ID results to the results array.
+     * 
+     * @param aNewResults contains results from ID query
+     */
+    virtual void NotifyNewResultsL(const RArray<TItemId>& aNewResults);
+
+    /**
+     * Appends distinct value results to the results array.
+     * 
+     * @param aResults contains results from distinct value query
+     */
+    virtual void NotifyNewResultsL( const CDesCArray& aNewResults );
+
+
+    /**
+     * Gets result from count query.
+     * 
+     * @param aResults contains result from count query
+     */
+    virtual void NotifyNewResults(TUint32 aResult);
+        
+    /**
+     * Notifies observers that the query was completed.
+     */
+    virtual void NotifyCompleted(TInt aError);
+
+
+	/* Utility methods. */
+	
+	/**
+	 * Sets the state of the query.
+	 *
+	 * @param aState  Query state.
+	 */
+    void SetState(TState aState);
+    
+    /** 
+     * Panics if the state of the query is the specified state.
+     *
+     * @param aState  Query state.
+     *
+     * @panic TMdEPanic::EQueryStateIllegalOperation  The query was not 
+     *        in the given state.
+     */
+    void AssertInState(TState aState);
+    
+    /** 
+     * Panics if the state of the query is not the specified state.
+     *
+     * @param aState  Query state.
+     *
+     * @panic TMdEPanic::EQueryStateIllegalOperation  The query was in the 
+     *        given state.
+     */
+    void AssertNotInState(TState aState);
+
+    
+private:
+
+    /* Private data structures. */
+
+    //  Result item for instances
+    struct TResult
+        {
+        /** Result item. */
+        CMdEItem* iItem;
+
+        /** Query has the ownership of the result item. */
+        TBool iOwned;
+
+        /** Constructor for initializing the struct. */
+        TResult(CMdEItem* aItem) : iItem(aItem), iOwned(EFalse) {}
+        };
+
+
+private:
+
+    /* Private methods. */
+
+    /**
+     * Appends new result items into the results array. Does not transfer
+     * ownership of the new results to the query.
+     *
+     * @param aNewResults  Array of result items.
+     */
+    void AppendResultsL(const RPointerArray<CMdEInstanceItem>& aNewResults);
+
+    void AppendResultsL(const RArray<TItemId>& aNewResults);
+
+	/*void AppendResultsL(CMdEInstanceItem* aObjectResult,
+    	const RPointerArray<CMdEInstanceItem>& aRelationResults, 
+    	const RPointerArray<CMdEInstanceItem>& aEventResults);*/
+    	
+    void AppendResultsL(const CDesCArray& aNewResults);
+    	
+private:
+
+	mutable TUint32 iQueryId;
+
+    /** The session of the query. */
+    CMdESession& iSession;
+
+	/** The namespace definition of the query */
+	CMdENamespaceDef& iNamespaceDef;
+    
+    /** Type of the query. */
+    TQueryType iType;
+
+    /** Type of results. */
+    TQueryResultMode iResultMode;
+
+    /** State of the query. */    
+    TState iState;
+
+    /** Latest error code. */
+    TInt iError;
+
+    /** Root node of the conditions tree.  Always present. */
+    CMdELogicCondition* iConditions;
+    
+    /** Array of result ordering rules. */
+    RArray<TMdEOrderRule> iOrderRules;
+
+    /** Instance result items. */
+    RArray<TResult> iResults;
+    
+    /** ID result items. */
+    RArray<TItemId> iIdResults;
+
+    /** Instance result object item */
+    TResult iObjectResult;
+	
+    /** Results of count query */
+    TInt iCountResult;
+
+    /** Observers. */
+    RPointerArray<MMdEQueryObserver> iObservers;
+    
+    CDesCArray* iDistinctResults;
+    };
+
+    
+// includes only for client more convinient usage
+	#include <mdeobjectquery.h>
+	#include <mderelationquery.h>
+	#include <mdeeventquery.h>
+	#include <mdelogiccondition.h>
+	#include <mdeobjectcondition.h>
+	#include <mderelationcondition.h>
+	#include <mdeeventcondition.h>
+	#include <mdepropertycondition.h>
+	#include <mderange.h>
+	#include <mdeorderrule.h>
+// end
+
+#endif  // __MDEQUERY_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mderange.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Used for representing value ranges of various types.
+*
+*/
+
+
+#ifndef __MDERANGE_H__
+#define __MDERANGE_H__
+
+#include <e32base.h>
+
+class CMdCSerializationBuffer;
+   
+enum TMdERangeType
+	{
+	EMdERangeTypeAny = 0,
+	EMdERangeTypeEqual,
+	EMdERangeTypeNotEqual,
+	EMdERangeTypeLess,
+	EMdERangeTypeLessOrEqual,
+	EMdERangeTypeGreater,
+	EMdERangeTypeGreaterOrEqual,
+	EMdERangeTypeBetween,
+	EMdERangeTypeNotBetween
+	};
+
+class TMdESerializeRange
+	{
+	public:
+		static void SerializeL( CMdCSerializationBuffer& aBuffer, TMdERangeType aType,
+				void* aMin, void* aMax, TInt aValueSize );
+		static TUint32 RequiredBufferSize( TInt aValueSize );
+	};
+	
+#include "mderange.inl"
+
+#endif  // __MDERANGE_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mderange.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,345 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef MDERANGE_INL_
+#define MDERANGE_INL_
+
+/**
+ * The TMdERange template is used for representing value ranges of various 
+ * types. A range is composed of an upper limit, a lower limit, and type 
+ * that describe how the limits are to be interpreted. 
+ *
+ * Value ranges are used with CMdERangePropertyCondition nodes to define 
+ * a range of values that the condition matches. Basic operations such as 
+ * "greater than", "equals to", and "between" are all implemented using 
+ * value ranges. There are also more complex ranges that can be used in 
+ * loops.
+ *
+ * TMdERange is the base template for many different kind of value ranges.
+ * However, all ranges can be processed with the Min(), Max(), and Type() 
+ * methods, regardless of any extra data defined by a specialized range type.
+ */
+template <class T>
+class TMdERange
+    {
+public:
+
+    /* Methods. */
+
+    /**
+     * Returns the lower limit of the range.
+     *
+     * @return  The minimum value.
+     */
+    inline const T& Min() const
+        {
+        return iMin;
+        }
+
+    /**
+     * Returns the upper limit of the range.
+     *
+     * @return  The maximum value.
+     */
+    inline const T& Max() const
+        {
+        return iMax;
+        }
+
+    /**
+     * Returns the type of the range.
+     *
+     * @return  type
+     */
+    inline const TMdERangeType& Type() const
+        {
+        return iType;
+        }
+
+    /**
+     * Sets the lower limit of the range.
+     *
+     * @param aMin  The minimum value.
+     */
+    inline void SetMin(const T& aMin)
+        {
+        iMin = aMin;
+        }
+
+    /**
+     * Sets the upper limit of the range.
+     *
+     * @param aMax  The maximum value.
+     */
+    inline void SetMax(const T& aMax)
+        {
+        iMax = aMax;
+        }
+    
+    /**
+     * Sets the type of the range.
+     *
+     * @param aType  The new type.
+     */
+    inline void SetType(TMdERangeType aType)
+        {
+        iType = aType;
+        }
+
+    /**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+    TUint32 RequiredBufferSize()
+    	{
+     	return TMdESerializeRange::RequiredBufferSize( sizeof(T) );
+    	}
+
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling) and return new position of serialized buffer.
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    void SerializeL(CMdCSerializationBuffer& aBuffer)
+    	{
+    	TMdESerializeRange::SerializeL( aBuffer, iType, &iMin, &iMax, sizeof(T) );
+    	}
+
+    /* Constructor. */
+    TMdERange(const T& aMin, const T& aMax, TMdERangeType aType = EMdERangeTypeAny)
+        : iType(aType), iMin(aMin), iMax(aMax)
+        {
+        }
+
+	/**
+     * Test if value is in the range.
+     *
+     * @param aValue Tested value.
+	 */
+    TBool InRange(const T& aValue)
+        {
+        switch( iType )
+        	{        	
+        	case EMdERangeTypeAny:
+        		{
+        		// always match
+        		return ETrue;
+        		}
+        	case EMdERangeTypeEqual:
+        		{
+        		return ( aValue == iMin );
+        		}
+			case EMdERangeTypeNotEqual:
+				{
+				return ( aValue != iMin );
+				}
+			case EMdERangeTypeLess:
+				{
+				return ( aValue < iMax );
+				}
+			case EMdERangeTypeLessOrEqual:
+				{
+				return ( aValue <= iMax );
+				}
+			case EMdERangeTypeGreater:
+				{
+				return ( aValue > iMin );
+				}
+			case EMdERangeTypeGreaterOrEqual:
+				{
+				return ( aValue >= iMin );
+				}
+			case EMdERangeTypeBetween:
+				{
+				// edges belong to range
+				return ( ( iMin <= aValue ) && ( aValue <= iMax ) );
+				}
+			case EMdERangeTypeNotBetween:
+				{
+				// edges belong to range
+				return ( ( iMin > aValue ) || ( aValue > iMax ) );
+				}
+			default:
+				{
+				// should never happen
+				return EFalse; 
+				}
+        	}
+	    }
+
+private:
+
+    /** Type. */
+    TMdERangeType iType;
+
+    /** Beginning of the range. */
+    T iMin;
+
+    /** End of the range. */
+    T iMax;
+    };
+
+
+/**
+ * Value range that covers everything.
+ */
+template <class T>
+class TMdEAny : public TMdERange<T>
+    {
+public:
+    TMdEAny()
+        : TMdERange<T>(T(0), T(0), EMdERangeTypeAny) {}
+    };
+
+
+/**
+ * TMdEEquals defines a range that contains only a single point. Thus it
+ * functions as an equivalence operator.
+ */
+template <class T> 
+class TMdEEqual : public TMdERange<T>
+    {
+public:
+    TMdEEqual(const T& aValue) 
+        : TMdERange<T>(aValue, aValue, EMdERangeTypeEqual) {}
+    };
+
+/**
+ * Range that contains all values except for one point.
+ */
+template <class T> 
+class TMdENotEqual : public TMdERange<T>
+    {
+public:
+    TMdENotEqual(const T& aValue) 
+        : TMdERange<T>(aValue, aValue, EMdERangeTypeNotEqual) {}
+    };
+
+/**
+ * Less-than range.
+ */
+template <class T> 
+class TMdELess : public TMdERange<T>
+    {
+public:
+    TMdELess(const T& aLimit) 
+        : TMdERange<T>(T(0), aLimit, EMdERangeTypeLess) {}
+    };
+
+
+/**
+ * Less-than-or-equal-to range.
+ */
+template <class T> 
+class TMdELessEqual : public TMdERange<T>
+    {
+public:
+    TMdELessEqual(const T& aLimit) 
+        : TMdERange<T>(T(0), aLimit, EMdERangeTypeLessOrEqual) {}
+    };
+
+
+/**
+ * Greater-than range.
+ */
+template <class T> 
+class TMdEGreater : public TMdERange<T>
+    {
+public:
+    TMdEGreater(const T& aLimit) 
+        : TMdERange<T>(aLimit, T(0), EMdERangeTypeGreater) {}
+    };
+
+
+/**
+ * Greater-than-or-equal-to range.
+ */
+template <class T> 
+class TMdEGreaterEqual : public TMdERange<T>
+    {
+public:
+    TMdEGreaterEqual(const T& aLimit) 
+        : TMdERange<T>(aLimit, T(0), EMdERangeTypeGreaterOrEqual) {}
+    };
+
+
+/**
+ * Between range.  The upper and lower limits are inclusive by default.
+ */
+template <class T> 
+class TMdEBetween : public TMdERange<T>
+    {
+public:
+    TMdEBetween(const T& aMin, const T& aMax) 
+        : TMdERange<T>(aMin, aMax, EMdERangeTypeBetween) {}
+    };
+
+
+/**
+ * Not-between range.  The upper and lower limits are inclusive by 
+ * default.
+ */
+template <class T> 
+class TMdENotBetween : public TMdERange<T>
+    {
+public:
+    TMdENotBetween(const T& aMin, const T& aMax) 
+        : TMdERange<T>(aMin, aMax, EMdERangeTypeNotBetween) {}
+    };
+
+
+/* Types that will be used in practice. */
+
+/** Value range of type TInt. */
+typedef TMdERange<TInt> TMdEIntRange;
+
+/** Value range of type TUint. */
+typedef TMdERange<TUint> TMdEUintRange;
+
+/** Value range of type TInt64. */
+typedef TMdERange<TInt64> TMdEInt64Range;
+
+/** Value range of type TReal. */
+typedef TMdERange<TReal> TMdERealRange;
+
+/** Value range of type TTime. */
+typedef TMdERange<TTime> TMdETimeRange;
+
+
+/** Macro for defining the real typenames. Makes four versions of each
+    range type. */
+#define MDE_DEFINE_ACTUAL_RANGE_TYPES(RangeName) \
+    typedef TMdE##RangeName<TInt> TMdEInt##RangeName; \
+    typedef TMdE##RangeName<TUint> TMdEUint##RangeName; \
+    typedef TMdE##RangeName<TInt64> TMdEInt64##RangeName; \
+    typedef TMdE##RangeName<TReal> TMdEReal##RangeName; \
+    typedef TMdE##RangeName<TTime> TMdETime##RangeName;
+
+MDE_DEFINE_ACTUAL_RANGE_TYPES(Any)
+MDE_DEFINE_ACTUAL_RANGE_TYPES(Equal)
+MDE_DEFINE_ACTUAL_RANGE_TYPES(NotEqual)
+MDE_DEFINE_ACTUAL_RANGE_TYPES(Less)
+MDE_DEFINE_ACTUAL_RANGE_TYPES(LessEqual)
+MDE_DEFINE_ACTUAL_RANGE_TYPES(Greater)
+MDE_DEFINE_ACTUAL_RANGE_TYPES(GreaterEqual)
+MDE_DEFINE_ACTUAL_RANGE_TYPES(Between)
+MDE_DEFINE_ACTUAL_RANGE_TYPES(NotBetween)
+
+#undef MDE_DEFINE_ACTUAL_RANGE_TYPES   
+
+#endif /*MDERANGE_INL_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mderangepropertycondition.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,171 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Represents value range of property condition
+*
+*/
+
+
+#ifndef __MDERANGEPROPERTYCONDITION_H__
+#define __MDERANGEPROPERTYCONDITION_H__
+
+
+#include <mdepropertycondition.h>
+#include <mderange.h>
+
+/* Forward declarations. */
+class CMdEPropertyDef;
+class CMdCSerializationBuffer;
+
+class TMdESerializeRangePropertyCondition
+{
+public:
+	static void SerializeL( CMdCSerializationBuffer& aBuffer, 
+			const CMdEPropertyCondition& aPropertyCondition, 
+			TMdERangeType aType, const void* aMin, const void* aMax, 
+			TInt aValueSize, TMdCOffset& aFreespaceOffset );
+	static TUint32 RequiredBufferSize( TInt aValueSize );
+};
+
+/**
+ * Instances of CMdERangePropertyCondition are associated with a specific 
+ * property definition.
+ */
+template <TConditionType KConditionType, class T>
+NONSHARABLE_CLASS(CMdERangePropertyCondition) : public CMdEPropertyCondition
+	{
+public:
+	/* Constructors and destructor. */
+
+	/**
+	 * Two-phased constructor.
+	 */
+	static CMdERangePropertyCondition* NewL( const CMdEPropertyDef& aPropertyDef,
+			const TMdERange<T>& aValueRange)
+		{
+		CMdERangePropertyCondition* self =
+				CMdERangePropertyCondition::NewLC( aPropertyDef, aValueRange );
+	    CleanupStack::Pop( self );
+	    return self;
+		}
+	
+	/**
+	* Two-phased constructor.
+	*/
+	static CMdERangePropertyCondition* NewLC( const CMdEPropertyDef& aPropertyDef,
+			const TMdERange<T>& aValueRange)
+		{
+		CMdERangePropertyCondition* self =
+				new ( ELeave ) CMdERangePropertyCondition( aPropertyDef, aValueRange );
+	    CleanupStack::PushL( self );
+	    self->ConstructL();
+	    return self;
+		}
+
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdERangePropertyCondition()
+        {
+        }
+
+
+	/* Methods. */
+	
+	/**
+	 * Returns the range of the property condition.
+	 *
+	 * @return  Range.
+	 */
+	inline const TMdERange<T>& Range() const
+	    {
+	    return iRange;
+	    }
+
+    /**
+     * Get possible query's internal optimization flags from condition.
+     *
+     * @param aFlaga query's internal optimization flags
+     * @return last level internal optimization flags
+     */
+    TUint32 InternalQueryOptimizationFlags(TUint32& aFlags)
+    	{
+    	return CMdEPropertyCondition::InternalQueryOptimizationFlags(aFlags);
+    	}
+
+    /**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+    TUint32 RequiredBufferSize() const
+    	{
+    	return TMdESerializeRangePropertyCondition::RequiredBufferSize( 
+    			sizeof(T) );
+    	}
+
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling) and return new position of serialized buffer.
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    void SerializeL(CMdCSerializationBuffer& aBuffer, 
+    		TMdCOffset& aFreespaceOffset) const
+    	{
+    	TMdESerializeRangePropertyCondition::SerializeL( aBuffer, *this, iRange.Type(), 
+    			&iRange.Min(), &iRange.Max(), sizeof(T), aFreespaceOffset );
+    	}
+
+protected:
+
+	/* Utility methods. */
+
+
+private:
+
+    /* Private methods. */
+	/**
+	 * Constructor. 
+	 *
+	 * @param aType  type of the condition node
+	 */
+    CMdERangePropertyCondition(const CMdEPropertyDef& aPropertyDef,
+        const TMdERange<T>& aValueRange)
+        : CMdEPropertyCondition(KConditionType, aPropertyDef), 
+          iRange(aValueRange)
+        {
+        }
+
+private:
+
+    /** The value range that is valid for the condition. */
+    TMdERange<T> iRange;
+    };
+
+
+/* The actual RangePropertyConditions. */
+
+#define MDE_DEFINE_RANGE_CONDITION(RangeType) \
+    typedef CMdERangePropertyCondition<EConditionTypeProperty##RangeType##Range, T##RangeType> CMdE##RangeType##RangePropertyCondition;
+
+MDE_DEFINE_RANGE_CONDITION(Int)
+MDE_DEFINE_RANGE_CONDITION(Int64)
+MDE_DEFINE_RANGE_CONDITION(Uint)
+MDE_DEFINE_RANGE_CONDITION(Real)
+MDE_DEFINE_RANGE_CONDITION(Time)
+
+#undef MDE_DEFINE_RANGE_CONDITION
+ 
+#endif  // __MDERANGEPROPERTYCONDITION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mderelation.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,261 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDERELATION_H__
+#define __MDERELATION_H__
+
+
+#include <mdeinstanceitem.h>
+
+
+class CMdERelationDef;
+class CMdCSerializationBuffer;
+class CMdENamespaceDef;
+
+
+NONSHARABLE_CLASS(TMdERelation)
+	{
+	public:
+
+		TMdERelation();
+	
+		IMPORT_C TItemId Id() const;
+	
+		/**
+		 * Returns the definition of the relation.
+		 *
+		 * @return  relation definition
+		 */
+		IMPORT_C CMdERelationDef& DefL() const;
+	
+		/**
+		 * Returns the identifier of the left object of the relation.
+		 *
+		 * @return  object identifier
+		 */
+		IMPORT_C TItemId LeftObjectId() const;
+	
+		/**
+		 * Returns the identifier of the right object of the relation.
+		 *
+		 * @return  object identifier
+		 */
+		IMPORT_C TItemId RightObjectId() const;
+
+	public:
+		/**
+		 * Calculates required size for buffer to serialize relation
+		 *
+		 * @return necessary buffer size
+		 */
+		TUint32 RequiredBufferSize() const;
+		
+		/**
+		 * DeSerialize relation
+		 *
+		 * @param aBuffer buffer where is serialized relation
+		 */
+		void DeSerializeL(CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef);
+
+	private:
+
+		TItemId iId;
+
+		TItemId iLeftObjectId;
+		TItemId iRightObjectId;
+
+		/** Relation definition. */
+		CMdERelationDef* iDef;
+	};
+
+/**
+ * Relation between two objects.
+ */
+NONSHARABLE_CLASS(CMdERelation) : public CMdEInstanceItem
+	{
+public:
+	
+	/* Constructors and destructor. */
+
+	/**
+	 * Create new realation from serialized buffer
+	 *
+	 * @param aBuffer serialized relation
+	 * @return new relation
+	 */
+	static CMdERelation* NewL(CMdESession* aSession, CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef);
+
+	/**
+	 * Create new realation from serialized buffer and leaves it on stack
+	 *
+	 * @param aBuffer serialized relation
+	 * @return new relation
+	 */
+	static CMdERelation* NewLC(CMdESession* aSession, CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef);
+
+
+	static CMdERelation* NewL(CMdERelationDef& aDef, TItemId aLeftObjectId, 
+			 TItemId aRightObjectId, TInt32 aParameter);
+	
+	static CMdERelation* NewLC(CMdERelationDef& aDef, TItemId aLeftObjectId, 
+			 TItemId aRightObjectId, TInt32 aParameter);
+	
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdERelation();
+
+
+	/* Methods. */
+
+	/**
+	 * Returns the definition of the relation.
+	 *
+	 * @return  relation definition
+	 */
+	IMPORT_C CMdERelationDef& Def() const;
+
+	/**
+	 * Returns the identifier of the left object of the relation.
+	 *
+	 * @return  object identifier
+	 */
+	IMPORT_C TItemId LeftObjectId() const;
+
+	/**
+	 * Returns the identifier of the right object of the relation.
+	 *
+	 * @return  object identifier
+	 */
+	IMPORT_C TItemId RightObjectId() const;
+
+	/**
+	 * Returns the parameter value associated with this relation
+	 *
+	 * @return The parameter value
+	 */
+	IMPORT_C TInt32 Parameter() const;
+	
+	/**
+	 * Set the parameter.
+	 * @param aParameter new value for parameter
+	 */
+	IMPORT_C void SetParameter(TInt32 aParameter);
+
+	/**
+	 * Sets left object ID.
+	 * @param aLeftObjectId left object ID
+	 */
+	IMPORT_C void SetLeftObjectIdL( TItemId aLeftObjectId );
+
+	/**
+	 * Sets right object ID.
+	 * @param aRightObjectId right object ID
+	 */
+	IMPORT_C void SetRightObjectIdL( TItemId aRightObjectId );
+
+	/**
+	 * Returns the GUID of the relation.
+	 *
+	 * @param aGuidHigh reference where GuidHigh will be stored
+	 * @param aGuidLow reference where GuidLow will be stored
+	 */
+	IMPORT_C void Guid(TInt64& aGuidHigh, TInt64& aGuidLow) const;
+
+	/**
+	 * Sets the GUID of the relation.
+	 *
+	 * @param aGuidHigh new GuidHigh value
+	 * @param aGuidLow new GuidLow value
+	 */
+	IMPORT_C void SetGuid(const TInt64& aGuidHigh, const TInt64& aGuidLow);
+
+	/**
+	 * Returns last modified date of the relation.
+	 *
+	 * @return last modified date
+	 */
+	IMPORT_C TTime LastModifiedDate() const;
+
+	/**
+	 * Sets last modified date of the relation.
+	 *
+	 * @param aLastModifiedDate last modified date
+	 */
+	IMPORT_C void SetLastModifiedDate(TTime aLastModifiedDate);
+
+	/**
+	 * Calculates required size for buffer to serialize relation
+	 *
+	 * @return necessary buffer size
+	 */
+	TUint32 RequiredBufferSize() const;
+
+	/**
+	 * Serialize relation
+	 *
+	 * @param aBuffer buffer where serialized relation should go
+	 */
+	TMdCOffset SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreespaceOffset) const;
+	
+protected:
+
+	/**
+	 * Constructs a new relation.
+	 *
+	 * @param aDef            definition of the new relation
+	 * @param aLeftObjectId   identifier of the left object of the new relation
+	 * @param aRightObjectId  identifier of the right object of the new relation
+	 * @param aParameter value for parameter
+	 * 
+	 */
+	CMdERelation(CMdESession* aSession, TItemId aId, 
+			     CMdERelationDef& aDef, TItemId aLeftObjectId, 
+				 TItemId aRightObjectId, TInt32 aParameter);
+	
+	/**
+	 * Second-phase constructor.
+	 */
+	void ConstructL();
+
+	TMdEInstanceType InstanceType() const;
+
+	
+private:
+
+	/** Relation definition. */
+	CMdERelationDef& iDef;
+
+	/** Left object ID. */
+	TItemId iLeftObjectId;
+
+	/** Right object ID. */
+	TItemId iRightObjectId;
+	
+	/** Parameter value */
+	TInt32 iParameter;
+	
+	/** Guid High and Low */
+	TInt64 iGuidHigh;
+	TInt64 iGuidLow;
+	
+	/** Relations last modified date */
+	TTime iLastModifiedDate;
+	};
+
+#endif  // __MDERELATION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mderelationcondition.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,237 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDERELATIONCONDITION_H__
+#define __MDERELATIONCONDITION_H__
+
+
+#include <mdccommon.h>
+#include <mdecondition.h>
+#include <mderange.h>
+
+
+/* Forward declarations. */
+class CMdELogicCondition;
+class CMdERelationDef;
+
+/**
+ * Search condition for relations.
+ */
+NONSHARABLE_CLASS(CMdERelationCondition) : public CMdECondition
+	{
+public:
+
+	/* Constructors and destructor. */
+
+	static CMdERelationCondition* NewL( TItemId aRelationId = KNoId,
+			const RArray<TItemId>* aRelationIds = NULL, 
+			TRelationConditionSide aSide = ERelationConditionSideEither,
+			const CMdERelationDef* aRelationDef = NULL,
+			const TMdEIntRange* aParameterRange = NULL );
+
+	static CMdERelationCondition* NewLC( TItemId aRelationId = KNoId,
+			const RArray<TItemId>* aRelationIds = NULL, 
+			TRelationConditionSide aSide = ERelationConditionSideEither,
+			const CMdERelationDef* aRelationDef = NULL,
+			const TMdEIntRange* aParameterRange = NULL );
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdERelationCondition();
+
+	/* Methods. */
+
+    /**
+     * Returns the relation ID.
+     *
+     * @return Relation ID.
+     */
+    IMPORT_C TItemId RelationId() const;
+
+    /**
+     * Returns the relation IDs.
+     *
+     * @return Relation IDs.
+     */
+    IMPORT_C const RArray<TItemId>* RelationIds() const;
+    
+    /**
+     * Returns a pointer to the relation definition.
+     *
+     * @return  Relation definition; or <code>NULL</code>,
+     *          if no relation definition has been associated with this
+     *          condition.
+     */
+    IMPORT_C const CMdERelationDef* RelationDef() const;
+
+    /**
+     * Returns the conditions for the object on the left side of the relation.
+     *
+     * @return  Logic condition node.
+     */
+    IMPORT_C CMdELogicCondition& LeftL();
+
+    /**
+     * Returns the conditions for the object on the right side of the 
+     * relation.
+     *
+     * @return  Logic condition node.
+     */
+    IMPORT_C CMdELogicCondition& RightL();
+
+    /**
+     * Returns the side on which a matched object must be.
+     * @return The side on which an object must be.
+     */
+    TRelationConditionSide Side() const;
+
+    /**
+     * Sets the side on which a matched object must be.
+     * @return The side on which an object must be.
+     */
+    IMPORT_C void SetSide(TRelationConditionSide aSide);
+
+    /**
+     * Returns the relation parameter range.
+     * @return Parameter's range conditions 
+     */
+    IMPORT_C const TMdEIntRange* ParameterRange() const;
+
+	/**
+	 * Sets the GUID which a relation must match.
+	 *
+	 * @param aGuidHigh new GuidHigh value
+	 * @param aGuidLow new GuidLow value
+	 */
+	IMPORT_C void SetGuid(const TInt64& aGuidHigh, const TInt64& aGuidLow);
+
+	/**
+	 * Gets the GUID which a relation must match.
+	 *
+	 * @param aGuidHigh reference where GuidHigh will be stored
+	 * @param aGuidLow reference where GuidLow will be stored
+	 * @return returns ETrue if relation condition contains GUID condition, 
+	 *         otherwise doesn't change parameters' values and returns EFalse
+	 */
+	IMPORT_C TBool Guid(TInt64& aGuidHigh, TInt64& aGuidLow) const;
+
+	/**
+	 * Sets the last modified date range which a relation must match.
+	 *
+	 * @param aLastModifiedTimeRange last modified date range
+	 */
+	IMPORT_C void SetLastModifiedDateRangeL(const TMdETimeRange& aLastModifiedDateRange);
+
+	/**
+	 * Gets the last modified date range which a relation must match.
+	 *
+	 * @param aLastModifiedDateRange reference where last modified date range will be stored
+	 * @return returns ETrue if relation condition contains last modified date range condition, 
+	 *         otherwise doesn't change parameter's value and returns EFalse
+	 */
+	IMPORT_C TBool LastModifiedDateRange(TMdETimeRange& aLastModifiedDateRange) const;
+
+    /**
+     * Get possible query's internal optimization flags from condition.
+     *
+     * @param aFlaga query's internal optimization flags
+     * @return last level internal optimization flags
+     */
+    TUint32 InternalQueryOptimizationFlags(TUint32& aFlags);
+
+	/**
+     * Get required size of serialized buffer when it is serialized.
+     *
+     * @return required serialized buffer size
+     */
+	TUint32 RequiredBufferSize() const;
+	
+	/**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling).
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    void SerializeL(CMdCSerializationBuffer& aBuffer,
+    		TMdCOffset& aFreespaceOffset) const;
+
+protected:
+
+    /* Constructor. */
+
+
+	/* Utility methods. */
+
+
+private:
+
+    /* Private methods. */
+
+  	/**
+	 * Constructor.
+	 *
+     * @param aRelationId  The relation ID which an relation must match.
+     * @param aSide  The side on which an object must be.
+	 * @param aRelationDef  relation definition
+	 */
+	CMdERelationCondition(TItemId aRelationId, TRelationConditionSide aSide, 
+			const CMdERelationDef* aRelationDef);
+
+    /**
+	 * Second-phase constructor. Creates two LogicConditions as children of 
+     * this relation condition and creates range condition for parameter. 
+     * Ownership of the parameter stays with caller.
+     *
+     * @param aRelationIds  The relation IDs which an relation must match.
+     * @param aParameterRange parameter range conditions
+	 */
+    void ConstructL(const RArray<TItemId>* aRelationIds, 
+    		const TMdEIntRange* aParameterRange);
+
+
+private:
+
+	const TItemId iRelationId;
+	
+	RArray<TItemId>* iRelationIds;
+
+    /** Relation definition. */
+    const CMdERelationDef* iRelationDef;
+
+    /** Conditions for the left object. */
+    CMdELogicCondition* iLeftCondition;
+
+    /** Conditions for the right object. */
+    CMdELogicCondition* iRightCondition;
+
+    /** The side on which an object must be. */
+    TRelationConditionSide iSide;
+
+    /** Conditions for the relation parameter. */
+    TMdEIntRange* iParameterRange;
+    
+    /** Conditions for the relation GUID. */
+    TInt64 iGuidHigh;
+    TInt64 iGuidLow;
+    
+    /** Conditions for the relation last modified date. */
+    TMdETimeRange* iLastModifiedDateRange;
+    };
+
+#endif  // __MDERELATIONCONDITION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mderelationdef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,89 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+#ifndef __MDERELATIONDEF_H__
+#define __MDERELATIONDEF_H__
+
+
+#include <e32base.h>
+
+#include <mdccommon.h>
+
+// Forward declaration
+class CMdCSerializationBuffer;
+class CMdENamespaceDef;
+class TMdCRelationDef;
+
+
+/**
+ * Relation definition.
+ */
+NONSHARABLE_CLASS(CMdERelationDef) : public CBase
+	{
+public:	
+
+	static CMdERelationDef* NewL(const TMdCRelationDef& aRelationDef, CMdCSerializationBuffer& aSchemaBuffer,
+			CMdENamespaceDef& aNamespaceDef);
+
+	static CMdERelationDef* NewLC(const TMdCRelationDef& aRelationDef, CMdCSerializationBuffer& aSchemaBuffer,
+			CMdENamespaceDef& aNamespaceDef);
+
+	/**
+	 * Returns the name of the item.
+	 *
+	 * @return  name
+	 */
+	IMPORT_C const TDesC& Name() const;
+
+	/**
+	 * Compare this relation definition with other relation definition.
+	 *
+	 * @param aRelationDef other relation definition
+	 *
+	 * @return  0 if relations are same, 1 or more if this is greater than other 
+	 *          and -1 or less if this is less than other.
+	 */
+	IMPORT_C TInt Compare(const CMdERelationDef& aRelationDef) const;
+
+	/**
+	 * Returns namespace definition of namespace which contains this relation
+	 * @return namespace definition of relation
+	 */
+	IMPORT_C CMdENamespaceDef& NamespaceDef() const;
+
+public:		
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdERelationDef();
+
+	TDefId Id() const;
+
+private:
+	CMdERelationDef(const TMdCRelationDef& aRelationDef, CMdENamespaceDef& aNamespaceDef);
+
+	void ConstructL(CMdCSerializationBuffer& aSchemaBuffer);
+
+private:
+	const TMdCRelationDef& iRelationDef;
+	CMdENamespaceDef& iNamespaceDef;
+
+	TPtrC16 iName;
+	};
+
+#endif  // __MDERELATIONDEF_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mderelationquery.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,85 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDERELATIONQUERY_H__
+#define __MDERELATIONQUERY_H__
+
+
+#include <mdequery.h>
+
+
+/* Forward declarations. */
+class CMdERelation;
+class CMdENamespaceDef;
+class CMdESession;
+
+/**
+ * Query that fetches a set of relation items from the metadata engine 
+ * database.
+ */
+NONSHARABLE_CLASS(CMdERelationQuery) : public CMdEQuery
+	{
+public:
+	
+	/* Constructors and destructor. */
+
+    /**
+	 * Destructor.
+	 */
+	virtual ~CMdERelationQuery();
+
+
+	/* Methods. */
+ 
+    /**
+	 * Returns one of the result objects.
+	 *
+	 * @return  The result object that was requested. The query retains 
+     *          ownership of the returned object.
+	 */
+	IMPORT_C CMdERelation& Result(TInt aIndex) const;
+
+
+protected:
+
+	/* Constructors. */
+	
+	/**
+	 * Constructor. 
+	 *
+	 * @param aType  type of the condition node
+	 */
+	CMdERelationQuery(CMdESession& aSession, CMdENamespaceDef& aNamespaceDef);
+
+	/**
+	 * Second-phase constructor.
+	 */
+	void RelationQueryConstructL();
+
+    virtual void DoCancel();
+
+private:
+
+    /* Private methods. */
+
+
+private:
+
+    };
+
+#endif  // __MDERELATIONQUERY_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdesession.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1743 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Metadata engine client session
+*
+*/
+
+
+#ifndef __MDESESSION_H__
+#define __MDESESSION_H__
+
+
+#include <e32base.h>
+#include <badesca.h>
+
+#include <mdccommon.h>
+
+
+/* Forward declarations. */
+class CMdESession;
+class CMdEObjectDef;
+class CMdERelationDef;
+class CMdEEventDef;
+class CMdEObject;
+class TMdEObject;
+class CMdERelation;
+class TMdERelation;
+class CMdEEvent;
+class CMdEObjectQuery;
+class CMdERelationQuery;
+class CMdEEventQuery;
+class CMdELogicCondition;
+class CMdEInstanceItem;
+class RMdEEngineSession;
+class MMdEQueryObserver;
+class CMdENamespaceDef;
+class RMdEDataBuffer;
+class CMdECondition;
+
+
+
+/**
+ * Observer interface for a metadata engine session.
+ * 
+ * 
+ * 
+ * Examples of MdE session usage:
+ * 
+ * The class that needs a MdE session needs to implement MMdESessionObserver interface to get
+ * a notification of completed session opening or an error that has occurred.
+ * 
+ * class CMdESessionExample : public MMdESessionObserver
+ * {
+ * 		void HandleSessionOpened(CMdESession& aSession, TInt aError);
+ *   	void HandleSessionError(CMdESession& aSession, TInt aError);
+ * 		...
+ * 
+ * 		CMdESession* iMdeSession;
+ * };
+ * 
+ * The session is opened simply by creating an instance of CMdESession.
+ * 
+ * void CMdESessionExample::OpenSession()
+ * {
+ * 		iMdeSession = CMdESession::NewL( *this );
+ * }
+ * 
+ * void CMdESessionExample::HandleSessionOpened(CMdESession& aSession, TInt aError)
+ *	{
+ *		if ( KErrNone != aError ) {
+ * 			// Error occurred when opening session. iMdeSession must be deleted and new
+ * 			// session opened if we wish to use MdE.
+ * 
+ * 			delete iMdeSession; iMdeSession = NULL;
+ * 			return;
+ * 		}
+ * 		
+ * 		// The session was opened successfully.
+ * 		...
+ *	}
+ * 
+ * void CMdESessionError::HandleSessionError(CMdESession& aSession, TInt aError)
+ * {
+ * 		// This function is called when an error has occurred in the session by some
+ * 		// external source (e.g. other clients). It’s important to notice, that 
+ * 		// this method is called when the session has already been opened, not when 
+ * 		// error happens during opening. Session can't be used anymore and it must be deleted.
+ * 
+ * 		delete iMdeSession; iMdeSession = NULL;
+ * }
+ */
+class MMdESessionObserver
+	{
+public:
+
+	/**
+	 * Called to notify the observer that opening the session has been 
+	 * completed and, if the opening succeeded, the session is ready for use.
+	 *
+	 * @param aSession session
+	 * @param aError   <code>KErrNone</code>, if opening the session succeeded;
+	 *                 or one of the system-wide error codes, if opening the 
+	 *                 session failed
+	 */
+	virtual void HandleSessionOpened(CMdESession& aSession, TInt aError) = 0;
+
+	/**
+	 * Called to notify the observer about errors, which are not a direct 
+	 * consequence of the operations initiated by the client but caused by 
+	 * some external source (e.g., other clients). The error cannot be 
+	 * recovered and all on-going operations initiated by the client have been 
+	 * aborted. Any attempts to continue using the session will cause a panic. 
+	 * The client should close the session immediately and try to open a new 
+	 * session, if it needs to continue using the metadata engine.
+	 *
+	 * @param aSession session
+	 * @param aError one of the system-wide error codes
+	 */
+	virtual void HandleSessionError(CMdESession& aSession, TInt aError) = 0;
+    };
+
+
+/**
+ * Observer interface for modifications of the metadata engine schema.
+ */
+class MMdESchemaObserver
+	{
+public:
+
+	/**
+	 * Called to notify the observer that the schema has been modified.
+	 *
+	 * @param none
+	 */
+	virtual void HandleSchemaModified() = 0;
+    };
+    
+/**
+ * Observer interface for modifications of the objects in the metadata engine 
+ * database.
+ * 
+ * Examples of observers.
+ * A class that is interested in observing events in the DB must implement observer interfaces
+ * and register as observer. Following examples show how this is done for objects but observing
+ * relations and events works the same way.
+ * 
+ * class CMdeObserverExample : public MMdEObjectObserver, public MMdEObjectPresentObserver
+ * {
+ *		void HandleObjectNotification(CMdESession& aSession, TObserverNotificationType aType,
+ *						const RArray<TItemId>& aObjectIdArray);
+ *		void HandleObjectPresentNotification(CMdESession& aSession, TBool aPresent,
+ *		 				const RArray<TItemId>& aObjectIdArray);
+ * 		...
+ * 		CMdESession* iMdeSession;
+ * };
+ * 
+ * void CMdeObserverExample::ConstructL()
+ * {
+ * 		// Register this class as observer and start listening to object remove events.
+ * 		// The logic condition can be as complicated as is necessary. In this example
+ * 		// the condition as simple as possible.
+ *		CMdELogicCondition* condition = CMdELogicCondition::NewL( ELogicConditionOperatorAnd );
+ *		iMdeSession->AddObjectObserverL( *this, condition, ENotifyRemove, 
+ *   		&iMdeSession->GetDefaultNamespaceDefL() );
+ * 
+ * 		// Start listening to changes in object present status.
+ * 		iMdeSession->AddObjectPresentObserverL( *this );
+ * }
+ * 
+ * @see MMdEObjectObserver::HandleObjectNotification
+ * void CMdeObserverExample::HandleObjectNotification(CMdESession& aSession, TObserverNotificationType aType,
+ *						const RArray<TItemId>& aObjectIdArray)
+ * {
+ *	 	if ( aType == ENotifyAdd )
+ * 		{	
+ * 		// object was added to DB
+ * 		} else if ( aType == ENotifyModify )
+ * 		{
+ * 		// object was modified
+ * 		} else if ( aType == ENotifyRemove )
+ * 		{
+ * 		// object was removed from DB
+ * 		}
+ * 
+ * 		// aObjectIdArray contains ids for all objects that were added/modified/removed
+ * }
+ * 
+ * void CMdeObserverExample::HandleObjectPresentNotification(CMdESession& aSession, 
+ *			TBool aPresent, const RArray<TItemId>& aObjectIdArray)
+ *	{
+ * 		if ( aPresent )
+ * 		{
+ * 			// objects in aObjectIdArray were set as present
+ * 		}
+ *  }
+ */
+class MMdEObjectObserver
+	{
+public:
+
+	/**
+	 * Called to notify the observer that new objects has been
+	 * added/modified/removed in the metadata engine database.
+	 * 
+	 * @param aSession session
+	 * @param aType defines if object was added/modified/remove
+	 * @param aObjectIdArray IDs of added object
+	 * @see CMdESession::AddObjectObserverL
+	 * @see CMdELogicCondition
+	 */
+	virtual void HandleObjectNotification(CMdESession& aSession, 
+						TObserverNotificationType aType,
+						const RArray<TItemId>& aObjectIdArray) = 0;
+    };
+    
+/**
+ * Observer interface for modifications of the objects in the metadata engine 
+ * database.
+ */
+class MMdEObjectPresentObserver
+	{
+public:
+
+	/**
+	 * Called to notify the observer that objects has been set
+	 * to present or not present state in the metadata engine database.
+	 *
+	 * @param aSession session
+	 * @param aPresent state: ETrue - present or  EFales - not present
+	 * @param aObjectIdArray object IDs which are set to present state
+	 */
+	virtual void HandleObjectPresentNotification(CMdESession& aSession, 
+			TBool aPresent, const RArray<TItemId>& aObjectIdArray) = 0;
+    };
+
+/**
+ * Observer interface for modifications of the relations in the metadata 
+ * engine database.
+ */
+class MMdERelationPresentObserver
+	{
+public:
+
+	/**
+	 * Called to notify the observer that objects has been set
+	 * to present or not present state in the metadata engine database.
+	 *
+	 * @param aSession session
+	 * @param aPresent state: ETrue - present or  EFales - not present
+	 * @param aObjectIdArray object IDs which are set to present state
+	 */
+	virtual void HandleRelationPresentNotification(CMdESession& aSession,
+			TBool aPresent, const RArray<TItemId>& aRelationIdArray) = 0;
+    };
+
+
+/**
+ * Observer interface for modifications of relations in the metadata engine 
+ * database. This observer returns only relations IDs.
+ */
+class MMdERelationObserver
+	{
+public:
+
+	/**
+	 * Called to notify the observer that new relations has been
+	 * added/modified/removed in the metadata engine database.
+	 *
+	 * @param aSession session
+	 * @param aType defines if relation was added/modified/remove
+	 * @param aRelationIdArray IDs of relations
+	 */
+	virtual void HandleRelationNotification(CMdESession& aSession, 
+			TObserverNotificationType aType,
+			const RArray<TItemId>& aRelationIdArray) = 0;
+    };
+
+/**
+ * Observer interface for modifications of relations in the metadata engine 
+ * database. This observer returns relations (not only IDs).
+ */
+class MMdERelationItemObserver
+	{
+public:
+
+	/**
+	 * Called to notify the observer that new relations has been
+	 * added/modified/removed in the metadata engine database.
+	 *
+	 * @param aSession session
+	 * @param aType if relation was added/modified/remove
+	 * @param aRelationArray relations
+	 */
+	virtual void HandleRelationItemNotification(CMdESession& aSession, 
+			TObserverNotificationType aType,
+			const RArray<TMdERelation>& aRelationArray) = 0;
+    };
+
+/**
+ * Observer interface for additions or removes of new events to the metadata 
+ * engine database.
+ */
+class MMdEEventObserver
+	{
+public:
+
+	/**
+	 * Called to notify the observer that new events has been
+	 * added or removed in the metadata engine database.
+	 *
+	 * @param aSession session
+	 * @param aType if event was added or removed
+	 * @param aEventIdArray IDs of added events
+	 */
+	virtual void HandleEventNotification(CMdESession& aSession, 
+			TObserverNotificationType aType,
+			const RArray<TItemId>& aEventIdArray) = 0;
+
+    };
+
+/**
+ * Metadata engine session.
+ */
+NONSHARABLE_CLASS(CMdESession) : public CBase
+	{
+public:
+
+	/* Constructors and destructor. */
+
+	/**
+	 * Opens a new metadata engine session.
+	 *
+	 * @param aObserver observer to notify when opening the session has been 
+	 *                  completed
+	 *
+	 * @return metadata engine session
+	 */
+	IMPORT_C static CMdESession* NewL(MMdESessionObserver& aObserver);
+
+	/**
+	 * Opens a new metadata engine session and leaves the session in the 
+	 * cleanup stack.
+	 *
+	 * @param aObserver observer to notify when opening the session has been 
+	 *                  completed
+     *
+	 * @return  metadata engine session
+	 */
+	IMPORT_C static CMdESession* NewLC(MMdESessionObserver& aObserver);
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdESession();
+
+	/* Methods for managing namespace definitions. */
+
+	/**
+	 * Returns the number of namespace definitions.
+	 *
+	 * @return number of namespace definitions
+	 */
+	virtual TInt NamespaceDefCount() const = 0;
+
+	/**
+	 * Returns the namespace definition at the specified index.
+	 *
+	 * @param aIndex index
+	 *
+	 * @return namespace definition
+	 */
+	virtual CMdENamespaceDef& NamespaceDefL(TInt aIndex) = 0;
+
+	/**
+	 * Returns the namespace definition with the specified name.
+	 *
+	 * @param aName name
+	 *
+	 * @return namespace definition; or 0, if there is no object definition
+	 *         with the specified name
+	 */
+	virtual CMdENamespaceDef& GetNamespaceDefL(const TDesC& aName) = 0;
+
+	 /* Returns the default namespace definition.
+	 *
+	 * @return  the default namespace definition.
+	 */
+	virtual CMdENamespaceDef& GetDefaultNamespaceDefL() = 0;
+
+	/**
+	 * Adds a new relation definition to namespace,
+	 *
+	 * Example:
+	 *  void AddRelationL()
+	 *  {
+	 *    _LIT( TestRelation, "TestRelation" );
+	 *    TBuf <15> relname( TestRelation );
+	 * 	  iMdeSession->AddRelationDefL( *iDefaultNamespaceDef, relname );
+	 *  }
+	 * 
+	 * @param aNamespaceDef namespace definition to which relation belongs
+	 * @param aName         relation definitions name
+	 */
+	virtual void AddRelationDefL(const CMdENamespaceDef &aNamespaceDef, 
+			const TDesC &aName) = 0;
+
+	/**
+	 * Adds a new event definition to namespace.
+	 * 
+	 * Example:
+	 *  void AddEventDefL()
+	 *  {
+	 *    _LIT( TestEvent, "TestEvent" );
+	 *    TBuf <10> eventName( TestEvent );
+	 * 	  iMdeSession->AddRelationDefL( *iDefaultNamespaceDef, eventName );
+	 *  }
+	 *
+	 * @param aNamespaceDef namespace definition to which event belongs
+	 * @param aName         event definitions name
+	 */
+	virtual void AddEventDefL(const CMdENamespaceDef &aNamespaceDef, 
+			const TDesC &aName) = 0;
+
+	/* Methods for managing objects. */
+
+    /**
+     * Adds multiple instance items to metadata database.
+     * The array contains the items, any other type than object, relation or 
+     * event causes a leave.
+	 *
+     * @param aItems list of items to add
+     * @return first item error
+     */
+	virtual TInt AddItemsL( RPointerArray<CMdEInstanceItem>& aItems ) = 0;
+
+    /**
+     * Commits multiple instance items to metadata database.
+     * The array contains the items, any other type than object, relation or 
+     * event causes a leave.
+     * 
+     * @param aItems list of items to add
+     * @return first item error
+     */
+	virtual TInt UpdateItemsL( RPointerArray<CMdEInstanceItem>& aItems ) = 0;
+
+   /**
+     * Adds multiple instance items asynchronously to metadata database.
+     * The array contains the items, any other type than object, relation or 
+     * event causes a leave. Returned serialized list of item IDs must be 
+     * deserialized with DeserializeItemsL method.
+     * 
+     * Example:
+     *  class CExampleActiveObject : public CActive
+     *  {
+     *    void CActiveObject::AddItemsL();
+     *    ...
+     *    RPointerArray<CMdEInstanceItem> iItems;
+     *    RMdEDataBuffer iResultBuffer;
+     *  };
+     * 
+     *  void CExampleActiveObject::AddItemsL()
+     *  {
+     *    iMdeSession->AddItemsAsyncL( iItems, iStatus, iResultBuffer );
+     *    SetActive();
+     *  }
+     * 
+     * When adding items is finished, RunL() will be called.
+     * 
+     * @param aItems List of item to add.
+     * @param aStatus Returns the result code after the asynchronous call 
+     *                completes.
+     * @param aSerializedItemIds Returned serialized list of item IDs.
+     */
+	virtual void AddItemsAsyncL( 
+			RPointerArray<CMdEInstanceItem>& aItems, 
+			TRequestStatus& aStatus,
+			RMdEDataBuffer& aSerializedItemIds) = 0;
+
+   /**
+     * Commits multiple instance items asynchronously to metadata database.
+     * The array contains the items, any other type than object, relation or 
+     * event causes a leave. Returned serialized list of item IDs must be 
+     * deserialized with DeserializeItemsL method.
+     * 
+     * Example:
+     *  class CExampleActiveObject : public CActive
+     *   {
+     *     void CActiveObject::UpdateItemsL();
+     *     ...
+     *     RPointerArray<CMdEInstanceItem> iItems;
+     *     RMdEDataBuffer iResultBuffer;
+     *   };
+     * 
+     *   void CExampleActiveObject::UpdateItemsL()
+     *   {
+     *     iMdeSession->UpdateItemsAsyncL( iItems, iStatus, iResultBuffer );
+     *     SetActive();
+     *   }
+     * 
+     * @param aItems List of item to add.
+     * @param aStatus Returns the result code after the asynchronous call 
+     *                completes.
+     * @param aSerializedItemIds Returned serialized list of item IDs.
+     */
+	virtual void UpdateItemsAsyncL( 
+			RPointerArray<CMdEInstanceItem>& aItems, 
+			TRequestStatus& aStatus,
+			RMdEDataBuffer& aSerializedItemIds ) = 0;
+
+	/**
+	 * Constructs a new empty object. Note that the object is not inserted in 
+	 * the database. The ownership of the new object is passed to the caller 
+	 * (that is, the caller is responsible for deleting the object).
+	 *
+	 * Example:
+	 *  _LIT( KObjectDef, "ObjectDefName" );
+	 *  TBuf<13> objDefStr( KObjectDef );
+	 *  CMdENamespaceDef& defNS = iMdESession->GetDefaultNamespaceDefL();
+	 *	CMdEObjectDef& mdeObjectDef = defNS.GetObjectDefL( objDefStr );
+	 *  CMdEObject* mdeObject = iMdESession->NewObjectL( mdeObjectDef, aUri );
+	 * 
+	 * @param aDef definition of the new object
+	 * @param aUri URI of the new object
+	 * @param aMediaId media ID of the new object (default 0)
+	 *
+	 * @return new object
+	 */
+	virtual CMdEObject* NewObjectL( CMdEObjectDef& aDef, const TDesC& aUri, 
+                                    TUint32 aMediaId = 0 ) = 0;
+
+	/**
+	 * Constructs a new empty object and leaves it in the cleanup stack. 
+	 * Note that the object is not inserted in the database. The ownership of 
+	 * the new object is passed to the caller (that is, the caller is 
+	 * responsible for deleting the object).
+	 * 
+ 	 * Example:
+	 *  _LIT( KObjectDef, "ObjectDefName" );
+	 *  TBuf<13> objDefStr( KObjectDef );
+	 *  CMdENamespaceDef& defNS = iMdESession->GetDefaultNamespaceDefL();
+	 *	CMdEObjectDef& mdeObjectDef = defNS.GetObjectDefL( objDefStr );
+	 *  CMdEObject* mdeObject = iMdESession->NewObjectLC( mdeObjectDef, aUri );
+	 *
+	 * @param aDef definition of the new object
+	 * @param aUri URI of the new object
+	 * @param aMediaId media ID of the new object (default 0)
+	 *
+	 * @return new object
+	 */
+	virtual CMdEObject* NewObjectLC( CMdEObjectDef& aDef, const TDesC& aUri, 
+                                     TUint32 aMediaId = 0 ) = 0;
+
+    /**
+     * Adds the specified new object to metadata database.
+     * aObject is modified so that it has the new item ID.
+     * If object adding fails object's ID is KNoId, 
+     * otherwise object adding is successful.
+     *
+     * @param aObject object to be added
+     *
+     * @return item ID of the added object
+     */
+    virtual TItemId AddObjectL(CMdEObject& aObject) = 0;
+
+    /**
+     * Adds multiple object items to the metadata engine database.
+     * The array contains the object items. aObjects are modified 
+     * so that those has the new item IDs. If object adding fails
+     * object's ID is KNoId, otherwise object adding is successful.
+     *
+     * @param aObjects  list of objects to be added
+     * @return first object error
+     */
+    virtual TInt AddObjectsL(RPointerArray<CMdEObject>& aObjects) = 0;
+
+	/**
+	 * Deserialize serialized list of item IDs
+	 *
+	 * @param aSerializedItemIds serialized list of item IDs
+	 * @param aResultObjects     if not NULL object IDs are deserialized from 
+	 *                           buffer to this ID array
+	 * @param aResultEvents      if not NULL event IDs are deserialized from 
+	 *                           buffer to this ID array
+	 * @param aResultRelations   if not NULL relation IDs are deserialized 
+	 *                           from buffer to this ID array
+	 *
+	 * @return error code of first failed item, if no errors KErrNone
+	 */
+	virtual TInt DeserializeIdsL( RMdEDataBuffer& aSerializedItemIds, 
+			RArray<TItemId>* aResultObjects = NULL, 
+			RArray<TItemId>* aResultEvents = NULL, 
+			RArray<TItemId>* aResultRelations = NULL ) = 0;
+						   
+	/**
+	 * Deserialize serialized list of items
+	 *
+	 * @param aSerializedItems serialized list of items
+	 * @param aItems items are deserialized from buffer to this item array
+	 *
+	 * @return first item error
+	 */
+	virtual TInt DeserializeItemsL( RMdEDataBuffer& aSerializedItems, 
+			RPointerArray<CMdEInstanceItem>& aItems ) = 0;
+
+	/**
+	 * Removes the object with the specified identifier from metadata database.
+	 *
+	 * @param aId identifier
+	 * @param aNamespaceDef namespace where object is removed, if NULL default 
+	 *                      namespace is used
+	 * @return KNoId if removing has failed, otherwise removed object's ID
+	 */
+	virtual TItemId RemoveObjectL( TItemId aId, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Removes the object with the specified URI from metadata database.
+	 *
+	 * @param aUri URI
+	 * @param aNamespaceDef namespace from remove object, if NULL default 
+	 *                      namespace is used
+	 * @return KNoId if removing has failed, otherwise removed object's ID
+	 */
+	virtual TItemId RemoveObjectL( const TDesC& aUri, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Removes the array of objects with the specified identifier from 
+	 * metadata database.
+	 *
+	 * @param aId object IDs to be removed
+	 * @param aResult result array where succefully removed object IDs are 
+	 *                added (KNoId is added from those objects which removing 
+	 *                has failed)
+	 * @param aNamespaceDef namespace where object is removed, if NULL default 
+	 *                      namespace is used
+	 * @return first item error
+	 */
+	virtual TInt RemoveObjectsL( 
+			const RArray<TItemId>& aId, RArray<TItemId>& aResult, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Removes the array of objects with the specified URI from metadata 
+	 * database.
+	 *
+	 * @param aUri object URIs to be removed
+	 * @param aResult result array where succefully removed object IDs are 
+	 *                added (KNoId is added from those objects which removing 
+	 *                has failed)
+	 * @param aNamespaceDef namespace where object is removed, if NULL default 
+	 *                      namespace is used
+	 * @return first item error
+	 */
+	virtual TInt RemoveObjectsL( 
+			const RPointerArray<TDesC>& aUri, RArray<TItemId>& aResult, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Asynchronously removes the array of objects with the specified 
+	 * object IDs from metadata database. Returned serialized list of item IDs 
+	 * must be deserialized with DeserializeIdsL method.
+	 *
+	 * @param aId object IDs to be removed
+     * @param aStatus returns the result code after the asynchronous call 
+     *                completes.
+     * @param aSerializedObjectIds returned serialized list of object IDs
+	 * @param aNamespaceDef namespace where object is removed, if NULL default 
+	 *                      namespace is used
+	 */
+	virtual void RemoveObjectsAsyncL( 
+			const RArray<TItemId>& aId, TRequestStatus& aStatus, 
+			RMdEDataBuffer& aSerializedObjectIds, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Asynchronously removes the array of objects with the specified URI from 
+	 * metadata database. Returned serialized list of item IDs must be 
+	 * deserialized with DeserializeIdsL method.
+	 *
+	 * @param aUri object URIs to be removed
+     * @param aStatus returns the result code after the asynchronous call 
+     *                completes.
+     * @param aSerializedObjectIds returned serialized list of object IDs
+	 * @param aNamespaceDef namespace where object is removed, if NULL default 
+	 *                      namespace is used
+	 */
+	virtual void RemoveObjectsAsyncL( 
+			const RPointerArray<TDesC>& aUri, TRequestStatus& aStatus, 
+			RMdEDataBuffer& aSerializedObjectIds, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+	
+	/**
+	 * Returns the object with the specified ID and specified object 
+	 * definition.
+	 *
+	 * Example:
+	 *   CMdENamespaceDef& defaultNamespace = iSession->GetDefaultNamespaceDefL();
+     * 	 CMdEObjectDef& imageObjDef = defaultNamespace.GetObjectDefL( MdeConstants::Image::KImageObject );
+	 * 	 CMdEObject* object = iSession->GetObjectL( aObjectId, imageObjDef );
+	 * 
+	 * @param aId object ID
+	 * @param aObjectDef object definition
+	 *
+	 * @return object or NULL, if there is no object with the specified 
+	 *         identifier in the metadata engine database
+	 */
+	virtual CMdEObject* GetObjectL( const TItemId aId, 
+			CMdEObjectDef& aObjectDef ) = 0;
+
+	/**
+	 * Returns the object (object may contain only properties defined in 
+	 * "Object") with the specified ID and specified namespace (if namespace 
+	 * is NULL, the default namespace is used).
+	 *
+	 * @param aId object ID
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  object or NULL, if there is no object with the specified 
+	 *          identifier in the metadata engine database
+	 */
+	virtual CMdEObject* GetObjectL( const TItemId aId, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Returns the object (object will contain all it's properties) 
+	 * with the specified ID and specified namespace 
+	 * (if namespace is NULL, the default namespace is used).
+	 *
+	 * @param aId object ID
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  object or NULL, if there is no object with the specified 
+	 *          identifier in the metadata engine database
+	 */
+	virtual CMdEObject* GetFullObjectL( const TItemId aId, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Returns the object with the specified GUID and specified object 
+	 * definition.
+	 * 
+	 * Example:
+	 *   CMdENamespaceDef& defaultNamespace = iSession->GetDefaultNamespaceDefL();
+     * 	 CMdEObjectDef& imageObjDef = defaultNamespace.GetObjectDefL( MdeConstants::Image::KImageObject );
+     *   CMdEObject* object = iMdeSession->GetObjectL( 12345, 67890, imageObjDef );
+	 *
+	 * @param aGuidHigh GUID high
+	 * @param aGuidLow GUID low
+	 * @param aObjectDef object definition
+	 *
+	 * @return  object or NULL, if there is no object with the specified 
+	 *          identifier in the metadata engine database
+	 */
+	virtual CMdEObject* GetObjectL( 
+			const TInt64 aGuidHigh, const TInt64 aGuidLow, 
+			CMdEObjectDef& aObjectDef ) = 0;
+
+	/**
+	 * Returns the object (object may contain only properties definied in 
+	 * "Object") with the specified GUID and specified namespace (if namespace 
+	 * is NULL, the default namespace is used).
+	 *
+	 * Example:
+     *   CMdEObject* object = iMdeSession->GetObjectL( 12345, 67890 );
+	 * 
+	 * @param aGuidHigh  GUID high
+	 * @param aGuidLow  GUID low
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  object or NULL, if there is no object with the specified 
+	 *          identifier in the metadata engine database
+	 */
+	virtual CMdEObject* GetObjectL( 
+			const TInt64 aGuidHigh, const TInt64 aGuidLow, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Returns the object (object will contain all it's properties) 
+	 * with the specified GUID and specified namespace 
+	 * (if namespace is NULL, the default namespace is used).
+	 * 
+	 * Example:
+     *   CMdEObject* object = iMdeSession->GetFullObjectL( 12345, 67890 );
+	 *
+	 * @param aGuidHigh GUID high
+	 * @param aGuidLow GUID low
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  object or NULL, if there is no object with the specified 
+	 *          identifier in the metadata engine database
+	 */
+	virtual CMdEObject* GetFullObjectL( 
+			const TInt64 aGuidHigh, const TInt64 aGuidLow, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Returns the object with the specified URI and specified object 
+	 * definition.
+	 *
+	 * Example:
+	 *   CMdENamespaceDef& defaultNamespace = iSession->GetDefaultNamespaceDefL();
+     * 	 CMdEObjectDef& imageObjDef = defaultNamespace.GetObjectDefL( MdeConstants::Image::KImageObject );
+     *   CMdEObject* object = iMdeSession->GetObjectL( aUri, imageObjDef );
+	 *
+	 * @param aUri object URI
+	 * @param aObjectDef object definition
+	 *
+	 * @return  object or NULL, if there is no object with the specified 
+	 *          identifier in the metadata engine database
+	 */
+	virtual CMdEObject* GetObjectL( const TDesC& aUri, 
+			CMdEObjectDef& aObjectDef ) = 0;
+
+	/**
+	 * Returns the object (object may contain only properties definied in 
+	 * "Object") with the specified URI specified namespace (if namespace is 
+	 * NULL, the default namespace is used).
+	 *
+	 * @param aUri object URI
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  object or NULL, if there is no object with the specified 
+	 *          identifier in the metadata engine database
+	 */
+	virtual CMdEObject* GetObjectL( const TDesC& aUri, 
+			CMdENamespaceDef* aNamespaceDef = NULL) = 0;
+
+	/**
+	 * Returns the object (object will contain all it's properties) with the 
+	 * specified URI specified namespace (if namespace is NULL, the default 
+	 * namespace is used).
+	 *
+	 * @param aUri object URI
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  object or NULL, if there is no object with the specified 
+	 *          identifier in the metadata engine database
+	 */
+	virtual CMdEObject* GetFullObjectL( const TDesC& aUri, 
+			CMdENamespaceDef* aNamespaceDef = NULL) = 0;
+
+	/**
+	 * Opens the object with the specified ID and specified object 
+	 * definition for modifications. The object is locked so that nobody else 
+	 * can open it for modifications. The modifications are committed by 
+	 * calling the <code>CommitObject()</code> method, which releases the lock.
+	 * The modifications can be canceled by calling the 
+	 * <code>CancelObject()</code> method, which also releases the lock.
+	 *
+	 * Example:
+	 *  CMdENamespaceDef& defaultNamespace = iMdeSession->GetDefaultNamespaceDefL();
+     *	CMdEObjectDef& imageDef = defaultNamespace.GetObjectDefL( MdeConstants::Image::KImageObject );
+	 *  CMdEObject* image = iMdESession->OpenObjectL( 17, imageDef );
+	 * 
+	 *  CMdEPropertyDef& lastModDatePropDef = imageDef.GetPropertyDefL(
+     *   		Object::KLastModifiedDateProperty );
+     * 
+     *  CMdEProperty* lastModDateProp = NULL;
+     *  image->Property( lastModDatePropDef, lastModDateProp, 0 );
+     * 
+     *  TTime currenttime( 0 );
+     *	currenttime.UniversalTime();
+     * 
+     *  if ( lastModDateProp )
+     *      {
+     *      lastModDateProp->SetTimeValueL( currenttime );
+     *      }
+     *  else
+     *      {
+     *      image->AddTimePropertyL( lastModDatePropDef, currenttime );
+     *      }
+     *  }
+     *  iMdeSession->CommitObjectL( *image );
+	 *  
+	 * 
+	 * @param aId  object ID
+	 * @param aObjectDef object definition
+	 *
+	 * @return  Object or NULL, if there is no object with the specified 
+     *          identifier in the metadata engine database.
+	 */
+	virtual CMdEObject* OpenObjectL( const TItemId aId, 
+			CMdEObjectDef& aObjectDef ) = 0;
+
+	/**
+	 * Opens the object (object may contain only properties definied in "Object") 
+	 * with the specified ID and specified namespace 
+	 * (if namespace is NULL, the default namespace is used) for modifications.
+	 * The object is locked so that nobody else can open it for modifications.
+	 * The modifications are committed by calling the <code>CommitObject()</code>
+	 * method, which releases the lock. The modifications can be canceled by
+	 * calling the <code>CancelObject()</code> method, which also releases the
+	 * lock.
+	 *
+	 * @param aId  object ID.
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  Object or NULL, if there is no object with the specified 
+     *          identifier in the metadata engine database.
+	 */
+	virtual CMdEObject* OpenObjectL( const TItemId aId, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Opens the object (object will contain all it's properties) 
+	 * with the specified ID and specified namespace 
+	 * (if namespace is NULL, the default namespace is used) for modifications.
+	 * The object is locked so that nobody else can open it for modifications.
+	 * The modifications are committed by calling the <code>CommitObject()</code>
+	 * method, which releases the lock. The modifications can be canceled by
+	 * calling the <code>CancelObject()</code> method, which also releases the
+	 * lock.
+	 *
+	 * @param aId  object ID.
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  Object or NULL, if there is no object with the specified 
+     *          identifier in the metadata engine database.
+	 */
+	virtual CMdEObject* OpenFullObjectL( const TItemId aId, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+
+	/**
+	 * Opens the object with the specified GUID and specified object 
+	 * definition for modifications. The object is locked so that nobody else 
+	 * can open it for modifications. The modifications are committed by 
+	 * calling the <code>CommitObject()</code> method, which releases the lock.
+	 * The modifications can be canceled by calling the 
+	 * <code>CancelObject()</code> method, which also releases the lock.
+	 *
+	 * @param aGuidHigh  GUID high
+	 * @param aGuidLow  GUID low
+	 * @param aObjectDef object definition
+	 *
+	 * @return  Object or NULL, if there is no object with the specified 
+     *          identifier in the metadata engine database.
+	 */
+	virtual CMdEObject* OpenObjectL( 
+			const TInt64 aGuidHigh, const TInt64 aGuidLow, 
+			CMdEObjectDef& aObjectDef ) = 0;
+
+	/**
+	 * Opens the object (object may contain only properties definied in "Object") 
+	 * with the specified GUID and specified namespace 
+	 * (if namespace is NULL, the default namespace is used) for modifications.
+	 * The object is locked so that nobody else can open it for modifications.
+	 * The modifications are committed by calling the <code>CommitObject()</code>
+	 * method, which releases the lock. The modifications can be canceled by
+	 * calling the <code>CancelObject()</code> method, which also releases the
+	 * lock.
+	 *
+	 * @param aGuidHigh  GUID high
+	 * @param aGuidLow  GUID low
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  Object or NULL, if there is no object with the specified 
+     *          identifier in the metadata engine database.
+	 */
+	virtual CMdEObject* OpenObjectL( 
+			const TInt64 aGuidHigh, const TInt64 aGuidLow, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Opens the object (object will contain all it's properties) 
+	 * with the specified GUID and specified namespace 
+	 * (if namespace is NULL, the default namespace is used) for modifications.
+	 * The object is locked so that nobody else can open it for modifications.
+	 * The modifications are committed by calling the <code>CommitObject()</code>
+	 * method, which releases the lock. The modifications can be canceled by
+	 * calling the <code>CancelObject()</code> method, which also releases the
+	 * lock.
+	 *
+	 * @param aGuidHigh  GUID high
+	 * @param aGuidLow  GUID low
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  Object or NULL, if there is no object with the specified 
+     *          identifier in the metadata engine database.
+	 */
+	virtual CMdEObject* OpenFullObjectL( 
+			const TInt64 aGuidHigh, const TInt64 aGuidLow, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+
+	/**
+	 * Opens the object with the specified URI for modifications and specified 
+	 * object definition. The object is locked so that nobody else can open it 
+	 * for modifications. The modifications are committed by calling the 
+	 * <code>CommitObject()</code> method, which releases the lock. The 
+	 * modifications can be canceled by calling the <code>CancelObject()</code> 
+	 * method, which also releases the lock.
+	 *
+	 * @param aUri  object URI
+	 * @param aObjectDef object definition
+	 *
+	 * @return  Object or NULL, if there is no object with the specified 
+     *          identifier in the metadata engine database.
+	 */
+	virtual CMdEObject* OpenObjectL( const TDesC& aUri, 
+			CMdEObjectDef& aObjectDef ) = 0;
+
+	/**
+	 * Opens the object (object may contain only properties definied in "Object") 
+	 * with the specified ID and specified namespace 
+	 * (if namespace is NULL, the default namespace is used) for modifications.
+	 * The object is locked so that nobody else can open it for modifications.
+	 * The modifications are committed by calling the <code>CommitObject()</code>
+	 * method, which releases the lock. The modifications can be canceled by
+	 * calling the <code>CancelObject()</code> method, which also releases the
+	 * lock.
+	 *
+	 * @param aUri  Object URI.
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  Object or NULL, if there is no object with the specified 
+     *          identifier in the metadata engine database.
+	 */
+	virtual CMdEObject* OpenObjectL( const TDesC& aUri, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Opens the object (object will contain all it's properties) 
+	 * with the specified ID and specified namespace 
+	 * (if namespace is NULL, the default namespace is used) for modifications.
+	 * The object is locked so that nobody else can open it for modifications.
+	 * The modifications are committed by calling the <code>CommitObject()</code>
+	 * method, which releases the lock. The modifications can be canceled by
+	 * calling the <code>CancelObject()</code> method, which also releases the
+	 * lock.
+	 *
+	 * @param aUri  Object URI.
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  Object or NULL, if there is no object with the specified 
+     *          identifier in the metadata engine database.
+	 */
+	virtual CMdEObject* OpenFullObjectL( const TDesC& aUri, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Gets metadata object id, definition and some flags by URI. Does not return the whole object.
+	 * 
+	 * @param aObject on return contains information about the metadata object
+	 * @param aUri metadata object URI
+	 * @param aNamespaceDef namespace definition. If namespace is NULL then the default namespace is used.
+	 */
+	virtual void CheckObjectL( TMdEObject& aObject, const TDesC& aUri, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Gets metadata object id, definition and some flags by id. Does not return the whole object.
+	 * 
+	 * @param aObject on return contains information about the metadata object
+	 * @param aId metadata object id
+	 * @param aNamespaceDef namespace definition. If namespace is NULL then the default namespace is used.
+	 */
+	virtual void CheckObjectL( TMdEObject& aObject, TItemId aId, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Gets an array of TMdEObject objects that contain metadata object ids, definitions and 
+	 * some flags by object ids. Does not return whole objects.
+	 * 
+	 * @param aObjects on return contains an array of objects containing information about metadata objects
+	 * @param aIds array of metadata object ids
+	 * @param aNamespaceDef namespace definition. If namespace is NULL then the default namespace is used.
+	 */
+	virtual void CheckObjectL( RArray<TMdEObject>& aObjects, 
+			const RArray<TItemId>& aIds, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+	
+	/**
+     * Commits the modifications made to the object to the database
+	 * and releases the modification lock.
+     * 
+	 * @param aObject  Object.
+     */
+    virtual void CommitObjectL(CMdEObject& aObject) = 0;
+
+	/**
+     * Commits the modifications made to objects to the database
+	 * and releases the modification locks.
+     * 
+	 * @param aObject  Object.
+     */
+    virtual void CommitObjectsL(RPointerArray<CMdEObject>& aObjects) = 0;
+
+    /**
+     * Cancels the modifications made to the object and releases the
+	 * modification lock.
+     * 
+	 * @param aObject  Object.
+     */
+    virtual TItemId CancelObjectL(CMdEObject& aObject) = 0;
+
+
+	/* Methods for managing relations. */
+
+	/**
+	 * Returns the relation with the specified ID and specified namespace 
+	 * (if namespace is NULL, the default namespace is used).
+	 * 
+	 * Note that the ownership of the returned relation is passed to the 
+	 * caller of the method (that is, the caller is responsible for deleting 
+	 * the relation).
+	 *
+	 * @param aId  relation ID
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  relation or NULL, if there is no relation with the specified ID
+	 *          in the metadata engine database
+	 */
+	virtual CMdERelation* GetRelationL(TItemId aId, 
+			CMdENamespaceDef* aNamespacedef = NULL) = 0;
+
+	/**
+	 * Constructs a new empty relation. Note that the relation is not inserted 
+	 * in the database. The ownership of the new relation is passed to the 
+	 * caller (that is, the caller is responsible for deleting the relation).
+	 * 
+	 * Example:
+     *	 CMdERelationDef& relationDef = namespaceDef.GetRelationDefL( MdeConstants::Relations::KContains );
+     *
+     *	 CMdERelation* relation = iMdeSession->NewRelationLC( relationDef, albumObject->Id(), audioObject->Id() );
+     *	 iMdeSession->AddRelationL( *relation );
+	 *
+	 * @param aDef  definition of the new relation
+	 * @param aLeftObjectId id of the left side of the relation
+	 * @param aRightObjectId id of the right side of the relation
+	 * @param aParameter the relation parameter
+	 *
+	 * @return  new relation
+	 */
+	virtual CMdERelation* NewRelationLC(CMdERelationDef& aDef, 
+			TItemId aLeftObjectId, TItemId aRightObjectId, 
+			TInt32 aParameter = 0) = 0;
+
+	/**
+	 * Constructs a new empty relation. Note that the relation is not inserted 
+	 * in the database. The ownership of the new relation is passed to the 
+	 * caller (that is, the caller is responsible for deleting the relation).
+	 *
+	 * Example:
+     *	 CMdERelationDef& relationDef = namespaceDef.GetRelationDefL( MdeConstants::Relations::KContains );
+     *
+     *	 CMdERelation* relation = iMdeSession->NewRelationL( relationDef, albumObject->Id(), audioObject->Id() );
+     *	 iMdeSession->AddRelationL( *relation );
+	 * 
+	 * @param aDef  definition of the new relation
+	 * @param aLeftObjectId id of the left side of the relation
+	 * @param aRightObjectId id of the right side of the relation
+	 * @param aParameter the relation parameter
+	 *
+	 * @return  new relation
+	 */
+	virtual CMdERelation* NewRelationL(CMdERelationDef& aDef, 
+			TItemId aLeftObjectId, TItemId aRightObjectId, 
+			TInt32 aParameter = 0) = 0;
+
+	/**
+	 * Adds a new relation to the metadata engine database.
+	 *
+	 * @param relation
+	 *
+	 * @return  identifier of the new relation
+	 */
+	virtual TItemId AddRelationL( CMdERelation& aRelation ) = 0;
+
+	/**
+	 * Commits changes made to the relation to the metadata engine database.
+     *
+     * @param relation
+	 *
+	 * @return  identifier of the new relation
+	 */
+	virtual TItemId UpdateRelationL( CMdERelation& aRelation ) = 0;
+
+	/**
+	 * Removes the relation with the specified identifier and specified 
+	 * namespace (if namespace is NULL, the default namespace is used)
+	 * from the metadata engine database.
+	 *
+	 * @param aId   ID of the relation to remove.
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  relation ID or KNoId, if there is no relation with the 
+	 *          specified ID in the metadata engine database
+	 */
+	virtual TItemId RemoveRelationL( TItemId aId, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+	
+	/**
+	 * Removes multiple relations with the specified IDs and specified 
+	 * namespace (if namespace is NULL, the default namespace is used)
+	 * from the metadata engine database.
+	 *
+	 * @param aId IDs of relations to remove.
+	 * @param aSuccessful Successfully removed IDs of relations (if removing 
+	 *                    has failed KNoId is added).
+	 * @param aNamespaceDef namespace
+	 */
+	virtual TInt RemoveRelationsL( 
+			const RArray<TItemId>& aId, RArray<TItemId>& aSuccessful, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/**
+	 * Removes multiple relations asynchronous with the specified IDs and 
+	 * specified namespace (if namespace is NULL, the default namespace is 
+	 * used) from the metadata engine database. Returned serialized list of 
+	 * item IDs must be deserialized with DeserializeIdsL method.
+	 *
+	 * @param aId IDs of relations to remove.
+     * @param aStatus returns the result code after the asynchronous call 
+     *                completes.
+     * @param aSerializedRelationIds returned serialized list of relation IDs
+	 * @param aNamespaceDef namespace
+	 */
+	virtual void RemoveRelationsAsyncL( 
+			const RArray<TItemId>& aId, TRequestStatus& aStatus, 
+			RMdEDataBuffer& aSerializedRelationIds, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+	/* Methods for managing events. */
+
+	/**
+	 * Constructs a new empty event. Note that the event is not inserted in the
+	 * database. The ownership of the new event is passed to the caller (that 
+	 * is, the caller is responsible for deleting the event).
+	 *
+	 * Example:
+	 *   CMdEEventDef* eventDef = &iDefaultNamespace->GetEventDefL( Events::KCreated );
+	 *   CMdEEvent* event = iMdeSession->NewEventLC( *eventDef, objectId, time );
+	 * 
+	 * @param aDef  definition of the new event
+	 * @param aObjectId the target object id
+	 * @param aTime time of the event
+	 * @param aSource source of the event
+	 * @param aParticipant participant of the event
+	 *
+	 * @return  new event
+	 */
+	virtual CMdEEvent* NewEventLC(CMdEEventDef& aDef, 
+			TItemId aObjectId, TTime aTime, 
+			const TDesC* aSource = NULL, const TDesC* aParticipant = NULL) = 0;
+
+	/**
+	 * Constructs a new empty event. Note that the event is not inserted in the
+	 * database. The ownership of the new event is passed to the caller (that 
+	 * is, the caller is responsible for deleting the event).
+	 *
+	 * Example:
+	 *   CMdEEventDef* eventDef = &iDefaultNamespace->GetEventDefL( Events::KCreated );
+	 *   CMdEEvent* event = iMdeSession->NewEventL( *eventDef, objectId, time );
+	 * 
+	 * @param aDef  definition of the new event
+	 * @param aObjectId the target object id
+	 * @param aTime time of the event
+	 * @param aSource source of the event
+	 * @param aParticipant participant of the event
+	 *
+	 * @return  new event
+	 */
+	virtual CMdEEvent* NewEventL(CMdEEventDef& aDef, 
+			TItemId aObjectId, TTime aTime, 
+			const TDesC* aSource = NULL, const TDesC* aParticipant = NULL) = 0;
+
+	/**
+	 * Returns the event with the specified identifier and specified namespace 
+	 * (if namespace is NULL, the default namespace is used).
+	 * Note that the ownership of the returned event is passed to the caller of
+	 * the method (that is, the caller is responsible for deleting the event).
+	 *
+	 * @param aId  Identifier.
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  Event or NULL, if there is no event with the specified 
+	 *          identifier in the metadata engine database.
+	 */
+	virtual CMdEEvent* GetEventL(TItemId aId, 
+			CMdENamespaceDef* aNamespaceDef = NULL) = 0;
+
+	/**
+	 * Adds a new event to the metadata engine database.
+	 *
+	 * @param event
+	 *
+	 * @return  Identifier of the new event.
+	 */
+	virtual TItemId AddEventL( CMdEEvent& aEvent ) = 0;
+
+	/**
+	 * Removes the event with the specified identifier and specified namespace 
+	 * (if namespace is NULL, the default namespace is used) from the metadata 
+	 * engine database.
+	 *
+	 * @param aId   ID of the event to remove.
+	 * @param aNamespaceDef namespace
+	 *
+	 * @return  event ID or KNoId, if there is no event with the specified ID
+	 *          in the metadata engine database
+	 */
+	virtual TItemId RemoveEventL( TItemId aId, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+	
+	/**
+	 * Removes multiple events with the specified IDs and specified 
+	 * namespace (if namespace is NULL, the default namespace is used)
+	 * from the metadata engine database.
+	 *
+	 * @param aId IDs of events to remove.
+	 * @param aSuccessful Successfully removed IDs of events (if removing has 
+	 *                    failed KNoId is added).
+	 * @param aNamespaceDef namespace
+	 */
+	virtual TInt RemoveEventsL(
+			const RArray<TItemId>& aId, RArray<TItemId>& aSuccessful, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+	
+	/**
+	 * Removes multiple events asynchronous with the specified IDs and 
+	 * specified namespace (if namespace is NULL, the default namespace is 
+	 * used) from the metadata engine database. Returned serialized list of 
+	 * item IDs must be deserialized with DeserializeIdsL method.
+	 *
+	 * @param aId IDs of events to remove.
+     * @param aStatus returns the result code after the asynchronous call 
+     *                completes.
+     * @param aSerializedEventIds returned serialized list of event IDs
+	 * @param aNamespaceDef namespace
+	 */
+	virtual void RemoveEventsAsyncL(
+			const RArray<TItemId>& aId, TRequestStatus& aStatus, 
+			RMdEDataBuffer& aSerializedEventIds, 
+			CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+
+	/* Methods for searching objects, relations, and events. */
+
+    /**
+	 * Creates a new object query.
+	 * 
+	 * Note that the ownership of the returned query is passed to the caller of
+	 * the method (that is, the caller is responsible for deleting the query).
+	 *
+	 * @param aNamespaceDef namespace where query will be run
+	 * @param aObjectDef object definition which defines objects which will be 
+	 *                   queried
+	 * @param aObserver observer which callback methods will be called
+	 *
+	 * @return  New object query.
+     */
+    virtual CMdEObjectQuery* NewObjectQueryL(CMdENamespaceDef& aNamespaceDef, 
+    		CMdEObjectDef& aObjectDef, MMdEQueryObserver* aObserver = 0) = 0;
+
+    /**
+	 * Creates a new object query.
+	 * 
+	 * Note that the ownership of the returned query is passed to the caller of
+	 * the method (that is, the caller is responsible for deleting the query).
+	 *
+	 * @param aObjectDef Object definition which defines the parent object.
+	 * @param aObjectDefs Object definitions which defines objects which will 
+	 *                    be queried. Ownership of aObjectDefs will change to 
+	 *                    query.
+	 * @param aObserver Observer which callback methods will be called.
+	 *
+	 * @return  New object query.
+     */
+    virtual CMdEObjectQuery* NewObjectQueryL(
+    		CMdEObjectDef& aObjectDef, 
+    		RPointerArray<CMdEObjectDef>* aObjectDefs, 
+    		MMdEQueryObserver* aObserver = 0) = 0;
+
+    /**
+	 * Creates a new relation query.
+	 * 
+	 * Note that the ownership of the returned query is passed to the caller of
+	 * the method (that is, the caller is responsible for deleting the query).
+	 *
+	 * @param aNamespaceDef namespace where query will be run
+	 * @param aObserver observer which callback methods will be called
+	 *
+     * @return  New relation query.
+     */
+    virtual CMdERelationQuery* NewRelationQueryL(
+    		CMdENamespaceDef& aNamespaceDef, 
+    		MMdEQueryObserver* aObserver = 0) = 0;
+
+    /**
+	 * Creates a new event query.
+	 * 
+	 * Note that the ownership of the returned query is passed to the caller of
+	 * the method (that is, the caller is responsible for deleting the query).
+	 *
+	 * @param aNamespaceDef namespace where query will be run
+	 * @param aObserver observer which callback methods will be called
+	 *
+     * @return  New event query.
+     */
+    virtual CMdEEventQuery* NewEventQueryL(CMdENamespaceDef& aNamespaceDef, 
+    		MMdEQueryObserver* aObserver = 0) = 0;
+
+
+	/* Methods for managing observers. */
+
+	/**
+	 * Adds a new schema observer to the session. No duplicate
+	 * observers are allowed.
+	 *
+	 * @param aObserver  observer
+	 */
+	virtual void AddSchemaObserverL(MMdESchemaObserver& aObserver) = 0;
+
+	/**
+	 * Removes the specified schema observer from the session.
+	 *
+	 * @param aObserver  observer
+	 */
+	virtual void RemoveSchemaObserverL(MMdESchemaObserver& aObserver) = 0;
+
+	/**
+	 * Adds a new object observer to the session. No duplicate observers are 
+     * allowed.
+     *
+     * The following restrictions are placed on the condition nodes:
+     * - Only CMdEObjectCondition and CMdEPropertyCondition nodes can be
+     *   used. CMdERangePropertyConditions are not allowed.
+     * - No nested logic conditions are allowed.
+	 *
+	 * @param aObserver   Observer.
+	 * @param aCondition  Condition that the objects, about which the observer
+	 *                    wants to receive notifications, must fulfill or NULL,
+	 *                    to receive notifications of all objects.
+     *                    Ownership of the condition is transferred to the
+     *                    session.
+     * @param aNotificationType what event type (add, modify, remove) should
+     *                          be notified to client
+     * @param aNamespaceDef specified namespace (if namespace is NULL, the 
+     *                      default namespace is used)
+     * 
+     * @leave KErrAlreadyExists if the same observer has already been added
+	 */
+	virtual void AddObjectObserverL(MMdEObjectObserver& aObserver,
+			CMdELogicCondition* aCondition = NULL, 
+			TUint32 aNotificationType = ENotifyAdd | ENotifyModify | ENotifyRemove,
+			CMdENamespaceDef* aNamespaceDef = NULL) = 0;
+
+	/**
+	 * Removes the specified object observer from the session.
+	 *
+	 * @param aObserver  observer
+     * @param aNamespaceDef specified namespace (if namespace is NULL, the 
+     *                      default namespace is used)
+	 */
+	virtual void RemoveObjectObserverL(MMdEObjectObserver& aObserver, 
+			CMdENamespaceDef* aNamespaceDef = NULL) = 0;
+
+	/**
+	 * Adds a new object present observer to the session. No duplicate 
+	 * observers are allowed.
+     *
+	 * @param aObserver   Observer
+	 * 
+     * @leave KErrAlreadyExists if the same observer has already been added
+	 */
+	virtual void AddObjectPresentObserverL(
+			MMdEObjectPresentObserver& aObserver) = 0;
+
+	/**
+	 * Removes the specified object present observer from the session.
+	 *
+	 * @param aObserver  observer
+	 */
+	virtual void RemoveObjectPresentObserverL(
+			MMdEObjectPresentObserver& aObserver)= 0;
+
+	/**
+	 * Adds a new relation observer to the session. No duplicate observers 
+     * are allowed.
+	 *
+     * The following restrictions are placed on the condition nodes:
+     * - Only CMdERelationCondition nodes are allowed.
+     * - No nested logic conditions are allowed.
+     *
+	 * @param aObserver   Observer.
+	 * @param aCondition  Condition that the relations, about which the observer
+	 *                    wants to receive notifications, must fulfill
+	 *                    or NULL, to receive notifications of all relations.
+     *                    Ownership of the condition is transferred to the
+     *                    session.
+     * @param aNotificationType what event type (add, modify, remove) should
+     *                          be notified to client
+     * @param aNamespaceDef specified namespace (if namespace is NULL, the 
+     *                      default namespace is used)
+     * 
+     * @leave KErrAlreadyExists if the same observer has already been added
+	 */
+	virtual void AddRelationObserverL(MMdERelationObserver& aObserver,
+			CMdECondition* aCondition = NULL, 
+			TUint32 aNotificationType = ENotifyAdd | ENotifyModify | ENotifyRemove,
+			CMdENamespaceDef* aNamespaceDef = NULL)= 0;
+	/**
+	 * Removes the specified relation observer from the session.
+	 *
+	 * @param aObserver  Observer.
+     * @param aNamespaceDef specified namespace (if namespace is NULL, the 
+     *                      default namespace is used)
+	 */
+	virtual void RemoveRelationObserverL(MMdERelationObserver& aObserver, 
+			CMdENamespaceDef* aNamespaceDef = NULL) = 0;
+
+	/**
+	 * Adds a new relation item observer to the session.
+	 * No duplicate observers are allowed.
+	 *
+     * The following restrictions are placed on the condition nodes:
+     * - Only CMdERelationCondition nodes are allowed.
+     * - No nested logic conditions are allowed.
+     *
+	 * @param aObserver   Observer.
+	 * @param aCondition  Condition that the relations, about which the observer
+	 *                    wants to receive notifications, must fulfill
+	 *                    or NULL, to receive notifications of all relations.
+     *                    Ownership of the condition is transferred to the
+     *                    session.
+     * @param aNotificationType what event type (add, modify, remove) should
+     *                          be notified to client
+     * @param aNamespaceDef specified namespace (if namespace is NULL, the 
+     *                      default namespace is used)
+     * 
+     * @leave KErrAlreadyExists if the same observer has already been added
+	 */
+	virtual void AddRelationItemObserverL(MMdERelationItemObserver& aObserver,
+			CMdECondition* aCondition = NULL, 
+			TUint32 aNotificationType = /*ENotifyAdd | ENotifyModify |*/ ENotifyRemove,
+			CMdENamespaceDef* aNamespaceDef = NULL)= 0;
+	/**
+	 * Removes the specified relation observer from the session.
+	 *
+	 * @param aObserver  Observer.
+     * @param aNamespaceDef specified namespace (if namespace is NULL, the 
+     *                      default namespace is used)
+	 */
+	virtual void RemoveRelationItemObserverL(MMdERelationItemObserver& aObserver, 
+			CMdENamespaceDef* aNamespaceDef = NULL) = 0;
+	
+	/**
+	 * Adds a new realation present observer to the session. No duplicate observers are 
+     * allowed.
+     *
+	 * @param aObserver   Observer.
+	 * 
+     * @leave KErrAlreadyExists if the same observer has already been added
+	 */
+	virtual void AddRelationPresentObserverL(
+			MMdERelationPresentObserver& aObserver) = 0;
+
+	/**
+	 * Removes the specified relation present observer from the session.
+	 *
+	 * @param aObserver  observer
+	 */
+	virtual void RemoveRelationPresentObserverL(
+			MMdERelationPresentObserver& aObserver)= 0;
+
+	/**
+	 * Adds a new event observer to the session. No duplicate observers 
+     * are allowed.
+     *
+     * The following restrictions are placed on the condition nodes:
+     * - Only CMdEEventCondition nodes are allowed.
+     * - No nested logic conditions are allowed.
+	 *
+	 * @param aObserver   Observer.
+	 * @param aCondition  Condition that the events, about which the observer
+	 *                    wants to receive notifications, must fulfill
+	 *                    or NULL, to receive notifications of all events.
+     * @param aNotificationType what event type (add or remove) should
+     *                          be notified to client
+     * @param aNamespaceDef specified namespace (if namespace is NULL, the 
+     *                      default namespace is used)
+     * 
+     * @leave KErrAlreadyExists if the same observer has already been added
+	 */
+	virtual void AddEventObserverL(MMdEEventObserver& aObserver,
+			CMdECondition* aCondition = NULL, 
+			TUint32 aNotificationType = ENotifyAdd | ENotifyRemove,
+			CMdENamespaceDef* aNamespaceDef = NULL) = 0;
+
+	/**
+	 * Removes the specified event observer from the session.
+	 *
+	 * @param aObserver  Observer.
+     * @param aNamespaceDef specified namespace (if namespace is NULL, the 
+     *                      default namespace is used)
+	 */
+	virtual void RemoveEventObserverL(MMdEEventObserver& aObserver, 
+			CMdENamespaceDef* aNamespaceDef = NULL) = 0;
+
+
+    /* Methods for import/export */
+
+	/**
+	 * Imports schemadata from file to default database.
+	 *
+	 * @param aFileName  filename where the schemadata to import is.
+	 */
+	virtual void ImportSchemaL( const TDesC& aFileName ) = 0;
+
+	/**
+	 * Imports metadata from file to default database.
+	 *
+	 * @param aFileName  filename where the metadata to import is.
+	 * @return The number of failed imports
+	 */
+	virtual TInt ImportMetadataL( const TDesC& aFileName ) = 0;
+
+	/**
+	 * Imports metadata asynchronously from file to default database.
+	 *
+	 * @param aFileName Filename where the metadata to import is.
+	 * @param aResult The number of failed imports and possible error code.
+	 * @param aStatus Returned status of method call.
+	 */
+	virtual void ImportMetadata( const TDesC& aFileName, 
+			TPckgBuf<TInt>& aResult, TRequestStatus& aStatus ) = 0;
+
+	/**
+	 * Exports metadata to file.
+	 *
+	 * @param aFileName  filename where the metadata is to be exported.
+     * @param aNamespaceDef specified namespace (if namespace is NULL, the 
+     *                      default namespace is used), ownership doesn't 
+     *                      change
+     * @param aObjectDefs object types to export (if NULL all objects are 
+     *                    exported), ownership doesn't change
+     * @param aRelationDefs relation types to export (if NULL all relations 
+     *                      are exported), ownership doesn't change
+     * @param aEventDefs event types to export (if NULL all events are 
+     *                   exported), ownership doesn't change
+	 */
+	virtual void ExportMetadataL( const TDesC& aFileName, 
+			const CMdENamespaceDef* aNamespaceDef = NULL, 
+	        const RPointerArray<CMdEObjectDef>* aObjectDefs = NULL, 
+	        const RPointerArray<CMdERelationDef>* aRelationDefs = NULL, 
+            const RPointerArray<CMdEEventDef>* aEventDefs = NULL ) = 0;
+
+	/**
+	 * Exports metadata asynchronously to file.
+	 *
+	 * @param aFileName Filename where the metadata is to be exported.
+	 * @param aStatus Returns the result code after the asynchronous call 
+     *                completes.
+	 * @param aBuffer Serialized buffer of export types, must be valid until 
+	 *                aStatus is completed and can be closed after that.
+     * @param aNamespaceDef Specified namespace (if namespace is NULL, the 
+     *                      default namespace is used), ownership doesn't 
+     *                      change.
+     * @param aObjectDefs Object types to export (if NULL all objects are 
+     *                    exported), ownership doesn't change.
+     * @param aRelationDefs Relation types to export (if NULL all relations 
+     *                      are exported), ownership doesn't change.
+     * @param aEventDefs Event types to export (if NULL all events are 
+     *                   exported), ownership doesn't change.
+	 */
+	virtual void ExportMetadataL( const TDesC& aFileName, 
+			TRequestStatus& aStatus, RMdEDataBuffer& aBuffer, 
+        	const CMdENamespaceDef* aNamespaceDef = NULL, 
+	        const RPointerArray<CMdEObjectDef>* aObjectDefs = NULL, 
+            const RPointerArray<CMdERelationDef>* aRelationDefs = NULL, 
+            const RPointerArray<CMdEEventDef>* aEventDefs = NULL ) = 0;
+	/**
+	 * Load whole schema from server side.
+	 */
+	virtual void LoadSchemaL() = 0;
+
+	/**
+	 * Get engine session reference.
+	 */
+    virtual RMdEEngineSession& EngineSession() = 0;
+
+	/**
+	 * Get schema version's major and minor version.
+	 *
+	 * @param aMajorVersion returned major version
+	 * @param aMinorVersion returned minor version
+	 */
+	virtual void GetSchemaVersionL(
+			TInt& aMajorVersion, TInt& aMinorVersion) = 0;
+
+	/**
+	 * Set object to "present" state by GUID.
+	 *
+	 * @param aGuidHigh Guid's high part
+	 * @param aGuidLow Guid's low part
+	 *
+	 * @leave KErrNotFound MdE can't find object in "not present" state 
+	 *                     with matching GUID
+	 */
+	virtual void SetObjectToPresentByGuidL( 
+			const TInt64& aGuidHigh, const TInt64& aGuidLow ) = 0;
+	
+protected:
+
+	/* Constructors. */
+
+	/**
+	 * Constructor.
+	 */
+	CMdESession();
+
+	/**
+	 * Second-phase constructor.
+	 */
+	void SessionConstruct();
+	};
+
+// includes only for client more convinient usage
+#include <mdeitem.h>
+#include <mdenamespacedef.h>
+#include <mdepropertydef.h>
+#include <mdeobjectdef.h>
+#include <mderelationdef.h>
+#include <mdeeventdef.h>
+#include <mdeproperty.h>
+#include <mdeobject.h>
+#include <mderelation.h>
+#include <mdeevent.h>
+#include <mdedatabuffer.h>
+
+#endif  // __MDESESSION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdetextproperty.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CMdETextProperty's compatible wrapper to CMdEProperty
+*
+*/
+
+
+#ifndef __MDETEXTPROPERTY_H__
+#define __MDETEXTPROPERTY_H__
+
+#include <mdeproperty.h>
+
+/**
+ * Text property compatibility wrapper to property.
+ */
+NONSHARABLE_CLASS(CMdETextProperty) : public CMdEProperty
+	{
+public:
+	/**
+	 * Returns the text value of the property.
+	 *
+	 * @return  value
+	 */
+	const TDesC& Value() const;
+
+	/**
+	 * Sets the text value of the property.
+	 *
+	 * @param aValue       New value.
+	 */
+	void SetValueL(const TDesC& aValue);
+	};
+
+#include <mdetextproperty.inl>
+	
+#endif  // __MDETEXTPROPERTY_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdetextproperty.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CMdETextProperty's compatibility wrapper to CMdEProperty
+*
+*/
+
+_LIT( KCMdETextPropertyGetValuePanic, "CMdETextProperty::Value" );
+_LIT( KCMdETextPropertySetValuePanic, "CMdETextProperty::SetValueL" );
+
+// ---------------------------------------------------------------------------
+// Value
+// ---------------------------------------------------------------------------
+//
+inline const TDesC& CMdETextProperty::Value() const
+	{
+	TDesC* des = NULL;
+
+	TRAPD( err, des = CONST_CAST( TDesC*, &TextValueL() ) );
+	if( err != KErrNone )
+		{
+#ifdef _DEBUG
+		User::Panic( KCMdETextPropertyGetValuePanic, KErrNotSupported );
+#endif
+		return KNullDesC;
+		}
+	return *des;
+	}
+
+// ---------------------------------------------------------------------------
+// SetValueL
+// ---------------------------------------------------------------------------
+//
+inline void CMdETextProperty::SetValueL(const TDesC& aValue)
+	{
+	TRAPD( err, SetTextValueL( aValue ) );
+	if( err != KErrNone )
+		{
+#ifdef _DEBUG		
+		User::Panic( KCMdETextPropertySetValuePanic, KErrNotSupported );
+#endif
+		}
+	}
+	
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdetextpropertycondition.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,140 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef __MDETEXTPROPERTYCONDITION_H__
+#define __MDETEXTPROPERTYCONDITION_H__
+
+
+#include <mdepropertycondition.h>
+
+
+/* Forward declarations. */
+class CMdEPropertyDef;
+
+
+/**
+ * Instances of CMdETextPropertyCondition are associated with a specific 
+ * property definition.
+ */
+NONSHARABLE_CLASS(CMdETextPropertyCondition) : public CMdEPropertyCondition
+	{
+public:
+
+	/* Constructors and destructor. */
+
+    /** 
+     * Constructs a new text property condition node.
+     *
+     * @param aPropertyDef    Property definition.
+     * @param aCompareMethod  Text comparison method.
+     * @param aText           Text to look for.
+     */
+    static CMdETextPropertyCondition* NewL(const CMdEPropertyDef& aPropertyDef,
+                                           TTextPropertyConditionCompareMethod aCompareMethod,
+                                           const TDesC& aText);
+
+    /** 
+     * Constructs a new text property condition node, leaving it on the 
+     * cleanup stack.
+     *
+     * @param aPropertyDef    Property definition.
+     * @param aCompareMethod  Text comparison method.
+     * @param aText           Text to look for.
+     */
+    static CMdETextPropertyCondition* NewLC(const CMdEPropertyDef& aPropertyDef,
+                                            TTextPropertyConditionCompareMethod aCompareMethod,
+                                            const TDesC& aText);
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdETextPropertyCondition();
+
+
+	/* Methods. */
+    
+    /**
+     * Returns the text of the condition.
+     *
+     * @return  Text descriptor.
+     */
+    const TDesC& Text() const;
+
+    /**
+     * Returns the comparison method of the condition.
+     *
+     * @return  Comparison method.
+     */
+    TTextPropertyConditionCompareMethod CompareMethod() const;
+
+	/**
+     * Get possible query's internal optimization flags from condition.
+     *
+     * @param aFlaga query's internal optimization flags
+     * @return last level internal optimization flags
+     */
+    TUint32 InternalQueryOptimizationFlags(TUint32& aFlags);
+    
+    /**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+    TUint32 RequiredBufferSize() const;
+   
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling) and return new position of serialized buffer.
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    void SerializeL(CMdCSerializationBuffer& aBuffer,
+    		TMdCOffset& aFreespaceOffset) const;
+   
+protected:
+
+   	/**
+	 * Constructor. 
+	 *
+	 * @param aType  type of the condition node
+	 */
+	CMdETextPropertyCondition(const CMdEPropertyDef& aPropertyDef,
+                              TTextPropertyConditionCompareMethod aCompareMethod);
+
+
+    /**
+     * Second-phase constuctor. 
+     */
+    void ConstructL(const TDesC& aText);
+
+
+private:
+
+    /* Private methods. */
+
+
+private:
+
+    /** The comparison method used when searching for the string. */
+    TTextPropertyConditionCompareMethod iCompareMethod;
+
+    /** The string to look for. */
+    HBufC* iText;
+    };
+
+#endif  // __MDETEXTPROPERTYCONDITION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/inc/mdeversioncenrepkey.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+#ifndef MDEVERSIONCENREPKEY_H
+#define MDEVERSIONCENREPKEY_H
+
+const TUid KMetadataEngineRepoUid = { 0x200009F3 };
+
+const TUint32 KMdEVersionMajorKey              = 0x1;
+const TUint32 KMdEVersionMinorKey              = 0x2;
+
+#endif /*MDEVERSIONCENREPKEY_H*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/metadata_engine_api.metaxml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,15 @@
+<?xml version="1.0" ?>
+<api id="6e6285c8b5a7d8b751d443b84aa1973a" dataversion="2.0">
+<name>metadata_engine_api</name>
+<description>metadata engine api</description>
+<type>c++</type>
+<collection>metadataengine</collection>
+<libs><lib name="mdccommon.lib"/>
+<lib name="mdeclient.lib"/>
+</libs>
+<release category="platform" sinceversion=""/>
+<attributes>
+<htmldocprovided>no</htmldocprovided>
+<adaptation>no</adaptation>
+</attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/Bmarm/MdETestScripterU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	LibEntryL__FR13CTestModuleIf @ 1 NONAME R3UNUSED ; LibEntryL(CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/Bwins/MdETestScripterU.DEF	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?LibEntryL@@YAPAVCScriptBase@@AAVCTestModuleIf@@@Z @ 1 NONAME ; class CScriptBase * LibEntryL(class CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/EABI/MdETestScripterU.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	_Z9LibEntryLR13CTestModuleIf @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/conf/MdETestScripter.cfg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3113 @@
+#
+# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:  Metadata Engine API tests
+#
+
+// ---------------------------------------------------------------------------
+// Metadata Engine API test cases
+// ---------------------------------------------------------------------------
+
+// These should be run in sequential mode if several cases are run at the same
+// time! 
+
+[Define]
+KErrNotFound -1
+KErrGeneral -2
+KErrNotSupported -5
+KErrArgument -6
+KErrCorrupt -20
+KErrAccessDenied -21
+KErrLocked 	-22
+KErrAlreadyExists -11
+
+KErrIncorrectType = -36201
+
+KLast -1;
+
+KById 0
+KByUri 1
+KByGuid 2
+KByIds 3
+KByDef 4
+KByIndex 5
+
+KAsync 0
+KSync 1
+
+KL 0
+KLC 1
+
+EFalse 0
+ETrue 1
+
+ESession 0
+EObjectDef 1
+ERelationDef 2
+EPropertyDef 3
+EEventDef 4
+ENamespaceDef 5
+EObject 6
+ERelation 7
+EProperty 8
+EEvent 9
+
+ENotifyAdd 1 
+ENotifyModify 2
+ENotifyRemove 4
+
+ESortDescending 0
+ESortAscending 1
+
+// enum TOrderRuleType
+EOrderRuleTypeItemID 1
+EOrderRuleTypeObjectURI 2
+EOrderRuleTypeObjectDef 3
+EOrderRuleTypeProperty 4
+EOrderRuleTypeCreationTime 5
+EOrderRuleTypeUsageCount 6
+EOrderRuleTypeSourceURI 7
+EOrderRuleTypeParticipantURI 8
+EOrderRuleTypeTargetObjectID 9
+EOrderRuleTypeEventDef 10
+EOrderRuleTypeParameterValue 11
+EOrderRuleTypeLeftObjectID 12
+EOrderRuleTypeRightObjectID 13
+EOrderRuleTypeRelationDef 14
+
+KNoNegate 0
+KNegate 1
+
+EOther      0
+ECamera     1
+EDownloaded 2
+ESideLoaded 3
+ERecorded   4
+
+ELogicConditionOperatorAnd 1
+ELogicConditionOperatorOr 2
+
+EAlbumUser            0
+EAlbumUserPredefined  1
+EAlbumSystemFavourite 2
+
+[Enddefine]
+
+[Test]
+title Observer 1: Add*ObserverL, Remove*ObserverL
+create MdETestScripter test
+waittestclass test
+test AddSchemaObserverL
+test RemoveSchemaObserverL
+allownextresult KErrNotFound
+test RemoveSchemaObserverL
+test AddObjectObserverL
+test RemoveObjectObserverL
+allownextresult KErrNotFound
+test RemoveObjectObserverL
+test AddObjectPresentObserverL
+test RemoveObjectPresentObserverL
+allownextresult KErrNotFound
+test RemoveObjectPresentObserverL
+test AddRelationObserverL
+test RemoveRelationObserverL
+allownextresult KErrNotFound
+test RemoveRelationObserverL
+test AddRelationItemObserverL
+test RemoveRelationItemObserverL
+allownextresult KErrNotFound
+test RemoveRelationItemObserverL
+test AddRelationPresentObserverL
+test RemoveRelationPresentObserverL
+allownextresult KErrNotFound
+test RemoveRelationPresentObserverL
+test AddEventObserverL
+test RemoveEventObserverL
+allownextresult KErrNotFound
+test RemoveEventObserverL
+delete test
+[Endtest]
+
+[Test]
+title Schema 1: ImportMetadataL, ExportMetadataL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test ImportMetadataL \Data\MdETestScripterImportMetadata.mde KSync
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_01.mde KSync EFalse EFalse EFalse
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_02.mde KSync EFalse EFalse ETrue
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_03.mde KSync EFalse ETrue  EFalse
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_04.mde KSync EFalse ETrue  ETrue
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_05.mde KSync ETrue  EFalse EFalse
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_06.mde KSync ETrue  EFalse ETrue
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_07.mde KSync ETrue  ETrue  EFalse
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_08.mde KSync ETrue  ETrue  ETrue
+test ImportMetadataL \Data\MdETestScripterImportMetadata.mde KAsync
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_11.mde KAsync EFalse EFalse EFalse
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_12.mde KAsync EFalse EFalse ETrue
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_13.mde KAsync EFalse ETrue  EFalse
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_14.mde KAsync EFalse ETrue  ETrue
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_15.mde KAsync ETrue  EFalse EFalse
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_16.mde KAsync ETrue  EFalse ETrue
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_17.mde KAsync ETrue  ETrue  EFalse
+test ExportMetadataL defaultNs \Data\MdETestScripterExportMetadata1_18.mde KAsync ETrue  ETrue  ETrue
+delete test
+[Endtest]
+
+[Test]
+title Schema 2: ImportSchemaL, NamespaceDefCountL
+create MdETestScripter test
+waittestclass test
+test ImportSchemaL \Data\MDETestScripterSchema.mde
+allowerrorcodes KErrCorrupt
+test ImportSchemaL \Data\MdETestScripterSchema2.mde
+test NamespaceDefCountL 3
+test LoadSchemaL
+test EngineSessionL
+test GetSchemaVersionL 1 0
+delete test
+[Endtest]
+
+[Test]
+title Schema 3: GetNamespaceDefL, GetDefaultNamespaceDefL, NamespaceDefL, CompareL, NameL, ReadOnlyL
+create MdETestScripter test
+waittestclass test
+test GetNamespaceDefL ns "http:\/\/sw.nokia.com/MdE"
+test NameL ENamespaceDef ns "http:\/\/sw.nokia.com/MdE"
+test GetDefaultNamespaceDefL defaultNs
+test NameL ENamespaceDef defaultNs "http:\/\/sw.nokia.com/MdE"
+test NamespaceDefL ns2 ESession 0
+test NameL ENamespaceDef ns2 "http:\/\/sw.nokia.com/MdE"
+test CompareL ENamespaceDef ns defaultNs 0
+test CompareL ENamespaceDef defaultNs ns 0
+test ReadOnlyL ENamespaceDef defaultNs EFalse
+delete test
+[Endtest]
+
+[Test]
+title Schema 4: SetObjectToPresentByGuidL
+create MdETestScripter test
+waittestclass test
+allownextresult KErrNotFound
+test SetObjectToPresentByGuidL 123 456
+delete test
+[Endtest]
+
+[Test]
+title Definitions 1: AddRelationDefL
+create MdETestScripter test
+waittestclass test
+allowerrorcodes KErrCorrupt
+test ImportSchemaL \Data\MdETestScripterSchema2.mde
+test GetNamespaceDefL testNs "http:\/\/sw.nokia.com/MdE/TestSchema2"
+test AddSchemaObserverL
+request ESchemaModified
+allowerrorcodes KErrAlreadyExists
+test AddRelationDefL testNs TestRelation
+wait ESchemaModified
+release ESchemaModified
+test ResetNamespaceDefArray
+test GetNamespaceDefL testNs "http:\/\/sw.nokia.com/MdE/TestSchema2"
+test GetRelationDefL relationDef testNs TestRelation
+// Relation name must only be characters
+allownextresult KErrGeneral
+test AddRelationDefL testNs TestRelation1
+delete test
+[Endtest]
+
+[Test]
+title Definitions 2: AddEventDefL
+create MdETestScripter test
+waittestclass test
+allowerrorcodes KErrCorrupt
+test ImportSchemaL \Data\MdETestScripterSchema2.mde
+test GetNamespaceDefL testNs "http:\/\/sw.nokia.com/MdE/TestSchema2"
+test AddSchemaObserverL
+request ESchemaModified
+allowerrorcodes KErrAlreadyExists
+test AddEventDefL testNs TestEvent
+wait ESchemaModified
+release ESchemaModified
+test ResetNamespaceDefArray
+test GetNamespaceDefL testNs "http:\/\/sw.nokia.com/MdE/TestSchema2"
+test GetEventDefL eventDef testNs TestEvent
+// Relation name must only be characters
+allownextresult KErrGeneral
+test AddEventDefL testNs TestEvent1
+delete test
+[Endtest]
+
+[Test]
+title Definitions 3: GetRelationDefL, RelationDefL, RelationDefCountL, GetEventDefL, EventDefL, EventDefCountL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetRelationDefL relDefContains defaultNs Contains
+test GetRelationDefL relDefReplaces defaultNs Replaces
+test GetRelationDefL relDefIsVersionOf defaultNs IsVersionOf
+test GetRelationDefL relDefRequiresf defaultNs Requires
+test GetRelationDefL relDefUses defaultNs Uses
+test GetRelationDefL relDefReferences defaultNs References
+test GetRelationDefL relDefSummarises defaultNs Summarises
+test GetRelationDefL relDefContainsLocation defaultNs ContainsLocation
+loop 8
+test RelationDefL relDefARRAY_INDEX defaultNs LOOP_COUNTER
+endloop
+test RelationDefCountL defaultNs 8
+test GetEventDefL eventDefCreated defaultNs Created
+test GetEventDefL eventDefDeleted defaultNs Deleted
+test GetEventDefL eventDefOpened defaultNs Opened
+test GetEventDefL eventDefPlayed defaultNs Played
+test GetEventDefL eventDefEdited defaultNs Edited
+test GetEventDefL eventDefSent defaultNs Sent
+test GetEventDefL eventDefReceived defaultNs Received
+loop 7
+test EventDefL eventDefARRAY_INDEX defaultNs LOOP_COUNTER
+endloop
+test EventDefCountL defaultNs 7
+test NamespaceDefL ns1 ERelationDef relDefContains
+test NamespaceDefL ns2 EEventDef eventDefCreated
+delete test
+[Endtest]
+
+[Test]
+title Definitions 4: GetObjectDefL, GetPropertyDefL, ReadOnlyL, MandatoryL, NameL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL objectDefLocation defaultNs Location
+test GetObjectDefL objectDefCalendar defaultNs Calendar
+test GetObjectDefL objectDefContact defaultNs Contact
+test GetObjectDefL objectDefMessage defaultNs Message
+test GetObjectDefL objectDefAlbum defaultNs Album
+test GetObjectDefL objectDefTag defaultNs Tag
+test GetObjectDefL objectDefMediaObject defaultNs MediaObject
+test GetObjectDefL objectDefVideo defaultNs Video
+test ParentL objectDefVideo objectDefMediaObject
+test PropertyDefCountL objectDefVideo 5
+test PropertyDefL propDefVideo0 defaultNs objectDefVideo 0
+allownextresult KErrArgument
+test PropertyDefL propDefErr defaultNs objectDefVideo -1
+test GetPropertyDefL videoCreationDatePropDef objectDefVideo CreationDate
+test NameL EPropertyDef videoCreationDatePropDef "CreationDate"
+test ReadOnlyL EPropertyDef videoCreationDatePropDef EFalse
+test MandatoryL videoCreationDatePropDef ETrue
+test ObjectDefL EPropertyDef objectDefVideo2 videoCreationDatePropDef
+test GetPropertyDefL lastModifiedDatePropDef objectDefVideo LastModifiedDate
+test NameL EPropertyDef lastModifiedDatePropDef "LastModifiedDate"
+test ReadOnlyL EPropertyDef lastModifiedDatePropDef EFalse
+test MandatoryL lastModifiedDatePropDef ETrue
+test ObjectDefL EPropertyDef objectDefVideo3 lastModifiedDatePropDef
+test GetObjectDefL objectDefImage defaultNs Image
+test ParentL objectDefImage objectDefMediaObject
+test GetPropertyDefL imageCreationDatePropDef objectDefImage CreationDate
+test NameL EPropertyDef imageCreationDatePropDef "CreationDate"
+test ReadOnlyL EPropertyDef imageCreationDatePropDef EFalse
+test ObjectDefL EPropertyDef objectDefImage2 imageCreationDatePropDef
+test MandatoryL imageCreationDatePropDef ETrue
+test GetPropertyDefL imageLastModifiedDatePropDef objectDefImage LastModifiedDate
+test NameL EPropertyDef imageLastModifiedDatePropDef "LastModifiedDate"
+test ReadOnlyL EPropertyDef imageLastModifiedDatePropDef EFalse
+test ObjectDefL EPropertyDef objectDefImage3 imageLastModifiedDatePropDef
+test MandatoryL imageLastModifiedDatePropDef ETrue
+test GetObjectDefL audioObjDef defaultNs Audio
+test GetPropertyDefL audioCreationDatePropDef audioObjDef CreationDate
+test NameL EPropertyDef audioCreationDatePropDef "CreationDate"
+test ReadOnlyL EPropertyDef audioCreationDatePropDef EFalse
+test ObjectDefL EPropertyDef audioObjDef2 audioCreationDatePropDef
+test MandatoryL audioCreationDatePropDef ETrue
+test GetPropertyDefL audioLastModifiedDatePropDef audioObjDef LastModifiedDate
+test NameL EPropertyDef audioLastModifiedDatePropDef "LastModifiedDate"
+test ReadOnlyL EPropertyDef audioLastModifiedDatePropDef EFalse
+test ObjectDefL EPropertyDef audioObjDef3 audioLastModifiedDatePropDef
+test MandatoryL audioLastModifiedDatePropDef ETrue
+test GetObjectDefL objectDefTrackLog defaultNs TrackLog
+test ObjectDefCountL defaultNs 12
+test NamespaceDefL ns1 EPropertyDef videoCreationDatePropDef
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 1: NewObjectL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test NewObjectL obj1 videoObjDef KLC
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 2: OpenObjectL, CancelObjectL, OpenForModificationsL, MovePropertiesL, CommitObjectL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test ImportMetadataL \Data\MdETestScripterImportMetadata.mde KSync
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\test2video1.3gp
+test OpenForModificationsL obj0 ETrue
+test OpenObjectL obj1 obj0 KByUri ENamespaceDef defaultNs
+test OpenForModificationsL obj1 ETrue
+allownextresult KErrLocked
+test OpenObjectL objNone obj1 KByUri ENamespaceDef defaultNs
+// objNone does not exist because open failed
+test CancelObjectL obj1
+test OpenForModificationsL obj1 EFalse
+allownextresult KErrAccessDenied
+test MovePropertiesL obj0 obj1
+test OpenObjectL obj2 obj1 KByUri ENamespaceDef defaultNs
+test SetMediaIdL obj2 121212
+test CommitObjectL obj2
+test OpenObjectL obj3 obj1 KByGuid ENamespaceDef defaultNs
+test CommitObjectL obj3
+test OpenObjectL obj4 obj1 KById ENamespaceDef defaultNs
+test CommitObjectL obj4
+test OpenObjectL obj5 obj1 KByUri EObjectDef videoObjDef
+test CommitObjectL obj5
+test OpenObjectL obj6 obj1 KByGuid EObjectDef videoObjDef
+test CommitObjectL obj6
+test OpenObjectL obj7 obj1 KById EObjectDef videoObjDef
+test SetGuidL EObject obj7 000002 000001
+test CommitObjectL obj7
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 3: CommitObjectsL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test ImportMetadataL \Data\MdETestScripterImportMetadata.mde KSync
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\test3video1.3gp
+test OpenObjectL obj1 obj0 KByUri ENamespaceDef defaultNs
+test SetUriL obj0 e:\testing\data\test3video2.mp4
+test OpenObjectL obj2 obj0 KByUri ENamespaceDef defaultNs
+// Commit two objects at starting from obj1 which created before obj2
+test SetGuidL EObject obj2 000003 000002
+test CommitObjectsL obj1 2
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 4: OpenFullObjectL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test ImportMetadataL \Data\MdETestScripterImportMetadata.mde KSync
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\test4video1.3gp
+test OpenFullObjectL obj1 obj0 KByUri
+allownextresult KErrLocked
+test OpenFullObjectL objNone obj0 KByUri
+// objNone does not exist because open failed
+test CancelObjectL obj1
+test OpenFullObjectL obj2 obj1 KByUri
+test CommitObjectL obj2
+test OpenFullObjectL obj3 obj1 KByGuid
+test CommitObjectL obj3
+test OpenFullObjectL obj4 obj1 KById
+test SetGuidL EObject obj4 000004 000001
+test CommitObjectL obj4
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 5: GetObjectL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test ImportMetadataL \Data\MdETestScripterImportMetadata.mde KSync
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\testvideo2.mp4
+test GetObjectL obj1 obj0 KByUri EObjectDef videoObjDef
+test GetObjectL obj2 obj1 KById EObjectDef videoObjDef
+test GetObjectL obj3 obj1 KByGuid EObjectDef videoObjDef
+test GetObjectL obj4 obj1 KByUri ENamespaceDef defaultNs
+test GetObjectL obj5 obj1 KById ENamespaceDef defaultNs
+test GetObjectL obj6 obj1 KByGuid ENamespaceDef defaultNs
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 6: GetFullObjectL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test ImportMetadataL \Data\MdETestScripterImportMetadata.mde KSync
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\testvideo2.mp4
+test GetFullObjectL obj1 videoObjDef obj0 KByUri
+test GetFullObjectL obj2 videoObjDef obj1 KById
+test GetFullObjectL obj3 videoObjDef obj1 KByGuid
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 7: AddObjectL, AddObjectsL, RemoveObjectL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+
+// Create four objects.
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test GetPropertyDefL creaDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creaDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000007 000001
+test NewObjectL obj1 videoObjDef KL
+test GetPropertyDefL creaDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creaDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20081130:235959.999999
+test SetGuidL EObject obj1 000007 000002
+test NewObjectL obj2 videoObjDef KL
+test GetPropertyDefL creaDatePropDef2 videoObjDef CreationDate
+test AddTimePropertyL obj2 creaDatePropDef2 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef2 videoObjDef LastModifiedDate
+test AddTimePropertyL obj2 lastModDatePropDef2 20081130:235959.999999
+test SetGuidL EObject obj2 000007 000003
+test NewObjectL obj3 videoObjDef KL
+test GetPropertyDefL creaDatePropDef3 videoObjDef CreationDate
+test AddTimePropertyL obj3 creaDatePropDef3 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef3 videoObjDef LastModifiedDate
+test AddTimePropertyL obj3 lastModDatePropDef3 20081130:235959.999999
+test SetGuidL EObject obj3 000007 000004
+
+// Add the objects to the database, observe the additions and verify the observed results.
+test AddObjectObserverL
+test AddObjectL obj0
+waittestclass test
+test VerifyObserverNotificationTypeL ENotifyAdd
+test AddObjectsL obj1 3
+waittestclass test
+test VerifyObserverNotificationTypeL ENotifyAdd
+test RemoveObjectObserverL
+test VerifyTItemIdsL EObject 0 4
+
+// Remove the objects, observe the removals and verify the observed results.
+test AddObjectObserverL
+test RemoveObjectL obj0 KById
+waittestclass test
+test VerifyObserverNotificationTypeL ENotifyRemove
+test RemoveObjectL obj1 KById
+waittestclass test
+test VerifyObserverNotificationTypeL ENotifyRemove
+test RemoveObjectL obj2 KById
+waittestclass test
+test VerifyObserverNotificationTypeL ENotifyRemove
+test RemoveObjectL obj3 KById
+waittestclass test
+test VerifyObserverNotificationTypeL ENotifyRemove
+test RemoveObjectObserverL
+test VerifyTItemIdsL EObject 0 4
+
+// Final cleanup.
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 8: CheckObjectL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test ImportMetadataL \Data\MdETestScripterImportMetadata.mde KSync
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\testvideo2.mp4
+test GetObjectL obj1 obj0 KByUri EObjectDef videoObjDef
+test SetUriL obj0 e:\testing\data\testvideo1.3gp
+test GetObjectL obj2 obj0 KByUri EObjectDef videoObjDef
+test CheckObjectL obj1 KByUri
+test CheckObjectL obj1 KById
+test CheckObjectL obj1 KByIds 2
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 9: MovePropertiesL, PropertyCountL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test GetPropertyDefL creationDatePropDef videoObjDef CreationDate
+test GetPropertyDefL lastModDatePropDef videoObjDef LastModifiedDate
+test GetPropertyDefL durationPropDef videoObjDef Duration
+test GetPropertyDefL sizePropDef videoObjDef Size
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\test9video0.mp4
+test AddTimePropertyL obj0 creationDatePropDef 20090611:235959.999999
+test AddTimePropertyL obj0 lastModDatePropDef 20090611:235959.999999
+test AddReal32PropertyL obj0 durationPropDef 30
+test AddUint32PropertyL obj0 sizePropDef 999999
+test AddObjectL obj0
+test NewObjectL obj1 videoObjDef KL
+test SetUriL obj1 e:\testing\data\test9video0.mp4
+test GetObjectL obj2 obj1 KByUri EObjectDef videoObjDef
+test SetGuidL EObject obj2 000009 000001
+test PropertyCountL EObject obj2 4
+test MovePropertiesL obj2 obj1
+test PropertyCountL EObject obj2 0
+test PropertyCountL EObject obj1 4
+test GetPropertyDefL creaDatePropDef0 videoObjDef CreationDate
+test PropertyCountL EPropertyDef obj1 creaDatePropDef0 1
+test SetUriL obj1 e:\testing\data\test9video1.mp4
+test AddObjectL obj1
+test RemoveObjectsL KSync KById obj0 2 1
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 10: Add*PropertyL, Set*ValueL, RemovePropertyL, PropertyL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL KLast e:\testing\data\test10video2.mp4
+test GetPropertyDefL creaDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creaDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test GetPropertyDefL titleDef videoObjDef Title
+test AddTextPropertyL obj0 titleDef "Testi"
+test GetPropertyDefL descrDef videoObjDef Description
+test AddTextPropertyL obj0 descrDef "Testi"
+test GetPropertyDefL commentDef videoObjDef Comment
+test AddTextPropertyL obj0 commentDef "Testi"
+test GetPropertyDefL ratingDef videoObjDef Rating
+test AddUint8PropertyL obj0 ratingDef 3
+test GetPropertyDefL genreDef videoObjDef Genre
+test AddTextPropertyL obj0 genreDef "Testi"
+test GetPropertyDefL copyrightDef videoObjDef Copyright
+test AddTextPropertyL obj0 copyrightDef "Testi"
+test GetPropertyDefL authorDef videoObjDef Author
+test AddTextPropertyL obj0 authorDef "Testi"
+test GetPropertyDefL bitrateDef videoObjDef Bitrate
+test AddUint16PropertyL obj0 bitrateDef 32
+test GetPropertyDefL framerateDef videoObjDef Framerate
+test AddReal32PropertyL obj0 framerateDef 32
+test PropertyCountL EObject obj0 11
+test SetGuidL EObject obj0 000010 000001
+test AddObjectL obj0
+loop 11
+test PropertyL propARRAY_INDEX KByDef obj0 LOOP_COUNTER 0
+test BelongsToSessionL EProperty KLast ETrue 
+test InDatabaseL EProperty KLast ETrue 
+test DefL defARRAY_INDEX EPropertyDef KLast
+test CompareL EPropertyDef KLast LOOP_COUNTER 0
+endloop
+loop 11
+test PropertyL prop2_ARRAY_INDEX KByIndex obj0 LOOP_COUNTER
+endloop
+// Test out of range index parameters to PropertyL
+allownextresult KErrArgument
+test PropertyL propErr KByIndex obj0 -1
+allownextresult KErrArgument
+test PropertyL propErr KByIndex obj0 12
+test SetTextValueL prop2 "Testi2"
+test SetTextValueL prop3 "Testi2"
+test SetTextValueL prop4 "Testi2"
+test SetUint8ValueL prop5 4
+test SetTextValueL prop6 "Testi2"
+test SetTextValueL prop7 "Testi2"
+test SetTextValueL prop8 "Testi2"
+test SetUint16ValueL prop9 16
+test SetReal32ValueL prop10 16
+test PropertyCountL EObject obj0 11
+loop 11
+test ObjectL LOOP_COUNTER obj0
+endloop
+test OpenObjectL obj1 obj0 KById ENamespaceDef defaultNs
+test RemovePropertyL obj1 Title
+test RemovePropertyL obj1 Description
+test RemovePropertyL obj1 Comment
+test RemovePropertyL obj1 Rating
+test RemovePropertyL obj1 Genre
+test RemovePropertyL obj1 Copyright
+test RemovePropertyL obj1 Author
+test RemovePropertyL obj1 Bitrate
+test RemovePropertyL obj1 Framerate
+test PropertyCountL EObject obj1 3
+test CommitObjectL obj1
+test RemoveObjectL obj1 KById
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 11: NewRelationL, AddRelationL, RemoveRelationL, SetGuid, GuidL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+
+// Create two objects and add them to the database.
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test GetPropertyDefL creteDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creteDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000011 000001
+test AddObjectL obj0
+test NewObjectL obj1 videoObjDef KL
+test GetPropertyDefL creteDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creteDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20081130:235959.999999
+test SetGuidL EObject obj1 000011 000002
+test AddObjectL obj1
+
+// Now add some relations between the two objects.
+test GetRelationDefL relDefContains defaultNs Contains
+test NewRelationL rel0 obj1 relDefContains obj0 0 KL
+test SetGuidL ERelation rel0 000011 000101
+test GetRelationDefL relDefReplaces defaultNs Replaces
+test NewRelationL rel1 obj1 relDefReplaces obj0 0 KLC
+test SetGuidL ERelation rel1 000011 000102
+test GetRelationDefL relDefIsVersionOf defaultNs IsVersionOf
+test NewRelationL rel2 obj1 relDefIsVersionOf obj0 0 KL
+test SetGuidL ERelation rel2 000011 000103
+test GetRelationDefL relDefRequires defaultNs Requires
+test NewRelationL rel3 obj1 relDefRequires obj0 0 KLC
+test SetGuidL ERelation rel3 000011 000104
+test GetRelationDefL relDefUses defaultNs Uses
+test NewRelationL rel4 obj1 relDefUses obj0 0 KL
+test SetGuidL ERelation rel4 000011 000105
+test GetRelationDefL relDefReferences defaultNs References
+test NewRelationL rel5 obj1 relDefReferences obj0 0 KLC
+test SetGuidL ERelation rel5 000011 000106
+test GetRelationDefL relDefSummarises defaultNs Summarises
+test NewRelationL rel6 obj1 relDefSummarises obj0 0 KL
+test SetGuidL ERelation rel6 000011 000107
+test CompareL ERelationDef relDefContains relDefContains 0
+test CompareL ERelationDef relDefReplaces relDefContains 1
+
+// Now add the relations to the database, observe the additions and verify the observed results.
+test AddRelationObserverL
+loop 7
+test BelongsToSessionL ERelation LOOP_COUNTER EFalse
+test InDatabaseL ERelation LOOP_COUNTER EFalse
+test AddRelationL LOOP_COUNTER
+waittestclass test
+test VerifyObserverNotificationTypeL ENotifyAdd
+test BelongsToSessionL ERelation LOOP_COUNTER ETrue
+test SessionL ERelation LOOP_COUNTER
+test InDatabaseL ERelation LOOP_COUNTER ETrue
+endloop
+test RemoveRelationObserverL
+test VerifyTItemIdsL ERelation 0 7
+
+test GuidL ERelation rel0 000011 000101
+test GuidL ERelation rel1 000011 000102
+test GuidL ERelation rel2 000011 000103
+test GuidL ERelation rel3 000011 000104
+test GuidL ERelation rel4 000011 000105
+test GuidL ERelation rel5 000011 000106
+test GuidL ERelation rel6 000011 000107
+
+// Remove the relations, observe the removals and verify the observed results.
+test AddRelationItemObserverL
+test AddRelationObserverL
+loop 7
+test RemoveRelationL LOOP_COUNTER
+waittestclass test
+test VerifyObserverNotificationTypeL ENotifyRemove
+waittestclass test
+test VerifyObserverNotificationTypeL ENotifyRemove
+endloop
+test RemoveRelationItemObserverL
+test RemoveRelationObserverL
+test VerifyMdERelationsL 0 7
+
+// Final cleanup.
+test RemoveObjectL obj0 KById
+test RemoveObjectL obj1 KById
+delete test 
+[Endtest]
+
+[Test]
+title Edit Object 12: NewEventL, AddEventL, GetEventL, RemoveEventL, CompareL, ObjectIdL, TimeL, SourceL, ParticipantL, DefL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+
+// Create an object and add it to the database.
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000012 000001
+test AddObjectL obj0
+
+// Add some events for the object.
+test GetEventDefL createdEventDef defaultNs Created
+test NewEventL event0 obj0 createdEventDef TestSource TestParticipant 20081130:235959.999999 KL
+test GetEventDefL deletedEventDef defaultNs Deleted
+test NewEventL event1 obj0 deletedEventDef TestSource TestParticipant 20081130:235959.999999 KLC
+test GetEventDefL opendedEventDef defaultNs Opened
+test NewEventL event2 obj0 opendedEventDef TestSource TestParticipant 20081130:235959.999999 KL
+test GetEventDefL playedEventDef defaultNs Played
+test NewEventL event3 obj0 playedEventDef TestSource TestParticipant 20081130:235959.999999 KLC
+test GetEventDefL editedEventDef defaultNs Edited
+test NewEventL event4 obj0 editedEventDef TestSource TestParticipant 20081130:235959.999999 KL
+test GetEventDefL sentEventDef defaultNs Sent
+test NewEventL event5 obj0 sentEventDef TestSource TestParticipant 20081130:235959.999999 KLC
+test GetEventDefL receivedEventDef defaultNs Received
+test NewEventL event6 obj0 receivedEventDef TestSource TestParticipant 20081130:235959.999999 KL
+
+// Test some assorted CMdEEvent methods.
+test DefL eventDef EEventDef event0
+// Note: the last parameter to CompareL (in this case 0) is the expected result of the call to *::Compare.
+test CompareL EEventDef createdEventDef eventDef 0
+test ObjectIdL event0 obj0
+test TimeL event0 20081130:235959.999999
+test SourceL event0 TestSource 0
+test ParticipantL event0 TestParticipant 0
+test CompareL EEventDef createdEventDef createdEventDef 0
+test CompareL EEventDef deletedEventDef createdEventDef 1
+
+// Now add the events to the database, observe the additions and verify the observed results.
+test AddEventObserverL
+loop 7
+test BelongsToSessionL EEvent LOOP_COUNTER EFalse
+test InDatabaseL EEvent LOOP_COUNTER EFalse
+test AddEventL LOOP_COUNTER
+waittestclass test
+test VerifyObserverNotificationTypeL ENotifyAdd
+test BelongsToSessionL EEvent LOOP_COUNTER ETrue
+test SessionL EEvent LOOP_COUNTER
+test InDatabaseL EEvent LOOP_COUNTER ETrue
+endloop
+test RemoveEventObserverL
+test VerifyTItemIdsL EEvent 0 7
+
+test GetEventL event7 event0
+
+// Remove the events, observe the removals and verify the observed results.
+test AddEventObserverL
+loop 7
+test RemoveEventL LOOP_COUNTER
+waittestclass test
+test VerifyObserverNotificationTypeL ENotifyRemove
+endloop
+test RemoveEventObserverL
+test VerifyTItemIdsL EEvent 0 7
+
+// Final cleanup.
+test RemoveObjectL obj0 KById
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 13: RemoveEventsL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+
+// Create an object and add it to the database.
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000013 000001
+test AddObjectL obj0
+
+// Add some events for the object.
+test GetEventDefL createdEventDef defaultNs Created
+test NewEventL event0 obj0 createdEventDef TestSource TestParticipant 20081130:235959.999999 KL
+test GetEventDefL deletedEventDef defaultNs Deleted
+test NewEventL event1 obj0 deletedEventDef TestSource TestParticipant 20081130:235959.999999 KLC
+test GetEventDefL opendedEventDef defaultNs Opened
+test NewEventL event2 obj0 opendedEventDef TestSource TestParticipant 20081130:235959.999999 KL
+test GetEventDefL playedEventDef defaultNs Played
+test NewEventL event3 obj0 playedEventDef TestSource TestParticipant 20081130:235959.999999 KLC
+test GetEventDefL editedEventDef defaultNs Edited
+test NewEventL event4 obj0 editedEventDef TestSource TestParticipant 20081130:235959.999999 KL
+test GetEventDefL sentEventDef defaultNs Sent
+test NewEventL event5 obj0 sentEventDef TestSource TestParticipant 20081130:235959.999999 KLC
+test GetEventDefL receivedEventDef defaultNs Received
+test NewEventL event6 obj0 receivedEventDef TestSource TestParticipant 20081130:235959.999999 KL
+
+// Now add the events to the database, observe the additions and verify the observed results.
+test AddEventObserverL
+loop 7
+test BelongsToSessionL EEvent LOOP_COUNTER EFalse
+test InDatabaseL EEvent LOOP_COUNTER EFalse
+test AddEventL LOOP_COUNTER
+waittestclass test
+test VerifyObserverNotificationTypeL ENotifyAdd
+test BelongsToSessionL EEvent LOOP_COUNTER ETrue
+test SessionL EEvent LOOP_COUNTER
+test InDatabaseL EEvent LOOP_COUNTER ETrue
+endloop
+test RemoveEventObserverL
+test VerifyTItemIdsL EEvent 0 7
+
+// Remove the events, observe the removals and verify the observed results.
+test AddEventObserverL
+test RemoveEventsL KSync event0 3
+
+request EEventsAsyncRemoved
+test RemoveEventsL KAsync event3 4
+wait EEventsAsyncRemoved
+release EEventsAsyncRemoved
+
+// Final cleanup.
+test RemoveEventObserverL
+test RemoveObjectL obj0 KById
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 14: NewRelationL, AddRelationL, GetRelationL, UpdateRelationL, RemoveRelationL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+
+// Create two objects and add them to the database.
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000014 000001
+test AddObjectL obj0
+test NewObjectL obj1 videoObjDef KL
+test GetPropertyDefL creationDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj1 000014 000002
+test AddObjectL obj1
+
+// Now add some relations between the two objects.
+test GetRelationDefL relDefContains defaultNs Contains
+test NewRelationL rel0 obj1 relDefContains obj0 0 KL
+test GetRelationDefL relDefReplaces defaultNs Replaces
+test NewRelationL rel1 obj1 relDefReplaces obj0 0 KLC
+test GetRelationDefL relDefIsVersionOf defaultNs IsVersionOf
+test NewRelationL rel2 obj1 relDefIsVersionOf obj0 0 KL
+test GetRelationDefL relDefRequires defaultNs Requires
+test NewRelationL rel3 obj1 relDefRequires obj0 0 KLC
+test GetRelationDefL relDefUses defaultNs Uses
+test NewRelationL rel4 obj1 relDefUses obj0 0 KL
+test GetRelationDefL relDefReferences defaultNs References
+test NewRelationL rel5 obj1 relDefReferences obj0 0 KLC
+test GetRelationDefL relDefSummarises defaultNs Summarises
+test NewRelationL rel6 obj1 relDefSummarises obj0 0 KL
+
+// Now add the relations to the database.
+loop 7
+test BelongsToSessionL ERelation LOOP_COUNTER EFalse
+test InDatabaseL ERelation LOOP_COUNTER EFalse
+test AddRelationL LOOP_COUNTER
+test BelongsToSessionL ERelation LOOP_COUNTER ETrue
+test SessionL ERelation LOOP_COUNTER
+test InDatabaseL ERelation LOOP_COUNTER ETrue
+endloop
+
+// Test UpdateRelationL.
+test GetRelationL rel7 rel0
+test UpdateRelationL 7
+
+// Now remove the relations from the database.
+loop 7
+test RemoveRelationL LOOP_COUNTER
+endloop
+
+// Final cleanup.
+test RemoveObjectL obj0 KById
+test RemoveObjectL obj1 KById
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 15: LeftObjectIdL, RightObjectIdL, ParameterL, SetParameterL, ...
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+
+// Create three objects and add them to the database.
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000015 000001
+test AddObjectL obj0
+test NewObjectL obj1 videoObjDef KL
+test GetPropertyDefL creationDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20081130:235959.999999
+test SetGuidL EObject obj1 000015 000002
+test AddObjectL obj1
+test NewObjectL obj2 videoObjDef KL
+test GetPropertyDefL creationDatePropDef2 videoObjDef CreationDate
+test AddTimePropertyL obj2 creationDatePropDef2 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef2 videoObjDef LastModifiedDate
+test AddTimePropertyL obj2 lastModDatePropDef2 20081130:235959.999999
+test SetGuidL EObject obj2 000015 000003
+test AddObjectL obj2
+
+// Create some relations between obj1 and obj0.
+test GetRelationDefL relDefContains defaultNs Contains
+test NewRelationL rel0 obj1 relDefContains obj0 999 KL
+test GetRelationDefL relDefReplaces defaultNs Replaces
+test NewRelationL rel1 obj1 relDefReplaces obj0 999 KLC
+test GetRelationDefL relDefIsVersionOf defaultNs IsVersionOf
+test NewRelationL rel2 obj1 relDefIsVersionOf obj0 999 KL
+test GetRelationDefL relDefRequires defaultNs Requires
+test NewRelationL rel3 obj1 relDefRequires obj0 0 KLC
+test GetRelationDefL relDefUses defaultNs Uses
+test NewRelationL rel4 obj1 relDefUses obj0 0 KL
+test GetRelationDefL relDefReferences defaultNs References
+test NewRelationL rel5 obj1 relDefReferences obj0 0 KLC
+test GetRelationDefL relDefSummarises defaultNs Summarises
+test NewRelationL rel6 obj1 relDefSummarises obj0 0 KL
+
+// Test some relation methods.
+test LeftObjectIdL rel0 obj1
+test RightObjectIdL rel0 obj0
+test ParameterL rel0 999
+test SetParameterL rel0 1000
+test ParameterL rel0 1000
+allownextresult KErrArgument
+test SetLeftObjectIdL rel0 obj0
+test SetLeftObjectIdL rel0 obj2
+allownextresult KErrArgument
+test SetRightObjectIdL rel0 obj2
+test SetRightObjectIdL rel0 obj1
+test SetLastModifiedDateL rel0 20101010:235959.999999
+test LastModifiedDateL rel0 20101010:235959.999999
+
+// Now add the relations to the database.
+loop 7
+test BelongsToSessionL ERelation LOOP_COUNTER EFalse
+test InDatabaseL ERelation LOOP_COUNTER EFalse
+test AddRelationL LOOP_COUNTER
+test BelongsToSessionL ERelation LOOP_COUNTER ETrue
+test SessionL ERelation LOOP_COUNTER
+test InDatabaseL ERelation LOOP_COUNTER ETrue
+endloop
+
+// Now remove the relations from the database.
+test RemoveRelationsL KSync rel0 3
+
+request ERelationsAsyncRemoved
+test RemoveRelationsL KAsync rel3 4
+wait ERelationsAsyncRemoved
+release ERelationsAsyncRemoved
+
+// Final cleanup.
+test RemoveObjectL obj0 KById
+test RemoveObjectL obj1 KById
+test RemoveObjectL obj2 KById
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 16: UriL, SetUriL, DefL, SetDefL, CompareL, MediaIdL, ...
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test ImportMetadataL \Data\MdETestScripterImportMetadata.mde KSync
+
+// Create an object and test some object definition primitives.
+test GetObjectDefL objDef defaultNs Object
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test DefL objDef2 EObjectDef obj0
+test CompareL EObjectDef videoObjDef objDef2 0
+allownextresult KErrNotSupported
+test SetDefL obj0 videoObjDef
+
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000016 000001
+
+// Test the object's SetUri, Uri, SetMediaId, MediaId, SetConfidential, Confidential, SetPlaceholder and Placeholder methods.
+test SetUriL obj0 e:\testing\data\Test16Video1.3gp
+test UriL obj0 e:\testing\data\test16video1.3gp
+test SetMediaIdL obj0 121212
+test MediaIdL obj0 121212
+test SetConfidentialL obj0 EFalse
+test ConfidentialL obj0 EFalse
+test SetConfidentialL obj0 ETrue
+test ConfidentialL obj0 ETrue
+test SetPlaceholderL obj0 EFalse
+test PlaceholderL obj0 EFalse
+test SetPlaceholderL obj0 ETrue
+test PlaceholderL obj0 ETrue
+
+// Now add the object to the database.
+test UsageCountL obj0 0 
+test BelongsToSessionL EObject KLast EFalse
+test InDatabaseL EObject KLast EFalse
+test AddObjectObserverL
+test AddObjectL obj0
+waittestclass test
+test VerifyObserverNotificationTypeL ENotifyAdd
+test RemoveObjectObserverL
+test VerifyTItemIdsL EObject 0 1
+test BelongsToSessionL EObject KLast ETrue
+test SessionL EObject KLast
+test InDatabaseL EObject KLast ETrue
+
+// Final cleanup.
+test RemoveObjectL obj0 KById
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 17: Create JPG Object
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL imageObjDef defaultNs Image
+test NewObjectL obj0 imageObjDef KL
+test SetUriL obj0 c:\Test17Image1.jpg
+test GetPropertyDefL originPropDef imageObjDef Origin
+test AddUint8PropertyL obj0 originPropDef 0
+test GetPropertyDefL creationDatePropDef imageObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 imageObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test GetPropertyDefL sizePropDef imageObjDef Size
+test AddUint32PropertyL obj0 sizePropDef 733064
+test GetPropertyDefL itemTypePropDef imageObjDef ItemType
+test AddTextPropertyL obj0 itemTypePropDef "image/jpg"
+test GetPropertyDefL drmPropDef imageObjDef DRM
+test AddBoolPropertyL obj0 drmPropDef 0
+test GetPropertyDefL releaseDatePropDef imageObjDef ReleaseDate
+test AddTimePropertyL obj0 releaseDatePropDef 20081130:235959.999999
+test GetPropertyDefL widthPropDef imageObjDef Width
+test AddUint16PropertyL obj0 widthPropDef 1024
+test GetPropertyDefL heightPropDef imageObjDef Height
+test AddUint16PropertyL obj0 heightPropDef 768
+test SetGuidL EObject obj0 000017 000001
+test BelongsToSessionL EObject KLast EFalse
+test InDatabaseL EObject KLast EFalse
+test AddObjectL obj0
+test BelongsToSessionL EObject KLast ETrue
+test SessionL EObject KLast
+test InDatabaseL EObject KLast ETrue
+test RemoveObjectL obj0 KById
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 18: AddFreeTextL, RemoveFreeTextL, FreeTextCountL, FreeTextL, FreeTextIndexL
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\Test18Video1.3gp
+test GetPropertyDefL creationDatePropDef videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test AddFreeTextL obj0 TestFreeText1
+test FreeTextL obj0 0 TestFreeText1
+test FreeTextIndexL obj0 0 TestFreeText1
+test FreeTextCountL obj0 1
+test RemoveFreeTextL obj0 0
+allowerrorcodes KErrNotFound
+test FreeTextIndexL obj0 0 TestFreeText1
+test FreeTextCountL obj0 0
+test AddFreeTextL obj0 TestFreeText1
+test SetGuidL EObject KLast 000018 000001
+test BelongsToSessionL EObject KLast EFalse
+test InDatabaseL EObject KLast EFalse
+test AddObjectL obj0
+test BelongsToSessionL EObject KLast ETrue
+test SessionL EObject KLast
+test InDatabaseL EObject KLast ETrue
+test RemoveObjectL obj0 KById
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 19: Create MP3 Object With 8 Text 7 Int Properties
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL audioObjectDef defaultNs Audio
+test NewObjectL obj0 audioObjectDef KL
+test SetUriL 0 c:\Test19Audio1.mp3
+test GetPropertyDefL creationDatePropDef audioObjectDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 audioObjectDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test GetPropertyDefL sizePropDef audioObjectDef Size
+test AddUint32PropertyL obj0 sizePropDef 5000
+test GetPropertyDefL itemTypePropDef audioObjectDef ItemType
+test AddTextPropertyL obj0 itemTypePropDef "audio/mp3"
+test GetPropertyDefL titlePropDef audioObjectDef Title
+test AddTextPropertyL obj0 titlePropDef "TestMp3"
+test GetPropertyDefL drmPropDef audioObjectDef DRM
+test AddBoolPropertyL obj0 drmPropDef 1
+test GetPropertyDefL durationPropDef audioObjectDef Duration
+test AddReal32PropertyL obj0 durationPropDef 1234
+test GetPropertyDefL trackPropDef audioObjectDef Track
+test AddUint16PropertyL obj0 trackPropDef 12
+test GetPropertyDefL descriptionPropDef audioObjectDef Description
+test AddTextPropertyL obj0 descriptionPropDef "Ambient noise from street"
+test GetPropertyDefL commentPropDef audioObjectDef Comment
+test AddTextPropertyL obj0 commentPropDef "No comments."
+test GetPropertyDefL genrePropDef audioObjectDef Genre
+test AddTextPropertyL obj0 genrePropDef "ambient"
+test GetPropertyDefL artistPropDef audioObjectDef Artist
+test AddTextPropertyL obj0 artistPropDef "Cars on street"
+test GetPropertyDefL albumPropDef audioObjectDef Album
+test AddTextPropertyL obj0 albumPropDef "Noises"
+test GetPropertyDefL composerPropDef audioObjectDef Composer
+test AddTextPropertyL obj0 composerPropDef "Myself"
+test SetGuidL EObject obj0 000019 000001
+test BelongsToSessionL EObject KLast EFalse
+test InDatabaseL EObject KLast EFalse
+test AddObjectL obj0
+test BelongsToSessionL EObject KLast ETrue
+test SessionL EObject KLast
+test InDatabaseL EObject KLast ETrue
+test RemoveObjectL obj0 KById
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 20: Create MP4 Object With 17 Properties
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\Test20Video1.mp4
+test GetPropertyDefL creationDatePropDef videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test GetPropertyDefL titlePropDef videoObjDef Title
+test AddTextPropertyL obj0 titlePropDef "Party video 1/2"
+test GetPropertyDefL sizePropDef videoObjDef Size
+test AddUint32PropertyL obj0 sizePropDef 12345678
+test GetPropertyDefL descriptionPropDef videoObjDef Description
+test AddTextPropertyL obj0 descriptionPropDef "First video from party."
+test GetPropertyDefL commentPropDef videoObjDef Comment
+test AddTextPropertyL obj0 commentPropDef "No comments."
+test GetPropertyDefL ratingPropDef videoObjDef Rating
+test AddUint8PropertyL obj0 ratingPropDef 4
+test GetPropertyDefL accessCountPropDef videoObjDef AccessCount
+test AddUint32PropertyL obj0 accessCountPropDef 0
+test GetPropertyDefL genrePropDef videoObjDef Genre
+test AddTextPropertyL obj0 genrePropDef "Party."
+test GetPropertyDefL drmPropDef videoObjDef DRM
+test AddBoolPropertyL obj0 drmPropDef 1
+test GetPropertyDefL releasedatePropDef videoObjDef ReleaseDate
+test AddTimePropertyL obj0 releasedatePropDef 20081130:235959.999999
+test GetPropertyDefL itemTypePropDef videoObjDef ItemType
+test AddTextPropertyL obj0 itemTypePropDef "video/mp4"
+test GetPropertyDefL widthPropDef videoObjDef Width
+test AddUint16PropertyL obj0 widthPropDef 640
+test GetPropertyDefL heightPropDef videoObjDef Height
+test AddUint16PropertyL obj0 heightPropDef 480
+test GetPropertyDefL durationPropDef videoObjDef Duration
+test AddReal32PropertyL obj0 durationPropDef 1234
+test GetPropertyDefL bitratePropDef videoObjDef Bitrate
+test AddUint16PropertyL obj0 bitratePropDef 25
+test GetPropertyDefL artistPropDef videoObjDef Artist
+test AddTextPropertyL obj0 artistPropDef "Myself"
+test SetGuidL EObject obj0 000020 000001
+test BelongsToSessionL EObject KLast EFalse
+test InDatabaseL EObject KLast EFalse
+test AddObjectL obj0
+test BelongsToSessionL EObject KLast ETrue
+test SessionL EObject KLast
+test InDatabaseL EObject KLast ETrue
+test RemoveObjectL obj0 KByUri
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 21: Create MP4 Object
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\Test21Video1.mp4
+test GetPropertyDefL creationDatePropDef videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test GetPropertyDefL sizePropDef videoObjDef Size
+test AddUint32PropertyL obj0 sizePropDef 12345678
+test GetPropertyDefL accessCountPropDef videoObjDef AccessCount
+test AddUint32PropertyL obj0 accessCountPropDef 0
+test GetPropertyDefL drmPropDef videoObjDef DRM
+test AddBoolPropertyL obj0 drmPropDef 1
+test GetPropertyDefL releasedatePropDef videoObjDef ReleaseDate
+test AddTimePropertyL obj0 releasedatePropDef 20081130:235959.999999
+test GetPropertyDefL itemTypePropDef videoObjDef ItemType
+test AddTextPropertyL obj0 itemTypePropDef "video/mp4"
+test GetPropertyDefL widthPropDef videoObjDef Width
+test AddUint16PropertyL obj0 widthPropDef 640
+test GetPropertyDefL heightPropDef videoObjDef Height
+test AddUint16PropertyL obj0 heightPropDef 480
+test GetPropertyDefL durationPropDef videoObjDef Duration
+test AddReal32PropertyL obj0 durationPropDef 1234
+test SetGuidL EObject obj0 000021 000001
+test BelongsToSessionL EObject KLast EFalse
+test InDatabaseL EObject KLast EFalse
+test AddObjectL obj0
+test BelongsToSessionL EObject KLast ETrue
+test SessionL EObject KLast
+test InDatabaseL EObject KLast ETrue
+test RemoveObjectL obj0 KByUri
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 22: Create Album Object
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL albumObjDef defaultNs Album
+test NewObjectL obj0 albumObjDef KL
+test GetPropertyDefL creationDatePropDef albumObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 albumObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test GetPropertyDefL typePropDef albumObjDef Type
+test AddUint16PropertyL obj0 typePropDef 25
+test GetPropertyDefL orderedPropDef albumObjDef Ordered
+test AddBoolPropertyL obj0 orderedPropDef EFalse
+test SetGuidL EObject obj0 000022 000001
+test BelongsToSessionL EObject KLast EFalse
+test InDatabaseL EObject KLast EFalse
+test AddObjectL obj0
+test BelongsToSessionL EObject KLast ETrue
+test SessionL EObject KLast
+test InDatabaseL EObject KLast ETrue
+test RemoveObjectL obj0 KById
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 23: Create Video Object
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\Test23Video1.mp4
+test GetPropertyDefL creationDatePropDef videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test GetPropertyDefL frameratePropDef videoObjDef Framerate
+test AddReal32PropertyL obj0 frameratePropDef 25
+test GetPropertyDefL audioFourCCPropDef videoObjDef AudioFourCC
+test AddUint32PropertyL obj0 audioFourCCPropDef 2000
+test GetPropertyDefL drmPropDef videoObjDef DRM
+test AddBoolPropertyL obj0 drmPropDef 1
+test GetPropertyDefL accessCountPropDef videoObjDef AccessCount
+test AddUint32PropertyL obj0 accessCountPropDef 10
+test GetPropertyDefL releaseDatePropDef videoObjDef ReleaseDate
+test AddTimePropertyL obj0 releaseDatePropDef 20081130:235959.999999
+test GetPropertyDefL durationPropDef videoObjDef Duration
+test AddReal32PropertyL obj0 durationPropDef 60
+test SetGuidL EObject obj0 000023 000001
+test BelongsToSessionL EObject KLast EFalse
+test InDatabaseL EObject KLast EFalse
+test AddObjectL obj0
+test BelongsToSessionL EObject KLast ETrue
+test SessionL EObject KLast
+test InDatabaseL EObject KLast ETrue
+test RemoveObjectL obj0 KByUri
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 24: Create Audio Object
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL audioObjDef defaultNs Audio
+test NewObjectL obj0 audioObjDef KL
+test SetUriL obj0 e:\testing\data\Test24Audio1.mp3
+test GetPropertyDefL creationDatePropDef audioObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModifiedDatePropDef audioObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModifiedDatePropDef 20081130:235959.999999
+test GetPropertyDefL samplingFrequencyPropDef audioObjDef SamplingFrequency
+test AddReal32PropertyL obj0 samplingFrequencyPropDef 25
+test GetPropertyDefL composerPropDef audioObjDef Composer
+test AddTextPropertyL obj0 composerPropDef "Bach"
+test GetPropertyDefL trackPropDef audioObjDef Track
+test AddUint16PropertyL obj0 trackPropDef 1
+test GetPropertyDefL originalArtistPropDef audioObjDef OriginalArtist
+test AddTextPropertyL obj0 originalArtistPropDef "Nightwish"
+test SetGuidL EObject obj0 000024 000001
+test BelongsToSessionL EObject KLast EFalse
+test InDatabaseL EObject KLast EFalse
+test AddObjectL obj0
+test BelongsToSessionL EObject KLast ETrue
+test SessionL EObject KLast
+test InDatabaseL EObject KLast ETrue
+test RemoveObjectL obj0 KByUri
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 25: Create Image Object
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL imageObjDef defaultNs Image
+test NewObjectL obj0 imageObjDef KL
+test SetUriL obj0 e:\testing\data\Test25Image1.jpg
+test GetPropertyDefL creationDatePropDef imageObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModifiedDatePropDef imageObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModifiedDatePropDef 20081130:235959.999999
+test GetPropertyDefL pixelXDimensionPropDef imageObjDef PixelXDimension
+test AddUint32PropertyL obj0 pixelXDimensionPropDef 20
+test GetPropertyDefL pixelYDimensionPropDef imageObjDef PixelYDimension
+test AddUint32PropertyL obj0 pixelYDimensionPropDef 20
+test GetPropertyDefL maxAperturePropDef imageObjDef MaxAperture
+test AddReal32PropertyL obj0 maxAperturePropDef 20
+test SetGuidL EObject obj0 000025 000001
+test BelongsToSessionL EObject KLast EFalse
+test InDatabaseL EObject KLast EFalse
+test AddObjectL obj0
+test BelongsToSessionL EObject KLast ETrue
+test SessionL EObject KLast
+test InDatabaseL EObject KLast ETrue
+test RemoveObjectL obj0 KByUri
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 26: *ValueL: Video
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL KLast e:\testing\data\test26video1.3gp
+test RemoveObjectsL KSync KByUri obj0 1 0
+test ImportMetadataL \Data\MdETestScripterImportMetadata.mde KSync
+test OpenFullObjectL obj1 obj0 KByUri
+test GetPropertyDefL creationDatePropDef videoObjDef CreationDate
+test PropertyL creationDate KByDef obj1 creationDatePropDef 0
+test TimeValueL creationDate 20080707:
+test GetPropertyDefL lastModifiedDatePropDef videoObjDef LastModifiedDate
+test PropertyL lastModifiedDate KByDef obj1 lastModifiedDatePropDef 0
+test TimeValueL lastModifiedDate 20080707:
+test GetPropertyDefL bitratePropDef videoObjDef Bitrate
+test PropertyL bitrate KByDef obj1 bitratePropDef 0
+test Uint16ValueL bitrate 23
+test GetPropertyDefL sizePropDef videoObjDef Size
+test PropertyL size KByDef obj1 sizePropDef 0
+test Uint32ValueL size 66192
+test GetPropertyDefL ratingPropDef videoObjDef Rating
+test PropertyL rating KByDef obj1 ratingPropDef 0
+test Uint8ValueL rating 4
+test GetPropertyDefL widthPropDef videoObjDef Width
+test PropertyL width KByDef obj1 widthPropDef 0
+test Uint16ValueL width 176
+test GetPropertyDefL heightPropDef videoObjDef Height
+test PropertyL height KByDef obj1 heightPropDef 0
+test Uint16ValueL height 144
+test GetPropertyDefL durationPropDef videoObjDef Duration
+test PropertyL duration KByDef obj1 durationPropDef 0
+test Real32ValueL duration 21
+test GetPropertyDefL releaseDatePropDef videoObjDef ReleaseDate
+test PropertyL releaseDate KByDef obj1 releaseDatePropDef 0
+test TimeValueL releaseDate 20080707:
+test GetPropertyDefL captureDatePropDef videoObjDef CaptureDate
+test PropertyL captureDate KByDef obj1 captureDatePropDef 0
+test TimeValueL captureDate 20080707:
+test GetPropertyDefL frameratePropDef videoObjDef Framerate
+test PropertyL framerate KByDef obj1 frameratePropDef 0
+test Real32ValueL framerate 7
+test GetPropertyDefL drmPropDef videoObjDef DRM
+test PropertyL drm KByDef obj1 drmPropDef 0
+test BoolValueL drm EFalse
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 27: *ValueL: All property types
+create MdETestScripter test
+waittestclass test
+allowerrorcodes KErrCorrupt
+test ImportSchemaL \Data\MdETestScripterSchema2.mde
+test GetNamespaceDefL testNs "http:\/\/sw.nokia.com/MdE/TestSchema2"
+test GetObjectDefL testObjDef testNs TestObjectType
+test NewObjectL obj0 testObjDef KL
+test SetUriL obj0 c:\data\other\testobject27
+test GetPropertyDefL testPropertyBoolDef testObjDef TestPropertyBool
+test AddBoolPropertyL obj0 testPropertyBoolDef EFalse
+test PropertyL boolProp KByDef obj0 testPropertyBoolDef EFalse
+test ReadOnlyL EPropertyDef testPropertyBoolDef EFalse
+test BoolValueL boolProp EFalse
+test GetPropertyDefL testPropertyInt8Def testObjDef TestPropertyInt8
+test AddInt8PropertyL obj0 testPropertyInt8Def 0
+test PropertyL int8Prop KByDef obj0 testPropertyInt8Def 0
+test ReadOnlyL EPropertyDef testPropertyInt8Def ETrue
+test Int8ValueL int8Prop 0
+test GetPropertyDefL testPropertyUint8Def testObjDef TestPropertyUint8
+test AddUint8PropertyL obj0 testPropertyUint8Def 0
+test PropertyL uint8Prop KByDef obj0 testPropertyUint8Def 0
+test ReadOnlyL EPropertyDef testPropertyUint8Def EFalse
+test Uint8ValueL uint8Prop 0
+test GetPropertyDefL testPropertyInt16Def testObjDef TestPropertyInt16
+test AddInt16PropertyL obj0 testPropertyInt16Def 0
+test PropertyL int16Prop KByDef obj0 testPropertyInt16Def 0
+test ReadOnlyL EPropertyDef testPropertyInt16Def ETrue
+test Int16ValueL int16Prop 0
+test GetPropertyDefL testPropertyUint16Def testObjDef TestPropertyUint16
+test AddUint16PropertyL obj0 testPropertyUint16Def 0
+test PropertyL uint16Prop KByDef obj0 testPropertyUint16Def 0
+test ReadOnlyL EPropertyDef testPropertyUint16Def EFalse
+test Uint16ValueL uint16Prop 0
+test GetPropertyDefL testPropertyInt32Def testObjDef TestPropertyInt32
+test AddInt32PropertyL obj0 testPropertyInt32Def 0
+test PropertyL int32Prop KByDef obj0 testPropertyInt32Def 0
+test ReadOnlyL EPropertyDef testPropertyInt32Def ETrue
+test Int32ValueL int32Prop 0
+test GetPropertyDefL testPropertyUint32Def testObjDef TestPropertyUint32
+test AddUint32PropertyL obj0 testPropertyUint32Def 0
+test PropertyL uint32Prop KByDef obj0 testPropertyUint32Def 0
+test ReadOnlyL EPropertyDef testPropertyUint32Def EFalse
+test Uint32ValueL uint32Prop 0
+test GetPropertyDefL testPropertyInt64Def testObjDef TestPropertyInt64
+test AddInt64PropertyL obj0 testPropertyInt64Def 0
+test PropertyL int64Prop KByDef obj0 testPropertyInt64Def 0
+test ReadOnlyL EPropertyDef testPropertyInt64Def ETrue
+test Int64ValueL int64Prop 0
+test GetPropertyDefL testPropertyReal32Def testObjDef TestPropertyReal32
+test AddReal32PropertyL obj0 testPropertyReal32Def 0
+test PropertyL real32Prop KByDef obj0 testPropertyReal32Def 0
+test ReadOnlyL EPropertyDef testPropertyReal32Def EFalse
+test Real32ValueL real32Prop 0
+test GetPropertyDefL testPropertyReal64Def testObjDef TestPropertyReal64
+test AddReal64PropertyL obj0 testPropertyReal64Def 0
+test PropertyL real64Prop KByDef obj0 testPropertyReal64Def 0
+test ReadOnlyL EPropertyDef testPropertyReal64Def ETrue
+test Real64ValueL real64Prop 0
+test GetPropertyDefL testPropertyTimeDef testObjDef TestPropertyTime
+test AddTimePropertyL obj0 testPropertyTimeDef 20081130:235959.999999
+test PropertyL timeProp KByDef obj0 testPropertyTimeDef 0
+test ReadOnlyL EPropertyDef testPropertyTimeDef EFalse
+test TimeValueL timeProp 20081130:235959.999999
+test GetPropertyDefL testPropertyTextDef testObjDef TestPropertyText
+test AddTextPropertyL obj0 testPropertyTextDef "Test Text"
+test PropertyL textProp KByDef obj0 testPropertyTextDef 0
+test ReadOnlyL EPropertyDef testPropertyTextDef ETrue
+test TextValueL textProp "Test Text"
+test GetPropertyDefL creaDatePropDef0 testObjDef CreationDate
+test AddTimePropertyL obj0 creaDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 testObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000027 000001
+test AddObjectL obj0
+test BelongsToSessionL EObject obj0 ETrue
+test SessionL EObject obj0
+test InDatabaseL EObject obj0 ETrue
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 28: Add*PropertyL: KErrArgument
+create MdETestScripter test
+waittestclass test
+allowerrorcodes KErrCorrupt
+test ImportSchemaL \Data\MdETestScripterSchema2.mde
+test GetNamespaceDefL testNs "http:\/\/sw.nokia.com/MdE/TestSchema2"
+test GetObjectDefL testObjDef testNs TestObjectType
+test NewObjectL obj0 testObjDef KL
+test SetUriL obj0 c:\data\other\testobject28
+test GetPropertyDefL testPropertyTimeDef testObjDef TestPropertyTime
+test GetPropertyDefL testPropertyTextDef testObjDef TestPropertyText
+allownextresult KErrArgument
+test AddBoolPropertyL obj0 testPropertyTimeDef EFalse
+allownextresult KErrArgument
+test AddInt8PropertyL obj0 testPropertyTimeDef 0
+allownextresult KErrArgument
+test AddUint8PropertyL obj0 testPropertyTimeDef 0
+allownextresult KErrArgument
+test AddInt16PropertyL obj0 testPropertyTimeDef 0
+allownextresult KErrArgument
+test AddUint16PropertyL obj0 testPropertyTimeDef 0
+allownextresult KErrArgument
+test AddInt32PropertyL obj0 testPropertyTimeDef 0
+allownextresult KErrArgument
+test AddUint32PropertyL obj0 testPropertyTimeDef 0
+allownextresult KErrArgument
+test AddInt64PropertyL obj0 testPropertyTimeDef 0
+allownextresult KErrArgument
+test AddReal32PropertyL obj0 testPropertyTimeDef 0
+allownextresult KErrArgument
+test AddReal64PropertyL obj0 testPropertyTimeDef 0
+allownextresult KErrArgument
+test AddTextPropertyL obj0 testPropertyTimeDef "Test Text"
+allownextresult KErrArgument
+test AddTimePropertyL obj0 testPropertyTextDef 20080707:
+test ReadOnlyL EPropertyDef testPropertyTextDef ETrue
+test GetPropertyDefL creaDatePropDef0 testObjDef CreationDate
+test AddTimePropertyL obj0 creaDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 testObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000028 000001
+test AddObjectL obj0
+test BelongsToSessionL EObject obj0 ETrue
+test SessionL EObject obj0
+test InDatabaseL EObject obj0 ETrue
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 29: Min*ValueL, Max*ValueL
+create MdETestScripter test
+waittestclass test
+allowerrorcodes KErrCorrupt
+test ImportSchemaL \Data\MdETestScripterSchema2.mde
+test GetNamespaceDefL testNs "http:\/\/sw.nokia.com/MdE/TestSchema2"
+test GetObjectDefL testObjDef testNs TestObjectType
+test GetPropertyDefL testPropInt32 testObjDef TestPropertyInt32
+test MinInt32ValueL testPropInt32 -2147483648
+test MaxInt32ValueL testPropInt32 2147483647
+test GetPropertyDefL testPropUint32 testObjDef TestPropertyUint32
+test MinUint32ValueL testPropUint32 0
+test MaxUint32ValueL testPropUint32 4294967295
+test GetPropertyDefL testPropInt64 testObjDef TestPropertyInt64
+test MinInt64ValueL testPropInt64 -9223372036854775808
+test MaxInt64ValueL testPropInt64 +9223372036854775807
+test GetPropertyDefL testPropReal64 testObjDef TestPropertyReal64
+test MinRealValueL testPropReal64 "-1.797693134862e+308"
+test MaxRealValueL testPropReal64 "1.797693134862e+308"
+test GetPropertyDefL testPropTime testObjDef TestPropertyTime
+test MinTimeValueL testPropTime 00000000:
+test MaxTimeValueL testPropTime 20100528:163021 
+test GetPropertyDefL testPropText testObjDef TestPropertyText
+test MinTextLengthL testPropText 1
+test MaxTextLengthL testPropText 65535
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 30: RemoveObjectsL KSync KById
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000030 000001
+test AddObjectL obj0
+test NewObjectL obj1 videoObjDef KL
+test GetPropertyDefL creationDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20081130:235959.999999
+test SetGuidL EObject obj1 000030 000002
+test AddObjectL obj1
+test NewObjectL obj2 videoObjDef KL
+test GetPropertyDefL creationDatePropDef2 videoObjDef CreationDate
+test AddTimePropertyL obj2 creationDatePropDef2 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef2 videoObjDef LastModifiedDate
+test AddTimePropertyL obj2 lastModDatePropDef2 20081130:235959.999999
+test SetGuidL EObject obj2 000030 000003
+test AddObjectL obj2
+test NewObjectL obj3 videoObjDef KL
+test GetPropertyDefL creationDatePropDef3 videoObjDef CreationDate
+test AddTimePropertyL obj3 creationDatePropDef3 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef3 videoObjDef LastModifiedDate
+test AddTimePropertyL obj3 lastModDatePropDef3 20081130:235959.999999
+test SetGuidL EObject obj3 000030 000004
+test AddObjectL obj3
+test NewObjectL obj4 videoObjDef KL
+test GetPropertyDefL creationDatePropDef4 videoObjDef CreationDate
+test AddTimePropertyL obj4 creationDatePropDef4 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef4 videoObjDef LastModifiedDate
+test AddTimePropertyL obj4 lastModDatePropDef4 20081130:235959.999999
+test SetGuidL EObject obj4 000030 000005
+test AddObjectL obj4
+test RemoveObjectsL KSync KById obj0 5
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 31: RemoveObjectsL KSync KByUri
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000031 000001
+test SetUriL obj0 e:\testing\data\Test31Video1.3gp
+test AddObjectL obj0
+test NewObjectL obj1 videoObjDef KL
+test GetPropertyDefL creationDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20081130:235959.999999
+test SetGuidL EObject obj1 000031 000002
+test SetUriL obj1 e:\testing\data\Test31Video2.3gp
+test AddObjectL obj1
+test NewObjectL obj2 videoObjDef KL
+test GetPropertyDefL creationDatePropDef2 videoObjDef CreationDate
+test AddTimePropertyL obj2 creationDatePropDef2 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef2 videoObjDef LastModifiedDate
+test AddTimePropertyL obj2 lastModDatePropDef2 20081130:235959.999999
+test SetGuidL EObject obj2 000031 000003
+test SetUriL obj2 e:\testing\data\Test31Video3.3gp
+test AddObjectL obj2
+test NewObjectL obj3 videoObjDef KL
+test GetPropertyDefL creationDatePropDef3 videoObjDef CreationDate
+test AddTimePropertyL obj3 creationDatePropDef3 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef3 videoObjDef LastModifiedDate
+test AddTimePropertyL obj3 lastModDatePropDef3 20081130:235959.999999
+test SetGuidL EObject obj3 000031 000004
+test SetUriL obj3 e:\testing\data\Test31Video4.3gp
+test AddObjectL obj3
+test NewObjectL obj4 videoObjDef KL
+test GetPropertyDefL creationDatePropDef4 videoObjDef CreationDate
+test AddTimePropertyL obj4 creationDatePropDef4 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef4 videoObjDef LastModifiedDate
+test AddTimePropertyL obj4 lastModDatePropDef4 20081130:235959.999999
+test SetGuidL EObject obj4 000031 000005
+test SetUriL obj4 e:\testing\data\Test31Video5.3gp
+test AddObjectL obj4
+test RemoveObjectsL KSync KByUri obj0 5 
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 32: RemoveObjectsL KAsync KById
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000032 000001
+test AddObjectL obj0
+test NewObjectL obj1 videoObjDef KL
+test GetPropertyDefL creationDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20081130:235959.999999
+test SetGuidL EObject obj1 000032 000002
+test AddObjectL obj1
+test NewObjectL obj2 videoObjDef KL
+test GetPropertyDefL creationDatePropDef2 videoObjDef CreationDate
+test AddTimePropertyL obj2 creationDatePropDef2 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef2 videoObjDef LastModifiedDate
+test AddTimePropertyL obj2 lastModDatePropDef2 20081130:235959.999999
+test SetGuidL EObject obj2 000032 000003
+test AddObjectL obj2
+test NewObjectL obj3 videoObjDef KL
+test GetPropertyDefL creationDatePropDef3 videoObjDef CreationDate
+test AddTimePropertyL obj3 creationDatePropDef3 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef3 videoObjDef LastModifiedDate
+test AddTimePropertyL obj3 lastModDatePropDef3 20081130:235959.999999
+test SetGuidL EObject obj3 000032 000004
+test AddObjectL obj3
+test NewObjectL obj4 videoObjDef KL
+test GetPropertyDefL creationDatePropDef4 videoObjDef CreationDate
+test AddTimePropertyL obj4 creationDatePropDef4 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef4 videoObjDef LastModifiedDate
+test AddTimePropertyL obj4 lastModDatePropDef4 20081130:235959.999999
+test SetGuidL EObject obj4 000032 000005
+test AddObjectL obj4
+request EObjectsAsyncRemoved
+test RemoveObjectsL KAsync KById obj0 5
+wait EObjectsAsyncRemoved
+release EObjectsAsyncRemoved
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 33: RemoveObjectsL KAsync KByUri
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000033 000001
+test SetUriL obj0 e:\testing\data\Test33Video1.3gp
+test AddObjectL obj0
+test NewObjectL obj1 videoObjDef KL
+test GetPropertyDefL creationDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20081130:235959.999999
+test SetGuidL EObject obj1 000033 000002
+test SetUriL obj1 e:\testing\data\Test33Video2.3gp
+test AddObjectL obj1
+test NewObjectL obj2 videoObjDef KL
+test GetPropertyDefL creationDatePropDef2 videoObjDef CreationDate
+test AddTimePropertyL obj2 creationDatePropDef2 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef2 videoObjDef LastModifiedDate
+test AddTimePropertyL obj2 lastModDatePropDef2 20081130:235959.999999
+test SetGuidL EObject obj2 000033 000003
+test SetUriL obj2 e:\testing\data\Test33Video3.3gp
+test AddObjectL obj2
+test NewObjectL obj3 videoObjDef KL
+test GetPropertyDefL creationDatePropDef3 videoObjDef CreationDate
+test AddTimePropertyL obj3 creationDatePropDef3 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef3 videoObjDef LastModifiedDate
+test AddTimePropertyL obj3 lastModDatePropDef3 20081130:235959.999999
+test SetGuidL EObject obj3 000033 000004
+test SetUriL obj3 e:\testing\data\Test33Video4.3gp
+test AddObjectL obj3
+test NewObjectL obj4 videoObjDef KL
+test GetPropertyDefL creationDatePropDef4 videoObjDef CreationDate
+test AddTimePropertyL obj4 creationDatePropDef4 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef4 videoObjDef LastModifiedDate
+test AddTimePropertyL obj4 lastModDatePropDef4 20081130:235959.999999
+test SetGuidL EObject obj4 000033 000005
+test SetUriL obj4 e:\testing\data\Test33Video5.3gp
+test AddObjectL obj4
+request EObjectsAsyncRemoved
+test RemoveObjectsL KAsync KByUri obj0 5
+wait EObjectsAsyncRemoved
+release EObjectsAsyncRemoved
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 34: AddItemsL KSync KAsync
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test NewObjectL obj0 videoObjDef KL
+test AddTimePropertyL obj0 creationDatePropDef0 20090507:
+test AddTimePropertyL obj0 lastModDatePropDef0 20090507:
+test SetGuidL EObject obj0 000034 000001
+test SetUriL obj0 e:\testing\data\Test34Video1.3gp
+test NewObjectL obj1 videoObjDef KL
+test AddTimePropertyL obj1 creationDatePropDef0 20090507:
+test AddTimePropertyL obj1 lastModDatePropDef0 20090507:
+test SetGuidL EObject obj1 000034 000002
+test SetUriL obj1 e:\testing\data\Test34Video2.3gp
+test NewObjectL obj2 videoObjDef KL
+test AddTimePropertyL obj2 creationDatePropDef0 20090507:
+test AddTimePropertyL obj2 lastModDatePropDef0 20090507:
+test SetGuidL EObject obj2 000034 000003
+test SetUriL obj2 e:\testing\data\Test34Video3.mp4
+test AddItemsL KSync EObject 0 1
+request EItemsAsyncAdd
+test AddItemsL KAsync EObject 1 2
+wait EItemsAsyncAdd
+release EItemsAsyncAdd
+delete test
+[Endtest]
+
+[Test]
+title Edit Object 35: UpdateItemsL KSync KAsync
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test NewObjectL obj0 videoObjDef KL
+test AddTimePropertyL obj0 creationDatePropDef0 20090601:
+test AddTimePropertyL obj0 lastModDatePropDef0 20090601:
+test SetGuidL EObject obj0 000035 000001
+test SetUriL obj0 e:\testing\data\Test35Video1.3gp
+test AddItemsL KSync EObject 0 1
+test OpenObjectL obj1 obj0 KByUri ENamespaceDef defaultNs
+test SetGuidL EObject obj1 000035 000002
+test SetUriL obj1 e:\testing\data\Test35Video2.3gp
+test UpdateItemsL KSync EObject 1 1
+test OpenObjectL obj2 obj1 KByUri ENamespaceDef defaultNs
+test SetGuidL EObject obj2 000035 000003
+test SetUriL obj2 e:\testing\data\Test35Video3.3gp
+request EItemsAsyncUpdate
+test UpdateItemsL KAsync EObject 2 1
+wait EItemsAsyncUpdate
+release EItemsAsyncUpdate
+delete test
+[Endtest]
+
+[Test]
+title Query 1: Object 
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+// Add 4 video objects to DB  
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\TEST_VIDEO8.mp4
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test NewObjectL obj1 videoObjDef KL
+test SetUriL obj1 e:\testing\data\TEST_VIDEO9.mp4
+test GetPropertyDefL creationDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20081130:235959.999999
+test NewObjectL obj2 videoObjDef KL
+test SetUriL obj2 e:\testing\data\TEST_VIDEO10.mp4
+test GetPropertyDefL creationDatePropDef2 videoObjDef CreationDate
+test AddTimePropertyL obj2 creationDatePropDef2 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef2 videoObjDef LastModifiedDate
+test AddTimePropertyL obj2 lastModDatePropDef2 20081130:235959.999999
+test NewObjectL obj3 videoObjDef KL
+test SetUriL obj3 e:\testing\data\TEST_VIDEO11.mp4
+test GetPropertyDefL creationDatePropDef3 videoObjDef CreationDate
+test AddTimePropertyL obj3 creationDatePropDef3 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef3 videoObjDef LastModifiedDate
+test AddTimePropertyL obj3 lastModDatePropDef3 20081130:235959.999999
+test AddObjectsL obj0 4
+
+// Query
+test NewObjectQueryL rootCond defaultNs Item Video Object
+
+test AddObjectConditionL objCond rootCond ObjectConditionCompare Uri e:\testing\data\TEST_VIDEO8.mp4
+
+test SetObjectQueryResultL { obj0 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveObjectsL KSync KById obj0 4
+delete test
+[Endtest]
+
+[Test]
+title Query 2: Relation Conditions
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+// Add 4 video objects to DB  
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\TEST_VIDEO12.mp4
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test NewObjectL obj1 videoObjDef KL
+test SetUriL obj1 e:\testing\data\TEST_VIDEO13.mp4
+test GetPropertyDefL creationDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20081130:235959.999999
+test NewObjectL obj2 videoObjDef KL
+test SetUriL obj2 e:\testing\data\TEST_VIDEO14.mp4
+test GetPropertyDefL creationDatePropDef2 videoObjDef CreationDate
+test AddTimePropertyL obj2 creationDatePropDef2 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef2 videoObjDef LastModifiedDate
+test AddTimePropertyL obj2 lastModDatePropDef2 20081130:235959.999999
+test NewObjectL obj3 videoObjDef KL
+test SetUriL obj3 e:\testing\data\TEST_VIDEO15.mp4
+test GetPropertyDefL creationDatePropDef3 videoObjDef CreationDate
+test AddTimePropertyL obj3 creationDatePropDef3 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef3 videoObjDef LastModifiedDate
+test AddTimePropertyL obj3 lastModDatePropDef3 20081130:235959.999999
+test AddObjectsL obj0 4
+test GetRelationDefL relDefContains defaultNs Contains
+test NewRelationL rel0 obj0 relDefContains obj1 0 KL
+test NewRelationL rel1 obj0 relDefContains obj2 0 KL
+test NewRelationL rel2 obj2 relDefContains obj3 0 KLC
+loop 3
+test AddRelationL LOOP_COUNTER
+endloop
+
+// Query
+test NewRelationQueryL rootCond defaultNs Item Video Object
+
+test AddRelationConditionL containsRelCond rootCond Left RelationDef Contains
+
+test LeftL leftCond containsRelCond
+test AddObjectConditionL objCond leftCond ObjectConditionCompare Uri e:\testing\data\TEST_VIDEO12.mp4
+
+test SetRelationQueryResultL { rel0 rel1 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveRelationsL KSync rel0 3
+test RemoveObjectsL KSync KById obj0 4
+delete test
+[Endtest]
+
+
+[Test]
+title Query 3: Time Property Conditions
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+// Add 4 video objects to DB  
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\TEST_VIDEO16.mp4
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test NewObjectL obj1 videoObjDef KL
+test SetUriL obj1 e:\testing\data\TEST_VIDE17.mp4
+test GetPropertyDefL creationDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20090000:000000.000000
+test NewObjectL obj2 videoObjDef KL
+test SetUriL obj2 e:\testing\data\TEST_VIDEO18.mp4
+test GetPropertyDefL creationDatePropDef2 videoObjDef CreationDate
+test AddTimePropertyL obj2 creationDatePropDef2 20090000:000000.000000
+test GetPropertyDefL lastModDatePropDef2 videoObjDef LastModifiedDate
+test AddTimePropertyL obj2 lastModDatePropDef2 20090000:000000.000001
+test NewObjectL obj3 videoObjDef KL
+test SetUriL obj3 e:\testing\data\TEST_VIDEO19.mp4
+test GetPropertyDefL creationDatePropDef3 videoObjDef CreationDate
+test AddTimePropertyL obj3 creationDatePropDef3 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef3 videoObjDef LastModifiedDate
+test AddTimePropertyL obj3 lastModDatePropDef3 20090000:000000.000002
+test AddObjectsL obj0 4
+
+
+test NewObjectQueryL rootCond defaultNs Item Video Object
+test AddPropertyConditionL propCond rootCond lastModDatePropDef0 TimeRange Greater 20090000:000000.000000 00000000:000000.000000
+
+
+test SetObjectQueryResultL { obj2 obj3 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveObjectsL KSync KById obj0 4
+delete test
+[Endtest]
+
+
+[Test]
+title Query 4: all images with JPEG MIME
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL imageObjDef defaultNs Image
+test NewObjectL obj0 imageObjDef KL
+test SetUriL obj0 e:\testing\data\Test25Image1.jpg
+test GetPropertyDefL itemTypePropertyPropDef imageObjDef ItemType
+test AddTextPropertyL obj0 itemTypePropertyPropDef "image/jpeg"
+test GetPropertyDefL creationDatePropDef imageObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModifiedDatePropDef imageObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModifiedDatePropDef 20081130:235959.999999
+test AddObjectL obj0
+
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj1 videoObjDef KL
+test SetUriL obj1 e:\testing\data\TEST_VIDE17.mp4
+test GetPropertyDefL creationDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20090000:000000.000000
+test AddObjectL obj1
+
+test NewObjectQueryL rootCond defaultNs Item Image Object
+test AddPropertyConditionL jpegMimeCond rootCond itemTypePropertyPropDef TextCompare Equals image/jpeg
+test SetObjectQueryResultL { obj0 }
+test FindL -1 -1
+waittestclass test
+test RemoveObjectL obj0 KById
+delete test
+[Endtest]
+
+[Test]
+title Query 5: all mediaobject properties from images and videos
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL mediaObjectDef defaultNs MediaObject
+test GetObjectDefL imageObjDef defaultNs Image
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 imageObjDef KL
+test SetUriL obj0 e:\testing\data\Test25Image1.jpg
+test GetPropertyDefL itemTypePropertyPropDef imageObjDef ItemType
+test AddTextPropertyL obj0 itemTypePropertyPropDef "image/jpeg"
+test GetPropertyDefL creationDatePropDef imageObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModifiedDatePropDef imageObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModifiedDatePropDef 20081130:235959.999999
+test AddObjectL obj0
+
+test NewObjectL obj1 videoObjDef KL
+test SetUriL obj1 e:\testing\data\TEST_VIDE17.mp4
+test GetPropertyDefL creationDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20090000:000000.000000
+test AddObjectL obj1
+
+test NewObjectQueryL rootCond defaultNs Item MediaObject LookupObject { imageObjDef videoObjDef }
+test SetObjectQueryResultL { obj0 obj1 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveObjectsL KSync KById obj0 2
+[Endtest]
+
+[Test]
+title Query 6: usage counts and titles from "user" albums, sorted by title A->Z
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+
+test GetObjectDefL albumObjDef defaultNs Album
+test NewObjectL obj0 albumObjDef KL
+test GetPropertyDefL titleDef albumObjDef Title
+test AddTextPropertyL obj0 titleDef "Humppaa 0"
+// test GetPropertyDefL usageCountPropDef albumObjDef UsageCount
+// test AddInt32PropertyL obj0 usageCountPropDef 25
+test GetPropertyDefL creationDatePropDef albumObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 albumObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test GetPropertyDefL typePropDef albumObjDef Type
+test AddUint16PropertyL obj0 typePropDef EAlbumUser
+test GetPropertyDefL orderedPropDef albumObjDef Ordered
+test AddBoolPropertyL obj0 orderedPropDef EFalse
+test SetGuidL EObject obj0 000022 000001
+test AddObjectL obj0
+
+test GetObjectDefL albumObjDef1 defaultNs Album
+test NewObjectL obj1 albumObjDef1 KL
+// test GetPropertyDefL titleDef albumObjDef Title
+test AddTextPropertyL obj1 titleDef "Humppaa 1"
+// test GetPropertyDefL usageCountPropDef1 albumObjDef1 UsageCount
+// test AddInt32PropertyL obj1 usageCountPropDef1 10
+test GetPropertyDefL creationDatePropDef1 albumObjDef1 CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 albumObjDef1 LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20081130:235959.999999
+test GetPropertyDefL typePropDef1 albumObjDef1 Type
+test AddUint16PropertyL obj1 typePropDef1 EAlbumUser
+test GetPropertyDefL orderedPropDef1 albumObjDef1 Ordered
+test AddBoolPropertyL obj1 orderedPropDef1 EFalse
+test SetGuidL EObject obj1 000022 000002
+test AddObjectL obj1
+
+
+test NewObjectL obj2 albumObjDef KL
+// test GetPropertyDefL titleDef albumObjDef Title
+test AddTextPropertyL obj2 titleDef "Humppaa 2"
+// test GetPropertyDefL usageCountPropDef1 albumObjDef1 UsageCount
+// test AddInt32PropertyL obj2 usageCountPropDef1 10
+test AddTimePropertyL obj2 creationDatePropDef1 20081130:235959.999999
+test AddTimePropertyL obj2 lastModDatePropDef1 20081130:235959.999999
+test AddUint16PropertyL obj2 typePropDef1 EAlbumUserPredefined
+test AddBoolPropertyL obj2 orderedPropDef1 EFalse
+test SetGuidL EObject obj2 000022 000003
+test AddObjectL obj2
+
+test GetRelationDefL relDefContains defaultNs Contains
+test NewRelationL rel0 obj0 relDefContains obj1 0 KL
+test NewRelationL rel1 obj0 relDefContains obj2 0 KL
+
+// test UsageCountL obj0 2
+// test UsageCountL obj1 1
+// test UsageCountL obj2 1
+
+loop 2
+test AddRelationL LOOP_COUNTER
+endloop
+
+
+
+test NewObjectQueryL rootCond defaultNs Item Album Object
+
+test GetPropertyDefL titlePropDef albumObjDef Title
+test AddPropertyFilterL titlePropDef
+test AppendOrderRuleL ESortAscending EOrderRuleTypeProperty titlePropDef
+
+test SetOperatorL rootCond ELogicConditionOperatorOr
+test AddPropertyConditionL albumPropCond rootCond typePropDef UintRange Less EAlbumUserPredefined EAlbumUserPredefined
+test AddPropertyConditionL typePropCond rootCond typePropDef PropCond
+test SetNegateL typePropCond ETrue
+
+test SetObjectQueryResultL { obj0 obj1 }
+test FindL -1 -1
+waittestclass test
+
+
+
+test RemoveRelationsL KSync rel0 2
+test RemoveObjectsL KSync KById obj0 2
+[Endtest]
+
+[Test]
+title Query 7: usage counts and titles from used tags and sort in descending order by usage count
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+
+test GetObjectDefL albumObjDef defaultNs Album
+test NewObjectL obj0 albumObjDef KL
+test GetPropertyDefL titleDef albumObjDef Title
+test AddTextPropertyL obj0 titleDef "Humppaa 0"
+// test GetPropertyDefL usageCountPropDef albumObjDef UsageCount
+// test AddInt32PropertyL obj0 usageCountPropDef 25
+test GetPropertyDefL creationDatePropDef albumObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 albumObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test GetPropertyDefL typePropDef albumObjDef Type
+test AddUint16PropertyL obj0 typePropDef EAlbumUser
+test GetPropertyDefL orderedPropDef albumObjDef Ordered
+test AddBoolPropertyL obj0 orderedPropDef EFalse
+test SetGuidL EObject obj0 000022 000001
+test AddObjectL obj0
+
+test GetObjectDefL albumObjDef1 defaultNs Album
+test NewObjectL obj1 albumObjDef1 KL
+// test GetPropertyDefL titleDef albumObjDef Title
+test AddTextPropertyL obj1 titleDef "Humppaa 1"
+// test GetPropertyDefL usageCountPropDef1 albumObjDef1 UsageCount
+// test AddInt32PropertyL obj1 usageCountPropDef1 10
+test GetPropertyDefL creationDatePropDef1 albumObjDef1 CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 albumObjDef1 LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20081130:235959.999999
+test GetPropertyDefL typePropDef1 albumObjDef1 Type
+test AddUint16PropertyL obj1 typePropDef1 EAlbumUser
+test GetPropertyDefL orderedPropDef1 albumObjDef1 Ordered
+test AddBoolPropertyL obj1 orderedPropDef1 EFalse
+test SetGuidL EObject obj1 000022 000002
+test AddObjectL obj1
+
+
+test NewObjectL obj2 albumObjDef KL
+// test GetPropertyDefL titleDef albumObjDef Title
+test AddTextPropertyL obj2 titleDef "Humppaa 2"
+// test GetPropertyDefL usageCountPropDef1 albumObjDef1 UsageCount
+// test AddInt32PropertyL obj2 usageCountPropDef1 10
+test AddTimePropertyL obj2 creationDatePropDef1 20081130:235959.999999
+test AddTimePropertyL obj2 lastModDatePropDef1 20081130:235959.999999
+test AddUint16PropertyL obj2 typePropDef1 EAlbumUserPredefined
+test AddBoolPropertyL obj2 orderedPropDef1 EFalse
+test SetGuidL EObject obj2 000022 000003
+test AddObjectL obj2
+
+test GetObjectDefL tagObjDef defaultNs Tag
+
+test NewObjectL tag0 tagObjDef KL
+test AddTimePropertyL tag0 creationDatePropDef1 20081130:235959.999999
+test AddTimePropertyL tag0 lastModDatePropDef1 20081130:235959.999999
+
+test NewObjectL tag1 tagObjDef KL
+test AddTimePropertyL tag1 creationDatePropDef1 20081130:235959.999999
+test AddTimePropertyL tag1 lastModDatePropDef1 20081130:235959.999999
+
+test AddObjectL tag0
+test AddObjectL tag1
+
+test GetRelationDefL relDefContains defaultNs Contains
+test NewRelationL rel0 obj0 relDefContains tag0 0 KL
+test NewRelationL rel1 obj1 relDefContains tag1 0 KL
+test NewRelationL rel2 obj2 relDefContains tag1 0 KL
+
+loop 3
+test AddRelationL LOOP_COUNTER
+endloop
+
+test NewObjectQueryL rootCond defaultNs Count Object Object
+
+test AddRelationConditionL relCond rootCond Left RelationDef Contains
+test RightL rightRelCond relCond
+test AddObjectConditionL objCond rightRelCond Object tag1 1
+
+test SetObjectQueryResultL { obj1 obj2 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveRelationsL KSync rel0 3
+test RemoveObjectsL KSync KById obj0 2
+test RemoveObjectsL KSync KById tag0 2
+[Endtest]
+
+[Test]
+title Query 8: object IDs from defined album
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+
+
+test GetObjectDefL albumObjDef defaultNs Album
+test NewObjectL albumObj0 albumObjDef KL
+test GetPropertyDefL titleDef albumObjDef Title
+test AddTextPropertyL albumObj0 titleDef "Humppaa 0"
+test GetPropertyDefL creationDatePropDef albumObjDef CreationDate
+test AddTimePropertyL albumObj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 albumObjDef LastModifiedDate
+test AddTimePropertyL albumObj0 lastModDatePropDef0 20081130:235959.999999
+test GetPropertyDefL typePropDef albumObjDef Type
+test AddUint16PropertyL albumObj0 typePropDef 25
+test GetPropertyDefL orderedPropDef albumObjDef Ordered
+test AddBoolPropertyL albumObj0 orderedPropDef EFalse
+test SetGuidL EObject albumObj0 000022 000001
+test AddObjectL albumObj0
+
+test GetObjectDefL audioObjDef defaultNs Audio
+test NewObjectL track0 audioObjDef KL
+test AddTextPropertyL track0 titleDef "HumppaSong"
+test AddTimePropertyL track0 creationDatePropDef 20081130:235959.999999
+test AddTimePropertyL track0 lastModDatePropDef0 20081130:235959.999999
+test AddObjectL track0
+
+test GetRelationDefL relDefContains defaultNs Contains
+test NewRelationL rel0 albumObj0 relDefContains track0 0 KL
+test AddRelationL rel0
+
+test NewObjectQueryL rootCond defaultNs Id Object Object
+test AddRelationConditionL containsRelCond rootCond Right RelationDef Contains
+test LeftL leftRelCond containsRelCond
+test AddObjectConditionL objCond leftRelCond Object albumObj0 1
+
+
+test SetObjectQueryResultL { track0 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveRelationL rel0
+test RemoveObjectsL KSync KById albumObj0 2
+
+[Endtest]
+
+[Test]
+title Query 9: object count from defined tag
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+
+test GetObjectDefL albumObjDef defaultNs Album
+test NewObjectL albumObj0 albumObjDef KL
+test GetPropertyDefL titleDef albumObjDef Title
+test AddTextPropertyL albumObj0 titleDef "Humppaa 0"
+test GetPropertyDefL creationDatePropDef albumObjDef CreationDate
+test AddTimePropertyL albumObj0 creationDatePropDef 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 albumObjDef LastModifiedDate
+test AddTimePropertyL albumObj0 lastModDatePropDef0 20081130:235959.999999
+test GetPropertyDefL typePropDef albumObjDef Type
+test AddUint16PropertyL albumObj0 typePropDef 25
+test GetPropertyDefL orderedPropDef albumObjDef Ordered
+test AddBoolPropertyL albumObj0 orderedPropDef EFalse
+test SetGuidL EObject albumObj0 000022 000001
+
+
+test GetObjectDefL audioObjDef defaultNs Audio
+test NewObjectL track0 audioObjDef KL
+test AddTextPropertyL track0 titleDef "HumppaSong"
+test AddTimePropertyL track0 creationDatePropDef 20081130:235959.999999
+test AddTimePropertyL track0 lastModDatePropDef0 20081130:235959.999999
+
+test AddObjectL albumObj0
+test AddObjectL track0
+
+test GetRelationDefL relDefContains defaultNs Contains
+test NewRelationL rel0 albumObj0 relDefContains track0 0 KL
+
+
+test AddRelationL rel0
+
+test NewObjectQueryL rootCond defaultNs Count Object Object
+test AddRelationConditionL containsRelCond rootCond Left RelationDef Contains
+test RightL rightRelCond containsRelCond
+test AddObjectConditionL objCond rightRelCond Object track0 1
+
+test SetObjectQueryResultL { track0 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveRelationL rel0
+test RemoveObjectsL KSync KById albumObj0 2
+
+// test RemoveRelationsL KSync rel0 1
+[Endtest]
+
+[Test]
+title Query 10: videos created within a year and (length less or equal than 30 seconds or size less than 1 MB)
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+// Add 4 video objects to DB  
+test GetObjectDefL videoObjDef defaultNs Video
+
+
+test GetPropertyDefL creationDatePropDef videoObjDef CreationDate
+test GetPropertyDefL lastModDatePropDef videoObjDef LastModifiedDate
+
+test GetPropertyDefL durationPropDef videoObjDef Duration
+test GetPropertyDefL sizePropDef videoObjDef Size
+
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\TEST_VIDEO16.mp4
+test AddTimePropertyL obj0 creationDatePropDef 20071130:235959.999999
+test AddTimePropertyL obj0 lastModDatePropDef 20081130:235959.999999
+test AddReal32PropertyL obj0 durationPropDef 30
+test AddUint32PropertyL obj0 sizePropDef 999999
+
+test NewObjectL obj1 videoObjDef KL
+test SetUriL obj1 e:\testing\data\TEST_VIDEO17.mp4
+test AddTimePropertyL obj1 creationDatePropDef 20081130:235959.999999
+test AddTimePropertyL obj1 lastModDatePropDef 20090000:000000.000000
+test AddReal32PropertyL obj1 durationPropDef 28
+test AddUint32PropertyL obj1 sizePropDef 999999
+
+test NewObjectL obj2 videoObjDef KL
+test SetUriL obj2 e:\testing\data\TEST_VIDEO18.mp4
+test AddTimePropertyL obj2 creationDatePropDef 20080001:000000.000000
+test AddTimePropertyL obj2 lastModDatePropDef 20090000:000000.000001
+test AddReal32PropertyL obj2 durationPropDef 28
+test AddUint32PropertyL obj2 sizePropDef 1000000
+
+test NewObjectL obj3 videoObjDef KL
+test SetUriL obj3 e:\testing\data\TEST_VIDEO19.mp4
+test AddTimePropertyL obj3 creationDatePropDef 20091130:235959.999999
+test AddTimePropertyL obj3 lastModDatePropDef 20090000:000000.000002
+test AddReal32PropertyL obj3 durationPropDef 28
+test AddUint32PropertyL obj3 sizePropDef 999999
+
+test AddObjectsL obj0 4
+
+test NewObjectQueryL rootCond defaultNs Item Video Object
+test AddPropertyConditionL propCond rootCond creationDatePropDef TimeRange Between 20080000:000000.000000 20090000:000000.000000
+test AddLogicConditionL durationCond rootCond OR
+
+test AddPropertyConditionL durationPropCond durationCond durationPropDef RealRange LessOrEqual 30 30
+test AddPropertyConditionL sizePropCond durationCond sizePropDef UintRange Less 1000000 1000000
+
+test SetObjectQueryResultL { obj1 obj2 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveObjectsL KSync KById obj0 4
+delete test
+[Endtest]
+
+[Test]
+title Query 11: images within some region (GPS location in some rectangle)
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+// Add 4 video objects to DB  
+test GetObjectDefL imageObjDef defaultNs Image
+
+
+test GetPropertyDefL creationDatePropDef imageObjDef CreationDate
+test GetPropertyDefL lastModDatePropDef imageObjDef LastModifiedDate
+
+test GetPropertyDefL sizePropDef imageObjDef Size
+
+test NewObjectL image0 imageObjDef KL
+test SetUriL image0 e:\testing\data\TEST_IMAGE16.jpg
+test AddTimePropertyL image0 creationDatePropDef 20071130:235959.999999
+test AddTimePropertyL image0 lastModDatePropDef 20081130:235959.999999
+test AddUint32PropertyL image0 sizePropDef 999999
+
+test NewObjectL image1 imageObjDef KL
+test SetUriL image1 e:\testing\data\TEST_IMAGE17.jpg
+test AddTimePropertyL image1 creationDatePropDef 20081130:235959.999999
+test AddTimePropertyL image1 lastModDatePropDef 20090000:000000.000000
+test AddUint32PropertyL image1 sizePropDef 999999
+
+test NewObjectL image2 imageObjDef KL
+test SetUriL image2 e:\testing\data\TEST_IMAGE18.jpg
+test AddTimePropertyL image2 creationDatePropDef 20080001:000000.000000
+test AddTimePropertyL image2 lastModDatePropDef 20090000:000000.000001
+test AddUint32PropertyL image2 sizePropDef 999999
+
+test NewObjectL image3 imageObjDef KL
+test SetUriL image3 e:\testing\data\TEST_IMAGE19.jpg
+test AddTimePropertyL image3 creationDatePropDef 20091130:235959.999999
+test AddTimePropertyL image3 lastModDatePropDef 20090000:000000.000002
+test AddUint32PropertyL image3 sizePropDef 999999
+
+test AddObjectsL image0 4
+
+test GetObjectDefL locationObjectDef defaultNs Location
+test GetPropertyDefL latitudeLocationPropDef locationObjectDef Latitude
+test GetPropertyDefL longitudeLocationPropDef locationObjectDef Longitude
+
+test NewObjectL loc0 locationObjectDef KL
+test AddTimePropertyL loc0 creationDatePropDef 20091130:235959.999999
+test AddTimePropertyL loc0 lastModDatePropDef 20090000:000000.000002
+test AddReal64PropertyL loc0 latitudeLocationPropDef 61
+test AddReal64PropertyL loc0 longitudeLocationPropDef 26
+
+test NewObjectL loc1 locationObjectDef KL
+test AddTimePropertyL loc1 creationDatePropDef 20091130:235959.999999
+test AddTimePropertyL loc1 lastModDatePropDef 20090000:000000.000002
+test AddReal64PropertyL loc1 latitudeLocationPropDef 62
+test AddReal64PropertyL loc1 longitudeLocationPropDef 60
+
+test AddObjectsL loc0 2
+
+test GetRelationDefL relContainsLocationDef defaultNs ContainsLocation
+
+test NewRelationL rel00 image0 relContainsLocationDef loc0 0 KL
+test NewRelationL rel11 image1 relContainsLocationDef loc1 0 KL
+test NewRelationL rel21 image2 relContainsLocationDef loc1 0 KL
+
+test AddRelationL rel00
+test AddRelationL rel11
+test AddRelationL rel21
+
+test NewObjectQueryL rootCond defaultNs Item Image Object
+
+test AddRelationConditionL relCond rootCond Left RelationDef ContainsLocation
+test RightL rightRelCond relCond
+
+test AddPropertyConditionL latitudePropCond rightRelCond latitudeLocationPropDef RealRange Between 60 63
+test AddPropertyConditionL longitudePropCond rightRelCond longitudeLocationPropDef RealRange Between 21 27
+
+test SetObjectQueryResultL { image0 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveObjectsL KSync KById image0 4
+test RemoveObjectsL KSync KById loc0 2
+test RemoveRelationsL KSync rel00 3
+
+delete test
+[Endtest]
+
+[Test]
+title Query 12: from downloaded objects, which are modified (last modified date) during this month
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+// Add 4 video objects to DB  
+test GetObjectDefL imageObjDef defaultNs Image
+test GetObjectDefL videoObjDef defaultNs Video
+test GetObjectDefL objDef defaultNs Object
+
+test GetPropertyDefL originPropDef objDef Origin
+
+test GetPropertyDefL creationDatePropDef imageObjDef CreationDate
+test GetPropertyDefL lastModDatePropDef imageObjDef LastModifiedDate
+
+test GetPropertyDefL videoCreationDatePropDef videoObjDef CreationDate
+test GetPropertyDefL videoLastModDatePropDef videoObjDef LastModifiedDate
+
+test GetPropertyDefL sizePropDef imageObjDef Size
+
+test NewObjectL image0 imageObjDef KL
+test SetUriL image0 e:\testing\data\TEST_IMAGE16.jpg
+test AddTimePropertyL image0 creationDatePropDef 20071130:235959.999999
+test AddTimePropertyL image0 lastModDatePropDef 20081130:235959.999999
+test AddUint32PropertyL image0 sizePropDef 999999
+test AddUint8PropertyL image0 originPropDef ECamera
+
+test NewObjectL image1 imageObjDef KL
+test SetUriL image1 e:\testing\data\TEST_IMAGE17.jpg
+test AddTimePropertyL image1 creationDatePropDef 20081130:235959.999999
+test AddTimePropertyL image1 lastModDatePropDef 20090001:000000.000000
+test AddUint32PropertyL image1 sizePropDef 999999
+test AddUint8PropertyL image1 originPropDef EDownloaded
+
+test NewObjectL video0 videoObjDef KL
+test SetUriL video0 e:\testing\data\TEST_VIDEO18.jpg
+test AddTimePropertyL video0 videoCreationDatePropDef 20080001:000000.000000
+test AddTimePropertyL video0 videoLastModDatePropDef 20090000:000000.000001
+test AddUint32PropertyL video0 sizePropDef 999999
+test AddUint8PropertyL video0 originPropDef ESideLoaded
+
+test NewObjectL video1 videoObjDef KL
+test SetUriL video1 e:\testing\data\TEST_VIDEO19.jpg
+test AddTimePropertyL video1 videoCreationDatePropDef 20091130:235959.999999
+test AddTimePropertyL video1 videoLastModDatePropDef 20091130:235959.999999
+test AddUint32PropertyL video1 sizePropDef 999999
+test AddUint8PropertyL video1 originPropDef EDownloaded
+
+test AddObjectsL image0 2
+test AddObjectsL video0 2
+
+test NewObjectQueryL rootCond defaultNs Item Object Object
+
+test AddPropertyFilterL sizePropDef
+test AddPropertyConditionL originPropCond rootCond originPropDef UintRange Equal EDownloaded 0
+test AddPropertyConditionL lastModPropCond rootCond videoLastModDatePropDef TimeRange Between 20090000:000000.000000 20090100:000000.000000
+
+test SetObjectQueryResultL { image1 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveObjectsL KSync KById image0 2
+test RemoveObjectsL KSync KById video0 2
+
+
+[Endtest]
+
+[Test]
+title Query 13: width, height and size properties from images and videos, sorted by size (largest->smallest)
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+// Add 2 image objects and 2 video objects to DB 
+test GetObjectDefL imageObjDef defaultNs Image
+test GetObjectDefL videoObjDef defaultNs Video
+test GetObjectDefL objDef defaultNs Object
+test GetObjectDefL mediaObjDef defaultNs MediaObject
+
+test GetPropertyDefL originPropDef objDef Origin
+
+test GetPropertyDefL creationDatePropDef imageObjDef CreationDate
+test GetPropertyDefL lastModDatePropDef imageObjDef LastModifiedDate
+
+test GetPropertyDefL videoCreationDatePropDef videoObjDef CreationDate
+test GetPropertyDefL videoLastModDatePropDef videoObjDef LastModifiedDate
+
+test GetPropertyDefL widthPropDef mediaObjDef Width
+test GetPropertyDefL heightPropDef mediaObjDef Height
+test GetPropertyDefL sizePropDef imageObjDef Size
+
+test NewObjectL image0 imageObjDef KL
+test SetUriL image0 e:\testing\data\TEST_IMAGE16.jpg
+test AddTimePropertyL image0 creationDatePropDef 20071130:235959.999999
+test AddTimePropertyL image0 lastModDatePropDef 20081130:235959.999999
+test AddUint32PropertyL image0 sizePropDef 999999
+test AddUint8PropertyL image0 originPropDef ECamera
+test AddUint16PropertyL image0 widthPropDef 200
+test AddUint16PropertyL image0 heightPropDef 100
+
+test NewObjectL image1 imageObjDef KL
+test SetUriL image1 e:\testing\data\TEST_IMAGE17.jpg
+test AddTimePropertyL image1 creationDatePropDef 20081130:235959.999999
+test AddTimePropertyL image1 lastModDatePropDef 20090000:000000.000000
+test AddUint32PropertyL image1 sizePropDef 999997
+test AddUint8PropertyL image1 originPropDef EDownloaded
+test AddUint16PropertyL image1 widthPropDef 200
+test AddUint16PropertyL image1 heightPropDef 100
+
+test NewObjectL video0 videoObjDef KL
+test SetUriL video0 e:\testing\data\TEST_VIDEO18.mp4
+test AddTimePropertyL video0 videoCreationDatePropDef 20080001:000000.000000
+test AddTimePropertyL video0 videoLastModDatePropDef 20090000:000000.000001
+test AddUint32PropertyL video0 sizePropDef 999998
+test AddUint8PropertyL video0 originPropDef ESideLoaded
+test AddUint16PropertyL video0 widthPropDef 200
+test AddUint16PropertyL video0 heightPropDef 100
+
+test NewObjectL video1 videoObjDef KL
+test SetUriL video1 e:\testing\data\TEST_VIDEO19.mp4
+test AddTimePropertyL video1 videoCreationDatePropDef 20091130:235959.999999
+test AddTimePropertyL video1 videoLastModDatePropDef 20091130:235959.999999
+test AddUint32PropertyL video1 sizePropDef 999996
+test AddUint8PropertyL video1 originPropDef EDownloaded
+test AddUint16PropertyL video1 widthPropDef 200
+test AddUint16PropertyL video1 heightPropDef 100
+
+test AddObjectsL image0 2
+test AddObjectsL video0 2
+
+test NewObjectQueryL rootCond defaultNs Item MediaObject LookupObject { imageObjDef videoObjDef }
+
+test AddPropertyFilterL widthPropDef
+test AddPropertyFilterL heightPropDef
+test AddPropertyFilterL sizePropDef
+test AppendOrderRuleL ESortDescending EOrderRuleTypeProperty sizePropDef
+
+test SetObjectQueryResultL { image0 video0 image1 video1 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveObjectsL KSync KById image0 2
+test RemoveObjectsL KSync KById video0 2
+[Endtest]
+
+[Test]
+title Query 14: distinct models from images by prefix "N", sorted A->Z
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+// Add 4 video objects to DB  
+test GetObjectDefL imageObjDef defaultNs Image
+test GetObjectDefL videoObjDef defaultNs Video
+test GetObjectDefL objDef defaultNs Object
+test GetObjectDefL mediaObjDef defaultNs MediaObject
+
+test GetPropertyDefL originPropDef objDef Origin
+
+test GetPropertyDefL creationDatePropDef imageObjDef CreationDate
+test GetPropertyDefL lastModDatePropDef imageObjDef LastModifiedDate
+
+
+
+test GetPropertyDefL widthPropDef mediaObjDef Width
+test GetPropertyDefL heightPropDef mediaObjDef Height
+test GetPropertyDefL sizePropDef imageObjDef Size
+test GetPropertyDefL modelPropDef imageObjDef Model
+
+test NewObjectL image0 imageObjDef KL
+test SetUriL image0 e:\testing\data\TEST_IMAGE16.jpg
+test AddTimePropertyL image0 creationDatePropDef 20071130:235959.999999
+test AddTimePropertyL image0 lastModDatePropDef 20081130:235959.999999
+test AddUint32PropertyL image0 sizePropDef 999999
+test AddUint8PropertyL image0 originPropDef ECamera
+test AddUint16PropertyL image0 widthPropDef 200
+test AddUint16PropertyL image0 heightPropDef 100
+test AddTextPropertyL image0 modelPropDef "NModel"
+
+test NewObjectL image1 imageObjDef KL
+test SetUriL image1 e:\testing\data\TEST_IMAGE17.jpg
+test AddTimePropertyL image1 creationDatePropDef 20081130:235959.999999
+test AddTimePropertyL image1 lastModDatePropDef 20090000:000000.000000
+test AddUint32PropertyL image1 sizePropDef 999999
+test AddUint8PropertyL image1 originPropDef EDownloaded
+test AddUint16PropertyL image1 widthPropDef 200
+test AddUint16PropertyL image1 heightPropDef 100
+test AddTextPropertyL image1 modelPropDef "NModel"
+
+test NewObjectL image2 imageObjDef KL
+test SetUriL image2 e:\testing\data\TEST_IMAGE18.jpg
+test AddTimePropertyL image2 creationDatePropDef 20080001:000000.000000
+test AddTimePropertyL image2 lastModDatePropDef 20090000:000000.000001
+test AddUint32PropertyL image2 sizePropDef 999999
+test AddUint8PropertyL image2 originPropDef ESideLoaded
+test AddUint16PropertyL image2 widthPropDef 200
+test AddUint16PropertyL image2 heightPropDef 100
+test AddTextPropertyL image2 modelPropDef "NModel"
+
+test NewObjectL image3 imageObjDef KL
+test SetUriL image3 e:\testing\data\TEST_IMAGE39.jpg
+test AddTimePropertyL image3 creationDatePropDef 20091130:235959.999999
+test AddTimePropertyL image3 lastModDatePropDef 20091130:235959.999999
+test AddUint32PropertyL image3 sizePropDef 999999
+test AddUint8PropertyL image3 originPropDef EDownloaded
+test AddUint16PropertyL image3 widthPropDef 200
+test AddUint16PropertyL image3 heightPropDef 100
+test AddTextPropertyL image3 modelPropDef "ModelN"
+
+test AddObjectsL image0 2
+test AddObjectsL image2 2
+
+test NewObjectQueryL rootCond defaultNs DistinctValues Image Object
+
+test AddPropertyConditionL modelPropCond rootCond modelPropDef TextCompare BeginsWith N
+test AppendOrderRuleL ESortAscending EOrderRuleTypeProperty modelPropDef
+test AddPropertyFilterL modelPropDef
+
+test SetObjectQueryResultL { image0 image1 image2 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveObjectsL KSync KById image0 2
+test RemoveObjectsL KSync KById image2 2
+
+[Endtest]
+
+[Test]
+title Query 15: objects with freetexts with freetext contains some text
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+// Add 4 video objects to DB  
+test GetObjectDefL imageObjDef defaultNs Image
+test GetObjectDefL videoObjDef defaultNs Video
+test GetObjectDefL objDef defaultNs Object
+test GetObjectDefL mediaObjDef defaultNs MediaObject
+
+test GetPropertyDefL originPropDef objDef Origin
+
+test GetPropertyDefL creationDatePropDef imageObjDef CreationDate
+test GetPropertyDefL lastModDatePropDef imageObjDef LastModifiedDate
+
+
+
+test GetPropertyDefL widthPropDef mediaObjDef Width
+test GetPropertyDefL heightPropDef mediaObjDef Height
+test GetPropertyDefL sizePropDef imageObjDef Size
+test GetPropertyDefL modelPropDef imageObjDef Model
+
+test NewObjectL image0 imageObjDef KL
+test SetUriL image0 e:\testing\data\TEST_IMAGE16.jpg
+test AddTimePropertyL image0 creationDatePropDef 20071130:235959.999999
+test AddTimePropertyL image0 lastModDatePropDef 20081130:235959.999999
+test AddUint32PropertyL image0 sizePropDef 999999
+test AddUint8PropertyL image0 originPropDef ECamera
+test AddUint16PropertyL image0 widthPropDef 200
+test AddUint16PropertyL image0 heightPropDef 100
+
+test AddFreeTextL image0 cat
+
+test NewObjectL image1 imageObjDef KL
+test SetUriL image1 e:\testing\data\TEST_IMAGE17.jpg
+test AddTimePropertyL image1 creationDatePropDef 20081130:235959.999999
+test AddTimePropertyL image1 lastModDatePropDef 20090000:000000.000000
+test AddUint32PropertyL image1 sizePropDef 999999
+test AddUint8PropertyL image1 originPropDef EDownloaded
+test AddUint16PropertyL image1 widthPropDef 200
+test AddUint16PropertyL image1 heightPropDef 100
+
+test AddFreeTextL image1 cata
+
+test NewObjectL image2 imageObjDef KL
+test SetUriL image2 e:\testing\data\TEST_IMAGE18.jpg
+test AddTimePropertyL image2 creationDatePropDef 20080001:000000.000000
+test AddTimePropertyL image2 lastModDatePropDef 20090000:000000.000001
+test AddUint32PropertyL image2 sizePropDef 999999
+test AddUint8PropertyL image2 originPropDef ESideLoaded
+test AddUint16PropertyL image2 widthPropDef 200
+test AddUint16PropertyL image2 heightPropDef 100
+
+test AddFreeTextL image2 acat
+
+test NewObjectL image3 imageObjDef KL
+test SetUriL image3 e:\testing\data\TEST_IMAGE39.jpg
+test AddTimePropertyL image3 creationDatePropDef 20091130:235959.999999
+test AddTimePropertyL image3 lastModDatePropDef 20091130:235959.999999
+test AddUint32PropertyL image3 sizePropDef 999999
+test AddUint8PropertyL image3 originPropDef EDownloaded
+test AddUint16PropertyL image3 widthPropDef 200
+test AddUint16PropertyL image3 heightPropDef 100
+
+test AddFreeTextL image3 TestFreeText3
+
+test AddObjectsL image0 4
+
+
+test NewObjectQueryL rootCond defaultNs ObjectWithFreetexts Object Object
+test AddObjectConditionL objCond rootCond ObjectConditionCompare FreeTextContains cat
+
+test SetObjectQueryResultL { image0 image1 image2 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveObjectsL KSync KById image0 2
+test RemoveObjectsL KSync KById image2 2
+
+
+[Endtest]
+
+[Test]
+title Query 16: 5 newest objects, sort by creation date, limit to 5
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+// Add 6 image objects and 1 video object to DB
+test GetObjectDefL imageObjDef defaultNs Image
+test GetObjectDefL videoObjDef defaultNs Video
+test GetObjectDefL objDef defaultNs Object
+test GetObjectDefL mediaObjDef defaultNs MediaObject
+
+test GetPropertyDefL originPropDef objDef Origin
+
+test GetPropertyDefL creationDatePropDef imageObjDef CreationDate
+test GetPropertyDefL lastModDatePropDef imageObjDef LastModifiedDate
+
+
+
+test GetPropertyDefL widthPropDef mediaObjDef Width
+test GetPropertyDefL heightPropDef mediaObjDef Height
+test GetPropertyDefL sizePropDef imageObjDef Size
+test GetPropertyDefL modelPropDef imageObjDef Model
+
+test NewObjectL image0 imageObjDef KL
+test SetUriL image0 e:\testing\data\TEST_IMAGE16.jpg
+test AddTimePropertyL image0 creationDatePropDef 20171130:235959.999999
+test AddTimePropertyL image0 lastModDatePropDef 20081130:235959.999999
+test AddUint32PropertyL image0 sizePropDef 999999
+test AddUint8PropertyL image0 originPropDef ECamera
+test AddUint16PropertyL image0 widthPropDef 200
+test AddUint16PropertyL image0 heightPropDef 100
+test AddTextPropertyL image0 modelPropDef "NModel"
+test AddFreeTextL image0 cat
+
+test NewObjectL image1 imageObjDef KL
+test SetUriL image1 e:\testing\data\TEST_IMAGE17.jpg
+test AddTimePropertyL image1 creationDatePropDef 20181130:235959.999999
+test AddTimePropertyL image1 lastModDatePropDef 20090000:000000.000000
+test AddUint32PropertyL image1 sizePropDef 999999
+test AddUint8PropertyL image1 originPropDef EDownloaded
+test AddUint16PropertyL image1 widthPropDef 200
+test AddUint16PropertyL image1 heightPropDef 100
+test AddTextPropertyL image1 modelPropDef "NModel"
+test AddFreeTextL image1 cata
+
+test NewObjectL image2 imageObjDef KL
+test SetUriL image2 e:\testing\data\TEST_IMAGE18.jpg
+test AddTimePropertyL image2 creationDatePropDef 20180001:000000.000000
+test AddTimePropertyL image2 lastModDatePropDef 20090000:000000.000001
+test AddUint32PropertyL image2 sizePropDef 999999
+test AddUint8PropertyL image2 originPropDef ESideLoaded
+test AddUint16PropertyL image2 widthPropDef 200
+test AddUint16PropertyL image2 heightPropDef 100
+test AddTextPropertyL image2 modelPropDef "NModel"
+test AddFreeTextL image2 acat
+
+test NewObjectL image3 imageObjDef KL
+test SetUriL image3 e:\testing\data\TEST_IMAGE39.jpg
+test AddTimePropertyL image3 creationDatePropDef 20191130:235959.999999
+test AddTimePropertyL image3 lastModDatePropDef 20091130:235959.999999
+test AddUint32PropertyL image3 sizePropDef 999999
+test AddUint8PropertyL image3 originPropDef EDownloaded
+test AddUint16PropertyL image3 widthPropDef 200
+test AddUint16PropertyL image3 heightPropDef 100
+test AddTextPropertyL image3 modelPropDef "ModelN"
+test AddFreeTextL image3 TestFreeText3
+
+test NewObjectL image4 imageObjDef KL
+test SetUriL image4 e:\testing\data\TEST_IMAGE49.jpg
+test AddTimePropertyL image4 creationDatePropDef 20191130:235959.999999
+test AddTimePropertyL image4 lastModDatePropDef 20091130:235959.999999
+test AddUint32PropertyL image4 sizePropDef 999999
+test AddUint8PropertyL image4 originPropDef EDownloaded
+test AddUint16PropertyL image4 widthPropDef 200
+test AddUint16PropertyL image4 heightPropDef 100
+test AddTextPropertyL image4 modelPropDef "ModelN"
+test AddFreeTextL image4 TestFreeText3
+
+test NewObjectL image5 imageObjDef KL
+test SetUriL image5 e:\testing\data\TEST_IMAGE59.jpg
+test AddTimePropertyL image5 creationDatePropDef 20161130:235959.999999
+test AddTimePropertyL image5 lastModDatePropDef 20091130:235959.999999
+test AddUint32PropertyL image5 sizePropDef 999999
+test AddUint8PropertyL image5 originPropDef EDownloaded
+test AddUint16PropertyL image5 widthPropDef 200
+test AddUint16PropertyL image5 heightPropDef 100
+test AddTextPropertyL image5 modelPropDef "ModelN"
+test AddFreeTextL image5 TestFreeText3
+
+
+test GetPropertyDefL durationPropDef videoObjDef Duration
+
+test NewObjectL video0 videoObjDef KL
+test SetUriL video0 e:\testing\data\TEST_VIDEO16.mp4
+test AddTimePropertyL video0 creationDatePropDef 20181130:235959.999999
+test AddTimePropertyL video0 lastModDatePropDef 20081130:235959.999999
+test AddReal32PropertyL video0 durationPropDef 30
+test AddUint32PropertyL video0 sizePropDef 999999
+
+test AddObjectsL image0 6
+test AddObjectsL video0 1
+
+test NewObjectQueryL rootCond defaultNs ObjectWithFreetexts Object Object
+test AppendOrderRuleL ESortDescending EOrderRuleTypeProperty creationDatePropDef
+
+test SetObjectQueryResultL { image1 image2 image3 image4 video0 }
+test FindL 5 -1
+waittestclass test
+
+test RemoveObjectsL KSync KById image0 6
+test RemoveObjectsL KSync KById video0 1
+[Endtest]
+
+[Test]
+title Query 17: all Played events, which belongs to object with some ID
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj0 000013 000001
+test AddObjectL obj0
+
+test NewObjectL obj1 videoObjDef KL
+test AddTimePropertyL obj1 creationDatePropDef0 20081130:235959.999999
+test AddTimePropertyL obj1 lastModDatePropDef0 20081130:235959.999999
+test SetGuidL EObject obj1 000013 000002
+test AddObjectL obj1
+
+test GetEventDefL createdEventDef defaultNs Created
+test NewEventL event0 obj0 createdEventDef TestSource TestParticipant 20081130:235959.999999 KL
+test GetEventDefL deletedEventDef defaultNs Deleted
+test NewEventL event1 obj0 deletedEventDef TestSource TestParticipant 20081130:235959.999999 KLC
+test GetEventDefL playedEventDef defaultNs Played
+test NewEventL event2 obj0 playedEventDef TestSource TestParticipant 20081130:235959.999999 KL
+test NewEventL event3 obj1 playedEventDef TestSource TestParticipant 20081130:235959.999999 KLC
+test GetEventDefL editedEventDef defaultNs Edited
+test NewEventL event4 obj1 editedEventDef TestSource TestParticipant 20081130:235959.999999 KL
+test GetEventDefL sentEventDef defaultNs Sent
+test NewEventL event5 obj1 sentEventDef TestSource TestParticipant 20081130:235959.999999 KLC
+test GetEventDefL receivedEventDef defaultNs Received
+test NewEventL event6 obj1 receivedEventDef TestSource TestParticipant 20081130:235959.999999 KL
+loop 7
+test BelongsToSessionL EEvent LOOP_COUNTER EFalse
+test InDatabaseL EEvent LOOP_COUNTER EFalse
+test AddEventL LOOP_COUNTER
+test BelongsToSessionL EEvent LOOP_COUNTER ETrue
+test SessionL EEvent LOOP_COUNTER
+test InDatabaseL EEvent LOOP_COUNTER ETrue
+endloop
+
+
+test NewEventQueryL rootCond defaultNs Item
+
+test AddEventConditionL eventCond rootCond EventDef Played
+test ObjectConditionsL objectCondition eventCond
+test AddObjectConditionL objCond objectCondition Object obj1 1
+
+test SetEventQueryResultL { event3 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveEventsL KSync event0 3
+request EEventsAsyncRemoved
+test RemoveEventsL KAsync event3 4
+wait EEventsAsyncRemoved
+release EEventsAsyncRemoved
+test RemoveObjectL obj0 KById
+test RemoveObjectL obj1 KById
+delete test
+[Endtest]
+
+[Test]
+title Query 18: all IsVersionOf relations, which belongs to video objects and parameter is not equal to 
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+// Add 4 video objects to DB  
+test GetObjectDefL videoObjDef defaultNs Video
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\TEST_VIDEO12.mp4
+test GetPropertyDefL creationDatePropDef0 videoObjDef CreationDate
+test AddTimePropertyL obj0 creationDatePropDef0 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef0 videoObjDef LastModifiedDate
+test AddTimePropertyL obj0 lastModDatePropDef0 20081130:235959.999999
+test NewObjectL obj1 videoObjDef KL
+test SetUriL obj1 e:\testing\data\TEST_VIDEO13.mp4
+test GetPropertyDefL creationDatePropDef1 videoObjDef CreationDate
+test AddTimePropertyL obj1 creationDatePropDef1 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef1 videoObjDef LastModifiedDate
+test AddTimePropertyL obj1 lastModDatePropDef1 20081130:235959.999999
+test NewObjectL obj2 videoObjDef KL
+test SetUriL obj2 e:\testing\data\TEST_VIDEO14.mp4
+test GetPropertyDefL creationDatePropDef2 videoObjDef CreationDate
+test AddTimePropertyL obj2 creationDatePropDef2 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef2 videoObjDef LastModifiedDate
+test AddTimePropertyL obj2 lastModDatePropDef2 20081130:235959.999999
+test NewObjectL obj3 videoObjDef KL
+test SetUriL obj3 e:\testing\data\TEST_VIDEO15.mp4
+test GetPropertyDefL creationDatePropDef3 videoObjDef CreationDate
+test AddTimePropertyL obj3 creationDatePropDef3 20081130:235959.999999
+test GetPropertyDefL lastModDatePropDef3 videoObjDef LastModifiedDate
+test AddTimePropertyL obj3 lastModDatePropDef3 20081130:235959.999999
+test AddObjectsL obj0 4
+
+test GetRelationDefL relDefContains defaultNs Contains
+test GetRelationDefL isVersionOfRelDef defaultNs IsVersionOf
+test NewRelationL rel0 obj0 isVersionOfRelDef obj1 1 KL
+test NewRelationL rel1 obj0 isVersionOfRelDef obj2 1 KL
+test NewRelationL rel2 obj2 isVersionOfRelDef obj3 0 KLC
+loop 3
+test AddRelationL LOOP_COUNTER
+endloop
+
+// Query
+test NewRelationQueryL rootCond defaultNs Item Video Object
+
+test AddRelationConditionL isVersionOfRelCond rootCond Left RelationDefRange IsVersionOf NotEqual 0 0
+
+test LeftL leftRelCond isVersionOfRelCond
+test AddObjectConditionL objCond leftRelCond ObjectDef Video
+
+test SetRelationQueryResultL { rel0 rel1 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveRelationsL KSync rel0 3
+test RemoveObjectsL KSync KById obj0 4
+delete test
+[Endtest]
+
+[Test]
+title Query 19: query the videos that are modified in the last 30 seconds
+create MdETestScripter test
+waittestclass test
+test GetDefaultNamespaceDefL defaultNs
+// Add 3 video objects to DB
+test GetObjectDefL videoObjDef defaultNs Video
+
+test GetPropertyDefL creationDatePropDef videoObjDef CreationDate
+test GetPropertyDefL lastModDatePropDef videoObjDef LastModifiedDate
+
+test NewObjectL obj0 videoObjDef KL
+test SetUriL obj0 e:\testing\data\TEST_VIDEO19_1.mp4
+test AddTimePropertyL obj0 creationDatePropDef 20090101:000000.000000
+test AddTimePropertyL obj0 lastModDatePropDef 20090809:115000.000000
+
+test NewObjectL obj1 videoObjDef KL
+test SetUriL obj1 e:\testing\data\TEST_VIDEO19_2.mp4
+test AddTimePropertyL obj1 creationDatePropDef 20090101:000000.000000
+test AddTimePropertyL obj1 lastModDatePropDef 20090808:115000.000000
+
+test NewObjectL obj2 videoObjDef KL
+test SetUriL obj2 e:\testing\data\TEST_VIDEO19_3.3gp
+test AddTimePropertyL obj2 creationDatePropDef 20090101:000000.000000
+test AddTimePropertyL obj2 lastModDatePropDef 20090809:115020.000000
+
+test AddObjectsL obj0 3
+
+test NewObjectQueryL rootCond defaultNs Item Video Object
+test AddPropertyConditionL propCond rootCond lastModDatePropDef TimeRange Between 20090809:115000.000000 20090809:115030.000000
+
+test SetObjectQueryResultL { obj0 obj2 }
+test FindL -1 -1
+waittestclass test
+
+test RemoveObjectsL KSync KById obj0 3
+delete test
+[Endtest]
+
+// [Test]
+// title Query : TestPopulateDbL
+// create MdETestScripter test
+// waittestclass test
+// test TestPopulateDbL
+// waittestclass test
+// [Endtest]
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/data/mmc/MDETestScripterSchema.mde	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+// TestSchema.mde
+
+namespace http://sw.nokia.com/MdE/TestSchema 0
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/data/mmc/MDETestScripterSchema2.mde	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,18 @@
+// TestSchema2.mde
+
+namespace http://sw.nokia.com/MdE/TestSchema2 0
+
+object http://sw.nokia.com/MdE/TestSchema2 TestObjectType Object 1
+property   TestPropertyBool               0    0        0    min   max
+property   TestPropertyInt8               1    0        1    min   max
+property   TestPropertyUint8              0    0        2    min   max
+property   TestPropertyInt16              1    0        3    min   max
+property   TestPropertyUint16             0    0        4    min   max
+property   TestPropertyInt32              1    0        5    min   max
+property   TestPropertyUint32             0    0        6    min   max
+property   TestPropertyInt64              1    0        7    min   max
+property   TestPropertyReal32             0    0        8    min   max
+property   TestPropertyReal64             1    0        9    min   max
+property   TestPropertyTime               0    0        10   min   20100629163021
+property   TestPropertyText               1    0        11   min   max
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/data/mmc/MdETestScripterImportMetadata.mde	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,134 @@
+object http://sw.nokia.com/MdE Video "e:\testing\data\test2video1.3gp" 4184041685
+property Origin 0
+property Size 66192
+property TimeOffset 120
+property CreationDate 20071217163916
+property LastModifiedDate 20071217143916
+property ItemType "video/H263-2000"
+property Bitrate 23
+property Width 176
+property Height 144
+property Duration 21
+property ReleaseDate 20071217163916
+property CaptureDate 20071217163916
+property Framerate 7
+
+object http://sw.nokia.com/MdE Video "e:\testing\data\test2video2.mp4" 4184041685
+property Origin 0
+property Size 733064
+property TimeOffset 120
+property CreationDate 20071217163916
+property LastModifiedDate 20071217143916
+property Bitrate 288
+property Width 320
+property Height 240
+property Duration 20
+property ReleaseDate 20071217163916
+property CaptureDate 20071217163916
+property Framerate 14
+
+object http://sw.nokia.com/MdE Video "e:\testing\data\test3video1.3gp" 4184041685
+property Origin 0
+property Size 66192
+property TimeOffset 120
+property CreationDate 20071217163916
+property LastModifiedDate 20071217143916
+property ItemType "video/H263-2000"
+property Bitrate 23
+property Width 176
+property Height 144
+property Duration 21
+property ReleaseDate 20071217163916
+property CaptureDate 20071217163916
+property Framerate 7
+
+object http://sw.nokia.com/MdE Video "e:\testing\data\test3video2.mp4" 4184041685
+property Origin 0
+property Size 733064
+property TimeOffset 120
+property CreationDate 20071217163916
+property LastModifiedDate 20071217143916
+property Bitrate 288
+property Width 320
+property Height 240
+property Duration 20
+property ReleaseDate 20071217163916
+property CaptureDate 20071217163916
+property Framerate 14
+
+object http://sw.nokia.com/MdE Video "e:\testing\data\test4video1.3gp" 4184041685
+property Origin 0
+property Size 66192
+property TimeOffset 120
+property CreationDate 20071217163916
+property LastModifiedDate 20071217143916
+property ItemType "video/H263-2000"
+property Bitrate 23
+property Width 176
+property Height 144
+property Duration 21
+property ReleaseDate 20071217163916
+property CaptureDate 20071217163916
+property Framerate 7
+
+object http://sw.nokia.com/MdE Video "e:\testing\data\test4video2" 4184041685
+property Origin 0
+property Size 733064
+property TimeOffset 120
+property CreationDate 20071217163916
+property LastModifiedDate 20071217143916
+property Bitrate 288
+property Width 320
+property Height 240
+property Duration 20
+property ReleaseDate 20071217163916
+property CaptureDate 20071217163916
+property Framerate 14
+
+object http://sw.nokia.com/MdE Video "e:\testing\data\test26video1.3gp" 4184041685
+property Origin 0
+property Size 66192
+property TimeOffset 120
+property CreationDate 20080808000000
+property LastModifiedDate 20080808000000
+property ItemType "video/H263-2000"
+property Bitrate 23
+property Size 12345678
+property Rating 4
+property Width 176
+property Height 144
+property Duration 21
+property ReleaseDate 20080808000000
+property CaptureDate 20080808000000
+property Framerate 7
+property DRM 0
+
+object http://sw.nokia.com/MdE Video "e:\testing\data\testvideo1.3gp" 4184041685
+property Origin 0
+property Size 66192
+property TimeOffset 120
+property CreationDate 20071217163916
+property LastModifiedDate 20071217143916
+property ItemType "video/H263-2000"
+property Bitrate 23
+property Width 176
+property Height 144
+property Duration 21
+property ReleaseDate 20071217163916
+property CaptureDate 20071217163916
+property Framerate 7
+
+object http://sw.nokia.com/MdE Video "e:\testing\data\testvideo2.mp4" 4184041685
+property Origin 0
+property Size 733064
+property TimeOffset 120
+property CreationDate 20071217163916
+property LastModifiedDate 20071217143916
+property Bitrate 288
+property Width 320
+property Height 240
+property Duration 20
+property ReleaseDate 20071217163916
+property CaptureDate 20071217163916
+property Framerate 14
+ 
\ No newline at end of file
Binary file mds_plat/metadata_engine_api/tsrc/data/mmc/test26video1.3gp has changed
Binary file mds_plat/metadata_engine_api/tsrc/data/mmc/test2video1.3gp has changed
Binary file mds_plat/metadata_engine_api/tsrc/data/mmc/test2video2.mp4 has changed
Binary file mds_plat/metadata_engine_api/tsrc/data/mmc/test3video1.3gp has changed
Binary file mds_plat/metadata_engine_api/tsrc/data/mmc/test3video2.mp4 has changed
Binary file mds_plat/metadata_engine_api/tsrc/data/mmc/test4video1.3gp has changed
Binary file mds_plat/metadata_engine_api/tsrc/data/mmc/test4video2 has changed
Binary file mds_plat/metadata_engine_api/tsrc/data/mmc/testvideo1.3gp has changed
Binary file mds_plat/metadata_engine_api/tsrc/data/mmc/testvideo2.mp4 has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/group/MdETestScripter.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET          MdETestScripter.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E3
+
+CAPABILITY      ALL -TCB
+VENDORID        VID_DEFAULT
+
+DEFFILE         MdETestScripter.DEF
+
+SOURCEPATH      ../src
+SOURCE          MdETestScripter.cpp
+SOURCE          MdETestScripterBlocks.cpp
+SOURCE          MdETestScripterEditCommands.cpp
+SOURCE          MdETestScripterSchemaCommands.cpp
+SOURCE          MdETestScripterQueryCommands.cpp
+SOURCE          MdETestScripterAO.cpp
+
+USERINCLUDE     ../inc 
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         efsrv.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+LIBRARY         mdccommon.lib
+LIBRARY         mdeclient.lib
+LIBRARY         PlatformEnv.lib
+LIBRARY	        bafl.lib
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/group/MdETestScripter.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,47 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+; Installation file for API test
+
+; Languages
+&EN
+
+; Header
+#{"MdETestScripter"},(0x101FB3E3),1,0,1,TYPE=SA
+
+; Localised Vendor name
+%{"Nokia-EN"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Files
+"\epoc32\release\armv5\urel\MdETestScripter.dll"      -"C:\sys\bin\MdETestScripter.dll"
+"..\init\MdETestScripter.ini"      -"C:\testframework\MdETestScripter.ini"
+"..\conf\MdETestScripter.cfg"      -"C:\testframework\MdETestScripter.cfg"
+
+"..\data\mmc\MdETestScripterImportMetadata.mde"      -"E:\testing\data\MdETestScripterImportMetadata.mde"
+"..\data\mmc\MdETestScripterSchema.mde"      -"E:\testing\data\MdETestScripterSchema.mde"
+"..\data\mmc\MdETestScripterSchema2.mde"      -"E:\testing\data\MdETestScripterSchema2.mde"
+
+"..\data\mmc\test2video1.3gp"      -"E:\testing\data\test2video1.3gp"
+"..\data\mmc\test2video2.mp4"      -"E:\testing\data\test2video2.mp4"
+"..\data\mmc\test3video1.3gp"      -"E:\testing\data\test3video1.3gp"
+"..\data\mmc\test3video2.mp4"      -"E:\testing\data\test3video2.mp4"
+"..\data\mmc\test4video1.3gp"      -"E:\testing\data\test4video1.3gp"
+"..\data\mmc\test4video2"      -"E:\testing\data\test4video2"
+"..\data\mmc\test26video1.3gp"      -"E:\testing\data\test26video1.3gp"
+"..\data\mmc\testvideo1.3gp"      -"E:\testing\data\testvideo1.3gp"
+"..\data\mmc\testvideo2.mp4"      -"E:\testing\data\testvideo2.mp4"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,44 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+MdETestScripter.mmp
+
+PRJ_TESTEXPORTS
+../conf/MdETestScripter.cfg /epoc32/winscw/c/TestFramework/MdETestScripter.cfg
+../init/MdETestScripter.ini /epoc32/winscw/c/TestFramework/MdETestScripter.ini
+../data/mmc/MdETestScripterImportMetadata.mde /epoc32/winscw/c/data/MdETestScripterImportMetadata.mde
+../data/mmc/MdETestScripterSchema.mde /epoc32/winscw/c/data/MdETestScripterSchema.mde
+../data/mmc/MdETestScripterSchema2.mde /epoc32/winscw/c/data/MdETestScripterSchema2.mde
+
+../data/mmc/test2video1.3gp /epoc32/WINSCW/C/Data/test2video1.3gp
+../data/mmc/test2video2.mp4 /epoc32/WINSCW/C/Data/test2video2.mp4
+../data/mmc/test3video1.3gp /epoc32/WINSCW/C/Data/test3video1.3gp
+../data/mmc/test3video2.mp4 /epoc32/WINSCW/C/Data/test3video2.mp4
+../data/mmc/test4video1.3gp /epoc32/WINSCW/C/Data/test4video1.3gp
+../data/mmc/test4video2 /epoc32/WINSCW/C/Data/test4video2
+../data/mmc/test26video1.3gp /epoc32/WINSCW/C/Data/test26video1.3gp
+../data/mmc/testvideo1.3gp /epoc32/WINSCW/C/Data/testvideo1.3gp
+../data/mmc/testvideo2.mp4 /epoc32/WINSCW/C/Data/testvideo2.mp4
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/inc/MdETestScripter.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,537 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+#ifndef MDETESTSCRIPTER_H
+#define MDETESTSCRIPTER_H
+
+//  INCLUDES
+#include <e32cmn.h>
+#include <StifLogger.h>
+#include <TestScripterInternal.h>
+#include <StifTestModule.h>
+#include <mdesession.h>
+#include <mdequery.h>
+
+// CONSTANTS
+const TInt KPathPrefixLength( 2 );
+
+const TInt KLast = -1;
+
+const TInt KById = 0;
+const TInt KByUri = 1;
+const TInt KByGuid = 2;
+const TInt KByIds = 3;
+const TInt KByDef = 4;
+const TInt KByIndex = 5;
+
+const TInt KL = 0;
+const TInt KLC = 1;
+
+const TInt KAsync = 0;
+const TInt KSync = 1;
+
+const TInt ESession = 0;
+const TInt EObjectDef = 1;
+const TInt ERelationDef = 2;
+const TInt EPropertyDef = 3;
+const TInt EEventDef = 4;
+const TInt ENamespaceDef = 5;
+const TInt EObject = 6;
+const TInt ERelation = 7;
+const TInt EProperty = 8;
+const TInt EEvent = 9;
+
+// MACROS
+_LIT( KMdETestScripter, "MdETestScripter" );
+#if ( defined (__WINS__) || defined (__WINSCW__) )
+_LIT( KMdETestDataPath, "" );
+#else 
+_LIT( KMdETestDataPath, "\\testing" );
+#endif
+
+_LIT( KMdETestScripterLogPath, "\\logs\\testframework\\MdETestScripter\\" ); 
+
+// Log file
+_LIT( KMdETestScripterLogFile, "MdETestScripter.txt" ); 
+_LIT( KMdETestScripterLogFileWithTitle, "MdETestScripter_[%S].txt" );
+
+// Events
+// Events for schema
+_LIT( KMdESchemaModified, "ESchemaModified" );
+
+// Events for async request
+_LIT( KMdEItemsAsyncAdd, "EItemsAsyncAdd" );
+_LIT( KMdEObjectsAsyncAdd, "EObjectsAsyncAdd" );
+_LIT( KMdERelationsAsyncAdd, "ERelationsAsyncAdd" );
+_LIT( KMdEEventsAsyncAdd, "EEventsAsyncAdd" );
+
+_LIT( KMdEItemsAsyncUpdate, "EItemsAsyncUpdate" );
+_LIT( KMdEObjectsAsyncUpdate, "EObjectsAsyncUpdate" );
+_LIT( KMdERelationsAsyncUpdate, "ERelationsAsyncUpdate" );
+_LIT( KMdEEventsAsyncUpdate, "EEventsAsyncUpdate" );
+
+_LIT( KMdEObjectsAsyncRemoved, "EObjectsAsyncRemoved" );
+_LIT( KMdERelationsAsyncRemoved, "ERelationsAsyncRemoved" );
+_LIT( KMdEEventsAsyncRemoved, "EEventsAsyncRemoved" );
+
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class CMdETestScripter;
+class CMdESession;
+class CMdENamespaceDef;
+class CMdEObject;
+class CMdEInstanceItem;
+class CMdEQuery;
+class CMdELogicCondition;
+class CMdETestScripterAO;
+
+// DATA TYPES
+
+// CLASS DECLARATION
+
+/**
+*  CMdETestScripter test class for STIF Test Framework TestScripter.
+*  ?other_description_lines
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+NONSHARABLE_CLASS(CMdETestScripter) : public CScriptBase,
+                                      public MMdESchemaObserver,
+                                      public MMdEObjectObserver,
+                                      public MMdEObjectPresentObserver,
+                                      public MMdERelationObserver,
+                                      public MMdERelationItemObserver,
+                                      public MMdERelationPresentObserver,
+                                      public MMdESessionObserver,
+                                      public MMdEEventObserver,
+                                      public MMdEQueryObserver
+    {
+    friend class CMdETestScripterAO;
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CMdETestScripter* NewL( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CMdETestScripter();
+
+    public: // New functions
+
+    public: // Functions from base classes
+        virtual TInt RunMethodL( CStifItemParser& aItem );
+
+    protected:  // New functions
+
+
+    protected:  // Functions from base classes
+
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CMdETestScripter( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Frees all resources allocated from test methods.
+        * @since ?Series60_version
+        */
+        void Delete();
+        
+        template <class T> T* SanitizeArrayIndexL(
+    		RPointerArray<T>& aArray, const CDesCArrayFlat& aNameArray, 
+    		CStifItemParser& aItem );
+        CMdEInstanceItem* GetInstanceItemByArrayIndexL(
+            TInt aMode, CStifItemParser& aItem );
+        void CheckTMdEObjectL( const TMdEObject& aTObject, const CMdEObject& aObject );
+        void CheckTMdERelationL( const TMdERelation& aTRelation, const CMdERelation& aRelation );
+        template <class T1, class T2> void CheckTInstanceL( const T1& aT1, const T2& aT2 );
+        void CheckTMdEObjectArrayL(
+            const RArray<TMdEObject>& aTObjects, TInt objIndex, TInt aCount );
+        void CheckTMdERelationArrayL(
+            const RArray<TMdERelation>& aTRelations, const TInt aObjIndex, const TInt aCount );
+        template <class T> void CheckTItemIdArrayL(
+            const RArray<TItemId>& aTItemIds, const RPointerArray<T>& aArray,
+            const TInt aIndex, const TInt aCount );
+        TInt CheckAsyncResultArrayL( TEventIf aEvent );
+        void FormInstanceItemArrayL(
+            CStifItemParser& aItem, RPointerArray<CMdEInstanceItem>& aItemArray ) const;
+
+        /**
+        * Test methods are listed below. 
+        */
+
+        // Observer add/remove test primitives
+        virtual TInt AddSchemaObserverL( CStifItemParser& aItem );
+        virtual TInt RemoveSchemaObserverL( CStifItemParser& aItem );
+        virtual TInt AddObjectObserverL( CStifItemParser& aItem );
+        virtual TInt RemoveObjectObserverL( CStifItemParser& aItem );
+        virtual TInt AddObjectPresentObserverL( CStifItemParser& aItem );
+        virtual TInt RemoveObjectPresentObserverL( CStifItemParser& aItem );
+        virtual TInt AddRelationObserverL( CStifItemParser& aItem );
+        virtual TInt RemoveRelationObserverL( CStifItemParser& aItem );
+        virtual TInt AddRelationItemObserverL( CStifItemParser& aItem );
+        virtual TInt RemoveRelationItemObserverL( CStifItemParser& aItem );
+        virtual TInt AddRelationPresentObserverL( CStifItemParser& aItem );
+        virtual TInt RemoveRelationPresentObserverL( CStifItemParser& aItem );
+        virtual TInt AddEventObserverL( CStifItemParser& aItem );
+        virtual TInt RemoveEventObserverL( CStifItemParser& aItem );
+
+        // Notification resulated test primitives
+        virtual TInt VerifyTItemIdsL( CStifItemParser& aItem );
+        virtual TInt VerifyMdERelationsL( CStifItemParser& aItem );
+        virtual TInt VerifyObserverNotificationTypeL( CStifItemParser& aItem );
+
+        // Metadata/schema/namespace test primitives.
+        virtual TInt ObjectDefCountL( CStifItemParser& aItem );
+        virtual TInt ObjectDefL( CStifItemParser& aItem );
+        virtual TInt GetObjectDefL( CStifItemParser& aItem );
+        virtual TInt RelationDefCountL( CStifItemParser& aItem );
+        virtual TInt RelationDefL( CStifItemParser& aItem );
+        virtual TInt GetRelationDefL( CStifItemParser& aItem );
+        virtual TInt EventDefCountL( CStifItemParser& aItem );
+        virtual TInt EventDefL( CStifItemParser& aItem );
+        virtual TInt GetEventDefL( CStifItemParser& aItem );
+
+        virtual TInt ExportMetadataL( CStifItemParser& aItem );
+        virtual TInt ImportMetadataL( CStifItemParser& aItem );
+        virtual TInt ImportSchemaL( CStifItemParser& aItem );
+        virtual TInt NamespaceDefCountL( CStifItemParser& aItem );
+        virtual TInt NamespaceDefL( CStifItemParser& aItem );
+        virtual TInt GetNamespaceDefL( CStifItemParser& aItem );
+        virtual TInt ResetNamespaceDefArray( CStifItemParser& aItem );
+        virtual TInt GetDefaultNamespaceDefL( CStifItemParser& aItem );
+        virtual TInt LoadSchemaL( CStifItemParser& aItem );
+        virtual TInt EngineSessionL( CStifItemParser& aItem );
+        virtual TInt GetSchemaVersionL( CStifItemParser& aItem );
+        virtual TInt SetObjectToPresentByGuidL( CStifItemParser& aItem );
+        
+        // Item / InstanceItem test primitives.
+        virtual TInt BelongsToSessionL( CStifItemParser& aItem );
+        virtual TInt SessionL( CStifItemParser& aItem );
+        virtual TInt InDatabaseL( CStifItemParser& aItem );
+        virtual TInt AddItemsL( CStifItemParser& aItem );
+        virtual TInt UpdateItemsL( CStifItemParser& aItem );
+
+        // Definition test primitives.
+        virtual TInt AddRelationDefL( CStifItemParser& aItem );
+        virtual TInt AddEventDefL( CStifItemParser& aItem );
+        virtual TInt PropertyDefCountL( CStifItemParser& aItem );
+        virtual TInt PropertyDefL( CStifItemParser& aItem );
+        virtual TInt GetPropertyDefL( CStifItemParser& aItem );
+        virtual TInt MandatoryL( CStifItemParser& aItem );
+        virtual TInt MinInt32ValueL( CStifItemParser& aItem );
+        virtual TInt MaxInt32ValueL( CStifItemParser& aItem );
+        virtual TInt MinUint32ValueL( CStifItemParser& aItem );
+        virtual TInt MaxUint32ValueL( CStifItemParser& aItem );
+        virtual TInt MinInt64ValueL( CStifItemParser& aItem );
+        virtual TInt MaxInt64ValueL( CStifItemParser& aItem );
+        virtual TInt MinRealValueL( CStifItemParser& aItem );
+        virtual TInt MaxRealValueL( CStifItemParser& aItem );
+        virtual TInt MinTimeValueL( CStifItemParser& aItem );
+        virtual TInt MaxTimeValueL( CStifItemParser& aItem );
+        virtual TInt MinTextLengthL( CStifItemParser& aItem );
+        virtual TInt MaxTextLengthL( CStifItemParser& aItem );
+        virtual TInt CompareL( CStifItemParser& aItem );
+        virtual TInt ParentL( CStifItemParser& aItem );
+        virtual TInt NameL( CStifItemParser& aItem );
+        virtual TInt ReadOnlyL( CStifItemParser& aItem );
+        virtual TInt DefL( CStifItemParser& aItem );
+
+        // Object test primitives.
+        virtual TInt SetDefL( CStifItemParser& aItem );
+        virtual TInt UriL( CStifItemParser& aItem );
+        virtual TInt SetUriL( CStifItemParser& aItem );
+        virtual TInt ConfidentialL( CStifItemParser& aItem );
+        virtual TInt SetConfidentialL( CStifItemParser& aItem );
+        virtual TInt PlaceholderL( CStifItemParser& aItem );
+        virtual TInt SetPlaceholderL( CStifItemParser& aItem );
+        virtual TInt MediaIdL( CStifItemParser& aItem );
+        virtual TInt SetMediaIdL( CStifItemParser& aItem );
+        virtual TInt UsageCountL( CStifItemParser& aItem );
+        virtual TInt GuidL( CStifItemParser& aItem );
+        virtual TInt SetGuidL( CStifItemParser& aItem );
+        virtual TInt OpenForModificationsL( CStifItemParser& aItem );
+        virtual TInt NewObjectL( CStifItemParser& aItem );
+        virtual TInt AddObjectL( CStifItemParser& aItem );
+        virtual TInt AddObjectsL( CStifItemParser& aItem );
+        virtual TInt GetObjectL( CStifItemParser& aItem );
+        virtual TInt GetFullObjectL( CStifItemParser& aItem );
+        virtual TInt CheckObjectL( CStifItemParser& aItem );
+        virtual TInt RemoveObjectL( CStifItemParser& aItem );
+        virtual TInt RemoveObjectsL( CStifItemParser& aItem );
+        virtual TInt RemoveAllObjectsL( CStifItemParser& aItem );
+        virtual TInt OpenObjectL( CStifItemParser& aItem );
+        virtual TInt OpenFullObjectL( CStifItemParser& aItem );
+        virtual TInt CommitObjectL( CStifItemParser& aItem );
+        virtual TInt CommitObjectsL( CStifItemParser& aItem );
+        virtual TInt CancelObjectL( CStifItemParser& aItem );
+
+        virtual TInt PropertyL( CStifItemParser& aItem );
+        virtual TInt PropertyCountL( CStifItemParser& aItem );
+        virtual TInt AddBoolPropertyL( CStifItemParser& aItem );
+        virtual TInt AddInt8PropertyL( CStifItemParser& aItem );
+        virtual TInt AddUint8PropertyL( CStifItemParser& aItem );
+        virtual TInt AddInt16PropertyL( CStifItemParser& aItem );
+        virtual TInt AddUint16PropertyL( CStifItemParser& aItem );
+        virtual TInt AddInt32PropertyL( CStifItemParser& aItem );
+        virtual TInt AddUint32PropertyL( CStifItemParser& aItem );
+        virtual TInt AddInt64PropertyL( CStifItemParser& aItem );
+        virtual TInt AddReal32PropertyL( CStifItemParser& aItem );
+        virtual TInt AddReal64PropertyL( CStifItemParser& aItem );
+        virtual TInt AddTextPropertyL( CStifItemParser& aItem );
+        virtual TInt AddTimePropertyL( CStifItemParser& aItem );
+
+        // Property test primitives.
+        virtual TInt ObjectL( CStifItemParser& aItem );
+        virtual TInt BoolValueL( CStifItemParser& aItem );
+        virtual TInt Int8ValueL( CStifItemParser& aItem );
+        virtual TInt Uint8ValueL( CStifItemParser& aItem );
+        virtual TInt Int16ValueL( CStifItemParser& aItem );
+        virtual TInt Uint16ValueL( CStifItemParser& aItem );
+        virtual TInt Int32ValueL( CStifItemParser& aItem );
+        virtual TInt Uint32ValueL( CStifItemParser& aItem );
+        virtual TInt Int64ValueL( CStifItemParser& aItem );
+        virtual TInt Real32ValueL( CStifItemParser& aItem );
+        virtual TInt Real64ValueL( CStifItemParser& aItem );
+        virtual TInt TimeValueL( CStifItemParser& aItem );
+        virtual TInt TextValueL( CStifItemParser& aItem );
+        virtual TInt SetBoolValueL( CStifItemParser& aItem );
+        virtual TInt SetInt8ValueL( CStifItemParser& aItem );
+        virtual TInt SetUint8ValueL( CStifItemParser& aItem );
+        virtual TInt SetInt16ValueL( CStifItemParser& aItem );
+        virtual TInt SetUint16ValueL( CStifItemParser& aItem );
+        virtual TInt SetInt32ValueL( CStifItemParser& aItem );
+        virtual TInt SetUint32ValueL( CStifItemParser& aItem );
+        virtual TInt SetInt64ValueL( CStifItemParser& aItem );
+        virtual TInt SetReal32ValueL( CStifItemParser& aItem );
+        virtual TInt SetReal64ValueL( CStifItemParser& aItem );
+        virtual TInt SetTimeValueL( CStifItemParser& aItem );
+        virtual TInt SetTextValueL( CStifItemParser& aItem );
+        virtual TInt RemovePropertyL( CStifItemParser& aItem );
+        virtual TInt MovePropertiesL( CStifItemParser& aItem );
+
+        // Free text test primitives.
+        virtual TInt FreeTextCountL( CStifItemParser& aItem );
+        virtual TInt FreeTextL( CStifItemParser& aItem );
+        virtual TInt FreeTextIndexL( CStifItemParser& aItem );
+        virtual TInt AddFreeTextL( CStifItemParser& aItem );
+        virtual TInt RemoveFreeTextL( CStifItemParser& aItem );
+
+        // Relation test primitives.
+        virtual TInt NewRelationL( CStifItemParser& aItem );
+        virtual TInt AddRelationL( CStifItemParser& aItem );
+        virtual TInt LeftObjectIdL( CStifItemParser& aItem );
+        virtual TInt RightObjectIdL( CStifItemParser& aItem );
+        virtual TInt ParameterL( CStifItemParser& aItem );
+        virtual TInt SetParameterL( CStifItemParser& aItem );
+        virtual TInt SetLeftObjectIdL( CStifItemParser& aItem );
+        virtual TInt SetRightObjectIdL( CStifItemParser& aItem );
+        virtual TInt LastModifiedDateL( CStifItemParser& aItem );
+        virtual TInt SetLastModifiedDateL( CStifItemParser& aItem );
+        virtual TInt GetRelationL( CStifItemParser& aItem );
+        virtual TInt UpdateRelationL( CStifItemParser& aItem );
+        virtual TInt RemoveRelationL( CStifItemParser& aItem );
+        virtual TInt RemoveRelationsL( CStifItemParser& aItem );
+
+        // Event test primitives.
+        virtual TInt NewEventL( CStifItemParser& aItem );
+        virtual TInt AddEventL( CStifItemParser& aItem );
+        virtual TInt ObjectIdL( CStifItemParser& aItem );
+        virtual TInt TimeL( CStifItemParser& aItem );
+        virtual TInt SourceL( CStifItemParser& aItem );
+        virtual TInt ParticipantL( CStifItemParser& aItem );
+        virtual TInt GetEventL( CStifItemParser& aItem );
+        virtual TInt RemoveEventL( CStifItemParser& aItem );
+        virtual TInt RemoveEventsL( CStifItemParser& aItem );
+        //[TestMethods] - Do not remove
+
+        // Metadata framework observer callback methods
+        void HandleObjectNotification( CMdESession& aSession, 
+            TObserverNotificationType aType,
+            const RArray<TItemId>& aObjectIdArray );
+        void HandleObjectPresentNotification(CMdESession& aSession, 
+            TBool aPresent, const RArray<TItemId>& aObjectIdArray);
+        void HandleRelationNotification( CMdESession& aSession, 
+            TObserverNotificationType aType,
+            const RArray<TItemId>& aRelationIdArray );
+        void HandleRelationItemNotification(CMdESession& aSession, 
+            TObserverNotificationType aType,
+            const RArray<TMdERelation>& aRelationArray);
+        void HandleRelationPresentNotification(CMdESession& aSession,
+            TBool aPresent, const RArray<TItemId>& aRelationIdArray);
+        void HandleEventNotification( CMdESession& aSession,
+            TObserverNotificationType aType,
+            const RArray<TItemId>& aEventIdArray );
+    	void HandleSessionOpened( CMdESession& aSession, TInt aError );
+    	void HandleSessionError( CMdESession& aSession, TInt aError );
+        void HandleSchemaModified();
+		TInt QueryObjectL( CStifItemParser& aItem );
+		TInt QueryRelationL( CStifItemParser& aItem );
+		TInt QueryEventL( CStifItemParser& aItem );
+
+		TInt TestPopulateDbL( CStifItemParser& aItem );
+		
+private:
+		CMdEObjectDef& GetObjectDefStrL( CStifItemParser& aItem );
+		CMdERelationDef& GetRelationDefStrL( CStifItemParser& aItem );
+		static TQueryResultMode CMdETestScripter::ResultModeL(TDesC& aModeString);
+		static TObjectConditionCompareMethod CompareMethodL( TDesC& aMethodString );
+		static TMdERangeType RangeTypeL( TDesC& aTypeString );
+
+		TInt GetObjectDefIndexL( CStifItemParser& aItem );	
+		TInt GetRelationDefIndexL( CStifItemParser& aItem );
+		TInt GetEventDefIndexL( CStifItemParser& aItem );
+		TInt GetPropertyDefIndexL( CStifItemParser& aItem );
+
+		TInt GetObjectIndexL( CStifItemParser& aItem );
+		TInt GetEventIndexL( CStifItemParser& aItem );
+		TInt GetRelationIndexL( CStifItemParser& aItem );
+		TInt GetPropertyIndexL( CStifItemParser& aItem );
+
+		TInt GetLogicConditionIndexL( CStifItemParser& aItem );
+		TInt GetRelationConditionIndexL( CStifItemParser& aItem );
+
+		void AppendNameL(CDesCArrayFlat* aNameArray, const TDesC& aName)
+			{
+			TInt pos;
+			TBuf<32> name(aName);
+			pos = name.Find(_L("ARRAY_INDEX"));
+			if ( pos != KErrNotFound )
+				{
+				name.SetLength( pos );
+				name.AppendNum( aNameArray->Count() );
+				}
+			if ( aNameArray->Find( name, pos ) )
+				{
+				aNameArray->AppendL( name );
+				}
+			else
+				{ // 
+				iLog->Log( _L( "indentifier = %S already used" ), &name );
+				User::Leave( KErrAlreadyExists );			
+				}						
+			}
+		
+
+public:
+
+		TInt NewObjectQueryL( CStifItemParser& aItem );
+		TInt NewRelationQueryL( CStifItemParser& aItem );
+		TInt NewEventQueryL( CStifItemParser& aItem );
+		TInt AddPropertyFilterL( CStifItemParser& aItem );
+		TInt AppendOrderRuleL( CStifItemParser& aItem );
+		TInt NewLogicConditionL( CStifItemParser& aItem );
+		TInt AddLogicConditionL( CStifItemParser& aItem );		
+		TInt AddObjectConditionL( CStifItemParser& aItem );
+		TInt AddPropertyConditionL( CStifItemParser& aItem );
+		TInt AddRelationConditionL( CStifItemParser& aItem );
+		TInt AddEventConditionL( CStifItemParser& aItem );
+		
+		TInt ObjectConditionsL( CStifItemParser& aItem );
+		
+		TInt RightL( CStifItemParser& aItem );
+		TInt LeftL( CStifItemParser& aItem );
+		TInt SetOperatorL( CStifItemParser& aItem );
+		TInt SetNegateL( CStifItemParser& aItem );
+		
+		TInt FindL( CStifItemParser& aItem );		
+			
+		void HandleQueryCompleted( CMdEQuery& aQuery, TInt aError );
+    	
+    	void HandleQueryNewResults(CMdEQuery& aQuery,
+                                       TInt aFirstNewItemIndex,
+                                       TInt aNewItemCount);
+        TInt SetObjectQueryResultL( CStifItemParser& aItem );
+        TInt SetEventQueryResultL( CStifItemParser& aItem );
+        TInt SetRelationQueryResultL( CStifItemParser& aItem );
+        
+    private:
+        // Data
+        TInt iError;
+
+        RPointerArray<CMdEObjectDef> iObjectDefArray;
+        RPointerArray<CMdERelationDef> iRelationDefArray;
+        RPointerArray<CMdEEventDef> iEventDefArray;
+        RPointerArray<CMdEPropertyDef> iPropertyDefArray;
+        RPointerArray<CMdENamespaceDef> iNamespaceDefArray;
+        
+		RPointerArray<CMdEObject> iObjectArray;
+        RPointerArray<CMdERelation> iRelationArray;
+        RPointerArray<CMdEEvent> iEventArray;
+        RPointerArray<CMdEProperty> iPropertyArray;
+		RPointerArray<CMdELogicCondition> iLogicConditionArray;
+		RPointerArray<CMdERelationCondition> iRelationConditionArray;
+		RPointerArray<CMdEObjectCondition> iObjectConditionArray;
+		RPointerArray<CMdEPropertyCondition> iPropertyConditionArray;
+		RPointerArray<CMdEEventCondition> iEventConditionArray;
+
+        // Result data from callbacks.
+        TObserverNotificationType iNotificationType;
+        CMdESession* iNotificationSession;
+        RArray<TMdERelation> iNotificationRelationArray;
+        RArray<TItemId> iNotificationItemIdArray;
+
+        CDesCArrayFlat *iObjectDefNameArray;
+        CDesCArrayFlat *iRelationDefNameArray;
+		CDesCArrayFlat *iEventDefNameArray;
+		CDesCArrayFlat *iPropertyDefNameArray;
+		CDesCArrayFlat *iNamespaceDefNameArray;
+		
+		CDesCArrayFlat *iObjectNameArray;		
+        CDesCArrayFlat *iRelationNameArray;
+        CDesCArrayFlat *iEventNameArray;
+        
+        CDesCArrayFlat *iPropertyNameArray;
+        
+		CDesCArrayFlat *iRelationConditionNameArray;
+		CDesCArrayFlat *iObjectConditionNameArray;
+		CDesCArrayFlat *iEventConditionNameArray;
+		
+		CDesCArrayFlat *iLogicConditionNameArray;		
+		CDesCArrayFlat *iPropertyConditionNameArray;
+
+		RArray<TInt> iResultIndices;
+
+        CMdESession* iMdeSession;
+		CMdENamespaceDef* iDefaultNamespaceDef;
+		CMdEQuery *iQuery;
+		CMdELogicCondition *iQueryRoot;
+        TFileName iFilePath;
+        
+        CMdETestScripterAO* iAsyncHandler;
+        RMdEDataBuffer iMdEDataBuf; // Buffer for mde async request results
+        RPointerArray<CMdEInstanceItem> iItemArray;
+        TInt iItemCount;
+    };
+
+#endif      // MDETESTSCRIPTER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/inc/MdETestScripterAO.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+#ifndef CMDETESTSCRIPTERAO_H
+#define CMDETESTSCRIPTERAO_H
+
+#include <e32base.h>
+#include <StifTestEventInterface.h>
+#include <TestScripterInternal.h>
+
+class CMdETestScripter;
+
+NONSHARABLE_CLASS(CMdETestScripterAO) : public CActive
+    {
+public:
+
+    ~CMdETestScripterAO();
+
+    static CMdETestScripterAO* NewL();
+
+    static CMdETestScripterAO* NewLC();
+
+public:
+    void Start( CMdETestScripter* aScripter, TEventIf aEvent );
+
+private:
+    CMdETestScripterAO();
+
+    void ConstructL();
+
+private:
+    void RunL();
+    void DoCancel();
+    TInt RunError(TInt aError);
+
+private:
+	CMdETestScripter* iScripter;
+    TEventIf iEvent;
+    };
+
+#endif // CMDETESTSCRIPTERAO_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/init/MdETestScripter.ini	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,64 @@
+[Engine_Defaults]
+
+TestReportMode= FullReport    # Possible values are: 'Empty', 'Summary', 'Environment',
+                                                     'TestCases' or 'FullReport'
+
+CreateTestReport= YES         # Possible values: YES or NO
+
+TestReportFilePath= C:\LOGS\TestFramework\
+TestReportFileName= TestReport
+
+TestReportFormat= TXT         # Possible values: TXT or HTML
+TestReportOutput= FILE        # Possible values: FILE or RDEBUG
+TestReportFileCreationMode= OVERWRITE # Possible values: OVERWRITE or APPEND
+
+DeviceResetDllName= StifResetForNokia.dll # e.g. 'StifHWResetStub.dll' for user specific reseting
+
+DisableMeasurement= stifmeasurementdisablenone  # Possible values are:
+              # 'stifmeasurementdisablenone', 'stifmeasurementdisableall'
+              # 'stifmeasurementplugin01', 'stifmeasurementplugin02',
+              # 'stifmeasurementplugin03', 'stifmeasurementplugin04',
+              # 'stifmeasurementplugin05' or 'stifbappeaprofiler'
+
+Timeout= 600000		            # Default timeout value for each test case. In milliseconds
+#UITestingSupport= YES        # Possible values: YES or NO
+#SeparateProcesses= YES       # Possible values: YES or NO (default: NO)
+[End_Defaults]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[New_Module]
+ModuleName= TestScripter
+TestCaseFile= c:\testframework\MdETestScripter.cfg
+[End_Module]
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+[Logger_Defaults]
+
+#NOTE: If you want to set Logger using next setting(s) remove comment(s)'#'
+#NOTE: TestEngine and TestServer logging settings cannot change here
+
+CreateLogDirectories= YES    # Possible values: YES or NO
+
+#EmulatorBasePath= C:\LOGS\TestFramework\
+#EmulatorFormat= HTML         # Possible values: TXT or HTML
+#EmulatorOutput= FILE         # Possible values: FILE or RDEBUG
+
+HardwareBasePath= C:\
+#HardwareFormat= HTML         # Possible values: TXT or HTML
+#HardwareOutput= FILE         # Possible values: FILE or RDEBUG
+
+#FileCreationMode= OVERWRITE  # Possible values: OVERWRITE or APPEND
+
+#ThreadIdToLogFile= YES       # Possible values: YES or NO
+#WithTimeStamp= YES           # Possible values: YES or NO
+#WithLineBreak= YES           # Possible values: YES or NO
+#WithEventRanking= YES        # Possible values: YES or NO
+
+#FileUnicode= YES             # Possible values: YES or NO
+#AddTestCaseTitle= YES        # Possible values: YES or NO
+[End_Logger_Defaults]
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+# End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/src/MdETestScripter.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,160 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+// INCLUDE FILES
+#include <StifTestInterface.h>
+#include <SettingServerClient.h>
+#include <PathInfo.h>
+#include <mdesession.h>
+#include "MdETestScripter.h"
+#include "MdETestScripterAO.h"
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::CMdETestScripter
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CMdETestScripter::CMdETestScripter( CTestModuleIf& aTestModuleIf ):
+        CScriptBase( aTestModuleIf )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::ConstructL()
+    {
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        } 
+    // Close Setting server session
+    settingServer.Close();
+
+    TFileName logFileName;
+    
+    if(loggerSettings.iAddTestCaseTitle)
+        {
+        TName title;
+        TestModuleIf().GetTestCaseTitleL(title);
+        logFileName.Format(KMdETestScripterLogFileWithTitle, &title);
+        }
+    else
+        {
+        logFileName.Copy(KMdETestScripterLogFile);
+        }
+
+#if ( defined (__WINS__) || defined (__WINSCW__) )
+    iFilePath.Copy( PathInfo::PhoneMemoryRootPath().Left( KPathPrefixLength ));
+#else
+    iFilePath.Copy( PathInfo::MemoryCardRootPath ().Left( KPathPrefixLength ));
+#endif
+    iFilePath.Append( KMdETestDataPath );
+	iFilePath.ZeroTerminate();
+
+    iLog = CStifLogger::NewL( KMdETestScripterLogPath, 
+                          logFileName,
+                          CStifLogger::ETxt,
+                          CStifLogger::EFile,
+                          EFalse );
+    iObjectDefNameArray = new (ELeave )CDesCArrayFlat( 8 );
+    iRelationDefNameArray = new (ELeave )CDesCArrayFlat( 8 );
+	iEventDefNameArray = new (ELeave )CDesCArrayFlat( 8 );
+	iPropertyDefNameArray = new (ELeave )CDesCArrayFlat( 8 );
+	iNamespaceDefNameArray = new (ELeave )CDesCArrayFlat( 8 );
+	
+	iObjectNameArray = new (ELeave )CDesCArrayFlat( 8 );
+    iRelationNameArray = new (ELeave )CDesCArrayFlat( 8 );
+    iEventNameArray = new (ELeave )CDesCArrayFlat( 8 );
+    
+    iPropertyNameArray = new (ELeave )CDesCArrayFlat( 8 );
+    
+	iRelationConditionNameArray = new (ELeave )CDesCArrayFlat( 8 );
+	iObjectConditionNameArray = new (ELeave )CDesCArrayFlat( 8 );
+	iEventConditionNameArray = new (ELeave )CDesCArrayFlat( 8 );
+			
+	iPropertyConditionNameArray = new (ELeave )CDesCArrayFlat( 8 );
+	iLogicConditionNameArray = new (ELeave )CDesCArrayFlat( 8 );
+
+	iMdeSession = CMdESession::NewL( *this );
+	iAsyncHandler = CMdETestScripterAO::NewL();
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CMdETestScripter* CMdETestScripter::NewL( 
+    CTestModuleIf& aTestModuleIf )
+    {
+    CMdETestScripter* self = new (ELeave) CMdETestScripter( aTestModuleIf );
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// ~CMdETestScripter()
+// Destructor.
+// -----------------------------------------------------------------------------
+//
+CMdETestScripter::~CMdETestScripter()
+    { 
+    // Delete resources allocated from test methods
+    Delete();
+
+    // Delete logger
+    delete iLog; 
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point.
+// Returns: CScriptBase: New CScriptBase derived object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScriptBase* LibEntryL( 
+    CTestModuleIf& aTestModuleIf ) // Backpointer to STIF Test Framework
+    {
+    return ( CScriptBase* ) CMdETestScripter::NewL( aTestModuleIf );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/src/MdETestScripterAO.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,72 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#include "MdETestScripterAO.h"
+#include "MdETestScripter.h"
+#include <e32debug.h>
+
+CMdETestScripterAO::CMdETestScripterAO() : CActive( EPriorityStandard )
+    {
+    }
+
+CMdETestScripterAO* CMdETestScripterAO::NewLC()
+    {
+    CMdETestScripterAO* self = new (ELeave) CMdETestScripterAO();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+CMdETestScripterAO* CMdETestScripterAO::NewL()
+    {
+    CMdETestScripterAO* self = CMdETestScripterAO::NewLC();
+    CleanupStack::Pop();
+    return self;
+    }
+
+void CMdETestScripterAO::ConstructL()
+    {
+    CActiveScheduler::Add( this );
+    }
+
+CMdETestScripterAO::~CMdETestScripterAO()
+    {
+    Cancel();
+    }
+
+void CMdETestScripterAO::Start( CMdETestScripter* aScripter, TEventIf aEvent )
+    {
+    Cancel();
+    iScripter = aScripter;
+    iEvent = aEvent;
+    SetActive();
+    }
+
+void CMdETestScripterAO::RunL()
+    {
+    iScripter->CheckAsyncResultArrayL( iEvent );
+    iScripter->TestModuleIf().Event( iEvent );
+    }
+
+void CMdETestScripterAO::DoCancel()
+    {
+    }
+
+TInt CMdETestScripterAO::RunError(TInt aError)
+    {
+    return aError;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/src/MdETestScripterBlocks.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,857 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+// [INCLUDE FILES] - do not remove
+#include <e32svr.h>
+#include <mdeobject.h>
+#include <mdeobjectdef.h>
+#include <mdesession.h>
+#include <mdeconstants.h>
+#include <StifParser.h>
+#include <Stiftestinterface.h>
+#include <StifTestEventInterface.h>
+#include "MdETestScripter.h"
+#include "MdETestScripterAO.h"
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::Delete
+// Delete here all resources allocated and opened from test methods. 
+// Called from destructor. 
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::Delete() 
+    {
+    iObjectDefArray.Reset();
+    iRelationDefArray.Reset();
+    iEventDefArray.Reset();
+    
+    iLogicConditionArray.Reset();
+    iRelationConditionArray.Reset();
+    iNotificationRelationArray.Reset();
+
+	RArray<TItemId> objectIds;
+	RArray<TItemId> resultObjectIds;
+	RArray<TItemId> eventIds;
+	RArray<TItemId> resultEventIds;
+	RArray<TItemId> relationIds;
+	RArray<TItemId> resultRelationIds;
+	
+	TInt count = iObjectArray.Count();
+	for (TInt i = 0; i < count; i++)
+		{
+		objectIds.Append(iObjectArray[i]->Id());	
+		}
+		
+	count = iEventArray.Count();
+	for (TInt i = 0; i < count; i++)
+		{
+		eventIds.Append(iEventArray[i]->Id());	
+		}
+		
+	count = iRelationArray.Count();
+	for (TInt i = 0; i < count; i++)
+		{
+		relationIds.Append(iRelationArray[i]->Id());	
+		}			
+	
+	if (objectIds.Count())
+		{
+		TRAP_IGNORE( iMdeSession->RemoveObjectsL( objectIds, resultObjectIds) );	
+		}
+
+    iObjectArray.ResetAndDestroy();
+    
+	if (eventIds.Count())
+		{    
+		TRAP_IGNORE( iMdeSession->RemoveEventsL( eventIds, resultEventIds) );
+		}
+    iEventArray.ResetAndDestroy();
+        
+	if (relationIds.Count())
+		{          
+		TRAP_IGNORE( iMdeSession->RemoveRelationsL( relationIds, resultRelationIds) );
+		}
+    iRelationArray.ResetAndDestroy();
+    
+    TInt allRemoved = ETrue;
+	count = iObjectArray.Count();
+	for (TInt i = 0; i < count; i++)
+		{
+		if (resultObjectIds[i] == KNoId)
+			{
+			allRemoved = EFalse;
+			break;	
+			}			
+		}
+	if (!allRemoved)
+		{
+		iLog->Log(_L( "All objects not removed from DB!!"));
+		}
+
+    allRemoved = ETrue;		
+	count = iEventArray.Count();
+	for (TInt i = 0; i < count; i++)
+		{
+		if (resultEventIds[i] == KNoId)
+			{
+			allRemoved = EFalse;
+			break;	
+			}		
+		}
+	if (!allRemoved)
+		{
+		iLog->Log(_L( "All events not removed from DB!!"));
+		}
+    iEventArray.ResetAndDestroy();
+		
+    allRemoved = ETrue;		
+	count = iRelationArray.Count();
+	for (TInt i = 0; i < count; i++)
+		{
+		if (resultRelationIds[i] == KNoId)
+			{
+			allRemoved = EFalse;
+			break;	
+			}		
+		}
+	if (!allRemoved)
+		{
+		iLog->Log(_L( "All relations not removed from DB!!"));
+		}
+				
+	objectIds.Close();
+	resultObjectIds.Close();
+	eventIds.Close();
+	resultEventIds.Close();
+	relationIds.Close();
+	resultRelationIds.Close();
+
+	iPropertyDefArray.Reset();
+
+    delete iObjectDefNameArray;
+    delete iRelationDefNameArray;
+	delete iEventDefNameArray;
+	delete iPropertyDefNameArray;
+	delete iNamespaceDefNameArray;
+	
+	delete iObjectNameArray;	
+    delete iRelationNameArray;
+    delete iEventNameArray;
+    
+    delete iPropertyNameArray;
+    
+	delete iLogicConditionNameArray;
+	delete iRelationConditionNameArray;
+	delete iObjectConditionNameArray;
+	
+	delete iPropertyConditionNameArray;
+	delete iEventConditionNameArray;	
+
+	delete iQuery;
+    delete iMdeSession;
+    iMdeSession = NULL;
+    delete iAsyncHandler;
+    iAsyncHandler = NULL;
+    iMdEDataBuf.Close();
+    iItemArray.Close();//Do not need call destroy because it does not own its pointers
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RunMethodL
+// Run specified method. Contains also table of test mothods and their names.
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RunMethodL( CStifItemParser& aItem ) 
+    {
+    static TStifFunctionInfo const KFunctions[] =
+        {  
+        // Observer add/remove methods
+        ENTRY( "AddSchemaObserverL", CMdETestScripter::AddSchemaObserverL ),
+        ENTRY( "RemoveSchemaObserverL", CMdETestScripter::RemoveSchemaObserverL ),
+        ENTRY( "AddObjectObserverL", CMdETestScripter::AddObjectObserverL ),
+        ENTRY( "RemoveObjectObserverL", CMdETestScripter::RemoveObjectObserverL ),
+        ENTRY( "AddObjectPresentObserverL", CMdETestScripter::AddObjectPresentObserverL ),
+        ENTRY( "RemoveObjectPresentObserverL", CMdETestScripter::RemoveObjectPresentObserverL ),
+        ENTRY( "AddRelationObserverL", CMdETestScripter::AddRelationObserverL ),
+        ENTRY( "RemoveRelationObserverL", CMdETestScripter::RemoveRelationObserverL ),
+        ENTRY( "AddRelationItemObserverL", CMdETestScripter::AddRelationItemObserverL ),
+        ENTRY( "RemoveRelationItemObserverL", CMdETestScripter::RemoveRelationItemObserverL ),
+        ENTRY( "AddRelationPresentObserverL", CMdETestScripter::AddRelationPresentObserverL ),
+        ENTRY( "RemoveRelationPresentObserverL", CMdETestScripter::RemoveRelationPresentObserverL ),
+        ENTRY( "AddEventObserverL", CMdETestScripter::AddEventObserverL ),
+        ENTRY( "RemoveEventObserverL", CMdETestScripter::RemoveEventObserverL ),
+
+        // Notification resulated test primitives
+        ENTRY( "VerifyTItemIdsL", CMdETestScripter::VerifyTItemIdsL ),
+        ENTRY( "VerifyMdERelationsL", CMdETestScripter::VerifyMdERelationsL ),
+        ENTRY( "VerifyObserverNotificationTypeL", CMdETestScripter::VerifyObserverNotificationTypeL ),
+
+        // Metadata/schema/namespace test primitives.
+        ENTRY( "ObjectDefCountL", CMdETestScripter::ObjectDefCountL ),
+        ENTRY( "ObjectDefL", CMdETestScripter::ObjectDefL ),
+        ENTRY( "GetObjectDefL", CMdETestScripter::GetObjectDefL ),
+        ENTRY( "RelationDefCountL", CMdETestScripter::RelationDefCountL ),
+        ENTRY( "RelationDefL", CMdETestScripter::RelationDefL ),
+        ENTRY( "GetRelationDefL", CMdETestScripter::GetRelationDefL ),
+        ENTRY( "EventDefCountL", CMdETestScripter::EventDefCountL ),
+        ENTRY( "EventDefL", CMdETestScripter::EventDefL ),
+        ENTRY( "GetEventDefL", CMdETestScripter::GetEventDefL ),
+
+        ENTRY( "ExportMetadataL", CMdETestScripter::ExportMetadataL ),
+        ENTRY( "ImportMetadataL", CMdETestScripter::ImportMetadataL ),
+        ENTRY( "ImportSchemaL", CMdETestScripter::ImportSchemaL ),
+        ENTRY( "NamespaceDefCountL", CMdETestScripter::NamespaceDefCountL ),
+        ENTRY( "NamespaceDefL", CMdETestScripter::NamespaceDefL ),
+        ENTRY( "GetNamespaceDefL", CMdETestScripter::GetNamespaceDefL ),
+        ENTRY( "GetDefaultNamespaceDefL", CMdETestScripter::GetDefaultNamespaceDefL ),
+        ENTRY( "ResetNamespaceDefArray", CMdETestScripter::ResetNamespaceDefArray ),
+        ENTRY( "LoadSchemaL", CMdETestScripter::LoadSchemaL ),
+        ENTRY( "EngineSessionL", CMdETestScripter::EngineSessionL ),
+        ENTRY( "GetSchemaVersionL", CMdETestScripter::GetSchemaVersionL ),
+        ENTRY( "SetObjectToPresentByGuidL", CMdETestScripter::SetObjectToPresentByGuidL ),
+
+        // Item / InstanceItem test primitives.
+        ENTRY( "BelongsToSessionL", CMdETestScripter::BelongsToSessionL ),
+        ENTRY( "SessionL", CMdETestScripter::SessionL ),
+        ENTRY( "InDatabaseL", CMdETestScripter::InDatabaseL ),
+        ENTRY( "AddItemsL", CMdETestScripter::AddItemsL ),
+        ENTRY( "UpdateItemsL", CMdETestScripter::UpdateItemsL ),
+
+        // Definition test primitives.
+        ENTRY( "AddRelationDefL", CMdETestScripter::AddRelationDefL ),
+        ENTRY( "AddEventDefL", CMdETestScripter::AddEventDefL ),
+        ENTRY( "PropertyDefCountL", CMdETestScripter::PropertyDefCountL ),
+        ENTRY( "PropertyDefL", CMdETestScripter::PropertyDefL ),
+        ENTRY( "GetPropertyDefL", CMdETestScripter::GetPropertyDefL ),
+        ENTRY( "MandatoryL", CMdETestScripter::MandatoryL ),
+        ENTRY( "MinInt32ValueL", CMdETestScripter::MinInt32ValueL ),
+        ENTRY( "MaxInt32ValueL", CMdETestScripter::MaxInt32ValueL ),
+        ENTRY( "MinUint32ValueL", CMdETestScripter::MinUint32ValueL ),
+        ENTRY( "MaxUint32ValueL", CMdETestScripter::MaxUint32ValueL ),
+        ENTRY( "MinInt64ValueL", CMdETestScripter::MinInt64ValueL ),
+        ENTRY( "MaxInt64ValueL", CMdETestScripter::MaxInt64ValueL ),
+        ENTRY( "MinRealValueL", CMdETestScripter::MinRealValueL ),
+        ENTRY( "MaxRealValueL", CMdETestScripter::MaxRealValueL ),
+        ENTRY( "MinTimeValueL", CMdETestScripter::MinTimeValueL ),
+        ENTRY( "MaxTimeValueL", CMdETestScripter::MaxTimeValueL ),
+        ENTRY( "MinTextLengthL", CMdETestScripter::MinTextLengthL ),
+        ENTRY( "MaxTextLengthL", CMdETestScripter::MaxTextLengthL ),
+        ENTRY( "CompareL", CMdETestScripter::CompareL ),
+        ENTRY( "ParentL", CMdETestScripter::ParentL ),
+        ENTRY( "NameL", CMdETestScripter::NameL ),
+        ENTRY( "ReadOnlyL", CMdETestScripter::ReadOnlyL ),
+        ENTRY( "DefL", CMdETestScripter::DefL ),
+
+        // Object test primitives.
+        ENTRY( "SetDefL", CMdETestScripter::SetDefL ),
+        ENTRY( "UriL", CMdETestScripter::UriL ),
+        ENTRY( "SetUriL", CMdETestScripter::SetUriL ),
+        ENTRY( "ConfidentialL", CMdETestScripter::ConfidentialL ),
+        ENTRY( "SetConfidentialL", CMdETestScripter::SetConfidentialL ),
+        ENTRY( "PlaceholderL", CMdETestScripter::PlaceholderL ),
+        ENTRY( "SetPlaceholderL", CMdETestScripter::SetPlaceholderL ),
+        ENTRY( "MediaIdL", CMdETestScripter::MediaIdL ),
+        ENTRY( "SetMediaIdL", CMdETestScripter::SetMediaIdL ),
+        ENTRY( "UsageCountL", CMdETestScripter::UsageCountL ),
+        ENTRY( "GuidL", CMdETestScripter::GuidL ),
+        ENTRY( "SetGuidL", CMdETestScripter::SetGuidL ),
+        ENTRY( "OpenForModificationsL", CMdETestScripter::OpenForModificationsL ),
+        ENTRY( "NewObjectL", CMdETestScripter::NewObjectL ),
+        ENTRY( "AddObjectL", CMdETestScripter::AddObjectL ),
+        ENTRY( "AddObjectsL", CMdETestScripter::AddObjectsL ),
+        ENTRY( "GetObjectL", CMdETestScripter::GetObjectL ),
+        ENTRY( "GetFullObjectL", CMdETestScripter::GetFullObjectL ),
+        ENTRY( "CheckObjectL", CMdETestScripter::CheckObjectL ),
+        ENTRY( "RemoveObjectL", CMdETestScripter::RemoveObjectL ),
+        ENTRY( "RemoveObjectsL", CMdETestScripter::RemoveObjectsL ),
+        ENTRY( "RemoveAllObjectsL", CMdETestScripter::RemoveAllObjectsL ),
+        ENTRY( "OpenObjectL", CMdETestScripter::OpenObjectL ),
+        ENTRY( "OpenFullObjectL", CMdETestScripter::OpenFullObjectL ),
+        ENTRY( "CommitObjectL", CMdETestScripter::CommitObjectL ),
+        ENTRY( "CommitObjectsL", CMdETestScripter::CommitObjectsL ),
+        ENTRY( "CancelObjectL", CMdETestScripter::CancelObjectL ),
+
+        ENTRY( "PropertyL", CMdETestScripter::PropertyL ),
+        ENTRY( "PropertyCountL", CMdETestScripter::PropertyCountL ),
+        ENTRY( "AddBoolPropertyL", CMdETestScripter::AddBoolPropertyL ),
+        ENTRY( "AddInt8PropertyL", CMdETestScripter::AddInt8PropertyL ),
+        ENTRY( "AddUint8PropertyL", CMdETestScripter::AddUint8PropertyL ),
+        ENTRY( "AddInt16PropertyL", CMdETestScripter::AddInt16PropertyL ),
+        ENTRY( "AddUint16PropertyL", CMdETestScripter::AddUint16PropertyL ),
+        ENTRY( "AddInt32PropertyL", CMdETestScripter::AddInt32PropertyL ),
+        ENTRY( "AddUint32PropertyL", CMdETestScripter::AddUint32PropertyL ),
+        ENTRY( "AddInt64PropertyL", CMdETestScripter::AddInt64PropertyL ),
+        ENTRY( "AddReal32PropertyL", CMdETestScripter::AddReal32PropertyL ),
+        ENTRY( "AddReal64PropertyL", CMdETestScripter::AddReal64PropertyL ),
+        ENTRY( "AddTextPropertyL", CMdETestScripter::AddTextPropertyL ),
+        ENTRY( "AddTimePropertyL", CMdETestScripter::AddTimePropertyL ),
+
+        // Property test primitives.
+        ENTRY( "ObjectL", CMdETestScripter::ObjectL ),
+        ENTRY( "BoolValueL", CMdETestScripter::BoolValueL ),
+        ENTRY( "Int8ValueL", CMdETestScripter::Int8ValueL ),
+        ENTRY( "Uint8ValueL", CMdETestScripter::Uint8ValueL ),
+        ENTRY( "Int16ValueL", CMdETestScripter::Int16ValueL ),
+        ENTRY( "Uint16ValueL", CMdETestScripter::Uint16ValueL ),
+        ENTRY( "Int32ValueL", CMdETestScripter::Int32ValueL ),
+        ENTRY( "Uint32ValueL", CMdETestScripter::Uint32ValueL ),
+        ENTRY( "Int64ValueL", CMdETestScripter::Int64ValueL ),
+        ENTRY( "Real32ValueL", CMdETestScripter::Real32ValueL ),
+        ENTRY( "Real64ValueL", CMdETestScripter::Real64ValueL ),
+        ENTRY( "TimeValueL", CMdETestScripter::TimeValueL ),
+        ENTRY( "TextValueL", CMdETestScripter::TextValueL ),
+        ENTRY( "SetBoolValueL", CMdETestScripter::SetBoolValueL ),
+        ENTRY( "SetInt8ValueL", CMdETestScripter::SetInt8ValueL ),
+        ENTRY( "SetUint8ValueL", CMdETestScripter::SetUint8ValueL ),
+        ENTRY( "SetInt16ValueL", CMdETestScripter::SetInt16ValueL ),
+        ENTRY( "SetUint16ValueL", CMdETestScripter::SetUint16ValueL ),
+        ENTRY( "SetInt32ValueL", CMdETestScripter::SetInt32ValueL ),
+        ENTRY( "SetUint32ValueL", CMdETestScripter::SetUint32ValueL ),
+        ENTRY( "SetInt64ValueL", CMdETestScripter::SetInt64ValueL ),
+        ENTRY( "SetReal32ValueL", CMdETestScripter::SetReal32ValueL ),
+        ENTRY( "SetReal64ValueL", CMdETestScripter::SetReal64ValueL ),
+        ENTRY( "SetTimeValueL", CMdETestScripter::SetTimeValueL ),
+        ENTRY( "SetTextValueL", CMdETestScripter::SetTextValueL ),
+        ENTRY( "RemovePropertyL", CMdETestScripter::RemovePropertyL ),
+        ENTRY( "MovePropertiesL", CMdETestScripter::MovePropertiesL ),
+
+        // Free text test primitives.
+        ENTRY( "FreeTextCountL", CMdETestScripter::FreeTextCountL ),
+        ENTRY( "FreeTextL", CMdETestScripter::FreeTextL ),
+        ENTRY( "FreeTextIndexL", CMdETestScripter::FreeTextIndexL ),
+        ENTRY( "AddFreeTextL", CMdETestScripter::AddFreeTextL ),
+        ENTRY( "RemoveFreeTextL", CMdETestScripter::RemoveFreeTextL ),
+
+        // Relation test primitives.
+        ENTRY( "NewRelationL", CMdETestScripter::NewRelationL ),
+        ENTRY( "AddRelationL", CMdETestScripter::AddRelationL ),
+        ENTRY( "LeftObjectIdL", CMdETestScripter::LeftObjectIdL ),
+        ENTRY( "RightObjectIdL", CMdETestScripter::RightObjectIdL ),
+        ENTRY( "ParameterL", CMdETestScripter::ParameterL ),
+        ENTRY( "SetParameterL", CMdETestScripter::SetParameterL ),
+        ENTRY( "SetLeftObjectIdL", CMdETestScripter::SetLeftObjectIdL ),
+        ENTRY( "SetRightObjectIdL", CMdETestScripter::SetRightObjectIdL ),
+        ENTRY( "LastModifiedDateL", CMdETestScripter::LastModifiedDateL ),
+        ENTRY( "SetLastModifiedDateL", CMdETestScripter::SetLastModifiedDateL ),
+        ENTRY( "GetRelationL", CMdETestScripter::GetRelationL ),
+        ENTRY( "UpdateRelationL", CMdETestScripter::UpdateRelationL ),
+        ENTRY( "RemoveRelationL", CMdETestScripter::RemoveRelationL ),
+        ENTRY( "RemoveRelationsL", CMdETestScripter::RemoveRelationsL ),
+
+        // Event test primitives.
+        ENTRY( "NewEventL", CMdETestScripter::NewEventL ),
+        ENTRY( "AddEventL", CMdETestScripter::AddEventL ),
+        ENTRY( "ObjectIdL", CMdETestScripter::ObjectIdL ),
+        ENTRY( "TimeL", CMdETestScripter::TimeL ),
+        ENTRY( "SourceL", CMdETestScripter::SourceL ),
+        ENTRY( "ParticipantL", CMdETestScripter::ParticipantL ),
+        ENTRY( "GetEventL", CMdETestScripter::GetEventL ),
+        ENTRY( "RemoveEventL", CMdETestScripter::RemoveEventL ),
+        ENTRY( "RemoveEventsL", CMdETestScripter::RemoveEventsL ),
+        ENTRY( "NewObjectQueryL", CMdETestScripter::NewObjectQueryL ),
+        ENTRY( "NewRelationQueryL", CMdETestScripter::NewRelationQueryL ),
+        ENTRY( "NewEventQueryL", CMdETestScripter::NewEventQueryL ),
+                
+        ENTRY( "QueryObjectL", CMdETestScripter::QueryObjectL ),
+        ENTRY( "QueryRelationL", CMdETestScripter::QueryRelationL ),
+        ENTRY( "QueryEventL", CMdETestScripter::QueryEventL ),
+        ENTRY( "AddPropertyFilterL", CMdETestScripter::AddPropertyFilterL ),
+        ENTRY( "AppendOrderRuleL", CMdETestScripter::AppendOrderRuleL ),
+        ENTRY( "NewLogicConditionL", CMdETestScripter::NewLogicConditionL ),
+        ENTRY( "AddLogicConditionL", CMdETestScripter::AddLogicConditionL ),
+        ENTRY( "AddObjectConditionL", CMdETestScripter::AddObjectConditionL ),
+        ENTRY( "AddPropertyConditionL", CMdETestScripter::AddPropertyConditionL ),
+        ENTRY( "AddRelationConditionL", CMdETestScripter::AddRelationConditionL ),
+        ENTRY( "AddEventConditionL", CMdETestScripter::AddEventConditionL ),
+        ENTRY( "FindL", CMdETestScripter::FindL ),
+        ENTRY( "SetObjectQueryResultL", CMdETestScripter::SetObjectQueryResultL ),
+        ENTRY( "SetEventQueryResultL", CMdETestScripter::SetEventQueryResultL ),
+        ENTRY( "SetRelationQueryResultL", CMdETestScripter::SetRelationQueryResultL ),
+        ENTRY( "RightL", CMdETestScripter::RightL ),
+        ENTRY( "LeftL", CMdETestScripter::LeftL ),
+        ENTRY( "SetOperatorL", CMdETestScripter::SetOperatorL ), 
+        ENTRY( "SetNegateL", CMdETestScripter::SetNegateL ),
+        ENTRY( "ObjectConditionsL", CMdETestScripter::ObjectConditionsL ),     
+        ENTRY( "TestPopulateDbL", CMdETestScripter::TestPopulateDbL )
+        
+        // [test cases entries] - Do not remove
+        };
+
+    const TInt count = sizeof( KFunctions ) / sizeof( TStifFunctionInfo );
+
+    return RunInternalL( KFunctions, count, aItem );
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTestScripter::HandleObjectNotification
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::HandleObjectNotification( CMdESession& aSession, 
+    TObserverNotificationType aType,
+    const RArray<TItemId>& aObjectIdArray )
+    {
+    iLog->Log(_L( "HandleObjectNotification" ));
+    
+    iNotificationSession = &aSession;
+    iNotificationType = aType;
+    for ( TInt i = 0; i < aObjectIdArray.Count(); ++i )
+        {
+        iNotificationItemIdArray.Append( aObjectIdArray[ i ] );
+        }
+
+    Signal();
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTestScripter::HandleObjectPresentNotification
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::HandleObjectPresentNotification( CMdESession& /* aSession */, 
+    TBool /* aPresent */, const RArray<TItemId>& /* aObjectIdArray */ )
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTestScripter::HandleSessionOpened
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::HandleSessionOpened( CMdESession& /* aSession */, TInt aError )
+    {
+    iLog->Log(_L( "HandleSessionOpened, aError == %d"), aError );
+    
+    Signal();
+
+    iError = aError;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTestScripter::HandleSessionError
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::HandleSessionError( CMdESession& /*aSession*/, TInt aError )
+    {
+    iLog->Log(_L( "HandleSessionError, aError == %d"), aError );
+
+    iError = aError;
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTestScripter::HandleSchemaModified
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::HandleSchemaModified()
+    {
+    iLog->Log(_L( "HandleSchemaModified" ));
+
+    TEventIf event( TEventIf::ESetEvent, TName( KMdESchemaModified ) );
+    TestModuleIf().Event( event );
+
+    Signal();// This can be removed after modify all related cases.
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTestScripter::HandleRelationNotification
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::HandleRelationNotification( CMdESession& aSession, 
+    TObserverNotificationType aType,
+    const RArray<TItemId>& aRelationIdArray )
+    {
+    iLog->Log(_L( "HandleRelationNotification" ));
+    
+    iNotificationSession = &aSession;
+    iNotificationType = aType;
+    for ( TInt i = 0; i < aRelationIdArray.Count(); ++i )
+        {
+        iNotificationItemIdArray.Append( aRelationIdArray[ i ] );
+        }
+
+    Signal();
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTestScripter::HandleRelationItemNotification
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::HandleRelationItemNotification(CMdESession& aSession, 
+    TObserverNotificationType aType,
+    const RArray<TMdERelation>& aRelationArray )
+    {
+    iLog->Log(_L( "HandleRelationItemNotification" ));
+
+    iNotificationSession = &aSession;
+    iNotificationType = aType;
+    for ( TInt i = 0; i < aRelationArray.Count(); ++i )
+        {
+        iNotificationRelationArray.Append( aRelationArray[ i ] );
+        }
+
+    Signal();
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTestScripter::HandleRelationPresentNotification
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::HandleRelationPresentNotification(CMdESession& /* aSession */,
+    TBool /* aPresent */,
+    const RArray<TItemId>& /* aRelationIdArray */ )
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHarvesterPluginTestScripter::HandleEventNotification
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::HandleEventNotification( CMdESession& aSession, 
+    TObserverNotificationType aType,
+    const RArray<TItemId>& aEventIdArray )
+    {
+    iLog->Log(_L( "HandleEventNotification" ));
+    
+    iNotificationSession = &aSession;
+    iNotificationType = aType;
+    for ( TInt i = 0; i < aEventIdArray.Count(); ++i )
+        {
+        iNotificationItemIdArray.Append( aEventIdArray[ i ] );
+        }
+
+    Signal();
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::GetInstanceItemByArrayIndexL
+// -----------------------------------------------------------------------------
+//
+CMdEInstanceItem* CMdETestScripter::GetInstanceItemByArrayIndexL(
+    const TInt aMode, CStifItemParser& aItem )
+    {
+    CMdEInstanceItem* ret = NULL;
+
+    if ( aMode == EObject )
+        {
+        ret = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+        TL( ret->InstanceType() == EMdETypeObject )
+        }
+    else if ( aMode == ERelation )
+        {
+        ret = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+        TL( ret->InstanceType() == EMdETypeRelation )
+        }
+    else if ( aMode == EEvent )
+        {
+        ret = SanitizeArrayIndexL( iEventArray, *iEventNameArray, aItem );
+        TL( ret->InstanceType() == EMdETypeEvent )
+        }
+    else if ( aMode == EProperty )
+        {
+        ret = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );
+        TL( ret->InstanceType() == EMdETypeProperty )
+        }
+    else
+        {
+    	User::Leave( KErrArgument );
+        }
+
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::CheckTMdEObjectL
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::CheckTMdEObjectL( const TMdEObject& aTObject, const CMdEObject& aObject )
+    {
+    TL( aObject.Id() == aTObject.Id());
+    TL( aObject.Def().Compare( aTObject.DefL()) == 0 );
+    TL( aObject.Confidential() == aTObject.Confidential());
+    TL( aObject.Placeholder() == aTObject.Placeholder());
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::CheckTMdERelationL
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::CheckTMdERelationL( const TMdERelation& aTRelation, const CMdERelation& aRelation )
+    {
+    TL( aRelation.Id() == aTRelation.Id());
+    TL( aRelation.Def().Compare( aTRelation.DefL()) == 0 );
+    TL( aRelation.LeftObjectId() == aTRelation.LeftObjectId())
+    TL( aRelation.RightObjectId() == aTRelation.RightObjectId()) 
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::CheckTMdEObjectArrayL
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::CheckTMdEObjectArrayL(
+    const RArray<TMdEObject>& aTObjects, const TInt aIndex, const TInt aCount )
+    {
+    TL( aTObjects.Count() == aCount );
+
+    for ( TInt i = 0; i < aTObjects.Count(); ++i )
+        {
+        const CMdEObject* object = NULL;
+        TInt j;
+
+        for ( j = 0; aIndex + j < iObjectArray.Count(); ++j )
+            {
+            if ( iObjectArray[ aIndex + j ]->Id() == aTObjects[ i ].Id())
+                {
+                object = iObjectArray[ aIndex + j ];
+
+                CheckTMdEObjectL( aTObjects[ i ], *object );
+                break;
+                }
+            }
+        TL( object );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::CheckTMdERelationArrayL
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::CheckTMdERelationArrayL(
+    const RArray<TMdERelation>& aTRelations, const TInt aIndex, const TInt aCount )
+    {
+    TL( aTRelations.Count() == aCount );
+
+    for ( TInt i = 0; i < aTRelations.Count(); ++i )
+        {
+        const CMdERelation* relation = NULL;
+        TInt j;
+
+        for ( j = 0; aIndex + j < iRelationArray.Count(); ++j )
+            {
+            if ( iRelationArray[ aIndex + j ]->Id() == aTRelations[ i ].Id())
+                {
+                relation = iRelationArray[ aIndex + j ];
+
+                CheckTMdERelationL( aTRelations[ i ], *relation );
+                break;
+                }
+            }
+        TL( relation );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::CheckTItemIdArrayL
+// -----------------------------------------------------------------------------
+//
+template <class T> void CMdETestScripter::CheckTItemIdArrayL(
+    const RArray<TItemId>& aTItemIds, const RPointerArray<T>& aArray,
+    const TInt aIndex, const TInt aCount )
+    {
+    TL( aTItemIds.Count() == aCount );
+
+    for ( TInt i = 0; i < aTItemIds.Count(); ++i )
+        {
+        const T* t = NULL;
+        TInt j;
+
+        for ( j = 0; aIndex + j < aArray.Count(); ++j )
+            {
+            if ( aArray[ aIndex + j ]->Id() == aTItemIds[ i ] )
+                {
+                t = aArray[ aIndex + j ];
+
+                break;
+                }
+            }
+        TL( t );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::CheckAsyncResultArrayL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::CheckAsyncResultArrayL( TEventIf aEvent )
+    {
+    TInt err = KErrNone;
+    if ( 0 == aEvent.Name().Compare( KMdEItemsAsyncAdd ) 
+        || 0 == aEvent.Name().Compare( KMdEItemsAsyncUpdate ) )
+        {
+        //Check result item ids count of iMdEDataBuf
+        //Update ids of iItemArray( iObjectArray, iRelationArray, iEventsArray ) to clear temp test data in delete() later.
+        err = iMdeSession->DeserializeItemsL( iMdEDataBuf, iItemArray );
+        }
+    else if ( 0 == aEvent.Name().Compare( KMdEObjectsAsyncRemoved )
+        || 0 == aEvent.Name().Compare( KMdEEventsAsyncRemoved )
+        || 0 == aEvent.Name().Compare( KMdERelationsAsyncRemoved ) )
+        {
+        RArray<TItemId> objectIds, eventIds, relationIds;
+        err = iMdeSession->DeserializeIdsL( iMdEDataBuf, &objectIds, &eventIds, &relationIds );
+        
+        //Check result item ids count of iMdEDataBuf
+        if ( 0 == aEvent.Name().Compare( KMdEObjectsAsyncRemoved ) )
+            {
+            TL( objectIds.Count() == iItemCount );
+            }
+        else if ( 0 == aEvent.Name().Compare( KMdEEventsAsyncRemoved ) )
+            {
+            TL( eventIds.Count() == iItemCount );
+            }
+        else if ( 0 == aEvent.Name().Compare( KMdERelationsAsyncRemoved ) )
+            {
+            TL( relationIds.Count() == iItemCount );
+            }
+        objectIds.Close();
+        eventIds.Close();
+        relationIds.Close();
+        }
+    iItemCount = 0;
+    iItemArray.Reset();
+    iMdEDataBuf.Close();//Clean mde buffer
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::FormInstanceItemArrayL
+// -----------------------------------------------------------------------------
+//
+void CMdETestScripter::FormInstanceItemArrayL(
+    CStifItemParser& aItem, RPointerArray<CMdEInstanceItem>& aItemArray ) const
+    {
+    TInt mode2;
+    TInt index;
+    TInt count;
+
+    User::LeaveIfError( aItem.GetNextInt( mode2 ));
+    User::LeaveIfError( aItem.GetNextInt( index ));
+    User::LeaveIfError( aItem.GetNextInt( count ));
+
+    for ( TInt i = 0; i < count; ++i )
+        {
+        if ( mode2 == EObject )
+            {
+            aItemArray.Append( iObjectArray[ index + i ] );
+            }
+        else if ( mode2 == ERelation )
+            {
+            aItemArray.Append( iRelationArray[ index + i ] );
+            }
+        else if ( mode2 == EEvent )
+            {
+            aItemArray.Append( iEventArray[ index + i ] );
+            }
+        else if ( mode2 == EProperty )
+            {
+            aItemArray.Append( iPropertyArray[ index + i ] );
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SanitizeArrayIndexL
+// -----------------------------------------------------------------------------
+//
+template <class T> T* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<T>& aArray, const CDesCArrayFlat& aNameArray, 
+    CStifItemParser& aItem )
+    {
+    __ASSERT_ALWAYS( aArray.Count() == aNameArray.Count(),
+                     User::Panic( KMdETestScripter, KErrGeneral ));
+
+    TPtrC nameOrIndex;
+    User::LeaveIfError( aItem.GetNextString( nameOrIndex ));
+	TLex lex( nameOrIndex );
+	TInt index;
+	TInt err = lex.Val( index );
+	if ( err == KErrGeneral )
+		{ // string is name identifier
+		for ( TInt nameIndex = 0; nameIndex < aNameArray.Count(); nameIndex++)
+			{
+			if ( nameOrIndex.Compare( aNameArray[ nameIndex ] ) == 0 )
+				{
+				return aArray[ nameIndex ];	
+				}
+			}
+		User::Leave( KErrNotFound );
+		return NULL; // suppress compile warning
+		}
+	else
+		{
+		if ( index == KLast )
+    		{
+    		index = aArray.Count() - 1;
+    		}
+
+		TL( aArray.Count() > index );
+		return aArray[ index ];
+		}		
+    }
+
+// ========================== TEMPLATE METHOD INSTANTIATIONS ===================
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SanitizeArrayIndexL
+// -----------------------------------------------------------------------------
+//
+template CMdEObjectDef* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<CMdEObjectDef>& aArray, const CDesCArrayFlat& aNameArray, CStifItemParser& aItem );
+template CMdERelationDef* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<CMdERelationDef>& aArray, const CDesCArrayFlat& aNameArray, CStifItemParser& aItem );
+template CMdEEventDef* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<CMdEEventDef>& aArray, const CDesCArrayFlat& aNameArray, CStifItemParser& aItem );
+template CMdEPropertyDef* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<CMdEPropertyDef>& aArray, const CDesCArrayFlat& aNameArray, CStifItemParser& aItem );
+template CMdENamespaceDef* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<CMdENamespaceDef>& aArray, const CDesCArrayFlat& aNameArray, CStifItemParser& aItem );
+template CMdEObject* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<CMdEObject>& aArray, const CDesCArrayFlat& aNameArray, CStifItemParser& aItem );
+template CMdERelation* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<CMdERelation>& aArray, const CDesCArrayFlat& aNameArray, CStifItemParser& aItem );
+template CMdEEvent* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<CMdEEvent>& aArray, const CDesCArrayFlat& aNameArray, CStifItemParser& aItem );
+template CMdEProperty* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<CMdEProperty>& aArray, const CDesCArrayFlat& aNameArray, CStifItemParser& aItem );
+template CMdERelationCondition* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<CMdERelationCondition>& aArray, const CDesCArrayFlat& aNameArray, CStifItemParser& aItem );
+template CMdELogicCondition* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<CMdELogicCondition>& aArray, const CDesCArrayFlat& aNameArray, CStifItemParser& aItem );
+template CMdEPropertyCondition* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<CMdEPropertyCondition>& aArray, const CDesCArrayFlat& aNameArray, CStifItemParser& aItem );
+template CMdEEventCondition* CMdETestScripter::SanitizeArrayIndexL(
+    RPointerArray<CMdEEventCondition>& aArray, const CDesCArrayFlat& aNameArray, CStifItemParser& aItem );
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::CheckTItemIdArrayL
+// -----------------------------------------------------------------------------
+//
+template void CMdETestScripter::CheckTItemIdArrayL(
+    const RArray<TItemId>& aTItemIds, const RPointerArray<CMdEObject>& aArray,
+    const TInt aIndex, const TInt aCount );
+template void CMdETestScripter::CheckTItemIdArrayL(
+    const RArray<TItemId>& aTItemIds, const RPointerArray<CMdEEvent>& aArray,
+    const TInt aIndex, const TInt aCount );
+template void CMdETestScripter::CheckTItemIdArrayL(
+    const RArray<TItemId>& aTItemIds, const RPointerArray<CMdERelation>& aArray,
+    const TInt aIndex, const TInt aCount );
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+// None
+
+//  [End of File] - Do not remove
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/src/MdETestScripterEditCommands.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,2647 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+// [INCLUDE FILES] - do not remove
+#include <mdeobject.h>
+#include <mdeconstants.h>
+#include <StifParser.h>
+#include <StifTestInterface.h>
+#include <StifTestEventInterface.h>
+#include "MdETestScripter.h"
+#include "MdETestScripterAO.h"
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::BelongsToSessionL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::BelongsToSessionL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    TInt state;
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    CMdEInstanceItem* instanceItem = GetInstanceItemByArrayIndexL( mode, aItem );
+    User::LeaveIfError( aItem.GetNextInt( state ));
+
+    TL( instanceItem->BelongsToSession() == (TBool)state );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SessionL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SessionL( CStifItemParser& aItem )
+    {
+    TInt mode;
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    CMdEInstanceItem* instanceItem = GetInstanceItemByArrayIndexL( mode, aItem );
+    TL( iMdeSession == &instanceItem->Session());
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::InDatabaseL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::InDatabaseL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    TInt state;
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    CMdEInstanceItem* instanceItem = GetInstanceItemByArrayIndexL( mode, aItem );
+    User::LeaveIfError( aItem.GetNextInt( state ));
+    TL( instanceItem->InDatabase() == (TBool)state );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddItemsL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddItemsL( CStifItemParser& aItem )
+    {
+    TInt mode1, err = KErrNone;
+    User::LeaveIfError( aItem.GetNextInt( mode1 ));
+
+    if ( mode1 == KSync )
+        {
+        RPointerArray<CMdEInstanceItem> itemArray;
+        FormInstanceItemArrayL( aItem, itemArray );
+        err = iMdeSession->AddItemsL( itemArray );
+        }
+    else if ( mode1 == KAsync )
+        {
+        FormInstanceItemArrayL( aItem, iItemArray );
+        TEventIf event( TEventIf::ESetEvent, TName( KMdEItemsAsyncAdd ) );
+        iAsyncHandler->Start( this, event );
+        iMdEDataBuf.Close();// make sure the last async request buffer cleaned before using again.
+        iMdeSession->AddItemsAsyncL( iItemArray, iAsyncHandler->iStatus, iMdEDataBuf );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::UpdateItemsL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::UpdateItemsL( CStifItemParser& aItem )
+    {
+    TInt mode1, err = KErrNone;
+    User::LeaveIfError( aItem.GetNextInt( mode1 ));
+
+    if ( mode1 == KSync )
+        {
+        RPointerArray<CMdEInstanceItem> itemArray;
+        FormInstanceItemArrayL( aItem, itemArray );
+        err = iMdeSession->UpdateItemsL( itemArray );
+        }
+    else if ( mode1 == KAsync )
+        {
+        FormInstanceItemArrayL( aItem, iItemArray );
+        TEventIf event( TEventIf::ESetEvent, TName( KMdEItemsAsyncUpdate ) );
+        iAsyncHandler->Start( this, event );
+        iMdEDataBuf.Close();// make sure the last async request buffer cleaned before using again.
+        iMdeSession->UpdateItemsAsyncL( iItemArray, iAsyncHandler->iStatus, iMdEDataBuf );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddRelationDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddRelationDefL( CStifItemParser& aItem )
+    {
+    TPtrC relationString;
+
+    CMdENamespaceDef* namespaceDef = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( relationString ));
+    TRAPD( err, iMdeSession->AddRelationDefL( *namespaceDef, relationString ) );
+    if( KErrAlreadyExists == err )
+        {
+        TEventIf event( TEventIf::ESetEvent, TName( KMdESchemaModified ) );
+        TestModuleIf().Event( event );
+        }
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddEventDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddEventDefL( CStifItemParser& aItem )
+    {
+    TPtrC eventString;
+
+    CMdENamespaceDef* namespaceDef = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( eventString ));
+    TRAPD( err, iMdeSession->AddEventDefL( *namespaceDef, eventString ) );
+    if( KErrAlreadyExists == err )
+        {
+        TEventIf event( TEventIf::ESetEvent, TName( KMdESchemaModified ) );
+        TestModuleIf().Event( event );
+       	}
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::PropertyDefCountL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::PropertyDefCountL( CStifItemParser& aItem )
+    {
+    TInt count;
+
+    CMdEObjectDef* objectDef = SanitizeArrayIndexL( iObjectDefArray, *iObjectDefNameArray, aItem);
+    User::LeaveIfError( aItem.GetNextInt( count ));
+    TL( objectDef->PropertyDefCount() == count );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::PropertyDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::PropertyDefL( CStifItemParser& aItem )
+    {
+    TInt index;
+
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));   
+
+    CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem);
+    CMdEObjectDef* objectDef = SanitizeArrayIndexL( iObjectDefArray, *iObjectDefNameArray, aItem);
+    User::LeaveIfError( aItem.GetNextInt( index ));
+    CMdEPropertyDef& propertyDef = objectDef->PropertyDefL( index );
+    TL( &propertyDef );
+    iPropertyDefArray.Append( &propertyDef );
+    AppendNameL( iPropertyDefNameArray, name );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::GetPropertyDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::GetPropertyDefL( CStifItemParser& aItem )
+    {
+    TPtrC propertyString;
+    
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));   
+
+    CMdEObjectDef* objectDef = SanitizeArrayIndexL( iObjectDefArray, *iObjectDefNameArray, aItem);
+    User::LeaveIfError( aItem.GetNextString( propertyString ));
+    CMdEPropertyDef& propertyDef = objectDef->GetPropertyDefL( propertyString );
+    iPropertyDefArray.Append( &propertyDef );
+    AppendNameL( iPropertyDefNameArray, name );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::CompareL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::CompareL( CStifItemParser& aItem )
+    {
+    TInt mode;
+
+    TInt expected;
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    TInt result( -1 );
+
+    if ( mode == EObjectDef )
+        {
+        CMdEObjectDef* item1 = SanitizeArrayIndexL( iObjectDefArray, *iObjectDefNameArray, aItem );
+        CMdEObjectDef* item2 = SanitizeArrayIndexL( iObjectDefArray, *iObjectDefNameArray, aItem );
+        result = item1->Compare( *item2 );
+        }
+    else if ( mode == ERelationDef )
+        {
+        CMdERelationDef* item1 = SanitizeArrayIndexL( iRelationDefArray, *iRelationDefNameArray, aItem );
+        CMdERelationDef* item2 = SanitizeArrayIndexL( iRelationDefArray, *iRelationDefNameArray, aItem );
+        result = item1->Compare( *item2 );
+        }
+    else if ( mode == EEventDef )
+        {
+        CMdEEventDef* item1 = SanitizeArrayIndexL( iEventDefArray, *iEventDefNameArray, aItem );
+        CMdEEventDef* item2 = SanitizeArrayIndexL( iEventDefArray, *iEventDefNameArray, aItem );
+        result = item1->Compare( *item2 );
+        }
+    else if ( mode == EPropertyDef )
+        {
+        CMdEPropertyDef* item1 = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+        CMdEPropertyDef* item2 = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+        result = item1->Compare( *item2 );
+        }
+    else if ( mode == ENamespaceDef )
+        {
+        CMdENamespaceDef* item1 = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+        CMdENamespaceDef* item2 = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+        result = item1->Compare( *item2 );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+        
+    User::LeaveIfError( aItem.GetNextInt( expected ));
+    TL( result == expected );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ReadOnlyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::ReadOnlyL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    TBool state;
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+
+    if ( mode == EPropertyDef )
+        {
+        CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+        User::LeaveIfError( aItem.GetNextInt( state ));
+        TL( propertyDef->ReadOnly() == (TBool)state );
+        }
+    else if ( mode == ENamespaceDef )
+        {
+        CMdENamespaceDef* namespaceDef = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+        User::LeaveIfError( aItem.GetNextInt( state ));
+        TL( namespaceDef->ReadOnly() == state );
+        }
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MandatoryL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MandatoryL( CStifItemParser& aItem )
+    {
+    TBool state;
+
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( state ));
+    TL( propertyDef->Mandatory() == (TBool)state );
+
+    return KErrNone;
+    }    
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MinInt32ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MinInt32ValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( value ));
+    TLex lex( value );
+    TInt32 valueU;
+    lex.BoundedVal( valueU, 0x7FFFFFFF );
+    TL( propertyDef->MinInt32ValueL() == valueU );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MaxInt32ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MaxInt32ValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( value ));
+    TLex lex( value );
+    TInt32 valueU;
+    lex.BoundedVal( valueU, 0x7FFFFFFF );
+    TL( propertyDef->MaxInt32ValueL() == valueU );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MinUint32ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MinUint32ValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( value ));
+    TLex lex( value );
+    TUint32 valueU;
+    lex.BoundedVal( valueU, EDecimal, 0xFFFFFFFF );
+    TL( propertyDef->MinUint32ValueL() == valueU );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MaxUint32ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MaxUint32ValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( value ));
+    TLex lex( value );
+    TUint32 valueU;
+    lex.BoundedVal( valueU, EDecimal, 0xFFFFFFFF );
+    TL( propertyDef->MaxUint32ValueL() == valueU );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MinInt64ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MinInt64ValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( value ));
+    TLex lex( value );
+    TInt64 value64;
+    lex.Val( value64, 0x7FFFFFFFFFFFFFFF );
+    TL( propertyDef->MinInt64ValueL() == value64 );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MaxInt64ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MaxInt64ValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( value ));
+    TLex lex( value );
+    TInt64 value64;
+    lex.Val( value64, 0x7FFFFFFFFFFFFFFF );
+    TL( propertyDef->MaxInt64ValueL() == value64 );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MinRealValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MinRealValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    aItem.SetParsingType( CStifItemParser::EQuoteStyleParsing );
+    User::LeaveIfError( aItem.GetNextString( value ));
+    TLex lex( value );
+    TReal valueR;
+    lex.Val( valueR );
+    TL( propertyDef->MinRealValueL() == valueR );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MaxRealValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MaxRealValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    aItem.SetParsingType( CStifItemParser::EQuoteStyleParsing );
+    User::LeaveIfError( aItem.GetNextString( value ));
+    TLex lex( value );
+    TReal valueR;
+    lex.Val( valueR );
+    TL( propertyDef->MaxRealValueL() == valueR );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MinTimeValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MinTimeValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( value ));
+    TTime time;
+    TL( time.Set( value ) == KErrNone );
+    TL( propertyDef->MinTimeValueL() == time );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MaxTimeValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MaxTimeValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( value ));
+    TTime time;
+    TL( time.Set( value ) == KErrNone );
+    TL( propertyDef->MaxTimeValueL() == time );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MinTextLengthL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MinTextLengthL( CStifItemParser& aItem )
+    {
+    TInt value;
+
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    TL( propertyDef->MinTextLengthL() == value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MaxTextLengthL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MaxTextLengthL( CStifItemParser& aItem )
+    {
+    TInt value;
+
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    TL( propertyDef->MaxTextLengthL() == value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::DefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::DefL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+
+    if ( mode == EObjectDef )
+        {
+           CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem);
+           CMdEObjectDef& objDef = object->Def();
+        TL( &objDef );
+        iObjectDefArray.Append( &objDef );
+        AppendNameL( iObjectDefNameArray, name );
+        }
+    else if ( mode == ERelationDef )
+        {
+           CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem);
+           CMdERelationDef& relDef = relation->Def();        
+        TL( &relDef );
+        iRelationDefArray.Append( &relDef );
+        AppendNameL( iRelationDefNameArray, name );
+        }
+    else if ( mode == EPropertyDef )
+        {
+           CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem);
+           const CMdEPropertyDef& propDef = property->Def();      
+        TL( &propDef );
+        iPropertyDefArray.Append( &propDef );
+        AppendNameL( iPropertyDefNameArray, name );
+        }
+    else if ( mode == EEventDef )
+        {
+        CMdEEvent* event = SanitizeArrayIndexL( iEventArray, *iEventNameArray, aItem );
+        CMdEEventDef& eventDef = event->Def();
+        TL( &eventDef );
+        iEventDefArray.Append( &eventDef );
+        AppendNameL( iEventDefNameArray, name );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetDefL( CStifItemParser& aItem )
+    {
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEObjectDef* objectDef = SanitizeArrayIndexL( iObjectDefArray, *iObjectDefNameArray, aItem );
+    object->SetDefL( *objectDef );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::UriL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::UriL( CStifItemParser& aItem )
+    {
+
+    TPtrC uri;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( uri ));
+    TL( object->Uri().Compare( uri ) == 0 );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetUriL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetUriL( CStifItemParser& aItem )
+    {
+
+    TPtrC uri;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( uri ));
+    object->SetUriL( uri );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ConfidentialL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::ConfidentialL( CStifItemParser& aItem )
+    {
+    TInt state;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( state ));
+    TL( object->Confidential() == (TBool)state );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetConfidentialL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetConfidentialL( CStifItemParser& aItem )
+    {
+    TInt state;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( state ));
+
+    object->SetConfidential( (TBool)state );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::PlaceholderL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::PlaceholderL( CStifItemParser& aItem )
+    {
+    TInt state;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( state ));
+    TL( object->Placeholder() == (TBool)state );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetPlaceholderL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetPlaceholderL( CStifItemParser& aItem )
+    {
+    TInt state;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( state ));
+
+    object->SetPlaceholder( (TBool)state );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MediaIdL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MediaIdL( CStifItemParser& aItem )
+    {
+    TInt mediaId;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( mediaId ));
+
+    TL( object->MediaId() == mediaId );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetMediaIdL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetMediaIdL( CStifItemParser& aItem )
+    {
+    TInt mediaId;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( mediaId ));
+
+    object->SetMediaId( mediaId );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::UsageCountL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::UsageCountL( CStifItemParser& aItem )
+    {
+
+    TInt count;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( count ));
+
+    TL( object->UsageCount() == count );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::GuidL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::GuidL( CStifItemParser& aItem )
+    {
+    TInt mode;
+
+    TInt guidHighExpected;
+    TInt guidLowExpected;
+    TInt64 guidHigh;
+    TInt64 guidLow;
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    if ( mode == EObject )
+        {
+        CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+        User::LeaveIfError( aItem.GetNextInt( guidHighExpected ));
+        User::LeaveIfError( aItem.GetNextInt( guidLowExpected ));        
+        object->Guid( guidHigh, guidLow );
+        }
+    else if ( mode == ERelation )
+        {
+        CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+        User::LeaveIfError( aItem.GetNextInt( guidHighExpected ));
+        User::LeaveIfError( aItem.GetNextInt( guidLowExpected ));     
+        relation->Guid( guidHigh, guidLow );
+        }
+          
+    TL( guidHighExpected == guidHigh );
+    TL( guidLowExpected == guidLow );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetGuidL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetGuidL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    
+    TInt guidHigh;
+    TInt guidLow;
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    if ( mode == EObject )
+        {
+        CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+        User::LeaveIfError( aItem.GetNextInt( guidHigh ));
+        User::LeaveIfError( aItem.GetNextInt( guidLow ));        
+        object->SetGuid( guidHigh, guidLow );
+        }
+    else if ( mode == ERelation )
+        {
+        CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+        User::LeaveIfError( aItem.GetNextInt( guidHigh ));
+        User::LeaveIfError( aItem.GetNextInt( guidLow ));     
+        relation->SetGuid( guidHigh, guidLow );
+        }
+        
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::OpenForModifications
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::OpenForModificationsL( CStifItemParser& aItem )
+    {
+    TInt open;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( open ));
+
+    TBool state = object->OpenForModifications();
+    TL( (TBool)open == state );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::NewObjectL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::NewObjectL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    CMdEObject* object = NULL;
+
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));    
+    
+    CMdEObjectDef* objectDef = SanitizeArrayIndexL( iObjectDefArray, *iObjectDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+
+    if ( mode == KL )
+        {
+        object = iMdeSession->NewObjectL(
+            *objectDef, MdeConstants::Object::KAutomaticUri );
+        }
+    else if ( mode == KLC )
+        {
+        object = iMdeSession->NewObjectLC(
+            *objectDef, MdeConstants::Object::KAutomaticUri );
+        CleanupStack::Pop( object );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    TL( object );
+    iObjectArray.Append( object );
+    AppendNameL( iObjectNameArray, name );    
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddObjectL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddObjectL( CStifItemParser& aItem )
+    {
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+
+    TItemId id = iMdeSession->AddObjectL( *object );
+    TL( id != KNoId );
+    TL( object->Id() == id );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddObjectsL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddObjectsL( CStifItemParser& aItem )
+    {
+    TInt count;
+    RPointerArray<CMdEObject> objectArray;
+
+    TInt firstIndex = GetObjectIndexL( aItem );
+    User::LeaveIfError( aItem.GetNextInt( count ));
+
+    for ( TInt i = 0; i < count; ++i )
+        {
+        objectArray.Append( iObjectArray[ firstIndex + i ] );
+        }
+
+    TInt err = iMdeSession->AddObjectsL( objectArray );
+    objectArray.Reset();
+    T1L ( err, KErrNone );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::GetObjectL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::GetObjectL( CStifItemParser& aItem )
+    {
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));
+
+    TInt mode1;
+    TInt mode2;
+    CMdEObject* newObject = NULL;
+    CMdEObjectDef* objectDef = NULL;
+    CMdENamespaceDef* namespaceDef = NULL;
+    TInt64 guidHigh = 0;
+    TInt64 guidLow = 0;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+
+    User::LeaveIfError( aItem.GetNextInt( mode1 ));
+    User::LeaveIfError( aItem.GetNextInt( mode2 ));
+
+    if ( mode2 == EObjectDef )
+        {
+        objectDef = SanitizeArrayIndexL( iObjectDefArray, *iObjectDefNameArray, aItem );
+        }
+        else if ( mode2 == ENamespaceDef )
+        {
+        namespaceDef = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+        }
+
+    if ( mode1 == KById && mode2 == EObjectDef )
+        {
+        newObject = iMdeSession->GetObjectL( object->Id(), *objectDef );
+        }
+    else if ( mode1 == KById && mode2 == ENamespaceDef )
+        {
+        newObject = iMdeSession->GetObjectL( object->Id(), namespaceDef );
+        }
+    else if ( mode1 == KByUri && mode2 == EObjectDef )
+        {
+        newObject = iMdeSession->GetObjectL( object->Uri(), *objectDef );
+        }
+    else if ( mode1 == KByUri && mode2 == ENamespaceDef )
+        {
+        newObject = iMdeSession->GetObjectL( object->Uri(), namespaceDef );
+        }
+    else if ( mode1 == KByGuid && mode2 == EObjectDef )
+        {
+        object->Guid( guidHigh, guidLow );
+        newObject = iMdeSession->GetObjectL( guidHigh, guidLow, *objectDef );
+        }
+    else if ( mode1 == KByGuid && mode2 == ENamespaceDef )
+        {
+        object->Guid( guidHigh, guidLow );
+        newObject = iMdeSession->GetObjectL( guidHigh, guidLow, namespaceDef );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    TL( newObject );
+    iObjectArray.Append( newObject );   
+    AppendNameL( iObjectNameArray, name );
+
+    iLog->Log( _L( "Object Id = %d URI = %S Propertycount = %d" ),
+        newObject->Id(), &newObject->Uri(), newObject->PropertyCount() );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::GetFullObjectL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::GetFullObjectL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    CMdEObject* newObject = NULL;
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));
+    
+    CMdEObjectDef* objectDef = SanitizeArrayIndexL( iObjectDefArray, *iObjectDefNameArray, aItem );
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    if ( mode == KById )
+        {
+        newObject = iMdeSession->GetFullObjectL( object->Id());
+       }
+    else if ( mode == KByUri )
+        {
+        newObject = iMdeSession->GetFullObjectL( object->Uri());
+        }
+    else if ( mode == KByGuid )
+        {
+        TInt64 guidHigh;
+        TInt64 guidLow;
+
+        object->Guid( guidHigh, guidLow );
+        newObject = iMdeSession->GetFullObjectL( guidHigh, guidLow );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+    TL( newObject );
+    iObjectArray.Append( newObject );
+    AppendNameL( iObjectNameArray, name );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::CheckObjectL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::CheckObjectL( CStifItemParser& aItem )
+    {
+    TInt objIndex;
+    TInt mode;
+    TMdEObject tObject;
+
+    objIndex = GetObjectIndexL( aItem );
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+
+    if ( mode == KById )
+        {
+        iMdeSession->CheckObjectL( tObject, iObjectArray[ objIndex ]->Id() );
+        CheckTMdEObjectL( tObject, *iObjectArray[ objIndex ] );
+        }
+    else if ( mode == KByUri )
+        {
+        iMdeSession->CheckObjectL( tObject, iObjectArray[ objIndex ]->Uri() );
+        CheckTMdEObjectL( tObject, *iObjectArray[ objIndex ] );
+        }
+    else if ( mode == KByIds )
+        {
+        TInt count;
+        RArray<TItemId> ids;
+        RArray<TMdEObject> tObjects;
+
+        User::LeaveIfError( aItem.GetNextInt( count ));
+        TL( iObjectArray.Count() > objIndex + count - 1 );
+
+        for ( TInt i = 0; i < count; ++i )
+            {
+            ids.Append( iObjectArray[ objIndex + i ]->Id() );
+            }
+        iMdeSession->CheckObjectL( tObjects, ids );
+        CheckTMdEObjectArrayL( tObjects, objIndex, count );
+
+        tObjects.Reset();
+        ids.Reset();
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveObjectL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveObjectL( CStifItemParser& aItem )
+    {
+    TInt mode;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+
+    TItemId id = KNoId;
+
+    if ( mode == KById )
+        {
+        id = iMdeSession->RemoveObjectL( object->Id() );
+        }
+    else if ( mode == KByUri )
+        {
+        id = iMdeSession->RemoveObjectL( object->Uri() );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    TL( id != KNoId );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveObjectsL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveObjectsL( CStifItemParser& aItem )
+    {
+    TInt mode1;
+    TInt mode2;
+    TInt objIndex;
+    TInt count;
+    TInt needMacroVerifyResult;
+    RArray<TItemId> objectIdArray;
+    RPointerArray<TDesC> objectUriArray;
+    RArray<TItemId> successful;
+    TRequestStatus status = KRequestPending;
+
+    User::LeaveIfError( aItem.GetNextInt( mode1 ));
+    User::LeaveIfError( aItem.GetNextInt( mode2 ));
+    objIndex = GetObjectIndexL( aItem );
+    User::LeaveIfError( aItem.GetNextInt( count ));
+    TL( iObjectArray.Count() > objIndex + count - 1 );
+    TRAPD( err, aItem.GetNextInt( needMacroVerifyResult ) );
+    if ( KErrNone != err )
+        {
+        needMacroVerifyResult = 1;
+        }
+
+    for ( TInt i = 0; i < count; ++i )
+        {
+        if ( mode2 == KById )
+            {
+            objectIdArray.Append( iObjectArray[ objIndex + i ]->Id() );
+            }
+        else if ( mode2 == KByUri )
+            {
+            objectUriArray.Append( &iObjectArray[ objIndex + i ]->Uri() );
+            }
+        }
+
+    if ( mode1 == KSync && mode2 == KById )
+        {
+        iMdeSession->RemoveObjectsL( objectIdArray, successful );
+        }
+    else if ( mode1 == KSync && mode2 == KByUri )
+        {
+        iMdeSession->RemoveObjectsL( objectUriArray, successful );
+        }
+    else if ( mode1 == KAsync && mode2 == KById )
+        {
+        iItemCount = count;
+        TEventIf event( TEventIf::ESetEvent, TName( KMdEObjectsAsyncRemoved ) );
+        iAsyncHandler->Start( this, event );
+        iMdEDataBuf.Close();// make sure the last async request buffer cleaned before using again.
+        iMdeSession->RemoveObjectsAsyncL( objectIdArray, iAsyncHandler->iStatus, iMdEDataBuf );
+        }
+    else if ( mode1 == KAsync && mode2 == KByUri )
+        {
+        iItemCount = count;
+        TEventIf event( TEventIf::ESetEvent, TName( KMdEObjectsAsyncRemoved ) );
+        iAsyncHandler->Start( this, event );
+        iMdEDataBuf.Close();// make sure the last async request buffer cleaned before using again.
+        iMdeSession->RemoveObjectsAsyncL( objectUriArray, iAsyncHandler->iStatus, iMdEDataBuf );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    if( needMacroVerifyResult && KSync == mode1 )
+        {
+        TL( successful.Count() == count );
+        for ( TInt i = 0; i < successful.Count(); ++i )
+            {
+            TL( successful[ i ] != KNoId );
+            }
+        }
+
+    successful.Reset();
+    objectIdArray.Reset();
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveAllObjectsL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveAllObjectsL( CStifItemParser& /* aItem */ )
+    {
+    TInt count = iObjectArray.Count();
+    RArray<TItemId> successful;
+    RArray<TItemId> objectIdArray;
+
+    for ( TInt i = 0; i < count; ++i )
+        {
+        objectIdArray.Append( iObjectArray[ i ]->Id() );
+        }
+
+    if (count)
+        {
+        iMdeSession->RemoveObjectsL( objectIdArray, successful );
+        }
+    objectIdArray.Reset();
+    successful.Reset();
+
+    return KErrNone;
+    }
+// -----------------------------------------------------------------------------
+// CMdETestScripter::OpenObjectL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::OpenObjectL( CStifItemParser& aItem )
+    {
+    _LIT( KMsg1, "Enter OpenObjectL" );
+    iLog->Log( KMsg1 );
+    RDebug::Print( KMsg1 );
+    
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));      
+
+    TInt mode1;
+    TInt mode2;
+    CMdEObject* newObject = NULL;
+    CMdEObjectDef* objectDef = NULL;
+    CMdENamespaceDef* namespaceDef = NULL;
+    TInt64 guidHigh = 0;
+    TInt64 guidLow = 0;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( mode1 ));
+    User::LeaveIfError( aItem.GetNextInt( mode2 ));
+
+    if ( mode2 == EObjectDef )
+        {
+        objectDef = SanitizeArrayIndexL( iObjectDefArray, *iObjectDefNameArray, aItem );
+        }
+        else if ( mode2 == ENamespaceDef )
+        {
+        namespaceDef = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+        }
+
+    if ( mode1 == KById && mode2 == EObjectDef )
+        {
+        newObject = iMdeSession->OpenObjectL( object->Id(), *objectDef );
+        }
+    else if ( mode1 == KById && mode2 == ENamespaceDef )
+        {
+        newObject = iMdeSession->OpenObjectL( object->Id(), namespaceDef );
+        }
+    else if ( mode1 == KByUri && mode2 == EObjectDef )
+        {
+        newObject = iMdeSession->OpenObjectL( object->Uri(), *objectDef );
+        }
+    else if ( mode1 == KByUri && mode2 == ENamespaceDef )
+        {
+        newObject = iMdeSession->OpenObjectL( object->Uri(), namespaceDef );
+        }
+    else if ( mode1 == KByGuid && mode2 == EObjectDef )
+        {
+        object->Guid( guidHigh, guidLow );
+        newObject = iMdeSession->OpenObjectL( guidHigh, guidLow, *objectDef );
+        }
+    else if ( mode1 == KByGuid && mode2 == ENamespaceDef )
+        {
+        object->Guid( guidHigh, guidLow );
+        newObject = iMdeSession->OpenObjectL( guidHigh, guidLow, namespaceDef );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+    TL( newObject );
+    iObjectArray.Append( newObject );
+    AppendNameL( iObjectNameArray, name );
+
+    _LIT( KMsg2, "Exit OpenObjectL" );
+    iLog->Log( KMsg2 );
+    RDebug::Print( KMsg2 );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::OpenFullObjectL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::OpenFullObjectL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));  
+    CMdEObject* newObject = NULL;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+
+    if ( mode == KById )
+        {
+        newObject = iMdeSession->OpenFullObjectL( object->Id() );
+        }
+    else if ( mode == KByUri )
+        {
+        newObject = iMdeSession->OpenFullObjectL( object->Uri() );
+        }
+    else if ( mode == KByGuid )
+        {
+        TInt64 guidHigh;
+        TInt64 guidLow;
+
+        object->Guid( guidHigh, guidLow );
+        newObject = iMdeSession->OpenFullObjectL( guidHigh, guidLow );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+    TL( newObject );
+    if ( !newObject->OpenForModifications() )
+        {
+        return KErrLocked;
+        }
+    iObjectArray.Append( newObject );
+    AppendNameL( iObjectNameArray, name );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::CommitObjectL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::CommitObjectL( CStifItemParser& aItem )
+    {
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    iMdeSession->CommitObjectL( *object );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::CommitObjectsL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::CommitObjectsL( CStifItemParser& aItem )
+    {
+    TInt objIndex;
+    TInt count;
+    RPointerArray<CMdEObject> objectArray;
+
+    objIndex = GetObjectIndexL( aItem );
+
+    User::LeaveIfError( aItem.GetNextInt( count ));
+
+    for ( TInt i = 0; i < count; ++i )
+        {
+        objectArray.Append( iObjectArray[ objIndex + i ] );
+        }
+
+    iMdeSession->CommitObjectsL( objectArray );
+    
+    objectArray.Reset();
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::CancelObjectL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::CancelObjectL( CStifItemParser& aItem )
+    {
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+
+    iMdeSession->CancelObjectL( *object );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::PropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::PropertyL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));  
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+
+    const CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );    
+    CMdEProperty* property;
+
+    if ( mode == KByIndex )
+        {
+        TInt index;
+
+        User::LeaveIfError( aItem.GetNextInt( index ));
+        property = &object->PropertyL( index );
+        }
+    else if ( mode == KByDef )
+        {
+        CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+        TInt startAt;
+        User::LeaveIfError( aItem.GetNextInt( startAt ));        
+        TL( object->Property( *propertyDef, property, startAt ) != KErrNotFound );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+    TL( property );
+
+    iPropertyArray.Append ( property );
+    AppendNameL( iPropertyNameArray, name );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::PropertyCountL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::PropertyCountL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    TInt count;
+    TInt state = 0;
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    const CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+
+    if ( mode == EObject )
+        {
+        state = object->PropertyCount();
+        }
+    else if ( mode == EPropertyDef )
+        {
+        CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+        state = object->PropertyCount( *propertyDef );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    User::LeaveIfError( aItem.GetNextInt( count ));
+    TL( count == state );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddBoolPropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddBoolPropertyL( CStifItemParser& aItem )
+    {
+    TInt value;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    CMdEProperty& prop = object->AddBoolPropertyL( *propertyDef, (TBool)value );
+    TL( &prop );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddInt8PropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddInt8PropertyL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    CMdEProperty& prop = object->AddInt8PropertyL( *propertyDef, value );
+    TL( &prop );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddUint8PropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddUint8PropertyL( CStifItemParser& aItem )
+    {
+    TInt value;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    CMdEProperty& prop = object->AddUint8PropertyL( *propertyDef, value );
+    TL( &prop );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddInt16PropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddInt16PropertyL( CStifItemParser& aItem )
+    {
+    TInt value;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    CMdEProperty& prop = object->AddInt16PropertyL( *propertyDef, value );
+    TL( &prop );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddUint16PropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddUint16PropertyL( CStifItemParser& aItem )
+    {
+    TInt value;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( value ));    
+    
+    CMdEProperty& prop = object->AddUint16PropertyL( *propertyDef, value );
+    TL( &prop );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddInt32PropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddInt32PropertyL( CStifItemParser& aItem )
+    {
+    TInt value;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    CMdEProperty& prop = object->AddInt32PropertyL( *propertyDef, value );
+    TL( &prop );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddUint32PropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddUint32PropertyL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    CMdEProperty& prop = object->AddUint32PropertyL( *propertyDef, value );
+    TL( &prop );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddInt64PropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddInt64PropertyL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    CMdEProperty& prop = object->AddInt64PropertyL( *propertyDef, value );
+    TL( &prop );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddReal32PropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddReal32PropertyL( CStifItemParser& aItem )
+    {
+    TInt value;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    CMdEProperty& prop = object->AddReal32PropertyL( *propertyDef, value );
+    TL( &prop );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddReal64PropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddReal64PropertyL( CStifItemParser& aItem )
+    {
+    TInt value;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    CMdEProperty& prop = object->AddReal64PropertyL( *propertyDef, value );
+    TL( &prop );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddTextPropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddTextPropertyL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+ 
+    aItem.SetParsingType( CStifItemParser::EQuoteStyleParsing );
+    User::LeaveIfError( aItem.GetNextString( value ));
+
+    CMdEProperty& prop = object->AddTextPropertyL( *propertyDef, value );
+    TL( &prop );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddTimePropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddTimePropertyL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );  
+    User::LeaveIfError( aItem.GetNextString( value ));
+
+    TTime time;
+    TL( time.Set( value ) == KErrNone );
+    CMdEProperty& prop = object->AddTimePropertyL( *propertyDef, time );
+    TL( &prop );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ObjectL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::ObjectL( CStifItemParser& aItem )
+    {
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    TL( object == &property->Object() );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::BoolValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::BoolValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );  
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    TL( property->BoolValueL() == value );
+
+    return KErrNone;
+    }
+// -----------------------------------------------------------------------------
+// CMdETestScripter::Int8ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::Int8ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );  
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    TL( property->Int8ValueL() == value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::Uint8ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::Uint8ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );  
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    TL( property->Uint8ValueL() == value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::Int16ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::Int16ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );  
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    TL( property->Int16ValueL() == value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::Uint16ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::Uint16ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );  
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    TL( property->Uint16ValueL() == value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::Int32ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::Int32ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );  
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    TL( property->Int32ValueL() == value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::Uint32ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::Uint32ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );  
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    TL( property->Uint32ValueL() == value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::Int64ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::Int64ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );  
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    TL( property->Int64ValueL() == value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::Real32ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::Real32ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );  
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    TL( property->Real32ValueL() == value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::Real64ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::Real64ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );  
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    TL( property->Real64ValueL() == value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::TimeValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::TimeValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );  
+    User::LeaveIfError( aItem.GetNextString( value ));
+
+    TTime time;
+    TL( time.Set( value ) == KErrNone );
+    TL( property->TimeValueL() == time );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::TextValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::TextValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );  
+    aItem.SetParsingType( CStifItemParser::EQuoteStyleParsing );
+    User::LeaveIfError( aItem.GetNextString( value ));
+
+    TL( value.Compare( property->TextValueL()) == 0 );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetBoolValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetBoolValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem ); 
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    property->SetBoolValueL( value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetInt8ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetInt8ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem ); 
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    property->SetInt8ValueL( value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetUint8ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetUint8ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem ); 
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    property->SetUint8ValueL( value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetInt16ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetInt16ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem ); 
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    property->SetInt16ValueL( value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetUint16ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetUint16ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    property->SetUint16ValueL( value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetInt32ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetInt32ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem ); 
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    property->SetInt32ValueL( value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetUint32ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetUint32ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem ); 
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    property->SetUint32ValueL( value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetInt64ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetInt64ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem ); 
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    property->SetInt64ValueL( value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetReal32ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetReal32ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( value ));
+    property->SetReal32ValueL( value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetReal64ValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetReal64ValueL( CStifItemParser& aItem )
+    {
+    TInt value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem ); 
+    User::LeaveIfError( aItem.GetNextInt( value ));
+
+    property->SetReal64ValueL( value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetTimeValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetTimeValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( value ));
+    TTime time;
+    TL( time.Set( value ) == KErrNone );
+    property->SetTimeValueL( time );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetTextValueL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetTextValueL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+    CMdEProperty* property = SanitizeArrayIndexL( iPropertyArray, *iPropertyNameArray, aItem );
+    aItem.SetParsingType( CStifItemParser::EQuoteStyleParsing );
+    User::LeaveIfError( aItem.GetNextString( value ));
+    property->SetTextValueL( value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemovePropertyL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemovePropertyL( CStifItemParser& aItem )
+    {
+    TPtrC propertyDefName;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( propertyDefName ));
+
+    CMdEPropertyDef& propertyDef = object->Def().GetPropertyDefL( propertyDefName );
+    CMdEProperty* property = NULL;
+    TInt propIndex = object->Property( propertyDef, property );
+    TL( propIndex );
+    object->RemoveProperty( propIndex );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::FreeTextCountL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::FreeTextCountL( CStifItemParser& aItem )
+    {
+    TInt count;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( count ));
+
+    TInt state = object->FreeTextCount();
+    TL( count == state );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::FreeTextL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::FreeTextL( CStifItemParser& aItem )
+    {
+    TInt index;
+    TPtrC text;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( index ));
+    User::LeaveIfError( aItem.GetNextString( text ));
+
+    TPtrC state = object->FreeText( index );
+    TL( text.Compare( state ) == 0 );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::FreeTextIndexL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::FreeTextIndexL( CStifItemParser& aItem )
+    {
+    TInt index;
+    TPtrC value;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( index ));
+    User::LeaveIfError( aItem.GetNextString( value ));
+
+    TInt state = object->FreeTextIndex( value );
+    TA1L( state, index );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddFreeTextL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddFreeTextL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( value ));
+
+    object->AddFreeTextL( value );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveFreeTextL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveFreeTextL( CStifItemParser& aItem )
+    {
+    TInt index;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( index ));
+
+    object->RemoveFreeText( index );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::MovePropertiesL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::MovePropertiesL( CStifItemParser& aItem )
+    {
+    CMdEObject* sourceObj = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEObject* targetObj = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+
+    targetObj->MovePropertiesL( *sourceObj );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::NewRelationL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::NewRelationL( CStifItemParser& aItem )
+    {
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));  
+    TPtrC relationString;
+    TInt parameter;
+    TInt mode;
+
+    CMdEObject* sourceObj = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdERelationDef* relationDef = SanitizeArrayIndexL( iRelationDefArray, *iRelationDefNameArray, aItem );
+    CMdEObject* targetObj = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( parameter ));
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+
+    CMdERelation* relation = NULL;
+
+    if ( mode == KL )
+        {
+        relation = iMdeSession->NewRelationL( *relationDef, sourceObj->Id(), targetObj->Id(), parameter );
+        }
+    else if ( mode == KLC )
+        {
+        relation = iMdeSession->NewRelationLC( *relationDef, sourceObj->Id(), targetObj->Id(), parameter );
+        CleanupStack::Pop( relation );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    TL( relation );
+    iRelationArray.Append( relation );
+    AppendNameL( iRelationNameArray, name );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddRelationL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddRelationL( CStifItemParser& aItem )
+    {
+    CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+
+    TItemId id = iMdeSession->AddRelationL( *relation );
+    TL( id != KNoId );
+    TL( relation->Id() == id );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::LeftObjectIdL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::LeftObjectIdL( CStifItemParser& aItem )
+    {
+    CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+
+    TL( relation->LeftObjectId() == object->Id() );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RightObjectIdL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RightObjectIdL( CStifItemParser& aItem )
+    {
+    CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+
+    TL( relation->RightObjectId() == object->Id() );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ParameterL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::ParameterL( CStifItemParser& aItem )
+    {
+    TInt parameter;
+
+    CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( parameter ));
+
+    TL( relation->Parameter() == parameter );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetParameterL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetParameterL( CStifItemParser& aItem )
+    {
+    TInt parameter;
+
+    CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( parameter ));
+
+    relation->SetParameter( parameter );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetLeftObjectIdL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetLeftObjectIdL( CStifItemParser& aItem )
+    {
+    CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+
+    relation->SetLeftObjectIdL( object->Id() );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetRightObjectIdL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetRightObjectIdL( CStifItemParser& aItem )
+    {
+    CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+
+    relation->SetRightObjectIdL( object->Id() );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::LastModifiedDateL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::LastModifiedDateL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( value ));
+
+    TTime time;
+    TL( time.Set( value ) == KErrNone );
+
+    TL( relation->LastModifiedDate() == time );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetLastModifiedDateL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetLastModifiedDateL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( value ));
+
+    TTime time;
+    TL( time.Set( value ) == KErrNone );
+
+    relation->SetLastModifiedDate( time );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::GetRelationL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::GetRelationL( CStifItemParser& aItem )
+    {
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));      
+    
+    CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+
+    CMdERelation* newRelation = iMdeSession->GetRelationL( relation->Id());
+
+    TL( newRelation );
+    iRelationArray.Append( newRelation );
+    AppendNameL( iRelationNameArray, name );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::UpdateRelationL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::UpdateRelationL( CStifItemParser& aItem )
+    {
+    CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+
+    TItemId id = iMdeSession->UpdateRelationL( *relation );
+    TL( id != KNoId );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveRelationL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveRelationL( CStifItemParser& aItem )
+    {
+    CMdERelation* relation = SanitizeArrayIndexL( iRelationArray, *iRelationNameArray, aItem );
+
+    TItemId id = iMdeSession->RemoveRelationL( relation->Id() );
+    TL( id != KNoId );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveRelationsL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveRelationsL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    TInt relIndex;
+    TInt count;
+    RArray<TItemId> relationIdArray;
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    relIndex = GetRelationIndexL( aItem );
+
+    User::LeaveIfError( aItem.GetNextInt( count ));
+    TL( iRelationArray.Count() > relIndex + count - 1 );
+
+    for ( TInt i = 0; i < count; ++i )
+        {
+        relationIdArray.Append( iRelationArray[ relIndex + i ]->Id() );
+        }
+
+    if ( mode == KSync )
+        {
+        RArray<TItemId> successful;
+
+        iMdeSession->RemoveRelationsL( relationIdArray, successful );
+        }
+    else if ( mode == KAsync )
+        {
+        iItemCount = count;
+        TEventIf event( TEventIf::ESetEvent, TName( KMdERelationsAsyncRemoved ) );
+        iAsyncHandler->Start( this, event );
+        iMdEDataBuf.Close();// make sure the last async request buffer cleaned before using again.
+        iMdeSession->RemoveRelationsAsyncL( relationIdArray, iAsyncHandler->iStatus, iMdEDataBuf );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::NewEventL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::NewEventL( CStifItemParser& aItem )
+    {
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));  
+
+    TPtrC eventSource;
+    TPtrC eventParticipant;
+    TPtrC value;
+    TInt mode;
+
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+    CMdEEventDef* eventDef = SanitizeArrayIndexL( iEventDefArray, *iEventDefNameArray, aItem );
+    
+    User::LeaveIfError( aItem.GetNextString( eventSource ));
+    User::LeaveIfError( aItem.GetNextString( eventParticipant ));
+    User::LeaveIfError( aItem.GetNextString( value ));
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+
+    TTime time;
+    TL( time.Set( value ) == KErrNone );
+    CMdEEvent* event = NULL;
+
+    if ( mode == KL )
+        {
+        event = iMdeSession->NewEventL(
+            *eventDef, object->Id(),
+            time, &eventSource, &eventParticipant );
+        }
+    else if ( mode == KLC )
+        {
+        event = iMdeSession->NewEventLC(
+            *eventDef, object->Id(),
+            time, &eventSource, &eventParticipant );
+        CleanupStack::Pop( event );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    TL( event );
+    iEventArray.Append( event );
+    AppendNameL( iEventNameArray, name );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddEventL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddEventL( CStifItemParser& aItem )
+    {
+    CMdEEvent* event = SanitizeArrayIndexL( iEventArray, *iEventNameArray, aItem );
+
+    TItemId id = iMdeSession->AddEventL( *event );
+    TL( id != KNoId );
+    TL( event->Id() == id );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ObjectIdL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::ObjectIdL( CStifItemParser& aItem )
+    {
+    CMdEEvent* event = SanitizeArrayIndexL( iEventArray, *iEventNameArray, aItem );
+    CMdEObject* object = SanitizeArrayIndexL( iObjectArray, *iObjectNameArray, aItem );
+
+    TL( event->ObjectId() == object->Id() );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::TimeL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::TimeL( CStifItemParser& aItem )
+    {
+    TPtrC value;
+
+    CMdEEvent* event = SanitizeArrayIndexL( iEventArray, *iEventNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( value ));
+
+    TTime time;
+    TL( time.Set( value ) == KErrNone );
+
+    TL( event->Time() == time );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SourceL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SourceL( CStifItemParser& aItem )
+    {
+    TPtrC source;
+    TInt expected;
+
+    CMdEEvent* event = SanitizeArrayIndexL( iEventArray, *iEventNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( source ));
+    User::LeaveIfError( aItem.GetNextInt( expected ));
+
+    TInt result = event->Source()->Compare( source );
+    TL( result == expected );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ParticipantL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::ParticipantL( CStifItemParser& aItem )
+    {
+    TPtrC participant;
+    TInt expected;
+
+    CMdEEvent* event = SanitizeArrayIndexL( iEventArray, *iEventNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( participant ));
+    User::LeaveIfError( aItem.GetNextInt( expected ));
+
+    TInt result = event->Participant()->Compare( participant );
+    TL( result == expected );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::GetEventL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::GetEventL( CStifItemParser& aItem )
+    {
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));    
+    CMdEEvent* event = SanitizeArrayIndexL( iEventArray, *iEventNameArray, aItem );
+
+    CMdEEvent* newEvent = iMdeSession->GetEventL( event->Id());
+
+    TL( event );
+    iEventArray.Append( newEvent );
+    AppendNameL( iEventNameArray, name );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveEventL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveEventL( CStifItemParser& aItem )
+    {
+    CMdEEvent* event = SanitizeArrayIndexL( iEventArray, *iEventNameArray, aItem );
+    TItemId id = iMdeSession->RemoveEventL( event->Id() );
+    TL( id != KNoId );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveEventsL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveEventsL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    TInt eventIndex;
+    TInt count;
+    RArray<TItemId> successful;
+    RArray<TItemId> eventIdArray;
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    eventIndex = GetEventIndexL( aItem );
+    User::LeaveIfError( eventIndex );
+    TL( iEventArray.Count() > eventIndex );
+    User::LeaveIfError( aItem.GetNextInt( count ));
+    TL( iEventArray.Count() > eventIndex + count - 1 );
+
+    for ( TInt i = 0; i < count; ++i )
+        {
+        eventIdArray.Append( iEventArray[ eventIndex + i ]->Id() );
+        }
+
+    if ( mode == KSync )
+        {
+        iMdeSession->RemoveEventsL( eventIdArray, successful );
+        }
+    else if ( mode == KAsync )
+        {
+        iItemCount = count;
+        TEventIf event( TEventIf::ESetEvent, TName( KMdEEventsAsyncRemoved ) );
+        iAsyncHandler->Start( this, event );
+        iMdEDataBuf.Close();// make sure the last async request buffer cleaned before using again.
+        iMdeSession->RemoveEventsAsyncL( eventIdArray, iAsyncHandler->iStatus, iMdEDataBuf );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    successful.Reset();
+    eventIdArray.Reset();
+
+    return KErrNone;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/src/MdETestScripterQueryCommands.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1826 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+// [INCLUDE FILES] - do not remove
+#include <mdeobject.h>
+#include <mdeobjectquery.h>
+#include <mdeconstants.h>
+#include <StifParser.h>
+#include <StifTestInterface.h>
+#include "MdETestScripter.h"
+
+const TInt KRootCond = -1;
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::FindL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::FindL( CStifItemParser& aItem )
+	{
+	TInt maxCount;
+	User::LeaveIfError( aItem.GetNextInt( maxCount ) );
+	TInt notifyCount;
+	User::LeaveIfError( aItem.GetNextInt( notifyCount ) );
+	
+	iQuery->FindL( maxCount, notifyCount );
+	return KErrNone;
+	}
+
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::QueryObjectL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::QueryObjectL( CStifItemParser& aItem )
+    {
+    TPtrC objectString;
+    
+    CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+    
+    User::LeaveIfError( aItem.GetNextString( objectString ));
+	CMdEObjectDef& objdef = space->GetObjectDefL( objectString );
+	
+	delete iQuery;
+	iQuery = NULL;
+	iQuery = iMdeSession->NewObjectQueryL( *space, objdef, this );
+	iQuery->SetResultMode( EQueryResultModeId );
+	iQuery->FindL(1);
+
+    return KErrNone;
+    }
+    
+	
+// -----------------------------------------------------------------------------
+// CMdETestScripter::NewObjectQueryL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::NewObjectQueryL( CStifItemParser& aItem )
+	{
+    TPtrC name;
+	User::LeaveIfError( aItem.GetNextString( name )); 
+    CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );	 		
+    TPtrC modeString;
+    User::LeaveIfError( aItem.GetNextString( modeString ));
+    TQueryResultMode modeEnum = ResultModeL( modeString );
+    
+    TPtrC objectString;
+    User::LeaveIfError( aItem.GetNextString( objectString ));
+
+	CMdEObjectDef& objdef = space->GetObjectDefL( objectString );
+	
+	delete iQuery;
+	iQuery = NULL;
+	
+	TPtrC type;
+	User::LeaveIfError( aItem.GetNextString( type ));
+	if ( type.Compare(_L("Object")) == 0 )
+		{
+		iQuery = iMdeSession->NewObjectQueryL( *space, objdef, this );			
+		}		
+	else if ( type.Compare(_L("LookupObject")) == 0 )
+		{		
+		RPointerArray<CMdEObjectDef> *objDefs = new (ELeave) RPointerArray<CMdEObjectDef>;
+		TPtrC startMark;
+		User::LeaveIfError( aItem.GetNextString( startMark ));
+		if ( startMark.Compare(_L("{")) == 0)
+			{
+			TInt index;
+			while( ETrue )
+				{
+				index = GetObjectDefIndexL( aItem );
+				if ( index == KErrCompletion )
+					{
+					break;
+					}
+				objDefs->Append( iObjectDefArray[ index ] );
+				}	
+			}
+		iQuery = iMdeSession->NewObjectQueryL( objdef, objDefs, this );	
+		}
+	else
+        {
+    	User::Leave( KErrArgument );
+        }
+	
+
+	iQuery->SetResultMode( modeEnum );
+	CMdELogicCondition* rootLogicCondition = &iQuery->Conditions();
+    iLogicConditionArray.Append( rootLogicCondition );
+    AppendNameL( iLogicConditionNameArray, name );		
+	return KErrNone;	
+	}
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::NewRelationQueryL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::NewRelationQueryL( CStifItemParser& aItem )
+	{	
+	
+    TPtrC name;
+	User::LeaveIfError( aItem.GetNextString( name ));  	
+	delete iQuery;
+	iQuery = NULL;
+	CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+    TPtrC modeString;
+    User::LeaveIfError( aItem.GetNextString( modeString ));
+    TQueryResultMode modeEnum = ResultModeL( modeString );
+    
+	iQuery = iMdeSession->NewRelationQueryL( *space, this );
+	iQuery->SetResultMode( modeEnum );
+	CMdELogicCondition* rootLogicCondition = &iQuery->Conditions();
+    iLogicConditionArray.Append( rootLogicCondition );
+    AppendNameL( iLogicConditionNameArray, name );	
+	return KErrNone;		
+	}
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::NewEventQueryL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::NewEventQueryL( CStifItemParser& aItem )
+	{	
+    TPtrC name;
+	User::LeaveIfError( aItem.GetNextString( name ));	
+	
+	delete iQuery;
+	iQuery = NULL;
+    CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );	
+    TPtrC modeString;
+    User::LeaveIfError( aItem.GetNextString( modeString ));
+    TQueryResultMode modeEnum = ResultModeL( modeString );
+
+	iQuery = iMdeSession->NewEventQueryL( *space, this );
+	iQuery->SetResultMode( modeEnum );
+	CMdELogicCondition* rootLogicCondition = &iQuery->Conditions();
+    iLogicConditionArray.Append( rootLogicCondition );
+    AppendNameL( iLogicConditionNameArray, name );		
+	return KErrNone;	
+	}
+	
+// -----------------------------------------------------------------------------	
+// CMdEObjectQuery::AddPropertyFilterL
+// -----------------------------------------------------------------------------
+// 
+TInt CMdETestScripter::AddPropertyFilterL( CStifItemParser& aItem )
+	{
+	CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem);
+	((CMdEObjectQuery *)iQuery)->AddPropertyFilterL( propertyDef );
+	return KErrNone;
+	}	
+
+
+// -----------------------------------------------------------------------------	
+// CMdEObjectQuery::AppendOrderRuleL
+// -----------------------------------------------------------------------------
+// 
+TInt CMdETestScripter::AppendOrderRuleL( CStifItemParser& aItem )
+	{
+	TInt ascending;
+	User::LeaveIfError( aItem.GetNextInt( ascending ) );
+	TInt orderRule;
+	User::LeaveIfError( aItem.GetNextInt( orderRule ) );
+	if ( orderRule == EOrderRuleTypeProperty )
+		{
+		CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem);
+		((CMdEObjectQuery *)iQuery)->AppendOrderRuleL( TMdEOrderRule( *propertyDef, ascending ));
+		}
+	else
+		{
+		((CMdEObjectQuery *)iQuery)->AppendOrderRuleL( TMdEOrderRule( (TOrderRuleType) orderRule, ascending ));	
+		}
+	return KErrNone;	
+	}
+
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::HandleQueryNewResults
+// -----------------------------------------------------------------------------
+//    
+void CMdETestScripter::HandleQueryNewResults( CMdEQuery& /*aQuery*/,
+    TInt /*aFirstNewItemIndex*/, TInt aNewItemCount )
+	{
+	_LIT( KMessage, "Query new results count: " );
+	_LIT( KMessage2, " new count: " );
+	TBuf<128> buf( KMessage );
+	buf.Append( KMessage2 );
+	buf.AppendNum( aNewItemCount );
+
+	}
+	
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::QueryRelationL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::QueryRelationL( CStifItemParser& aItem )
+    {
+    TPtrC relationString;
+    User::LeaveIfError( aItem.GetNextString( relationString ));
+
+	CMdERelationDef& reldef = iNamespaceDefArray[0]->GetRelationDefL( relationString );
+	
+	delete iQuery;
+	iQuery = NULL;	
+	iQuery = iMdeSession->NewRelationQueryL( *iNamespaceDefArray[0], this );
+	iQuery->SetResultMode( EQueryResultModeId );
+	iQueryRoot = &iQuery->Conditions();
+	iQueryRoot->AddRelationConditionL( reldef );	
+	iQuery->FindL(1);
+
+    return KErrNone;
+    }	
+    
+// -----------------------------------------------------------------------------
+// CMdETestScripter::QueryEventL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::QueryEventL( CStifItemParser& aItem )    
+    {
+    TPtrC eventString;
+    User::LeaveIfError( aItem.GetNextString( eventString ));
+
+	CMdEEventDef& evdef = iNamespaceDefArray[0]->GetEventDefL( eventString );
+	
+	delete iQuery;
+	iQuery = NULL;
+	iQuery = iMdeSession->NewEventQueryL( *iNamespaceDefArray[0], this );
+	iQuery->SetResultMode( EQueryResultModeId );
+	iQueryRoot = &iQuery->Conditions();
+	iQueryRoot->AddEventConditionL( evdef );	
+	iQuery->FindL(1);
+
+    return KErrNone;
+    }
+
+_LIT(KAND , "AND");
+_LIT(KOR , "OR");	
+	
+// -----------------------------------------------------------------------------	
+// CMdETestScripter::NewLogicConditionL
+// -----------------------------------------------------------------------------
+//    
+TInt CMdETestScripter::NewLogicConditionL( CStifItemParser& aItem )
+	{
+	TPtrC name;
+	User::LeaveIfError( aItem.GetNextString( name ));
+	TPtrC logicOperator;
+	User::LeaveIfError( aItem.GetNextString( logicOperator ));
+	TLogicConditionOperator logCondOperator = ELogicConditionOperatorAnd;
+	if ( logicOperator.Compare( KAND ) == 0)
+		{
+		logCondOperator = ELogicConditionOperatorAnd;	
+		}
+	else if ( logicOperator.Compare( KOR ) == 0)
+		{
+		logCondOperator = ELogicConditionOperatorOr;		
+		}
+	else
+        {
+    	User::Leave( KErrArgument );
+        }
+	CMdELogicCondition* condition = CMdELogicCondition::NewL( logCondOperator );
+	iLogicConditionArray.Append( condition );
+	AppendNameL( iEventConditionNameArray, name );
+	return KErrNone;	
+	}
+
+
+// -----------------------------------------------------------------------------	
+// CMdETestScripter::RightL
+// -----------------------------------------------------------------------------
+//    
+TInt CMdETestScripter::RightL( CStifItemParser& aItem )
+	{
+	TPtrC name;
+	User::LeaveIfError( aItem.GetNextString( name ));
+	
+	CMdERelationCondition* relationCond = SanitizeArrayIndexL(
+		 iRelationConditionArray, *iRelationConditionNameArray, aItem );			
+	CMdELogicCondition* rightCond = &relationCond->RightL();
+    iLogicConditionArray.Append( rightCond );
+    AppendNameL( iLogicConditionNameArray, name );
+    return KErrNone;
+	}
+
+// -----------------------------------------------------------------------------	
+// CMdETestScripter::LeftL
+// -----------------------------------------------------------------------------
+//    
+TInt CMdETestScripter::LeftL( CStifItemParser& aItem )
+	{
+	TPtrC name;
+	User::LeaveIfError( aItem.GetNextString( name ));
+	
+	CMdERelationCondition* relationCond = SanitizeArrayIndexL( 
+		iRelationConditionArray, *iRelationConditionNameArray, aItem );			
+	CMdELogicCondition* leftCond = &relationCond->LeftL();
+    iLogicConditionArray.Append( leftCond );
+    AppendNameL( iLogicConditionNameArray, name );
+    return KErrNone;
+	}
+
+// -----------------------------------------------------------------------------	
+// CMdETestScripter::SetOperatorL
+// -----------------------------------------------------------------------------
+//    
+TInt CMdETestScripter::SetOperatorL( CStifItemParser& aItem )
+	{
+	CMdELogicCondition* logicCondition = SanitizeArrayIndexL( iLogicConditionArray, *iLogicConditionNameArray, aItem );	
+	TInt logicalOperator;
+	User::LeaveIfError( aItem.GetNextInt( logicalOperator ));
+	logicCondition->SetOperator( ( TLogicConditionOperator )logicalOperator );
+    return KErrNone;
+	}
+	
+// -----------------------------------------------------------------------------	
+// CMdETestScripter::SetNegateL
+// -----------------------------------------------------------------------------
+//    
+TInt CMdETestScripter::SetNegateL( CStifItemParser& aItem )
+	{
+	CMdEPropertyCondition* condition = SanitizeArrayIndexL( iPropertyConditionArray, *iPropertyConditionNameArray, aItem );	
+	TInt boolean;
+	User::LeaveIfError( aItem.GetNextInt( boolean ));
+	((CMdECondition *)condition)->SetNegate( boolean );
+    return KErrNone;
+	}	
+	
+	
+
+// -----------------------------------------------------------------------------	
+// CMdETestScripter::AddLogicConditionL
+// -----------------------------------------------------------------------------
+//    
+TInt CMdETestScripter::AddLogicConditionL( CStifItemParser& aItem )
+	{
+	TPtrC name;
+	User::LeaveIfError( aItem.GetNextString( name ));			
+	
+	CMdELogicCondition* logicCondition = SanitizeArrayIndexL( iLogicConditionArray, *iLogicConditionNameArray, aItem );
+	
+	TPtrC logicOperator;
+	User::LeaveIfError( aItem.GetNextString( logicOperator ));
+	TLogicConditionOperator logCondOperator = ELogicConditionOperatorAnd;
+	if ( logicOperator.Compare( KAND ) == 0)
+		{
+		logCondOperator = ELogicConditionOperatorAnd;	
+		}
+	else if ( logicOperator.Compare( KOR ) == 0)
+		{
+		logCondOperator = ELogicConditionOperatorOr;		
+		}
+	else
+        {
+    	User::Leave( KErrArgument );
+        }
+    CMdELogicCondition* condition = &logicCondition->AddLogicConditionL( logCondOperator );
+    iLogicConditionArray.Append( condition );
+    AppendNameL( iLogicConditionNameArray, name );
+    return KErrNone;
+	}
+
+
+	_LIT(KRelationDef, "RelationDef");
+	_LIT(KRelationDefRange, "RelationDefRange");
+	
+	_LIT(KAny, "Any");
+	_LIT(KEqual, "Equal");
+	_LIT(KNotEqual, "NotEqual");
+	_LIT(KLess, "Less");
+	_LIT(KLessOrEqual, "LessOrEqual");
+	_LIT(KGreater, "Greater");
+	_LIT(KGreaterOrEqual, "GreaterOrEqual");
+	_LIT(KBetween, "Between");
+	_LIT(KNotBetween, "NotBetween");
+
+	_LIT(KObject , "Object");
+	_LIT(KObjectDef , "ObjectDef");
+	_LIT(KGuid , "Guid");
+
+	_LIT(KNone , "None");
+	_LIT(KId , "Id");
+	_LIT(KIds , "Ids");
+	_LIT(KUri , "Uri");
+	_LIT(KUriBeginsWith , "UriBeginsWith");
+	_LIT(KFreeText , "FreeText");
+	_LIT(KFreeTextContains , "FreeTextContains");
+	_LIT(KFreeTextBeginsWith , "FreeTextBeginsWith");
+	_LIT(KFreeTextEndsWith , "FreeTextEndsWith");
+	_LIT(KFreeTextUsageCount , "FreeTextUsageCount");
+
+
+	_LIT(KCount , "Count");
+	_LIT(KItem , "Item");
+	_LIT(KDistinctValues , "DistinctValues");
+	_LIT(KObjectWithFreetexts , "ObjectWithFreetexts");
+
+
+
+TQueryResultMode CMdETestScripter::ResultModeL(TDesC& aModeString)
+	{
+	TQueryResultMode modeEnum = EQueryResultModeId;
+	if ( aModeString.Compare( KId ) == 0 )
+		{
+		modeEnum = EQueryResultModeId;	
+		}
+	else if ( aModeString.Compare( KItem ) == 0 )
+		{
+		modeEnum = EQueryResultModeItem;	
+		}
+	else if ( aModeString.Compare( KCount ) == 0 )
+		{
+		modeEnum = EQueryResultModeCount;	
+		}
+	else if ( aModeString.Compare( KDistinctValues ) == 0 )
+		{
+		modeEnum = EQueryResultModeDistinctValues;	
+		}
+	else if ( aModeString.Compare( KObjectWithFreetexts ) == 0 )
+		{
+		modeEnum = EQueryResultModeObjectWithFreetexts;	
+		}
+	else
+        {
+    	User::Leave( KErrArgument );
+        }
+    return modeEnum;	
+	}
+
+
+CMdERelationDef& CMdETestScripter::GetRelationDefStrL( CStifItemParser& aItem )
+	{
+	TPtrC relationDefStr;
+	User::LeaveIfError( aItem.GetNextString( relationDefStr ));
+	TLex lex( relationDefStr );
+	TInt integer;
+	TInt err = lex.Val( integer );
+	if ( err == KErrGeneral )
+		{
+		return iNamespaceDefArray[0]->GetRelationDefL( relationDefStr );		
+		}
+	else
+		{
+		return *iRelationDefArray[ integer ];	
+		}
+	}
+
+TInt CMdETestScripter::GetObjectDefIndexL( CStifItemParser& aItem )
+	{
+	TPtrC objectDefStr;
+	User::LeaveIfError( aItem.GetNextString( objectDefStr ));
+	TLex lex( objectDefStr );
+	TInt integer;
+	TInt err = lex.Val( integer );
+	if ( err == KErrGeneral )
+		{
+		if ( objectDefStr.Compare( _L("}")) == 0)
+			{ 
+			return KErrCompletion;	// indictes end of list
+			}		
+		for ( TInt i = 0; i < iObjectDefNameArray->Count(); i++)
+			{
+			if ( objectDefStr.Compare( (*iObjectDefNameArray)[i] ) == 0 )
+				{
+				return i;	
+				}
+			}
+		return KErrNotFound;
+		}
+	else
+		{
+		return integer ;	
+		}
+	}
+	
+TInt CMdETestScripter::GetRelationDefIndexL( CStifItemParser& aItem )
+	{
+	TPtrC relationDefStr;
+	User::LeaveIfError( aItem.GetNextString( relationDefStr ));
+	TLex lex( relationDefStr );
+	TInt integer;
+	TInt err = lex.Val( integer );
+	if ( err == KErrGeneral )
+		{
+		for ( TInt i = 0; i < iRelationDefNameArray->Count(); i++)
+			{
+			if ( relationDefStr.Compare( (*iRelationDefNameArray)[i] ) == 0 )
+				{
+				return i;	
+				}
+			}
+		return KErrNotFound;
+		}
+	else
+		{
+		return integer ;	
+		}
+	}	
+
+TInt CMdETestScripter::GetEventDefIndexL( CStifItemParser& aItem )
+	{
+	TPtrC eventDefStr;
+	User::LeaveIfError( aItem.GetNextString( eventDefStr ));
+	TLex lex( eventDefStr );
+	TInt integer;
+	TInt err = lex.Val( integer );
+	if ( err == KErrGeneral )
+		{
+		for ( TInt i = 0; i < iEventDefNameArray->Count(); i++)
+			{
+			if ( eventDefStr.Compare( (*iEventDefNameArray)[i] ) == 0 )
+				{
+				return i;	
+				}
+			}
+		return KErrNotFound;
+		}
+	else
+		{
+		return integer ;	
+		}
+	}	
+
+TInt CMdETestScripter::GetObjectIndexL( CStifItemParser& aItem )
+	{
+	TPtrC objectStr;
+	User::LeaveIfError( aItem.GetNextString( objectStr ));
+	TLex lex( objectStr );
+	TInt integer;
+	TInt err = lex.Val( integer );
+	if ( err == KErrGeneral )
+		{
+		if ( objectStr.Compare( _L("}")) == 0)
+			{ 
+			return KErrCompletion;	// indictes end of list
+			}
+		for ( TInt i = 0; i < iObjectNameArray->Count(); i++)
+			{
+			if ( objectStr.Compare( (*iObjectNameArray)[i] ) == 0 )
+				{
+				return i;	
+				}
+			}
+		return KErrNotFound;
+		}
+	else
+		{
+		return integer ;	
+		}
+	}	
+
+
+TInt CMdETestScripter::GetEventIndexL( CStifItemParser& aItem )
+	{
+	TPtrC eventStr;
+	User::LeaveIfError( aItem.GetNextString( eventStr ));
+	TLex lex( eventStr );
+	TInt integer;
+	TInt err = lex.Val( integer );
+	if ( err == KErrGeneral )
+		{
+		if ( eventStr.Compare( _L("}")) == 0)
+			{ 
+			return KErrCompletion;	// indictes end of list
+			}		
+		for ( TInt i = 0; i < iEventNameArray->Count(); i++)
+			{
+			if ( eventStr.Compare( (*iEventNameArray)[i] ) == 0 )
+				{
+				return i;	
+				}
+			}
+		return KErrNotFound;
+		}
+	else
+		{
+		return integer ;	
+		}
+	}
+
+TInt CMdETestScripter::GetRelationIndexL( CStifItemParser& aItem )
+	{
+	TPtrC relationStr;
+	User::LeaveIfError( aItem.GetNextString( relationStr ));
+	TLex lex( relationStr );
+	TInt integer;
+	TInt err = lex.Val( integer );
+	if ( err == KErrGeneral )
+		{
+		if ( relationStr.Compare( _L("}")) == 0)
+			{ 
+			return KErrCompletion;	// indictes end of list
+			}		
+		for ( TInt i = 0; i < iRelationNameArray->Count(); i++)
+			{
+			if ( relationStr.Compare( (*iRelationNameArray)[i] ) == 0 )
+				{
+				return i;	
+				}
+			}
+		return KErrNotFound;
+		}
+	else
+		{
+		return integer ;	
+		}
+	}
+
+TInt CMdETestScripter::GetLogicConditionIndexL( CStifItemParser& aItem )
+	{
+	TPtrC logicConditionStr;
+	User::LeaveIfError( aItem.GetNextString( logicConditionStr ));
+	TLex lex( logicConditionStr );
+	TInt integer;
+	TInt err = lex.Val( integer );
+	if ( err == KErrGeneral )
+		{
+		for ( TInt i = 0; i < iLogicConditionNameArray->Count(); i++)
+			{
+			if ( logicConditionStr.Compare( (*iLogicConditionNameArray)[i] ) == 0 )
+				{
+				return i;	
+				}
+			}
+		return KErrNotFound;
+		}
+	else
+		{
+		return integer ;	
+		}
+	}
+
+
+TInt CMdETestScripter::GetRelationConditionIndexL( CStifItemParser& aItem )
+	{
+	TPtrC relationConditionStr;
+	User::LeaveIfError( aItem.GetNextString( relationConditionStr ));
+	TLex lex( relationConditionStr );
+	TInt integer;
+	TInt err = lex.Val( integer );
+	if ( err == KErrGeneral )
+		{
+		for ( TInt i = 0; i < iRelationConditionNameArray->Count(); i++)
+			{
+			if ( relationConditionStr.Compare( (*iRelationConditionNameArray)[i] ) == 0 )
+				{
+				return i;	
+				}
+			}
+		return KErrNotFound;
+		}
+	else
+		{
+		return integer ;	
+		}
+	}
+	
+	
+
+TInt CMdETestScripter::GetPropertyDefIndexL( CStifItemParser& aItem )
+	{
+	TPtrC propertyDefStr;
+	User::LeaveIfError( aItem.GetNextString( propertyDefStr ));
+	TLex lex( propertyDefStr );
+	TInt integer;
+	TInt err = lex.Val( integer );
+	if ( err == KErrGeneral )
+		{
+		if ( propertyDefStr.Compare( _L("}")) == 0)
+			{ 
+			return KErrCompletion;	// indictes end of list
+			}
+		for ( TInt i = 0; i < iPropertyDefNameArray->Count(); i++)
+			{
+			if ( propertyDefStr.Compare( (*iPropertyDefNameArray)[i] ) == 0 )
+				{
+				return i;	
+				}
+			}
+		return KErrNotFound;
+		}
+	else
+		{
+		return integer ;	
+		}
+	}
+
+TInt CMdETestScripter::GetPropertyIndexL( CStifItemParser& aItem )
+	{
+	TPtrC propertyStr;
+	User::LeaveIfError( aItem.GetNextString( propertyStr ));
+	TLex lex( propertyStr );
+	TInt integer;
+	TInt err = lex.Val( integer );
+	if ( err == KErrGeneral )
+		{
+		for ( TInt i = 0; i < iPropertyNameArray->Count(); i++)
+			{
+			if ( propertyStr.Compare( (*iPropertyNameArray)[i] ) == 0 )
+				{
+				return i;	
+				}
+			}
+		return KErrNotFound;
+		}
+	else
+		{
+		return integer ;	
+		}
+	}
+
+
+CMdEObjectDef& CMdETestScripter::GetObjectDefStrL( CStifItemParser& aItem )
+	{
+	TPtrC objectDefStr;
+	User::LeaveIfError( aItem.GetNextString( objectDefStr ));
+	TLex lex( objectDefStr );
+	TInt integer;
+	TInt err = lex.Val( integer );
+	if ( err == KErrGeneral )
+		{
+		return iNamespaceDefArray[0]->GetObjectDefL( objectDefStr );		
+		}
+	else
+		{
+		return *iObjectDefArray[ integer ];	
+		}
+	}
+
+TObjectConditionCompareMethod CMdETestScripter::CompareMethodL(TDesC& aMethodString)
+	{
+	TObjectConditionCompareMethod methodEnum = EObjectConditionCompareNone;
+	if ( aMethodString.Compare( KNone ) == 0 )
+		{
+		methodEnum = EObjectConditionCompareNone;	
+		}
+	else if ( aMethodString.Compare( KId ) == 0 )
+		{
+		methodEnum = EObjectConditionCompareId;	
+		}
+	else if ( aMethodString.Compare( KIds ) == 0 )
+		{
+		methodEnum = EObjectConditionCompareIds;	
+		}
+	else if ( aMethodString.Compare( KGuid ) == 0 )
+		{
+		methodEnum = EObjectConditionCompareGuid;	
+		}
+	else if ( aMethodString.Compare( KObjectDef ) == 0 )
+		{
+		methodEnum = EObjectConditionCompareObjectDef;	
+		}
+	else if ( aMethodString.Compare( KUri ) == 0 )
+		{
+		methodEnum = EObjectConditionCompareUri;	
+		}
+	else if ( aMethodString.Compare( KUriBeginsWith ) == 0 )
+		{
+		methodEnum = EObjectConditionCompareUriBeginsWith;	
+		}
+	else if ( aMethodString.Compare( KFreeText ) == 0 )
+		{
+		methodEnum = EObjectConditionCompareFreeText;	
+		}
+	else if ( aMethodString.Compare( KFreeTextContains ) == 0 )
+		{
+		methodEnum = EObjectConditionCompareFreeTextContains;	
+		}
+	else if ( aMethodString.Compare( KFreeTextBeginsWith ) == 0 )
+		{
+		methodEnum = EObjectConditionCompareFreeTextBeginsWith;	
+		}					
+	else if ( aMethodString.Compare( KFreeTextEndsWith ) == 0 )
+		{
+		methodEnum = EObjectConditionCompareFreeTextEndsWith;	
+		}
+	else if ( aMethodString.Compare( KFreeTextUsageCount ) == 0 )
+		{
+		methodEnum = EObjectConditionCompareUsageCount;	
+		}
+	else
+        {
+    	User::Leave( KErrArgument );
+        }
+    return methodEnum;	
+	}
+
+
+TMdERangeType CMdETestScripter::RangeTypeL(TDesC& aTypeString)
+	{
+	TMdERangeType rangeType = EMdERangeTypeAny;
+	if ( aTypeString.Compare( KAny ) == 0 )
+		{
+		rangeType = EMdERangeTypeAny;	
+		}
+	else if ( aTypeString.Compare( KEqual ) == 0 )
+		{
+		rangeType = EMdERangeTypeEqual;	
+		}
+	else if ( aTypeString.Compare( KNotEqual ) == 0 )
+		{
+		rangeType = EMdERangeTypeNotEqual;	
+		}
+	else if ( aTypeString.Compare( KLess ) == 0 )
+		{
+		rangeType = EMdERangeTypeLess;	
+		}
+	else if ( aTypeString.Compare( KLessOrEqual ) == 0 )
+		{
+		rangeType = EMdERangeTypeLessOrEqual;	
+		}
+	else if ( aTypeString.Compare( KGreater ) == 0 )
+		{
+		rangeType = EMdERangeTypeGreater;	
+		}
+	else if ( aTypeString.Compare( KGreaterOrEqual ) == 0 )
+		{
+		rangeType = EMdERangeTypeGreaterOrEqual;	
+		}
+	else if ( aTypeString.Compare( KBetween ) == 0 )
+		{
+		rangeType = EMdERangeTypeBetween;	
+		}
+	else if ( aTypeString.Compare( KNotBetween ) == 0 )
+		{
+		rangeType = EMdERangeTypeNotBetween;	
+		}
+	else
+        {
+    	User::Leave( KErrArgument );
+        }
+    return rangeType;
+	}
+	
+
+// -----------------------------------------------------------------------------	
+// CMdETestScripter::AddObjectConditionL
+// -----------------------------------------------------------------------------
+//    
+TInt CMdETestScripter::AddObjectConditionL( CStifItemParser& aItem )
+	{
+	TPtrC name;
+	User::LeaveIfError( aItem.GetNextString( name ));	
+	CMdEObjectCondition* newObjectCondition = NULL;
+	
+	
+	CMdELogicCondition* logicCondition = SanitizeArrayIndexL( iLogicConditionArray, *iLogicConditionNameArray, aItem );
+	
+#if 0
+	logicConditionIndex = GetLogicConditionIndexL( aItem );    
+	CMdELogicCondition* logicCondition;
+	if ( logicConditionIndex >= 0 )
+		{
+		logicCondition = iLogicConditionArray[ logicConditionIndex ];
+		}
+	else if ( logicConditionIndex == KRootCond )
+		{
+		logicCondition = &iQuery->Conditions();	
+		}
+	else
+		{
+		User::Leave( logicConditionIndex );	
+		}
+
+#endif
+
+	TPtrC type;
+	User::LeaveIfError( aItem.GetNextString( type ));
+
+	_LIT(KObjectConditionCompare , "ObjectConditionCompare");
+
+	_LIT(KRange , "Range");
+	
+	if ( type.Compare( KObject ) == 0)
+		{
+		TInt firstIndex = GetObjectIndexL( aItem );
+		TInt objectCount;
+		User::LeaveIfError( aItem.GetNextInt( objectCount ));
+		if ( objectCount == 1 )
+			{
+			newObjectCondition = &logicCondition->AddObjectConditionL( iObjectArray[ firstIndex ]->Id() );	
+			}
+		else
+			{
+			RArray<TItemId> objectIdArray;
+			for ( TInt i = firstIndex ; i < firstIndex + objectCount ; i++ )
+				{
+				objectIdArray.Append( iObjectArray[ i ]->Id() );
+				}
+			newObjectCondition = &logicCondition->AddObjectConditionL( objectIdArray );			
+			objectIdArray.Reset();	
+			}
+		}
+	else if ( type.Compare( KObjectDef ) == 0 )
+		{
+		newObjectCondition = &logicCondition->AddObjectConditionL( GetObjectDefStrL( aItem ) );
+		}
+	else if ( type.Compare( KGuid ) == 0 )
+		{
+	    TInt guidHigh;
+	    TInt guidLow;
+	    TInt64 guidHigh64;
+	    TInt64 guidLow64;	
+		User::LeaveIfError( aItem.GetNextInt( guidHigh ));
+		guidHigh64 = guidHigh;
+    	User::LeaveIfError( aItem.GetNextInt( guidLow ));
+    	guidLow64 = guidLow;
+		newObjectCondition = &logicCondition->AddObjectConditionL( guidHigh64, guidLow64 );
+		}
+	else if ( type.Compare( KObjectConditionCompare ) == 0 )
+		{
+		TPtrC method;
+		User::LeaveIfError( aItem.GetNextString( method ));
+		TObjectConditionCompareMethod methodEnum = CompareMethodL( method );
+
+	    TPtrC string;
+	    User::LeaveIfError( aItem.GetNextString( string ));
+	    if ( methodEnum == EObjectConditionCompareId )
+		    {
+		    TLex lex( string );
+			TInt integer;
+			TInt err = lex.Val( integer );
+			if ( err == KErrGeneral )
+				{ // string is not a number so it should be a object name
+				for ( TInt i = 0; i < iObjectNameArray->Count(); i++)
+					{
+					if ( string.Compare( (*iObjectNameArray)[i] ) == 0 )
+						{
+						TBuf<20> objIdString;
+						objIdString.Num(iObjectArray[i]->Id());
+						newObjectCondition = &logicCondition->AddObjectConditionL(
+			    			EObjectConditionCompareId, 
+			    			objIdString );
+			    		break;
+						}
+					}					
+				}
+		    }
+		else
+	    	{
+	    	newObjectCondition = &logicCondition->AddObjectConditionL(
+    			methodEnum, 
+    			string);
+	    	}
+		}
+	else if ( type.Compare( KRange ) == 0 )
+		{
+		TPtrC type;
+		User::LeaveIfError( aItem.GetNextString( type ));	
+		TMdERangeType rangeType = RangeTypeL( type );
+	    					
+		TInt min;
+		User::LeaveIfError( aItem.GetNextInt( min ) );
+		TInt max;
+		User::LeaveIfError( aItem.GetNextInt( max ) );
+		newObjectCondition = &logicCondition->AddObjectConditionL( TMdEUintRange(min, max, rangeType));				
+		}
+	else
+        {
+    	User::Leave( KErrArgument );
+        }
+    iObjectConditionArray.Append( newObjectCondition );      
+    AppendNameL( iObjectConditionNameArray, name );
+          
+	return KErrNone;	
+	}	
+
+
+_LIT(KTimeRange, "TimeRange");
+
+// -----------------------------------------------------------------------------	
+// CMdETestScripter::AddPropertyConditionL
+// -----------------------------------------------------------------------------
+//    
+TInt CMdETestScripter::AddPropertyConditionL( CStifItemParser& aItem )
+	{
+	
+	TPtrC name;
+	User::LeaveIfError( aItem.GetNextString( name ));	
+	
+	CMdELogicCondition* logicCondition = SanitizeArrayIndexL( iLogicConditionArray, *iLogicConditionNameArray, aItem );
+	
+	CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem);
+
+	TPtrC type;
+	User::LeaveIfError( aItem.GetNextString( type ));
+	_LIT(KPropCond, "PropCond");
+	_LIT(KBool, "Bool");
+	_LIT(KIntRange, "IntRange");
+	_LIT(KInt64Range, "Int64Range");
+	_LIT(KUintRange, "UintRange");
+	_LIT(KRealRange, "RealRange");
+
+	_LIT(KTextCompare, "TextCompare");
+	_LIT(KEquals, "Equals");
+	_LIT(KContains, "Contains");	
+	_LIT(KBeginsWith, "BeginsWith");
+	_LIT(KEndsWith, "EndsWith");
+	
+	CMdEPropertyCondition* propertyCondition = NULL;
+	if (type.Compare( KPropCond ) == 0)
+		{
+		
+		propertyCondition = &logicCondition->AddPropertyConditionL( *propertyDef );	
+		}
+	else if (type.Compare( KBool ) == 0)
+		{
+		TInt boolean;
+		User::LeaveIfError( aItem.GetNextInt( boolean ) );
+		}
+	else if (type.Compare( KIntRange ) == 0)
+		{
+		TPtrC type;
+		User::LeaveIfError( aItem.GetNextString( type ));	
+		TMdERangeType rangeType = RangeTypeL( type );
+	    					
+		TInt min;
+		User::LeaveIfError( aItem.GetNextInt( min ) );
+		TInt max;
+		User::LeaveIfError( aItem.GetNextInt( max ) );
+		propertyCondition = &logicCondition->AddPropertyConditionL( *propertyDef, TMdEIntRange( min, max, rangeType ) );	
+		}
+	else if (type.Compare( KInt64Range ) == 0)
+		{		
+		TPtrC type;
+		User::LeaveIfError( aItem.GetNextString( type ));	
+		TMdERangeType rangeType = RangeTypeL( type );
+	    					
+		TInt min;
+		User::LeaveIfError( aItem.GetNextInt( min ) );
+		TInt64 min64 = min ;
+		TInt max;
+		User::LeaveIfError( aItem.GetNextInt( max ) );
+		TInt64 max64 = max ;
+		propertyCondition = &logicCondition->AddPropertyConditionL( *propertyDef, TMdEInt64Range( min64, max64, rangeType ) );		
+		}
+	else if (type.Compare( KUintRange ) == 0)
+		{
+		TPtrC type;
+		User::LeaveIfError( aItem.GetNextString( type ));	
+		TMdERangeType rangeType = RangeTypeL( type );
+	    					
+		TUint min;
+		User::LeaveIfError( aItem.GetNextInt( min ) );
+		TUint max;
+		User::LeaveIfError( aItem.GetNextInt( max ) );
+		propertyCondition = &logicCondition->AddPropertyConditionL( *propertyDef, TMdEUintRange( min, max, rangeType ) );	
+		}
+	else if (type.Compare( KRealRange ) == 0)
+		{
+		TPtrC type;
+		User::LeaveIfError( aItem.GetNextString( type ));
+
+		TMdERangeType rangeType = RangeTypeL( type );
+	    					
+		TReal min;
+		TPtrC minStr;
+		User::LeaveIfError( aItem.GetNextString( minStr ) );
+		TLex lex( minStr );
+		lex.Val( min );
+		
+		TReal max;
+		TPtrC maxStr;
+		User::LeaveIfError( aItem.GetNextString( maxStr ) );
+		lex.Assign( maxStr );
+		lex.Val( max );
+		
+		propertyCondition = &logicCondition->AddPropertyConditionL( *propertyDef, TMdEIntRange( min, max, rangeType ) );	
+		}
+	else if (type.Compare( KTimeRange ) == 0)
+		{
+		TPtrC type;
+		User::LeaveIfError( aItem.GetNextString( type ));
+
+		TMdERangeType rangeType = RangeTypeL( type );
+	    					
+		TTime min;
+		TPtrC minStr;
+		User::LeaveIfError( aItem.GetNextString( minStr ) );
+		min.Set( minStr );
+		
+		TTime max;
+		TPtrC maxStr;
+		User::LeaveIfError( aItem.GetNextString( maxStr ) );
+		max.Set( maxStr );
+
+		
+		propertyCondition = &logicCondition->AddPropertyConditionL( *propertyDef, TMdETimeRange( min, max, rangeType ) );		
+		}
+	else if (type.Compare( KTextCompare ) == 0)
+		{
+		TPtrC type;
+		User::LeaveIfError( aItem.GetNextString( type ));
+		TTextPropertyConditionCompareMethod compareMethod = ETextPropertyConditionCompareEquals;
+		if (type.Compare( KEquals ) == 0)
+			{
+			compareMethod = ETextPropertyConditionCompareEquals;
+			}
+		else if (type.Compare( KContains ) == 0)
+			{
+			compareMethod = ETextPropertyConditionCompareContains;
+			}
+		else if (type.Compare( KBeginsWith ) == 0)
+			{
+			compareMethod = ETextPropertyConditionCompareBeginsWith;
+			}
+		else if (type.Compare( KEndsWith ) == 0)
+			{
+			compareMethod = ETextPropertyConditionCompareEndsWith;
+			}
+		else
+			{
+			User::Leave( KErrArgument );			
+			}
+		TPtrC text;
+		User::LeaveIfError( aItem.GetNextString( text ) );
+		propertyCondition = &logicCondition->AddPropertyConditionL(
+    		*propertyDef,
+    		compareMethod,
+            text);
+		}
+	else
+		{
+		User::Leave( KErrArgument );	
+		}
+		
+		iPropertyConditionArray.Append( propertyCondition ); 	 
+
+    AppendNameL(iPropertyConditionNameArray, name );		
+	return KErrNone;		
+	}
+    
+
+_LIT(KTimeAndEventCompare, "TimeAndEventCompare");
+
+// -----------------------------------------------------------------------------	
+// CMdETestScripter::AddRelationConditionL
+// -----------------------------------------------------------------------------
+//    
+TInt CMdETestScripter::AddRelationConditionL( CStifItemParser& aItem )
+	{
+	_LIT(KRelationId, "RelationId");
+	_LIT(KLeft, "Left");
+	_LIT(KRight, "Right");
+	_LIT(KEither, "Either");
+	TPtrC name;
+	User::LeaveIfError( aItem.GetNextString( name ));	
+
+	CMdELogicCondition* logicCondition = SanitizeArrayIndexL( iLogicConditionArray, *iLogicConditionNameArray, aItem );
+
+#if 0	
+	TInt logicConditionIndex = GetLogicConditionIndexL( aItem );    
+	CMdELogicCondition* logicCondition;
+	if ( logicConditionIndex >= 0 )
+		{
+		logicCondition = iLogicConditionArray[ logicConditionIndex ];
+		}
+	else if ( logicConditionIndex == KRootCond )
+		{
+		logicCondition = &iQuery->Conditions();	
+		}
+	else
+		{
+		User::Leave( logicConditionIndex );	
+		}
+#endif
+
+	CMdERelationCondition* newRelation = NULL;
+	
+	TPtrC side;
+	User::LeaveIfError( aItem.GetNextString( side ));
+	TRelationConditionSide condSide = ERelationConditionSideEither;
+	if (side.Compare( KLeft ) == 0)
+		{
+		condSide = ERelationConditionSideLeft;
+		}
+	else if (side.Compare( KRight ) == 0)
+		{
+		condSide = ERelationConditionSideRight;
+		}
+	else if (side.Compare( KEither ) == 0)
+		{
+		condSide = ERelationConditionSideEither;
+		}
+	else
+		{
+		User::Leave( KErrArgument );	
+		}	
+	TPtrC type;
+	User::LeaveIfError( aItem.GetNextString( type ));
+	if (type.Compare( KRelationId ) == 0)
+		{
+		TInt id;
+
+		TInt relationIdCount;
+		User::LeaveIfError( aItem.GetNextInt( relationIdCount ));
+		if ( relationIdCount == 1 )
+			{
+			User::LeaveIfError( aItem.GetNextInt( id ) );
+			newRelation = &logicCondition->AddRelationConditionL( TItemId ( id ) , condSide);	
+			}
+		else
+			{
+			RArray<TItemId> relationIdArray;
+			for ( TInt i = 0 ; i < relationIdCount ; i++ )
+				{
+				aItem.GetNextInt( id );
+				relationIdArray.Append( TItemId ( id ));
+				}
+			newRelation = &logicCondition->AddRelationConditionL( TItemId ( id ), condSide );			
+			relationIdArray.Reset();	
+			}		
+		
+		}
+	else if ( type.Compare( KRelationDef ) == 0)
+		{
+		CMdERelationDef& relationDef = GetRelationDefStrL( aItem );
+		newRelation = &logicCondition->AddRelationConditionL( relationDef, condSide );
+		}
+	else if (type.Compare( KRelationDefRange ) == 0)
+		{
+		CMdERelationDef& relationDef = GetRelationDefStrL( aItem );
+		TPtrC type;
+		User::LeaveIfError( aItem.GetNextString( type ));	
+		TMdERangeType rangeType = RangeTypeL( type );
+	    					
+		TInt min;
+		User::LeaveIfError( aItem.GetNextInt( min ) );
+		TInt max;
+		User::LeaveIfError( aItem.GetNextInt( max ) );
+
+		newRelation = &logicCondition->AddRelationConditionL( relationDef,
+			 TMdEIntRange( min, max, rangeType ), condSide );
+		}
+	else
+		{
+		User::Leave( KErrArgument );			
+		}
+	
+	iRelationConditionArray.Append( newRelation );
+	AppendNameL( iRelationConditionNameArray, name );
+	
+	return KErrNone;			
+	}
+
+// -----------------------------------------------------------------------------	
+// CMdETestScripter::AddEventConditionL
+// -----------------------------------------------------------------------------
+// 	
+TInt CMdETestScripter::AddEventConditionL( CStifItemParser& aItem )
+	{
+	_LIT(KEventId, "EventId");
+	_LIT(KNoParam, "NoParam");
+	_LIT(KEventDef, "EventDef");
+	_LIT(KEventCompare, "EventCompare");
+	
+	TPtrC name;
+	User::LeaveIfError( aItem.GetNextString( name ));
+	CMdEEventCondition* newEvent = NULL;
+		
+	TInt logicConditionIndex = GetLogicConditionIndexL( aItem );    
+	CMdELogicCondition* logicCondition = NULL;
+	if ( logicConditionIndex >= 0 )
+		{
+		logicCondition = iLogicConditionArray[ logicConditionIndex ];
+		}
+	else if ( logicConditionIndex == KRootCond )
+		{
+		logicCondition = &iQuery->Conditions();	
+		}
+	else
+		{
+		User::Leave( logicConditionIndex );	
+		}
+	
+	TPtrC type;
+	User::LeaveIfError( aItem.GetNextString( type ));
+	if (type.Compare( KNoParam ) == 0)
+		{
+		logicCondition->AddEventConditionL();		
+		}
+	else if (type.Compare( KEventId ) == 0)
+		{
+		TInt id;
+		User::LeaveIfError( aItem.GetNextInt( id ) );
+		newEvent = &logicCondition->AddEventConditionL( TItemId(id) );		
+		}
+	else if (type.Compare( KEventDef ) == 0)
+		{
+	    TPtrC eventString;
+	    User::LeaveIfError( aItem.GetNextString( eventString ));
+
+		CMdEEventDef& evdef = iNamespaceDefArray[0]->GetEventDefL( eventString );
+		newEvent = &logicCondition->AddEventConditionL( evdef );		
+		}
+	else if (type.Compare( KTimeRange ) == 0)
+		{
+		TPtrC type;
+		User::LeaveIfError( aItem.GetNextString( type ));
+
+		TMdERangeType rangeType = RangeTypeL( type );
+	    					
+		TInt64 min;
+		TPtrC minStr;
+		User::LeaveIfError( aItem.GetNextString( minStr ) );
+		TLex lex( minStr );
+		lex.Val( min );
+		
+		TInt64 max;
+		TPtrC maxStr;
+		User::LeaveIfError( aItem.GetNextString( maxStr ) );
+		lex.Assign( maxStr );
+		lex.Val( max );
+		
+		newEvent = &logicCondition->AddEventConditionL( TMdETimeRange( min, max, rangeType ) );		
+		}		
+	else if (type.Compare( KEventCompare ) == 0)
+		{
+		
+
+		TPtrC type;
+		User::LeaveIfError( aItem.GetNextString( type ));
+
+		_LIT( KNone, "None");
+		_LIT( KSourceURI, "SourceURI");
+		_LIT( KParticipantURI, "ParticipantURI");
+		_LIT( KId, "Id");
+		
+		TEventConditionCompareMethod compareMethod = EEventConditionCompareNone;
+		if (type.Compare( KNone ) == 0)
+			{
+			compareMethod = EEventConditionCompareNone;	
+			}
+		else if (type.Compare( KSourceURI ) == 0)
+			{
+			compareMethod = EEventConditionCompareSourceURI;	
+			}
+		else if (type.Compare( KParticipantURI ) == 0)
+			{
+			compareMethod = EEventConditionCompareParticipantURI;	
+			}
+		else if (type.Compare( KId ) == 0)
+			{
+			compareMethod = EEventConditionCompareId;	
+			}
+		else 		
+			{
+			User::Leave( KErrArgument );			
+			}
+	
+		TPtrC text;
+		User::LeaveIfError( aItem.GetNextString( text ) );
+		newEvent = &logicCondition->AddEventConditionL( compareMethod, text );
+		}
+	else if (type.Compare( KTimeAndEventCompare ) == 0)
+		{
+
+		_LIT( KNone, "None");
+		_LIT( KSourceURI, "SourceURI");
+		_LIT( KParticipantURI, "ParticipantURI");
+		_LIT( KId, "Id");
+
+		TPtrC type;
+		User::LeaveIfError( aItem.GetNextString( type ));
+
+		TMdERangeType rangeType = RangeTypeL( type );
+	    					
+		TInt64 min;
+		TPtrC minStr;
+		User::LeaveIfError( aItem.GetNextString( minStr ) );
+		TLex lex( minStr );
+		lex.Val( min );
+		
+		TInt64 max;
+		TPtrC maxStr;
+		User::LeaveIfError( aItem.GetNextString( maxStr ) );
+		lex.Assign( maxStr );
+		lex.Val( max );
+		
+		TEventConditionCompareMethod compareMethod = EEventConditionCompareNone;
+		if (type.Compare( KNone ) == 0)
+			{
+			compareMethod = EEventConditionCompareNone;	
+			}
+		else if (type.Compare( KSourceURI ) == 0)
+			{
+			compareMethod = EEventConditionCompareSourceURI;	
+			}
+		else if (type.Compare( KParticipantURI ) == 0)
+			{
+			compareMethod = EEventConditionCompareParticipantURI;	
+			}
+		else if (type.Compare( KId ) == 0)
+			{
+			compareMethod = EEventConditionCompareId;	
+			}
+		else 		
+			{
+			User::Leave( KErrArgument );			
+			}
+	
+		TPtrC text;
+		User::LeaveIfError( aItem.GetNextString( text ) );
+		newEvent = &logicCondition->AddEventConditionL( TMdETimeRange( min, max, rangeType ),
+			 compareMethod, text );
+		}
+
+	AppendNameL( iEventConditionNameArray , name );
+	iEventConditionArray.AppendL( newEvent );				
+	return KErrNone;		
+	}
+    
+// -----------------------------------------------------------------------------	
+// CMdETestScripter::ObjectConditionsL
+// -----------------------------------------------------------------------------
+// 	
+TInt CMdETestScripter::ObjectConditionsL( CStifItemParser& aItem )
+	{
+	TPtrC name;
+	User::LeaveIfError( aItem.GetNextString( name ));
+	CMdEEventCondition* eventCondition = SanitizeArrayIndexL( iEventConditionArray, *iEventConditionNameArray, aItem );
+	CMdELogicCondition& objectConditions = eventCondition->ObjectConditionsL();
+	AppendNameL( iLogicConditionNameArray , name );
+	iLogicConditionArray.AppendL( &objectConditions );				
+	return KErrNone;			
+	}
+    
+#if 0    
+    
+void CMdETestScripter::HandleQueryCompleted(CMdEQuery& aQuery, TInt aError)
+	{	
+	TBuf<128> buf;
+	
+	Signal();
+	
+	if (aQuery.Type() == EQueryTypeObject)
+		{
+		iLog->Log(_L("Object query completed notification: Error=%d"), aError);
+
+        TQueryResultMode mode = aQuery.ResultMode();        
+        if ( mode == EQueryResultModeItem )
+            {
+			TInt cou = aQuery.Count();
+
+			buf.Format(_L("  EModeItem, results=%d"), cou);
+			iLog->Log(buf);
+
+			for( TInt i = 0; i < cou; i++ )
+				{
+				const TInt64 rid = (TInt64)aQuery.ResultItem( i ).Id();
+	            buf.Format(_L("  Id %d = %Ld"), i, rid);
+    	        iLog->Log(buf);
+				}
+            }
+        else if ( mode == EQueryResultModeId )
+            {
+            TInt cou = aQuery.Count();
+            
+            buf.Format(_L("  EModeId, results=%d"), cou);
+            iLog->Log(buf);
+			TInt i;
+			TInt64 rid;
+			RArray<TInt64> ridArray;
+			for( i = 0; i < cou; i++ )
+				{
+				rid = (TInt64)aQuery.ResultId( i );
+				ridArray.Append( rid );
+				}
+
+			for( i = cou; --i >= 0; )
+				{
+				for( TInt j = iResultIndices.Count(); --j >= 0 ; )
+					{
+					if ( iObjectArray[ iResultIndices[j]]->Id() == ridArray[i] )
+						{ // matching result
+						iResultIndices.Remove( j );
+						ridArray.Remove( i );
+						}
+					}
+				}
+				
+			if ( iResultIndices.Count() != 0 || iObjectArray.Count() != 0 )
+				{ 
+				_LIT( KTestMessage1, "Not expected object query result" );
+				iLog->Log( KTestMessage1 );
+				return;
+				}
+            }
+        else if ( mode == EQueryResultModeCount )
+            {
+            TInt cou = aQuery.Count();
+            buf.Format(_L("  EModeCount, results=%d"), cou);
+            iLog->Log(buf);
+            }
+		}
+	else if (aQuery.Type() == EQueryTypeRelation)
+		{
+		iLog->Log(_L("Relation query completed notification: Error=%d"), aError);
+		
+        TInt cou = aQuery.Count();
+            
+        buf.Format(_L("  results=%d"), cou);
+        iLog->Log(buf);
+		}
+	else if (aQuery.Type() == EQueryTypeEvent)
+		{
+		iLog->Log(_L("Event query completed notification: Error=%d"), aError);
+
+        TInt cou = aQuery.Count();
+            
+        buf.Format(_L("  results=%d"), cou);
+        iLog->Log(buf);
+		}
+	else
+		{
+		_LIT( KTestMessage2, "Query completed notification of unknown query" );
+		iLog->Log( KTestMessage2 );
+		}
+	}
+
+#else
+
+void CMdETestScripter::HandleQueryCompleted(CMdEQuery& aQuery, TInt /* aError */ )
+	{	
+	TBuf<128> buf;
+	
+	Signal();
+	
+	RArray<TInt64> expectedIdArray;
+    RArray<TInt64> resultIdArray;	
+	
+	if (aQuery.Type() == EQueryTypeObject)
+		{
+		for( TInt j = iResultIndices.Count(); --j >= 0 ; )
+			{
+			expectedIdArray.Append( iObjectArray[ iResultIndices[j]]->Id() );
+			}
+		}
+	else if (aQuery.Type() == EQueryTypeRelation)
+		{
+		for( TInt j = iResultIndices.Count(); --j >= 0 ; )
+			{
+			expectedIdArray.Append( iRelationArray[ iResultIndices[j]]->Id() );
+			}
+		}
+	else if (aQuery.Type() == EQueryTypeEvent)
+		{
+		for( TInt j = iResultIndices.Count(); --j >= 0 ; )
+			{
+			expectedIdArray.Append( iEventArray[ iResultIndices[j]]->Id() );
+			}
+		}
+	else
+		{
+		_LIT( KTestMessage3, "Query completed notification of unknown query" );
+		iLog->Log( KTestMessage3 );
+		}
+		
+	TQueryResultMode mode = aQuery.ResultMode(); 
+	if ( mode == EQueryResultModeCount )
+		{
+		if (aQuery.Count() != iResultIndices.Count())
+			{
+			_LIT( KTestMessage4, "Not expected query result count" );
+			iLog->Log( KTestMessage4 );
+			expectedIdArray.Reset();
+			return;
+			}
+		}
+	else
+		{
+		for (TInt i = 0; i < aQuery.Count(); i++)
+			{
+			if (aQuery.ResultMode() == EQueryResultModeId)
+				{
+				_LIT(KFormat3,"ID: %Ld");
+				const TInt64 id = (TInt64)aQuery.ResultId(i);
+				resultIdArray.Append( id );
+				iLog->Log(KFormat3, id);
+				}
+			else if (aQuery.ResultMode() == EQueryResultModeItem
+					|| aQuery.ResultMode() == EQueryResultModeObjectWithFreetexts)
+				{
+				switch( aQuery.Type() )
+					{
+					case EQueryTypeObject:
+						{
+						_LIT(KFormat5o,"Object ID: %Ld URI: '%S' Def: '%S' Properties: %d Freetexts: %d UsageCount: %d");
+
+						CMdEObject& obj = (CMdEObject&)aQuery.ResultItem(i);
+						const TInt64 objId = (TInt64)obj.Id();
+						resultIdArray.Append( objId );
+						iLog->Log(KFormat5o, objId, &obj.Uri(), &obj.Def().Name(), obj.PropertyCount(), obj.FreeTextCount(), obj.UsageCount());
+						}
+						break;
+					case EQueryTypeRelation:
+						{
+						_LIT(KFormat4r,"Relation ID: %Ld Def: '%S' Left ID: %Ld Right ID: %Ld Param: %d");
+
+						CMdERelation& rel = (CMdERelation&)aQuery.ResultItem(i);
+						const TInt64 relId = (TInt64)rel.Id();
+						resultIdArray.Append( relId );
+						const TInt64 relLId = (TInt64)rel.LeftObjectId();
+						const TInt64 relRId = (TInt64)rel.RightObjectId();
+						iLog->Log(KFormat4r, relId, &rel.Def().Name(), relLId, relRId, rel.Parameter());
+						}
+						break;
+					case EQueryTypeEvent:
+						{
+						_LIT(KFormat4e,"Event ID: %Ld Def: '%S' Object ID: %Ld");
+
+						CMdEEvent& eve = (CMdEEvent&)aQuery.ResultItem(i);
+						const TInt64 eveId = (TInt64)eve.Id();
+						resultIdArray.Append( eveId );
+						const TInt64 eveOId = (TInt64)eve.ObjectId();
+						iLog->Log(KFormat4e, eveId, &eve.Def().Name(), eveOId);
+						}
+						break;
+					}
+				}
+			else if (aQuery.ResultMode() == EQueryResultModeDistinctValues)
+				{
+				_LIT(KFormat5,"Found with text: ");
+
+				buf = KFormat5;
+				buf.Append( aQuery.ResultDistinctValue(i) );
+				iLog->Log( buf );
+				}
+			}
+		
+		
+		if (aQuery.ResultMode() == EQueryResultModeId || aQuery.ResultMode() == EQueryResultModeItem
+					|| aQuery.ResultMode() == EQueryResultModeObjectWithFreetexts )	
+			{
+			for(TInt i = resultIdArray.Count(); --i >= 0; )
+				{
+				for( TInt j = expectedIdArray.Count(); --j >= 0 ; )
+					{
+					if ( expectedIdArray[j] == resultIdArray[i] )
+						{ // matching result
+						expectedIdArray.Remove( j );
+						resultIdArray.Remove( i );
+						break;
+						}
+					}
+				}
+				
+			if ( expectedIdArray.Count() != 0 || resultIdArray.Count() != 0 )
+				{ 		
+				expectedIdArray.Reset();
+				resultIdArray.Reset();
+				_LIT( KTestMessage5, "Not expected object query result" );
+				iLog->Log( KTestMessage5 );
+				return;
+				}			
+			}
+		}	
+	}
+
+#endif	
+
+
+
+TInt CMdETestScripter::SetEventQueryResultL( CStifItemParser& aItem )
+	{
+	iResultIndices.Reset();
+	TPtrC startMark;
+	User::LeaveIfError( aItem.GetNextString( startMark ));
+	TLex lex;
+	TPtrC indexStr;
+	TInt index;
+
+	if ( startMark.Compare(_L("{")) == 0)
+		{
+		while( ETrue )
+			{
+			index = GetEventIndexL( aItem );
+			if ( index == KErrCompletion )
+				{
+				break;
+				}
+			iResultIndices.Append( index );
+			}
+		}
+	return KErrNone;
+	}
+
+TInt CMdETestScripter::SetRelationQueryResultL( CStifItemParser& aItem )
+	{
+	iResultIndices.Reset();
+	TPtrC startMark;
+	User::LeaveIfError( aItem.GetNextString( startMark ));
+	TLex lex;
+	TPtrC indexStr;
+	TInt index;
+
+	if ( startMark.Compare(_L("{")) == 0)
+		{
+		while( ETrue )
+			{
+			index = GetRelationIndexL( aItem );
+			if ( index == KErrCompletion )
+				{
+				break;
+				}
+			iResultIndices.Append( index );
+			}
+		}
+	return KErrNone;	
+	}
+	
+	
+TInt CMdETestScripter::SetObjectQueryResultL( CStifItemParser& aItem )
+	{
+	iResultIndices.Reset();
+	TPtrC startMark;
+	User::LeaveIfError( aItem.GetNextString( startMark ));
+	TLex lex;
+	TPtrC indexStr;
+	TInt index;
+
+	if ( startMark.Compare(_L("{")) == 0)
+		{
+		while( ETrue )
+			{
+			index = GetObjectIndexL( aItem );
+			if ( index == KErrCompletion )
+				{
+				break;
+				}
+			iResultIndices.Append( index );
+			}
+		}
+	return KErrNone;
+	}
+	
+
+// -----------------------------------------------------------------------------	
+// CMdETestScripter::TestPopulateDbL
+// -----------------------------------------------------------------------------
+//    
+TInt CMdETestScripter::TestPopulateDbL( CStifItemParser& /*aItem*/ )
+	{
+	CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+	CMdEObjectDef& objectDef = namespaceDef.GetObjectDefL( MdeConstants::Album::KAlbumObject );
+	CMdEObject* albumObject = iMdeSession->NewObjectL(
+            objectDef, MdeConstants::Object::KAutomaticUri );
+	CMdEPropertyDef& creationDatePropertyDef = objectDef.GetPropertyDefL( MdeConstants::Object::KCreationDateProperty );
+	TTime time( 0 );
+    albumObject->AddTimePropertyL( creationDatePropertyDef, time );
+    
+	CMdEPropertyDef& lastModifiedDatePropertyDef = objectDef.GetPropertyDefL( MdeConstants::Object::KLastModifiedDateProperty );
+
+    albumObject->AddTimePropertyL( lastModifiedDatePropertyDef, time );
+    iMdeSession->AddObjectL( *albumObject );	    
+    
+	CMdEObjectDef& audioObjectDef = namespaceDef.GetObjectDefL( MdeConstants::Audio::KAudioObject );
+	CMdEObject* audioObject = iMdeSession->NewObjectL(
+            audioObjectDef, MdeConstants::Object::KAutomaticUri );
+
+    audioObject->AddTimePropertyL( creationDatePropertyDef, time );
+    
+    audioObject->AddTimePropertyL( lastModifiedDatePropertyDef, time );
+    iMdeSession->AddObjectL( *audioObject );
+    CMdERelationDef& relationDef = namespaceDef.GetRelationDefL( MdeConstants::Relations::KContains );
+    
+    CMdERelation* relation = iMdeSession->NewRelationL( relationDef, albumObject->Id(), audioObject->Id(), 0 );
+    iMdeSession->AddRelationL( *relation );
+    
+    CMdEObjectDef& objDef = namespaceDef.GetObjectDefL( 	MdeConstants::Object::KBaseObject );
+    
+    delete iQuery;
+    iQuery = NULL;
+	iQuery = iMdeSession->NewObjectQueryL( namespaceDef, objDef, this );
+
+	CMdELogicCondition& rootCond = iQuery->Conditions();
+
+	CMdERelationDef& containsRelDef = namespaceDef.GetRelationDefL( 
+		MdeConstants::Relations::KContains );
+
+	CMdERelationCondition& relCond = rootCond.AddRelationConditionL( 
+		containsRelDef, ERelationConditionSideRight );
+	CMdELogicCondition& leftRelCond = relCond.LeftL();
+
+	leftRelCond.AddObjectConditionL( albumObject->Id() );
+
+	iQuery->SetResultMode( EQueryResultModeId );
+
+	iQuery->FindL();
+	return KErrNone;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_plat/metadata_engine_api/tsrc/src/MdETestScripterSchemaCommands.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,762 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+// [INCLUDE FILES] - do not remove
+#include <mdeobject.h>
+#include <mdeconstants.h>
+#include <StifParser.h>
+#include <StifTestInterface.h>
+#include "MdETestScripter.h"
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddSchemaObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddSchemaObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->AddSchemaObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveSchemaObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveSchemaObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->RemoveSchemaObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddObjectObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddObjectObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->AddObjectObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveObjectObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveObjectObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->RemoveObjectObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddObjectPresentObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddObjectPresentObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->AddObjectPresentObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveObjectPresentObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveObjectPresentObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->RemoveObjectPresentObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddRelationObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddRelationObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->AddRelationObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveRelationObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveRelationObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->RemoveRelationObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddRelationItemObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddRelationItemObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->AddRelationItemObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveRelationItemObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveRelationItemObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->RemoveRelationItemObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddRelationPresentObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddRelationPresentObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->AddRelationPresentObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveRelationPresentObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveRelationPresentObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->RemoveRelationPresentObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::AddEventObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::AddEventObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->AddEventObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RemoveEventObserverL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RemoveEventObserverL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->RemoveEventObserverL( *this );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::VerifyTItemIdsL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::VerifyTItemIdsL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    TInt index;
+    TInt count;
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    User::LeaveIfError( aItem.GetNextInt( index ));
+    User::LeaveIfError( aItem.GetNextInt( count ));
+
+    if ( mode == EObject )
+        {
+        CheckTItemIdArrayL( iNotificationItemIdArray, iObjectArray, index, count );
+        }
+    else if ( mode == EEvent )
+        {
+        CheckTItemIdArrayL( iNotificationItemIdArray, iEventArray, index, count );
+        }
+    else if ( mode == ERelation )
+        {
+        CheckTItemIdArrayL( iNotificationItemIdArray, iRelationArray, index, count );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    iNotificationItemIdArray.Reset();
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::VerifyMdERelationsL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::VerifyMdERelationsL( CStifItemParser& aItem )
+    {
+    TInt index;
+    TInt count;
+
+    User::LeaveIfError( aItem.GetNextInt( index ));
+    User::LeaveIfError( aItem.GetNextInt( count ));
+
+    CheckTMdERelationArrayL( iNotificationRelationArray, index, count );
+    iNotificationRelationArray.Reset();
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::VerifyObserverNotificationTypeL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::VerifyObserverNotificationTypeL( CStifItemParser& aItem )
+    {
+    TInt type;
+
+    User::LeaveIfError( aItem.GetNextInt( type ));
+
+    TL( iNotificationType == type );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ParentL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::ParentL( CStifItemParser& aItem )
+    {
+    CMdEObjectDef* objectDef = SanitizeArrayIndexL( iObjectDefArray, *iObjectDefNameArray, aItem );
+    CMdEObjectDef* parentDef = SanitizeArrayIndexL( iObjectDefArray, *iObjectDefNameArray, aItem );
+    TL( objectDef->ParentL() == parentDef );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::NameL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::NameL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    TPtrC name;
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    if ( mode == EPropertyDef )
+        {
+        CMdEPropertyDef* propDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+        aItem.SetParsingType( CStifItemParser::EQuoteStyleParsing );
+        User::LeaveIfError( aItem.GetNextString( name ));
+        TL( name.Compare( propDef->Name()) == 0 );           
+        }
+    else if ( mode == ENamespaceDef )
+        {
+        CMdENamespaceDef* spaceDef = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+        aItem.SetParsingType( CStifItemParser::EQuoteStyleParsing );
+        User::LeaveIfError( aItem.GetNextString( name ));
+        TL( name.Compare( spaceDef->Name()) == 0 );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ObjectDefCountL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::ObjectDefCountL( CStifItemParser& aItem )
+    {
+    TInt count;
+
+    CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( count ));
+
+    TL( space->ObjectDefCount() == count );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ObjectDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::ObjectDefL( CStifItemParser& aItem )
+    {
+    TInt mode;
+    TPtrC name;
+    TInt index;
+    CMdEObjectDef* objectDef = NULL;
+
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    User::LeaveIfError( aItem.GetNextString( name ));
+    if ( mode == ENamespaceDef )
+        {
+        CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+        User::LeaveIfError( aItem.GetNextInt( index ));
+        objectDef = &space->ObjectDefL( index );
+        }
+    else if ( mode == EPropertyDef )
+        {
+        CMdEPropertyDef* propDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );
+        objectDef = &propDef->ObjectDef();
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    TL( objectDef );
+    iObjectDefArray.Append( objectDef );
+    AppendNameL( iObjectDefNameArray, name );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::GetObjectDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::GetObjectDefL( CStifItemParser& aItem )
+    {
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));    
+    
+    TPtrC objectString;
+    CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( objectString ));
+    CMdEObjectDef& objectDef = space->GetObjectDefL( objectString );
+    TL( &objectDef );
+    iObjectDefArray.Append( &objectDef );
+    AppendNameL( iObjectDefNameArray, name );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RelationDefCountL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RelationDefCountL( CStifItemParser& aItem )
+    {
+    TInt count;
+
+    CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( count ));
+
+    TL( space->RelationDefCount() == count );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::RelationDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::RelationDefL( CStifItemParser& aItem )
+    {
+
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));  
+    TInt index;
+
+    CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( index ));
+    
+    CMdERelationDef& relationDef = space->RelationDefL( index );
+    TL( &relationDef );
+    iRelationDefArray.Append( &relationDef );
+    AppendNameL( iRelationDefNameArray, name );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::GetRelationDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::GetRelationDefL( CStifItemParser& aItem )
+    {
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));      
+    TPtrC relationString;
+
+    CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( relationString ));
+
+    CMdERelationDef& relationDef = space->GetRelationDefL( relationString );
+    TL( &relationDef );
+    iRelationDefArray.Append( &relationDef );
+    AppendNameL( iRelationDefNameArray, name );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::EventDefCountL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::EventDefCountL( CStifItemParser& aItem )
+    {
+    TInt count;
+
+    CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( count ));
+
+    TL( space->EventDefCount() == count );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::EventDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::EventDefL( CStifItemParser& aItem )
+    {
+    
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));     
+    TInt index;
+
+    CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextInt( index ));
+
+    CMdEEventDef& eventDef = space->EventDefL( index );
+    TL( &eventDef );
+    iEventDefArray.Append( &eventDef );
+    AppendNameL( iEventDefNameArray, name );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::GetEventDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::GetEventDefL( CStifItemParser& aItem )
+    {
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));   
+    TPtrC eventString;
+
+    CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( eventString ));
+    CMdEEventDef& eventDef = space->GetEventDefL( eventString );
+    TL( &eventDef );
+    iEventDefArray.Append( &eventDef );
+    AppendNameL( iEventDefNameArray, name );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ExportMetadataL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::ExportMetadataL( CStifItemParser& aItem )
+    {
+    TPtrC path;
+    TInt mode;
+    TInt useObjectDefs;
+    TInt useRelationDefs;
+    TInt useEventDefs;
+
+    const RPointerArray<CMdEObjectDef>* objectDefs;
+    const RPointerArray<CMdERelationDef>* relationDefs;
+    const RPointerArray<CMdEEventDef>* eventDefs;
+
+    CMdENamespaceDef* space = SanitizeArrayIndexL( iNamespaceDefArray, *iNamespaceDefNameArray, aItem );
+    User::LeaveIfError( aItem.GetNextString( path ));
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+    User::LeaveIfError( aItem.GetNextInt( useObjectDefs ));
+    User::LeaveIfError( aItem.GetNextInt( useRelationDefs ));
+    User::LeaveIfError( aItem.GetNextInt( useEventDefs ));
+
+    objectDefs = (useObjectDefs) ? &iObjectDefArray : NULL;
+    relationDefs = (useRelationDefs) ? &iRelationDefArray : NULL;
+    eventDefs = (useEventDefs) ? &iEventDefArray : NULL;
+
+    TFileName filePath( iFilePath );
+    filePath.Append( path );
+    filePath.ZeroTerminate();
+
+    if ( mode == KAsync )
+        {
+        TRequestStatus status = KRequestPending;
+        RMdEDataBuffer buf;
+
+        CleanupClosePushL( buf );
+        iMdeSession->ExportMetadataL( filePath, status, buf, space,
+            objectDefs, relationDefs, eventDefs );
+        User::WaitForRequest( status );
+
+        CleanupStack::PopAndDestroy( &buf );
+        }
+    else if ( mode == KSync )
+        {
+        iMdeSession->ExportMetadataL( filePath, space,
+            objectDefs, relationDefs, eventDefs );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+    iLog->Log( _L( "ExportMetadataL End"));
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ImportMetadataL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::ImportMetadataL( CStifItemParser& aItem )
+    {            
+    TPtrC path;
+    TInt mode;
+    TInt ret = KErrNone;
+
+    User::LeaveIfError( aItem.GetNextString( path ));
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+
+    TFileName filePath( iFilePath );
+    filePath.Append( path );
+    filePath.ZeroTerminate();
+
+    if ( mode == KAsync )
+        {
+        TRequestStatus status = KRequestPending;
+        TPckgBuf<TInt> buf( ret );
+
+        iMdeSession->ImportMetadata( filePath, buf, status );
+        User::WaitForRequest( status );
+        ret = buf();
+        }
+    else if ( mode == KSync )
+        {
+        ret = iMdeSession->ImportMetadataL( filePath );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+       iLog->Log( _L( "ImportMetadataL ret: %d" ), ret );
+    TL ( ret >= 0 );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ImportSchemaL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::ImportSchemaL( CStifItemParser& aItem )
+    {
+    TPtrC path;
+    User::LeaveIfError( aItem.GetNextString( path ));
+
+    TFileName filePath( iFilePath );
+    filePath.Append( path );
+    filePath.ZeroTerminate();
+
+    iMdeSession->ImportSchemaL( filePath );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::NamespaceDefCountL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::NamespaceDefCountL( CStifItemParser& aItem )
+    {
+    TInt count;
+
+    User::LeaveIfError( aItem.GetNextInt( count ));
+
+    TInt state = iMdeSession->NamespaceDefCount();
+    TL( count == state );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::NamespaceDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::NamespaceDefL( CStifItemParser& aItem )
+    {
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));
+        
+    TInt mode;
+    User::LeaveIfError( aItem.GetNextInt( mode ));
+
+    CMdENamespaceDef* namespaceDef = NULL;
+    if ( mode == ESession )
+        {
+        TInt index;
+
+        User::LeaveIfError( aItem.GetNextInt( index ));
+        namespaceDef = &iMdeSession->NamespaceDefL( index );
+        }
+    if ( mode == EEventDef )
+        {
+        CMdEEventDef* eventDef = SanitizeArrayIndexL( iEventDefArray, *iEventDefNameArray, aItem );
+        namespaceDef = &eventDef->NamespaceDef();
+        }
+    else if ( mode == EObjectDef )
+        {
+        CMdEObjectDef* objectDef = SanitizeArrayIndexL( iObjectDefArray, *iObjectDefNameArray, aItem );
+        namespaceDef = &objectDef->NamespaceDef();
+        }
+    else if ( mode == EPropertyDef )
+        {
+        CMdEPropertyDef* propertyDef = SanitizeArrayIndexL( iPropertyDefArray, *iPropertyDefNameArray, aItem );        
+        namespaceDef = &propertyDef->NamespaceDef();
+        }
+    else if ( mode == ERelationDef )
+        {
+        CMdERelationDef* relationDef = SanitizeArrayIndexL( iRelationDefArray, *iRelationDefNameArray, aItem );
+        namespaceDef = &relationDef->NamespaceDef();
+        }
+
+    iNamespaceDefArray.Append( namespaceDef );
+    AppendNameL( iNamespaceDefNameArray, name );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::GetNamespaceDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::GetNamespaceDefL( CStifItemParser& aItem )
+    {
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));    
+
+    aItem.SetParsingType( CStifItemParser::EQuoteStyleParsing );
+    TPtrC nsName;
+    User::LeaveIfError( aItem.GetNextString( nsName ));
+
+    CMdENamespaceDef& namespaceDef = iMdeSession->GetNamespaceDefL( nsName );
+    iNamespaceDefArray.Append( &namespaceDef );
+    AppendNameL( iNamespaceDefNameArray, name );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::GetDefaultNamespaceDefL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::GetDefaultNamespaceDefL( CStifItemParser& aItem )
+    {
+    TPtrC name;
+    User::LeaveIfError( aItem.GetNextString( name ));    
+        
+    CMdENamespaceDef& namespaceDef = iMdeSession->GetDefaultNamespaceDefL();
+    iNamespaceDefArray.Append( &namespaceDef );
+    AppendNameL( iNamespaceDefNameArray, name );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::LoadSchemaL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::LoadSchemaL( CStifItemParser& /* aItem */ )
+    {
+    iMdeSession->LoadSchemaL();
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::EngineSessionL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::EngineSessionL( CStifItemParser& /* aItem */ )
+    {
+    RMdEEngineSession& session = iMdeSession->EngineSession();
+    TL( &session );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::GetSchemaVersionL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::GetSchemaVersionL( CStifItemParser& aItem )
+    {
+    TInt majorVersion;
+    TInt minorVersion;
+    TInt expectedMajorVersion;
+    TInt expectedMinorVersion;
+
+    User::LeaveIfError( aItem.GetNextInt( expectedMajorVersion ));
+    User::LeaveIfError( aItem.GetNextInt( expectedMinorVersion ));
+
+    iMdeSession->GetSchemaVersionL( majorVersion, minorVersion );
+    TL( majorVersion == expectedMajorVersion );
+    TL( minorVersion == expectedMinorVersion );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::SetObjectToPresentByGuidL
+// -----------------------------------------------------------------------------
+//
+TInt CMdETestScripter::SetObjectToPresentByGuidL( CStifItemParser& aItem )
+    {
+    TInt guidHigh;
+    TInt guidLow;
+
+    User::LeaveIfError( aItem.GetNextInt( guidHigh ));
+    User::LeaveIfError( aItem.GetNextInt( guidLow ));
+
+    iMdeSession->SetObjectToPresentByGuidL( guidHigh, guidLow );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CMdETestScripter::ClearNamespaceDefArray
+// -----------------------------------------------------------------------------
+TInt CMdETestScripter::ResetNamespaceDefArray( CStifItemParser& /*aItem*/ )
+    {
+    iNamespaceDefArray.Reset();
+    iNamespaceDefNameArray->Reset();
+    return KErrNone;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/content_listing_framework_api.metaxml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,18 @@
+<?xml version="1.0" ?>
+<api id="3e9e9c540b26fcdd30bf3d686a37a9c9" dataversion="2.0">
+  <name>Content Listing Framework API</name>
+  <description>An interface for acquiring lists of media items</description>
+  <type>c++</type>
+  <collection>clfwrapper</collection>
+  <libs>
+    <lib name="ContentListingFramework.lib" />
+  </libs>
+  <release category="public" sinceversion="3.1"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>no</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+:                Content Listing Framework API
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/MCLFPostFilter.h     MW_LAYER_PUBLIC_EXPORT_PATH(MCLFPostFilter.h)
+../inc/MCLFCustomSorter.h     MW_LAYER_PUBLIC_EXPORT_PATH(MCLFCustomSorter.h)
+../inc/CLFContentListing.rh     MW_LAYER_PUBLIC_EXPORT_PATH(CLFContentListing.rh)
+../inc/CLFContentListing.h     MW_LAYER_PUBLIC_EXPORT_PATH(CLFContentListing.h)
+../inc/MCLFProcessObserver.h     MW_LAYER_PUBLIC_EXPORT_PATH(MCLFProcessObserver.h)
+../inc/CLFContentListing.hrh     MW_LAYER_PUBLIC_EXPORT_PATH(CLFContentListing.hrh)
+../inc/ContentListingFactory.h     MW_LAYER_PUBLIC_EXPORT_PATH(ContentListingFactory.h)
+../inc/MCLFSortingStyle.h     MW_LAYER_PUBLIC_EXPORT_PATH(MCLFSortingStyle.h)
+../inc/MCLFOperationObserver.h     MW_LAYER_PUBLIC_EXPORT_PATH(MCLFOperationObserver.h)
+../inc/MCLFContentListingEngine.h     MW_LAYER_PUBLIC_EXPORT_PATH(MCLFContentListingEngine.h)
+../inc/MCLFCustomGrouper.h     MW_LAYER_PUBLIC_EXPORT_PATH(MCLFCustomGrouper.h)
+../inc/MCLFModifiableItem.h     MW_LAYER_PUBLIC_EXPORT_PATH(MCLFModifiableItem.h)
+../inc/MCLFChangedItemObserver.h     MW_LAYER_PUBLIC_EXPORT_PATH(MCLFChangedItemObserver.h)
+../inc/MCLFItemListModel.h     MW_LAYER_PUBLIC_EXPORT_PATH(MCLFItemListModel.h)
+../inc/MCLFItem.h     MW_LAYER_PUBLIC_EXPORT_PATH(MCLFItem.h)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/CLFContentListing.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,40 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef CLFCONTENTLISTING_H
+#define CLFCONTENTLISTING_H
+
+//  INCLUDES
+#include <e32def.h>
+
+// DATA TYPES
+/**
+* Content Listing Framework Field ID
+*/
+typedef TUint TCLFFieldId;
+
+/**
+* Content Listing Framework Item ID
+*/
+typedef TUint TCLFItemId;
+
+
+#endif      // CLFCONTENTLISTING_H
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/CLFContentListing.hrh	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,161 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef CLFCONTENTLISTING_HRH
+#define CLFCONTENTLISTING_HRH
+
+// DATA TYPES
+
+/**
+*  Content Listing Framework list model media types.
+*/
+enum TCLFMediaType
+    {
+    /// Unknown media type
+    ECLFMediaTypeUnknown        = 0x0,
+    /// Music media type
+    ECLFMediaTypeMusic          = 0x1,
+    /// Sound media type
+    ECLFMediaTypeSound          = 0x2,
+    /// Image media type
+    ECLFMediaTypeImage          = 0x3,
+    /// Video media type
+    ECLFMediaTypeVideo          = 0x4,
+    /// Streaming URLs
+    ECLFMediaTypeStreamingURL   = 0x5,
+    /// Playlists
+    ECLFMediaTypePlaylist       = 0x6,
+    /// Presentations
+    ECLFMediaTypePresentations  = 0x8
+    };
+
+/**
+*  Content Listing Framework list model grouping styles.
+*/
+enum TCLFGrouping
+    {
+    /// No grouping
+    ECLFNoGrouping          = 0x0,
+    /// Model groups items to music albums
+    ECLFMusicAlbumGrouping  = 0x1
+    };
+
+/**
+*  Content Listing Framework sorting style orderings.
+*/
+enum TCLFSortingStyleOrdering
+    {
+    /// Ascending sorting order
+    ECLFOrderingAscending   = 0x0,
+    /// Descending sorting order
+    ECLFOrderingDescending  = 0x1
+    };
+
+/**
+*  Content Listing Framework undefined item position.
+*/
+enum TCLFUndefinedItemPosition
+    {
+    /// Undefined items are added to end in the list
+    ECLFSortingStyleUndefinedEnd   = 0x0,
+    /// Undefined items are added to first in the list
+    ECLFSortingStyleUndefinedFirst  = 0x1
+    };
+
+/**
+*  Content Listing Framework item fields data types.
+*/
+enum TCLFItemDataType
+    {
+    /// Undefined data type, do not use
+    ECLFItemDataTypeNull    = 0x0,
+    /// Data type is Integer
+    ECLFItemDataTypeTInt32  = 0x1,
+    /// Data type is descriptor
+    ECLFItemDataTypeDesC    = 0x2,
+    /// Data type is date/time
+    ECLFItemDataTypeTTime   = 0x3
+    };
+
+/**
+*  Content Listing Framework item field IDs.
+*/
+enum TCLFDefaultFieldId
+    {
+    /// Null field ID, do not use
+    ECLFFieldIdNull                 = 0x00000000,
+    // File data
+    /// File name field:
+    /// descriptor
+    ECLFFieldIdFileName             = 0x00000001,
+    /// File name field:
+    /// descriptor
+    ECLFFieldIdFileExtension        = 0x00000002,
+    /// File path field:
+    /// descriptor
+    ECLFFieldIdPath                 = 0x00000003,
+    /// File drive field:
+    /// descriptor
+    ECLFFieldIdDrive                = 0x00000004,
+    /// File size field:
+    /// integer
+    ECLFFieldIdFileSize             = 0x00000005,
+    /// File date field:
+    /// date/time
+    ECLFFieldIdFileDate             = 0x00000006,
+    /// Mime type field:
+    /// descriptor
+    ECLFFieldIdMimeType             = 0x00000007,
+    /// Media type field:
+    /// integer
+    ECLFFieldIdMediaType            = 0x00000008,
+    /// Full name and path of the file:
+    /// descriptor
+    ECLFFieldIdFileNameAndPath      = 0x0000000B,
+
+    /// Music file song name:
+    /// descriptor
+    ECLFFieldIdSongName             = 0x00001000,
+    /// Music file artist:
+    /// descriptor
+    ECLFFieldIdArtist               = 0x00001001,
+    /// Music file album:
+    /// descriptor
+    ECLFFieldIdAlbum                = 0x00001002,
+    /// Music file genre:
+    /// descriptor
+    ECLFFieldIdGenre                = 0x00001003,
+    /// Music file track number:
+    /// integer
+    ECLFFieldIdTrackNumber          = 0x00001004,
+    /// Music file composer:
+    /// descriptor
+    ECLFFieldIdComposer             = 0x00001104,
+
+    /// Ram link first URL:
+    /// descriptor
+    ECLFFieldIdRamLinkFirstURL      = 0x00001200,
+
+    /// Playlist song count:
+    /// integer
+    ECLFFieldIdPlaylistSongCount    = 0x00001201
+    };
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/CLFContentListing.rh	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,168 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+#ifndef CLFCONTENTLISTING_RH
+#define CLFCONTENTLISTING_RH
+
+
+//  INCLUDES
+#include <CLFContentListing.hrh>
+
+//  STRUCTURE DEFINITIONS
+
+// -----------------------------------------------------------------------------
+// CLF_FIELD_ID
+// Field ID
+// -----------------------------------------------------------------------------
+//
+STRUCT CLF_FIELD_ID
+    {
+    LONG field_id;  // TCLFFieldId
+    }
+
+// -----------------------------------------------------------------------------
+// CLF_SORTING_STYLE
+// Sorting style
+// Example:
+// RESOURCE CLF_SORTING_STYLE r_sorting_style
+//     {
+//     ordering = ECLFOrderingAscending;
+//     data_type = ECLFItemDataTypeDesC;
+//     fields =
+//         {
+//         CLF_FIELD_ID { field_id = ECLFFieldIdSongName; },
+//         CLF_FIELD_ID { field_id = ECLFFieldIdAlbum; }
+//         };
+//     }
+// -----------------------------------------------------------------------------
+//
+STRUCT CLF_SORTING_STYLE
+    {
+    WORD version = 1;
+    LONG ordering;      // TCLFSortingStyleOrdering
+    LONG data_type;     // TCLFItemDataType data type of fields
+                                   // TCLFUndefinedItemPosition
+    BYTE undefined_item_position = ECLFSortingStyleUndefinedEnd;
+    STRUCT fields[];    // CLF_FIELD_ID
+    }
+
+// -----------------------------------------------------------------------------
+// CLF_MIME_TYPE_ARRAY
+// List of mime types
+// Example:
+// RESOURCE CLF_MIME_TYPE_ARRAY r_mime_type_array
+//     {
+//     mime_types =
+//         {
+//         LBUF { txt = "image/*"; },
+//         LBUF { txt = "audio/*"; }
+//         };
+//     }
+// -----------------------------------------------------------------------------
+//
+STRUCT CLF_MIME_TYPE_ARRAY
+    {
+    WORD version = 1;
+    STRUCT mime_types[]; // LBUF
+    }
+
+// -----------------------------------------------------------------------------
+// CLF_MEDIA_TYPE
+// List of mime types
+// -----------------------------------------------------------------------------
+//
+STRUCT CLF_MEDIA_TYPE
+    {
+    LONG media_type;    // TCLFMediaType
+    }
+
+// -----------------------------------------------------------------------------
+// CLF_MEDIA_TYPE_ARRAY
+// List of media types
+// -----------------------------------------------------------------------------
+//
+STRUCT CLF_MEDIA_TYPE_ARRAY
+    {
+    WORD version = 1;
+    STRUCT media_types[];   //  CLF_MEDIA_TYPE_ARRAY
+    }
+
+// -----------------------------------------------------------------------------
+// CLF_LIST_MODEL
+// List model
+// Example:
+// RESOURCE CLF_LIST_MODEL r_list_model
+//     {
+//     mime_type_array = CLF_MIME_TYPE_ARRAY
+//         {
+//         mime_types =
+//             {
+//             LBUF { txt = "image/*"; },
+//             LBUF { txt = "audio/*"; }
+//             };
+//         };
+//     media_type_array = CLF_MEDIA_TYPE_ARRAY
+//         {
+//         media_types =
+//             {
+//             CLF_MEDIA_TYPE { media_type = ECLFMediaTypeMusic; }
+//             };
+//         };
+//     sorting_style = CLF_SORTING_STYLE
+//         {
+//         ordering = ECLFOrderingAscending;
+//         data_type = ECLFItemDataTypeDesC;
+//         fields =
+//             {
+//             CLF_FIELD_ID { field_id = ECLFFieldIdSongName; },
+//             CLF_FIELD_ID { field_id = ECLFFieldIdAlbum; }
+//             };
+//         };
+//     }
+// -----------------------------------------------------------------------------
+//
+STRUCT CLF_LIST_MODEL
+    {
+    WORD version = 1;
+    LONG grouping = ECLFNoGrouping; // TCLFGrouping
+    STRUCT mime_type_array;         // CLF_MIME_TYPE_ARRAY
+    STRUCT media_type_array;        // CLF_MEDIA_TYPE_ARRAY
+    STRUCT sorting_style;           // CLF_SORTING_STYLE
+    }
+
+// -----------------------------------------------------------------------------
+// CLF_MEDIA_TYPE_ARRAY
+// List of media types version 2
+// There can be multible sortings styles.
+// First sorting style is primary style, all items is sorted by this style,
+// if there is items that doesn't have field (undefined items) which is defined in
+// primary sorting style, then second sorting style is used to those items etc.
+// -----------------------------------------------------------------------------
+//
+STRUCT CLF_LIST_MODEL_V2
+    {
+    WORD version = 2;
+    LONG grouping = ECLFNoGrouping; // TCLFGrouping
+    STRUCT mime_type_array;         // CLF_MIME_TYPE_ARRAY
+    STRUCT media_type_array;        // CLF_MEDIA_TYPE_ARRAY
+    STRUCT sorting_style_array[];   // array of CLF_SORTING_STYLE
+    }
+
+
+#endif      // CLFCONTENTLISTING_RH
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/ContentListingFactory.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,106 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef CONTENTLISTINGFACTORY_H
+#define CONTENTLISTINGFACTORY_H
+
+//  INCLUDES
+#include <e32def.h>
+
+// FORWARD DECLARATIONS
+class MCLFContentListingEngine;
+class MCLFModifiableItem;
+class MCLFSortingStyle;
+class TResourceReader;
+
+// CLASS DECLARATION
+
+/**
+*  Factory for Content Listing Framework.
+*  You can create new instances of Content Listing Engines, Modifiable items
+*  and Sorting Styles by using this factory.<br><br>
+*  Example:
+*  @code
+*  // Create a new instance of Content Listing Engine
+*  MCLFContentListingEngine* engine =
+*      ContentListingFactory::NewContentListingEngineLC();
+*
+*  // Create a new instance of Sorting style
+*  MCLFSortingStyle* sortingStyle =
+*      ContentListingFactory::NewSortingStyleLC();
+*
+*  // Create a new instance of Modifiable item
+*  MCLFModifiableItem* modItem =
+*      ContentListingFactory::NewModifiableItemLC();
+*  @endcode
+*
+*  @lib ContentListingFramework.lib
+*  @since S60 3.1
+*/
+class ContentListingFactory
+    {
+    public: // New functions
+
+        /**
+        * Create new instance of Content Listing Engine.
+        * @since S60 3.1
+        * @return New instance of Content Listing Engine.
+        *         Ownership is transferred to the client application.
+        */
+        IMPORT_C static MCLFContentListingEngine* NewContentListingEngineLC();
+
+        /**
+        * Create new instance of Modifiable Item.
+        * @since S60 3.1
+        * @return New instance of Modifiable Item.
+        *         Ownership is transferred to the client application.
+        */
+        IMPORT_C static MCLFModifiableItem* NewModifiableItemLC();
+
+        /**
+        * Create new instance of Sorting Style.
+        * @since S60 3.1
+        * @return New instance of the Sorting Style.
+        *         Ownership is transferred to the client application.
+        */
+        IMPORT_C static MCLFSortingStyle* NewSortingStyleLC();
+
+        /**
+        * Create new instance of Sorting Style from resource of the
+        * application by using TResourceReader.
+        * @since S60 3.1
+        * @param aResource Resource reader to sorting style resource.
+        *                  Use resource struct CLF_SORTING_STYLE. See
+        *                  CLFContentListing.rh
+        * @return New instance of the Sorting Style.
+        *         Ownership is transferred to the client application.
+        */
+        IMPORT_C static MCLFSortingStyle* NewSortingStyleLC(
+                                                TResourceReader& aResource );
+
+    private:
+        // Prohibit C++ default constructor.
+        ContentListingFactory();
+        // Prohibit Destructor.
+        ~ContentListingFactory();
+
+    };
+
+#endif      // CONTENTLISTINGFACTORY_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/MCLFChangedItemObserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef MCLFCHANGEDITEMOBSERVER_H
+#define MCLFCHANGEDITEMOBSERVER_H
+
+//  INCLUDES
+#include <CLFContentListing.h>
+#include <e32std.h>
+
+// FORWARD DECLARATIONS
+class MCLFChangedItemObserverExt;
+
+// CLASS DECLARATION
+
+/**
+*  Changed Item Observer interface.
+*  Implement this interface to get notifications of changed,
+*  new or deleted items.
+*
+*  @lib ContentListingFramework.lib
+*  @since S60 3.1
+*/
+class MCLFChangedItemObserver
+    {
+    public: // New functions
+
+        /**
+        * Abstract method for handling item change event. This method is
+        * called when, for example, some item is renamed.
+        * @since S60 3.1
+        * @param aItemIDArray List of Item IDs of changed items.
+        */
+        virtual void HandleItemChangeL(
+                            const TArray<TCLFItemId>& aItemIDArray ) = 0;
+
+        /**
+        * Abstract method for handling errors. This method can be used to
+        * handle errors in changed item event.
+        * @since S60 3.1
+        * @param aError System wide error code.
+        */
+        virtual void HandleError( TInt aError ) = 0;
+
+    protected:
+
+        /**
+        * Destructor.
+        */
+        virtual ~MCLFChangedItemObserver() {}
+
+    private: // Extension interface
+
+        /**
+        * This member is internal and not intended for use.
+        */
+        virtual MCLFChangedItemObserverExt* Extension() { return NULL; }
+
+    };
+
+#endif      // MCLFCHANGEDITEMOBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/MCLFContentListingEngine.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,179 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef MCLFCONTENTLISTINGENGINE_H
+#define MCLFCONTENTLISTINGENGINE_H
+
+//  INCLUDES
+#include <CLFContentListing.h>
+#include <e32std.h>
+
+// FORWARD DECLARATIONS
+class MCLFContentListingEngineExt;
+class MCLFChangedItemObserver;
+class MCLFItemListModel;
+class MCLFOperationObserver;
+class TResourceReader;
+class MCLFProcessObserver;
+
+// CLASS DECLARATION
+
+/**
+*  Content Listing Engine.
+*  With Content Listing Engine, client can create item list models,
+*  add an observer to get notifications of changed items and
+*  send update notifications to server.
+*  Client can create an instance this class with ContentListingFactory.<br><br>
+*  Usage:
+*
+*  @code
+*
+*  // Create a new instance with Content Listing Factory
+*  MCLFContentListingEngine* engine =
+*                    ContentListingFactory::NewContentListingEngineLC();
+*
+*  // Add changed item observer
+*  engine->AddChangedItemObserverL( *myObserver );
+*
+*  // Send update notification when item is changed.
+*  engine->UpdateItemsL();
+*
+*  // Remember to remove the observer, when it is deleted
+*  engine->RemoveChangedItemObserver( *myObserver );
+*
+*  @endcode
+*
+*  @lib ContentListingFramework.lib
+*  @since S60 3.1
+*/
+class MCLFContentListingEngine
+    {
+    public: // Constructors and destructor
+
+        /**
+        * Destructor.
+        */
+        virtual ~MCLFContentListingEngine() {}
+
+    public: // New functions
+
+        /**
+        * Create a new instance of the Item List Model.
+        * @since S60 3.1
+        * @param aObserver Reference to an Operation Observer
+        * @return New instance of the Item List Model.
+        *         Ownership is transfered to the client application.
+        */
+        virtual MCLFItemListModel* CreateListModelLC(
+                        MCLFOperationObserver& aObserver ) = 0;
+
+        /**
+        * Create a new instance of Item List Model from the application
+        * resource.
+        * @since S60 3.1
+        * @param aObserver Reference to an Operation Observer.
+        * @param aResource Resource reader to list model resource.
+        *                  Use resource struct CLF_LIST_MODEL. See
+        *                  CLFContentListing.rh
+        * @return New instance of Item List Model.
+        *         Ownership is transfered to the client application.
+        */
+        virtual MCLFItemListModel* CreateListModelLC(
+                        MCLFOperationObserver& aObserver,
+                        TResourceReader& aResource ) = 0;
+
+        /**
+        * Add a changed item observer to the Engine.
+        * Changed item observer will notify you when items are changed, added
+        * or removed. Remember to remove the observer before you delete
+        * observer object.
+        * @since S60 3.1
+        * @param aObserver Changed item observer to be added
+        */
+        virtual void AddChangedItemObserverL(
+                        MCLFChangedItemObserver& aObserver ) = 0;
+
+        /**
+        * Remove a changed item observer from the Engine.
+        * @since S60 3.1
+        * @param aObserver Changed item observer to be removed
+        */
+        virtual void RemoveChangedItemObserver(
+                        MCLFChangedItemObserver& aObserver ) = 0;
+
+        /**
+        * Add CLF process observer.
+        * Remember to remove the observer before delete the observer object.
+        * @since S60 3.1
+        * @param aObserver Process observer to be added
+        */
+        virtual void AddCLFProcessObserverL(
+                        MCLFProcessObserver& aObserver ) = 0;
+
+        /**
+        * Remove CLF process observer.
+        * @since S60 3.1
+        * @param aObserver Process observer to be removed
+        */
+        virtual void RemoveCLFProcessObserver(
+                        MCLFProcessObserver& aObserver ) = 0;
+
+        /**
+        * Send item update notification.
+        * Client must use this method when media item(s) is changed or deleted.
+        * This method call will request the CLF server to update its list
+        * of items. Unneccesary update notifications should be avoided because
+        * they generate load to the system!
+        * @since S60 3.1
+        */
+        virtual void UpdateItemsL() = 0;
+
+        /**
+        * Send item update notification.
+        * Client must use this method when media item(s) is changed or deleted.
+        * This method call will request the CLF server to update items that are
+        * defined in the TArray.
+        * @since S60 3.1
+        * @param aItemIDArray List of Item IDs of modified items
+        */
+        virtual void UpdateItemsL(
+                        const TArray<TCLFItemId>& aItemIDArray ) = 0;
+
+        /**
+        * Send item update notification.
+        * Client must use this method when media item(s) is changed or deleted.
+        * @param aSemanticId Sematic ID is transfered to server plugins
+        * @param aOpaqueData Opaque data is transfered to server plugins
+        * @since S60 3.1
+        */
+        virtual void UpdateItemsL(
+                        TInt aSemanticId,
+                        const TDesC8& aOpaqueData ) = 0;
+
+    private: // Extension interface
+
+        /**
+        * This member is internal and not intended for use.
+        */
+        virtual MCLFContentListingEngineExt* Extension() { return NULL; }
+
+    };
+
+#endif      // MCLFCONTENTLISTINGENGINE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/MCLFCustomGrouper.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,108 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef MCLFCUSTOMGROUPER_H
+#define MCLFCUSTOMGROUPER_H
+
+//  INCLUDES
+#include <e32std.h>
+
+// FORWARD DECLARATIONS
+class MCLFCustomGrouperExt;
+class MCLFItem;
+
+// CLASS DECLARATION
+
+/**
+*  Custom grouper interface of Content Listing Framework.
+*  With this interface, client can add own custom grouper
+*  to its List Model. Custom grouper is used for grouping list model items.
+*  For example, List Model of music files can be grouped by genre or artist
+*  name by using this interface.
+*  Use ContentListingFactory to create items for new groups (MCLFModifiableItem).
+*  <br><br>
+*  Example:
+*  @code
+*  // This grouper will overwrite the source list and add three items to model.
+*  void CMyGrouper::GroupItemsL( const TArray<MCLFItem*>& aSourceList,
+*                                RPointerArray<MCLFItem>& aGroupedList )
+*      {
+*      _LIT( KTest, "test" );
+*      MCLFModifiableItem* item = ContentListingFactory::NewModifiableItemLC();
+*      item->AddFieldL( ECLFFieldIdName, KTest );
+*      aGroupedList.AppendL( item );
+*      CleanupStack::Pop(); // item
+*
+*      _LIT( KTest1, "test1" );
+*      item = ContentListingFactory::NewModifiableItemLC();
+*      item->AddFieldL( ECLFFieldIdName, KTest1 );
+*      aGroupedList.AppendL( item );
+*      CleanupStack::Pop(); // item
+*
+*      _LIT( KTest2, "test2" );
+*      item = ContentListingFactory::NewModifiableItemLC();
+*      item->AddFieldL( ECLFFieldIdName, KTest2 );
+*      aGroupedList.AppendL( item );
+*      CleanupStack::Pop(); // item
+*      }
+*  @endcode
+*
+*  Custom grouper is activated and removed by calling method
+*  MCLFItemListModel::SetCustomGrouper
+*
+*  @lib ContentListingFramework.lib
+*  @since S60 3.1
+*/
+class MCLFCustomGrouper
+    {
+    public: // New functions
+
+        /**
+        * Abstract method for grouping Content Listing Framework items of
+        * list models. This method is called when the grouping process is
+        * executed by refreshing the model.
+        * @since S60 3.1
+        * @param aSourceList Source list. Contains all items that are in
+        *        the list model when the grouping process starts.
+        * @param aGroupedList Grouped/destination list. While grouping, each
+        *        group should be added to this list. The list model will
+        *        contain only these items when the grouping process is
+        *        finished.
+        */
+        virtual void GroupItemsL( const TArray<MCLFItem*>& aSourceList,
+                                  RPointerArray<MCLFItem>& aGroupedList ) = 0;
+
+    protected:
+
+        /**
+        * Destructor.
+        */
+        virtual ~MCLFCustomGrouper() {}
+
+    private: // Extension interface
+
+        /**
+        * This member is internal and not intended for use.
+        */
+        virtual MCLFCustomGrouperExt* Extension() { return NULL; }
+
+    };
+
+#endif      // MCLFCUSTOMGROUPER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/MCLFCustomSorter.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,89 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef MCLFCUSTOMSORTER_H
+#define MCLFCUSTOMSORTER_H
+
+//  INCLUDES
+#include <e32std.h>
+
+// FORWARD DECLARATIONS
+class MCLFItem;
+class MCLFCustomSorterExt;
+
+// CLASS DECLARATION
+
+/**
+*  Custom sorter interface for Content Listing Framework.
+*  With this interface, client can create a customized sorter for
+*  sorting items in list model. For example, items in the List Model
+*  can be sorted by Item IDs or it can be randomized.<br><br>
+*  Example:
+*  @code
+*  // Example sorter that sorts items by Item IDs
+*  void CMySorter::SortItemsL( RPointerArray<MCLFItem>& aItemArray )
+*      {
+*      TLinearOrder<MCLFItem> sorter( CMySorter::Compare );
+*      aItemArray.Sort( sorter );
+*      }
+*
+*  TInt CMySorter::Compare( const MCLFItem& aFirst, const MCLFItem& aSecond )
+*      {
+*      return aFirst.ItemId() - aSecond.ItemId();
+*      }
+*  @endcode
+*
+*  Custom sorter is activated and removed by calling method
+*  MCLFItemListModel::SetCustomSorter
+*
+*  @lib ContentListingFramework.lib
+*  @since S60 3.1
+*/
+class MCLFCustomSorter
+    {
+    public: // New functions
+
+        /**
+        * Abstract method for sorting Content Listing Framework items in a list
+        * model. This method is called when the sorting process is executed
+        * by calling refresh to the List Model.
+        * @since S60 3.1
+        * @param aItemArray The array to sort. Contains all items of
+        *        the List Model.
+        */
+        virtual void SortItemsL( RPointerArray<MCLFItem>& aItemArray ) = 0;
+
+    protected:
+
+        /**
+        * Destructor.
+        */
+        virtual ~MCLFCustomSorter() {}
+
+    private: // Extension interface
+
+        /**
+        * This member is internal and not intended for use.
+        */
+        virtual MCLFCustomSorterExt* Extension() { return NULL; }
+
+    };
+
+#endif      // MCLFCUSTOMSORTER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/MCLFItem.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,142 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef MCLFITEM_H
+#define MCLFITEM_H
+
+//  INCLUDES
+#include <CLFContentListing.hrh>
+#include <CLFContentListing.h>
+#include <e32std.h>
+
+// FORWARD DECLARATIONS
+class MCLFItemExt;
+
+// CLASS DECLARATION
+
+/**
+*  Content Listing Framework item.
+*  All items that are fetched from server have got an Item ID number.
+*  Item ID is defined in runtime so do not store Item IDs permanently.
+*  One item can contain multiple fields. The field consists of a Field ID and
+*  field data. Type of the field is defined with Field ID: see
+*  TCLFDefaultFieldId in CLFContentListing.hrh.
+*  For example, a music file could contain these two fields:
+*  ECLFFieldIdSongName (data: title of the song) and ECLFFieldIdArtist
+*  (data: name of the artist).<br><br>
+*  Usage:
+*  @code
+*  // Get file names and sizes of all items
+*  TInt count( listModel->ItemCount() );
+*  for( TInt i = 0 ; i < count ; ++i )
+*      {
+*      const MCLFItem& myItem = listModel->Item( i );
+*
+*      // Get file name of an item (string data)
+*      TPtrC fileName;
+*      TInt error( myItem.GetField( ECLFFieldIdFileName, fileName ) );
+*
+*      ...
+*
+*      // Get file size of an item (integer data)
+*      TInt32 size( 0 );
+*      error = myItem.GetField( ECLFFieldIdFileSize, size );
+*
+*      ...
+*
+*      }
+*  @endcode
+*
+*  @lib ContentListingFramwork.lib
+*  @since S60 3.1
+*/
+class MCLFItem
+    {
+    public:  // Destructor
+
+        /**
+        * Destructor.
+        */
+        virtual ~MCLFItem() {}
+
+    public: // New functions
+
+        /**
+        * Get Item ID of the item.
+        * @since S60 3.1
+        * @return Item ID of the item
+        */
+        virtual TCLFItemId ItemId() const = 0;
+
+        /**
+        * Get data type of the field. Data type can be text, time or integer.
+        * @since S60 3.1
+        * @param aFieldId ID of the field (TCLFDefaultFieldId)
+        * @return Data type of the field.
+        *         ECLFItemDataTypeNull, if the field does not exist in the item.
+        */
+        virtual TCLFItemDataType DataType( TCLFFieldId aFieldId ) const = 0;
+
+        /**
+        * Get field data that is a string.
+        * @since S60 3.1
+        * @param aFieldId ID of the field (TCLFDefaultFieldId)
+        * @param aData Data of the field
+        * @return System wide error code.
+        *         KErrNone if field exist,
+        *         KErrNotFound if field doesn't exist,
+        *         KErrNotSupported if field type doesn't match
+        */
+        virtual TInt GetField( TCLFFieldId aFieldId, TPtrC& aData ) const = 0;
+
+        /**
+        * Get field data that is an integer.
+        * @since S60 3.1
+        * @param aFieldId ID of the field (TCLFDefaultFieldId)
+        * @param aData Data of the field
+        * @return System wide error code.
+        *         KErrNone if field exist,
+        *         KErrNotFound if field doesn't exist,
+        *         KErrNotSupported if field type doesn't match
+        */
+        virtual TInt GetField( TCLFFieldId aFieldId, TInt32& aData ) const = 0;
+
+        /**
+        * Get field data that is a time data.
+        * @since S60 3.1
+        * @param aFieldId ID of the field (TCLFDefaultFieldId)
+        * @param aData Data of the field
+        * @return System wide error code.
+        *         KErrNone if field exist,
+        *         KErrNotFound if field doesn't exist,
+        *         KErrNotSupported if field type doesn't match
+        */
+        virtual TInt GetField( TCLFFieldId aFieldId, TTime& aData ) const = 0;
+
+    private: // Extension interface
+
+        /**
+        * This member is internal and not intended for use.
+        */
+        virtual MCLFItemExt* Extension() { return NULL; }
+
+    };
+
+#endif      // MCLFITEM_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/MCLFItemListModel.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,270 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef MCLFITEMLISTMODEL_H
+#define MCLFITEMLISTMODEL_H
+
+//  INCLUDES
+#include <CLFContentListing.hrh>
+#include <bamdesca.h>
+
+// DATA TYPES
+/**
+*  Content Listing Framework list model refresh type.
+*/
+enum TCLFRefreshTypeFlags
+    {
+    /// Post filter is refreshed
+    ECLFRefreshPostFilter   = 0x1,
+    /// Grouping is refreshed
+    ECLFRefreshGrouping     = 0x2,
+    /// Sorting is refreshed
+    ECLFRefreshSorting      = 0x4,
+    /// All filters are used
+    ECLFRefreshAll          = 0xFFFFFFFF
+    };
+
+// FORWARD DECLARATIONS
+class MCLFItemListModelExt;
+class MCLFItem;
+class MCLFPostFilter;
+class MCLFCustomGrouper;
+class MCLFPostFilter;
+class MCLFSortingStyle;
+class MCLFCustomSorter;
+class TResourceReader;
+
+// CLASS DECLARATION
+
+/**
+*  List Model for Content Listing Framework.
+*  This model is used to list Content Listing items. These items provide
+*  infomation of media files on the device and one item represents one media
+*  file. The model can be manipulated by sorters, post filters and groupers.
+*  List Model is created by using Content Listing Engine.<br><br>
+*  Usage:
+*  @code
+*  // Create a new List Model instance
+*  MCLFItemListModel* listModel = iEngine->CreateListModelLC( *myObserver );
+*
+*  // Append music-type to wanted types array to exclude
+*  // all other files than music files from the list model
+*  RArray<TCLFMediaType> myMediaTypes;
+*  CleanupClosePushL( myMediaTypes );
+*  myMediaTypes.AppendL( ECLFMediaTypeMusic );
+*
+*  // Set wanted types with SetWantedMimeTypesL or/and SetWantedMediaTypesL.
+*  // You can add both if you want.
+*  listModel->SetWantedMediaTypesL( myMediaTypes.Array() );
+*  CleanupStack::PopAndDestroy( &myMediaTypes );
+*
+*  // Set sorting style (if you want to sort items)
+*  listModel->SetSortingStyle( mySortingStyle );
+*
+*  // You can also add post filter, custom sorter and custom grouper to model.
+*
+*  // Refresh the List Model.
+*  // The model will fetch items from server and use post filter to filter items,
+*  // grouping style or custom grouper to group items and finally sort items
+*  // with sorting style or custom sorter.
+*  listModel->RefreshL();
+*
+*  // You can also refresh the post filter and sorting only. This call does not
+*  // fetch items from the server. The model is only filtered and sorted.
+*  listModel->RefreshL( ECLFRefreshPostFilter | ECLFRefreshSorting );
+*  @endcode
+*
+*  @lib ContentListingFramework.lib
+*  @since S60 3.1
+*/
+class MCLFItemListModel
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Destructor.
+        */
+        virtual ~MCLFItemListModel() {}
+
+    public: // New functions
+
+        /**
+        * Get Content Listing Framework item from the List Model.
+        * @since S60 3.1
+        * @pre aIndex >= 0 && aIndex < ItemCount()
+        * @param aIndex Index of the item
+        * @return Content Listing Framework item
+        */
+        virtual const MCLFItem& Item( TInt aIndex ) const = 0;
+
+        /**
+        * Get number of items that are in the model.
+        * @since S60 3.1
+        * @return Count of items
+        */
+        virtual TInt ItemCount() const = 0;
+
+        /**
+        * Activate or remove Sorting style.
+        * Setting a new sorting style will remove all old secondary sorters.
+        * Removing the sorting will also remove all secondary sorters too.
+        * @since S60 3.1
+        * @param aSortingStyle Sorting style to activate,
+        *        if the pointer is NULL then sorting styles are removed
+        */
+        virtual void SetSortingStyle( MCLFSortingStyle* aSortingStyle ) = 0;
+
+        /**
+        * Append a secondary sorting style to the list model.
+        * If an item doesn't have the field defined by primary or
+        * any previous secondary sorting style, the items are sorted using
+        * the next secondary sorting style. When a sorting style is
+        * appended using this method, it becomes the least significant
+        * sorting style until a new one is added after it.
+        * Items with undefined fields are placed before or after items
+        * with defined fields, depending on the undefined field position
+        * setting in MCLFSortingStyle.
+        * @since S60 3.1
+        * @param aSortingStyle Secondary sorting style to add.
+        */
+        virtual void AppendSecondarySortingStyleL(
+                                    MCLFSortingStyle& aSortingStyle ) = 0;
+
+        /**
+        * Activate or remove custom sorter.
+        * Custom sorter will overwrite sorting style (if there is a sorting
+        * style activated). See MCLFCustomSorter for an example implementation
+        * of a custom sorter.
+        * @since S60 3.1
+        * @param aCustomSorter Custom sorter to activate.
+        *        If the pointer is NULL, sorting style is used (if there is one
+        *        activated)
+        */
+        virtual void SetCustomSorter( MCLFCustomSorter* aCustomSorter ) = 0;
+
+        /**
+        * Activate a grouping style for the List Model. Use ECLFNoGrouping as
+        * the grouping style if you want to remove grouping.
+        * Default grouping style is ECLFNoGrouping.
+        * @since S60 3.1
+        * @param aGrouping Grouping style to activate
+        */
+        virtual void SetGroupingStyle( TCLFGrouping aGrouping ) = 0;
+
+        /**
+        * Activate or remove custom grouper. See MCLFCustomGrouper for an example
+        * implementation of a custom grouper.
+        * Custom grouper will overwrite grouping style.
+        * @since S60 3.1
+        * @param aCustomGrouper Custom grouper to activate,
+        *        if pointer is NULL then then grouping style is used
+        */
+        virtual void SetCustomGrouper( MCLFCustomGrouper* aCustomGrouper ) = 0;
+
+        /**
+        * Activate or remove post filter. Post filter removes items from the
+        * List Model. See MCLFPostFilter for an example implementation of a
+        * post filter.
+        * @since S60 3.1
+        * @param aPostFilter Post filter to activate,
+        *        if pointer is NULL then active post filter will be removed.
+        */
+        virtual void SetPostFilter( MCLFPostFilter* aPostFilter ) = 0;
+
+        /**
+        * Wanted mime types of media files that will be requested to the model.
+        * Overwrites old mime types if they were set.
+        * @since S60 3.1
+        * @param aMimeTypes List of wanted mime types. Mime types can contain
+        *                   wildcard characters "*" and "?", where "*" matches
+        *                   zero or more consecutive occurrences of any character
+        *                   and "?" matches a single occurrence of any character
+        */
+        virtual void SetWantedMimeTypesL( const MDesCArray& aMimeTypes ) = 0;
+
+        /**
+        * Wanted mime types of media files that will be requested to the model.
+        * Overwrites old mime types if they were set.
+        * @since S60 3.1
+        * @param aResource Resource reader to mime type list resource.
+        *                  Use resource struct CLF_MIME_TYPE_ARRAY.
+        */
+        virtual void SetWantedMimeTypesL( TResourceReader& aResource ) = 0;
+
+        /**
+        * Wanted media types of media files that will be requested to the model.
+        * Overwrites old media types if they were set.
+        * @since S60 3.1
+        * @param aMediaTypes List of wanted media types
+        */
+        virtual void SetWantedMediaTypesL(
+                            const TArray<TInt>& aMediaTypes ) = 0;
+
+
+        /**
+        * Wanted media types of media files that will be requested to the model.
+        * Overwrites old media types if they were set.
+        * @since S60 3.1
+        * @param aResource Resource reader to media type list resource.
+        *                  Use resource struct CLF_MEDIA_TYPE_ARRAY
+        */
+        virtual void SetWantedMediaTypesL( TResourceReader& aResource ) = 0;
+
+        /**
+        * Refresh the model. This function is asynchronous (non-blocking) and
+        * MCLFOperationObserver is called when the refresh operation is
+        * completed. <br>
+        * <br>
+        * Operations in refresh are executed in the following order:<br>
+        * 1. Model gets wanted items from server.
+        *    Use SetWantedMediaTypesL and/or SetWantedMimeTypesL to define
+        *    wanted items.<br>
+        * 2. Model uses post filter to filter items.<br>
+        * 3. Model groups items if grouping is selected.<br>
+        * 4. Model sorting items.<br>
+        * @since S60 3.1
+        */
+        virtual void RefreshL() = 0;
+
+        /**
+        * Refresh the model. This function is synchronous (blocking). Use
+        * parameter(s) to define the type of refresh. See TCLFRefreshTypeFlags
+        * for refresh flags.
+        * @since S60 3.1
+        * @param aRefreshType Flag(s) to use for refreshing.
+        */
+        virtual void RefreshL( TInt32 aRefreshType ) = 0;
+
+        /**
+        * Cancel asynchronous refresh operation.
+        * @since S60 3.1
+        */
+        virtual void CancelRefresh() = 0;
+
+    private: // Extension interface
+
+        /**
+        * This member is internal and not intended for use.
+        */
+        virtual MCLFItemListModelExt* Extension() { return NULL; }
+
+    };
+
+#endif      // MCLFITEMLISTMODEL_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/MCLFModifiableItem.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,100 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef MCLFMODIFIABLEITEM_H
+#define MCLFMODIFIABLEITEM_H
+
+//  INCLUDES
+#include <MCLFItem.h>
+
+// FORWARD DECLARATIONS
+class MCLFModifiableItemExt;
+
+// CLASS DECLARATION
+
+/**
+*  Modifiable item for Content Listing Framework.
+*  Use ContentListingFactory to create modifiable items. These new items are
+*  used as groups in the custom grouper (see MCLFCustomGrouper). Modifiable
+*  item is like MCLFItem but you can add new fields to the modifiable item.
+*  One item can contain multiple fields, but normally it is not needed in
+*  a custom grouper. The field consists of a Field ID and field data. Type
+*  of the field is defined with Field ID. See TCLFDefaultFieldId in
+*  CLFContentListing.hrh.<br><br>
+*  Example:
+*  @code
+*  // Create a modifiable item and add one string field to it.
+*  // Field id is ECLFFieldIdArtist and field value is "test".
+*  _LIT( KTest, "test" );
+*  MCLFModifiableItem* item = ContentListingFactory::NewModifiableItemLC();
+*  item->AddFieldL( ECLFFieldIdArtist, KTest );
+*  CleanupStack::Pop(); // item
+*  @endcode
+*
+*  @lib ContentListingFramework.lib
+*  @since S60 3.1
+*/
+class MCLFModifiableItem : public MCLFItem
+    {
+    public:  // Destructor
+        /**
+        * Destructor.
+        */
+        virtual ~MCLFModifiableItem() {}
+
+    public: // New functions
+
+        /**
+        * Add new string field to the item.
+        * @since S60 3.1
+        * @param aFieldId Field ID
+        * @param aValue Field value
+        */
+        virtual void AddFieldL( TCLFFieldId aFieldId,
+                                const TDesC& aValue ) = 0;
+
+        /**
+        * Add new integer field to the item.
+        * @since S60 3.1
+        * @param aFieldId Field ID
+        * @param aValue Field value
+        */
+        virtual void AddFieldL( TCLFFieldId aFieldId,
+                                TInt32 aValue ) = 0;
+
+        /**
+        * Add new time field to the item.
+        * @since S60 3.1
+        * @param aFieldId Field ID
+        * @param aValue Field value
+        */
+        virtual void AddFieldL( TCLFFieldId aFieldId,
+                                const TTime& aValue ) = 0;
+
+    private: // Extension interface
+
+        /**
+        * This member is internal and not intended for use.
+        */
+        virtual MCLFModifiableItemExt* ModifiableItemExtension() { return NULL; }
+
+    };
+
+#endif      // MCLFMODIFIABLEITEM_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/MCLFOperationObserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,85 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef MCLFOPERATIONOBSERVER_H
+#define MCLFOPERATIONOBSERVER_H
+
+//  INCLUDES
+#include <e32def.h>
+
+// DATA TYPES
+/**
+* Content Listing Framework list model operation events
+*/
+enum TCLFOperationEvent
+    {
+    /// Refresh operation is completed
+    ECLFRefreshComplete = 0x0,
+    /// Model content is obsolated and should be refreshed
+    ECLFModelOutdated = 0x1
+    };
+
+// FORWARD DECLARATIONS
+class MCLFOperationObserverExt;
+
+// CLASS DECLARATION
+
+/**
+*  Operation Observer is for observing operation events of the Content Listing
+*  Framework. Client application gets notified when asynchronous operations
+*  are completed. For example, ECLFRefreshComplete event is received when the
+*  asynchronous refresh operation is compeleted.
+*
+*  @lib ContentListingFramework.lib
+*  @since S60 3.1
+*/
+class MCLFOperationObserver
+    {
+    public: // New functions
+
+        /**
+        * Abstract method to get list model operation events. This method is
+        * called when an event is received.
+        * @since S60 3.1
+        * @param aOperationEvent Operation event code of the event
+        * @param aError System wide error code if the operation did not
+        *        succeed.
+        */
+        virtual void HandleOperationEventL( TCLFOperationEvent aOperationEvent,
+                                            TInt aError ) = 0;
+
+    protected:
+
+        /**
+        * Destructor.
+        */
+        virtual ~MCLFOperationObserver() {}
+
+    private: // Extension interface
+
+        /**
+        * This member is internal and not intended for use.
+        */
+        virtual MCLFOperationObserverExt* Extension() { return NULL; }
+
+
+    };
+
+#endif      // MCLFOPERATIONOBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/MCLFPostFilter.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef MCLFPOSTFILTER_H
+#define MCLFPOSTFILTER_H
+
+//  INCLUDES
+#include <e32std.h>
+
+// FORWARD DECLARATIONS
+class MCLFPostFilterExt;
+class MCLFItem;
+
+// CLASS DECLARATION
+
+/**
+*  Post filter interface for Content Listing Framework.
+*  With this interface client you can add own post filter to
+*  exclude items from list model.<br><br>
+*  Example:
+*  @code
+*  // This example filters items by drive letter:
+*  // Items that are in phone memory are included to the list model.
+*  // All other items will be filtered.
+*  void CMyFilter::FilterItemsL( const TArray<MCLFItem*>& aItemList,
+*                                RPointerArray<MCLFItem>& aFilteredItemList )
+*      {
+*      TCharF phoneMemory( PathInfo::PhoneMemoryRootPath()[0] );
+*      TInt count( aItemList.Count() );
+*      for( TInt i = 0 ; i < count ; ++i )
+*          {
+*          TPtrC ptr;
+*          MCLFItem* item = aItemList[i];
+*          TInt error( item->GetField( ECLFFieldIdDrive, ptr ) );
+*          if( error == KErrNone )
+*              {
+*              TCharF memory( ptr[0] );
+*              if( memory == phoneMemory )
+*                  {
+*                  aFilteredItemList.AppendL( item );
+*                  }
+*              }
+*          }
+*      }
+*  @endcode
+*  @lib ContentListingFramework.lib
+*  @since S60 3.1
+*/
+class MCLFPostFilter
+    {
+    public: // New functions
+
+        /**
+        * Abstract method to filter source list. This method is called when
+        * the filtering process is executed by list model refresh.
+        * @since S60 3.1
+        * @param aItemList Source list, contains all items that are in
+        *        the list model
+        * @param aFilteredItemList Filtered/destination list, contains all items
+                 that will be in the list model after filtering.
+        */
+        virtual void FilterItemsL( const TArray<MCLFItem*>& aItemList,
+                                   RPointerArray<MCLFItem>& aFilteredItemList ) = 0;
+
+    protected:
+
+        /**
+        * Destructor.
+        */
+        virtual ~MCLFPostFilter() {}
+
+    private: // Extension interface
+
+        /**
+        * This member is internal and not intended for use.
+        */
+        virtual MCLFPostFilterExt* Extension() { return NULL; }
+
+
+    };
+
+#endif      // MCLFPOSTFILTER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/MCLFProcessObserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,81 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef MCLFPROCESSOBSERVER_H
+#define MCLFPROCESSOBSERVER_H
+
+//  INCLUDES
+#include <e32std.h>
+
+// DATA TYPES
+/**
+* Content Listing Framework process events
+*/
+enum TCLFProcessEvent
+    {
+    /// CLF server starts update process
+    ECLFUpdateStart = 0x0,
+    /// CLF server update process is end
+    ECLFUpdateStop = 0x1
+    };
+
+// FORWARD DECLARATIONS
+class MCLFProcessObserverExt;
+
+// CLASS DECLARATION
+
+/**
+*  Process observer interface for Content Listing Framework.
+*  Implement this interface to get notified of process events. These process
+*  events are generated when update process of CLF server is started
+*  and finished.
+*
+*  @lib ContentListingFramework.lib
+*  @since S60 3.1
+*/
+class MCLFProcessObserver
+    {
+    public: // New functions
+
+        /**
+        * Abstract method to handle CLF process event. This method is called
+        * when process events are generated.
+        * @since S60 3.1
+        * @param aProcessEvent The process event that was generated.
+        */
+        virtual void HandleCLFProcessEventL( TCLFProcessEvent aProcessEvent ) = 0;
+
+    protected:
+
+        /**
+        * Destructor.
+        */
+        virtual ~MCLFProcessObserver() {}
+
+    private: // Extension interface
+
+        /**
+        * This member is internal and not intended for use.
+        */
+        virtual MCLFProcessObserverExt* Extension() { return NULL; }
+
+    };
+
+#endif      // MCLFProcessObserver_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/inc/MCLFSortingStyle.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,163 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef MCLFSORTINGSTYLE_H
+#define MCLFSORTINGSTYLE_H
+
+//  INCLUDES
+#include <CLFContentListing.hrh>
+#include <CLFContentListing.h>
+#include <e32std.h>
+
+// FORWARD DECLARATIONS
+class MCLFSortingStyleExt;
+
+// CLASS DECLARATION
+
+/**
+*  Sorting style for Content Listing Framework.
+*  This class can be used to define primary and secondary sorting styles for
+*  Content Listing Framework list model. Sorting styles are used to sort the
+*  list model.<br><br>
+*  Secondary sorting style is used to sort items that could not be sorted by
+*  the primary sorting style. In other words, items that do not have the
+*  field defined by primary or any previous secondary sorting style, the items
+*  are sorted using the next secondary sorting style. When a secondary sorting
+*  style is appended, it becomes the least significant sorting style until a
+*  new one is added after it. Items with undefined fields are placed before or
+*  after items with defined fields, depending on the undefined field position
+*  setting in MCLFSortingStyle.
+*  <br><br>
+*  Usage:
+*  @code
+*  // Create a sorting style instance
+*  MCLFSortingStyle* sortingStyle = ContentListingFactory::NewSortingStyleLC();
+*
+*  // Set sort ordering
+*  sortingStyle->SetOrdering( ECLFOrderingDescending );
+*
+*  // Set undefied item position. Undefined items are items that doesn't
+*  // have field that is defined in sorting style fields
+*  sortingStyle->SetUndefinedItemPosition( ECLFSortingStyleUndefinedEnd );
+*
+*  // All sorting style parameter fields are string type
+*  sortingStyle->SetSortingDataType( ECLFItemDataTypeDesC );
+*
+*  // Set default sorting parameter
+*  sortingStyle->AddFieldL( ECLFFieldIdSongName );
+*
+*  // Set secondary sorting parameter
+*  sortingStyle->AddFieldL( ECLFFieldIdFileName );
+*
+*  // If item doesn't have ECLFFieldIdSongName field then
+*  // ECLFFieldIdFileName field is used to sort item.
+*  @endcode
+*
+*  @lib ContentListingFramework.lib
+*  @since S60 3.1
+*/
+class MCLFSortingStyle
+    {
+    public:  // Destructor
+
+        /**
+        * Destructor.
+        */
+        virtual ~MCLFSortingStyle() {}
+
+    public: // New functions
+
+        /**
+        * Reset settings of the sorting style to default.
+        * @since S60 3.1
+        */
+        virtual void ResetL() = 0;
+
+        /**
+        * Set sort ordering. Ordering can be ascending or descending. See
+        * TCLFSortingStyleOrdering
+        * @since S60 3.1
+        * @param aOrdering Sort ordering to be set
+        */
+        virtual void SetOrdering( TCLFSortingStyleOrdering aOrdering ) = 0;
+
+        /**
+        * Get current sort ordering of the sorting style.
+        * @since S60 3.1
+        * @return Current sort ordering
+        */
+        virtual TCLFSortingStyleOrdering Ordering() const = 0;
+
+        /**
+        * Set data type of sorting parameter fields. Data type can be text,
+        * time or number. See TCLFItemDataType
+        * @since S60 3.1
+        * @param aDataType Data type to be set
+        */
+        virtual void SetSortingDataType( TCLFItemDataType aDataType ) = 0;
+
+        /**
+        * Get current sorting data type of fields.
+        * @since S60 3.1
+        * @return Current data type sorting of sorting fields
+        */
+        virtual TCLFItemDataType SortingDataType() const = 0;
+
+        /**
+        * Set undefined item position. Items not having information for defined
+        * sorting parameter fields are placed to top or bottom of the model. See
+        * TCLFUndefinedItemPosition
+        * @since S60 3.1
+        * @param aUndefinedItemPosition Position for undefiened items
+        */
+        virtual void SetUndefinedItemPosition(
+                    TCLFUndefinedItemPosition aUndefinedItemPosition ) = 0;
+
+        /**
+        * Get current position of undefined items.
+        * @since S60 3.1
+        * @return Current position for undefined items
+        */
+        virtual TCLFUndefinedItemPosition UndefinedItemPosition() const = 0;
+
+        /**
+        * Add new field to the sorting style. First added field will be the
+        * default field. Remember to set type of field(s) with
+        * SetSortingDataType. Fields that are some other type will be ignored.
+        * See TCLFDefaultFieldId in CLFContentListing.hrh
+        * @since S60 3.1
+        * @param aFieldId Id of the sorting parameter field
+        */
+        virtual void AddFieldL( TCLFFieldId aFieldId ) = 0;
+
+        /**
+        * Get IDs of fields that have been set to the sorting style.
+        * @since S60 3.1
+        * @param aArray Array of field IDs
+        */
+        virtual void GetFieldsL( RArray<TCLFFieldId>& aArray ) const = 0;
+
+    private: // Extension interface
+
+        virtual MCLFSortingStyleExt* Extension() { return NULL; }
+
+    };
+
+#endif      // MCLFSORTINGSTYLE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/tsrc/bwins/T_CLFApiMdlTestu.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?CreateTestSuiteL@@YAPAVMEUnitTest@@XZ @ 1 NONAME ; class MEUnitTest * CreateTestSuiteL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/tsrc/custom/preset_custom.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,61 @@
+<?xml version="1.0"?>
+<test>
+    <name>SP API Test Automation - Content Listing Framework Wrapper</name>
+    <target>
+        <device rank="none" alias="DEFAULT">
+            <property name="HARNESS" value="EUNIT" />
+        </device>
+    </target>
+    <plan name="Public API automatic tests" harness="EUNIT" enabled="true" passrate="100">
+        <session name="EUnit tests" harness="EUNIT" enabled="true" passrate="100">
+            <set name="API tests" harness="EUNIT" enabled="true" passrate="100">
+                <target>
+                    <device rank="master" alias="DEFAULT"/>
+                </target>
+                <case name="Testrun" harness="EUNIT" enabled="true" passrate="100">
+                    <step name="Create CTC log dir" harness="EUNIT" enabled="true" passrate="100" significant="false">
+                        <command>makedir</command>
+                        <params>
+                            <param dir="c:\data\ctc\"/>
+                        </params>
+                    </step>
+                    <step name="CTC start" harness="EUNIT" enabled="true" passrate="100" significant="false">
+                        <command>execute</command>
+                        <params>
+                            <param file="z:\sys\bin\ctcman.exe"/>
+                        </params>
+                    </step>
+                    <step name="Create EUnit log dir" harness="EUNIT" enabled="true" passrate="100" significant="false">
+                        <command>makedir</command>
+                        <params>
+                            <param dir="c:\DigiaEUnit\logs\"/>
+                        </params>
+                    </step>
+                    <step name="Execute Client API tests" harness="EUNIT" enabled="true" passrate="100" significant="true">
+                        <command>execute</command>
+                        <params>
+                            <param parameters="/l xml T_CLFApiMdlTest.dll"/>
+                            <param timeout="7200"/>
+                            <param result-file="c:\Shared\EUnit\logs\T_CLFApiMdlTest_log.xml"/>
+                            <param file="z:\sys\bin\EUNITEXERUNNER.EXE"/>
+                        </params>
+                    </step>
+                    <step name="Save CTC data" harness="EUNIT" enabled="true" passrate="100" significant="false">
+                        <command>execute</command>
+                        <params>
+                            <param parameters="writelocal"/>
+                            <param file="z:\sys\bin\ctcman.exe"/>
+                        </params>
+                    </step>
+                    <step name="Fetch and clean CTC data" harness="EUNIT" enabled="true" passrate="100" significant="false">
+                        <command>fetch-log</command>
+                        <params>
+                            <param delete="true"/>
+                            <param path="c:\data\ctc\ctcdata.txt"/>
+                        </params>
+                    </step>
+                </case>
+            </set>
+        </session>
+    </plan>
+</test>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/tsrc/eabi/T_CLFApiMdlTestu.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	_Z16CreateTestSuiteLv @ 1 NONAME
+	_ZTI19T_CLFApiModuleTests @ 2 NONAME ; #<TI>#
+	_ZTV19T_CLFApiModuleTests @ 3 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/tsrc/group/T_ContentListingFramework.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+// DEFINES
+#define         KEUnitUid3 0x1000af59
+#define         KEUnitTestDllUid2 0x1000af5a
+
+// Build target
+TARGET          T_CLFApiMdlTest.dll
+TARGETTYPE      dll
+UID             KEUnitTestDllUid2 KEUnitUid3
+CAPABILITY      ALL -TCB -DRM
+VENDORID        VID_DEFAULT
+
+APP_LAYER_SYSTEMINCLUDE
+
+// Source files
+SOURCEPATH      ../src
+SOURCE          CreateTestSuite.cpp
+SOURCE          T_CLFApiModuleTests.cpp
+
+START RESOURCE  T_ContentListingFramework.rss
+  HEADER
+  TARGETPATH    RESOURCE_FILES_DIR
+  LANGUAGE_IDS
+END
+
+// Include paths
+USERINCLUDE     ../inc
+
+SYSTEMINCLUDE     /epoc32/include/platform/digia/eunit
+
+// Dependencies to system components
+LIBRARY         euser.lib
+LIBRARY         EUnit.lib
+LIBRARY         efsrv.lib
+LIBRARY         bafl.lib
+LIBRARY         platformenv.lib
+LIBRARY         ContentListingFramework.lib 
+LIBRARY         estor.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/tsrc/group/T_ContentListingFramework.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,32 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+; Installation file for API test
+
+; Languages
+&EN
+
+; Header
+#{"ContentListingFrameworkAPItest"},(0x1000af59),1,0,1,TYPE=SA
+
+; Localised Vendor name
+%{"Nokia-EN"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Files
+"\epoc32\release\armv5\urel\T_CLFApiMdlTest.dll"      -"C:\sys\bin\T_CLFApiMdlTest.dll"
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/tsrc/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTMMPFILES
+    T_ContentListingFramework.mmp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/tsrc/inc/T_CLFApiModuleTests.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,177 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Part of CLF API tests
+*
+*/
+
+
+// INCLUDES
+#include <ceunittestsuiteclass.h>
+#include <bautils.h>
+#include <barsc.h>
+#include <CLFContentListing.hrh>
+#include <CLFContentListing.h>
+
+// FORWARD DECLARATION
+class MCLFContentListingEngine;
+class MCLFItemListModel;
+class MCLFSortingStyle;
+class TTestOperationObserver;
+class TTestCustomSorter;
+class TTestCustomGrouper;
+class TTestPostFilter;
+class TTestChangedItemObserver;
+class MCLFModifiableItem;
+class TTestCLFProcessObserver;
+class MCLFItem;
+
+/**
+ * Test suite for Content Listing Framework API
+ */
+class T_CLFApiModuleTests : public CEUnitTestSuiteClass
+    {
+    public:     // Construct / destruct
+        static T_CLFApiModuleTests* NewLC();
+        ~T_CLFApiModuleTests();
+
+    private:
+        void ConstructL();
+
+    private:    // Assistance methods
+        void ResourceL( TInt aResourceId );
+        void SortingStyleResourceL();
+        void ListModelResourceL();
+        void CreateNewFileL( TInt aNumber, TDes& aFileName );
+        TCLFItemId FindTestFileIdL( TInt aNumber );
+        TBool CheckFileNameShortingL();
+        TBool CheckFileSizeShortingL();
+        TBool CheckFileDateShortingL();
+        TBool CheckFileTypesL( const MDesCArray& aMimeTypeArray, const TArray<TInt>& aMediaTypes );
+        TBool CheckMimeTypesL( const MDesCArray& aMimeTypeArray, const TDesC& aMimeType );
+        TBool CheckMediaTypesL( const TArray<TInt>& aMediaTypes, TCLFMediaType aMediaType );
+        HBufC8* MakeOpaqueDataL( const MDesCArray& aFiles );
+        void MakeMultibleSortingItemsL( RPointerArray<MCLFModifiableItem>& aItemArray );
+        TBool CheckMultibleSortingShortingL();
+        TBool CheckMultibleSortingShorting2L();
+        const MCLFItem* FindItem( MCLFItemListModel& aModel, TCLFItemId aItemId );
+
+
+    private:    // test methods
+        // setups
+        void BaseSetupL();
+        void SortingStyleResourceSetupL();
+        void CreateModelSetupL();
+        void CreateModelFromResourceSetupL();
+        void ListModelSetupL();
+        void ListModelSetupFromResourceL();
+        void ListModelAllFileItemsSetupL();
+        void EngineTestSetupL();
+        void SortingStyleTestSetupL();
+        void SortingStyleResourceTestSetupL();
+        void ModifiableItemTestSetupL();
+        void ItemTestSetupL();
+        void MultibleSortingSetupL();
+        void MultibleSortingResourceSetupL();
+
+        // teardowns
+        void Teardown();
+
+        // tests
+        // Constructor test
+        void CreateEngineTestL();
+        void CreateModifiableItemTestL();
+        void CreateSortignStyleTestL();
+        void CreateSortignStyleFromResourceTestL();
+        void CreateListModelTestL();
+        void CreateListModelFromResourceTestL();
+
+        // Engine test
+        void UpdateItemsTestL();
+        void UpdateItemsWithIdTestL();
+        void UpdateItemsWithOpaqueDataFolderTestL();
+
+        // Sorting Style test;
+        void SortingStyleResourceTestL();
+        void SortingStyleOrderingTestL();
+        void SortingStyleDataTypeTestL();
+        void SortingStyleUndefinedItemPositionTestL();
+        void SortingStyleFieldTestL();
+
+        // List model test
+        void RefreshTestL();
+        void SetSortingStyleTestL();
+        void SetCustomSorterTestL();
+        void GroupingTestL();
+        void SetPostFilterTestL();
+        void SetWantedMimeTypesTestL();
+        void SetWantedMediaTypesTestL();
+        void SetWantedMediaAndMimeTypesTestL();
+        void MultibleSortingTestL();
+        void ModelItemsChangedTestL();
+
+
+        // item test
+        void ItemFieldTestL();
+
+        // Modifiable item test
+        void MIFieldTestL();
+
+    private:    // Implementation
+
+        EUNIT_DECLARE_TEST_TABLE;
+
+    private:    // Data
+        MCLFContentListingEngine* iEngine;
+        MCLFItemListModel* iListModel;
+        MCLFSortingStyle* iSortingStyle;
+        MCLFSortingStyle* iSortingStyle1;
+        MCLFSortingStyle* iSortingStyle2;
+        MCLFSortingStyle* iSortingStyle3;
+        MCLFModifiableItem* iModifiableItem;
+        const MCLFItem* iItem; // ref. not owned
+
+        TTestOperationObserver* iTestObserver;
+        TTestCustomSorter* iTestSorter;
+        TTestCustomSorter* iTestSorter1;
+        TTestCustomGrouper* iTestGrouper;
+        TTestCustomGrouper* iTestGrouper1;
+        TTestPostFilter* iTestFilter;
+        TTestPostFilter* iTestFilter1;
+        TTestCLFProcessObserver* iTestCLFProcessObserver;
+        TTestCLFProcessObserver* iTestCLFProcessObserver1;
+
+        CDesCArray* iMimeTypeArray;
+        CDesCArray* iMimeTypeArray1;
+        RArray<TInt> iMediaTypeArray;
+        RArray<TInt> iMediaTypeArray1;
+
+        TTestChangedItemObserver* iChangedItemObserver;
+        TTestChangedItemObserver* iChangedItemObserver1;
+        RArray<TCLFItemId> iUpdateItemIdArray;
+        HBufC8* iOpaqueData;
+        TInt iSemanticId;
+
+        RFs iFs;
+        RResourceFile iResourceFile;
+        HBufC8* iDataBuffer;
+        TResourceReader iResourceReader;
+        CActiveSchedulerWait iWait;
+        RArray<TCLFItemId> iChangedArray;
+        TInt iItemCount;
+        RPointerArray<MCLFModifiableItem> iModifiableItems;
+        TFileName iFileName;
+
+    };
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/tsrc/src/CreateTestSuite.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+// INCLUDES
+#include <ceunittestsuite.h>
+#include "T_CLFApiModuleTests.h"
+
+/**
+ * Test suite factory function.
+ */
+EXPORT_C MEUnitTest* CreateTestSuiteL()
+    {
+    CEUnitTestSuite* mainSuite = CEUnitTestSuite::NewLC(_L("Content Listing Framework API Module Tests"));
+
+    // NewLC leaves the pointer to cleanupstack until AddL finishes
+    mainSuite->AddL( T_CLFApiModuleTests::NewLC() );
+    CleanupStack::Pop();
+
+    CleanupStack::Pop( mainSuite );
+    return mainSuite;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/tsrc/src/T_CLFApiModuleTests.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,2513 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of CLF API test 
+*
+*/
+
+
+// INCLUDES
+#include "T_CLFApiModuleTests.h"
+#include <s32mem.h> 
+#include <eunitmacros.h>
+
+// the header for the tested class
+#include <ContentListingFactory.h>
+#include <MCLFChangedItemObserver.h>
+#include <MCLFContentListingEngine.h>
+#include <MCLFCustomGrouper.h>
+#include <MCLFCustomSorter.h>
+#include <MCLFItem.h>
+#include <MCLFItemListModel.h>
+#include <MCLFModifiableItem.h>
+#include <MCLFOperationObserver.h>
+#include <MCLFPostFilter.h>
+#include <MCLFSortingStyle.h>
+#include <T_ContentListingFramework.rsg>
+#include <collate.h>
+#include <PathInfo.h>
+#include <MCLFProcessObserver.h>
+#include <CLFContentListingExtended.hrh>
+
+//CONSTS
+#ifdef __WINSCW__
+_LIT( KTestResourceFile, "z:\\resource\\T_ContentListingFramework.rsc" );
+#else
+_LIT( KTestResourceFile, "c:\\sys\\bin\\T_ContentListingFramework.rsc" );
+#endif
+_LIT( KTestFileNameBase, "CLFTestFiles\\TestFile" );
+_LIT( KTestFileExt, ".txt" );
+
+const TCLFFieldId KMultibleSortingTestField1 = 0x80000001;
+const TCLFFieldId KMultibleSortingTestField2 = 0x80000002;
+const TCLFFieldId KMultibleSortingTestField3 = 0x80000003;
+const TCLFFieldId KMultibleSortingTestField4 = 0x80000004;
+const TCLFFieldId KMultibleSortingTestField5 = 0x80000005;
+const TCLFFieldId KMultibleSortingTestField6 = 0x80000006;
+
+const TInt KCLFUpdateFoldersSemanticId = 0x1000;
+
+// ---------------------------------------------------------------------------
+// class CMGXAsyncCallback
+// ---------------------------------------------------------------------------
+//
+class CCLFAsyncCallback : public CBase
+    {
+    public:
+        ~CCLFAsyncCallback()
+            {
+            if ( iActiveWait.IsStarted() )
+                {
+                iActiveWait.AsyncStop();
+                }
+            }
+    public:
+        static void AfterL( TTimeIntervalMicroSeconds32 aInterval )
+            {
+            CCLFAsyncCallback* self = new( ELeave ) CCLFAsyncCallback();
+            CleanupStack::PushL( self );
+            CPeriodic* periodic = CPeriodic::NewL( CActive::EPriorityIdle );
+            CleanupStack::PushL( periodic );
+            TCallBack callBack( CallBackL, self );
+            TTimeIntervalMicroSeconds32 interval( 1000000 );
+            periodic->Start( aInterval, aInterval, callBack );
+            self->iActiveWait.Start();
+            periodic->Cancel();
+            CleanupStack::PopAndDestroy( 2 ); // periodic, self
+            }
+
+        static TInt CallBackL( TAny* aObject )
+            {
+            CCLFAsyncCallback* self = reinterpret_cast< CCLFAsyncCallback* >( aObject );
+            if ( self->iActiveWait.IsStarted() )
+                {
+                self->iActiveWait.AsyncStop();
+                }
+            return EFalse;
+            }
+            
+    private:
+        CActiveSchedulerWait iActiveWait;
+    };
+
+// ---------------------------------------------------------------------------
+// class TTestOperationObserver
+// ---------------------------------------------------------------------------
+//
+class TTestOperationObserver : public MCLFOperationObserver
+    {
+    public:
+        TTestOperationObserver()
+            // set invalid values
+            : iOperationEvent( TCLFOperationEvent( -1 ) ), iError( 1 ), iWait( NULL )
+            {}
+        void HandleOperationEventL( TCLFOperationEvent aOperationEvent,
+                                    TInt aError )
+            {
+            iError = aError;
+            iOperationEvent = aOperationEvent;
+            if( iWait &&
+                iWait->IsStarted() )
+                {
+                iWait->AsyncStop();
+                }
+            }
+        TCLFOperationEvent iOperationEvent;
+        TInt iError;
+        CActiveSchedulerWait* iWait;
+
+    };
+
+// ---------------------------------------------------------------------------
+// class TTestCustomSorter
+// ---------------------------------------------------------------------------
+//
+class TTestCustomSorter : public MCLFCustomSorter
+    {
+    public:
+        TTestCustomSorter() : iSortItems( EFalse )
+            {
+            }
+        void SortItemsL( RPointerArray<MCLFItem>& /*aItemArray*/ )
+            {
+            //aItemArray;
+            iSortItems = ETrue;
+            }
+        TBool iSortItems;
+
+    };
+
+// ---------------------------------------------------------------------------
+// class TTestCustomGrouper
+// ---------------------------------------------------------------------------
+//
+class TTestCustomGrouper : public MCLFCustomGrouper
+    {
+    public:
+        TTestCustomGrouper() : iGroupCount( 2 ), iCopyItems( EFalse ), iModifiableItems( NULL )
+            {
+            }
+        void GroupItemsL( const TArray<MCLFItem*>& /*aSourceList*/,
+                          RPointerArray<MCLFItem>& aGroupedList )
+            {
+            //aSourceList;
+            if( iCopyItems )
+                {
+                TInt count( iModifiableItems->Count() );
+                for( TInt i = 0 ; i < count ; ++i )
+                    {
+                    aGroupedList.AppendL( (*iModifiableItems)[i] );
+                    }
+                }
+            else if( iModifiableItems )
+                {
+                iModifiableItems->ResetAndDestroy();
+                for( TInt i = 0 ; i < iGroupCount ; ++i )
+                    {
+                    MCLFModifiableItem* item = ContentListingFactory::NewModifiableItemLC();
+                    iModifiableItems->AppendL( item );
+                    CleanupStack::Pop(); // item
+                    aGroupedList.AppendL( item );
+                    }
+                }
+            }
+        TInt iGroupCount;
+        TBool iCopyItems;
+        RPointerArray<MCLFModifiableItem>* iModifiableItems;
+    };
+
+// ---------------------------------------------------------------------------
+// class TTestPostFilter
+// ---------------------------------------------------------------------------
+//
+class TTestPostFilter : public MCLFPostFilter
+    {
+    public:
+        TTestPostFilter() : iShouldFilterCount( 5 ), iAllFilter( EFalse )
+            {
+            }
+
+        void FilterItemsL( const TArray<MCLFItem*>& aItemList,
+                           RPointerArray<MCLFItem>& aFilteredItemList )
+            {
+            iFilteredCount = 0;
+            if( iAllFilter )
+                {
+                iFilteredCount = aItemList.Count();
+                return;
+                }
+            for( TInt i = 0 ; i < aItemList.Count() ; ++i )
+                {
+                if( i < iShouldFilterCount  )
+                    {
+                    iFilteredCount++;
+                    }
+                else
+                    {
+                    aFilteredItemList.AppendL( aItemList[i] );
+                    }
+                }
+            }
+        TInt iShouldFilterCount;
+        TBool iAllFilter;
+        TInt iFilteredCount;
+
+    };
+
+// ---------------------------------------------------------------------------
+// class TTestChangedItemObserver
+// ---------------------------------------------------------------------------
+//
+class TTestChangedItemObserver : public MCLFChangedItemObserver
+    {
+    public:
+        TTestChangedItemObserver()
+            : iHandleItemChange( EFalse ),
+              iLastError( KErrNone ),
+              iChangedArray( NULL ),
+              iWait( NULL )      
+            {
+            }
+        void HandleItemChangeL( const TArray<TCLFItemId>& aItemIDArray )
+            {
+            iHandleItemChange = ETrue;
+            if( iChangedArray )
+                {
+                iChangedArray->Reset();
+                for( TInt i = 0 ; i < aItemIDArray.Count() ; ++i )
+                    {
+                    iChangedArray->AppendL( aItemIDArray[i] );
+                    }
+                }
+            if( iWait && iWait->IsStarted() )
+                {
+                iWait->AsyncStop();
+                }
+
+            }
+        void HandleError( TInt aError )
+            {
+            iLastError = aError;
+            if( iWait && iWait->IsStarted() )
+                {
+                iWait->AsyncStop();
+                }
+            }
+        TInt iHandleItemChange;
+        TInt iLastError;
+        RArray<TCLFItemId>* iChangedArray;
+        CActiveSchedulerWait* iWait;
+    };
+
+// ---------------------------------------------------------------------------
+// class TTestCLFProcessObserver
+// ---------------------------------------------------------------------------
+//
+class TTestCLFProcessObserver : public MCLFProcessObserver
+    {
+    public:
+        TTestCLFProcessObserver()
+            : iStartEvent( EFalse ), iEndEvent( EFalse )
+            {}
+        void HandleCLFProcessEventL( TCLFProcessEvent aProcessEvent )
+            {
+            switch ( aProcessEvent )
+                {
+                case ECLFUpdateStart:
+                    {
+                    iStartEvent = ETrue;
+                    break;
+                    }
+                case ECLFUpdateStop:
+                    {
+                    iEndEvent = ETrue;
+                    break;
+                    }
+                default:
+                    {
+                    User::Panic( _L("CLF module test"), 1 );
+                    }
+                }
+            }
+        void Reset()
+            {
+            iStartEvent = EFalse;
+            iEndEvent = EFalse;
+            }
+        TBool iStartEvent;
+        TBool iEndEvent;
+    };
+
+void SerializeL( const MDesCArray& aDataArray, CBufBase& aBuffer )
+    {
+    const TInt count( aDataArray.MdcaCount() );
+    RBufWriteStream writeStream( aBuffer );
+    CleanupClosePushL( writeStream );
+    writeStream.WriteInt32L( count );
+    for( TInt i = 0 ; i < count ; ++i )
+        {
+        const TDesC& des = aDataArray.MdcaPoint( i );
+        TInt length( des.Length() );
+        writeStream.WriteInt32L( length );
+        writeStream.WriteL( des, length );
+        }
+    CleanupStack::PopAndDestroy( &writeStream );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::NewLC()
+// Create the testing class
+// ---------------------------------------------------------------------------
+//
+T_CLFApiModuleTests* T_CLFApiModuleTests::NewLC()
+    {
+    T_CLFApiModuleTests* self = new(ELeave) T_CLFApiModuleTests;
+
+    CleanupStack::PushL( self );
+    // need to generate the table, so call base classes
+    // second phase constructor
+    self->ConstructL();
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::ConstructL()
+    {
+    CEUnitTestSuiteClass::ConstructL();
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::~T_CLFApiModuleTests()
+// ---------------------------------------------------------------------------
+//
+T_CLFApiModuleTests::~T_CLFApiModuleTests()
+    {
+    Teardown();
+    }
+
+/**
+ * Assistance methods
+ */
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::ResourceL
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::ResourceL( TInt aResourceId )
+    {
+    delete iDataBuffer;
+    iDataBuffer = NULL;
+    iDataBuffer = iResourceFile.AllocReadL( aResourceId );
+    iResourceReader.SetBuffer( iDataBuffer );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SortingStyleResourceL
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::SortingStyleResourceL()
+    {
+    ResourceL( R_SORTING_STYLE );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::ListModelResourceL
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::ListModelResourceL()
+    {
+    ResourceL( R_LIST_MODEL );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CreateNewFileL
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::CreateNewFileL( TInt aNumber, TDes& aFileName )
+    {
+    aFileName.Copy( PathInfo::PhoneMemoryRootPath() );
+    aFileName.Append( KTestFileNameBase );
+    TBuf<125> buf;
+    buf.Num( aNumber );
+    aFileName.Append( buf );
+    aFileName.Append( KTestFileExt );
+
+    RFile file;
+    BaflUtils::EnsurePathExistsL( iFs, aFileName );
+    TInt error( file.Replace( iFs, aFileName, EFileShareAny | EFileWrite ) );
+    if( error == KErrNone )
+        {
+        error = file.Write( _L8("Test data") );
+        }
+    file.Close();
+    User::LeaveIfError( error );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::FindTestFileIdL
+// ---------------------------------------------------------------------------
+//
+TCLFItemId T_CLFApiModuleTests::FindTestFileIdL( TInt aNumber )
+    {
+    TCLFItemId id( 0 );
+    MCLFItemListModel* model = iEngine->CreateListModelLC( *iTestObserver );
+    iMimeTypeArray->AppendL( _L("*") );
+
+    iTestObserver->iWait = &iWait;
+    model->SetWantedMimeTypesL( *iMimeTypeArray );
+    model->RefreshL();
+    iWait.Start();
+
+    TFileName testFileName( PathInfo::PhoneMemoryRootPath() );
+    testFileName.Append( KTestFileNameBase );
+    TBuf<125> buf;
+    buf.Num( aNumber );
+    testFileName.Append( buf );
+    testFileName.Append( KTestFileExt );
+    for( TInt i = 0 ; i < model->ItemCount() ; ++i )
+        {
+        const MCLFItem& item = model->Item( i );
+        TPtrC fileName;
+        if( item.GetField( ECLFFieldIdFileNameAndPath, fileName ) != KErrNone )
+            {
+            continue;
+            }
+        if( fileName.CompareF( testFileName ) == 0 )
+            {
+            id = item.ItemId();
+            break;
+            }
+        }
+    CleanupStack::PopAndDestroy(); // model
+    return id;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CheckFileNameShortingL
+// ---------------------------------------------------------------------------
+//
+TBool T_CLFApiModuleTests::CheckFileNameShortingL()
+    {
+    TCollationMethod m = *Mem::CollationMethodByIndex( 0 );
+    m.iFlags |= TCollationMethod::EIgnoreNone | TCollationMethod::EFoldCase;
+
+    for( TInt i = 0 ; i < iListModel->ItemCount() -1 ; ++i )
+        {
+        const MCLFItem& item = iListModel->Item( i );
+        const MCLFItem& item1 = iListModel->Item( i + 1 );
+        TPtrC name;
+        TPtrC name1;
+
+        if( item.GetField( ECLFFieldIdFileName, name ) != KErrNone ||
+            item1.GetField( ECLFFieldIdFileName, name1 ) != KErrNone )
+            {
+            return EFalse;
+            }
+        if( name.CompareC( name1, 3, &m ) > 0 )
+            {
+            return EFalse;
+            }
+        }
+    return ETrue;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CheckFileSizeShortingL
+// ---------------------------------------------------------------------------
+//
+TBool T_CLFApiModuleTests::CheckFileSizeShortingL()
+    {
+    for( TInt i = 0 ; i < iListModel->ItemCount() -1 ; ++i )
+        {
+        const MCLFItem& item = iListModel->Item( i );
+        const MCLFItem& item1 = iListModel->Item( i + 1 );
+        TInt32 size;
+        TInt32 size1;
+        if( item.GetField( ECLFFieldIdFileSize, size ) != KErrNone ||
+            item1.GetField( ECLFFieldIdFileSize, size1 ) != KErrNone )
+            {
+            return EFalse;
+            }
+        if( size < size1 )
+            {
+            return EFalse;
+            }
+        }
+    return ETrue;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CheckMultibleSortingShortingL
+// ---------------------------------------------------------------------------
+//
+TBool T_CLFApiModuleTests::CheckMultibleSortingShortingL()
+    {
+    const MCLFItem* item = &( iListModel->Item( 0 ) );
+    TInt32 data( 0 );
+    if( item->GetField( KMultibleSortingTestField2, data ) != KErrNone ||
+        data != 5 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 1 ) );
+    if( item->GetField( KMultibleSortingTestField2, data ) != KErrNone ||
+        data != 4 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 2 ) );
+    if( item->GetField( KMultibleSortingTestField2, data ) != KErrNone ||
+        data != 3 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 3 ) );
+    if( item->GetField( KMultibleSortingTestField3, data ) != KErrNone ||
+        data != 6 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 4 ) );
+    if( item->GetField( KMultibleSortingTestField3, data ) != KErrNone ||
+        data != 7 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 5 ) );
+    if( item->GetField( KMultibleSortingTestField3, data ) != KErrNone ||
+        data != 8 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 6 ) );
+    if( item->GetField( KMultibleSortingTestField4, data ) != KErrNone ||
+        data != 9 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 7 ) );
+    if( item->GetField( KMultibleSortingTestField4, data ) != KErrNone ||
+        data != 10 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 8 ) );
+    if( item->GetField( KMultibleSortingTestField4, data ) != KErrNone ||
+        data != 11 )
+        {
+        return EFalse;
+        }
+// unsorted start
+    item = &( iListModel->Item( 9 ) );
+    if( item->GetField( KMultibleSortingTestField6, data ) != KErrNone ||
+        ( data < 15 || data > 17 ) )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 10 ) );
+    if( item->GetField( KMultibleSortingTestField6, data ) != KErrNone ||
+        ( data < 15 || data > 17 ) )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 11 ) );
+    if( item->GetField( KMultibleSortingTestField6, data ) != KErrNone ||
+        ( data < 15 || data > 17 ) )
+        {
+        return EFalse;
+        }
+// unsorted end
+    item = &( iListModel->Item( 12 ) );
+    if( item->GetField( KMultibleSortingTestField5, data ) != KErrNone ||
+        data != 12 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 13 ) );
+    if( item->GetField( KMultibleSortingTestField5, data ) != KErrNone ||
+        data != 13 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 14 ) );
+    if( item->GetField( KMultibleSortingTestField5, data ) != KErrNone ||
+        data != 14 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 15 ) );
+    if( item->GetField( KMultibleSortingTestField1, data ) != KErrNone ||
+        data != 0 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 16 ) );
+    if( item->GetField( KMultibleSortingTestField1, data ) != KErrNone ||
+        data != 1 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 17 ) );
+    if( item->GetField( KMultibleSortingTestField1, data ) != KErrNone ||
+        data != 2 )
+        {
+        return EFalse;
+        }
+
+    return ETrue;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CheckMultibleSortingShorting2L
+// ---------------------------------------------------------------------------
+//
+TBool T_CLFApiModuleTests::CheckMultibleSortingShorting2L()
+    {
+// check sorted
+    const MCLFItem* item = &( iListModel->Item( 0 ) );
+    TInt32 data( 0 );
+    if( item->GetField( KMultibleSortingTestField5, data ) != KErrNone ||
+        data != 12 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 1 ) );
+    if( item->GetField( KMultibleSortingTestField5, data ) != KErrNone ||
+        data != 13 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 2 ) );
+    if( item->GetField( KMultibleSortingTestField5, data ) != KErrNone ||
+        data != 14 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 3 ) );
+    if( item->GetField( KMultibleSortingTestField6, data ) != KErrNone ||
+        data != 15 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 4 ) );
+    if( item->GetField( KMultibleSortingTestField6, data ) != KErrNone ||
+        data != 16 )
+        {
+        return EFalse;
+        }
+    item = &( iListModel->Item( 5 ) );
+    if( item->GetField( KMultibleSortingTestField6, data ) != KErrNone ||
+        data != 17 )
+        {
+        return EFalse;
+        }
+// check unsorted
+    for( TInt i = 6 ; i < 18 ; ++i )
+        {
+        item = &( iListModel->Item( i ) );
+        if( item->GetField( KMultibleSortingTestField1, data ) != KErrNone )
+            {
+            if( item->GetField( KMultibleSortingTestField2, data ) != KErrNone )
+                {
+                if( item->GetField( KMultibleSortingTestField3, data ) != KErrNone )
+                    {
+                    if( item->GetField( KMultibleSortingTestField4, data ) != KErrNone )
+                        {
+                        return EFalse;
+                        }
+                    }
+                }
+            }
+        if( data < 0 || data > 11 )
+            {
+            return EFalse;
+            }
+        }
+
+    return ETrue;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CheckFileDateShortingL
+// ---------------------------------------------------------------------------
+//
+TBool T_CLFApiModuleTests::CheckFileDateShortingL()
+    {
+    for( TInt i = 0 ; i < iListModel->ItemCount() -1 ; ++i )
+        {
+        const MCLFItem& item = iListModel->Item( i );
+        const MCLFItem& item1 = iListModel->Item( i + 1 );
+        TTime date;
+        TTime date1;
+        if( item.GetField( ECLFFieldIdFileDate, date ) != KErrNone ||
+            item1.GetField( ECLFFieldIdFileDate, date1 ) != KErrNone )
+            {
+            return EFalse;
+            }
+        if( date > date1 )
+            {
+            return EFalse;
+            }
+        }
+    return ETrue;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CheckFileTypesL
+// ---------------------------------------------------------------------------
+//
+TBool T_CLFApiModuleTests::CheckFileTypesL( const MDesCArray& aMimeTypeArray,
+                                            const TArray<TInt>& aMediaTypes )
+    {
+    for( TInt i = 0 ; i < iListModel->ItemCount() ; ++i )
+        {
+        TPtrC mimeType;
+        TInt32 mediaType;
+        TInt error = iListModel->Item( i ).GetField( ECLFFieldIdMimeType, mimeType );
+        if( iListModel->Item( i ).GetField( ECLFFieldIdMediaType, mediaType ) != KErrNone )
+            {
+            return EFalse;
+            }
+        TBool mimeTypeVal( EFalse );
+        TBool mediaTypeVal( EFalse );
+        if( error == KErrNone )
+            {
+            mimeTypeVal = CheckMimeTypesL( aMimeTypeArray, mimeType );
+            }
+        mediaTypeVal = CheckMediaTypesL( aMediaTypes, TCLFMediaType( mediaType ) );
+        if( !( mimeTypeVal || mediaTypeVal ) )
+            {
+            return EFalse;
+            }
+        }
+    return ETrue;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CheckMimeTypesL
+// ---------------------------------------------------------------------------
+//
+TBool T_CLFApiModuleTests::CheckMimeTypesL( const MDesCArray& aMimeTypeArray,
+                                            const TDesC& aMimeType )
+    {
+    for( TInt j = 0 ; j < aMimeTypeArray.MdcaCount() ; ++j )
+        {
+        if( aMimeTypeArray.MdcaPoint( j ).Match( aMimeType ) == KErrNotFound )
+            {
+            return ETrue;
+            }
+        }
+    return EFalse;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CheckMediaTypesL
+// ---------------------------------------------------------------------------
+//
+TBool T_CLFApiModuleTests::CheckMediaTypesL( const TArray<TInt>& aMediaTypes,
+                                             TCLFMediaType aMediaType )
+    {
+    for( TInt j = 0 ; j < aMediaTypes.Count() ; ++j )
+        {
+        if( aMediaTypes[j] == aMediaType )
+            {
+            return ETrue;
+            }
+        }
+    return EFalse;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::MakeOpaqueDataL
+// ---------------------------------------------------------------------------
+//
+HBufC8* T_CLFApiModuleTests::MakeOpaqueDataL( const MDesCArray& aFiles )
+    {
+    CDesCArray* folderArray = new ( ELeave ) CDesCArraySeg( 8 );
+    CleanupStack::PushL( folderArray );
+    TInt count( aFiles.MdcaCount() );
+    for( TInt i = 0 ; i < count ; ++i )
+        {
+        TPtrC folderPath( TParsePtrC(
+                            aFiles.MdcaPoint( i ) ).DriveAndPath() );
+        TInt tmp( 0 );
+        if( folderArray->Find( folderPath, tmp, ECmpFolded ) != 0 )
+            {
+            folderArray->AppendL( folderPath );
+            }
+        }
+
+    CBufBase* dynBuffer = CBufFlat::NewL( 64 );
+    CleanupStack::PushL( dynBuffer );
+    SerializeL( *folderArray, *dynBuffer );
+    HBufC8* ret = dynBuffer->Ptr( 0 ).AllocL();
+    CleanupStack::PopAndDestroy( 2, folderArray );
+    return ret;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::MakeMultibleSortingItemsL
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::MakeMultibleSortingItemsL(
+                        RPointerArray<MCLFModifiableItem>& aItemArray )
+    {
+    for( TInt i = 0 ; i < 18 ; ++i )
+        {
+        MCLFModifiableItem* item = ContentListingFactory::NewModifiableItemLC();
+        aItemArray.AppendL( item );
+        CleanupStack::Pop();
+
+        if( i < 3 )
+            {
+            item->AddFieldL( KMultibleSortingTestField1, i );
+            }
+        else if( i < 6 )
+            {
+            item->AddFieldL( KMultibleSortingTestField2, i );
+            }
+        else if( i < 9 )
+            {
+            item->AddFieldL( KMultibleSortingTestField3, i );
+            }
+        else if( i < 12 )
+            {
+            item->AddFieldL( KMultibleSortingTestField4, i );
+            }
+        else if( i < 15 )
+            {
+            item->AddFieldL( KMultibleSortingTestField5, i );
+            }
+        else
+            {
+            item->AddFieldL( KMultibleSortingTestField6, i );
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::FindItem
+// ---------------------------------------------------------------------------
+//
+const MCLFItem* T_CLFApiModuleTests::FindItem( MCLFItemListModel& aModel, TCLFItemId aItemId )
+    {
+    for( TInt i = 0 ; i < aModel.ItemCount() ; ++i )
+        {
+        const MCLFItem& item = aModel.Item( i );
+        if( item.ItemId() == aItemId )
+            {
+            return &item;
+            }
+        }
+    return NULL;
+    }
+
+/**
+ * Setup
+ */
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::BaseSetupL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::BaseSetupL()
+    {
+    iFs.Close();
+    iResourceFile.Close();
+    
+    User::LeaveIfError( iFs.Connect() );
+    TFileName fileName( KTestResourceFile );
+    BaflUtils::NearestLanguageFile( iFs, fileName );
+    iResourceFile.OpenL( iFs, KTestResourceFile );
+    iResourceFile.ConfirmSignatureL( 0 );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SortingStyleResourceSetupL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::SortingStyleResourceSetupL()
+    {
+    BaseSetupL();
+    SortingStyleResourceL();
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CreateModelSetupL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::CreateModelSetupL()
+    {
+    iEngine = ContentListingFactory::NewContentListingEngineLC();
+    CleanupStack::Pop();
+    iTestObserver  = new (ELeave) TTestOperationObserver;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CreateModelFromResourceSetupL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::CreateModelFromResourceSetupL()
+    {
+    BaseSetupL();
+    CreateModelSetupL();
+    ListModelResourceL();
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::ListModelSetupL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::ListModelSetupL()
+    {
+    BaseSetupL();
+    CreateModelSetupL();
+    iListModel = iEngine->CreateListModelLC( *iTestObserver );
+    CleanupStack::Pop();
+
+    iSortingStyle = ContentListingFactory::NewSortingStyleLC();
+    CleanupStack::Pop();
+    iSortingStyle1 = ContentListingFactory::NewSortingStyleLC();
+    CleanupStack::Pop();
+    iSortingStyle2 = ContentListingFactory::NewSortingStyleLC();
+    CleanupStack::Pop();
+    iSortingStyle3 = ContentListingFactory::NewSortingStyleLC();
+    CleanupStack::Pop();
+
+    iTestSorter = new (ELeave) TTestCustomSorter;
+    iTestSorter1 = new (ELeave) TTestCustomSorter;
+    iTestGrouper = new (ELeave) TTestCustomGrouper;
+    iTestGrouper1 = new (ELeave) TTestCustomGrouper;
+    iTestFilter = new (ELeave) TTestPostFilter;
+    iTestFilter1 = new (ELeave) TTestPostFilter;
+    iMimeTypeArray = new (ELeave) CDesCArrayFlat( 8 );
+    iMimeTypeArray1 = new (ELeave) CDesCArrayFlat( 8 );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::MultibleSortingSetupL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::MultibleSortingSetupL()
+    {
+    ListModelSetupL();
+    MakeMultibleSortingItemsL( iModifiableItems );
+
+// use custom grouper to make own items
+    iTestGrouper->iModifiableItems = &iModifiableItems;
+    iTestGrouper->iCopyItems = ETrue;
+    iListModel->SetCustomGrouper( iTestGrouper );
+
+// set sorters
+    iSortingStyle->ResetL();
+    iSortingStyle->SetSortingDataType( ECLFItemDataTypeTInt32 );
+    iSortingStyle->AddFieldL( KMultibleSortingTestField1 );
+    iSortingStyle->SetUndefinedItemPosition( ECLFSortingStyleUndefinedFirst );
+
+    iSortingStyle1->ResetL();
+    iSortingStyle1->SetSortingDataType( ECLFItemDataTypeTInt32 );
+    iSortingStyle1->AddFieldL( KMultibleSortingTestField2 );
+    iSortingStyle1->SetUndefinedItemPosition( ECLFSortingStyleUndefinedEnd );
+    iSortingStyle1->SetOrdering( ECLFOrderingDescending );
+
+    iSortingStyle2->ResetL();
+    iSortingStyle2->SetSortingDataType( ECLFItemDataTypeTInt32 );
+    iSortingStyle2->AddFieldL( KMultibleSortingTestField3 );
+    iSortingStyle2->AddFieldL( KMultibleSortingTestField4 );
+    iSortingStyle2->SetUndefinedItemPosition( ECLFSortingStyleUndefinedEnd );
+
+    iSortingStyle3->ResetL();
+    iSortingStyle3->SetSortingDataType( ECLFItemDataTypeTInt32 );
+    iSortingStyle3->AddFieldL( KMultibleSortingTestField5 );
+    iSortingStyle3->SetUndefinedItemPosition( ECLFSortingStyleUndefinedFirst );
+
+    iListModel->SetSortingStyle( iSortingStyle );
+    iListModel->AppendSecondarySortingStyleL( *iSortingStyle1 );
+    iListModel->AppendSecondarySortingStyleL( *iSortingStyle2 );
+    iListModel->AppendSecondarySortingStyleL( *iSortingStyle3 );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::MultibleSortingResourceSetupL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::MultibleSortingResourceSetupL()
+    {
+    ListModelSetupL();
+    delete iListModel;
+    iListModel = NULL;
+    ResourceL( R_LIST_MODEL_MULTIBLE );
+    iListModel = iEngine->CreateListModelLC( *iTestObserver, iResourceReader );
+    CleanupStack::Pop();
+
+// use custom grouper to make own items
+    MakeMultibleSortingItemsL( iModifiableItems );
+    iTestGrouper->iModifiableItems = &iModifiableItems;
+    iTestGrouper->iCopyItems = ETrue;
+    iListModel->SetCustomGrouper( iTestGrouper );
+
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::ListModelAllFileItemsSetupL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::ListModelAllFileItemsSetupL()
+    {
+    ListModelSetupL();
+    iMediaTypeArray.AppendL( ECLFMediaTypeVideo );
+    iMediaTypeArray.AppendL( ECLFMediaTypeImage );
+    iMediaTypeArray.AppendL( ECLFMediaTypeSound );
+    iMediaTypeArray.AppendL( ECLFMediaTypeMusic );
+    iMediaTypeArray.AppendL( ECLFMediaTypeStreamingURL );
+    iMediaTypeArray.AppendL( ECLFMediaTypePlaylist );
+    iListModel->SetWantedMediaTypesL( iMediaTypeArray.Array() );
+    iTestObserver->iWait = &iWait;
+    iListModel->RefreshL();
+    iWait.Start();
+    iItemCount = iListModel->ItemCount();
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::ListModelSetupFromResourceL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::ListModelSetupFromResourceL()
+    {
+    BaseSetupL();
+    CreateModelSetupL();
+    ListModelResourceL();
+    iListModel = iEngine->CreateListModelLC( *iTestObserver, iResourceReader );
+    CleanupStack::Pop();
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::EngineTestSetupL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::EngineTestSetupL()
+    {
+    User::LeaveIfError( iFs.Connect() );
+    iTestObserver  = new (ELeave) TTestOperationObserver;
+    iMimeTypeArray = new (ELeave) CDesCArrayFlat( 8 );
+    iEngine = ContentListingFactory::NewContentListingEngineLC();
+    CleanupStack::Pop();
+    iChangedItemObserver = new (ELeave) TTestChangedItemObserver;
+    iChangedItemObserver1 = new (ELeave) TTestChangedItemObserver;
+    iTestCLFProcessObserver = new (ELeave) TTestCLFProcessObserver;
+    iTestCLFProcessObserver1 = new (ELeave) TTestCLFProcessObserver;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SortingStyleTestSetupL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::SortingStyleTestSetupL()
+    {
+    iSortingStyle = ContentListingFactory::NewSortingStyleLC();
+    CleanupStack::Pop();
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SortingStyleResourceTestSetupL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::SortingStyleResourceTestSetupL()
+    {
+    SortingStyleResourceSetupL();
+    iSortingStyle1 = ContentListingFactory::NewSortingStyleLC( iResourceReader );
+    CleanupStack::Pop();
+
+    ResourceL( R_SORTING_STYLE_EMPTY );
+    iSortingStyle = ContentListingFactory::NewSortingStyleLC( iResourceReader );
+    CleanupStack::Pop();
+
+    ResourceL( R_SORTING_STYLE_UNDEFINEDITEM );
+    iSortingStyle2 = ContentListingFactory::NewSortingStyleLC( iResourceReader );
+    CleanupStack::Pop();
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::ModifiableItemTestSetupL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::ModifiableItemTestSetupL()
+    {
+    iModifiableItem = ContentListingFactory::NewModifiableItemLC();
+    CleanupStack::Pop();
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::ItemTestSetupL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::ItemTestSetupL()
+    {
+    ListModelSetupL();
+    CreateNewFileL( 12, iFileName );
+    iEngine->UpdateItemsL();
+    iMimeTypeArray->Reset();
+    iMimeTypeArray->AppendL( _L("*") );
+    iListModel->SetWantedMimeTypesL( *iMimeTypeArray );
+
+    iTestObserver->iWait = &iWait;
+    iListModel->RefreshL();
+    iWait.Start();
+
+    for( TInt i = 0 ; i < iListModel->ItemCount() ; ++i )
+        {
+        const MCLFItem& item = iListModel->Item( i );
+        TPtrC fn;
+        item.GetField( ECLFFieldIdFileNameAndPath, fn );
+        if( iFileName.CompareF( fn ) == 0 )
+            {
+            iItem = &item;
+            }
+        }
+
+    EUNIT_ASSERT( iItem ); // Item should be in model
+
+    }
+
+/**
+ * Teardown
+ */
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::Teardown
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::Teardown()
+    {
+    iResourceFile.Close();
+    iFs.Close();
+    iMediaTypeArray.Reset();
+    iMediaTypeArray.Close();
+    iMediaTypeArray1.Reset();
+    iMediaTypeArray1.Close();
+    iUpdateItemIdArray.Reset();
+    iUpdateItemIdArray.Close();
+    iChangedArray.Reset();
+    iChangedArray.Close();
+    iModifiableItems.ResetAndDestroy();
+    iModifiableItems.Close();
+    
+    delete iListModel;
+    iListModel = NULL;
+    delete iEngine;
+    iEngine = NULL;
+    delete iSortingStyle;
+    iSortingStyle = NULL;
+    delete iSortingStyle1;
+    iSortingStyle1 = NULL;
+    delete iSortingStyle2;
+    iSortingStyle2 = NULL;
+    delete iSortingStyle3;
+    iSortingStyle3 = NULL;
+    delete iDataBuffer;
+    iDataBuffer = NULL;    
+    delete iTestObserver;
+    iTestObserver = NULL;
+    delete iTestSorter;
+    iTestSorter = NULL;
+    delete iTestSorter1;
+    iTestSorter1 = NULL;
+    delete iTestGrouper;
+    iTestGrouper = NULL;
+    delete iTestGrouper1;
+    iTestGrouper1 = NULL;
+    delete iTestFilter;
+    iTestFilter = NULL;
+    delete iTestFilter1;
+    iTestFilter1 = NULL;
+    delete iMimeTypeArray;
+    iMimeTypeArray = NULL;
+    delete iMimeTypeArray1;
+    iMimeTypeArray1 = NULL;
+    delete iChangedItemObserver;
+    iChangedItemObserver = NULL;
+    delete iChangedItemObserver1;
+    iChangedItemObserver1 = NULL;
+    delete iOpaqueData;
+    iOpaqueData = NULL;
+    delete iModifiableItem;
+    iModifiableItem = NULL;
+    delete iTestCLFProcessObserver1;
+    iTestCLFProcessObserver1 = NULL;
+    delete iTestCLFProcessObserver;
+    iTestCLFProcessObserver = NULL;
+    
+    TTimeIntervalMicroSeconds32 time = 1000000;
+    TRAP_IGNORE( CCLFAsyncCallback::AfterL( time ) );
+    }
+
+/**
+ * Tests, construction
+ */
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CreateEngineTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::CreateEngineTestL()
+    {
+    MCLFContentListingEngine* engine = NULL;
+    engine = ContentListingFactory::NewContentListingEngineLC();
+    EUNIT_ASSERT( engine );
+    CleanupStack::PopAndDestroy();
+    engine = NULL;
+    engine = ContentListingFactory::NewContentListingEngineLC();
+    CleanupStack::Pop();
+    EUNIT_ASSERT( engine );
+    delete engine;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CreateModifiableItemTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::CreateModifiableItemTestL()
+    {
+    MCLFModifiableItem* item = NULL;
+    item = ContentListingFactory::NewModifiableItemLC();
+    EUNIT_ASSERT( item );
+    CleanupStack::PopAndDestroy();
+    item = NULL;
+    item = ContentListingFactory::NewModifiableItemLC();
+    CleanupStack::Pop();
+    EUNIT_ASSERT( item );
+    delete item;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CreateSortignStyleTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::CreateSortignStyleTestL()
+    {
+    MCLFSortingStyle* sortingStyle = NULL;
+    sortingStyle = ContentListingFactory::NewSortingStyleLC();
+    EUNIT_ASSERT( sortingStyle );
+    CleanupStack::PopAndDestroy();
+    sortingStyle = NULL;
+    sortingStyle = ContentListingFactory::NewSortingStyleLC();
+    CleanupStack::Pop();
+    EUNIT_ASSERT( sortingStyle );
+    delete sortingStyle;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CreateSortignStyleFromResourceTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::CreateSortignStyleFromResourceTestL()
+    {
+    MCLFSortingStyle* sortingStyle = NULL;
+    sortingStyle = ContentListingFactory::NewSortingStyleLC( iResourceReader );
+    EUNIT_ASSERT( sortingStyle );
+    CleanupStack::PopAndDestroy();
+    sortingStyle = NULL;
+
+    SortingStyleResourceL(); // refresh resource reader
+    sortingStyle = ContentListingFactory::NewSortingStyleLC( iResourceReader );
+    CleanupStack::Pop();
+    EUNIT_ASSERT( sortingStyle );
+    delete sortingStyle;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CreateListModelTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::CreateListModelTestL()
+    {
+    MCLFItemListModel* model = NULL;
+    model = iEngine->CreateListModelLC( *iTestObserver );
+    EUNIT_ASSERT( model );
+    CleanupStack::PopAndDestroy();
+    model = NULL;
+
+    model = iEngine->CreateListModelLC( *iTestObserver );
+    CleanupStack::Pop();
+    EUNIT_ASSERT( model );
+    delete model;
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::CreateListModelFromResourceTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::CreateListModelFromResourceTestL()
+    {
+    MCLFItemListModel* model = NULL;
+    model = iEngine->CreateListModelLC( *iTestObserver, iResourceReader );
+    EUNIT_ASSERT( model );
+    CleanupStack::PopAndDestroy();
+    model = NULL;
+
+    ListModelResourceL();
+    model = iEngine->CreateListModelLC( *iTestObserver, iResourceReader );
+    CleanupStack::Pop();
+    EUNIT_ASSERT( model );
+    delete model;
+
+
+    ResourceL( R_LIST_MODEL_INCORRECT_VERSION );
+    EUNIT_ASSERT_SPECIFIC_LEAVE( iEngine->CreateListModelLC( *iTestObserver, iResourceReader ), KErrNotSupported );
+   }
+
+/**
+ * Tests, engine
+ */
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::UpdateItemsTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::UpdateItemsTestL()
+    {
+    // MDS will do the updating automatically in the background,
+    // thus only checking that the methods return correctly
+    iChangedItemObserver->iWait = &iWait;
+    iChangedItemObserver->iChangedArray = &iChangedArray;
+    iEngine->AddChangedItemObserverL( *iChangedItemObserver );
+    iEngine->AddCLFProcessObserverL( *iTestCLFProcessObserver );
+    iEngine->AddCLFProcessObserverL( *iTestCLFProcessObserver1 );
+
+    CreateNewFileL( 0, iFileName );
+    CreateNewFileL( 1, iFileName );
+    CreateNewFileL( 2, iFileName );
+    CreateNewFileL( 3, iFileName );
+    CreateNewFileL( 4, iFileName );
+    CreateNewFileL( 5, iFileName );
+
+// update server
+// to avoid incorrect test result
+    CreateNewFileL( 0, iFileName );
+    iEngine->UpdateItemsL();
+
+    EUNIT_ASSERT( iChangedItemObserver->iLastError == KErrNone );
+
+    iChangedArray.Reset();
+    iEngine->RemoveCLFProcessObserver( *iTestCLFProcessObserver1 );
+    iChangedItemObserver->iHandleItemChange = EFalse;
+    iChangedItemObserver1->iHandleItemChange = EFalse;
+    iTestCLFProcessObserver->Reset();
+    iTestCLFProcessObserver1->Reset();
+    iEngine->UpdateItemsL();
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::UpdateItemsWithIdTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::UpdateItemsWithIdTestL()
+    {
+    // MDS will do the updating automatically in the background,
+    // thus only checking that the methods return correctly
+    iChangedItemObserver->iWait = &iWait;
+    iChangedItemObserver->iChangedArray = &iChangedArray;
+    iEngine->AddChangedItemObserverL( *iChangedItemObserver );
+    iEngine->AddChangedItemObserverL( *iChangedItemObserver1 );
+    iEngine->AddCLFProcessObserverL( *iTestCLFProcessObserver );
+
+    CreateNewFileL( 0, iFileName );
+    CreateNewFileL( 1, iFileName );
+    CreateNewFileL( 2, iFileName );
+
+// update server
+// to avoid incorrect test result
+    CreateNewFileL( 0, iFileName );
+    iEngine->UpdateItemsL();
+    
+    EUNIT_ASSERT( iChangedItemObserver->iLastError == KErrNone );
+
+// start testing
+// update by id
+    TUint id1 = FindTestFileIdL( 1 );
+    TUint id0 = FindTestFileIdL( 0 );
+    TUint id2 = FindTestFileIdL( 2 );
+    iUpdateItemIdArray.AppendL( id1 );
+    iChangedItemObserver->iHandleItemChange = EFalse;
+    iChangedItemObserver1->iHandleItemChange = EFalse;
+    iTestCLFProcessObserver->Reset();
+    iTestCLFProcessObserver1->Reset();
+    CreateNewFileL( 0, iFileName );
+    CreateNewFileL( 1, iFileName );
+    iEngine->UpdateItemsL( iUpdateItemIdArray.Array() );
+    
+    EUNIT_ASSERT( iChangedItemObserver->iLastError == KErrNone );
+
+    iEngine->RemoveChangedItemObserver( *iChangedItemObserver1 );
+    iEngine->AddCLFProcessObserverL( *iTestCLFProcessObserver1 );
+
+    iChangedItemObserver->iHandleItemChange = EFalse;
+    iChangedItemObserver1->iHandleItemChange = EFalse;
+    iTestCLFProcessObserver->Reset();
+    iTestCLFProcessObserver1->Reset();
+    iUpdateItemIdArray.AppendL( id0 );
+    iUpdateItemIdArray.AppendL( id2 );
+    
+// update server
+// to avoid incorrect test result
+    iEngine->UpdateItemsL();
+    
+    EUNIT_ASSERT( iChangedItemObserver->iLastError == KErrNone );
+    
+    CreateNewFileL( 0, iFileName );
+    CreateNewFileL( 1, iFileName );
+    CreateNewFileL( 2, iFileName );
+    iChangedArray.Reset();
+    
+    iEngine->UpdateItemsL( iUpdateItemIdArray.Array() );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::UpdateItemsWithOpaqueDataFolderTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::UpdateItemsWithOpaqueDataFolderTestL()
+    {
+    // update server
+    // to avoid incorrect test result
+    iEngine->UpdateItemsL();
+    iWait.Start();
+
+    // start testing
+    // update by opaque data
+    // folders data
+    iSemanticId = KCLFUpdateFoldersSemanticId;
+    delete iOpaqueData;
+    iOpaqueData = NULL;
+
+    CDesCArray* fileArray = new (ELeave) CDesCArraySeg( 8 );
+    iOpaqueData = MakeOpaqueDataL( *fileArray );
+    // Calls internally same MDS method as when updating all data
+    // thus only interested if this call leaves
+    iEngine->UpdateItemsL( iSemanticId, *iOpaqueData );
+    }
+
+/**
+ * Tests, list model
+ */
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::RefreshTestL
+// ---------------------------------------------------------------------------
+//  
+void T_CLFApiModuleTests::RefreshTestL()
+    {
+    iMimeTypeArray->Reset();
+    iMimeTypeArray->AppendL( _L("*") );
+    iListModel->SetWantedMimeTypesL( *iMimeTypeArray );
+
+    iTestObserver->iWait = &iWait;
+    iTestObserver->iError = 100;
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( iTestObserver->iOperationEvent == ECLFRefreshComplete );
+    EUNIT_ASSERT( iTestObserver->iError == KErrNone );
+    EUNIT_ASSERT( iListModel->ItemCount() > 0 );
+
+// cancel refresh
+    iListModel->RefreshL();
+    iListModel->CancelRefresh();
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SetSortingStyleTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::SetSortingStyleTestL()
+    {
+    iListModel->SetSortingStyle( NULL );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( !CheckFileNameShortingL() );
+
+// file name sorting
+    iSortingStyle->ResetL();
+    iSortingStyle->SetSortingDataType( ECLFItemDataTypeDesC );
+    iSortingStyle->AddFieldL( ECLFFieldIdFileName );
+    iListModel->SetSortingStyle( iSortingStyle );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( CheckFileNameShortingL() );
+
+// file size sorting
+    iSortingStyle1->ResetL();
+    iSortingStyle1->SetOrdering( ECLFOrderingDescending );
+    iSortingStyle1->SetSortingDataType( ECLFItemDataTypeTInt32 );
+    iSortingStyle1->AddFieldL( ECLFFieldIdFileSize );
+    iListModel->SetSortingStyle( iSortingStyle1 );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( CheckFileSizeShortingL() );
+
+    iListModel->SetSortingStyle( NULL );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( !CheckFileNameShortingL() );
+    EUNIT_ASSERT( !CheckFileSizeShortingL() );
+    EUNIT_ASSERT( !CheckFileDateShortingL() );
+
+// time sorting
+    iSortingStyle->ResetL();
+    iSortingStyle->SetSortingDataType( ECLFItemDataTypeTTime );
+    iSortingStyle->AddFieldL( ECLFFieldIdFileDate );
+    iListModel->SetSortingStyle( iSortingStyle );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( CheckFileDateShortingL() );
+
+// parameter test (time)
+    iListModel->SetSortingStyle( NULL );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( !CheckFileNameShortingL() );
+    EUNIT_ASSERT( !CheckFileSizeShortingL() );
+    EUNIT_ASSERT( !CheckFileDateShortingL() );
+
+    iListModel->SetSortingStyle( iSortingStyle );
+    iListModel->RefreshL( ECLFRefreshPostFilter );
+    EUNIT_ASSERT( !CheckFileNameShortingL() );
+    EUNIT_ASSERT( !CheckFileSizeShortingL() );
+    EUNIT_ASSERT( !CheckFileDateShortingL() );
+
+    iListModel->RefreshL( ECLFRefreshGrouping );
+    EUNIT_ASSERT( !CheckFileNameShortingL() );
+    EUNIT_ASSERT( !CheckFileSizeShortingL() );
+    EUNIT_ASSERT( !CheckFileDateShortingL() );
+
+    iListModel->RefreshL( ECLFRefreshSorting );
+    EUNIT_ASSERT( !CheckFileNameShortingL() );
+    EUNIT_ASSERT( !CheckFileSizeShortingL() );
+    EUNIT_ASSERT( CheckFileDateShortingL() );
+
+// custom sorter (overwrite sorting style)
+    iTestSorter->iSortItems = EFalse;
+
+    iListModel->SetCustomSorter( iTestSorter );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( iTestSorter->iSortItems );
+    EUNIT_ASSERT( !CheckFileNameShortingL() );
+    EUNIT_ASSERT( !CheckFileSizeShortingL() );
+    EUNIT_ASSERT( !CheckFileDateShortingL() );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SetCustomSorterTestL
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::SetCustomSorterTestL()
+    {
+    iTestSorter->iSortItems = EFalse;
+    iTestSorter1->iSortItems = EFalse;
+
+    iListModel->SetCustomSorter( NULL );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( !iTestSorter->iSortItems );
+    EUNIT_ASSERT( !iTestSorter1->iSortItems );
+
+    iTestSorter->iSortItems = EFalse;
+    iTestSorter1->iSortItems = EFalse;
+
+    iListModel->SetCustomSorter( iTestSorter );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( iTestSorter->iSortItems );
+    EUNIT_ASSERT( !iTestSorter1->iSortItems );
+
+    iTestSorter->iSortItems = EFalse;
+    iTestSorter1->iSortItems = EFalse;
+
+    iListModel->SetCustomSorter( iTestSorter1 );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( !iTestSorter->iSortItems );
+    EUNIT_ASSERT( iTestSorter1->iSortItems );
+
+    iTestSorter->iSortItems = EFalse;
+    iTestSorter1->iSortItems = EFalse;
+
+    iListModel->SetCustomSorter( NULL );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( !iTestSorter->iSortItems );
+    EUNIT_ASSERT( !iTestSorter1->iSortItems );
+
+    iTestSorter->iSortItems = EFalse;
+    iTestSorter1->iSortItems = EFalse;
+
+    iListModel->SetCustomSorter( iTestSorter );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( iTestSorter->iSortItems );
+    EUNIT_ASSERT( !iTestSorter1->iSortItems );
+
+    iTestSorter->iSortItems = EFalse;
+    iTestSorter1->iSortItems = EFalse;
+
+    iListModel->SetCustomSorter( iTestSorter1 );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( !iTestSorter->iSortItems );
+    EUNIT_ASSERT( iTestSorter1->iSortItems );
+
+// parameter test
+    iTestSorter->iSortItems = EFalse;
+    iTestSorter1->iSortItems = EFalse;
+
+    iListModel->SetCustomSorter( NULL );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( !iTestSorter->iSortItems );
+    EUNIT_ASSERT( !iTestSorter1->iSortItems );
+
+
+    iTestSorter->iSortItems = EFalse;
+    iTestSorter1->iSortItems = EFalse;
+
+    iListModel->SetCustomSorter( iTestSorter );
+    iListModel->RefreshL( ECLFRefreshPostFilter );
+    EUNIT_ASSERT( !iTestSorter->iSortItems );
+    EUNIT_ASSERT( !iTestSorter1->iSortItems );
+
+    iListModel->RefreshL( ECLFRefreshGrouping );
+    EUNIT_ASSERT( !iTestSorter->iSortItems );
+    EUNIT_ASSERT( !iTestSorter1->iSortItems );
+
+    iListModel->RefreshL( ECLFRefreshSorting );
+    EUNIT_ASSERT( iTestSorter->iSortItems );
+    EUNIT_ASSERT( !iTestSorter1->iSortItems );
+
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::GroupingTestL
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::GroupingTestL()
+    {
+    iTestGrouper->iModifiableItems = &iModifiableItems;
+    iTestGrouper1->iModifiableItems = &iModifiableItems;
+
+// No grouping
+    iListModel->SetCustomGrouper( NULL );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( iListModel->ItemCount() == iItemCount );
+
+// couple groups
+    iListModel->SetCustomGrouper( iTestGrouper );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( iListModel->ItemCount() == iModifiableItems.Count() );
+
+// 0 groups
+    iTestGrouper1->iGroupCount = 0;
+    iListModel->SetCustomGrouper( iTestGrouper1 );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( iListModel->ItemCount() == iModifiableItems.Count() );
+
+// No grouping
+    iListModel->SetCustomGrouper( NULL );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( iListModel->ItemCount() == iItemCount );
+// Music album grouping
+    iListModel->SetGroupingStyle( ECLFMusicAlbumGrouping );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( iListModel->ItemCount() != iItemCount );
+// No grouping
+    iListModel->SetGroupingStyle( ECLFNoGrouping );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( iListModel->ItemCount() == iItemCount );
+
+// test parameters
+    iTestGrouper->iGroupCount = 1000;
+    iListModel->SetCustomGrouper( iTestGrouper );
+    iListModel->RefreshL( ECLFRefreshPostFilter );
+    EUNIT_ASSERT( iListModel->ItemCount() == iItemCount );
+    iListModel->RefreshL( ECLFRefreshSorting );
+    EUNIT_ASSERT( iListModel->ItemCount() == iItemCount );
+    iListModel->RefreshL( ECLFRefreshGrouping );
+    EUNIT_ASSERT( iListModel->ItemCount() == iModifiableItems.Count() );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SetPostFilterTestL
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::SetPostFilterTestL()
+    {
+// no filter
+    iListModel->SetPostFilter( NULL );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( iListModel->ItemCount() == iItemCount );
+
+// filter couple items
+    iListModel->SetPostFilter( iTestFilter );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( ( iListModel->ItemCount() + iTestFilter->iFilteredCount ) == iItemCount );
+
+// filter all items
+    iListModel->SetPostFilter( iTestFilter1 );
+    iTestFilter1->iAllFilter = ETrue;
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( ( iListModel->ItemCount() + iTestFilter1->iFilteredCount ) == iItemCount );
+
+// no filter
+    iListModel->SetPostFilter( NULL );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( iListModel->ItemCount() == iItemCount );
+
+// filter one item
+    iListModel->SetPostFilter( iTestFilter );
+    iTestFilter->iShouldFilterCount = 1;
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( ( iListModel->ItemCount() + iTestFilter->iFilteredCount ) == iItemCount );
+
+// filter couple items
+    iListModel->SetPostFilter( iTestFilter1 );
+    iTestFilter1->iAllFilter = EFalse;
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( ( iListModel->ItemCount() + iTestFilter1->iFilteredCount ) == iItemCount );
+
+// test parameters
+    iListModel->SetPostFilter( NULL );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( iListModel->ItemCount() == iItemCount );
+    iListModel->SetPostFilter( iTestFilter1 );
+    iTestFilter1->iAllFilter = ETrue;
+    iListModel->RefreshL( ECLFRefreshSorting );
+    EUNIT_ASSERT( iListModel->ItemCount() == iItemCount );
+    iListModel->RefreshL( ECLFRefreshGrouping );
+    EUNIT_ASSERT( iListModel->ItemCount() == iItemCount );
+    iListModel->RefreshL( ECLFRefreshPostFilter );
+    EUNIT_ASSERT( ( iListModel->ItemCount() + iTestFilter1->iFilteredCount ) == iItemCount );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SetWantedMimeTypesTestL
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::SetWantedMimeTypesTestL()
+    {
+    iTestObserver->iWait = &iWait;
+
+// list not defined (mimetype)
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( iListModel->ItemCount() == 0 );
+
+// couple mime types
+    iMimeTypeArray->Reset();
+    iMimeTypeArray->AppendL( _L( "audio/mpeg" ) );
+    iMimeTypeArray->AppendL( _L( "audio/aac" ) );
+    iMimeTypeArray->AppendL( _L( "audio/mp3" ) );
+    iMimeTypeArray->AppendL( _L( "audio/x-mp3" ) );
+    iMimeTypeArray->AppendL( _L( "audio/mp4" ) );
+    iMimeTypeArray->AppendL( _L( "audio/3gpp" ) );
+    iMimeTypeArray->AppendL( _L( "audio/m4a" ) );
+    iMimeTypeArray->AppendL( _L( "audio/3gpp2" ) );
+    iMimeTypeArray->AppendL( _L( "audio/mpeg4") );
+    iListModel->SetWantedMimeTypesL( *iMimeTypeArray );
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( CheckFileTypesL( *iMimeTypeArray, iMediaTypeArray.Array() ) );
+
+// unsupported mimetype
+    iMimeTypeArray1->Reset();
+    iMimeTypeArray1->AppendL( _L("ei tämmöstä ees pitäis olla")  );
+    iListModel->SetWantedMimeTypesL( *iMimeTypeArray1 );
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( iListModel->ItemCount() == 0 );
+
+// empty mimetype list
+    iMimeTypeArray1->Reset();
+    iListModel->SetWantedMimeTypesL( *iMimeTypeArray1 );
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( iListModel->ItemCount() == 0 );
+
+// from resource (mimetype)
+    iMimeTypeArray->Reset();
+    iMimeTypeArray->AppendL( _L("image/*")  );
+    iMimeTypeArray->AppendL( _L("audio/*")  );
+
+    ResourceL( R_MIME_TYPE_ARRAY );
+    iListModel->SetWantedMimeTypesL( iResourceReader );
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( CheckFileTypesL( *iMimeTypeArray, iMediaTypeArray.Array() ) );
+
+    ResourceL( R_MIME_TYPE_ARRAY_EMPTY );
+    iListModel->SetWantedMimeTypesL( iResourceReader );
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( iListModel->ItemCount() == 0 );
+
+// incorrect resource version
+    ResourceL( R_MIME_TYPE_ARRAY_INCORRECT_VERSION );
+    EUNIT_ASSERT_SPECIFIC_LEAVE( iListModel->SetWantedMimeTypesL( iResourceReader ), KErrNotSupported );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SetWantedMediaTypesTestL
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::SetWantedMediaTypesTestL()
+    {
+    iTestObserver->iWait = &iWait;
+
+// list not defined (mediatype)
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( iListModel->ItemCount() == 0 );
+
+// couple media types
+    iMediaTypeArray.AppendL( ECLFMediaTypeVideo );
+    iMediaTypeArray.AppendL( ECLFMediaTypeImage );
+    iMediaTypeArray.AppendL( ECLFMediaTypeSound );
+    iMediaTypeArray.AppendL( ECLFMediaTypeMusic );
+    iMediaTypeArray.AppendL( ECLFMediaTypeStreamingURL );
+    iMediaTypeArray.AppendL( ECLFMediaTypePlaylist );
+    iMediaTypeArray.AppendL( TCLFMediaType( ECLFMediaTypeCollection ) );
+
+    iListModel->SetWantedMediaTypesL( iMediaTypeArray.Array() );
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( CheckFileTypesL( *iMimeTypeArray, iMediaTypeArray.Array() ) );
+
+// empty media type list list
+    iListModel->SetWantedMediaTypesL( iMediaTypeArray1.Array() );
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( iListModel->ItemCount() == 0 );
+
+// media type list from resource
+    iMediaTypeArray.Reset();
+    iMediaTypeArray.AppendL( ECLFMediaTypeImage );
+    iMediaTypeArray.AppendL( TCLFMediaType( ECLFMediaTypeCollection ) );
+    ResourceL( R_MEDIA_TYPE_ARRAY );
+    iListModel->SetWantedMediaTypesL( iResourceReader );
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( CheckFileTypesL( *iMimeTypeArray, iMediaTypeArray.Array() ) );
+
+// empty media type list from resource
+    ResourceL( R_MEDIA_TYPE_ARRAY_EMPTY );
+    iListModel->SetWantedMediaTypesL( iResourceReader );
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( iListModel->ItemCount() == 0 );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SetWantedMediaAndMimeTypesTestL
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::SetWantedMediaAndMimeTypesTestL()
+    {
+    iTestObserver->iWait = &iWait;
+
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( iListModel->ItemCount() == 0 );
+
+// couple types
+    iMimeTypeArray->AppendL( _L( "audio/mpeg" ) );
+    iMimeTypeArray->AppendL( _L( "audio/aac" ) );
+    iMimeTypeArray->AppendL( _L( "audio/mp3" ) );
+    iMimeTypeArray->AppendL( _L( "audio/x-mp3" ) );
+    iMimeTypeArray->AppendL( _L( "audio/mp4" ) );
+    iMimeTypeArray->AppendL( _L( "audio/3gpp" ) );
+    iMimeTypeArray->AppendL( _L( "audio/m4a" ) );
+    iMimeTypeArray->AppendL( _L( "audio/3gpp2" ) );
+    iMimeTypeArray->AppendL( _L( "audio/mpeg4") );
+    iListModel->SetWantedMimeTypesL( *iMimeTypeArray );
+
+    iMediaTypeArray.AppendL( ECLFMediaTypeVideo );
+    iListModel->SetWantedMediaTypesL( iMediaTypeArray.Array() );
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( CheckFileTypesL( *iMimeTypeArray, iMediaTypeArray.Array() ) );
+
+// refresh again
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( CheckFileTypesL( *iMimeTypeArray, iMediaTypeArray.Array() ) );
+
+// empty lists
+    iMediaTypeArray.Reset();
+    iMimeTypeArray->Reset();
+    iListModel->SetWantedMediaTypesL( iMediaTypeArray.Array() );
+    iListModel->SetWantedMimeTypesL( *iMimeTypeArray );
+    iListModel->RefreshL();
+    iWait.Start();
+    EUNIT_ASSERT( iListModel->ItemCount() == 0 );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::MultibleSortingTestL
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::MultibleSortingTestL()
+    {
+
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( CheckMultibleSortingShortingL() );
+
+// resort
+
+    iSortingStyle->ResetL();
+    iSortingStyle->SetSortingDataType( ECLFItemDataTypeTInt32 );
+    iSortingStyle->AddFieldL( KMultibleSortingTestField6 );
+    iSortingStyle->AddFieldL( KMultibleSortingTestField5 );
+    iSortingStyle->SetUndefinedItemPosition( ECLFSortingStyleUndefinedEnd );
+    iListModel->SetSortingStyle( iSortingStyle );
+    iListModel->RefreshL( ECLFRefreshAll );
+    EUNIT_ASSERT( CheckMultibleSortingShorting2L() );
+
+    }
+
+/*
+* Test model item(s) obsolate functionality
+*/
+
+// ---------------------------------------------------------------------------
+// ModelItemsChangedTestL
+// ---------------------------------------------------------------------------
+//
+void T_CLFApiModuleTests::ModelItemsChangedTestL()
+    {
+    const TInt newFileNumber( 10 );
+
+// create test files
+    CreateNewFileL( 0, iFileName );
+    CreateNewFileL( 1, iFileName );
+    CreateNewFileL( 2, iFileName );
+    CreateNewFileL( newFileNumber, iFileName );
+    User::LeaveIfError( iFs.Delete( iFileName ) );
+
+// update server
+// to avoid incorrect test result
+    CreateNewFileL( 0, iFileName );
+    iEngine->UpdateItemsL();
+
+// create list model with all files
+    iMimeTypeArray->Reset();
+    iMimeTypeArray->AppendL( _L("*") );
+    iListModel->SetWantedMimeTypesL( *iMimeTypeArray );
+
+    iTestObserver->iWait = &iWait;
+    iTestObserver->iError = 100;
+    iListModel->RefreshL();
+    iWait.Start();  // wait until model is refreshed
+    EUNIT_ASSERT( iTestObserver->iOperationEvent == ECLFRefreshComplete );
+    EUNIT_ASSERT( iTestObserver->iError == KErrNone );
+    EUNIT_ASSERT( iListModel->ItemCount() > 0 );
+
+    const TInt listModelItemCount( iListModel->ItemCount() );
+    const TCLFItemId testId( FindTestFileIdL( 0 ) );
+
+// test with modified item
+    CreateNewFileL( 0, iFileName );
+    iEngine->UpdateItemsL();
+    iWait.Start(); // wait until model outdated event is received
+
+    EUNIT_ASSERT( iTestObserver->iOperationEvent == ECLFModelOutdated );
+    EUNIT_ASSERT( iTestObserver->iError == KErrNone );
+    EUNIT_ASSERT( iListModel->ItemCount() == listModelItemCount );
+    EUNIT_ASSERT( NULL != FindItem( *iListModel, testId ) );
+
+    iTestObserver->iError = 100;
+    iListModel->RefreshL();
+    iWait.Start();  // wait until model is refreshed
+    EUNIT_ASSERT( iTestObserver->iOperationEvent == ECLFRefreshComplete );
+    EUNIT_ASSERT( iTestObserver->iError == KErrNone );
+    EUNIT_ASSERT( iListModel->ItemCount() == listModelItemCount );
+    EUNIT_ASSERT( NULL != FindItem( *iListModel, testId ) );
+
+// test with new item
+    CreateNewFileL( newFileNumber, iFileName );
+    iEngine->UpdateItemsL();
+    iWait.Start(); // wait until model outdated event is received
+
+    EUNIT_ASSERT( iTestObserver->iOperationEvent == ECLFModelOutdated );
+    EUNIT_ASSERT( iTestObserver->iError == KErrNone );
+    EUNIT_ASSERT( iListModel->ItemCount() == listModelItemCount );
+
+    iTestObserver->iError = 100;
+    iListModel->RefreshL();
+    iWait.Start();  // wait until model is refreshed
+    EUNIT_ASSERT( iTestObserver->iOperationEvent == ECLFRefreshComplete );
+    EUNIT_ASSERT( iTestObserver->iError == KErrNone );
+    EUNIT_ASSERT( iListModel->ItemCount() == listModelItemCount + 1 );
+
+// delete file
+    User::LeaveIfError( iFs.Delete( iFileName ) );
+    iEngine->UpdateItemsL();
+    iWait.Start(); // wait until model outdated event is received
+
+    EUNIT_ASSERT( iTestObserver->iOperationEvent == ECLFModelOutdated );
+    EUNIT_ASSERT( iTestObserver->iError == KErrNone );
+    EUNIT_ASSERT( iListModel->ItemCount() == listModelItemCount + 1 );
+
+    iTestObserver->iError = 100;
+    iListModel->RefreshL();
+    iWait.Start();  // wait until model is refreshed
+    EUNIT_ASSERT( iTestObserver->iOperationEvent == ECLFRefreshComplete );
+    EUNIT_ASSERT( iTestObserver->iError == KErrNone );
+    EUNIT_ASSERT( iListModel->ItemCount() == listModelItemCount );
+    }
+
+/**
+ * Tests, Modifiable item
+ */
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::MIFieldTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::MIFieldTestL()
+    {
+    const TUint KTestField1 = 1;
+    const TUint KTestField2 = 112312312;
+    const TUint KTestField3 = 13333;
+    const TUint KTestFieldIncorrect = 2;
+
+    TTime time( 100 );
+    TInt32 integer( 12 );
+    TBuf<30> data( _L("data") );
+    iModifiableItem->AddFieldL( KTestField1, time );
+    iModifiableItem->AddFieldL( KTestField2, integer );
+    iModifiableItem->AddFieldL( KTestField3, data );
+
+// data type test
+    EUNIT_ASSERT( iModifiableItem->DataType(
+                                KTestField1 ) == ECLFItemDataTypeTTime );
+    EUNIT_ASSERT( iModifiableItem->DataType(
+                                KTestField2 ) == ECLFItemDataTypeTInt32 );
+    EUNIT_ASSERT( iModifiableItem->DataType(
+                                KTestField3 ) == ECLFItemDataTypeDesC );
+    EUNIT_ASSERT( iModifiableItem->DataType(
+                                KTestFieldIncorrect ) == ECLFItemDataTypeNull );
+    EUNIT_ASSERT( iModifiableItem->DataType(
+                                ECLFFieldIdNull ) == ECLFItemDataTypeNull );
+
+// get field
+    TTime time1( 0 );
+    TInt32 integer1( 0 );
+    TPtrC ptr;
+    EUNIT_ASSERT( KErrNone == iModifiableItem->GetField(
+                                                KTestField1, time1 ) );
+    EUNIT_ASSERT( time == time1 );
+    EUNIT_ASSERT( KErrNone == iModifiableItem->GetField(
+                                                KTestField2, integer1 ) );
+    EUNIT_ASSERT( integer == integer1 );
+    EUNIT_ASSERT( KErrNone == iModifiableItem->GetField(
+                                                KTestField3, ptr ) );
+    EUNIT_ASSERT( data == ptr );
+
+// incorrect field id
+    EUNIT_ASSERT( KErrNotFound == iModifiableItem->GetField(
+                                                KTestFieldIncorrect, ptr ) );
+    EUNIT_ASSERT( KErrNotFound == iModifiableItem->GetField(
+                                                KTestFieldIncorrect, integer1 ) );
+    EUNIT_ASSERT( KErrNotFound == iModifiableItem->GetField(
+                                                KTestFieldIncorrect, time1 ) );
+
+// incorrect field type
+    EUNIT_ASSERT( KErrNotSupported == iModifiableItem->GetField(
+                                                KTestField1, ptr ) );
+    EUNIT_ASSERT( KErrNotSupported == iModifiableItem->GetField(
+                                                KTestField3, integer1 ) );
+    EUNIT_ASSERT( KErrNotSupported == iModifiableItem->GetField(
+                                                KTestField2, time1 ) );
+
+
+    EUNIT_ASSERT( iModifiableItem->ItemId() == 0 );
+    }
+
+/**
+ * Tests, item
+ */
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::ItemFieldTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::ItemFieldTestL()
+    {
+// data type test
+    EUNIT_ASSERT( iItem->DataType(
+                                ECLFFieldIdFileDate ) == ECLFItemDataTypeTTime );
+    EUNIT_ASSERT( iItem->DataType(
+                                ECLFFieldIdFileSize ) == ECLFItemDataTypeTInt32 );
+    EUNIT_ASSERT( iItem->DataType(
+                                ECLFFieldIdFileNameAndPath ) == ECLFItemDataTypeDesC );
+    EUNIT_ASSERT( iItem->DataType(
+                                ECLFFieldIdNull ) == ECLFItemDataTypeNull );
+
+// get field
+    TTime time1( 0 );
+    TInt32 integer1( 0 );
+    TPtrC ptr;
+    TEntry entry;
+    User::LeaveIfError( iFs.Entry( iFileName, entry ) );
+
+    EUNIT_ASSERT( KErrNone == iItem->GetField( ECLFFieldIdFileDate, time1 ) );
+    EUNIT_ASSERT( entry.iModified == time1 );
+    EUNIT_ASSERT( KErrNone == iItem->GetField( ECLFFieldIdFileSize, integer1 ) );
+    EUNIT_ASSERT( entry.iSize == integer1 );
+    EUNIT_ASSERT( KErrNone == iItem->GetField( ECLFFieldIdFileNameAndPath, ptr ) );
+    EUNIT_ASSERT( iFileName == ptr );
+
+    TParsePtrC parse( iFileName );
+
+    EUNIT_ASSERT( KErrNone == iItem->GetField( ECLFFieldIdFileExtension, ptr ) );
+    EUNIT_ASSERT( parse.Ext() == ptr );
+
+    EUNIT_ASSERT( KErrNone == iItem->GetField( ECLFFieldIdFileName, ptr ) );
+    EUNIT_ASSERT( parse.Name() == ptr );
+
+    EUNIT_ASSERT( KErrNone == iItem->GetField( ECLFFieldIdPath, ptr ) );
+    EUNIT_ASSERT( parse.Path() == ptr );
+
+    EUNIT_ASSERT( KErrNone == iItem->GetField( ECLFFieldIdDrive, ptr ) );
+    EUNIT_ASSERT( parse.Drive() == ptr );
+
+
+// incorrect field id
+    EUNIT_ASSERT( KErrNotFound == iItem->GetField(
+                                                ECLFFieldIdNull, ptr ) );
+    EUNIT_ASSERT( KErrNotFound == iItem->GetField(
+                                                ECLFFieldIdNull, integer1 ) );
+    EUNIT_ASSERT( KErrNotFound == iItem->GetField(
+                                                ECLFFieldIdNull, time1 ) );
+
+// incorrect field type
+    EUNIT_ASSERT( KErrNotSupported == iItem->GetField(
+                                                ECLFFieldIdFileSize, ptr ) );
+    EUNIT_ASSERT( KErrNotSupported == iItem->GetField(
+                                                ECLFFieldIdFileDate, integer1 ) );
+    EUNIT_ASSERT( KErrNotSupported == iItem->GetField(
+                                                ECLFFieldIdFileNameAndPath, time1 ) );
+
+
+    EUNIT_ASSERT( iItem->ItemId() != 0 );
+    }
+
+/**
+ * Tests, Sorting style
+ */
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SortingStyleResourceTestL
+// ---------------------------------------------------------------------------
+//  
+void T_CLFApiModuleTests::SortingStyleResourceTestL()
+    {
+    const TInt KArray1IdCount( 4 );
+    const TInt KArray2IdCount( 1 );
+
+
+    RArray<TCLFItemId> itemIdArray;
+    CleanupClosePushL( itemIdArray );
+
+    EUNIT_ASSERT( iSortingStyle->Ordering() == ECLFOrderingAscending );
+    EUNIT_ASSERT( iSortingStyle1->Ordering() == ECLFOrderingDescending );
+    EUNIT_ASSERT( iSortingStyle2->Ordering() == ECLFOrderingDescending );
+    EUNIT_ASSERT( iSortingStyle->SortingDataType() == ECLFItemDataTypeTInt32 );
+    EUNIT_ASSERT( iSortingStyle1->SortingDataType() == ECLFItemDataTypeDesC );
+    EUNIT_ASSERT( iSortingStyle2->SortingDataType() == ECLFItemDataTypeDesC );
+
+    iSortingStyle->GetFieldsL( itemIdArray );
+
+    EUNIT_ASSERT( itemIdArray.Count() == 0 );
+
+    itemIdArray.Reset();
+    iSortingStyle1->GetFieldsL( itemIdArray );
+
+    EUNIT_ASSERT( itemIdArray.Count() == KArray1IdCount );
+
+    itemIdArray.Reset();
+    iSortingStyle2->GetFieldsL( itemIdArray );
+
+    EUNIT_ASSERT( itemIdArray.Count() == KArray2IdCount );
+
+    CleanupStack::PopAndDestroy( &itemIdArray ); // itemIdArray.Close
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SortingStyleOrderingTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::SortingStyleOrderingTestL()
+    {
+    iSortingStyle->SetOrdering( ECLFOrderingAscending );
+    EUNIT_ASSERT( iSortingStyle->Ordering() == ECLFOrderingAscending );
+    iSortingStyle->SetOrdering( ECLFOrderingDescending );
+    EUNIT_ASSERT( iSortingStyle->Ordering() == ECLFOrderingDescending );
+    iSortingStyle->SetOrdering( ECLFOrderingAscending );
+    EUNIT_ASSERT( iSortingStyle->Ordering() == ECLFOrderingAscending );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SortingStyleDataTypeTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::SortingStyleDataTypeTestL()
+    {
+    iSortingStyle->SetSortingDataType( ECLFItemDataTypeTInt32 );
+    EUNIT_ASSERT( iSortingStyle->SortingDataType() == ECLFItemDataTypeTInt32 );
+    iSortingStyle->SetSortingDataType( ECLFItemDataTypeDesC );
+    EUNIT_ASSERT( iSortingStyle->SortingDataType() == ECLFItemDataTypeDesC );
+    iSortingStyle->SetSortingDataType( ECLFItemDataTypeTTime );
+    EUNIT_ASSERT( iSortingStyle->SortingDataType() == ECLFItemDataTypeTTime );
+    iSortingStyle->SetSortingDataType( ECLFItemDataTypeNull );
+    EUNIT_ASSERT( iSortingStyle->SortingDataType() == ECLFItemDataTypeNull );
+    iSortingStyle->SetSortingDataType( ECLFItemDataTypeTInt32 );
+    EUNIT_ASSERT( iSortingStyle->SortingDataType() == ECLFItemDataTypeTInt32 );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SortingStyleUndefinedItemPositionTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::SortingStyleUndefinedItemPositionTestL()
+    {
+    iSortingStyle->SetUndefinedItemPosition( ECLFSortingStyleUndefinedEnd );
+    EUNIT_ASSERT( iSortingStyle->UndefinedItemPosition() == ECLFSortingStyleUndefinedEnd );
+    iSortingStyle->SetUndefinedItemPosition( ECLFSortingStyleUndefinedFirst );
+    EUNIT_ASSERT( iSortingStyle->UndefinedItemPosition() == ECLFSortingStyleUndefinedFirst );
+    iSortingStyle->SetUndefinedItemPosition( ECLFSortingStyleUndefinedEnd );
+    EUNIT_ASSERT( iSortingStyle->UndefinedItemPosition() == ECLFSortingStyleUndefinedEnd );
+    }
+
+// ---------------------------------------------------------------------------
+// T_CLFApiModuleTests::SortingStyleFieldTestL
+// ---------------------------------------------------------------------------
+// 
+void T_CLFApiModuleTests::SortingStyleFieldTestL()
+    {
+    RArray<TCLFItemId> itemIdArray;
+    CleanupClosePushL( itemIdArray );
+
+    iSortingStyle->GetFieldsL( itemIdArray );
+    EUNIT_ASSERT( itemIdArray.Count() == 0 );
+
+    iSortingStyle->AddFieldL( ECLFFieldIdFileName );
+    iSortingStyle->AddFieldL( ECLFFieldIdCollectionId );
+    iSortingStyle->AddFieldL( ECLFFieldIdCollectionName );
+    iSortingStyle->AddFieldL( ECLFFieldIdArtist );
+
+    iSortingStyle->GetFieldsL( itemIdArray );
+
+    EUNIT_ASSERT( itemIdArray.Count() == 4 );
+
+    itemIdArray.Reset();
+    iSortingStyle->ResetL();
+    iSortingStyle->GetFieldsL( itemIdArray );
+    EUNIT_ASSERT( itemIdArray.Count() == 0 );
+
+    CleanupStack::PopAndDestroy( &itemIdArray ); // itemIdArray.Close
+    }
+
+// ---------------------------------------------------------------------------
+// Test case table for this test suite class
+// ---------------------------------------------------------------------------
+// 
+
+EUNIT_BEGIN_TEST_TABLE( T_CLFApiModuleTests, "T_CLFApiModuleTests", "MODULE" )
+
+// Constructor tests
+    EUNIT_TEST( "Create engine",
+                "",
+                "",
+                "FUNCTIONALITY",
+                BaseSetupL,
+                CreateEngineTestL,
+                Teardown )
+
+    EUNIT_TEST( "Create modifiable item",
+                "",
+                "",
+                "FUNCTIONALITY",
+                BaseSetupL,
+                CreateModifiableItemTestL,
+                Teardown )
+
+    EUNIT_TEST( "Create sorting style",
+                "",
+                "",
+                "FUNCTIONALITY",
+                BaseSetupL,
+                CreateSortignStyleTestL,
+                Teardown )
+
+    EUNIT_TEST( "Create sorting style from resource",
+                "",
+                "",
+                "FUNCTIONALITY",
+                SortingStyleResourceSetupL,
+                CreateSortignStyleFromResourceTestL,
+                Teardown )
+
+    EUNIT_TEST( "Create list model",
+                "",
+                "",
+                "FUNCTIONALITY",
+                CreateModelSetupL,
+                CreateListModelTestL,
+                Teardown )
+
+    EUNIT_TEST( "Create list model from resource",
+                "",
+                "",
+                "FUNCTIONALITY",
+                CreateModelFromResourceSetupL,
+                CreateListModelFromResourceTestL,
+                Teardown )
+
+// Engine tests
+
+    EUNIT_TEST( "Engine update test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                EngineTestSetupL,
+                UpdateItemsTestL,
+                Teardown )
+
+    EUNIT_TEST( "Engine update test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                EngineTestSetupL,
+                UpdateItemsWithIdTestL,
+                Teardown )
+
+    EUNIT_TEST( "Engine update test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                EngineTestSetupL,
+                UpdateItemsWithOpaqueDataFolderTestL,
+                Teardown )
+
+// Sorting Style tests
+    EUNIT_TEST( "Sorting style from resource",
+                "",
+                "",
+                "FUNCTIONALITY",
+                SortingStyleResourceTestSetupL,
+                SortingStyleResourceTestL,
+                Teardown )
+
+    EUNIT_TEST( "Sorting style ordering test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                SortingStyleTestSetupL,
+                SortingStyleOrderingTestL,
+                Teardown )
+
+    EUNIT_TEST( "Sorting style data type test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                SortingStyleTestSetupL,
+                SortingStyleDataTypeTestL,
+                Teardown )
+
+    EUNIT_TEST( "Sorting style undefined item position test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                SortingStyleTestSetupL,
+                SortingStyleUndefinedItemPositionTestL,
+                Teardown )
+
+    EUNIT_TEST( "Sorting style field test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                SortingStyleTestSetupL,
+                SortingStyleFieldTestL,
+                Teardown )
+
+// List model tests
+    EUNIT_TEST( "List model refresh test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                ListModelSetupL,
+                RefreshTestL,
+                Teardown )
+
+    EUNIT_TEST( "List model sorting style test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                ListModelAllFileItemsSetupL,
+                SetSortingStyleTestL,
+                Teardown )
+
+    EUNIT_TEST( "List model custom sorter test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                ListModelAllFileItemsSetupL,
+                SetCustomSorterTestL,
+                Teardown )
+
+    EUNIT_TEST( "List model grouping test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                ListModelAllFileItemsSetupL,
+                GroupingTestL,
+                Teardown )
+
+    EUNIT_TEST( "List model post filter test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                ListModelAllFileItemsSetupL,
+                SetPostFilterTestL,
+                Teardown )
+
+    EUNIT_TEST( "List model wanted mime types test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                ListModelSetupL,
+                SetWantedMimeTypesTestL,
+                Teardown )
+
+    EUNIT_TEST( "List model wanted media types test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                ListModelSetupL,
+                SetWantedMediaTypesTestL,
+                Teardown )
+
+    EUNIT_TEST( "List model wanted media and mime types",
+                "",
+                "",
+                "FUNCTIONALITY",
+                ListModelSetupL,
+                SetWantedMediaAndMimeTypesTestL,
+                Teardown )
+
+    EUNIT_TEST( "List model multible sorters",
+                "",
+                "",
+                "FUNCTIONALITY",
+                MultibleSortingSetupL,
+                MultibleSortingTestL,
+                Teardown )
+
+    EUNIT_TEST( "List model multible sorters",
+                "",
+                "",
+                "FUNCTIONALITY",
+                MultibleSortingResourceSetupL,
+                MultibleSortingTestL,
+                Teardown )
+
+    EUNIT_TEST( "List model changed items",
+                "",
+                "",
+                "FUNCTIONALITY",
+                ListModelSetupL,
+                ModelItemsChangedTestL,
+                Teardown )
+
+
+// Modifiable item tests
+    EUNIT_TEST( "Modifiable item test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                ModifiableItemTestSetupL,
+                MIFieldTestL,
+                Teardown )
+
+// Item tests
+    EUNIT_TEST( "Item test",
+                "",
+                "",
+                "FUNCTIONALITY",
+                ItemTestSetupL,
+                ItemFieldTestL,
+                Teardown )
+
+
+EUNIT_END_TEST_TABLE
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/content_listing_framework_api/tsrc/src/T_ContentListingFramework.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,241 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+
+//  RESOURCE IDENTIFIER
+NAME    CLFT
+
+//  INCLUDES
+#include <eikon.rh>
+#include <PathConfiguration.hrh>
+#include <CLFContentListing.rh>
+#include <CLFContentListing.hrh>
+#include <CLFContentListingExtended.hrh>
+
+//  CONSTANTS
+//  MACROS
+
+//  RESOURCE DEFINITIONS
+// -----------------------------------------------------------------------------
+//
+// ?resource_name
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE RSS_SIGNATURE { signature = 0; }
+
+// -----------------------------------------------------------------------------
+//
+// ?resource_name
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE CLF_SORTING_STYLE r_sorting_style
+    {
+    ordering = ECLFOrderingDescending;
+    data_type = ECLFItemDataTypeDesC;
+    fields =
+        {
+        CLF_FIELD_ID { field_id = ECLFFieldIdFileName; },
+        CLF_FIELD_ID { field_id = ECLFFieldIdCollectionName; },
+        CLF_FIELD_ID { field_id = ECLFFieldIdMimeType; },
+        CLF_FIELD_ID { field_id = ECLFFieldIdArtist; }
+        };
+    }
+
+RESOURCE CLF_SORTING_STYLE r_sorting_style_empty
+    {
+    ordering = ECLFOrderingAscending;
+    data_type = ECLFItemDataTypeTInt32;
+    fields =
+        {
+        };
+    }
+
+RESOURCE CLF_SORTING_STYLE r_sorting_style_undefineditem
+    {
+    ordering = ECLFOrderingDescending;
+    data_type = ECLFItemDataTypeDesC;
+    undefined_item_position = ECLFSortingStyleUndefinedFirst;
+    fields =
+        {
+        CLF_FIELD_ID { field_id = ECLFFieldIdArtist; }
+        };
+    }
+
+RESOURCE CLF_LIST_MODEL r_list_model
+    {
+    mime_type_array = CLF_MIME_TYPE_ARRAY
+        {
+        mime_types =
+            {
+            LBUF { txt = "image/*"; }
+            };
+        };
+    media_type_array = CLF_MEDIA_TYPE_ARRAY
+        {
+        media_types =
+            {
+            CLF_MEDIA_TYPE { media_type = ECLFMediaTypeCollection; }
+            };
+        };
+    sorting_style = CLF_SORTING_STYLE
+        {
+        ordering = ECLFOrderingAscending;
+        data_type = ECLFItemDataTypeDesC;
+        fields =
+            {
+            CLF_FIELD_ID { field_id = ECLFFieldIdFileName; },
+            CLF_FIELD_ID { field_id = ECLFFieldIdCollectionName; },
+            CLF_FIELD_ID { field_id = ECLFFieldIdAlbum; }
+            };
+        };
+    }
+
+RESOURCE CLF_LIST_MODEL r_list_model_incorrect_version
+    {
+    version = 88;
+    mime_type_array = CLF_MIME_TYPE_ARRAY
+        {
+        mime_types =
+            {
+            };
+        };
+    media_type_array = CLF_MEDIA_TYPE_ARRAY
+        {
+        media_types =
+            {
+            };
+        };
+    sorting_style = CLF_SORTING_STYLE
+        {
+        ordering = ECLFOrderingAscending;
+        data_type = ECLFItemDataTypeDesC;
+        fields =
+            {
+            };
+        };
+    }
+
+
+RESOURCE CLF_MIME_TYPE_ARRAY r_mime_type_array
+    {
+    mime_types =
+        {
+        LBUF { txt = "image/*"; },
+        LBUF { txt = "audio/*"; }
+        };
+    }
+
+RESOURCE CLF_MIME_TYPE_ARRAY r_mime_type_array_empty
+    {
+    mime_types =
+        {
+        };
+    }
+
+RESOURCE CLF_MIME_TYPE_ARRAY r_mime_type_array_incorrect_version
+    {
+    version = 88;
+    mime_types =
+        {
+        };
+    }
+
+RESOURCE CLF_MEDIA_TYPE_ARRAY r_media_type_array
+    {
+    media_types =
+        {
+        CLF_MEDIA_TYPE { media_type = ECLFMediaTypeImage; },
+        CLF_MEDIA_TYPE { media_type = ECLFMediaTypeCollection; }
+        };
+    }
+
+RESOURCE CLF_MEDIA_TYPE_ARRAY r_media_type_array_empty
+    {
+    media_types =
+        {
+        };
+    }
+
+RESOURCE CLF_LIST_MODEL_V2 r_list_model_multible
+     {
+    mime_type_array = CLF_MIME_TYPE_ARRAY
+        {
+        mime_types =
+            {
+            };
+        };
+     media_type_array = CLF_MEDIA_TYPE_ARRAY
+         {
+         media_types =
+             {
+             };
+         };
+     sorting_style_array =
+        {
+        CLF_SORTING_STYLE
+            {
+            ordering = ECLFOrderingAscending;
+            data_type = ECLFItemDataTypeTInt32;
+            undefined_item_position = ECLFSortingStyleUndefinedFirst;
+            fields =
+                {
+                CLF_FIELD_ID { field_id = 0x80000001; }
+                };
+            },
+        CLF_SORTING_STYLE
+            {
+            ordering = ECLFOrderingDescending;
+            data_type = ECLFItemDataTypeTInt32;
+            undefined_item_position = ECLFSortingStyleUndefinedEnd;
+            fields =
+                {
+                CLF_FIELD_ID { field_id = 0x80000002; }
+                };
+            },
+        CLF_SORTING_STYLE
+            {
+            ordering = ECLFOrderingAscending;
+            data_type = ECLFItemDataTypeTInt32;
+            undefined_item_position = ECLFSortingStyleUndefinedEnd;
+            fields =
+                {
+                CLF_FIELD_ID { field_id = 0x80000003; },
+                CLF_FIELD_ID { field_id = 0x80000004; }
+                };
+            },
+        CLF_SORTING_STYLE
+            {
+            ordering = ECLFOrderingAscending;
+            data_type = ECLFItemDataTypeTInt32;
+            undefined_item_position = ECLFSortingStyleUndefinedFirst;
+            fields =
+                {
+                CLF_FIELD_ID { field_id = 0x80000005; }
+                };
+            }
+        };
+    }
+
+
+// End of File
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mds_pub/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+#ifdef RD_MDS_2_5
+#include "../content_listing_framework_api/group/bld.inf"
+#endif
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/bwincw/mdeclientu.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,297 @@
+EXPORTS
+	??0RMdEDataBuffer@@QAE@XZ @ 1 NONAME ; RMdEDataBuffer::RMdEDataBuffer(void)
+	??0TMdEObject@@QAE@XZ @ 2 NONAME ; TMdEObject::TMdEObject(void)
+	??0TMdEOrderRule@@QAE@ABVCMdEPropertyDef@@H@Z @ 3 NONAME ; TMdEOrderRule::TMdEOrderRule(class CMdEPropertyDef const &, int)
+	??0TMdEOrderRule@@QAE@W4TOrderRuleType@@H@Z @ 4 NONAME ; TMdEOrderRule::TMdEOrderRule(enum TOrderRuleType, int)
+	?AddBoolPropertyL@CMdEObject@@QAEAAVCMdEProperty@@AAVCMdEPropertyDef@@H@Z @ 5 NONAME ; class CMdEProperty & CMdEObject::AddBoolPropertyL(class CMdEPropertyDef &, int)
+	?AddEventConditionL@CMdELogicCondition@@QAEAAVCMdEEventCondition@@ABV?$TMdERange@VTTime@@@@@Z @ 6 NONAME ; class CMdEEventCondition & CMdELogicCondition::AddEventConditionL(class TMdERange<class TTime> const &)
+	?AddEventConditionL@CMdELogicCondition@@QAEAAVCMdEEventCondition@@ABV?$TMdERange@VTTime@@@@W4TEventConditionCompareMethod@@ABVTDesC16@@@Z @ 7 NONAME ; class CMdEEventCondition & CMdELogicCondition::AddEventConditionL(class TMdERange<class TTime> const &, enum TEventConditionCompareMethod, class TDesC16 const &)
+	?AddEventConditionL@CMdELogicCondition@@QAEAAVCMdEEventCondition@@ABVCMdEEventDef@@@Z @ 8 NONAME ; class CMdEEventCondition & CMdELogicCondition::AddEventConditionL(class CMdEEventDef const &)
+	?AddEventConditionL@CMdELogicCondition@@QAEAAVCMdEEventCondition@@K@Z @ 9 NONAME ; class CMdEEventCondition & CMdELogicCondition::AddEventConditionL(unsigned long)
+	?AddEventConditionL@CMdELogicCondition@@QAEAAVCMdEEventCondition@@W4TEventConditionCompareMethod@@ABVTDesC16@@@Z @ 10 NONAME ; class CMdEEventCondition & CMdELogicCondition::AddEventConditionL(enum TEventConditionCompareMethod, class TDesC16 const &)
+	?AddEventConditionL@CMdELogicCondition@@QAEAAVCMdEEventCondition@@XZ @ 11 NONAME ; class CMdEEventCondition & CMdELogicCondition::AddEventConditionL(void)
+	?AddFreeTextL@CMdEObject@@QAEXABVTDesC16@@@Z @ 12 NONAME ; void CMdEObject::AddFreeTextL(class TDesC16 const &)
+	?AddHarvestingPrioritizationObserver@CMdEHarvesterSession@@QAEXAAVTRequestStatus@@@Z @ 13 NONAME ; void CMdEHarvesterSession::AddHarvestingPrioritizationObserver(class TRequestStatus &)
+	?AddInt16PropertyL@CMdEObject@@QAEAAVCMdEProperty@@AAVCMdEPropertyDef@@F@Z @ 14 NONAME ; class CMdEProperty & CMdEObject::AddInt16PropertyL(class CMdEPropertyDef &, short)
+	?AddInt32PropertyL@CMdEObject@@QAEAAVCMdEProperty@@AAVCMdEPropertyDef@@J@Z @ 15 NONAME ; class CMdEProperty & CMdEObject::AddInt32PropertyL(class CMdEPropertyDef &, long)
+	?AddInt64PropertyL@CMdEObject@@QAEAAVCMdEProperty@@AAVCMdEPropertyDef@@_J@Z @ 16 NONAME ; class CMdEProperty & CMdEObject::AddInt64PropertyL(class CMdEPropertyDef &, long long)
+	?AddInt8PropertyL@CMdEObject@@QAEAAVCMdEProperty@@AAVCMdEPropertyDef@@C@Z @ 17 NONAME ; class CMdEProperty & CMdEObject::AddInt8PropertyL(class CMdEPropertyDef &, signed char)
+	?AddLogicConditionL@CMdELogicCondition@@QAEAAV1@W4TLogicConditionOperator@@@Z @ 18 NONAME ; class CMdELogicCondition & CMdELogicCondition::AddLogicConditionL(enum TLogicConditionOperator)
+	?AddMemoryCard@CMdEHarvesterSession@@QAEXK@Z @ 19 NONAME ; void CMdEHarvesterSession::AddMemoryCard(unsigned long)
+	?AddObjectConditionL@CMdELogicCondition@@QAEAAVCMdEObjectCondition@@ABV?$RArray@K@@@Z @ 20 NONAME ; class CMdEObjectCondition & CMdELogicCondition::AddObjectConditionL(class RArray<unsigned long> const &)
+	?AddObjectConditionL@CMdELogicCondition@@QAEAAVCMdEObjectCondition@@ABV?$TMdERange@I@@@Z @ 21 NONAME ; class CMdEObjectCondition & CMdELogicCondition::AddObjectConditionL(class TMdERange<unsigned int> const &)
+	?AddObjectConditionL@CMdELogicCondition@@QAEAAVCMdEObjectCondition@@ABVCMdEObjectDef@@@Z @ 22 NONAME ; class CMdEObjectCondition & CMdELogicCondition::AddObjectConditionL(class CMdEObjectDef const &)
+	?AddObjectConditionL@CMdELogicCondition@@QAEAAVCMdEObjectCondition@@K@Z @ 23 NONAME ; class CMdEObjectCondition & CMdELogicCondition::AddObjectConditionL(unsigned long)
+	?AddObjectConditionL@CMdELogicCondition@@QAEAAVCMdEObjectCondition@@W4TObjectConditionCompareMethod@@ABVTDesC16@@@Z @ 24 NONAME ; class CMdEObjectCondition & CMdELogicCondition::AddObjectConditionL(enum TObjectConditionCompareMethod, class TDesC16 const &)
+	?AddObjectConditionL@CMdELogicCondition@@QAEAAVCMdEObjectCondition@@_J0@Z @ 25 NONAME ; class CMdEObjectCondition & CMdELogicCondition::AddObjectConditionL(long long, long long)
+	?AddObserverL@CMdEQuery@@QAEXAAVMMdEQueryObserver@@@Z @ 26 NONAME ; void CMdEQuery::AddObserverL(class MMdEQueryObserver &)
+	?AddPropertyConditionL@CMdELogicCondition@@QAEAAV?$CMdERangePropertyCondition@$03H@@ABVCMdEPropertyDef@@ABV?$TMdERange@H@@@Z @ 27 NONAME ; class CMdERangePropertyCondition<4, int> & CMdELogicCondition::AddPropertyConditionL(class CMdEPropertyDef const &, class TMdERange<int> const &)
+	?AddPropertyConditionL@CMdELogicCondition@@QAEAAV?$CMdERangePropertyCondition@$04_J@@ABVCMdEPropertyDef@@ABV?$TMdERange@_J@@@Z @ 28 NONAME ; class CMdERangePropertyCondition<5, long long> & CMdELogicCondition::AddPropertyConditionL(class CMdEPropertyDef const &, class TMdERange<long long> const &)
+	?AddPropertyConditionL@CMdELogicCondition@@QAEAAV?$CMdERangePropertyCondition@$05I@@ABVCMdEPropertyDef@@ABV?$TMdERange@I@@@Z @ 29 NONAME ; class CMdERangePropertyCondition<6, unsigned int> & CMdELogicCondition::AddPropertyConditionL(class CMdEPropertyDef const &, class TMdERange<unsigned int> const &)
+	?AddPropertyConditionL@CMdELogicCondition@@QAEAAV?$CMdERangePropertyCondition@$06N@@ABVCMdEPropertyDef@@ABV?$TMdERange@N@@@Z @ 30 NONAME ; class CMdERangePropertyCondition<7, double> & CMdELogicCondition::AddPropertyConditionL(class CMdEPropertyDef const &, class TMdERange<double> const &)
+	?AddPropertyConditionL@CMdELogicCondition@@QAEAAV?$CMdERangePropertyCondition@$07VTTime@@@@ABVCMdEPropertyDef@@ABV?$TMdERange@VTTime@@@@@Z @ 31 NONAME ; class CMdERangePropertyCondition<8, class TTime> & CMdELogicCondition::AddPropertyConditionL(class CMdEPropertyDef const &, class TMdERange<class TTime> const &)
+	?AddPropertyConditionL@CMdELogicCondition@@QAEAAVCMdEBoolPropertyCondition@@ABVCMdEPropertyDef@@H@Z @ 32 NONAME ; class CMdEBoolPropertyCondition & CMdELogicCondition::AddPropertyConditionL(class CMdEPropertyDef const &, int)
+	?AddPropertyConditionL@CMdELogicCondition@@QAEAAVCMdEPropertyCondition@@ABVCMdEPropertyDef@@@Z @ 33 NONAME ; class CMdEPropertyCondition & CMdELogicCondition::AddPropertyConditionL(class CMdEPropertyDef const &)
+	?AddPropertyConditionL@CMdELogicCondition@@QAEAAVCMdETextPropertyCondition@@ABVCMdEPropertyDef@@W4TTextPropertyConditionCompareMethod@@ABVTDesC16@@@Z @ 34 NONAME ; class CMdETextPropertyCondition & CMdELogicCondition::AddPropertyConditionL(class CMdEPropertyDef const &, enum TTextPropertyConditionCompareMethod, class TDesC16 const &)
+	?AddPropertyFilterL@CMdEObjectQuery@@QAEXPBVCMdEPropertyDef@@@Z @ 35 NONAME ; void CMdEObjectQuery::AddPropertyFilterL(class CMdEPropertyDef const *)
+	?AddReal32PropertyL@CMdEObject@@QAEAAVCMdEProperty@@AAVCMdEPropertyDef@@M@Z @ 36 NONAME ; class CMdEProperty & CMdEObject::AddReal32PropertyL(class CMdEPropertyDef &, float)
+	?AddReal64PropertyL@CMdEObject@@QAEAAVCMdEProperty@@AAVCMdEPropertyDef@@N@Z @ 37 NONAME ; class CMdEProperty & CMdEObject::AddReal64PropertyL(class CMdEPropertyDef &, double)
+	?AddRelationConditionL@CMdELogicCondition@@QAEAAVCMdERelationCondition@@AAV?$RArray@K@@W4TRelationConditionSide@@@Z @ 38 NONAME ; class CMdERelationCondition & CMdELogicCondition::AddRelationConditionL(class RArray<unsigned long> &, enum TRelationConditionSide)
+	?AddRelationConditionL@CMdELogicCondition@@QAEAAVCMdERelationCondition@@ABVCMdERelationDef@@ABV?$TMdERange@H@@W4TRelationConditionSide@@@Z @ 39 NONAME ; class CMdERelationCondition & CMdELogicCondition::AddRelationConditionL(class CMdERelationDef const &, class TMdERange<int> const &, enum TRelationConditionSide)
+	?AddRelationConditionL@CMdELogicCondition@@QAEAAVCMdERelationCondition@@ABVCMdERelationDef@@W4TRelationConditionSide@@@Z @ 40 NONAME ; class CMdERelationCondition & CMdELogicCondition::AddRelationConditionL(class CMdERelationDef const &, enum TRelationConditionSide)
+	?AddRelationConditionL@CMdELogicCondition@@QAEAAVCMdERelationCondition@@KW4TRelationConditionSide@@@Z @ 41 NONAME ; class CMdERelationCondition & CMdELogicCondition::AddRelationConditionL(unsigned long, enum TRelationConditionSide)
+	?AddRelationConditionL@CMdELogicCondition@@QAEAAVCMdERelationCondition@@W4TRelationConditionSide@@@Z @ 42 NONAME ; class CMdERelationCondition & CMdELogicCondition::AddRelationConditionL(enum TRelationConditionSide)
+	?AddTextPropertyL@CMdEObject@@QAEAAVCMdEProperty@@AAVCMdEPropertyDef@@ABVTDesC16@@@Z @ 43 NONAME ; class CMdEProperty & CMdEObject::AddTextPropertyL(class CMdEPropertyDef &, class TDesC16 const &)
+	?AddTimePropertyL@CMdEObject@@QAEAAVCMdEProperty@@AAVCMdEPropertyDef@@VTTime@@@Z @ 44 NONAME ; class CMdEProperty & CMdEObject::AddTimePropertyL(class CMdEPropertyDef &, class TTime)
+	?AddUint16PropertyL@CMdEObject@@QAEAAVCMdEProperty@@AAVCMdEPropertyDef@@G@Z @ 45 NONAME ; class CMdEProperty & CMdEObject::AddUint16PropertyL(class CMdEPropertyDef &, unsigned short)
+	?AddUint32PropertyL@CMdEObject@@QAEAAVCMdEProperty@@AAVCMdEPropertyDef@@K@Z @ 46 NONAME ; class CMdEProperty & CMdEObject::AddUint32PropertyL(class CMdEPropertyDef &, unsigned long)
+	?AddUint8PropertyL@CMdEObject@@QAEAAVCMdEProperty@@AAVCMdEPropertyDef@@E@Z @ 47 NONAME ; class CMdEProperty & CMdEObject::AddUint8PropertyL(class CMdEPropertyDef &, unsigned char)
+	?AppendOrderRuleL@CMdEQuery@@QAEXABVTMdEOrderRule@@@Z @ 48 NONAME ; void CMdEQuery::AppendOrderRuleL(class TMdEOrderRule const &)
+	?Ascending@TMdEOrderRule@@QBEHXZ @ 49 NONAME ; int TMdEOrderRule::Ascending(void) const
+	?AutoLockL@CMdEHarvesterSession@@QAEXAAV?$RPointerArray@VCMdEObject@@@@@Z @ 50 NONAME ; void CMdEHarvesterSession::AutoLockL(class RPointerArray<class CMdEObject> &)
+	?BelongsToSession@CMdEItem@@QBEHXZ @ 51 NONAME ; int CMdEItem::BelongsToSession(void) const
+	?BoolValueL@CMdEProperty@@QBEHXZ @ 52 NONAME ; int CMdEProperty::BoolValueL(void) const
+	?Cancel@CMdEQuery@@QAEXXZ @ 53 NONAME ; void CMdEQuery::Cancel(void)
+	?CancelHarvestingPrioritizationObserver@CMdEHarvesterSession@@QAEHXZ @ 54 NONAME ; int CMdEHarvesterSession::CancelHarvestingPrioritizationObserver(void)
+	?CaseSensitive@TMdEOrderRule@@QAEHXZ @ 55 NONAME ; int TMdEOrderRule::CaseSensitive(void)
+	?ChangePath@CMdEHarvesterSession@@QAEXABVTDesC16@@0AAVTRequestStatus@@@Z @ 56 NONAME ; void CMdEHarvesterSession::ChangePath(class TDesC16 const &, class TDesC16 const &, class TRequestStatus &)
+	?CheckMemoryCard@CMdEHarvesterSession@@QAEHKAAH@Z @ 57 NONAME ; int CMdEHarvesterSession::CheckMemoryCard(unsigned long, int &)
+	?Close@RMdEDataBuffer@@QAEXXZ @ 58 NONAME ; void RMdEDataBuffer::Close(void)
+	?Compare@CMdEEventDef@@QBEHABV1@@Z @ 59 NONAME ; int CMdEEventDef::Compare(class CMdEEventDef const &) const
+	?Compare@CMdENamespaceDef@@QBEHABV1@@Z @ 60 NONAME ; int CMdENamespaceDef::Compare(class CMdENamespaceDef const &) const
+	?Compare@CMdEObjectDef@@QBEHABV1@@Z @ 61 NONAME ; int CMdEObjectDef::Compare(class CMdEObjectDef const &) const
+	?Compare@CMdEPropertyDef@@QBEHABV1@@Z @ 62 NONAME ; int CMdEPropertyDef::Compare(class CMdEPropertyDef const &) const
+	?Compare@CMdERelationDef@@QBEHABV1@@Z @ 63 NONAME ; int CMdERelationDef::Compare(class CMdERelationDef const &) const
+	?CompareMethod@CMdEObjectCondition@@QBE?AW4TObjectConditionCompareMethod@@XZ @ 64 NONAME ; enum TObjectConditionCompareMethod CMdEObjectCondition::CompareMethod(void) const
+	?Condition@CMdELogicCondition@@QBEAAVCMdECondition@@H@Z @ 65 NONAME ; class CMdECondition & CMdELogicCondition::Condition(int) const
+	?Conditions@CMdEQuery@@QBEAAVCMdELogicCondition@@XZ @ 66 NONAME ; class CMdELogicCondition & CMdEQuery::Conditions(void) const
+	?Confidential@CMdEObject@@QBEHXZ @ 67 NONAME ; int CMdEObject::Confidential(void) const
+	?Confidential@TMdEObject@@QBEHXZ @ 68 NONAME ; int TMdEObject::Confidential(void) const
+	?ConfidentialityLevel@CMdEObjectCondition@@QBE?AW4TObjectConditionConfidentialityLevel@@XZ @ 69 NONAME ; enum TObjectConditionConfidentialityLevel CMdEObjectCondition::ConfidentialityLevel(void) const
+	?Count@CMdELogicCondition@@QBEHXZ @ 70 NONAME ; int CMdELogicCondition::Count(void) const
+	?Count@CMdEQuery@@QBEHXZ @ 71 NONAME ; int CMdEQuery::Count(void) const
+	?Def@CMdEEvent@@QBEAAVCMdEEventDef@@XZ @ 72 NONAME ; class CMdEEventDef & CMdEEvent::Def(void) const
+	?Def@CMdEObject@@QBEAAVCMdEObjectDef@@XZ @ 73 NONAME ; class CMdEObjectDef & CMdEObject::Def(void) const
+	?Def@CMdEProperty@@QBEABVCMdEPropertyDef@@XZ @ 74 NONAME ; class CMdEPropertyDef const & CMdEProperty::Def(void) const
+	?Def@CMdERelation@@QBEAAVCMdERelationDef@@XZ @ 75 NONAME ; class CMdERelationDef & CMdERelation::Def(void) const
+	?DefL@TMdEObject@@QBEABVCMdEObjectDef@@XZ @ 76 NONAME ; class CMdEObjectDef const & TMdEObject::DefL(void) const
+	?DefL@TMdERelation@@QBEAAVCMdERelationDef@@XZ @ 77 NONAME ; class CMdERelationDef & TMdERelation::DefL(void) const
+	?Error@CMdEQuery@@QBEHXZ @ 78 NONAME ; int CMdEQuery::Error(void) const
+	?EventDef@CMdEEventCondition@@QBEPBVCMdEEventDef@@XZ @ 79 NONAME ; class CMdEEventDef const * CMdEEventCondition::EventDef(void) const
+	?EventDefCount@CMdENamespaceDef@@QBEHXZ @ 80 NONAME ; int CMdENamespaceDef::EventDefCount(void) const
+	?EventDefL@CMdENamespaceDef@@QAEAAVCMdEEventDef@@H@Z @ 81 NONAME ; class CMdEEventDef & CMdENamespaceDef::EventDefL(int)
+	?EventId@CMdEEventCondition@@QBEKXZ @ 82 NONAME ; unsigned long CMdEEventCondition::EventId(void) const
+	?FindL@CMdEQuery@@QAEXII@Z @ 83 NONAME ; void CMdEQuery::FindL(unsigned int, unsigned int)
+	?FreeText@CMdEObject@@QBE?AVTPtrC16@@H@Z @ 84 NONAME ; class TPtrC16 CMdEObject::FreeText(int) const
+	?FreeTextCount@CMdEObject@@QBEHXZ @ 85 NONAME ; int CMdEObject::FreeTextCount(void) const
+	?FreeTextIndex@CMdEObject@@QBEHABVTDesC16@@@Z @ 86 NONAME ; int CMdEObject::FreeTextIndex(class TDesC16 const &) const
+	?GetEventDefL@CMdENamespaceDef@@QAEAAVCMdEEventDef@@ABVTDesC16@@@Z @ 87 NONAME ; class CMdEEventDef & CMdENamespaceDef::GetEventDefL(class TDesC16 const &)
+	?GetEventDefL@CMdENamespaceDef@@QAEPAVCMdEEventDef@@K@Z @ 88 NONAME ABSENT ; class CMdEEventDef * CMdENamespaceDef::GetEventDefL(unsigned long)
+	?GetMediaL@CMdEHarvesterSession@@QAEHKAAVTChar@@AAH@Z @ 89 NONAME ; int CMdEHarvesterSession::GetMediaL(unsigned long, class TChar &, int &)
+	?GetMemoryCard@CMdEHarvesterSession@@QAEHAAK@Z @ 90 NONAME ; int CMdEHarvesterSession::GetMemoryCard(unsigned long &)
+	?GetObjectDefL@CMdENamespaceDef@@QAEAAVCMdEObjectDef@@ABVTDesC16@@@Z @ 91 NONAME ; class CMdEObjectDef & CMdENamespaceDef::GetObjectDefL(class TDesC16 const &)
+	?GetObjectL@CMdESessionImpl@@UAEPAVCMdEObject@@ABVTDesC16@@PAVCMdENamespaceDef@@@Z @ 92 NONAME ; class CMdEObject * CMdESessionImpl::GetObjectL(class TDesC16 const &, class CMdENamespaceDef *)
+	?GetPending@CMdEHarvesterSession@@QAEPAVTGetPendingPgckWrapper@@PBVCMdEObjectDef@@AAHAAVCMdCSerializationBuffer@@AAVTRequestStatus@@@Z @ 93 NONAME ABSENT ; class TGetPendingPgckWrapper * CMdEHarvesterSession::GetPending(class CMdEObjectDef const *, int &, class CMdCSerializationBuffer &, class TRequestStatus &)
+	?GetPendingCount@CMdEHarvesterSession@@QAEPAVTGetPendingPgckWrapper@@PBVCMdEObjectDef@@AAVTRequestStatus@@@Z @ 94 NONAME ABSENT ; class TGetPendingPgckWrapper * CMdEHarvesterSession::GetPendingCount(class CMdEObjectDef const *, class TRequestStatus &)
+	?GetPresentMediasL@CMdEHarvesterSession@@QAEXAAV?$RArray@UTMdEMediaInfo@@@@@Z @ 95 NONAME ; void CMdEHarvesterSession::GetPresentMediasL(class RArray<struct TMdEMediaInfo> &)
+	?GetPropertyDefL@CMdEObjectDef@@QAEAAVCMdEPropertyDef@@ABVTDesC16@@@Z @ 96 NONAME ; class CMdEPropertyDef & CMdEObjectDef::GetPropertyDefL(class TDesC16 const &)
+	?GetRelationDefL@CMdENamespaceDef@@QAEAAVCMdERelationDef@@ABVTDesC16@@@Z @ 97 NONAME ; class CMdERelationDef & CMdENamespaceDef::GetRelationDefL(class TDesC16 const &)
+	?GetRelationDefL@CMdENamespaceDef@@QAEPAVCMdERelationDef@@K@Z @ 98 NONAME ABSENT ; class CMdERelationDef * CMdENamespaceDef::GetRelationDefL(unsigned long)
+	?Guid@CMdEObject@@QBEXAA_J0@Z @ 99 NONAME ; void CMdEObject::Guid(long long &, long long &) const
+	?Guid@CMdERelation@@QBEXAA_J0@Z @ 100 NONAME ; void CMdERelation::Guid(long long &, long long &) const
+	?Guid@CMdERelationCondition@@QBEHAA_J0@Z @ 101 NONAME ; int CMdERelationCondition::Guid(long long &, long long &) const
+	?HarvestingPrioritizationUriCountL@CMdEHarvesterSession@@QAEHXZ @ 102 NONAME ; int CMdEHarvesterSession::HarvestingPrioritizationUriCountL(void)
+	?HarvestingPrioritizationUriL@CMdEHarvesterSession@@QAEPAVHBufC16@@H@Z @ 103 NONAME ; class HBufC16 * CMdEHarvesterSession::HarvestingPrioritizationUriL(int)
+	?Id@CMdEItem@@QBEKXZ @ 104 NONAME ; unsigned long CMdEItem::Id(void) const
+	?Id@TMdEObject@@QBEKXZ @ 105 NONAME ; unsigned long TMdEObject::Id(void) const
+	?Id@TMdERelation@@QBEKXZ @ 106 NONAME ; unsigned long TMdERelation::Id(void) const
+	?InDatabase@CMdEItem@@QBEHXZ @ 107 NONAME ; int CMdEItem::InDatabase(void) const
+	?InsertOrderRuleL@CMdEQuery@@QAEXABVTMdEOrderRule@@H@Z @ 108 NONAME ; void CMdEQuery::InsertOrderRuleL(class TMdEOrderRule const &, int)
+	?Int16ValueL@CMdEProperty@@QBEFXZ @ 109 NONAME ; short CMdEProperty::Int16ValueL(void) const
+	?Int32ValueL@CMdEProperty@@QBEJXZ @ 110 NONAME ; long CMdEProperty::Int32ValueL(void) const
+	?Int64ValueL@CMdEProperty@@QBE_JXZ @ 111 NONAME ; long long CMdEProperty::Int64ValueL(void) const
+	?Int8ValueL@CMdEProperty@@QBECXZ @ 112 NONAME ; signed char CMdEProperty::Int8ValueL(void) const
+	?IsComplete@CMdEQuery@@QBEHXZ @ 113 NONAME ; int CMdEQuery::IsComplete(void) const
+	?LastModifiedDate@CMdERelation@@QBE?AVTTime@@XZ @ 114 NONAME ; class TTime CMdERelation::LastModifiedDate(void) const
+	?LastModifiedDateRange@CMdERelationCondition@@QBEHAAV?$TMdERange@VTTime@@@@@Z @ 115 NONAME ; int CMdERelationCondition::LastModifiedDateRange(class TMdERange<class TTime> &) const
+	?LeftL@CMdERelationCondition@@QAEAAVCMdELogicCondition@@XZ @ 116 NONAME ; class CMdELogicCondition & CMdERelationCondition::LeftL(void)
+	?LeftObjectId@CMdERelation@@QBEKXZ @ 117 NONAME ; unsigned long CMdERelation::LeftObjectId(void) const
+	?LeftObjectId@TMdERelation@@QBEKXZ @ 118 NONAME ; unsigned long TMdERelation::LeftObjectId(void) const
+	?Locked@CMdECondition@@QBEHXZ @ 119 NONAME ; int CMdECondition::Locked(void) const
+	?Mandatory@CMdEPropertyDef@@QBEHXZ @ 120 NONAME ; int CMdEPropertyDef::Mandatory(void) const
+	?MaxInt32ValueL@CMdEPropertyDef@@QBEJXZ @ 121 NONAME ; long CMdEPropertyDef::MaxInt32ValueL(void) const
+	?MaxInt64ValueL@CMdEPropertyDef@@QBE_JXZ @ 122 NONAME ; long long CMdEPropertyDef::MaxInt64ValueL(void) const
+	?MaxRealValueL@CMdEPropertyDef@@QBENXZ @ 123 NONAME ; double CMdEPropertyDef::MaxRealValueL(void) const
+	?MaxTextLengthL@CMdEPropertyDef@@QBEHXZ @ 124 NONAME ; int CMdEPropertyDef::MaxTextLengthL(void) const
+	?MaxTimeValueL@CMdEPropertyDef@@QBE?AVTTime@@XZ @ 125 NONAME ; class TTime CMdEPropertyDef::MaxTimeValueL(void) const
+	?MaxUint32ValueL@CMdEPropertyDef@@QBEKXZ @ 126 NONAME ; unsigned long CMdEPropertyDef::MaxUint32ValueL(void) const
+	?MediaId@CMdEObject@@QBEKXZ @ 127 NONAME ; unsigned long CMdEObject::MediaId(void) const
+	?MinInt32ValueL@CMdEPropertyDef@@QBEJXZ @ 128 NONAME ; long CMdEPropertyDef::MinInt32ValueL(void) const
+	?MinInt64ValueL@CMdEPropertyDef@@QBE_JXZ @ 129 NONAME ; long long CMdEPropertyDef::MinInt64ValueL(void) const
+	?MinRealValueL@CMdEPropertyDef@@QBENXZ @ 130 NONAME ; double CMdEPropertyDef::MinRealValueL(void) const
+	?MinTextLengthL@CMdEPropertyDef@@QBEHXZ @ 131 NONAME ; int CMdEPropertyDef::MinTextLengthL(void) const
+	?MinTimeValueL@CMdEPropertyDef@@QBE?AVTTime@@XZ @ 132 NONAME ; class TTime CMdEPropertyDef::MinTimeValueL(void) const
+	?MinUint32ValueL@CMdEPropertyDef@@QBEKXZ @ 133 NONAME ; unsigned long CMdEPropertyDef::MinUint32ValueL(void) const
+	?Modified@CMdEProperty@@QBEHXZ @ 134 NONAME ; int CMdEProperty::Modified(void) const
+	?MovePropertiesL@CMdEObject@@QAEXAAV1@@Z @ 135 NONAME ; void CMdEObject::MovePropertiesL(class CMdEObject &)
+	?Name@CMdEEventDef@@QBEABVTDesC16@@XZ @ 136 NONAME ; class TDesC16 const & CMdEEventDef::Name(void) const
+	?Name@CMdENamespaceDef@@QBEABVTDesC16@@XZ @ 137 NONAME ; class TDesC16 const & CMdENamespaceDef::Name(void) const
+	?Name@CMdEObjectDef@@QBEABVTDesC16@@XZ @ 138 NONAME ; class TDesC16 const & CMdEObjectDef::Name(void) const
+	?Name@CMdEPropertyDef@@QBEABVTDesC16@@XZ @ 139 NONAME ; class TDesC16 const & CMdEPropertyDef::Name(void) const
+	?Name@CMdERelationDef@@QBEABVTDesC16@@XZ @ 140 NONAME ; class TDesC16 const & CMdERelationDef::Name(void) const
+	?NamespaceDef@CMdEEventDef@@QBEAAVCMdENamespaceDef@@XZ @ 141 NONAME ; class CMdENamespaceDef & CMdEEventDef::NamespaceDef(void) const
+	?NamespaceDef@CMdEObjectDef@@QBEAAVCMdENamespaceDef@@XZ @ 142 NONAME ; class CMdENamespaceDef & CMdEObjectDef::NamespaceDef(void) const
+	?NamespaceDef@CMdEPropertyDef@@QBEAAVCMdENamespaceDef@@XZ @ 143 NONAME ; class CMdENamespaceDef & CMdEPropertyDef::NamespaceDef(void) const
+	?NamespaceDef@CMdEQuery@@QBEAAVCMdENamespaceDef@@XZ @ 144 NONAME ; class CMdENamespaceDef & CMdEQuery::NamespaceDef(void) const
+	?NamespaceDef@CMdERelationDef@@QBEAAVCMdENamespaceDef@@XZ @ 145 NONAME ; class CMdENamespaceDef & CMdERelationDef::NamespaceDef(void) const
+	?Negate@CMdECondition@@QBEHXZ @ 146 NONAME ; int CMdECondition::Negate(void) const
+	?NewL@CMdEHarvesterSession@@SAPAV1@AAVCMdESession@@@Z @ 147 NONAME ; class CMdEHarvesterSession * CMdEHarvesterSession::NewL(class CMdESession &)
+	?NewL@CMdELogicCondition@@SAPAV1@W4TLogicConditionOperator@@@Z @ 148 NONAME ; class CMdELogicCondition * CMdELogicCondition::NewL(enum TLogicConditionOperator)
+	?NewL@CMdESession@@SAPAV1@AAVMMdESessionObserver@@@Z @ 149 NONAME ; class CMdESession * CMdESession::NewL(class MMdESessionObserver &)
+	?NewLC@CMdEHarvesterSession@@SAPAV1@AAVCMdESession@@@Z @ 150 NONAME ; class CMdEHarvesterSession * CMdEHarvesterSession::NewLC(class CMdESession &)
+	?NewLC@CMdELogicCondition@@SAPAV1@W4TLogicConditionOperator@@@Z @ 151 NONAME ; class CMdELogicCondition * CMdELogicCondition::NewLC(enum TLogicConditionOperator)
+	?NewLC@CMdESession@@SAPAV1@AAVMMdESessionObserver@@@Z @ 152 NONAME ; class CMdESession * CMdESession::NewLC(class MMdESessionObserver &)
+	?NotPlaceholder@CMdEObjectCondition@@QBEHXZ @ 153 NONAME ; int CMdEObjectCondition::NotPlaceholder(void) const
+	?NotPresent@CMdEObjectCondition@@QBEHXZ @ 154 NONAME ; int CMdEObjectCondition::NotPresent(void) const
+	?NotPresent@TMdEObject@@QBEHXZ @ 155 NONAME ; int TMdEObject::NotPresent(void) const
+	?Object@CMdEProperty@@QBEABVCMdEObject@@XZ @ 156 NONAME ; class CMdEObject const & CMdEProperty::Object(void) const
+	?ObjectConditionsL@CMdEEventCondition@@QAEAAVCMdELogicCondition@@XZ @ 157 NONAME ; class CMdELogicCondition & CMdEEventCondition::ObjectConditionsL(void)
+	?ObjectDef@CMdEObjectCondition@@QBEPBVCMdEObjectDef@@XZ @ 158 NONAME ; class CMdEObjectDef const * CMdEObjectCondition::ObjectDef(void) const
+	?ObjectDef@CMdEObjectQuery@@QBEAAVCMdEObjectDef@@XZ @ 159 NONAME ; class CMdEObjectDef & CMdEObjectQuery::ObjectDef(void) const
+	?ObjectDef@CMdEPropertyDef@@QBEAAVCMdEObjectDef@@XZ @ 160 NONAME ; class CMdEObjectDef & CMdEPropertyDef::ObjectDef(void) const
+	?ObjectDefCount@CMdENamespaceDef@@QBEHXZ @ 161 NONAME ; int CMdENamespaceDef::ObjectDefCount(void) const
+	?ObjectDefL@CMdENamespaceDef@@QAEAAVCMdEObjectDef@@H@Z @ 162 NONAME ; class CMdEObjectDef & CMdENamespaceDef::ObjectDefL(int)
+	?ObjectId@CMdEEvent@@QBEKXZ @ 163 NONAME ; unsigned long CMdEEvent::ObjectId(void) const
+	?ObjectId@CMdEObjectCondition@@QBEKXZ @ 164 NONAME ; unsigned long CMdEObjectCondition::ObjectId(void) const
+	?ObjectIds@CMdEObjectCondition@@QBEPBV?$RArray@K@@XZ @ 165 NONAME ; class RArray<unsigned long> const * CMdEObjectCondition::ObjectIds(void) const
+	?OpenForModifications@CMdEObject@@QBEHXZ @ 166 NONAME ; int CMdEObject::OpenForModifications(void) const
+	?Operator@CMdELogicCondition@@QBE?AW4TLogicConditionOperator@@XZ @ 167 NONAME ; enum TLogicConditionOperator CMdELogicCondition::Operator(void) const
+	?OrderRule@CMdEQuery@@QBE?AVTMdEOrderRule@@H@Z @ 168 NONAME ; class TMdEOrderRule CMdEQuery::OrderRule(int) const
+	?OrderRuleCount@CMdEQuery@@QBEHXZ @ 169 NONAME ; int CMdEQuery::OrderRuleCount(void) const
+	?OwnsResult@CMdEQuery@@QAEHH@Z @ 170 NONAME ; int CMdEQuery::OwnsResult(int)
+	?Parameter@CMdERelation@@QBEJXZ @ 171 NONAME ; long CMdERelation::Parameter(void) const
+	?ParameterRange@CMdERelationCondition@@QBEPBV?$TMdERange@H@@XZ @ 172 NONAME ; class TMdERange<int> const * CMdERelationCondition::ParameterRange(void) const
+	?ParentL@CMdEObjectDef@@QAEPAV1@XZ @ 173 NONAME ; class CMdEObjectDef * CMdEObjectDef::ParentL(void)
+	?Participant@CMdEEvent@@QBEPBVTDesC16@@XZ @ 174 NONAME ; class TDesC16 const * CMdEEvent::Participant(void) const
+	?ParticipantObjectConditionsL@CMdEEventCondition@@QAEAAVCMdELogicCondition@@XZ @ 175 NONAME ; class CMdELogicCondition & CMdEEventCondition::ParticipantObjectConditionsL(void)
+	?ParticipantURI@CMdEEventCondition@@QBEPBVTDesC16@@XZ @ 176 NONAME ; class TDesC16 const * CMdEEventCondition::ParticipantURI(void) const
+	?Placeholder@CMdEObject@@QBEHXZ @ 177 NONAME ; int CMdEObject::Placeholder(void) const
+	?Placeholder@TMdEObject@@QBEHXZ @ 178 NONAME ; int TMdEObject::Placeholder(void) const
+	?Property@CMdEObject@@QBEHABVCMdEPropertyDef@@AAPAVCMdEProperty@@H@Z @ 179 NONAME ; int CMdEObject::Property(class CMdEPropertyDef const &, class CMdEProperty * &, int) const
+	?PropertyCount@CMdEObject@@QBEHABVCMdEPropertyDef@@@Z @ 180 NONAME ; int CMdEObject::PropertyCount(class CMdEPropertyDef const &) const
+	?PropertyCount@CMdEObject@@QBEHXZ @ 181 NONAME ; int CMdEObject::PropertyCount(void) const
+	?PropertyDef@CMdEPropertyCondition@@QBEABVCMdEPropertyDef@@XZ @ 182 NONAME ; class CMdEPropertyDef const & CMdEPropertyCondition::PropertyDef(void) const
+	?PropertyDef@TMdEOrderRule@@QBEPBVCMdEPropertyDef@@XZ @ 183 NONAME ; class CMdEPropertyDef const * TMdEOrderRule::PropertyDef(void) const
+	?PropertyDefCount@CMdEObjectDef@@QBEHXZ @ 184 NONAME ; int CMdEObjectDef::PropertyDefCount(void) const
+	?PropertyDefL@CMdEObjectDef@@QAEAAVCMdEPropertyDef@@H@Z @ 185 NONAME ; class CMdEPropertyDef & CMdEObjectDef::PropertyDefL(int)
+	?PropertyL@CMdEObject@@QBEAAVCMdEProperty@@H@Z @ 186 NONAME ; class CMdEProperty & CMdEObject::PropertyL(int) const
+	?PropertyType@CMdEPropertyDef@@QBE?AW4TPropertyType@@XZ @ 187 NONAME ; enum TPropertyType CMdEPropertyDef::PropertyType(void) const
+	?ReadOnly@CMdENamespaceDef@@QBEHXZ @ 188 NONAME ; int CMdENamespaceDef::ReadOnly(void) const
+	?ReadOnly@CMdEPropertyDef@@QBEHXZ @ 189 NONAME ; int CMdEPropertyDef::ReadOnly(void) const
+	?Real32ValueL@CMdEProperty@@QBEMXZ @ 190 NONAME ; float CMdEProperty::Real32ValueL(void) const
+	?Real64ValueL@CMdEProperty@@QBENXZ @ 191 NONAME ; double CMdEProperty::Real64ValueL(void) const
+	?RelationDef@CMdERelationCondition@@QBEPBVCMdERelationDef@@XZ @ 192 NONAME ; class CMdERelationDef const * CMdERelationCondition::RelationDef(void) const
+	?RelationDefCount@CMdENamespaceDef@@QBEHXZ @ 193 NONAME ; int CMdENamespaceDef::RelationDefCount(void) const
+	?RelationDefL@CMdENamespaceDef@@QAEAAVCMdERelationDef@@H@Z @ 194 NONAME ; class CMdERelationDef & CMdENamespaceDef::RelationDefL(int)
+	?RelationId@CMdERelationCondition@@QBEKXZ @ 195 NONAME ; unsigned long CMdERelationCondition::RelationId(void) const
+	?RelationIds@CMdERelationCondition@@QBEPBV?$RArray@K@@XZ @ 196 NONAME ; class RArray<unsigned long> const * CMdERelationCondition::RelationIds(void) const
+	?Remove@CMdELogicCondition@@QAEXH@Z @ 197 NONAME ; void CMdELogicCondition::Remove(int)
+	?RemoveFilesNotPresent@CMdEHarvesterSession@@QAEXK@Z @ 198 NONAME ; void CMdEHarvesterSession::RemoveFilesNotPresent(unsigned long)
+	?RemoveFilesNotPresent@CMdEHarvesterSession@@QAEXKH@Z @ 199 NONAME ; void CMdEHarvesterSession::RemoveFilesNotPresent(unsigned long, int)
+	?RemoveFreeText@CMdEObject@@QAEXH@Z @ 200 NONAME ; void CMdEObject::RemoveFreeText(int)
+	?RemoveObserver@CMdEQuery@@QAEXAAVMMdEQueryObserver@@@Z @ 201 NONAME ; void CMdEQuery::RemoveObserver(class MMdEQueryObserver &)
+	?RemoveOrderRule@CMdEQuery@@QAEXH@Z @ 202 NONAME ; void CMdEQuery::RemoveOrderRule(int)
+	?RemoveProperty@CMdEObject@@QAEXH@Z @ 203 NONAME ; void CMdEObject::RemoveProperty(int)
+	?Removed@TMdEObject@@QBEHXZ @ 204 NONAME ; int TMdEObject::Removed(void) const
+	?ResetDBL@CMdEHarvesterSession@@QAEXXZ @ 205 NONAME ; void CMdEHarvesterSession::ResetDBL(void)
+	?ResetPending@CMdEHarvesterSession@@QAEXABV?$RArray@K@@@Z @ 206 NONAME ABSENT ; void CMdEHarvesterSession::ResetPending(class RArray<unsigned long> const &)
+	?ResetPropertyFilter@CMdEObjectQuery@@QAEXXZ @ 207 NONAME ; void CMdEObjectQuery::ResetPropertyFilter(void)
+	?Result@CMdEEventQuery@@QBEAAVCMdEEvent@@H@Z @ 208 NONAME ; class CMdEEvent & CMdEEventQuery::Result(int) const
+	?Result@CMdEObjectQuery@@QBEAAVCMdEObject@@H@Z @ 209 NONAME ; class CMdEObject & CMdEObjectQuery::Result(int) const
+	?Result@CMdERelationQuery@@QBEAAVCMdERelation@@H@Z @ 210 NONAME ; class CMdERelation & CMdERelationQuery::Result(int) const
+	?ResultDistinctValue@CMdEQuery@@QBE?AVTPtrC16@@H@Z @ 211 NONAME ; class TPtrC16 CMdEQuery::ResultDistinctValue(int) const
+	?ResultId@CMdEQuery@@QBEKH@Z @ 212 NONAME ; unsigned long CMdEQuery::ResultId(int) const
+	?ResultIds@CMdEQuery@@QBEABV?$RArray@K@@XZ @ 213 NONAME ; class RArray<unsigned long> const & CMdEQuery::ResultIds(void) const
+	?ResultItem@CMdEQuery@@QBEAAVCMdEItem@@H@Z @ 214 NONAME ; class CMdEItem & CMdEQuery::ResultItem(int) const
+	?ResultMode@CMdEQuery@@QBE?AW4TQueryResultMode@@XZ @ 215 NONAME ; enum TQueryResultMode CMdEQuery::ResultMode(void) const
+	?ResultObjectItem@CMdEQuery@@QBEAAVCMdEItem@@XZ @ 216 NONAME ; class CMdEItem & CMdEQuery::ResultObjectItem(void) const
+	?RightL@CMdERelationCondition@@QAEAAVCMdELogicCondition@@XZ @ 217 NONAME ; class CMdELogicCondition & CMdERelationCondition::RightL(void)
+	?RightObjectId@CMdERelation@@QBEKXZ @ 218 NONAME ; unsigned long CMdERelation::RightObjectId(void) const
+	?RightObjectId@TMdERelation@@QBEKXZ @ 219 NONAME ; unsigned long TMdERelation::RightObjectId(void) const
+	?Session@CMdEHarvesterSession@@QAEPAVCMdESession@@XZ @ 220 NONAME ; class CMdESession * CMdEHarvesterSession::Session(void)
+	?Session@CMdEItem@@QBEAAVCMdESession@@XZ @ 221 NONAME ; class CMdESession & CMdEItem::Session(void) const
+	?Session@CMdEQuery@@QBEAAVCMdESession@@XZ @ 222 NONAME ; class CMdESession & CMdEQuery::Session(void) const
+	?SessionRef@CMdEHarvesterSession@@QAEAAVCMdESession@@XZ @ 223 NONAME ; class CMdESession & CMdEHarvesterSession::SessionRef(void)
+	?SetAscending@TMdEOrderRule@@QAEXH@Z @ 224 NONAME ; void TMdEOrderRule::SetAscending(int)
+	?SetBoolValueL@CMdEProperty@@QAEXH@Z @ 225 NONAME ; void CMdEProperty::SetBoolValueL(int)
+	?SetCaseSensitive@TMdEOrderRule@@QAEXH@Z @ 226 NONAME ; void TMdEOrderRule::SetCaseSensitive(int)
+	?SetConfidential@CMdEObject@@QAEXH@Z @ 227 NONAME ; void CMdEObject::SetConfidential(int)
+	?SetConfidentialityLevel@CMdEObjectCondition@@QAEXW4TObjectConditionConfidentialityLevel@@@Z @ 228 NONAME ; void CMdEObjectCondition::SetConfidentialityLevel(enum TObjectConditionConfidentialityLevel)
+	?SetDefL@CMdEObject@@QAEXAAVCMdEObjectDef@@@Z @ 229 NONAME ; void CMdEObject::SetDefL(class CMdEObjectDef &)
+	?SetFileToPresent@CMdEHarvesterSession@@QAEHKABVTDesC16@@AAUTMdSFileInfo@@@Z @ 230 NONAME ; int CMdEHarvesterSession::SetFileToPresent(unsigned long, class TDesC16 const &, struct TMdSFileInfo &)
+	?SetFilesToNotPresent@CMdEHarvesterSession@@QAEXK@Z @ 231 NONAME ; void CMdEHarvesterSession::SetFilesToNotPresent(unsigned long)
+	?SetFilesToNotPresent@CMdEHarvesterSession@@QAEXKH@Z @ 232 NONAME ; void CMdEHarvesterSession::SetFilesToNotPresent(unsigned long, int)
+	?SetFilesToPresentL@CMdEHarvesterSession@@QAEXKABV?$RArray@VTPtrC16@@@@ABV?$RArray@UTMdSFileInfo@@@@AAV?$RArray@W4TFilePresentStates@@@@@Z @ 233 NONAME ; void CMdEHarvesterSession::SetFilesToPresentL(unsigned long, class RArray<class TPtrC16> const &, class RArray<struct TMdSFileInfo> const &, class RArray<enum TFilePresentStates> &)
+	?SetGuid@CMdEObject@@QAEXAB_J0@Z @ 234 NONAME ; void CMdEObject::SetGuid(long long const &, long long const &)
+	?SetGuid@CMdERelation@@QAEXAB_J0@Z @ 235 NONAME ; void CMdERelation::SetGuid(long long const &, long long const &)
+	?SetGuid@CMdERelationCondition@@QAEXAB_J0@Z @ 236 NONAME ; void CMdERelationCondition::SetGuid(long long const &, long long const &)
+	?SetHarvestingPrioritizationChunkL@CMdEHarvesterSession@@QAEXH@Z @ 237 NONAME ; void CMdEHarvesterSession::SetHarvestingPrioritizationChunkL(int)
+	?SetInt16ValueL@CMdEProperty@@QAEXF@Z @ 238 NONAME ; void CMdEProperty::SetInt16ValueL(short)
+	?SetInt32ValueL@CMdEProperty@@QAEXJ@Z @ 239 NONAME ; void CMdEProperty::SetInt32ValueL(long)
+	?SetInt64ValueL@CMdEProperty@@QAEX_J@Z @ 240 NONAME ; void CMdEProperty::SetInt64ValueL(long long)
+	?SetInt8ValueL@CMdEProperty@@QAEXC@Z @ 241 NONAME ; void CMdEProperty::SetInt8ValueL(signed char)
+	?SetLastModifiedDate@CMdERelation@@QAEXVTTime@@@Z @ 242 NONAME ; void CMdERelation::SetLastModifiedDate(class TTime)
+	?SetLastModifiedDateRangeL@CMdERelationCondition@@QAEXABV?$TMdERange@VTTime@@@@@Z @ 243 NONAME ; void CMdERelationCondition::SetLastModifiedDateRangeL(class TMdERange<class TTime> const &)
+	?SetLeftObjectIdL@CMdERelation@@QAEXK@Z @ 244 NONAME ; void CMdERelation::SetLeftObjectIdL(unsigned long)
+	?SetLocked@CMdECondition@@UAEXH@Z @ 245 NONAME ; void CMdECondition::SetLocked(int)
+	?SetMediaId@CMdEObject@@QAEXK@Z @ 246 NONAME ; void CMdEObject::SetMediaId(unsigned long)
+	?SetMediaL@CMdEHarvesterSession@@QAEXKVTChar@@H@Z @ 247 NONAME ; void CMdEHarvesterSession::SetMediaL(unsigned long, class TChar, int)
+	?SetNegate@CMdECondition@@QAEXH@Z @ 248 NONAME ; void CMdECondition::SetNegate(int)
+	?SetNotPlaceholder@CMdEObjectCondition@@QAEXH@Z @ 249 NONAME ; void CMdEObjectCondition::SetNotPlaceholder(int)
+	?SetNotPresent@CMdEObjectCondition@@QAEXH@Z @ 250 NONAME ; void CMdEObjectCondition::SetNotPresent(int)
+	?SetOperator@CMdELogicCondition@@QAEXW4TLogicConditionOperator@@@Z @ 251 NONAME ; void CMdELogicCondition::SetOperator(enum TLogicConditionOperator)
+	?SetParameter@CMdERelation@@QAEXJ@Z @ 252 NONAME ; void CMdERelation::SetParameter(long)
+	?SetPending@CMdEHarvesterSession@@QAEXABV?$RArray@K@@@Z @ 253 NONAME ABSENT ; void CMdEHarvesterSession::SetPending(class RArray<unsigned long> const &)
+	?SetPlaceholder@CMdEObject@@QAEXH@Z @ 254 NONAME ; void CMdEObject::SetPlaceholder(int)
+	?SetPropertyDef@TMdEOrderRule@@QAEXABVCMdEPropertyDef@@@Z @ 255 NONAME ; void TMdEOrderRule::SetPropertyDef(class CMdEPropertyDef const &)
+	?SetReal32ValueL@CMdEProperty@@QAEXM@Z @ 256 NONAME ; void CMdEProperty::SetReal32ValueL(float)
+	?SetReal64ValueL@CMdEProperty@@QAEXN@Z @ 257 NONAME ; void CMdEProperty::SetReal64ValueL(double)
+	?SetResultMode@CMdEQuery@@QAEXW4TQueryResultMode@@@Z @ 258 NONAME ; void CMdEQuery::SetResultMode(enum TQueryResultMode)
+	?SetRightObjectIdL@CMdERelation@@QAEXK@Z @ 259 NONAME ; void CMdERelation::SetRightObjectIdL(unsigned long)
+	?SetSession@CMdEHarvesterSession@@QAEXAAVCMdESession@@@Z @ 260 NONAME ; void CMdEHarvesterSession::SetSession(class CMdESession &)
+	?SetSide@CMdERelationCondition@@QAEXW4TRelationConditionSide@@@Z @ 261 NONAME ; void CMdERelationCondition::SetSide(enum TRelationConditionSide)
+	?SetTextValueL@CMdEProperty@@QAEXABVTDesC16@@@Z @ 262 NONAME ; void CMdEProperty::SetTextValueL(class TDesC16 const &)
+	?SetTimeValueL@CMdEProperty@@QAEXABVTTime@@@Z @ 263 NONAME ; void CMdEProperty::SetTimeValueL(class TTime const &)
+	?SetType@TMdEOrderRule@@QAEXW4TOrderRuleType@@@Z @ 264 NONAME ; void TMdEOrderRule::SetType(enum TOrderRuleType)
+	?SetUint16ValueL@CMdEProperty@@QAEXG@Z @ 265 NONAME ; void CMdEProperty::SetUint16ValueL(unsigned short)
+	?SetUint32ValueL@CMdEProperty@@QAEXK@Z @ 266 NONAME ; void CMdEProperty::SetUint32ValueL(unsigned long)
+	?SetUint8ValueL@CMdEProperty@@QAEXE@Z @ 267 NONAME ; void CMdEProperty::SetUint8ValueL(unsigned char)
+	?SetUriL@CMdEObject@@QAEXABVTDesC16@@@Z @ 268 NONAME ; void CMdEObject::SetUriL(class TDesC16 const &)
+	?Source@CMdEEvent@@QBEPBVTDesC16@@XZ @ 269 NONAME ; class TDesC16 const * CMdEEvent::Source(void) const
+	?SourceObjectConditionsL@CMdEEventCondition@@QAEAAVCMdELogicCondition@@XZ @ 270 NONAME ; class CMdELogicCondition & CMdEEventCondition::SourceObjectConditionsL(void)
+	?SourceURI@CMdEEventCondition@@QBEPBVTDesC16@@XZ @ 271 NONAME ; class TDesC16 const * CMdEEventCondition::SourceURI(void) const
+	?State@CMdEQuery@@QBE?AW4TState@1@XZ @ 272 NONAME ; enum CMdEQuery::TState CMdEQuery::State(void) const
+	?String@CMdEObjectCondition@@QBEPBVTDesC16@@XZ @ 273 NONAME ; class TDesC16 const * CMdEObjectCondition::String(void) const
+	?TakeOwnershipOfResult@CMdEQuery@@QAEPAVCMdEItem@@H@Z @ 274 NONAME ; class CMdEItem * CMdEQuery::TakeOwnershipOfResult(int)
+	?TextValueL@CMdEProperty@@QBEABVTDesC16@@XZ @ 275 NONAME ; class TDesC16 const & CMdEProperty::TextValueL(void) const
+	?Time@CMdEEvent@@QBE?AVTTime@@XZ @ 276 NONAME ; class TTime CMdEEvent::Time(void) const
+	?TimeRange@CMdEEventCondition@@QBEPBV?$TMdERange@VTTime@@@@XZ @ 277 NONAME ; class TMdERange<class TTime> const * CMdEEventCondition::TimeRange(void) const
+	?TimeValueL@CMdEProperty@@QBE?AVTTime@@XZ @ 278 NONAME ; class TTime CMdEProperty::TimeValueL(void) const
+	?Type@CMdECondition@@QBE?AW4TConditionType@@XZ @ 279 NONAME ; enum TConditionType CMdECondition::Type(void) const
+	?Type@CMdEQuery@@QBE?AW4TQueryType@@XZ @ 280 NONAME ; enum TQueryType CMdEQuery::Type(void) const
+	?Type@TMdEOrderRule@@QBE?AW4TOrderRuleType@@XZ @ 281 NONAME ; enum TOrderRuleType TMdEOrderRule::Type(void) const
+	?Uint16ValueL@CMdEProperty@@QBEGXZ @ 282 NONAME ; unsigned short CMdEProperty::Uint16ValueL(void) const
+	?Uint32ValueL@CMdEProperty@@QBEKXZ @ 283 NONAME ; unsigned long CMdEProperty::Uint32ValueL(void) const
+	?Uint8ValueL@CMdEProperty@@QBEEXZ @ 284 NONAME ; unsigned char CMdEProperty::Uint8ValueL(void) const
+	?Uri@CMdEObject@@QBEABVTDesC16@@XZ @ 285 NONAME ; class TDesC16 const & CMdEObject::Uri(void) const
+	?UsageCount@CMdEObject@@QBEKXZ @ 286 NONAME ; unsigned long CMdEObject::UsageCount(void) const
+	?Value@CMdEBoolPropertyCondition@@QBEHXZ @ 287 NONAME ; int CMdEBoolPropertyCondition::Value(void) const
+	?GetPendingCount@CMdEHarvesterSession@@QAEPAVTGetPendingPgckWrapper@@PBVCMdEObjectDef@@@Z @ 288 NONAME ABSENT ; class TGetPendingPgckWrapper * CMdEHarvesterSession::GetPendingCount(class CMdEObjectDef const *)
+	?GetPendingCount@CMdEHarvesterSession@@QAEHPBVCMdEObjectDef@@@Z @ 289 NONAME ; int CMdEHarvesterSession::GetPendingCount(class CMdEObjectDef const *)
+	?GetPending@CMdEHarvesterSession@@QAEHPBVCMdEObjectDef@@AAHAAVCMdCSerializationBuffer@@@Z @ 290 NONAME ; int CMdEHarvesterSession::GetPending(class CMdEObjectDef const *, int &, class CMdCSerializationBuffer &)
+	?ChangeCDriveMediaId@CMdEHarvesterSession@@QAEXXZ @ 291 NONAME ; void CMdEHarvesterSession::ChangeCDriveMediaId(void)
+	?ResetPendingL@CMdEHarvesterSession@@QAEXABV?$RArray@K@@@Z @ 292 NONAME ; void CMdEHarvesterSession::ResetPendingL(class RArray<unsigned long> const &)
+	?SetPendingL@CMdEHarvesterSession@@QAEXABV?$RArray@K@@@Z @ 293 NONAME ; void CMdEHarvesterSession::SetPendingL(class RArray<unsigned long> const &)
+	?PlaceholderOnly@CMdEObjectCondition@@QBEHXZ @ 294 NONAME ; int CMdEObjectCondition::PlaceholderOnly(void) const
+	?SetPlaceholderOnly@CMdEObjectCondition@@QAEXH@Z @ 295 NONAME ; void CMdEObjectCondition::SetPlaceholderOnly(int)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/eabi/mdeclientu.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,368 @@
+EXPORTS
+	_ZN10CMdEObject10SetMediaIdEm @ 1 NONAME
+	_ZN10CMdEObject12AddFreeTextLERK7TDesC16 @ 2 NONAME
+	_ZN10CMdEObject14RemoveFreeTextEi @ 3 NONAME
+	_ZN10CMdEObject14RemovePropertyEi @ 4 NONAME
+	_ZN10CMdEObject14SetPlaceholderEi @ 5 NONAME
+	_ZN10CMdEObject15MovePropertiesLERS_ @ 6 NONAME
+	_ZN10CMdEObject15SetConfidentialEi @ 7 NONAME
+	_ZN10CMdEObject16AddBoolPropertyLER15CMdEPropertyDefi @ 8 NONAME
+	_ZN10CMdEObject16AddInt8PropertyLER15CMdEPropertyDefa @ 9 NONAME
+	_ZN10CMdEObject16AddTextPropertyLER15CMdEPropertyDefRK7TDesC16 @ 10 NONAME
+	_ZN10CMdEObject16AddTimePropertyLER15CMdEPropertyDef5TTime @ 11 NONAME
+	_ZN10CMdEObject17AddInt16PropertyLER15CMdEPropertyDefs @ 12 NONAME
+	_ZN10CMdEObject17AddInt32PropertyLER15CMdEPropertyDefl @ 13 NONAME
+	_ZN10CMdEObject17AddInt64PropertyLER15CMdEPropertyDefx @ 14 NONAME
+	_ZN10CMdEObject17AddUint8PropertyLER15CMdEPropertyDefh @ 15 NONAME
+	_ZN10CMdEObject18AddReal32PropertyLER15CMdEPropertyDeff @ 16 NONAME
+	_ZN10CMdEObject18AddReal64PropertyLER15CMdEPropertyDefd @ 17 NONAME
+	_ZN10CMdEObject18AddUint16PropertyLER15CMdEPropertyDeft @ 18 NONAME
+	_ZN10CMdEObject18AddUint32PropertyLER15CMdEPropertyDefm @ 19 NONAME
+	_ZN10CMdEObject7SetDefLER13CMdEObjectDef @ 20 NONAME
+	_ZN10CMdEObject7SetGuidERKxS1_ @ 21 NONAME
+	_ZN10CMdEObject7SetUriLERK7TDesC16 @ 22 NONAME
+	_ZN10TMdEObjectC1Ev @ 23 NONAME
+	_ZN10TMdEObjectC2Ev @ 24 NONAME
+	_ZN11CMdESession4NewLER19MMdESessionObserver @ 25 NONAME
+	_ZN11CMdESession5NewLCER19MMdESessionObserver @ 26 NONAME
+	_ZN12CMdEProperty13SetBoolValueLEi @ 27 NONAME
+	_ZN12CMdEProperty13SetInt8ValueLEa @ 28 NONAME
+	_ZN12CMdEProperty13SetTextValueLERK7TDesC16 @ 29 NONAME
+	_ZN12CMdEProperty13SetTimeValueLERK5TTime @ 30 NONAME
+	_ZN12CMdEProperty14SetInt16ValueLEs @ 31 NONAME
+	_ZN12CMdEProperty14SetInt32ValueLEl @ 32 NONAME
+	_ZN12CMdEProperty14SetInt64ValueLEx @ 33 NONAME
+	_ZN12CMdEProperty14SetUint8ValueLEh @ 34 NONAME
+	_ZN12CMdEProperty15SetReal32ValueLEf @ 35 NONAME
+	_ZN12CMdEProperty15SetReal64ValueLEd @ 36 NONAME
+	_ZN12CMdEProperty15SetUint16ValueLEt @ 37 NONAME
+	_ZN12CMdEProperty15SetUint32ValueLEm @ 38 NONAME
+	_ZN12CMdERelation12SetParameterEl @ 39 NONAME
+	_ZN12CMdERelation16SetLeftObjectIdLEm @ 40 NONAME
+	_ZN12CMdERelation17SetRightObjectIdLEm @ 41 NONAME
+	_ZN12CMdERelation19SetLastModifiedDateE5TTime @ 42 NONAME
+	_ZN12CMdERelation7SetGuidERKxS1_ @ 43 NONAME
+	_ZN13CMdECondition9SetLockedEi @ 44 NONAME
+	_ZN13CMdECondition9SetNegateEi @ 45 NONAME
+	_ZN13CMdEObjectDef12PropertyDefLEi @ 46 NONAME
+	_ZN13CMdEObjectDef15GetPropertyDefLERK7TDesC16 @ 47 NONAME
+	_ZN13CMdEObjectDef7ParentLEv @ 48 NONAME
+	_ZN13TMdEOrderRule12SetAscendingEi @ 49 NONAME
+	_ZN13TMdEOrderRule13CaseSensitiveEv @ 50 NONAME
+	_ZN13TMdEOrderRule14SetPropertyDefERK15CMdEPropertyDef @ 51 NONAME
+	_ZN13TMdEOrderRule16SetCaseSensitiveEi @ 52 NONAME
+	_ZN13TMdEOrderRule7SetTypeE14TOrderRuleType @ 53 NONAME
+	_ZN13TMdEOrderRuleC1E14TOrderRuleTypei @ 54 NONAME
+	_ZN13TMdEOrderRuleC1ERK15CMdEPropertyDefi @ 55 NONAME
+	_ZN13TMdEOrderRuleC2E14TOrderRuleTypei @ 56 NONAME
+	_ZN13TMdEOrderRuleC2ERK15CMdEPropertyDefi @ 57 NONAME
+	_ZN14RMdEDataBuffer5CloseEv @ 58 NONAME
+	_ZN14RMdEDataBufferC1Ev @ 59 NONAME
+	_ZN14RMdEDataBufferC2Ev @ 60 NONAME
+	_ZN15CMdEObjectQuery18AddPropertyFilterLEPK15CMdEPropertyDef @ 61 NONAME
+	_ZN15CMdEObjectQuery19ResetPropertyFilterEv @ 62 NONAME
+	_ZN15CMdESessionImpl10GetObjectLERK7TDesC16P16CMdENamespaceDef @ 63 NONAME
+	_ZN16CMdENamespaceDef10ObjectDefLEi @ 64 NONAME
+	_ZN16CMdENamespaceDef12GetEventDefLERK7TDesC16 @ 65 NONAME
+	_ZN16CMdENamespaceDef12GetEventDefLEm @ 66 NONAME ABSENT
+	_ZN16CMdENamespaceDef12RelationDefLEi @ 67 NONAME
+	_ZN16CMdENamespaceDef13GetObjectDefLERK7TDesC16 @ 68 NONAME
+	_ZN16CMdENamespaceDef15GetRelationDefLERK7TDesC16 @ 69 NONAME
+	_ZN16CMdENamespaceDef15GetRelationDefLEm @ 70 NONAME ABSENT
+	_ZN16CMdENamespaceDef9EventDefLEi @ 71 NONAME
+	_ZN18CMdEEventCondition17ObjectConditionsLEv @ 72 NONAME
+	_ZN18CMdEEventCondition23SourceObjectConditionsLEv @ 73 NONAME
+	_ZN18CMdEEventCondition28ParticipantObjectConditionsLEv @ 74 NONAME
+	_ZN18CMdELogicCondition11SetOperatorE23TLogicConditionOperator @ 75 NONAME
+	_ZN18CMdELogicCondition18AddEventConditionLE28TEventConditionCompareMethodRK7TDesC16 @ 76 NONAME
+	_ZN18CMdELogicCondition18AddEventConditionLERK12CMdEEventDef @ 77 NONAME
+	_ZN18CMdELogicCondition18AddEventConditionLERK9TMdERangeI5TTimeE @ 78 NONAME
+	_ZN18CMdELogicCondition18AddEventConditionLERK9TMdERangeI5TTimeE28TEventConditionCompareMethodRK7TDesC16 @ 79 NONAME
+	_ZN18CMdELogicCondition18AddEventConditionLEm @ 80 NONAME
+	_ZN18CMdELogicCondition18AddEventConditionLEv @ 81 NONAME
+	_ZN18CMdELogicCondition18AddLogicConditionLE23TLogicConditionOperator @ 82 NONAME
+	_ZN18CMdELogicCondition19AddObjectConditionLE29TObjectConditionCompareMethodRK7TDesC16 @ 83 NONAME
+	_ZN18CMdELogicCondition19AddObjectConditionLERK13CMdEObjectDef @ 84 NONAME
+	_ZN18CMdELogicCondition19AddObjectConditionLERK6RArrayImE @ 85 NONAME
+	_ZN18CMdELogicCondition19AddObjectConditionLERK9TMdERangeIjE @ 86 NONAME
+	_ZN18CMdELogicCondition19AddObjectConditionLEm @ 87 NONAME
+	_ZN18CMdELogicCondition19AddObjectConditionLExx @ 88 NONAME
+	_ZN18CMdELogicCondition21AddPropertyConditionLERK15CMdEPropertyDef @ 89 NONAME
+	_ZN18CMdELogicCondition21AddPropertyConditionLERK15CMdEPropertyDef35TTextPropertyConditionCompareMethodRK7TDesC16 @ 90 NONAME
+	_ZN18CMdELogicCondition21AddPropertyConditionLERK15CMdEPropertyDefRK9TMdERangeI5TTimeE @ 91 NONAME
+	_ZN18CMdELogicCondition21AddPropertyConditionLERK15CMdEPropertyDefRK9TMdERangeIdE @ 92 NONAME
+	_ZN18CMdELogicCondition21AddPropertyConditionLERK15CMdEPropertyDefRK9TMdERangeIiE @ 93 NONAME
+	_ZN18CMdELogicCondition21AddPropertyConditionLERK15CMdEPropertyDefRK9TMdERangeIjE @ 94 NONAME
+	_ZN18CMdELogicCondition21AddPropertyConditionLERK15CMdEPropertyDefRK9TMdERangeIxE @ 95 NONAME
+	_ZN18CMdELogicCondition21AddPropertyConditionLERK15CMdEPropertyDefi @ 96 NONAME
+	_ZN18CMdELogicCondition21AddRelationConditionLE22TRelationConditionSide @ 97 NONAME
+	_ZN18CMdELogicCondition21AddRelationConditionLER6RArrayImE22TRelationConditionSide @ 98 NONAME
+	_ZN18CMdELogicCondition21AddRelationConditionLERK15CMdERelationDef22TRelationConditionSide @ 99 NONAME
+	_ZN18CMdELogicCondition21AddRelationConditionLERK15CMdERelationDefRK9TMdERangeIiE22TRelationConditionSide @ 100 NONAME
+	_ZN18CMdELogicCondition21AddRelationConditionLEm22TRelationConditionSide @ 101 NONAME
+	_ZN18CMdELogicCondition4NewLE23TLogicConditionOperator @ 102 NONAME
+	_ZN18CMdELogicCondition5NewLCE23TLogicConditionOperator @ 103 NONAME
+	_ZN18CMdELogicCondition6RemoveEi @ 104 NONAME
+	_ZN19CMdEObjectCondition13SetNotPresentEi @ 105 NONAME
+	_ZN19CMdEObjectCondition17SetNotPlaceholderEi @ 106 NONAME
+	_ZN19CMdEObjectCondition23SetConfidentialityLevelE36TObjectConditionConfidentialityLevel @ 107 NONAME
+	_ZN20CMdEHarvesterSession10ChangePathERK7TDesC16S2_R14TRequestStatus @ 108 NONAME
+	_ZN20CMdEHarvesterSession10GetPendingEPK13CMdEObjectDefRiR23CMdCSerializationBufferR14TRequestStatus @ 109 NONAME ABSENT
+	_ZN20CMdEHarvesterSession10SessionRefEv @ 110 NONAME
+	_ZN20CMdEHarvesterSession10SetPendingERK6RArrayImE @ 111 NONAME ABSENT
+	_ZN20CMdEHarvesterSession10SetSessionER11CMdESession @ 112 NONAME
+	_ZN20CMdEHarvesterSession12ResetPendingERK6RArrayImE @ 113 NONAME ABSENT
+	_ZN20CMdEHarvesterSession13AddMemoryCardEm @ 114 NONAME
+	_ZN20CMdEHarvesterSession13GetMemoryCardERm @ 115 NONAME
+	_ZN20CMdEHarvesterSession15CheckMemoryCardEmRi @ 116 NONAME
+	_ZN20CMdEHarvesterSession15GetPendingCountEPK13CMdEObjectDefR14TRequestStatus @ 117 NONAME ABSENT
+	_ZN20CMdEHarvesterSession16SetFileToPresentEmRK7TDesC16R12TMdSFileInfo @ 118 NONAME
+	_ZN20CMdEHarvesterSession17GetPresentMediasLER6RArrayI13TMdEMediaInfoE @ 119 NONAME
+	_ZN20CMdEHarvesterSession18SetFilesToPresentLEmRK6RArrayI7TPtrC16ERKS0_I12TMdSFileInfoERS0_I18TFilePresentStatesE @ 120 NONAME
+	_ZN20CMdEHarvesterSession20SetFilesToNotPresentEm @ 121 NONAME
+	_ZN20CMdEHarvesterSession20SetFilesToNotPresentEmi @ 122 NONAME
+	_ZN20CMdEHarvesterSession21RemoveFilesNotPresentEm @ 123 NONAME
+	_ZN20CMdEHarvesterSession21RemoveFilesNotPresentEmi @ 124 NONAME
+	_ZN20CMdEHarvesterSession28HarvestingPrioritizationUriLEi @ 125 NONAME
+	_ZN20CMdEHarvesterSession33HarvestingPrioritizationUriCountLEv @ 126 NONAME
+	_ZN20CMdEHarvesterSession33SetHarvestingPrioritizationChunkLEi @ 127 NONAME
+	_ZN20CMdEHarvesterSession35AddHarvestingPrioritizationObserverER14TRequestStatus @ 128 NONAME
+	_ZN20CMdEHarvesterSession38CancelHarvestingPrioritizationObserverEv @ 129 NONAME
+	_ZN20CMdEHarvesterSession4NewLER11CMdESession @ 130 NONAME
+	_ZN20CMdEHarvesterSession5NewLCER11CMdESession @ 131 NONAME
+	_ZN20CMdEHarvesterSession7SessionEv @ 132 NONAME
+	_ZN20CMdEHarvesterSession8ResetDBLEv @ 133 NONAME
+	_ZN20CMdEHarvesterSession9AutoLockLER13RPointerArrayI10CMdEObjectE @ 134 NONAME
+	_ZN20CMdEHarvesterSession9GetMediaLEmR5TCharRi @ 135 NONAME
+	_ZN20CMdEHarvesterSession9SetMediaLEm5TChari @ 136 NONAME
+	_ZN21CMdERelationCondition25SetLastModifiedDateRangeLERK9TMdERangeI5TTimeE @ 137 NONAME
+	_ZN21CMdERelationCondition5LeftLEv @ 138 NONAME
+	_ZN21CMdERelationCondition6RightLEv @ 139 NONAME
+	_ZN21CMdERelationCondition7SetGuidERKxS1_ @ 140 NONAME
+	_ZN21CMdERelationCondition7SetSideE22TRelationConditionSide @ 141 NONAME
+	_ZN9CMdEQuery10OwnsResultEi @ 142 NONAME
+	_ZN9CMdEQuery12AddObserverLER17MMdEQueryObserver @ 143 NONAME
+	_ZN9CMdEQuery13SetResultModeE16TQueryResultMode @ 144 NONAME
+	_ZN9CMdEQuery14RemoveObserverER17MMdEQueryObserver @ 145 NONAME
+	_ZN9CMdEQuery15RemoveOrderRuleEi @ 146 NONAME
+	_ZN9CMdEQuery16AppendOrderRuleLERK13TMdEOrderRule @ 147 NONAME
+	_ZN9CMdEQuery16InsertOrderRuleLERK13TMdEOrderRulei @ 148 NONAME
+	_ZN9CMdEQuery21TakeOwnershipOfResultEi @ 149 NONAME
+	_ZN9CMdEQuery5FindLEjj @ 150 NONAME
+	_ZN9CMdEQuery6CancelEv @ 151 NONAME
+	_ZNK10CMdEObject10UsageCountEv @ 152 NONAME
+	_ZNK10CMdEObject11PlaceholderEv @ 153 NONAME
+	_ZNK10CMdEObject12ConfidentialEv @ 154 NONAME
+	_ZNK10CMdEObject13FreeTextCountEv @ 155 NONAME
+	_ZNK10CMdEObject13FreeTextIndexERK7TDesC16 @ 156 NONAME
+	_ZNK10CMdEObject13PropertyCountERK15CMdEPropertyDef @ 157 NONAME
+	_ZNK10CMdEObject13PropertyCountEv @ 158 NONAME
+	_ZNK10CMdEObject20OpenForModificationsEv @ 159 NONAME
+	_ZNK10CMdEObject3DefEv @ 160 NONAME
+	_ZNK10CMdEObject3UriEv @ 161 NONAME
+	_ZNK10CMdEObject4GuidERxS0_ @ 162 NONAME
+	_ZNK10CMdEObject7MediaIdEv @ 163 NONAME
+	_ZNK10CMdEObject8FreeTextEi @ 164 NONAME
+	_ZNK10CMdEObject8PropertyERK15CMdEPropertyDefRP12CMdEPropertyi @ 165 NONAME
+	_ZNK10CMdEObject9PropertyLEi @ 166 NONAME
+	_ZNK10TMdEObject10NotPresentEv @ 167 NONAME
+	_ZNK10TMdEObject11PlaceholderEv @ 168 NONAME
+	_ZNK10TMdEObject12ConfidentialEv @ 169 NONAME
+	_ZNK10TMdEObject2IdEv @ 170 NONAME
+	_ZNK10TMdEObject4DefLEv @ 171 NONAME
+	_ZNK10TMdEObject7RemovedEv @ 172 NONAME
+	_ZNK12CMdEEventDef12NamespaceDefEv @ 173 NONAME
+	_ZNK12CMdEEventDef4NameEv @ 174 NONAME
+	_ZNK12CMdEEventDef7CompareERKS_ @ 175 NONAME
+	_ZNK12CMdEProperty10BoolValueLEv @ 176 NONAME
+	_ZNK12CMdEProperty10Int8ValueLEv @ 177 NONAME
+	_ZNK12CMdEProperty10TextValueLEv @ 178 NONAME
+	_ZNK12CMdEProperty10TimeValueLEv @ 179 NONAME
+	_ZNK12CMdEProperty11Int16ValueLEv @ 180 NONAME
+	_ZNK12CMdEProperty11Int32ValueLEv @ 181 NONAME
+	_ZNK12CMdEProperty11Int64ValueLEv @ 182 NONAME
+	_ZNK12CMdEProperty11Uint8ValueLEv @ 183 NONAME
+	_ZNK12CMdEProperty12Real32ValueLEv @ 184 NONAME
+	_ZNK12CMdEProperty12Real64ValueLEv @ 185 NONAME
+	_ZNK12CMdEProperty12Uint16ValueLEv @ 186 NONAME
+	_ZNK12CMdEProperty12Uint32ValueLEv @ 187 NONAME
+	_ZNK12CMdEProperty3DefEv @ 188 NONAME
+	_ZNK12CMdEProperty6ObjectEv @ 189 NONAME
+	_ZNK12CMdEProperty8ModifiedEv @ 190 NONAME
+	_ZNK12CMdERelation12LeftObjectIdEv @ 191 NONAME
+	_ZNK12CMdERelation13RightObjectIdEv @ 192 NONAME
+	_ZNK12CMdERelation16LastModifiedDateEv @ 193 NONAME
+	_ZNK12CMdERelation3DefEv @ 194 NONAME
+	_ZNK12CMdERelation4GuidERxS0_ @ 195 NONAME
+	_ZNK12CMdERelation9ParameterEv @ 196 NONAME
+	_ZNK12TMdERelation12LeftObjectIdEv @ 197 NONAME
+	_ZNK12TMdERelation13RightObjectIdEv @ 198 NONAME
+	_ZNK12TMdERelation2IdEv @ 199 NONAME
+	_ZNK12TMdERelation4DefLEv @ 200 NONAME
+	_ZNK13CMdECondition4TypeEv @ 201 NONAME
+	_ZNK13CMdECondition6LockedEv @ 202 NONAME
+	_ZNK13CMdECondition6NegateEv @ 203 NONAME
+	_ZNK13CMdEObjectDef12NamespaceDefEv @ 204 NONAME
+	_ZNK13CMdEObjectDef16PropertyDefCountEv @ 205 NONAME
+	_ZNK13CMdEObjectDef4NameEv @ 206 NONAME
+	_ZNK13CMdEObjectDef7CompareERKS_ @ 207 NONAME
+	_ZNK13TMdEOrderRule11PropertyDefEv @ 208 NONAME
+	_ZNK13TMdEOrderRule4TypeEv @ 209 NONAME
+	_ZNK13TMdEOrderRule9AscendingEv @ 210 NONAME
+	_ZNK14CMdEEventQuery6ResultEi @ 211 NONAME
+	_ZNK15CMdEObjectQuery6ResultEi @ 212 NONAME
+	_ZNK15CMdEObjectQuery9ObjectDefEv @ 213 NONAME
+	_ZNK15CMdEPropertyDef12NamespaceDefEv @ 214 NONAME
+	_ZNK15CMdEPropertyDef12PropertyTypeEv @ 215 NONAME
+	_ZNK15CMdEPropertyDef13MaxRealValueLEv @ 216 NONAME
+	_ZNK15CMdEPropertyDef13MaxTimeValueLEv @ 217 NONAME
+	_ZNK15CMdEPropertyDef13MinRealValueLEv @ 218 NONAME
+	_ZNK15CMdEPropertyDef13MinTimeValueLEv @ 219 NONAME
+	_ZNK15CMdEPropertyDef14MaxInt32ValueLEv @ 220 NONAME
+	_ZNK15CMdEPropertyDef14MaxInt64ValueLEv @ 221 NONAME
+	_ZNK15CMdEPropertyDef14MaxTextLengthLEv @ 222 NONAME
+	_ZNK15CMdEPropertyDef14MinInt32ValueLEv @ 223 NONAME
+	_ZNK15CMdEPropertyDef14MinInt64ValueLEv @ 224 NONAME
+	_ZNK15CMdEPropertyDef14MinTextLengthLEv @ 225 NONAME
+	_ZNK15CMdEPropertyDef15MaxUint32ValueLEv @ 226 NONAME
+	_ZNK15CMdEPropertyDef15MinUint32ValueLEv @ 227 NONAME
+	_ZNK15CMdEPropertyDef4NameEv @ 228 NONAME
+	_ZNK15CMdEPropertyDef7CompareERKS_ @ 229 NONAME
+	_ZNK15CMdEPropertyDef8ReadOnlyEv @ 230 NONAME
+	_ZNK15CMdEPropertyDef9MandatoryEv @ 231 NONAME
+	_ZNK15CMdEPropertyDef9ObjectDefEv @ 232 NONAME
+	_ZNK15CMdERelationDef12NamespaceDefEv @ 233 NONAME
+	_ZNK15CMdERelationDef4NameEv @ 234 NONAME
+	_ZNK15CMdERelationDef7CompareERKS_ @ 235 NONAME
+	_ZNK16CMdENamespaceDef13EventDefCountEv @ 236 NONAME
+	_ZNK16CMdENamespaceDef14ObjectDefCountEv @ 237 NONAME
+	_ZNK16CMdENamespaceDef16RelationDefCountEv @ 238 NONAME
+	_ZNK16CMdENamespaceDef4NameEv @ 239 NONAME
+	_ZNK16CMdENamespaceDef7CompareERKS_ @ 240 NONAME
+	_ZNK16CMdENamespaceDef8ReadOnlyEv @ 241 NONAME
+	_ZNK17CMdERelationQuery6ResultEi @ 242 NONAME
+	_ZNK18CMdEEventCondition14ParticipantURIEv @ 243 NONAME
+	_ZNK18CMdEEventCondition7EventIdEv @ 244 NONAME
+	_ZNK18CMdEEventCondition8EventDefEv @ 245 NONAME
+	_ZNK18CMdEEventCondition9SourceURIEv @ 246 NONAME
+	_ZNK18CMdEEventCondition9TimeRangeEv @ 247 NONAME
+	_ZNK18CMdELogicCondition5CountEv @ 248 NONAME
+	_ZNK18CMdELogicCondition8OperatorEv @ 249 NONAME
+	_ZNK18CMdELogicCondition9ConditionEi @ 250 NONAME
+	_ZNK19CMdEObjectCondition10NotPresentEv @ 251 NONAME
+	_ZNK19CMdEObjectCondition13CompareMethodEv @ 252 NONAME
+	_ZNK19CMdEObjectCondition14NotPlaceholderEv @ 253 NONAME
+	_ZNK19CMdEObjectCondition20ConfidentialityLevelEv @ 254 NONAME
+	_ZNK19CMdEObjectCondition6StringEv @ 255 NONAME
+	_ZNK19CMdEObjectCondition8ObjectIdEv @ 256 NONAME
+	_ZNK19CMdEObjectCondition9ObjectDefEv @ 257 NONAME
+	_ZNK19CMdEObjectCondition9ObjectIdsEv @ 258 NONAME
+	_ZNK21CMdEPropertyCondition11PropertyDefEv @ 259 NONAME
+	_ZNK21CMdERelationCondition10RelationIdEv @ 260 NONAME
+	_ZNK21CMdERelationCondition11RelationDefEv @ 261 NONAME
+	_ZNK21CMdERelationCondition11RelationIdsEv @ 262 NONAME
+	_ZNK21CMdERelationCondition14ParameterRangeEv @ 263 NONAME
+	_ZNK21CMdERelationCondition21LastModifiedDateRangeER9TMdERangeI5TTimeE @ 264 NONAME
+	_ZNK21CMdERelationCondition4GuidERxS0_ @ 265 NONAME
+	_ZNK25CMdEBoolPropertyCondition5ValueEv @ 266 NONAME
+	_ZNK8CMdEItem10InDatabaseEv @ 267 NONAME
+	_ZNK8CMdEItem16BelongsToSessionEv @ 268 NONAME
+	_ZNK8CMdEItem2IdEv @ 269 NONAME
+	_ZNK8CMdEItem7SessionEv @ 270 NONAME
+	_ZNK9CMdEEvent11ParticipantEv @ 271 NONAME
+	_ZNK9CMdEEvent3DefEv @ 272 NONAME
+	_ZNK9CMdEEvent4TimeEv @ 273 NONAME
+	_ZNK9CMdEEvent6SourceEv @ 274 NONAME
+	_ZNK9CMdEEvent8ObjectIdEv @ 275 NONAME
+	_ZNK9CMdEQuery10ConditionsEv @ 276 NONAME
+	_ZNK9CMdEQuery10IsCompleteEv @ 277 NONAME
+	_ZNK9CMdEQuery10ResultItemEi @ 278 NONAME
+	_ZNK9CMdEQuery10ResultModeEv @ 279 NONAME
+	_ZNK9CMdEQuery12NamespaceDefEv @ 280 NONAME
+	_ZNK9CMdEQuery14OrderRuleCountEv @ 281 NONAME
+	_ZNK9CMdEQuery16ResultObjectItemEv @ 282 NONAME
+	_ZNK9CMdEQuery19ResultDistinctValueEi @ 283 NONAME
+	_ZNK9CMdEQuery4TypeEv @ 284 NONAME
+	_ZNK9CMdEQuery5CountEv @ 285 NONAME
+	_ZNK9CMdEQuery5ErrorEv @ 286 NONAME
+	_ZNK9CMdEQuery5StateEv @ 287 NONAME
+	_ZNK9CMdEQuery7SessionEv @ 288 NONAME
+	_ZNK9CMdEQuery8ResultIdEi @ 289 NONAME
+	_ZNK9CMdEQuery9OrderRuleEi @ 290 NONAME
+	_ZNK9CMdEQuery9ResultIdsEv @ 291 NONAME
+	_ZTI10CMdEObject @ 292 NONAME ABSENT ; #<TI>#
+	_ZTI11CMdESession @ 293 NONAME ABSENT ; #<TI>#
+	_ZTI12CMdEEventDef @ 294 NONAME ABSENT ; #<TI>#
+	_ZTI12CMdEProperty @ 295 NONAME ABSENT ; #<TI>#
+	_ZTI12CMdERelation @ 296 NONAME ABSENT ; #<TI>#
+	_ZTI13CMdECondition @ 297 NONAME ABSENT ; #<TI>#
+	_ZTI13CMdEObjectDef @ 298 NONAME ABSENT ; #<TI>#
+	_ZTI14CMdEEventQuery @ 299 NONAME ABSENT ; #<TI>#
+	_ZTI14CMdENotifierAO @ 300 NONAME ABSENT ; #<TI>#
+	_ZTI15CMdEObjectQuery @ 301 NONAME ABSENT ; #<TI>#
+	_ZTI15CMdEPropertyDef @ 302 NONAME ABSENT ; #<TI>#
+	_ZTI15CMdERelationDef @ 303 NONAME ABSENT ; #<TI>#
+	_ZTI15CMdESessionImpl @ 304 NONAME ABSENT ; #<TI>#
+	_ZTI16CMdEInstanceItem @ 305 NONAME ABSENT ; #<TI>#
+	_ZTI16CMdENamespaceDef @ 306 NONAME ABSENT ; #<TI>#
+	_ZTI17CMdERelationQuery @ 307 NONAME ABSENT ; #<TI>#
+	_ZTI18CMdEEventCondition @ 308 NONAME ABSENT ; #<TI>#
+	_ZTI18CMdEEventQueryImpl @ 309 NONAME
+	_ZTI18CMdELogicCondition @ 310 NONAME ABSENT ; #<TI>#
+	_ZTI19CMdEObjectCondition @ 311 NONAME ABSENT ; #<TI>#
+	_ZTI19CMdEObjectQueryImpl @ 312 NONAME ABSENT ; #<TI>#
+	_ZTI20CMdEHarvesterSession @ 313 NONAME ABSENT ; #<TI>#
+	_ZTI20CMdESessionStartupAO @ 314 NONAME ABSENT ; #<TI>#
+	_ZTI21CMdEPropertyCondition @ 315 NONAME ABSENT ; #<TI>#
+	_ZTI21CMdERelationCondition @ 316 NONAME ABSENT ; #<TI>#
+	_ZTI21CMdERelationQueryImpl @ 317 NONAME
+	_ZTI22CMdEAsynchronousFindAO @ 318 NONAME ABSENT ; #<TI>#
+	_ZTI23CMdESessionAsyncHandler @ 319 NONAME ABSENT ; #<TI>#
+	_ZTI25CMdEBoolPropertyCondition @ 320 NONAME ABSENT ; #<TI>#
+	_ZTI25CMdETextPropertyCondition @ 321 NONAME ABSENT ; #<TI>#
+	_ZTI30CMdEQueryCriteriaSerialization @ 322 NONAME ABSENT ; #<TI>#
+	_ZTI8CMdEItem @ 323 NONAME ABSENT ; #<TI>#
+	_ZTI9CMdEEvent @ 324 NONAME ABSENT ; #<TI>#
+	_ZTI9CMdEQuery @ 325 NONAME ABSENT ; #<TI>#
+	_ZTV10CMdEObject @ 326 NONAME ABSENT ; #<VT>#
+	_ZTV11CMdESession @ 327 NONAME ABSENT ; #<VT>#
+	_ZTV12CMdEEventDef @ 328 NONAME ABSENT ; #<VT>#
+	_ZTV12CMdEProperty @ 329 NONAME ABSENT ; #<VT>#
+	_ZTV12CMdERelation @ 330 NONAME ABSENT ; #<VT>#
+	_ZTV13CMdECondition @ 331 NONAME ABSENT ; #<VT>#
+	_ZTV13CMdEObjectDef @ 332 NONAME ABSENT ; #<VT>#
+	_ZTV14CMdEEventQuery @ 333 NONAME ABSENT ; #<VT>#
+	_ZTV14CMdENotifierAO @ 334 NONAME ABSENT ; #<VT>#
+	_ZTV15CMdEObjectQuery @ 335 NONAME ABSENT ; #<VT>#
+	_ZTV15CMdEPropertyDef @ 336 NONAME ABSENT ; #<VT>#
+	_ZTV15CMdERelationDef @ 337 NONAME ABSENT ; #<VT>#
+	_ZTV15CMdESessionImpl @ 338 NONAME ABSENT ; #<VT>#
+	_ZTV16CMdEInstanceItem @ 339 NONAME ABSENT ; #<VT>#
+	_ZTV16CMdENamespaceDef @ 340 NONAME ABSENT ; #<VT>#
+	_ZTV17CMdERelationQuery @ 341 NONAME ABSENT ; #<VT>#
+	_ZTV18CMdEEventCondition @ 342 NONAME ABSENT ; #<VT>#
+	_ZTV18CMdEEventQueryImpl @ 343 NONAME 
+	_ZTV18CMdELogicCondition @ 344 NONAME ABSENT ; #<VT>#
+	_ZTV19CMdEObjectCondition @ 345 NONAME ABSENT ; #<VT>#
+	_ZTV19CMdEObjectQueryImpl @ 346 NONAME ABSENT ; #<VT>#
+	_ZTV20CMdEHarvesterSession @ 347 NONAME ABSENT ; #<VT>#
+	_ZTV20CMdESessionStartupAO @ 348 NONAME ABSENT ; #<VT>#
+	_ZTV21CMdEPropertyCondition @ 349 NONAME ABSENT ; #<VT>#
+	_ZTV21CMdERelationCondition @ 350 NONAME ABSENT ; #<VT>#
+	_ZTV21CMdERelationQueryImpl @ 351 NONAME 
+	_ZTV22CMdEAsynchronousFindAO @ 352 NONAME ABSENT ; #<VT>#
+	_ZTV23CMdESessionAsyncHandler @ 353 NONAME ABSENT ; #<VT>#
+	_ZTV25CMdEBoolPropertyCondition @ 354 NONAME ABSENT ; #<VT>#
+	_ZTV25CMdETextPropertyCondition @ 355 NONAME ABSENT ; #<VT>#
+	_ZTV30CMdEQueryCriteriaSerialization @ 356 NONAME ABSENT ; #<VT>#
+	_ZTV8CMdEItem @ 357 NONAME ABSENT ; #<VT>#
+	_ZTV9CMdEEvent @ 358 NONAME ABSENT ; #<VT>#
+	_ZTV9CMdEQuery @ 359 NONAME ABSENT ; #<VT>#
+	_ZN20CMdEHarvesterSession10GetPendingEPK13CMdEObjectDefRiR23CMdCSerializationBuffer @ 360 NONAME
+	_ZN20CMdEHarvesterSession15GetPendingCountEPK13CMdEObjectDef @ 361 NONAME
+	_ZN20CMdEHarvesterSession19ChangeCDriveMediaIdEv @ 362 NONAME
+	_ZN20CMdEHarvesterSession11SetPendingLERK6RArrayImE @ 363 NONAME
+	_ZN20CMdEHarvesterSession13ResetPendingLERK6RArrayImE @ 364 NONAME
+	_ZN19CMdEObjectCondition18SetPlaceholderOnlyEi @ 365 NONAME
+	_ZNK19CMdEObjectCondition15PlaceholderOnlyEv @ 366 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+mdeclient.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/group/mdeclient.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,89 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION         10.0
+TARGET          mdeclient.dll
+TARGETTYPE      dll
+TARGETPATH	    /sys/bin
+UID             0x1000008d 0x200009F1	
+
+CAPABILITY	    CAP_CLIENT_DLL
+VENDORID        VID_DEFAULT
+
+USERINCLUDE     ../../../inc
+USERINCLUDE     ../inc
+
+#if defined(WINSCW)
+    deffile ../bwincw/mdeclientu.def
+#elif defined(ARMCC)
+    deffile ../eabi/mdeclientu.def
+#endif
+nostrictdef
+
+SOURCEPATH      		../src
+SOURCE          		mde.cpp
+SOURCE          		mdepanic.cpp
+SOURCE	    		mdedatabuffer.cpp
+SOURCE	    		mdesession.cpp
+SOURCE	    		mdeharvestersession.cpp
+SOURCE	    		mdeitem.cpp
+SOURCE	    		mdepropertydef.cpp
+SOURCE	    		mdeobjectdef.cpp
+SOURCE	    		mderelationdef.cpp
+SOURCE	    		mdeeventdef.cpp
+SOURCE			mdeinstanceitem.cpp
+SOURCE			mdeobject.cpp
+SOURCE			mdeproperty.cpp
+SOURCE			mderelation.cpp
+SOURCE			mdeevent.cpp
+SOURCE			mdequery.cpp
+SOURCE			mdeobjectquery.cpp
+SOURCE			mderelationquery.cpp
+SOURCE			mdeeventquery.cpp
+SOURCE			mdeorderrule.cpp
+SOURCE			mdecondition.cpp
+SOURCE			mdelogiccondition.cpp
+SOURCE			mdeobjectcondition.cpp
+SOURCE			mdepropertycondition.cpp
+SOURCE			mdetextpropertycondition.cpp
+SOURCE			mdeboolpropertycondition.cpp
+SOURCE			mderelationcondition.cpp
+SOURCE			mdeeventcondition.cpp
+SOURCE			mdequerycriteriaserialization.cpp
+SOURCE          		mdenamespacedef.cpp
+SOURCE          		mderange.cpp
+SOURCE          		mderangepropertycondition.cpp
+SOURCE          		mdesessionstartupao.cpp
+SOURCE	    		mdesessionimpl.cpp
+SOURCE	    		mdeenginesession.cpp
+SOURCE          		mdequeryimpl.cpp
+SOURCE          		mdeasynchronousfindao.cpp
+SOURCE          		mdenotifierao.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         	euser.lib
+LIBRARY         	bafl.lib
+LIBRARY     	mdccommon.lib
+
+DEBUGLIBRARY    flogger.lib
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/inc/mdeasynchronousfindao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,164 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Asynchronous query active object
+*
+*/
+
+
+#ifndef __MDEASYNCHRONOUSFINDAO_H__
+#define __MDEASYNCHRONOUSFINDAO_H__
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include <badesca.h>
+
+#include <mdccommon.h>
+
+// forward declarations
+class CMdEQuery;
+class CMdESessionImpl;
+class RMdEEngineSession;
+class CMdEInstanceItem;
+class CMdEQueryCriteriaSerialization;
+
+/**
+* MdESessionMonitorAO
+* An abstract active object that is used for multiple purposes in
+* MdE client side.
+*/
+NONSHARABLE_CLASS(CMdEAsynchronousFindAO) : public CActive
+    {
+    public: // Constructors and destructors
+
+        /**
+        * NewL.
+        * Two-phased constructor.
+        * Creates a CCSAsyncRequestHandler object using two phase construction,
+        * and return a pointer to the created object.
+        * @param aSession The engine session
+        * @param aType the query type
+        * @return A pointer to the created instance of CCSAsyncRequestHandler.
+        */
+        static CMdEAsynchronousFindAO* NewL( CMdEQuery& aQuery,
+            CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession );
+
+        /**
+         * NewL.
+         * Two-phased constructor.
+         * Creates a CCSAsyncRequestHandler object using two phase construction,
+         * and return a pointer to the created object.
+         * @param aSession The engine session
+         * @param aType the query type
+         * @return A pointer to the created instance of CCSAsyncRequestHandler.
+         */
+         static CMdEAsynchronousFindAO* NewLC( CMdEQuery& aQuery,
+             CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession );
+
+        /**
+        * ~CCSAsyncRequestHandler.
+        * Destructor.
+        * Destroys the object and release all memory objects.
+        */
+        virtual ~CMdEAsynchronousFindAO();
+
+    public: // New functions
+
+        /**
+        * Starts find
+        */
+        void DoFindL( TUint aMaxCount, TUint aNotifyCount );
+
+    protected: // Functions from base classes
+
+	    /**
+	     * Calls notify results on CMdEQuery class (one of its subclasses)
+	     * @param aStatus the asynchronous find status
+	     */
+	    void DoNotifyResultsL( TInt aStatus );
+    
+        /**
+        * Calls notify on CMdEQuery class (one of its subclasses)
+        * @param aStatus the asynchronous find status
+        */
+        void DoNotifyL( TBool aNewResults, TInt aStatus );
+
+        /**
+        * From CActive
+        * Callback function.
+        * Invoked to handle responses from the server.
+        */
+        void RunL();
+
+		/**
+		* From CActive
+		*/
+		TInt RunError(TInt aError);
+
+        /**
+        * From CActive
+        * Cancels any outstanding operation.
+        */
+        void DoCancel();
+
+    private: // Constructors and destructors
+
+        /**
+        * CCSAsyncRequestHandler.
+        * Performs the first phase of two phase construction.
+        * @param aSession The engine session
+        * @param aType the query type
+        */
+        CMdEAsynchronousFindAO( CMdEQuery& aQuery,
+            CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession );
+
+        /**
+        * ConstructL.
+        * Performs the second phase construction of a
+        * CCSAsyncRequestHandler object.
+        */
+        void ConstructL();
+
+
+    private: // Data
+
+        /** the query object */
+        CMdEQuery& iQuery;
+
+        /** The session impl class */
+        CMdESessionImpl& iSessionImpl;
+
+        /** The engine session */
+        RMdEEngineSession& iSession;
+
+        /** package that will receive result hierarchy size */
+        TPckgBuf<TInt> iResultSize;
+
+        /** query results (stored here only temporarily) */
+        RPointerArray<CMdEInstanceItem> iResultList;
+
+        /** ID query results (stored here only temporarily) */
+        RArray<TItemId> iIdResultList;
+
+        /** Count query result */
+        TUint32 iCountResult;
+
+		CMdEQueryCriteriaSerialization* iConditionBuffer;
+
+		/** distinct query results (stored here only temporarily) */
+		CDesCArray* iDistinctResults;
+    };
+
+
+#endif //__MDEASYNCHRONOUSFINDAO_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/inc/mdeengine.pan	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef __MDECLIENT_PAN__
+#define __MDECLIENT_PAN__
+
+/** Panic Category */
+_LIT( KMdEEngine, "MdEEngine" );
+
+/** CSAsync application panic codes */
+enum TMdEEnginePanics
+    {
+    EMdEEngineBasicUi = 1,
+    EMdEEngineProgram,
+    EMdEEngineBadState
+    };
+
+#endif // __MDECLIENT_PAN__
+
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/inc/mdeenginesession.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,528 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is Metadata engine client session file
+*
+*/
+
+
+#ifndef __MDEENGINESESSION_H__
+#define __MDEENGINESESSION_H__
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <e32base.h>
+#include <badesca.h>
+
+#include "mdscommoninternal.h"
+#include "mdequery.h"
+#include "mdeharvestersession.h"
+
+// CONSTANTS
+// Number of message slots to reserve for this client server session.
+// 27 = 1 asynchronous find + max.25 pending notifier hooks + 1 extra
+const TUint KMetadataMessageSlots = 27;
+
+const TUid KServerUid3 = { 0x0765EEC3 }; // Server UID
+
+_LIT( KMdSServerFilename, "MdSServer" );
+
+#ifdef __WINS__
+static const TUint KServerMinHeapSize = 0x10000;
+static const TUint KServerMaxHeapSize = 0x400000; // ~4 megs
+#endif
+
+// FORWARD DECLARATIONS
+class CMdESessionImpl;
+class CMdESchemaItem;
+class CMdEInstanceItem;
+class CMdEQuery;
+class CMdEQueryCriteriaSerialization;
+class CMdCSerializationBuffer;
+class TMdEObject;
+
+// CLASS DECLARATION
+/**
+* RMdEEngineSession
+*  This class provides the client-side interface to the server session
+*/
+class RMdEEngineSession : public RSessionBase
+    {
+    public: // Constructors and destructors
+
+        /**
+        * RMdEEngineSession.
+        * Constructs the object.
+        */
+        RMdEEngineSession(CMdESessionImpl& aSession);
+
+    public: // New functions
+
+        /**
+        * Open server.
+        * Connects to the server.
+        * @return Error code.
+        */
+        void OpenL(TRequestStatus& aStatus);
+        
+        /**
+        * Cancel server opening.
+        * Cancels server opening.
+        * @return Error code.
+        */
+       void OpenCancel(TRequestStatus& aStatus);
+
+        /**
+        * Connect session to server.
+        * Create a session.
+        * @return Error code.
+        */
+        void ConnectL();
+
+        /**
+        * Shut down session
+        * Performs session shutdown activities in server end
+        * @return Error code.
+        */
+        TInt Shutdown();
+
+        /**
+        * Version.
+        * Gets the version number.
+        * @return The version.
+        */
+        TVersion Version() const;
+
+        /**
+         * Adds an event definition to the database.
+         * @param aNameSpaceId id of the namespace to add the definition into
+         * @param aName name of the event
+         */
+		void DoAddEventDefL(const TDefId aNameSpaceId, const TDesC &aName );
+
+		/**
+		 * Adds a relation definition to the database.
+		 * @param aNameSpaceId id of the namespace to add the definition into
+		 * @param aName name of the relation
+		 */
+		void DoAddRelationDefL(const TDefId aNameSpaceId, const TDesC &aName );
+
+		/**
+		 * Adds items to the database.
+		 * @param aSerializedBuffer items serialized in a buffer
+		 * @param aResultBuffer on return contains serialized results
+		 */
+        void DoAddItemsL( const CMdCSerializationBuffer& aSerializedBuffer, CMdCSerializationBuffer& aResultBuffer );
+
+        /**
+		 * Adds items to the database asynchronously.
+		 * @param aSerializedBuffer items serialized in a buffer
+		 * @param aResultBuffer on return contains serialized results
+		 * @param aStatus the asynchronous response status
+		 */
+        void DoAddItemsAsync( const CMdCSerializationBuffer& aSerializedBuffer, CMdCSerializationBuffer& aResultBuffer, TRequestStatus& aStatus );
+
+        /**
+		 * Removes items from the database.
+		 * @param aRemoveId item ids serialized in a buffer
+		 * @param aSuccessfulId on return contains ids of successfully remove items in a serialization buffer.
+		 */
+        void DoRemoveItemsL( const CMdCSerializationBuffer& aRemoveId, CMdCSerializationBuffer& aSuccessfulId );
+
+        /**
+		 * Removes items from the database asynchronously.
+		 * @param aRemoveId item ids serialized in a buffer
+		 * @param aSuccessfulId on return contains ids of successfully remove items in a serialization buffer.
+		 * @param aStatus the asynchronous response status
+		 */
+        void DoRemoveItemsAsync( const CMdCSerializationBuffer& aRemoveId, CMdCSerializationBuffer& aSuccessfulId, TRequestStatus& aStatus );
+
+        /**
+         * Updates items in the database.
+         * @param aSerializedBuffer serialized buffer of updated items
+         * @param aResultBuffer on return contains serialized results
+         */
+        void DoUpdateItemsL( const CMdCSerializationBuffer& aSerializedBuffer, CMdCSerializationBuffer& aResultBuffer );
+
+        /**
+         * Updates items in the database asynchronously.
+         * @param aSerializedBuffer serialized buffer of updated items
+         * @param aResultBuffer on return contains serialized results
+         * @param aStatus the asynchronous response status
+         */
+        void DoUpdateItemsAsync( const CMdCSerializationBuffer& aSerializedBuffer, CMdCSerializationBuffer& aResultBuffer, TRequestStatus& aStatus );
+
+        /**
+         * Finds objects synchronously.
+         * @param aQuery the query
+         * @param aSerializationBuffer query criterias serialiazed in a buffer
+         * @param aLocktype how the object should be locked during the query
+         * @param aNotifyCount count indicating how often the client should be notified
+         */
+        CMdCSerializationBuffer* DoFindSyncLC( 
+        	const CMdEQuery* aQuery, 
+        	const CMdEQueryCriteriaSerialization& aSerializationBuffer,
+            TMdCQueryLockType aLocktype,TUint32 aNotifyCount);
+            
+        /**
+        * Finds objects asynchronously
+        * @param 
+        * @param 
+        * @param 
+        * @param aAsyncStatus the asynchronous response status
+        */
+        void DoFindAsync(
+        	TUint32 aQueryId, 
+            const CMdEQueryCriteriaSerialization& aSerializationBuffer,
+            TPckgBuf<TInt>* aSizeBuf,
+            TRequestStatus& aAsyncStatus, 
+            TUint32 aNotifyCount = KMdEQueryDefaultMaxCount);
+
+        /**
+        * Continues a step in an existing asynchronous find
+        * @param 
+        * @param 
+        * @param aAsyncStatus the asynchronous response status
+        */
+        void DoFindContinue( 
+        	const CMdEQuery* aQuery, 
+            TPckgBuf<TInt>* aSizeBuf,
+            TRequestStatus& aAsyncStatus );
+
+        /**
+        * Cancels ongoing find
+        */
+        void DoFindCancelL( const CMdEQuery* aQuery );
+
+        /**
+        * Registers for notifications
+        */
+        void DoRegisterL( TInt aId,
+            TUint32 aType,
+            CMdCSerializationBuffer& aBuffer,
+            TDefId aNamespaceDefId );
+
+        /**
+        * Continues registration for more notifications
+        */
+        void DoListen( TInt aId,
+            TPckgBuf<TInt>* aSizeBuf,
+            TRequestStatus& aAsyncStatus );
+
+        /**
+        * Unregisters observer for no more notifications
+        */
+        void DoUnregisterL( TInt aId );
+
+        /**
+        * DoLoadSchemaL.
+        * Gets find results to client 
+        * @param aHandle handle to shared memory chunk
+        */
+        void DoLoadSchemaL( TInt& aHandle );
+
+        /**
+        * DoGetDataL.
+        * Gets data to client.
+        * @param aQuery the query ID
+        * @param aSize number of bytes to reserve for hierarchy
+        * @param aRelatedCommand command related to which the data is obtained.
+        * @param aExtraData an optional id specifying the identity of the data to obtain.
+        */
+		void DoGetDataL( const CMdEQuery* aQuery, 
+			CMdCSerializationBuffer* aResultBuffer, 
+			TUint32 aRelatedCommand, TUint32 aExtraData = 0 );
+        /**
+        * DoGetDataL.
+        * Gets data from the server for a notifier AO
+        * @param aBuffer The data buffer to read to from the server
+        * @param aId The id of the observer requesting the data
+        */
+		void DoGetDataL( CMdCSerializationBuffer& aBuffer, TUint32 aId );
+
+		void DoCheckObjectL( CMdCSerializationBuffer& aObjectBuffer, 
+				const TDesC& aUri, TDefId aNamespaceDefId );
+
+		void DoCheckObjectL( CMdCSerializationBuffer& aObjectBuffer, 
+				TItemId aId, TDefId aNamespaceDefId );
+
+		void DoCheckObjectL( CMdCSerializationBuffer& aObjectsBuffer, 
+				const CMdCSerializationBuffer& aObjectIdsBuffer, 
+				TDefId aNamespaceDefId );
+
+        /**
+        * Commits changes to objects to database
+        * @param aCodedObjects objects in coded form
+        */
+        void DoCommitObjectsL( const CMdCSerializationBuffer& aCodedObjects );
+
+        /**
+        * Cancels changes to object to database
+        * @param aCodedId id of locked object in coded form
+        */
+        void DoCancelObjectL( CMdCSerializationBuffer& aRemoveId );
+
+        /**
+         * Imports schema from a file.
+         * @param aFilename schema file name
+         */
+        void DoImportSchemaL( const TDesC& aFileName );
+    
+        /**
+         * Imports metadata from a file.
+         * @param aFilename metadata file name
+         */
+        TInt DoImportMetadataL( const TDesC& aFileName );
+
+        /**
+         * Imports metadata from a file asynchronously.
+         * @param aFilename metadata file name
+         * @param aResult packaged error code
+         * @param aStatus asynchronous request status
+         */
+        void DoImportMetadata( const TDesC& aFileName, TPckgBuf<TInt>& aResult, TRequestStatus& aStatus );
+
+        /**
+         * Exports metadata into a file.
+         * @param aFilename metadata file name
+         * @param aItems items to export in a serialized buffer
+         */
+        void DoExportMetadataL( const TDesC& aFileName, const CMdCSerializationBuffer& aItems );
+
+        /**
+         * Exports metadata into a file asynchronously.
+         * @param aFilename metadata file name
+         * @param aItems items to export in a serialized buffer
+         * @param aStatus asynchronous request status
+         */
+        void DoExportMetadataL( const TDesC& aFileName, const CMdCSerializationBuffer& aItems,
+								TRequestStatus& aStatus);
+
+        /**
+    	 * Add memory card with given media ID and current time. If memory card 
+    	 * already exist only time is updated to current time.
+    	 * @param memory card's media ID
+    	 */
+		void DoAddMemoryCard(TUint32 aMediaId);
+
+		/**
+		 * Get latest memory card's media ID.
+		 * @param returned memory card's media ID
+		 * @return EFalse if there is no any memory cards added
+		 */
+		TBool DoGetMemoryCard(TUint32& aMediaId);
+		
+	    /**
+		 * Check if there is memory card with given media ID.
+		 * @param memory card's media ID
+		 * @param returned boolean if memory card exists or not
+		 * @return EFalse if there was error
+		 */
+		TBool DoCheckMemoryCard(TUint32 aMediaId, TBool& aExist);
+
+		/**
+		 * Set media's media ID, drive and present state.
+		 * 
+		 * @param media's media ID
+		 * @param media's drive
+		 * @param media's present state
+		 */
+		void DoSetMediaL(TUint32 aMediaId, TChar aDrive, TBool aPresentState);
+
+		/**
+		 * Get media's drive and present state by media ID.
+		 * 
+		 * @param aMediaId media's media ID
+		 * @param aDrive returned media's drive
+		 * @param aPresent returned media's present state
+		 * @return EFalse if there is no media with matching media ID in DB
+		 */
+		TBool DoGetMediaL(TUint32 aMediaId, TChar& aDrive, 
+				TBool& aPresentState);
+
+	    /**
+		 * Get present medias' media IDs and drives.
+		 * 
+		 * @param aMedias returned present medias' media IDs and drives
+		 */
+		void DoGetPresentMediasL(RArray<TMdEMediaInfo>& aMedias);
+		
+		/**
+	     * Set file to present state.
+	     *
+	     * @param aMediaId file's media ID
+	     * @param aUri file's URI
+	     * @param aFileInfo file's modified date and byte size
+	     *
+	     * @return ETrue if file existed and changing to present state was 
+	     *               successful
+	     */
+		TBool DoSetFileToPresent(TUint32 aMediaId, const TDesC& aUri, 
+				TMdSFileInfo& aFileInfo);
+
+		/**
+		 * Set files to present state.
+		 * 
+		 * @param aMediaIdAndCount files' media ID and file count
+		 * @param aUris serialized files' URIs
+		 * @param aFileInfos serialized files' modified dates and byte sizes
+		 * @param aResults serialized values from TFilePresentStates
+		 * 
+		 * @return Error code
+		 */
+		TInt DoSetFilesToPresent(TMdSMediaIdAndCount aMediaIdAndCount, 
+				const TDes8& aUris, const TDes8& aFileInfos, TDes8& aResults);		
+		
+		
+		/**
+		 * Set all files, which media ID is given, to not present state.
+		 *
+		 * @param aMediaId media ID
+		 * @param aStartUp is start up or normal unmount
+		 */		
+		void DoSetFilesToNotPresent(TUint32 aMediaId, TBool aStartUp);
+
+		/**
+	     * Remove all objects, which are in not present state, with given media ID
+	     * 
+		 * @param aMediaId media ID
+		 * @param aStartUp is start up or normal mount
+	     */
+		void DoRemoveFilesNotPresent(TUint32 aMediaId, TBool aStartUp);
+
+		/**
+		 * Get schema version's major and minor version.
+		 *
+		 * @param aMajorVersion returned major version
+		 * @param aMinorVersion returned minor version
+		 */
+		void DoGetSchemaVersionL(TInt& aMajorVersion, TInt& aMinorVersion);
+
+		/**
+		 * Set object to "present" state by GUID.
+		 *
+		 * @param aGuidHigh Guid's high part
+		 * @param aGuidLow Guid's low part
+		 * 
+		 * @leave KErrNotFound MdE can't find object in "not present" state 
+		 *                     with matching GUID
+		 * 
+		 */
+		void DoSetObjectToPresentByGuidL( 
+				const TInt64& aGuidHigh, const TInt64& aGuidLow );
+		
+		/**
+		 * Set global harvester prioritization chunk to MdE Server. There can 
+		 * be only one chunk and observer at once. If MdE Server already 
+		 * contains active observer, old observer completes with KErrAbort, 
+		 * chunk is always changed to this new one. Observer is added using 
+		 * DoAddHarvestingPrioritizationObserver.
+         * @param aHandle the handle of global chunk that will receive object 
+         *                URIs which need to be prioritize
+         */
+		void DoSetHarvestingPrioritizationChunkL( RHandleBase aHandle );
+
+		/**
+		 * Add harvester prioritization observer to MdE Server. There can be 
+		 * only one chunk and observer at once. If MdE Server already contains 
+		 * active observer, aStatus completes with KErrAlreadyExists. When MdE 
+		 * Server needs prioritize object, aStatus completes with KErrNone.
+         * @param aStatus the asynchronous response status which is changed 
+         *                when there is object URIs to be prioritize
+		 */
+		void DoAddHarvestingPrioritizationObserver( TRequestStatus& aStatus );
+
+		/**
+		 * Cancel harvester prioritization observer from MdE Server. 
+		 * @return If MdE Server doesn't have outstanding observer method 
+		 *         returns KErrNotFound, otherwise KErrNone is returned.
+		 */
+		TInt DoCancelHarvestingPrioritizationObserver();
+		
+		/**
+		 * Change path of objects.
+		 * 
+		 * @param aOldPath old path
+		 * @param aNewPath new path
+	     * @param aStatus the asynchronous response status which is changed when 
+	     *                URIs are changed
+		 */
+		void DoChangePath( const TDesC& aOldPath, const TDesC& aNewPath,
+				TRequestStatus& aStatus );
+		
+		/**
+		 * Change C-drive media id to MdS_Medias table and update it to all objects.
+		 */
+		void DoChangeCDriveMediaId();
+		
+		/**
+		 * Set "binary composing to file" pending flag to objects
+		 *
+		 * @param aObjectId object IDs
+		 */
+		void DoSetPendingL( const RArray<TItemId>& aObjectIds );
+
+		/**
+		 * Reset "binary composing to file" pending flag from objects
+		 *
+		 * @param aObjectId object IDs
+		 */
+		void DoResetPendingL( const RArray<TItemId>& aObjectIds );
+
+		/**
+		 * Get count of objects with "binary composing to file" pending flag
+		 *
+		 * @param aObjectDef object definition which limits what objects are
+		 *                   returned or NULL when all objects are returned
+		 * 
+		 * @return count of objects
+		 */
+		TInt DoGetPendingCount( const CMdEObjectDef* aObjectDef );
+		
+		/**
+		 * Get IDs from objects with "binary composing to file" pending flag
+		 *
+		 * @param aObjectDef object definition which limits what objects are
+		 *                   returned or NULL when all objects are returned
+		 * @param aObjectIdCount count of returned object IDs
+		 * @param aObjectIdBuffer serialized buffer of returned object IDs
+		 * 
+		 * @return If returned value is > 0, buffer is not large enough for 
+		 * 		    objects ID from DB, otherwise error code is returned.
+		 */
+		TInt DoGetPending( const CMdEObjectDef* aObjectDef, 
+				TInt& aObjectIdCount, 
+				CMdCSerializationBuffer& aObjectIdBuffer );
+		
+		/**
+		 * Resets DB
+		 * only for internal purpose and DEBUG ONLY!!
+		 */
+		void DoResetDBL();
+		
+		/**
+		 * Check if there was error in client-server communication and notify
+		 * session if needed.
+		 */
+		void NotifySessionError( TInt aError );
+		
+    private: // Data
+    	CMdESessionImpl& iSession;
+    
+		RProcess iServerProcess;
+
+		TBool iIsSessionOpen;
+		TBool iIsSessionProcessOpen;
+    };
+
+#endif // __MDEENGINESESSION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/inc/mdenotifierao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,164 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Notifier client side active object
+*
+*/
+
+
+#ifndef __MDENOTIFIERAOAO_H__
+#define __MDENOTIFIERAOAO_H__
+
+// INCLUDE FILES
+#include <e32base.h>
+
+#include "mdccommon.h"
+#include "mdecondition.h"
+
+
+// forward declarations
+class RMdEEngineSession;
+class CMdESessionImpl;
+class CMdENamespaceDef;
+class CMdERelation;
+class TMdERelation;
+
+// local constants
+const TInt KDefaultBufferSize = 1024; // 1 KB
+/**
+* CMdENotifierAO
+* An active object that receives notifications from server
+* side whenever a registrated event has occurred.
+*/
+NONSHARABLE_CLASS(CMdENotifierAO) : public CActive
+    {
+    public: // Constructors and destructors
+
+		/**
+		 * Two-phased constructor.
+		 * @param aSessionImpl session impl
+		 * @param aSession the server handler
+		 * @return the created instance
+		 */
+		 static CMdENotifierAO* NewL(
+		     CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession );
+
+        /**
+        * Two-phased constructor.
+        * @param aSessionImpl session impl
+        * @param aSession the server handler
+        * @return the created instance
+        */
+        static CMdENotifierAO* NewLC(
+            CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CMdENotifierAO();
+
+        /**
+        * register for receiving events
+        * @param aMode observer mode: object, event or relation
+        * @param aObserver observer to be notified when event occurs
+        * @param aCondition condition when to notify
+        */
+        void RegisterL( TUint32 aType, TAny* aObserver, CMdECondition* aCondition, CMdENamespaceDef& aNamespaceDef );
+
+        /**
+        * compares an observer against one stored in this AO
+        * @param aMode observer mode: object, event or relation
+        * @param aObserver observer pointer
+        */
+        TBool Match( TUint32 aType, TAny* aObserver, CMdENamespaceDef& aNamespaceDef );
+
+        /**
+        * ID of this client side notifier object
+        */
+        TInt Id();
+
+    protected: // Functions from base classes
+
+        /**
+        * From CActive
+        * Callback function.
+        * Invoked to handle responses from the server.
+        */
+        void RunL();
+
+        /**
+        * From CActive
+        * Handles errors that occur during notifying the observer.
+        */
+        TInt RunError(TInt aError);
+
+        /**
+        * From CActive
+        * Cancels any outstanding operation.
+        */
+        void DoCancel();
+
+    private: // Constructors and destructors
+
+        /**
+        * constructor
+        * @param aSessionImpl session impl
+        * @param aSession the server handler
+        */
+        CMdENotifierAO(
+            CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession );
+
+        /**
+        * 2nd phase constructor
+        */
+        void ConstructL();
+
+        /**
+        * notify the corresponding client observer pointer
+        * @param aItem the item (in coded form) to be notified
+        * @param aStatus what has actually happened with the item
+        */
+        void DoNotifyObserver();
+		
+		
+		void DecodeIdBufferL();
+		void DecodeRelationItemBufferL();
+
+    private: // Data
+
+        /** the session impl. */
+        CMdESessionImpl& iSessionImpl;
+
+        /** the session */
+        RMdEEngineSession& iSession;
+
+        /** observer to be notified, actual class depends on type */
+        TAny* iObserver;
+
+        /** notifier type */
+        TUint32 iType;
+
+		/** Namespace definition's ID */
+        TDefId iNamespaceDefId;
+
+        /** size of result block */
+        TPckgBuf<TInt> iResultSize;
+
+        CMdCSerializationBuffer* iDataBuffer;
+
+		RArray<TItemId> iIdArray;
+
+		RArray<TMdERelation> iRelationItemArray;
+    };
+
+#endif //__MDENOTIFIERAOAO_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/inc/mdequerycriteriaserialization.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,179 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Serialize query criteria
+*
+*/
+
+#ifndef __MDEQUERYCRITERIASERIALIZATION_H__
+#define __MDEQUERYCRITERIASERIALIZATION_H__
+
+#include <e32cmn.h>
+#include <e32def.h>
+#include <e32des8.h>
+
+#include "mdccommon.h"
+#include "mdcserializationbuffer.h"
+#include "mdeorderrule.h"
+#include "mdscommoninternal.h"
+
+
+// forward declaration
+class CMdELogicCondition;
+class CMdENamespaceDef;
+class CMdEObjectDef;
+
+
+/**
+ * Query criteria serialization.
+ */
+NONSHARABLE_CLASS(CMdEQueryCriteriaSerialization) : public CBase
+	{
+	friend class CMdSFindSqlClause;
+	
+public:
+
+	/* Constructors and destructor. */
+
+	/**
+	 * Constructs a new serialized query criteria.
+	 * @param aResultMode Query's result type
+	 * @param aQueryType  Type of query
+	 * @param aNamespaceDef namespace definition
+	 * @param aObjectDef 
+	 * @param aObjectDefs
+	 * @param aLimit 
+	 * @param aOffset
+	 * @param aQueryOptimizationFlags query optimization flags
+	 * @param aRootCondition the root condition
+	 * @param aOrderRule array of order rules
+	 * @param aPropertyFilter array of property filters
+	 * 
+	 * @return  query criteria serialization instance
+	 *
+	 * @leave KErrNotSupported result mode and query type don't match
+	 * @leave KErrCompletion   result mode is EModeDistinctValues and query 
+	 *                         criteria is incorrect
+	 */
+	static CMdEQueryCriteriaSerialization* NewL(
+		TQueryResultMode aResultMode, 
+		TQueryType aQueryType, CMdENamespaceDef& aNamespaceDef, 
+		CMdEObjectDef* aObjectDef, RPointerArray<CMdEObjectDef>* aObjectDefs, 
+		TUint32 aLimit, TUint32 aOffset, TUint32 aQueryOptimizationFlags, 
+		CMdELogicCondition& aRootCondition, 
+		RArray<TMdEOrderRule>& aOrderRule, RPointerArray<CMdEPropertyDef>* aPropertyFilter);
+
+	/**
+	 * Constructs a new serialized query criteria and leaves it in the
+	 * cleanup stack.
+	 * @param aResultMode Query's result type
+	 * @param aQueryType  Type of query
+	 * @param aNamespaceDef namespace definition
+	 * @param aObjectDef 
+	 * @param aObjectDefs
+	 * @param aLimit 
+	 * @param aOffset
+	 * @param aQueryOptimizationFlags query optimization flags
+	 * @param aRootCondition the root condition
+	 * @param aOrderRule array of order rules
+	 * @param aPropertyFilter array of property filters
+	 *
+	 * @return  query criteria serialization instance
+	 *
+	 * @leave KErrNotSupported result mode and query type don't match
+	 * @leave KErrCompletion   result mode is EModeDistinctValues and query 
+	 *                         criteria is incorrect
+	 */
+	static CMdEQueryCriteriaSerialization* NewLC(
+		TQueryResultMode aResultMode, 
+		TQueryType aQueryType, CMdENamespaceDef& aNamespaceDef, 
+		CMdEObjectDef* aObjectDef, RPointerArray<CMdEObjectDef>* aObjectDefs, 
+		TUint32 aLimit, TUint32 aOffset, TUint32 aQueryOptimizationFlags, 
+		CMdELogicCondition& aRootCondition, 
+		RArray<TMdEOrderRule>& aOrderRule, RPointerArray<CMdEPropertyDef>* aPropertyFilter);
+
+	/**
+	 * Constructs a new serialized query criteria.
+	 * @param aSerializationBuffer serialized query
+	 *
+	 * @return  query criteria serialization instance
+	 */
+	static CMdEQueryCriteriaSerialization* NewL(CMdCSerializationBuffer& aSerializationBuffer);
+
+	/**
+	 * Constructs a new serialized query criteria and leaves it in the
+	 * cleanup stack.
+	 * @param aSerializationBuffer serialized query
+	 *
+	 * @return  query criteria serialization instance
+	 */
+	static CMdEQueryCriteriaSerialization* NewLC(CMdCSerializationBuffer& aSerializationBuffer);
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEQueryCriteriaSerialization();
+
+    /**
+    * Returns pointer to the serialized data (read only)
+    */
+    TPtr8 Buffer() const;
+
+    /**
+    * Returns pointer to the serialized data (read only)
+    */
+    const TPtr8* BufferPtr() const;
+    
+    /**
+    * Returns pointer to the serialization buffer
+    */
+    CMdCSerializationBuffer& SerializationBuffer();
+
+private:
+
+	/* Constructors. */
+
+	/**
+	 * Constructor.
+	 */
+	CMdEQueryCriteriaSerialization(TBool aOwnSerializedBuffer);
+
+	/**
+	 * Second-phase constructor.
+	 *
+	 * @param aResultMode  result mode to serialize
+	 * @param aQueryType  query type to serialize
+	 * @param aLimit  limit to serialize
+	 * @param aOffset  offset to serialize
+	 * @param aCondition  root logic condition to serialize
+	 * @param aOrderRule  order rules to serialize
+	 * @param aPropertyFilter  property filters to serialize
+	 */
+	void ConstructL( TQueryResultMode aResultMode, TQueryType aQueryType, 
+					 CMdENamespaceDef& aNamespaceDef, 
+					 CMdEObjectDef* aObjectDef, RPointerArray<CMdEObjectDef>* aObjectDefs, 
+					 TUint32 aLimit, TUint32 aOffset, TUint32 aQueryOptimizationFlags, 
+					 CMdELogicCondition& aRootCondition, RArray<TMdEOrderRule>& aOrderRules, 
+					 RPointerArray<CMdEPropertyDef>* aPropertyFilter );
+	
+private:
+
+    /** Serialized query criteria. */
+    CMdCSerializationBuffer* iSerializedBuffer;
+
+    /** Does own serialized buffer. */
+    const TBool iOwnSerializedBuffer;
+	};
+
+
+#endif  // __MDEQUERYCRITERIASERIALIZATION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/inc/mdequeryimpl.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,271 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of object, relation and event query
+*
+*/
+
+
+#ifndef __MDEQUERYIMPL_H__
+#define __MDEQUERYIMPL_H__
+
+#include "mdeobjectquery.h"
+#include "mderelationquery.h"
+#include "mdeeventquery.h"
+
+// Forward declaration
+class CMdESessionImpl;
+class CMdENamespaceDef;
+class CMdEObjectDef;
+class RMdEEngineSession;
+class CMdEAsynchronousFindAO;
+
+/**
+ * Object query implementation.
+ */
+NONSHARABLE_CLASS(CMdEObjectQueryImpl) : public CMdEObjectQuery
+	{
+public:
+
+    /* Constructors and destructor. */
+	/**
+	 * Two-phased constructor.
+	 */
+	static CMdEObjectQueryImpl* NewL( CMdESessionImpl& aSessionImpl, CMdENamespaceDef& aNamespaceDef, 
+			CMdEObjectDef& aObjectDef, RPointerArray<CMdEObjectDef>* aObjectDefs,
+			RMdEEngineSession& aSession );
+	
+	static CMdEObjectQueryImpl* NewLC( CMdESessionImpl& aSessionImpl, CMdENamespaceDef& aNamespaceDef, 
+			CMdEObjectDef& aObjectDef, RPointerArray<CMdEObjectDef>* aObjectDefs,
+			RMdEEngineSession& aSession );
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEObjectQueryImpl();
+
+
+    /* Methods. */
+
+    /**
+     * As in CMdEQuery.
+	 */
+    void DoFindL( TUint aMaxCount, TUint aNotifyCount );
+
+    /**
+     * Notifies results
+	 */
+    void DoNotifyResultsL( RPointerArray<CMdEInstanceItem>& aResultList );
+
+    /**
+     * Notifies results of id query
+	 */
+    void DoNotifyResultsL( RArray<TItemId>& aResultIdList );
+
+    /**
+     * Notifies result of distinct values query
+     */
+    void DoNotifyResultsL( CDesCArray& aResults );
+
+    /**
+     * Notifies result of count query
+	 */
+    void DoNotifyResults( TInt aResultCount );
+    
+    /**
+     * Notifies query completed
+	 */
+    void DoNotifyCompleted( TInt aError );
+
+protected:
+    
+    /**
+     * As in CMdEQuery.
+     */
+    void DoCancel();
+    
+private:
+	/**
+	 * Constructor. Note that new queries should be created using the factory
+	 * @param aSessionImpl the session
+	 */
+	CMdEObjectQueryImpl( CMdESessionImpl& aSessionImpl, CMdENamespaceDef& aNamespaceDef, 
+			CMdEObjectDef& aObjectDef, RPointerArray<CMdEObjectDef>* aObjectDefs );
+	
+	/**
+	 * Second-phase constructor.
+	 * @param aSession reference to the engine session
+	 */
+	void ConstructL( CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession );
+
+    
+private:
+
+	/** Asynchronous find support. */
+	CMdEAsynchronousFindAO* iAsyncFind;
+    };
+
+/**
+ * Relation query stub implementation.
+ */
+class CMdERelationQueryImpl
+    : public CMdERelationQuery
+	{
+public:
+
+    /* Constructors and destructor. */
+	/**
+	 * Two-phased constructor.
+	 */
+	static CMdERelationQueryImpl* NewL( CMdESessionImpl& aSessionImpl,
+			CMdENamespaceDef& aNamespaceDef, RMdEEngineSession& aSession );
+	
+	static CMdERelationQueryImpl* NewLC( CMdESessionImpl& aSessionImpl,
+			CMdENamespaceDef& aNamespaceDef, RMdEEngineSession& aSession );
+	
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdERelationQueryImpl();
+
+
+    /* Methods from CMdERelationQuery. */
+
+    /**
+     * As in CMdEQuery.
+	 */
+    void DoFindL( TUint aMaxCount, TUint aNotifyCount );
+
+    /**
+     * Notifies results
+	 */
+    void DoNotifyResultsL( RPointerArray<CMdEInstanceItem>& aResultList );
+
+    /**
+     * Notifies results of id query
+	 */
+    void DoNotifyResultsL( RArray<TItemId>& aResultIdList );
+
+    /**
+     * Notifies result of count query
+	 */
+    void DoNotifyResults( TUint32 aResultCount );
+
+    /**
+     * Notifies query completed
+	 */
+    void DoNotifyCompleted( TInt aError );
+
+protected:
+ 
+    /**
+     * As in CMdEQuery.
+     */
+    void DoCancel();
+    
+private:
+	/**
+	 * Constructs a new relation query in the specified session.
+	 * @param aSessionImpl the session
+	 */
+	CMdERelationQueryImpl( CMdESessionImpl& aSessionImpl, CMdENamespaceDef& aNamespaceDef );
+	
+	/**
+	 * Second-phase constructor.
+	 * @param aSession reference to the engine session
+	 */
+	void ConstructL( CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession );
+
+    
+private:
+
+	/** Asynchronous find support. */
+	CMdEAsynchronousFindAO* iAsyncFind;
+    };
+
+/**
+ * Event query implementation.
+ */
+class CMdEEventQueryImpl: public CMdEEventQuery
+	{
+public:
+
+    /* Constructors and destructor. */
+
+	static CMdEEventQueryImpl* NewL( CMdESessionImpl& aSessionImpl,
+		CMdENamespaceDef& aNamespaceDef, RMdEEngineSession& aSession );
+
+	static CMdEEventQueryImpl* NewLC( CMdESessionImpl& aSessionImpl,
+		CMdENamespaceDef& aNamespaceDef, RMdEEngineSession& aSession );
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdEEventQueryImpl();
+
+
+    /* Methods from CMdEEventQuery. */
+
+    /**
+     * As in CMdEQuery.
+	 */
+    void DoFindL( TUint aMaxCount, TUint aNotifyCount );
+
+    /**
+     * Notifies results
+	 */
+    void DoNotifyResultsL( RPointerArray<CMdEInstanceItem>& aResultList );
+
+    /**
+     * Notifies results of id query
+	 */
+    void DoNotifyResultsL( RArray<TItemId>& aResultIdList );
+
+    /**
+     * Notifies result of count query
+	 */
+    void DoNotifyResults( TUint32 aResultCount );
+
+    /**
+     * Notifies query completed
+	 */
+    void DoNotifyCompleted( TInt aError );
+
+protected:
+    
+    /**
+     * As in CMdEQuery.
+     */
+    void DoCancel();
+    
+private:
+	/**
+	 * Constructs a new event query in the specified session.
+	 * @param aSessionImpl the session
+	 */
+	CMdEEventQueryImpl( CMdESessionImpl& aSessionImpl, CMdENamespaceDef& aNamespaceDef );
+	
+	/**
+	 * Second-phase constructor. 
+	 * @param aSession reference to the engine session
+	 */
+	void ConstructL( CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession );
+
+    
+private:
+
+	/** Asynchronous find support. */
+	CMdEAsynchronousFindAO* iAsyncFind;
+	};
+
+#endif  // __MDEQUERYIMPL_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/inc/mdesessionimpl.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,672 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Metadata engine client session implementation*
+*/
+
+
+#ifndef __MDESESSIONIMPL_H__
+#define __MDESESSIONIMPL_H__
+
+#include "mdesession.h"
+#include "mdeenginesession.h"
+#include "mdscommoninternal.h"
+
+
+// forward declarations
+class CMdENotifierAO;
+class CMdEDataBuffer;
+class CMdCSerializationBuffer;
+class CMdESessionStartupAO;
+class CMdESessionAsyncHandler;
+
+class RMdESessionAsyncRequest
+	{
+		friend class CMdESessionAsyncHandler;
+	private:
+		enum TRequestType
+		{
+			EAddRequest,
+			EUpdateRequest,
+			ERemoveRequest
+		};
+	
+		RMdESessionAsyncRequest(TRequestType aRequestType, 
+			CMdCSerializationBuffer* aBuffer, 
+			CMdCSerializationBuffer& aResultBuffer,
+			TRequestStatus& aRequestStatus);
+		
+		void Close();
+
+	private:
+		TRequestType iRequestType;
+		CMdCSerializationBuffer* iBuffer;
+		CMdCSerializationBuffer* iResultBuffer;
+		TRequestStatus* iRequestStatus;
+	};
+
+NONSHARABLE_CLASS(CMdESessionAsyncHandler) : public CActive
+{
+public:
+	void AddRequest( CMdCSerializationBuffer* aBuffer,
+			CMdCSerializationBuffer& aResultBuffer, 
+			TRequestStatus& aRequestStatus );
+
+	void UpdateRequest( CMdCSerializationBuffer * aBuffer,
+			CMdCSerializationBuffer& aResultBuffer,
+			TRequestStatus& aRequestStatus );
+
+	void RemoveRequest( CMdCSerializationBuffer* aBuffer,
+			CMdCSerializationBuffer& aResultBuffer,
+			TRequestStatus& aRequestStatus );
+		
+	static CMdESessionAsyncHandler* NewL(CMdESessionImpl& aSession, 
+			RMdEEngineSession &aEngineSession);
+		
+	static CMdESessionAsyncHandler* NewLC( CMdESessionImpl& aSession, 
+			RMdEEngineSession &aEngineSession );
+		
+	~CMdESessionAsyncHandler();
+		
+	
+private:	
+	void RunL();
+
+	TInt RunError(TInt aError);
+
+	void DoCancel();
+
+	CMdESessionAsyncHandler(CMdESessionImpl& aSession, 
+			RMdEEngineSession &aEngineSession);
+
+	void ConstructL();
+
+private:
+	RArray<RMdESessionAsyncRequest> iRequests;
+	CMdESessionImpl& iSession;
+	RMdEEngineSession& iEngineSession;
+};
+
+/**
+ * Metadata engine session implementation.
+ */
+NONSHARABLE_CLASS(CMdESessionImpl) : public CMdESession
+	{
+	friend class CMdESessionStartupAO;
+
+    public: // Constructors and destructor.
+
+    	/**
+    	 * Constructor.
+    	 *
+    	 * @param aObserver observer to notify when opening the session has 
+    	 *                  been completed
+    	 */
+    	CMdESessionImpl( MMdESessionObserver& aObserver );
+
+    	/**
+    	 * Second-phase constructor.
+    	 */
+    	void ConstructL();
+
+    	/**
+    	 * Destructor.
+    	 */
+    	virtual ~CMdESessionImpl();
+
+		/** From MdESession */
+		TInt NamespaceDefCount() const;
+
+		/** From MdESession */
+		CMdENamespaceDef& NamespaceDefL(TInt aIndex);
+
+		/** From MdESession */
+		CMdENamespaceDef& GetNamespaceDefL(const TDesC& aName);
+
+		CMdENamespaceDef& GetNamespaceDefL(TDefId aId);
+
+		/** From MdESession */
+		CMdENamespaceDef& GetDefaultNamespaceDefL();
+
+		/** From MdESession */
+		CMdEObject* NewObjectL( CMdEObjectDef& aDef, const TDesC& aUri, 
+                TUint32 aMediaId = 0 );
+
+		/** From MdESession */
+		CMdEObject* NewObjectLC( CMdEObjectDef& aDef, const TDesC& aUri, 
+				TUint32 aMediaId = 0 );
+
+		/** From MdESession */
+	    TInt AddObjectsL(RPointerArray<CMdEObject>& aObjects);
+
+		/** From MdESession */
+	    void CommitObjectL(CMdEObject& aObject);
+
+		/** From MdESession */
+	    void CommitObjectsL(RPointerArray<CMdEObject>& aObjects);
+
+		/** From MdESession */
+	    TItemId CancelObjectL(CMdEObject& aObject);
+
+		/** From MdESession */
+		CMdERelation* NewRelationLC(CMdERelationDef& aDef, 
+				TItemId aLeftObjectId, TItemId aRightObjectId, 
+				TInt32 aParameter);
+
+		/** From MdESession */
+		CMdERelation* NewRelationL(CMdERelationDef& aDef, 
+				TItemId aLeftObjectId, TItemId aRightObjectId, 
+				TInt32 aParameter);
+
+		/** From MdESession */
+		CMdEEvent* NewEventLC(CMdEEventDef& aDef, TItemId aObjectId, 
+				TTime aTime, const TDesC* aSource, const TDesC* aParticipant);
+
+		/** From MdESession */
+		CMdEEvent* NewEventL(CMdEEventDef& aDef, TItemId aObjectId, 
+				TTime aTime, const TDesC* aSource, const TDesC* aParticipant);
+
+		/** From MdESession */
+		void AddSchemaObserverL(MMdESchemaObserver& aObserver);
+
+		/** From MdESession */
+		void RemoveSchemaObserverL(MMdESchemaObserver& aObserver);
+
+		/** From MdESession */
+		void AddRelationDefL(const CMdENamespaceDef &aNamespaceDef, 
+				const TDesC &aName);
+
+		/** From MdESession */
+		void AddEventDefL(const CMdENamespaceDef &aNamespaceDef, 
+				const TDesC &aName);
+
+		/* From MdESession */
+    	TItemId AddObjectL(CMdEObject& aObject);
+    	
+    	/* From MdESession */
+		TInt DeserializeIdsL( RMdEDataBuffer& aSerializedItemIds, 
+				RArray<TItemId>* aResultObjects = NULL,
+				RArray<TItemId>* aResultEvents = NULL, 
+				RArray<TItemId>* aResultRelations = NULL );
+
+    	/* From MdESession */
+   		TInt DeserializeItemsL( RMdEDataBuffer& aSerializedItems, 
+   				RPointerArray<CMdEInstanceItem>& aItems );
+
+    	/* From MdESession */
+    	TItemId RemoveObjectL( TItemId aId, CMdENamespaceDef* aNamespaceDef );
+    	
+    	/* From MdESession */
+    	TItemId RemoveObjectL( const TDesC& aUri, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession */
+		TInt RemoveObjectsL( const RArray<TItemId>& aId, 
+				RArray<TItemId>& aResult, CMdENamespaceDef* aNamespaceDef );
+	
+    	/* From MdESession */
+		TInt RemoveObjectsL( const RPointerArray<TDesC>& aUri, 
+				RArray<TItemId>& aResult, CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession */
+		void RemoveObjectsAsyncL( 
+				const RArray<TItemId>& aId, TRequestStatus& aStatus, 
+				RMdEDataBuffer& aSerializedObjectIds, 
+				CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession */
+		void RemoveObjectsAsyncL( 
+				const RPointerArray<TDesC>& aUri, TRequestStatus& aStatus, 
+				RMdEDataBuffer& aSerializedObjectIds, 
+				CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession */
+    	CMdEObject* GetObjectL( const TItemId aId, 
+    			CMdEObjectDef& aObjectDef );
+
+    	/* From MdESession */
+    	CMdEObject* OpenObjectL( const TItemId aId, 
+    			CMdEObjectDef& aObjectDef );
+
+    	/* From MdESession */
+    	CMdEObject* GetObjectL( 
+    			const TInt64 aGuidHigh, const TInt64 aGuidLow, 
+    			CMdEObjectDef& aObjectDef );
+
+    	/* From MdESession */
+    	CMdEObject* OpenObjectL( 
+    			const TInt64 aGuidHigh, const TInt64 aGuidLow, 
+    			CMdEObjectDef& aObjectDef );
+    	
+    	/* From MdESession. */
+    	CMdEObject* GetObjectL( const TDesC& aUri, 
+    			CMdEObjectDef& aObjectDef );
+
+    	/* From MdESession. */
+    	CMdEObject* OpenObjectL( const TDesC& aUri, 
+    			CMdEObjectDef& aObjectDef );
+
+    	/* From MdESession */
+    	CMdEObject* GetObjectL( const TItemId aId, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession */
+    	CMdEObject* OpenObjectL( const TItemId aId, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession */
+    	CMdEObject* GetObjectL(
+    			const TInt64 aGuidHigh, const TInt64 aGuidLow, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession */
+    	CMdEObject* OpenObjectL( 
+    			const TInt64 aGuidHigh, const TInt64 aGuidLow, 
+    			CMdENamespaceDef* aNamespaceDef );
+    	
+    	/* From MdESession. */
+    	CMdEObject* GetObjectL( const TDesC& aUri, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession. */
+    	CMdEObject* OpenObjectL( const TDesC& aUri, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession */
+    	CMdEObject* GetFullObjectL( const TItemId aId, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession */
+    	CMdEObject* OpenFullObjectL( const TItemId aId, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession */
+    	CMdEObject* GetFullObjectL( 
+    			const TInt64 aGuidHigh, const TInt64 aGuidLow, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession */
+    	CMdEObject* OpenFullObjectL( 
+    			const TInt64 aGuidHigh, const TInt64 aGuidLow, 
+    			CMdENamespaceDef* aNamespaceDef );
+    	
+    	/* From MdESession. */
+    	CMdEObject* GetFullObjectL( const TDesC& aUri, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession. */
+    	CMdEObject* OpenFullObjectL( const TDesC& aUri, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	void CheckObjectL( 	TMdEObject& aObject, const TDesC& aUri, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	void CheckObjectL( TMdEObject& aObject, TItemId aId, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	void CheckObjectL( RArray<TMdEObject>& aObjects, 
+    			const RArray<TItemId>& aIds, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession. */
+     	TItemId AddRelationL( CMdERelation& aRelation );
+
+    	/* From MdESession. */
+     	TItemId UpdateRelationL( CMdERelation& aRelation );
+
+    	/* From MdESession. */
+        TInt AddItemsL( RPointerArray<CMdEInstanceItem>& aItems );
+
+    	/* From MdESession. */
+        TInt UpdateItemsL( RPointerArray<CMdEInstanceItem>& aItems );
+
+		/* From MdESession. */
+        void AddItemsAsyncL( 
+        		RPointerArray<CMdEInstanceItem>& aItems, 
+        		TRequestStatus& aStatus,
+        		RMdEDataBuffer& aSerializedItemIds );
+
+		/* From MdESession. */
+        void UpdateItemsAsyncL( 
+        		RPointerArray<CMdEInstanceItem>& aItems, 
+        		TRequestStatus& aStatus,
+        		RMdEDataBuffer& aSerializedItemIds );
+
+    	/* From MdESession. */
+        CMdERelation* GetRelationL(TItemId aId, 
+        		CMdENamespaceDef* aNamespaceDef);
+
+    	/* From MdESession. */
+    	TItemId RemoveRelationL(TItemId aId, 
+    			CMdENamespaceDef* aNamespaceDef);
+    	
+    	/* From MdESession. */
+    	TInt RemoveRelationsL(const RArray<TItemId>& aId, 
+    			RArray<TItemId>& aSuccessful, CMdENamespaceDef* aNamespaceDef);
+
+    	/* From MdESession. */
+    	void RemoveRelationsAsyncL(
+    			const RArray<TItemId>& aId, TRequestStatus& aStatus, 
+    			RMdEDataBuffer& aSerializedRelationIds, 
+    			CMdENamespaceDef* aNamespaceDef );
+
+    	/* From MdESession. */
+        CMdEObjectQuery* NewObjectQueryL(CMdENamespaceDef& aNamespaceDef, 
+        		CMdEObjectDef& aObjectDef, MMdEQueryObserver* aObserver);
+
+        /* From MdESession. */
+        CMdEObjectQuery* NewObjectQueryL(CMdEObjectDef& aObjectDef, 
+        		RPointerArray<CMdEObjectDef>* aObjectDefs, 
+        		MMdEQueryObserver* aObserver);
+        
+    	/* From MdESession. */
+        CMdEEvent* GetEventL(TItemId aId, CMdENamespaceDef* aNamespaceDef);
+
+    	/* From MdESession. */
+        TItemId AddEventL( CMdEEvent& aEvent );   
+    						
+    	/* From MdESession. */		   
+		TItemId RemoveEventL( TItemId aId, CMdENamespaceDef* aNamespaceDef );
+		
+		/* From MdESession. */
+		TInt RemoveEventsL( const RArray<TItemId>& aId, 
+				RArray<TItemId>& aSuccessful, 
+				CMdENamespaceDef* aNamespaceDef );
+		
+		/* From MdESession. */
+		void RemoveEventsAsyncL( 
+				const RArray<TItemId>& aId, TRequestStatus& aStatus, 
+				RMdEDataBuffer& aSerializedEventIds, 
+				CMdENamespaceDef* aNamespaceDef );
+	
+    	/* From MdESession. */
+        CMdERelationQuery* NewRelationQueryL(CMdENamespaceDef& aNamespaceDef, 
+        		MMdEQueryObserver* aObserver);
+
+    	/* From MdESession. */
+        CMdEEventQuery* NewEventQueryL(CMdENamespaceDef& aNamespaceDef, 
+        		MMdEQueryObserver* aObserver);
+
+        /* From MdESession. */
+    	void AddObjectObserverL(MMdEObjectObserver& aObserver,
+    							CMdELogicCondition* aCondition,
+    							TUint32 aNotificationType,
+    							CMdENamespaceDef* aNamespaceDef);
+
+        /* From MdESession. */
+    	void RemoveObjectObserverL(MMdEObjectObserver& aObserver, 
+    							  CMdENamespaceDef* aNamespaceDef);
+
+		/* From MdESession. */
+		void AddObjectPresentObserverL(
+				MMdEObjectPresentObserver& aObserver);
+
+		/* From MdESession. */
+		void RemoveObjectPresentObserverL(
+				MMdEObjectPresentObserver& aObserver);
+	
+        /* From MdESession. */
+    	void AddRelationObserverL(MMdERelationObserver& aObserver,
+    							  CMdECondition* aCondition,
+    							  TUint32 aNotificationType,
+    							  CMdENamespaceDef* aNamespaceDef);
+
+        /* From MdESession. */
+    	void RemoveRelationObserverL(MMdERelationObserver& aObserver,
+    								CMdENamespaceDef* aNamespaceDef);
+
+    	/* From MdESession. */
+    	void AddRelationItemObserverL(MMdERelationItemObserver& aObserver,
+    								  CMdECondition* aCondition,
+    								  TUint32 aNotificationType,
+    								  CMdENamespaceDef* aNamespaceDef);
+
+    	/* From MdESession. */
+    	void RemoveRelationItemObserverL(MMdERelationItemObserver& aObserver, 
+    									CMdENamespaceDef* aNamespaceDef);
+
+    	/* From MdESession. */
+		void AddRelationPresentObserverL(
+				MMdERelationPresentObserver& aObserver);
+
+        /* From MdESession. */
+		void RemoveRelationPresentObserverL(
+				MMdERelationPresentObserver& aObserver);
+
+        /* From MdESession. */
+    	void AddEventObserverL(MMdEEventObserver& aObserver,
+    						   CMdECondition* aCondition, 
+ 							   TUint32 aNotificationType,
+    						   CMdENamespaceDef* aNamespaceDef);
+
+        /* From MdESession. */
+    	void RemoveEventObserverL(MMdEEventObserver& aObserver, 
+    							 CMdENamespaceDef* aNamespaceDef);
+
+        /** Finds an existing observer notifier */
+        TInt FindNotifier( TUint32 aNotifyType, TAny* aObserver, 
+        		CMdENamespaceDef& aNamespaceDef );
+
+        /** With this call Notifier announces it is in error state */
+        void NotifierInError( CMdENotifierAO* aNotifier );
+
+        /* From MdESession. */
+        void ImportSchemaL( const TDesC& aFileName );
+
+        /* From MdESession. */
+        TInt ImportMetadataL(const TDesC& aFileName );
+
+        /* From MdESession. */
+        void ImportMetadata( const TDesC& aFileName, TPckgBuf<TInt>& aResult, 
+        		TRequestStatus& aStatus );
+
+        /* From MdESession. */
+        void ExportMetadataL( const TDesC& aFileName, 
+        					  const CMdENamespaceDef* aNamespaceDef = NULL, 
+	                		  const RPointerArray<CMdEObjectDef>* aObjectDefs = NULL, 
+                    		  const RPointerArray<CMdERelationDef>* aRelationDefs = NULL, 
+                        	  const RPointerArray<CMdEEventDef>* aEventDefs = NULL );
+
+        /* From MdESession. */
+        void ExportMetadataL( const TDesC& aFileName, TRequestStatus& aStatus, 
+        					  RMdEDataBuffer& aBuffer, 
+        					  const CMdENamespaceDef* aNamespaceDef = NULL, 
+	                		  const RPointerArray<CMdEObjectDef>* aObjectDefs = NULL, 
+                    		  const RPointerArray<CMdERelationDef>* aRelationDefs = NULL, 
+                        	  const RPointerArray<CMdEEventDef>* aEventDefs = NULL );
+
+		void LoadSchemaL();
+
+		RMdEEngineSession& EngineSession();
+
+		/* From MdESession. */
+    	void GetSchemaVersionL(TInt& aMajorVersion, TInt& aMinorVersion);
+
+    	/* From MdESession. */
+    	void SetObjectToPresentByGuidL( 
+    			const TInt64& aGuidHigh, const TInt64& aGuidLow );
+    	
+        void GetCountL( CMdCSerializationBuffer* aBuffer, TUint32& aResult );
+
+        void GetItemIdL( CMdCSerializationBuffer* aBuffer, 
+        		RArray<TItemId>& aIdArray );
+
+        void GetDistinctValuesL( CMdCSerializationBuffer& aBuffer, 
+        		CDesCArray& aResults );
+
+		/**
+		 * Should be called to notify the base class about errors, which are 
+		 * not a direct consequence of the operations initiated by the client 
+		 * but caused by some external source (e.g., other clients). Attempts 
+		 * to recover from the error have failed. All on-going operations 
+		 * initiated by the client should be aborted before calling this 
+		 * method. After calling this method any attempts to use the session 
+		 * will cause a panic.
+		 *
+		 * @param aError  one of the system-wide error codes
+		 */
+		void NotifyError(TInt aError);
+
+    protected:
+
+        /*
+        * Loads the schema
+        */
+        void DoLoadSchemaL();
+
+       	void Close();
+
+		/* Methods to notify the base class about different events. */
+
+		/**
+		 * Should be called to notify the base class that opening the session 
+		 * has been completed and, if the opening succeeded, the session is 
+		 * ready for use.
+		 *
+		 * @param aError <code>KErrNone</code>, if opening the session 
+		 *               succeeded; or one of the system-wide error codes, 
+		 *               if opening the session failed
+		 */
+		void NotifySessionOpened(TInt aError);
+
+		/* Utility methods for concrete session implementations. */	
+
+		/**
+		 * Panics if the session has not been succesfully opened.
+		 */
+		void CheckOpened() const;
+
+	public:
+
+		void DeserializeQueryResultL( CMdCSerializationBuffer& aBuffer, 
+				RPointerArray<CMdEInstanceItem>& aItems );
+
+	protected:						   		       
+		CMdCSerializationBuffer* SerializeItemsL( 
+				RPointerArray<CMdEInstanceItem>& aItems );					   		       
+		
+		TItemId AddItemL( CMdEInstanceItem& aItem );
+		
+		void DeserializeAddingResultsL( 
+				RPointerArray<CMdEInstanceItem>& aItems, 
+				CMdCSerializationBuffer& aResultBuffer );
+		
+		/**
+		 * Creates a serialized buffer with id marked to be removed
+		 *
+		 * @param aNamespaceDef namespace where items should be removed
+		 * @param aObjects objects id to remove (could be NULL)
+		 * @param aEvents events id to remove (could be NULL)
+		 * @param aRelations relation id to remove (could be NULL)
+		 * @return serialized buffer
+		 */
+		CMdCSerializationBuffer* RemoveCommonL( 
+				CMdENamespaceDef& aNamespaceDef, 
+				const RPointerArray<TDesC16>* aObjects,
+				const RArray<TItemId>* aEvents, 
+				const RArray<TItemId>* aRelations );
+		
+	 	/**
+		 * Creates a serialized buffer with id marked to be removed
+		 *
+		 * @param aNamespaceDef namespace where items should be removed
+		 * @param aObjects objects uri to remove (could be NULL)
+		 * @param aEvents events id to remove (could be NULL)
+		 * @param aRelations relation id to remove (could be NULL)
+		 * @return serialized buffer
+		 */
+		CMdCSerializationBuffer* RemoveCommonL( 
+				CMdENamespaceDef& aNamespaceDef, 
+				const RArray<TItemId>* aObjects, 
+				const RArray<TItemId>* aEvents, 
+				const RArray<TItemId>* aRelations );
+
+		/**
+		 * Creates a serialized buffer with defs id items to be exported
+		 *
+		 * @param aNamespaceDef namespace from where items should be removed 
+		 *                      (NULL means from every)
+		 * @param aObjectDefs objectDefs to export
+		 * @param aRelationDefs
+		 * @param aEventDefs
+		 * @return serialized items ids
+		 */
+		CMdCSerializationBuffer* ExportCommonL( 
+				const CMdENamespaceDef* aNamespaceDef,
+				const RPointerArray<CMdEObjectDef>* aObjectDefs,
+                const RPointerArray<CMdERelationDef>* aRelationDefs,
+                const RPointerArray<CMdEEventDef>* aEventDefs );
+
+	private:
+		/**
+		 * If aId is KNoId it isn't used. If aUri is KNullDesC, it isn't used.
+		 */
+		CMdEObject* GetObjectL( CMdEObjectDef& aObjectDef, const TItemId aId, 
+				                const TInt64 aGuidHigh, const TInt64 aGuidLow, 
+				                const TDesC& aUri, TMdCQueryLockType aLocktype,
+				                TBool aIncludeFreetexts );
+
+		/**
+		 * Return namespace definition or default namespace definition
+		 * 
+		 * @param aNamespaceDef namespace definition or NULL
+		 * @return default namespace definition if parameter was NULL, 
+		 *         othrewise namespace definition which was given as parameter
+		 */
+		CMdENamespaceDef* GetNamespaceDefL( CMdENamespaceDef* aNamespaceDef );
+		
+    private: // data members
+
+		/**
+		*
+		*/
+		CMdESessionStartupAO* iSessionStartupAO;
+
+        /**
+        * array of observer notifier active objects
+        */
+        RPointerArray<CMdENotifierAO> iNotifiers;
+                
+		/** Open observer. */
+		MMdESessionObserver* iSessionObserver;
+
+		/** Schema observers. */
+		RPointerArray<MMdESchemaObserver> iSchemaObserverArray;
+		
+		RChunk iSchemaChunk;
+		
+		CMdCSerializationBuffer* iSchemaBuffer;
+		
+		RPointerArray<CMdENamespaceDef> iNamespaceDefs;
+		
+		CMdESessionAsyncHandler* iAsyncHandler;
+
+		TUint32 iNextQueryId;
+		
+	protected:
+
+		/**
+	 	* iSession, client server session 
+	 	*/
+	    RMdEEngineSession iSession;
+	
+		enum TSessionState
+			{
+				EMdESessionClosed = 0,
+				EMdESessionOpen,
+				EMdESessionError,
+			};
+		TSessionState iSessionState;
+	};
+
+#endif  // __MDESESSIONIMPL_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/inc/mdesessionstartupao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,113 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  MdE session startup active object*
+*/
+
+
+#ifndef __MDESESSIONSTARTUPAO_H__
+#define __MDESESSIONSTARTUPAO_H__
+
+#include <e32base.h>
+
+// Forward declaration
+class CMdESessionImpl;
+class RMdEEngineSession;
+
+/**
+* CMdESessionStartupAO
+* An active object that handles asynchronous MdE session starting.
+*/
+NONSHARABLE_CLASS(CMdESessionStartupAO) : public CActive
+    {
+    public: // Constructors and destructors
+
+        /**
+        * Two-phased constructor.
+        * @param aSessionImpl session impl
+        * @param aSession the server handler
+        * @return the created instance
+        */
+        static CMdESessionStartupAO* NewL(
+            CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession );
+
+        /**
+        * Two-phased constructor.
+        * @param aSessionImpl session impl
+        * @param aSession the server handler
+        * @return the created instance
+        */
+        static CMdESessionStartupAO* NewLC(
+            CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CMdESessionStartupAO();
+
+    protected: // Functions from base classes
+
+        /**
+        * From CActive
+        * Callback function.
+        * Invoked to handle responses from the server.
+        */
+        void RunL();
+
+        /**
+        * From CActive
+        * Handles errors that occur during notifying the observer.
+        */
+        TInt RunError(TInt aError);
+
+        /**
+        * From CActive
+        * Cancels any outstanding operation.
+        */
+        void DoCancel();
+
+    private: // Constructors and destructors
+
+        /**
+        * constructor
+        * @param aSessionImpl session impl
+        * @param aSession the server handler
+        */
+        CMdESessionStartupAO( 
+            CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession );
+
+        /**
+        * 2nd phase constructor
+        */
+        void ConstructL();
+
+    private: // Data
+
+		enum TMdESessionStartupAOStates
+			{
+			EStartupOpenServer,
+			EStartupConnect,
+			EStartupLoadSchema,
+			EStartupNotifyClient
+			};
+
+        TMdESessionStartupAOStates iState;
+
+        /** the session impl. */
+        CMdESessionImpl& iSessionImpl;
+
+        /** the session */
+        RMdEEngineSession& iSession;
+    };
+
+#endif //__MDESESSIONSTARTUPAO_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mde.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#include <e32std.h>
+
+
+TBool E32Dll()
+    {
+    return ETrue;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeasynchronousfindao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,397 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Asynchronous query active object
+*
+*/
+
+
+// INCLUDE FILES
+#include "mdeasynchronousfindao.h"
+#include "mdequeryimpl.h"
+
+#include "mdeenginesession.h"
+#include "mdelogiccondition.h"
+#include "mdesessionimpl.h"
+#include "mdequerycriteriaserialization.h"
+#include "mdeinstanceitem.h"
+
+// ========================= MEMBER FUNCTIONS ==================================
+
+CMdEAsynchronousFindAO* CMdEAsynchronousFindAO::NewL( CMdEQuery& aQuery,
+    CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession )
+    {
+    CMdEAsynchronousFindAO* self = CMdEAsynchronousFindAO::NewLC( aQuery, aSessionImpl, aSession );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+CMdEAsynchronousFindAO* CMdEAsynchronousFindAO::NewLC( CMdEQuery& aQuery,
+	    CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession )
+    {
+    CMdEAsynchronousFindAO* self =
+        new ( ELeave ) CMdEAsynchronousFindAO( aQuery, aSessionImpl, aSession );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+void CMdEAsynchronousFindAO::ConstructL()
+    {
+    }
+
+CMdEAsynchronousFindAO::CMdEAsynchronousFindAO( CMdEQuery& aQuery,
+    CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession )
+    : CActive( CActive::EPriorityStandard )
+    , iQuery( aQuery )
+    , iSessionImpl ( aSessionImpl )
+    , iSession( aSession )
+    , iCountResult( 0 )
+    , iConditionBuffer( NULL )
+    , iDistinctResults( NULL )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+
+void CMdEAsynchronousFindAO::DoFindL( TUint aMaxCount, TUint aNotifyCount )
+    {    
+	CMdEObjectDef* objectDef = NULL;
+
+	RPointerArray<CMdEObjectDef>* objectDefs = NULL;
+	
+    RPointerArray<CMdEPropertyDef>* propertyFilter = NULL;
+
+	// get query's internal optimization flags
+	TUint32 queryOptimizationFlags = 0;
+	iQuery.Conditions().InternalQueryOptimizationFlags(queryOptimizationFlags);
+
+	TQueryResultMode resultMode = iQuery.ResultMode();
+
+    // set property filter and distinct
+    if( EQueryTypeObject == iQuery.Type() )
+    	{
+    	CMdEObjectQuery& objectQuery = (CMdEObjectQuery&)iQuery;
+
+		objectDef = &objectQuery.ObjectDef();
+		
+		objectDefs = objectQuery.ObjectDefs();
+
+		// if result mode is objects with freetext
+		// change it to normal items for server 
+		// (freetext including to results is in query optimization flags)
+		if( EQueryResultModeObjectWithFreetexts == resultMode )
+			{
+			resultMode = EQueryResultModeItem;
+			queryOptimizationFlags |= EContainsFreetextCondition;
+			}
+
+    	if( EQueryResultModeItem == resultMode || 
+    		EQueryResultModeDistinctValues == resultMode )
+        	{
+        	if( objectQuery.PropertyFilter().Count() > 0 )
+        		{        		
+        		propertyFilter = &objectQuery.PropertyFilter();
+        		}
+        	}
+        }
+
+    iConditionBuffer = 
+    	CMdEQueryCriteriaSerialization::NewLC( resultMode, iQuery.Type(),     										   
+    										   iQuery.NamespaceDef(), 
+    										   objectDef, 
+    										   objectDefs, 
+    										   aMaxCount, 
+    										   0, // 0 offset because it's not used currently
+    										   queryOptimizationFlags, 
+    										   iQuery.Conditions(), iQuery.OrderRules(),
+    										   propertyFilter );
+	CleanupStack::Pop();
+    iSession.DoFindAsync( 
+    	iQuery.GetQueryId(), 
+        *iConditionBuffer,
+        &iResultSize, 
+        iStatus, 
+        aNotifyCount );
+
+    SetActive();
+    }
+
+
+CMdEAsynchronousFindAO::~CMdEAsynchronousFindAO()
+    {
+    Cancel(); // Causes call to DoCancel()
+
+	delete iDistinctResults;
+
+	delete iConditionBuffer;
+
+    iResultList.ResetAndDestroy();
+    iResultList.Close();
+
+    iIdResultList.Close();
+    }
+
+
+void CMdEAsynchronousFindAO::RunL()
+    {
+    // condition buffer can be safely removed now
+    if( iConditionBuffer )
+    	{
+    	delete iConditionBuffer;
+    	iConditionBuffer = NULL;
+    	}
+
+    // check if client side query is in error state (for example cancelled)
+    if( iQuery.State() == CMdEQuery::EStateError )
+    	{
+    	TRAP_IGNORE( iSession.DoFindCancelL( &iQuery ) );
+    	return;
+    	}
+    
+    const TInt status = iStatus.Int();
+    switch ( status )
+        {
+        case EAsyncFindSetReady:
+        case EAsyncFindComplete:
+            {            
+            // fetch results from server
+            CMdCSerializationBuffer* results = CMdCSerializationBuffer::NewLC(iResultSize());
+
+            iSession.DoGetDataL( &iQuery, results, status );
+
+			const TQueryResultMode resultMode = iQuery.ResultMode();
+
+            if ( resultMode == EQueryResultModeItem || resultMode == EQueryResultModeObjectWithFreetexts )
+                {
+                iSessionImpl.DeserializeQueryResultL( *results, iResultList );
+                }
+            else if ( resultMode == EQueryResultModeId )
+                {
+                iSessionImpl.GetItemIdL( results, iIdResultList );
+                }
+            else if ( resultMode == EQueryResultModeCount )
+                {
+                iSessionImpl.GetCountL( results, iCountResult );
+                }
+            else if ( resultMode == EQueryResultModeDistinctValues )
+            	{
+            	if( iDistinctResults )
+            		{            		
+            		delete iDistinctResults;
+            		iDistinctResults = NULL;
+            		}
+
+            	iDistinctResults = new (ELeave) CDesCArrayFlat( 16 );
+            	iSessionImpl.GetDistinctValuesL( *results, *iDistinctResults );
+            	}
+
+            CleanupStack::PopAndDestroy( results );
+
+            // notify the results
+            DoNotifyL( ETrue, status );
+            
+            if ( status == EAsyncFindSetReady )
+                {
+                iResultSize = 0;
+                
+                // continue find, fetch next set
+                iSession.DoFindContinue( &iQuery, &iResultSize, iStatus );
+                SetActive();
+                }
+            }
+            break;
+
+        default:
+            {
+            // notify of an error
+            DoNotifyL( EFalse, status );
+            }
+            break;
+        }
+    }
+
+TInt CMdEAsynchronousFindAO::RunError(TInt aError)
+	{
+	// in error cases make sure that results are cleaned
+	iResultList.Reset();
+	
+	iIdResultList.Reset();
+	
+	delete iDistinctResults;
+	iDistinctResults = NULL;
+
+	if( aError == KErrServerTerminated )
+		{
+		iSessionImpl.NotifyError( aError );
+		}
+	else
+		{
+		// cancel query if it's still running
+		if( iQuery.State() != EAsyncFindComplete )
+			{
+			TRAP_IGNORE( iSession.DoFindCancelL( &iQuery ) );
+			}
+		}
+
+    const TQueryType mode = iQuery.Type();
+
+    if ( mode == EQueryTypeObject ) 
+        {
+        CMdEObjectQueryImpl& qi = (CMdEObjectQueryImpl&)iQuery;
+        qi.DoNotifyCompleted( aError );
+        }
+    else if ( mode == EQueryTypeRelation )
+        {
+        CMdERelationQueryImpl& qi = (CMdERelationQueryImpl&)iQuery;
+        qi.DoNotifyCompleted( aError );
+        }
+    else if ( mode == EQueryTypeEvent )
+        {
+        CMdEEventQueryImpl& qi = (CMdEEventQueryImpl&)iQuery;
+        qi.DoNotifyCompleted( aError );
+        }
+
+	return KErrNone;
+	}
+
+void CMdEAsynchronousFindAO::DoNotifyResultsL( TInt aStatus )
+    {
+    // Notify result instances
+    if ( ( aStatus == EAsyncFindSetReady ||
+           aStatus == EAsyncFindComplete ) &&
+           iResultList.Count() > 0)
+        {
+        const TQueryType mode = iQuery.Type();
+
+        if ( mode == EQueryTypeObject )
+            {
+            CMdEObjectQueryImpl& qi = (CMdEObjectQueryImpl&)iQuery;
+            qi.DoNotifyResultsL( iResultList );
+            }
+        else if ( mode == EQueryTypeRelation )
+            {
+            CMdERelationQueryImpl& qi = (CMdERelationQueryImpl&)iQuery;
+            qi.DoNotifyResultsL( iResultList );
+            }
+        else if ( mode == EQueryTypeEvent )
+            {
+            CMdEEventQueryImpl& qi = (CMdEEventQueryImpl&)iQuery;
+            qi.DoNotifyResultsL( iResultList );
+            }
+
+        // get rid of local results list
+        iResultList.Reset();
+        }
+    // Notify result ids
+    else if ( ( aStatus == EAsyncFindSetReady ||
+           aStatus == EAsyncFindComplete ) &&
+           iIdResultList.Count() > 0)
+        {
+        const TQueryType mode = iQuery.Type();
+        
+        if ( mode == EQueryTypeObject )
+            {
+            CMdEObjectQueryImpl& qi = (CMdEObjectQueryImpl&)iQuery;
+            qi.DoNotifyResultsL( iIdResultList );
+            }
+        else if ( mode == EQueryTypeRelation )
+            {
+            CMdERelationQueryImpl& qi = (CMdERelationQueryImpl&)iQuery;
+            qi.DoNotifyResultsL( iIdResultList );
+            }
+        else if ( mode == EQueryTypeEvent )
+            {
+            CMdEEventQueryImpl& qi = (CMdEEventQueryImpl&)iQuery;
+            qi.DoNotifyResultsL( iIdResultList );
+            }
+
+        // get rid of local results list
+        iIdResultList.Reset();
+        }
+    else if ( iQuery.ResultMode() == EQueryResultModeCount )
+        {
+        const TQueryType mode = iQuery.Type();
+        
+        if ( mode == EQueryTypeObject )
+            {
+            CMdEObjectQueryImpl& qi = (CMdEObjectQueryImpl&)iQuery;
+            qi.DoNotifyResults( iCountResult );
+            }
+        else if ( mode == EQueryTypeRelation )
+            {
+            CMdERelationQueryImpl& qi = (CMdERelationQueryImpl&)iQuery;
+            qi.DoNotifyResults( iCountResult );
+            }
+        else if ( mode == EQueryTypeEvent )
+            {
+            CMdEEventQueryImpl& qi = (CMdEEventQueryImpl&)iQuery;
+            qi.DoNotifyResults( iCountResult );
+            }
+        }
+    else if ( ( aStatus == EAsyncFindSetReady ||
+           aStatus == EAsyncFindComplete ) &&
+           iDistinctResults && iQuery.ResultMode() == EQueryResultModeDistinctValues )
+    	{
+    	CMdEObjectQueryImpl& qi = (CMdEObjectQueryImpl&)iQuery;    	
+    	qi.DoNotifyResultsL( *iDistinctResults );
+
+    	delete iDistinctResults;
+    	iDistinctResults = NULL;
+    	}
+    }
+
+void CMdEAsynchronousFindAO::DoNotifyL( TBool aNewResults, TInt aStatus )
+	{
+	if( aNewResults )
+		{
+		DoNotifyResultsL( aStatus );
+		}
+
+    // Notify complete
+    if ( aStatus != EAsyncFindSetReady )
+        {
+        const TInt code = ( aStatus == EAsyncFindComplete ? KErrNone : aStatus );
+        
+        const TQueryType mode = iQuery.Type();
+
+        if ( mode == EQueryTypeObject ) 
+            {
+            CMdEObjectQueryImpl& qi = (CMdEObjectQueryImpl&)iQuery;
+            qi.DoNotifyCompleted( code );
+            }
+        else if ( mode == EQueryTypeRelation )
+            {
+            CMdERelationQueryImpl& qi = (CMdERelationQueryImpl&)iQuery;
+            qi.DoNotifyCompleted( code );
+            }
+        else if ( mode == EQueryTypeEvent )
+            {
+            CMdEEventQueryImpl& qi = (CMdEEventQueryImpl&)iQuery;
+            qi.DoNotifyCompleted( code );
+            }
+        }
+    
+    if( aStatus == KErrServerTerminated )
+    	{
+    	iSessionImpl.NotifyError( aStatus );
+    	}
+    }
+
+
+void CMdEAsynchronousFindAO::DoCancel()
+    {
+    TRAP_IGNORE( iSession.DoFindCancelL( &iQuery ) );
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeboolpropertycondition.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,98 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Property conditions for boolean property values
+*
+*/
+
+#include "mdeboolpropertycondition.h"
+#include "mdcserializationbuffer.h"
+#include "mdepropertydef.h"
+#include "mdcquery.h"
+
+
+	/* Constructors and destructor. */
+CMdEBoolPropertyCondition* CMdEBoolPropertyCondition::NewL( 
+		const CMdEPropertyDef& aPropertyDef, TBool aValue )
+	{
+	CMdEBoolPropertyCondition* self = CMdEBoolPropertyCondition::NewLC( aPropertyDef, aValue );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+
+CMdEBoolPropertyCondition* CMdEBoolPropertyCondition::NewLC( 
+		const CMdEPropertyDef& aPropertyDef, TBool aValue )
+	{
+	CMdEBoolPropertyCondition* self = new ( ELeave ) CMdEBoolPropertyCondition( aPropertyDef, aValue );
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+	}
+
+CMdEBoolPropertyCondition::CMdEBoolPropertyCondition(const CMdEPropertyDef& aPropertyDef, TBool aValue)
+        : CMdEPropertyCondition(EConditionTypePropertyBool, aPropertyDef), iValue(aValue)
+    {
+    }
+
+
+void CMdEBoolPropertyCondition::ConstructL()
+    {
+    // Base class construction.
+    CMdEPropertyCondition::ConstructL();
+    }
+    
+
+CMdEBoolPropertyCondition::~CMdEBoolPropertyCondition()
+    {
+    }
+
+
+EXPORT_C TBool CMdEBoolPropertyCondition::Value() const
+    {
+    return iValue;
+    }
+
+TUint32 CMdEBoolPropertyCondition::InternalQueryOptimizationFlags(TUint32& aFlags)
+	{
+	return CMdEPropertyCondition::InternalQueryOptimizationFlags(aFlags);
+	}
+
+TUint32 CMdEBoolPropertyCondition::RequiredBufferSize() const
+	{
+	// Required size for property condition
+	TUint32 bufferSize = sizeof( TMdCPropertyCondition );
+
+	//Required size for bool value (coverted to TUint8)
+	bufferSize += CMdCSerializationBuffer::KRequiredSizeForTBool;
+
+	return bufferSize;
+	}
+
+void CMdEBoolPropertyCondition::SerializeL(CMdCSerializationBuffer& aBuffer,
+		TMdCOffset& aFreespaceOffset) const
+	{
+	TMdCPropertyCondition property;
+
+	property.iConditionType = iType;
+	property.iNegated = iNegated;
+	property.iObjectDefId = iPropertyDef.ObjectDefId();
+	property.iPropertyDefId = iPropertyDef.Id();
+	property.iCondition = aBuffer.Position() + sizeof( TMdCPropertyCondition );
+
+	property.SerializeL( aBuffer );
+
+	aBuffer.InsertL( iValue );
+
+	aFreespaceOffset = aBuffer.Position();
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdecondition.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,67 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Base class for all search condition tree nodes.
+*
+*/
+
+#include "mdecondition.h"
+#include "mdcquery.h"
+#include "mdepanic.h"
+#include "mdcserializationbuffer.h"
+
+CMdECondition::CMdECondition(TConditionType aType)
+        : iType(aType), iNegated(EFalse)
+    {
+	__ASSERT_DEBUG(aType > EConditionTypeFirst && aType < EConditionTypeLast,
+					TMdEPanic::Panic(TMdEPanic::EInternal));
+    }
+
+void CMdECondition::ConditionConstruct()
+    {
+    }
+
+CMdECondition::~CMdECondition()
+	{
+	}
+
+EXPORT_C TConditionType CMdECondition::Type() const
+    {
+    return iType;
+    }
+
+EXPORT_C TBool CMdECondition::Negate() const
+    {
+    return iNegated;
+    }
+
+EXPORT_C void CMdECondition::SetNegate(TBool aNegate)
+    {
+    AssertNotLocked();
+    iNegated = aNegate;
+    }
+
+EXPORT_C TBool CMdECondition::Locked() const
+    {
+    return iLocked;
+    }
+
+EXPORT_C void CMdECondition::SetLocked(TBool aLocked)
+    {
+    iLocked = aLocked;
+    }
+
+void CMdECondition::AssertNotLocked() const
+    {
+    __ASSERT_DEBUG(!iLocked, TMdEPanic::Panic(TMdEPanic::EConditionLocked));
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdedatabuffer.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Serializard data buffer container
+*
+*/
+
+#include <mdedatabuffer.h>
+
+#include "mdcserializationbuffer.h"
+
+EXPORT_C RMdEDataBuffer::RMdEDataBuffer() : iBuffer( NULL )
+	{
+	}
+
+EXPORT_C void RMdEDataBuffer::Close()
+	{
+	if( iBuffer )
+		{
+		delete iBuffer;
+		iBuffer = NULL;
+		}
+	}
+
+void RMdEDataBuffer::SetBufferL(CMdCSerializationBuffer* aBuffer)
+	{
+	if( !iBuffer )
+		{
+		iBuffer = aBuffer;
+		}
+	else
+		{
+		User::Leave( KErrCorrupt );
+		}
+	}
+
+CMdCSerializationBuffer* RMdEDataBuffer::GetBufferLC()
+	{
+	CMdCSerializationBuffer* buffer = iBuffer;
+	iBuffer = NULL; // cleanup stack handles deletion, if PushL leaves
+	CleanupStack::PushL( buffer );
+	return buffer;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeenginesession.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,940 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is Metadata engine client session file
+*
+*/
+
+#include <e32std.h>
+#include <f32file.h>
+
+// INCLUDE FILES
+#include "mdeenginesession.h"
+#include "mdcserializationbuffer.h"
+#include "mdequerycriteriaserialization.h"
+#include "mdesessionimpl.h"
+#include "mdsutils.h"
+
+RMdEEngineSession::RMdEEngineSession(CMdESessionImpl& aSession) 
+	: RSessionBase(), iSession( aSession )
+    {
+   	iIsSessionOpen = EFalse;
+   	iIsSessionProcessOpen = EFalse;
+    }
+
+void RMdEEngineSession::OpenL(TRequestStatus& aStatus)
+    {
+    TFindServer findMdEServer( KMdSServerName );
+    TFullName name;
+
+    const TInt result = findMdEServer.Next( name );
+    if( result == KErrNone )
+        {
+        // Server already running
+		iIsSessionProcessOpen = ETrue;
+
+		TRequestStatus* status = &aStatus;
+        User::RequestComplete( status, KErrNone );
+
+        return;
+        }
+
+    User::LeaveIfError( iServerProcess.Create( KMdSServerFilename, 
+    		KNullDesC ) );
+
+	iIsSessionProcessOpen = ETrue;
+
+    iServerProcess.Rendezvous( aStatus );
+
+    if( aStatus != KRequestPending )
+    	{
+        iServerProcess.Kill( 0 );   // abort startup
+    	}
+    else
+    	{
+        iServerProcess.Resume();    // logon OK - start the server   
+    	}
+    }
+
+void RMdEEngineSession::OpenCancel(TRequestStatus& aStatus)
+	{
+	if( iIsSessionProcessOpen )
+		{		
+		iServerProcess.RendezvousCancel( aStatus );
+
+		iServerProcess.Close();
+	
+		iIsSessionProcessOpen = EFalse;
+		}
+	}
+
+void RMdEEngineSession::ConnectL()
+    {
+    if( iIsSessionProcessOpen )
+    	{
+	    TBool error = (iServerProcess.ExitType() != EExitPending);
+
+    	iServerProcess.Close();
+
+		iIsSessionProcessOpen = EFalse;
+	
+		if( error )
+			{
+			User::LeaveIfError( KErrCommsBreak );
+			}
+
+	    const TInt result = CreateSession( 
+	    	KMdSServerName,
+			Version(),
+	        KMetadataMessageSlots,
+	        EIpcSession_Unsharable );
+
+		User::LeaveIfError( result );
+		
+		iIsSessionOpen = ETrue;
+    	}
+    else
+    	{
+    	User::LeaveIfError( KErrBadHandle );
+    	}
+    }
+
+TInt RMdEEngineSession::Shutdown()
+    {
+    TInt err = KErrNone;
+
+    if( iIsSessionOpen )
+    	{
+	    err = SendReceive( EShutdown );
+    	}
+
+	if( iIsSessionProcessOpen )
+		{		
+		iServerProcess.Close();
+
+		iIsSessionProcessOpen = EFalse;
+		}
+
+    return err;
+    }
+
+TVersion RMdEEngineSession::Version() const
+    {
+    return( TVersion( KMdSServMajorVersionNumber,
+                      KMdSServMinorVersionNumber,
+                      KMdSServBuildVersionNumber ) );
+    }
+
+void RMdEEngineSession::DoAddEventDefL(const TDefId aNameSpaceId, 
+		const TDesC &aName )
+	{
+	TIpcArgs ipcArgs;
+	ipcArgs.Set( EAddDefArgNamespaceId, aNameSpaceId );
+	ipcArgs.Set( EAddDefArgDefName,     &aName );
+    const TInt ret = SendReceive( EAddEventDef, ipcArgs );
+    
+    NotifySessionError( ret );
+    
+    User::LeaveIfError( ret );
+	}
+
+void RMdEEngineSession::DoAddRelationDefL(const TDefId aNameSpaceId, 
+		const TDesC &aName )
+	{
+	TIpcArgs ipcArgs;
+	ipcArgs.Set( EAddDefArgNamespaceId, aNameSpaceId );
+	ipcArgs.Set( EAddDefArgDefName,     &aName );
+    const TInt ret = SendReceive( EAddRelationDef, ipcArgs );
+    
+    NotifySessionError( ret );
+    
+    User::LeaveIfError( ret );
+	}
+
+void RMdEEngineSession::DoAddItemsL( 
+		const CMdCSerializationBuffer& aSerializedBuffer, 
+		CMdCSerializationBuffer& aResultBuffer )
+    {
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, aSerializedBuffer.BufferConstPtr() );
+    ipcArgs.Set( 1, aResultBuffer.BufferPtr() );
+    const TInt ret = SendReceive( EAdd, ipcArgs );
+    
+    NotifySessionError( ret );
+    
+    User::LeaveIfError( ret );
+    }
+
+void RMdEEngineSession::DoAddItemsAsync( 
+		const CMdCSerializationBuffer& aSerializedBuffer, 
+		CMdCSerializationBuffer& aResultBuffer, TRequestStatus& aStatus )
+    {
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, aSerializedBuffer.BufferConstPtr() );
+    ipcArgs.Set( 1, aResultBuffer.BufferPtr() );
+	SendReceive( EAdd, ipcArgs, aStatus );
+    }
+
+void RMdEEngineSession::DoUpdateItemsL( 
+		const CMdCSerializationBuffer& aSerializedBuffer, 
+		CMdCSerializationBuffer& aResultBuffer )
+    {
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, aSerializedBuffer.BufferConstPtr() );
+    ipcArgs.Set( 1, aResultBuffer.BufferPtr() );
+    const TInt ret = SendReceive( EUpdate, ipcArgs );
+    
+    NotifySessionError( ret );
+    
+    User::LeaveIfError( ret );
+    }
+
+void RMdEEngineSession::DoUpdateItemsAsync( 
+		const CMdCSerializationBuffer& aSerializedBuffer, 
+		CMdCSerializationBuffer& aResultBuffer, TRequestStatus& aStatus )
+    {
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, aSerializedBuffer.BufferConstPtr() );
+    ipcArgs.Set( 1, aResultBuffer.BufferPtr() );
+	SendReceive( EUpdate, ipcArgs, aStatus );
+    }
+    
+CMdCSerializationBuffer* RMdEEngineSession::DoFindSyncLC( 
+	const CMdEQuery* aQuery, 
+    const CMdEQueryCriteriaSerialization& aSerializationBuffer, 
+    TMdCQueryLockType aLocktype, TUint32 aNotifyCount)
+	{
+    TIpcArgs ipcArgs;
+    TPckgBuf<TInt> size(0);
+
+    ipcArgs.Set( EFindArgQueryId,         (TUint32)aQuery->GetQueryId() );
+    ipcArgs.Set( EFindArgConditions,      aSerializationBuffer.BufferPtr() );
+    ipcArgs.Set( EFindArgResulBufferSize, &size );
+    ipcArgs.Set( EFindArgNotifyCount,     aNotifyCount );	
+
+    const TInt err = SendReceive( EFind, ipcArgs );
+    
+    NotifySessionError( err );
+    
+    User::LeaveIfError( err );
+
+    CMdCSerializationBuffer* resultBuf = 
+    	CMdCSerializationBuffer::NewLC( size() );
+
+    DoGetDataL( aQuery, resultBuf, EFind, aLocktype );
+
+    return resultBuf;	
+	}
+
+void RMdEEngineSession::DoFindAsync( TUint32 aQueryId, 
+		const CMdEQueryCriteriaSerialization& aSerializationBuffer,
+		TPckgBuf<TInt>* aSizeBuf, TRequestStatus& aAsyncStatus, 
+		TUint32 aNotifyCount )
+    {
+    TIpcArgs ipcArgs;
+
+    ipcArgs.Set( EFindArgQueryId,         (TUint32)aQueryId );
+    ipcArgs.Set( EFindArgConditions,      aSerializationBuffer.BufferPtr() );
+    ipcArgs.Set( EFindArgResulBufferSize, aSizeBuf );
+    ipcArgs.Set( EFindArgNotifyCount,     aNotifyCount );
+
+    SendReceive( EAsyncFind, ipcArgs, aAsyncStatus );
+    }
+
+void RMdEEngineSession::DoFindContinue( 
+	const CMdEQuery* aQuery, 
+    TPckgBuf<TInt>* aSizeBuf,
+    TRequestStatus& aAsyncStatus )
+    {
+    TIpcArgs ipcArgs;
+
+    ipcArgs.Set( EFindArgQueryId,         (TUint32)aQuery->GetQueryId() );
+    ipcArgs.Set( EFindArgResulBufferSize, aSizeBuf );
+
+    SendReceive( EContinueAsyncFind, ipcArgs, aAsyncStatus );
+    }
+
+void RMdEEngineSession::DoFindCancelL( const CMdEQuery* aQuery )
+    {
+    // silently skip if session is not open
+    if( iIsSessionOpen )
+    	{
+    	TIpcArgs ipcArgs;
+    	ipcArgs.Set( EFindArgQueryId, (TUint32)aQuery->GetQueryId() );
+
+	    const TInt err = SendReceive( ECancelFind, ipcArgs );
+	
+	    NotifySessionError( err );
+	    
+	    User::LeaveIfError( err );
+    	}
+    }
+    
+void RMdEEngineSession::DoCheckObjectL( 
+		CMdCSerializationBuffer& aObjectBuffer, const TDesC& aUri, 
+		TDefId aNamespaceDefId )
+	{
+	TIpcArgs ipcArgs;
+
+	TPckgBuf<TDefId> namespaceDefId( aNamespaceDefId );
+
+	ipcArgs.Set( ECheckObjectArgType,           ECheckObjectByUri );
+	ipcArgs.Set( ECheckObjectArgTypeValue,      &aUri );
+	ipcArgs.Set( ECheckObjectArgNamespaceDefId, &namespaceDefId );
+	ipcArgs.Set( ECheckObjectArgObject,         aObjectBuffer.BufferPtr() );
+
+	TInt err = SendReceive( ECheckObject, ipcArgs );
+	
+	NotifySessionError( err );
+	
+	User::LeaveIfError( err );
+	}
+
+void RMdEEngineSession::DoCheckObjectL( 
+		CMdCSerializationBuffer& aObjectBuffer, TItemId aId, 
+		TDefId aNamespaceDefId )
+	{
+	TIpcArgs ipcArgs;
+	TPckgBuf<TDefId> namespaceDefId( aNamespaceDefId );
+	TPckgBuf<TItemId> objectId( aId );
+
+	ipcArgs.Set( ECheckObjectArgType,           ECheckObjectById );
+	ipcArgs.Set( ECheckObjectArgTypeValue,      &objectId );
+	ipcArgs.Set( ECheckObjectArgNamespaceDefId, &namespaceDefId );
+	ipcArgs.Set( ECheckObjectArgObject,         aObjectBuffer.BufferPtr() );
+
+	TInt err = SendReceive( ECheckObject, ipcArgs );
+	
+	NotifySessionError( err );
+	
+	User::LeaveIfError( err );
+	}
+
+void RMdEEngineSession::DoCheckObjectL( 
+		CMdCSerializationBuffer& aObjectsBuffer, 
+		const CMdCSerializationBuffer& aObjectIdsBuffer, 
+		TDefId aNamespaceDefId )
+	{
+	TIpcArgs ipcArgs;
+	TPckgBuf<TDefId> namespaceDefId( aNamespaceDefId );
+
+	ipcArgs.Set( ECheckObjectArgType,           ECheckObjectByIds );
+	ipcArgs.Set( ECheckObjectArgTypeValue,      aObjectIdsBuffer.BufferPtr() );
+	ipcArgs.Set( ECheckObjectArgNamespaceDefId, &namespaceDefId );
+	ipcArgs.Set( ECheckObjectArgObject,         aObjectsBuffer.BufferPtr() );
+
+	TInt err = SendReceive( ECheckObject, ipcArgs );
+	
+	NotifySessionError( err );
+	
+	User::LeaveIfError( err );
+	}
+
+void RMdEEngineSession::DoCommitObjectsL( const CMdCSerializationBuffer& aCodedObjects )
+	{
+	TIpcArgs ipcArgs;
+	ipcArgs.Set( 0, aCodedObjects.BufferConstPtr() );
+
+	TInt err = SendReceive( EUpdate, ipcArgs );
+	
+	NotifySessionError( err );
+	
+	User::LeaveIfError( err );
+	}
+
+void RMdEEngineSession::DoCancelObjectL( CMdCSerializationBuffer& aRemoveId )
+    {
+    // silently skip if session is not open
+    if( iIsSessionOpen )
+    	{
+	    TIpcArgs ipcArgs;
+	    ipcArgs.Set( 0, aRemoveId.BufferPtr() );
+	
+	   	TInt err = SendReceive( ECancelObject, ipcArgs );
+	   	
+	   	NotifySessionError( err );
+	   	
+	   	User::LeaveIfError( err );
+    	}
+    }
+
+void RMdEEngineSession::DoRegisterL( TInt aId,
+    TUint32 aType,
+    CMdCSerializationBuffer& aBuffer,
+    TDefId aNamespaceDefId )
+    {
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, aId );
+    ipcArgs.Set( 1, aType );
+    ipcArgs.Set( 2, aBuffer.BufferPtr() );
+    ipcArgs.Set( 3, aNamespaceDefId );
+
+    const TInt err = SendReceive( ERegister, ipcArgs );
+
+    NotifySessionError( err );
+
+    User::LeaveIfError( err );
+    }
+
+void RMdEEngineSession::DoListen( TInt aId,
+    TPckgBuf<TInt>* aSizeBuf,
+    TRequestStatus& aAsyncStatus )
+    {
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, aId );
+    ipcArgs.Set( 1, aSizeBuf );
+
+    SendReceive( EListen, ipcArgs, aAsyncStatus );
+    }
+
+void RMdEEngineSession::DoUnregisterL( TInt aId )
+    {
+    // silently skip if session is not open
+    if( iIsSessionOpen )
+    	{
+	    TIpcArgs ipcArgs;
+	    ipcArgs.Set( 0, aId );
+	
+	    const TInt err = SendReceive( EUnregister, ipcArgs );
+	
+	    NotifySessionError( err );
+	
+	    User::LeaveIfError( err );
+    	}
+    }
+
+void RMdEEngineSession::DoRemoveItemsL( const CMdCSerializationBuffer& aRemoveId, CMdCSerializationBuffer& aSuccessfulId )
+    {
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, aRemoveId.BufferConstPtr() );
+    ipcArgs.Set( 1, aSuccessfulId.BufferPtr() );
+
+   	TInt err = SendReceive( ERemove, ipcArgs );
+   	
+   	NotifySessionError( err );
+   	
+   	User::LeaveIfError( err );
+    }
+
+void RMdEEngineSession::DoRemoveItemsAsync( const CMdCSerializationBuffer& aRemoveId, CMdCSerializationBuffer& aSuccessfulId, TRequestStatus& aStatus )
+    {
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, aRemoveId.BufferPtr() );
+    ipcArgs.Set( 1, aSuccessfulId.BufferPtr() );
+
+   	SendReceive( ERemove, ipcArgs, aStatus );
+    }
+
+void RMdEEngineSession::DoLoadSchemaL( TInt& aHandle )
+    {
+    TPckgBuf<TInt> handleBuf;
+
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 1, &handleBuf );
+    ipcArgs.Set( 2, ELoadSchema );
+    
+    const TInt err = SendReceive( EGetData, ipcArgs );
+    
+    NotifySessionError( err );
+    
+    User::LeaveIfError( err );
+
+    aHandle = handleBuf();
+    }
+
+void RMdEEngineSession::DoGetDataL( const CMdEQuery* aQuery, 
+	CMdCSerializationBuffer* aResultBuffer, 
+	TUint32 aRelatedCommand, TUint32 aExtraData)
+	{
+	TIpcArgs ipcArgs;
+
+    ipcArgs.Set( 0, (TUint32)aQuery->GetQueryId() );
+	ipcArgs.Set( 1, aResultBuffer->BufferPtr() );
+    ipcArgs.Set( 2, aRelatedCommand );
+    ipcArgs.Set( 3, aExtraData );
+
+    const TInt err = SendReceive( EGetData, ipcArgs );
+    
+    NotifySessionError( err );
+    
+    User::LeaveIfError( err );
+	}
+
+void RMdEEngineSession::DoGetDataL( CMdCSerializationBuffer& aBuffer, TUint32 aExtraData )
+    {
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, 0 );
+    ipcArgs.Set( 1, aBuffer.BufferPtr() );
+    ipcArgs.Set( 2, EListen );
+    ipcArgs.Set( 3, aExtraData );
+    const TInt err = SendReceive( EGetData, ipcArgs );
+    
+    NotifySessionError( err );
+    
+    User::LeaveIfError( err );
+    }
+
+void RMdEEngineSession::DoImportSchemaL( const TDesC& aFileName )
+    {
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &aFileName );
+
+    const TInt err = SendReceive( EImportSchema, ipcArgs );
+
+    NotifySessionError( err );
+    
+    User::LeaveIfError( err );
+    }
+    
+TInt RMdEEngineSession::DoImportMetadataL( const TDesC& aFileName )
+    {
+    TIpcArgs ipcArgs;
+    TPckgBuf<TInt> failed;
+    ipcArgs.Set( 0, &aFileName );
+    ipcArgs.Set( 1, &failed );
+
+    const TInt err = SendReceive( EImportMetadata, ipcArgs );
+
+    NotifySessionError( err );
+    
+    User::LeaveIfError( err );    
+    return failed();
+    }
+
+void RMdEEngineSession::DoImportMetadata( const TDesC& aFileName, 
+		TPckgBuf<TInt>& aResult, TRequestStatus& aStatus )
+    {
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &aFileName );
+    ipcArgs.Set( 1, &aResult );
+
+    SendReceive( EAsyncImportMetadata, ipcArgs, aStatus );
+    }
+
+void RMdEEngineSession::DoExportMetadataL( const TDesC& aFileName, 
+		const CMdCSerializationBuffer& aItems )
+    {
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &aFileName );
+    ipcArgs.Set( 1, aItems.BufferConstPtr() );
+
+    const TInt err = SendReceive( EExportMetadata, ipcArgs );
+
+    NotifySessionError( err );
+    
+    User::LeaveIfError( err );    
+    }
+
+void RMdEEngineSession::DoExportMetadataL( const TDesC& aFileName, 
+		const CMdCSerializationBuffer& aItems, TRequestStatus& aStatus )
+    {
+    TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &aFileName );
+    ipcArgs.Set( 1, aItems.BufferConstPtr() );
+
+    SendReceive( EAsyncExportMetadata, ipcArgs, aStatus );
+    }
+
+void RMdEEngineSession::DoAddMemoryCard(TUint32 aMediaId)
+	{
+    TPckgC<TUint32> mediaIdPckg( aMediaId );
+
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &mediaIdPckg );
+
+    const TInt err = SendReceive( EAddMemoryCard, ipcArgs );
+
+    NotifySessionError( err );
+	}
+
+TBool RMdEEngineSession::DoGetMemoryCard(TUint32& aMediaId)
+	{
+    TPckg<TUint32> mediaIdPckg( aMediaId );
+
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &mediaIdPckg );
+
+    const TInt error = SendReceive( EGetMemoryCard, ipcArgs );
+
+    NotifySessionError( error );
+
+    if( error != KErrNone )
+    	{
+    	return EFalse;
+    	}
+    else
+    	{
+	    aMediaId = mediaIdPckg();
+    	return ETrue;
+    	}
+    }
+
+TBool RMdEEngineSession::DoCheckMemoryCard(TUint32 aMediaId, TBool& aExist)
+	{
+    TPckgC<TUint32> mediaIdPckg( aMediaId );
+    TPckg<TBool> existPckg( aExist );
+
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &mediaIdPckg );
+    ipcArgs.Set( 1, &existPckg );
+
+    const TInt error = SendReceive( ECheckMemoryCard, ipcArgs );
+
+    NotifySessionError( error );
+    
+    if( error != KErrNone )
+    	{
+    	return EFalse;
+    	}
+    else
+    	{
+	    aExist = existPckg();
+    	return ETrue;
+    	}
+    }
+
+void RMdEEngineSession::DoSetMediaL(TUint32 aMediaId, TChar aDrive, 
+		TBool aPresentState)
+	{
+    TPckgC<TUint32> mediaIdPckg( aMediaId );
+    TPckgC<TChar> drivePckg( aDrive );
+    TPckgC<TBool> presentStatePckg( aPresentState );
+
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &mediaIdPckg );
+    ipcArgs.Set( 1, &drivePckg );
+    ipcArgs.Set( 2, &presentStatePckg );
+
+    const TInt err = SendReceive( ESetMedia, ipcArgs );
+
+    NotifySessionError( err );
+    
+    User::LeaveIfError( err );
+	}
+
+TBool RMdEEngineSession::DoGetMediaL(TUint32 aMediaId, TChar& aDrive, 
+		TBool& aPresentState)
+	{
+	TPckgC<TUint32> mediaIdPckg( aMediaId );
+    TPckg<TChar> drivePckg( aDrive );
+    TPckg<TBool> presentStatePckg( aPresentState );
+
+    TBool exists;
+    TPckg<TBool> existsPckg( exists );
+
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &mediaIdPckg );
+    ipcArgs.Set( 1, &drivePckg );
+    ipcArgs.Set( 2, &presentStatePckg );
+    ipcArgs.Set( 3, &existsPckg );
+
+    const TInt error = SendReceive( EGetMedia, ipcArgs );
+
+    NotifySessionError( error );
+
+	User::LeaveIfError( error );
+
+	aDrive = drivePckg();
+	aPresentState = presentStatePckg();
+	
+	exists = existsPckg();
+	
+	return exists;
+    }
+
+void RMdEEngineSession::DoGetPresentMediasL(RArray<TMdEMediaInfo>& aMedias)
+	{
+	// buffer size for media info for every possible drive
+	const TInt KMediaInfoSize = sizeof( TMdEMediaInfo ) * KMaxDrives;
+
+	TInt32 mediaCount;
+	TPckg<TInt32> mediaCountPckg( mediaCount );
+	
+	HBufC8* mediaInfoBuffer = HBufC8::NewLC( KMediaInfoSize );
+	
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &mediaCountPckg );
+    TPtr8 ptr( CONST_CAST( TUint8*, mediaInfoBuffer->Ptr() ), KMediaInfoSize );
+    ipcArgs.Set( 1, &ptr );
+
+	TInt error = SendReceive( EGetPresentMedias, ipcArgs );
+
+    NotifySessionError( error );
+
+	User::LeaveIfError( error );
+
+	mediaCount = mediaCountPckg();
+
+	aMedias.ReserveL( mediaCount );
+
+	mediaCount *= sizeof( TMdEMediaInfo );
+	
+	const TUint8* mediaInfoPtr = mediaInfoBuffer->Ptr();
+	
+	// get media infos from buffer
+	for( TInt32 i = 0; i < mediaCount; i += sizeof( TMdEMediaInfo ) )
+		{
+		const TMdEMediaInfo& mediaInfo = *STATIC_CAST( const TMdEMediaInfo*, 
+				(const TMdEMediaInfo*)( mediaInfoPtr + i ) );
+		
+		aMedias.AppendL( mediaInfo );
+		}
+	
+	CleanupStack::PopAndDestroy( mediaInfoBuffer );
+	}
+
+TBool RMdEEngineSession::DoSetFileToPresent(TUint32 aMediaId, 
+		const TDesC& aUri, TMdSFileInfo& aFileInfo)
+	{
+    TPckgC<TUint32> mediaIdPckg( aMediaId );
+    TPckgC<TMdSFileInfo> fileInfoPckg( aFileInfo );
+
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &mediaIdPckg );
+    ipcArgs.Set( 1, &aUri );
+    ipcArgs.Set( 2, &fileInfoPckg );
+
+   	TInt error = SendReceive( ESetFileToPresent, ipcArgs );
+
+   	NotifySessionError( error );
+
+   	if( error != KErrNone )
+    	{
+    	return EFalse;
+    	}
+    else
+    	{
+    	return ETrue;
+    	}
+	}
+
+TInt RMdEEngineSession::DoSetFilesToPresent(TMdSMediaIdAndCount aMediaIdAndCount, 
+		const TDes8& aUris, const TDes8& aFileInfos, TDes8& aResults)
+	{
+    TPckgC<TMdSMediaIdAndCount> mediaIdAndCountPckg( aMediaIdAndCount );
+
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &mediaIdAndCountPckg );
+    ipcArgs.Set( 1, &aUris );
+    ipcArgs.Set( 2, &aFileInfos );
+    ipcArgs.Set( 3, &aResults );
+
+   	TInt error = SendReceive( ESetFilesToPresent, ipcArgs );
+
+   	return error;
+	}
+
+void RMdEEngineSession::DoSetFilesToNotPresent(TUint32 aMediaId, TBool aStartUp)
+	{
+    TPckgC<TUint32> mediaIdPckg( aMediaId );
+    TPckgC<TBool> startUpPckg( aStartUp );
+
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &mediaIdPckg );
+    ipcArgs.Set( 1, &startUpPckg );
+
+    const TInt err = SendReceive( ESetFilesToNotPresent, ipcArgs );
+
+    NotifySessionError( err );
+	}
+	
+void RMdEEngineSession::DoRemoveFilesNotPresent(TUint32 aMediaId, TBool aStartUp)
+	{
+    TPckgC<TUint32> mediaIdPckg( aMediaId );
+    TPckgC<TBool> startUpPckg( aStartUp );
+	
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &mediaIdPckg );
+    ipcArgs.Set( 1, &startUpPckg );
+
+    const TInt err = SendReceive( ERemoveFilesNotPresent, ipcArgs );
+    
+    NotifySessionError( err );
+	}
+
+void RMdEEngineSession::DoGetSchemaVersionL(
+		TInt& aMajorVersion, TInt& aMinorVersion)
+	{
+    TPckg<TInt> majorVersion( aMajorVersion );
+    TPckg<TInt> minorVersion( aMinorVersion );
+
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &majorVersion );
+    ipcArgs.Set( 1, &minorVersion );
+
+    const TInt err = SendReceive( EGetSchemaVersion, ipcArgs );
+    
+    NotifySessionError( err );
+    
+    User::LeaveIfError( err );
+    }
+
+void RMdEEngineSession::DoSetObjectToPresentByGuidL( 
+		const TInt64& aGuidHigh, const TInt64& aGuidLow )
+	{
+    TPckgC<TInt64> guidHigh( aGuidHigh );
+    TPckgC<TInt64> guidLow( aGuidLow );
+
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( ESetObjectToPresentByGuidArgGuidHigh, &guidHigh );
+    ipcArgs.Set( ESetObjectToPresentByGuidArgGuidLow,  &guidLow );
+
+    const TInt err = SendReceive( ESetObjectToPresentByGuid, ipcArgs );
+
+    NotifySessionError( err );
+
+    User::LeaveIfError( err );
+	}
+
+void RMdEEngineSession::DoChangePath( 
+		const TDesC& aOldPath, const TDesC& aNewPath, TRequestStatus& aStatus )
+	{
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, &aOldPath );
+    ipcArgs.Set( 1, &aNewPath );
+
+	SendReceive( EChangePath, ipcArgs, aStatus );
+	}
+
+void RMdEEngineSession::DoChangeCDriveMediaId()
+	{
+	SendReceive( EChangeMediaId );
+	}
+
+void RMdEEngineSession::DoSetPendingL( const RArray<TItemId>& aObjectIds )
+	{
+	HBufC8* idBuffer = SerializeArrayL( aObjectIds );
+	CleanupStack::PushL( idBuffer );
+
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, idBuffer );
+
+    const TInt err = SendReceive( ESetPending, ipcArgs );
+
+    NotifySessionError( err );
+
+	CleanupStack::PopAndDestroy( idBuffer );
+	}
+
+void RMdEEngineSession::DoResetPendingL( const RArray<TItemId>& aObjectIds )
+	{
+	HBufC8* idBuffer = SerializeArrayL( aObjectIds );
+	CleanupStack::PushL( idBuffer );
+
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, idBuffer );
+
+    const TInt err = SendReceive( EResetPending, ipcArgs );
+
+    NotifySessionError( err );
+
+	CleanupStack::PopAndDestroy( idBuffer );
+	}
+	
+TInt RMdEEngineSession::DoGetPendingCount( const CMdEObjectDef* aObjectDef )
+	{
+	TDefId objectDefId = KNoDefId;
+	
+	if( aObjectDef )
+		{
+		objectDefId = aObjectDef->Id();
+		}
+
+	TPckg<TDefId> objectDefIdPckg( objectDefId );
+	TPckg<TInt> idCountPckg( 0 );
+	
+	TIpcArgs ipcArgs;
+	ipcArgs.Set( 0, &objectDefIdPckg );
+	ipcArgs.Set( 1, &idCountPckg );
+
+    SendReceive( EGetPendingCount, ipcArgs );
+
+    return idCountPckg();
+	}
+
+TInt RMdEEngineSession::DoGetPending( 
+		const CMdEObjectDef* aObjectDef, TInt& /* aObjectIdCount */, 
+		CMdCSerializationBuffer& aObjectIdBuffer )
+	{
+	TDefId objectDefId = KNoDefId;
+	
+	if( aObjectDef )
+		{
+		objectDefId = aObjectDef->Id();
+		}
+
+	TPckg<TDefId> objectDefIdPckg( objectDefId );
+	TPckg<TInt> idCountPckg( 0 );
+	TPckg<TInt> resultPckg( 0 );
+	TInt result( 0 );
+	
+	TIpcArgs ipcArgs;
+	ipcArgs.Set( 0, &objectDefIdPckg );
+	ipcArgs.Set( 1, &idCountPckg );
+	ipcArgs.Set( 2, aObjectIdBuffer.BufferPtr() );
+	ipcArgs.Set( 3, &resultPckg );
+	
+    SendReceive( EGetPending, ipcArgs );
+
+    result = resultPckg();
+    
+    return result;
+	}
+
+void RMdEEngineSession::DoResetDBL()
+	{
+	TInt err = SendReceive( EResetDB );
+
+    NotifySessionError( err );
+
+	User::LeaveIfError( err );
+	}
+
+void RMdEEngineSession::DoSetHarvestingPrioritizationChunkL( 
+		RHandleBase aHandle )
+	{
+	TIpcArgs ipcArgs;
+    ipcArgs.Set( 0, aHandle );
+
+    const TInt err = SendReceive( ESetHarvestingPrioritizationChunk, ipcArgs );
+    
+    NotifySessionError( err );
+    
+    User::LeaveIfError( err );
+	}
+
+void RMdEEngineSession::DoAddHarvestingPrioritizationObserver( 
+		TRequestStatus& aStatus )
+	{
+    SendReceive( EAddHarvestingPrioritizationObserver, aStatus );
+	}
+
+TInt RMdEEngineSession::DoCancelHarvestingPrioritizationObserver()
+	{
+    const TInt err = SendReceive( ECancelHarvestingPrioritizationObserver );
+    
+    NotifySessionError( err );
+    
+    return err;
+	}
+
+void RMdEEngineSession::NotifySessionError( TInt aError )
+	{
+	if( aError != KErrServerTerminated )
+		{
+		return;
+		}
+	
+	iIsSessionOpen = EFalse;
+	iSession.NotifyError( aError );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeevent.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,223 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Representation of single event
+*
+*/
+
+#include "mdeevent.h"
+#include "mdcitem.h"
+#include "mdcserializationbuffer.h"
+#include "mdeeventdef.h"
+#include "mdenamespacedef.h"
+
+CMdEEvent* CMdEEvent::NewL(CMdEEventDef& aDef, TItemId aObjectId, TTime aTime,
+			const TDesC* aSource, const TDesC* aParticipant)
+	{
+	CMdEEvent* self = CMdEEvent::NewLC( aDef, aObjectId, aTime, aSource, aParticipant );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+CMdEEvent* CMdEEvent::NewLC(CMdEEventDef& aDef, TItemId aObjectId, TTime aTime,
+		const TDesC* aSource, const TDesC* aParticipant )
+	{
+	CMdEEvent* self = new (ELeave) CMdEEvent( NULL, KNoId, aDef, aObjectId, aTime );
+	CleanupStack::PushL( self );
+	self->ConstructL( aSource, aParticipant );
+	return self;
+	}
+
+
+CMdEEvent::CMdEEvent(CMdESession* aSession, TItemId aId, CMdEEventDef& aDef, TItemId aObjectId, TTime aTime)
+		: CMdEInstanceItem(aSession, aId), iDef(aDef), iObjectId(aObjectId), iTime(aTime)
+	{
+	}
+
+void CMdEEvent::ConstructL(const TDesC* aSource, const TDesC* aParticipant)
+	{
+	InstanceItemBaseConstruct();
+
+	if( aSource )
+		{		
+		iSource = aSource->AllocL();
+		}
+	else
+		{
+		iSource = NULL;
+		}
+
+	if( aParticipant )
+		{		
+		iParticipant = aParticipant->AllocL();
+		}
+	else
+		{
+		iParticipant = NULL;
+		}
+	}
+
+CMdEEvent::~CMdEEvent()
+	{
+	delete iSource;
+	delete iParticipant;
+	}
+
+CMdEEvent* CMdEEvent::NewL(CMdESession* aSession, CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef )
+	{
+	CMdEEvent* ret = CMdEEvent::NewLC( aSession, aBuffer, aNamespaceDef );
+	CleanupStack::Pop( ret );
+	return ret;
+	}
+
+CMdEEvent* CMdEEvent::NewLC(CMdESession* aSession, CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef )
+	{
+	const TMdCEvent& serializedEvent = TMdCEvent::GetFromBufferL( aBuffer );
+	if (serializedEvent.iId == KNoId)
+		{
+		User::Leave( KErrNotFound );
+		}
+	if (serializedEvent.iDefId == KNoDefId)
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	CMdEEventDef* eventDef = aNamespaceDef.GetEventDefL( serializedEvent.iDefId );
+	if ( !eventDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+	if ( serializedEvent.iObjectId == KNoId )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	CMdEEvent* event = new(ELeave) CMdEEvent( aSession, serializedEvent.iId, *eventDef,
+			serializedEvent.iObjectId, serializedEvent.iTime );
+	CleanupStack::PushL( event );
+
+	TPtrC16 source; 
+	TPtrC16 participant;
+
+	TPtrC16* sourcePtr = NULL;
+	TPtrC16* participantPtr = NULL;
+
+	if( serializedEvent.iSourceText.iPtr.iCount > 0 )
+		{
+		aBuffer.PositionL( serializedEvent.iSourceText.iPtr.iOffset );
+		source.Set( aBuffer.ReceivePtr16L() );
+		sourcePtr = &source;
+		}
+
+	if( serializedEvent.iParticipantText.iPtr.iCount > 0 )
+		{
+		aBuffer.PositionL( serializedEvent.iParticipantText.iPtr.iOffset );
+		participant.Set( aBuffer.ReceivePtr16L() );
+		participantPtr = &participant;
+		}
+
+	event->ConstructL( sourcePtr, participantPtr );
+	return event;
+	}
+
+EXPORT_C CMdEEventDef& CMdEEvent::Def() const
+	{
+	return iDef;
+	}
+
+
+EXPORT_C TItemId CMdEEvent::ObjectId() const
+	{
+	return iObjectId;
+	}
+
+
+EXPORT_C TTime CMdEEvent::Time() const
+	{
+	return iTime;
+	}
+
+
+EXPORT_C const TDesC* CMdEEvent::Source() const
+	{
+	return iSource;
+	}
+
+
+EXPORT_C const TDesC* CMdEEvent::Participant() const
+	{
+	return iParticipant;
+	}
+
+TUint32 CMdEEvent::RequiredBufferSize() const
+	{
+	TUint32 requiredSize = sizeof(TMdCEvent);
+
+	if( iSource )
+		{
+		requiredSize += CMdCSerializationBuffer::RequiredSize(*iSource);
+		}
+		
+	if( iParticipant )
+		{
+		requiredSize += CMdCSerializationBuffer::RequiredSize(*iParticipant);
+		}
+
+	return requiredSize;
+	}
+
+TMdCOffset CMdEEvent::SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreespaceOffset) const
+	{
+	const TMdCOffset eventPosition = aBuffer.Position();
+	TMdCEvent event;
+	event.iId = Id();
+	event.iDefId = iDef.Id();
+	event.iObjectId = iObjectId;
+	event.iTime = iTime;
+
+	if( iSource )
+		{
+		event.iSourceText.iPtr.iCount = iSource->Length();
+		event.iSourceText.iPtr.iOffset = aFreespaceOffset;
+		aBuffer.PositionL( aFreespaceOffset );
+		aFreespaceOffset = aBuffer.InsertL( *iSource );
+		}
+	else
+		{
+		event.iSourceText.iPtr.iCount = 0;
+		event.iSourceText.iPtr.iOffset = KNoOffset;
+		}
+
+	if( iParticipant )
+		{
+		event.iParticipantText.iPtr.iCount = iParticipant->Length();
+		event.iParticipantText.iPtr.iOffset = aFreespaceOffset;
+		aBuffer.PositionL( aFreespaceOffset );
+		aFreespaceOffset = aBuffer.InsertL( *iParticipant );
+		}
+	else
+		{
+		event.iParticipantText.iPtr.iCount = 0;
+		event.iParticipantText.iPtr.iOffset = KNoOffset;
+		}
+
+	aBuffer.PositionL( eventPosition );
+	event.SerializeL( aBuffer );
+
+	return aFreespaceOffset;
+	}
+
+TMdEInstanceType CMdEEvent::InstanceType() const
+	{
+	return EMdETypeEvent;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeeventcondition.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,297 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Representation of query event condition
+*
+*/
+
+#include "mdeeventcondition.h"
+#include "mdelogiccondition.h"
+#include "mdeeventdef.h"
+#include "mdscommoninternal.h"
+#include "mdepanic.h"
+#include "mdcserializationbuffer.h"
+#include "mdcquery.h"
+
+CMdEEventCondition* CMdEEventCondition::NewL( TItemId aEventId, const CMdEEventDef* aEventDef,
+		const TMdETimeRange* aCreationTimeRange, TEventConditionCompareMethod aCompareMethod,
+        const TDesC* aString )
+    {
+    CMdEEventCondition* self = CMdEEventCondition::NewLC( aEventId, aEventDef, aCreationTimeRange,
+    		aCompareMethod, aString );
+    CleanupStack::Pop( self );
+    return self;
+    }
+	
+CMdEEventCondition* CMdEEventCondition::NewLC(TItemId aEventId, const CMdEEventDef* aEventDef,
+		const TMdETimeRange* aCreationTimeRange, TEventConditionCompareMethod aCompareMethod,
+        const TDesC* aString )
+    {
+    CMdEEventCondition* self = new (ELeave) CMdEEventCondition( aEventId, aEventDef );
+	CleanupStack::PushL( self );
+	self->ConstructL( aCreationTimeRange, aCompareMethod, aString );
+	return self;
+    }
+
+CMdEEventCondition::CMdEEventCondition(TItemId aEventId, const CMdEEventDef* aEventDef)
+	: CMdECondition(EConditionTypeEvent), iEventId(aEventId), iEventDef(aEventDef)
+	{
+    iCompareMethod = EEventConditionCompareNone;
+    iCreationTimeRange = NULL;
+    iObjectConditions = NULL;
+    iSourceConditions = NULL;
+    iParticipantConditions = NULL;
+    iURI = NULL;
+	}
+
+void CMdEEventCondition::ConstructL(const TMdETimeRange* aCreationTimeRange,
+                                    TEventConditionCompareMethod aCompareMethod,
+                                    const TDesC* aString)
+    {
+    iCompareMethod = aCompareMethod;
+    
+    if(aCreationTimeRange)
+        {
+        // Make a copy of the creation time range.
+        iCreationTimeRange = new (ELeave) TMdETimeRange(*aCreationTimeRange);
+        }
+
+    if(aString)
+        {            
+        switch(aCompareMethod)
+            {
+            case EEventConditionCompareNone:
+                // No comparison specified.
+                break;
+            
+            case EEventConditionCompareSourceURI:
+                // Make a copy of the source URI descriptor.
+                iURI = aString->AllocL();
+                break;
+
+            case EEventConditionCompareParticipantURI:
+                // Make a copy of the participant URI descriptor.
+                iURI = aString->AllocL();
+                break;
+
+            default:
+                __ASSERT_DEBUG( EFalse, TMdEPanic::Panic(TMdEPanic::EInternal) );
+            }
+        }
+    }
+
+
+CMdEEventCondition::~CMdEEventCondition()
+	{
+    delete iCreationTimeRange;
+    delete iObjectConditions;
+    delete iSourceConditions;
+    delete iParticipantConditions;
+    delete iURI;
+	}
+
+
+EXPORT_C CMdELogicCondition& CMdEEventCondition::ObjectConditionsL()
+    {
+	if( !iObjectConditions )
+		{
+		iObjectConditions = CMdELogicCondition::NewL( ELogicConditionOperatorAnd ); 
+		}
+
+    return *iObjectConditions;
+    }
+
+
+EXPORT_C CMdELogicCondition& CMdEEventCondition::SourceObjectConditionsL()
+	{
+	if( !iSourceConditions )
+		{
+		iSourceConditions = CMdELogicCondition::NewL( ELogicConditionOperatorAnd ); 
+		}
+
+    return *iSourceConditions;
+	}
+
+
+EXPORT_C CMdELogicCondition& CMdEEventCondition::ParticipantObjectConditionsL()
+	{
+	if( !iParticipantConditions )
+		{
+		iParticipantConditions = CMdELogicCondition::NewL( ELogicConditionOperatorAnd ); 
+		}
+
+    return *iParticipantConditions;
+	}
+
+
+EXPORT_C TItemId CMdEEventCondition::EventId() const
+    {
+    return iEventId;
+    }
+
+
+EXPORT_C const CMdEEventDef* CMdEEventCondition::EventDef() const
+    {
+    return iEventDef;
+    }
+    
+
+EXPORT_C const TMdETimeRange* CMdEEventCondition::TimeRange() const
+    {
+    return iCreationTimeRange;
+    }
+
+
+EXPORT_C const TDesC* CMdEEventCondition::SourceURI() const
+    {
+    if ( iCompareMethod == EEventConditionCompareSourceURI )
+    	{
+    	return iURI;
+    	}
+    
+    return NULL;
+    }
+
+
+EXPORT_C const TDesC* CMdEEventCondition::ParticipantURI() const
+    {
+    if ( iCompareMethod == EEventConditionCompareParticipantURI )
+    	{
+    	return iURI;
+    	}
+    
+    return NULL;
+    }
+
+TUint32 CMdEEventCondition::InternalQueryOptimizationFlags(TUint32& aFlags)
+	{
+	aFlags |= EContainsEventCondition;
+	return EContainsEventCondition;
+	}
+
+TUint32 CMdEEventCondition::RequiredBufferSize() const
+	{
+	TUint32 bufferSize = sizeof( TMdCEventCondition );
+
+	// size of each object to be serialized
+	if( iCreationTimeRange )
+		{		
+		bufferSize += iCreationTimeRange->RequiredBufferSize();
+		}
+
+	if( iObjectConditions )
+		{
+		bufferSize += iObjectConditions->RequiredBufferSize();
+		}
+
+	if( iSourceConditions )
+		{
+		bufferSize += iSourceConditions->RequiredBufferSize();
+		}
+
+	if( iParticipantConditions )
+		{
+		bufferSize += iParticipantConditions->RequiredBufferSize();
+		}
+
+	if ( iURI )
+		{
+		bufferSize += CMdCSerializationBuffer::RequiredSize( *iURI );
+		}
+
+	return bufferSize;
+	}
+
+
+void CMdEEventCondition::SerializeL(CMdCSerializationBuffer& aBuffer,
+		TMdCOffset& aFreespaceOffset) const
+	{
+	TMdCEventCondition condition;
+
+	condition.iConditionType = iType;
+	condition.iNegated = iNegated;
+	condition.iCompareMethod = iCompareMethod;
+	condition.iEventId = iEventId;
+
+	if( iEventDef )
+		{	
+		condition.iEventDefId = iEventDef->Id();
+		}
+	else
+		{
+		condition.iEventDefId = KNoDefId;
+		}
+	
+	// init offsets to "zero", updated later if needed
+	condition.iCreationTimeRange = KNoOffset;
+	condition.iObjectCondition = KNoOffset;
+	condition.iSourceCondition = KNoOffset;
+	condition.iParticipantCondition = KNoOffset;
+	condition.iUriCondition = KNoOffset;
+
+	const TUint32 conditionOffset = aBuffer.Position();
+
+	// get position after condition
+	aFreespaceOffset = conditionOffset + sizeof( TMdCEventCondition );
+	aBuffer.PositionL( aFreespaceOffset );
+
+	if( iCreationTimeRange )
+		{		
+		condition.iCreationTimeRange = aFreespaceOffset;
+
+		iCreationTimeRange->SerializeL( aBuffer );
+
+		aFreespaceOffset = aBuffer.Position();
+		}
+
+	if( iObjectConditions )
+		{		
+		condition.iObjectCondition = aFreespaceOffset;
+		
+		iObjectConditions->SerializeL( aBuffer, aFreespaceOffset );
+		
+		aFreespaceOffset = aBuffer.Position();
+		}
+
+	if( iSourceConditions )
+		{		
+		condition.iSourceCondition = aFreespaceOffset;
+
+		iSourceConditions->SerializeL( aBuffer, aFreespaceOffset );
+
+		aFreespaceOffset = aBuffer.Position();
+		}
+
+	if( iParticipantConditions )
+		{		
+		condition.iParticipantCondition = aFreespaceOffset;
+
+		iParticipantConditions->SerializeL( aBuffer, aFreespaceOffset );
+
+		aFreespaceOffset = aBuffer.Position();
+		}
+
+	if ( ( EEventConditionCompareSourceURI == iCompareMethod ) || 
+		( EEventConditionCompareParticipantURI == iCompareMethod ) )
+		{
+		condition.iUriCondition = aFreespaceOffset;
+
+		aBuffer.InsertL( *iURI );
+
+		aFreespaceOffset = aBuffer.Position();
+		}
+
+	aBuffer.PositionL( conditionOffset );
+
+	condition.SerializeL( aBuffer );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeeventdef.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,80 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#include "mdeeventdef.h"
+
+#include "mdcdef.h"
+#include "mdenamespacedef.h"
+#include "mdcserializationbuffer.h"
+
+
+CMdEEventDef::CMdEEventDef( const TMdCEventDef& aEventDef, CMdENamespaceDef& aNamespaceDef )
+    : iEventDef(aEventDef), iNamespaceDef(aNamespaceDef)
+    {
+    }
+
+CMdEEventDef* CMdEEventDef::NewL( const TMdCEventDef& aEventDef,
+		CMdCSerializationBuffer& aSchemaBuffer, CMdENamespaceDef& aNamespaceDef )
+    {
+    CMdEEventDef* def = CMdEEventDef::NewLC( aEventDef, aSchemaBuffer, aNamespaceDef );
+    CleanupStack::Pop( def );
+    return def;
+    }
+
+CMdEEventDef* CMdEEventDef::NewLC( const TMdCEventDef& aEventDef,
+		CMdCSerializationBuffer& aSchemaBuffer, CMdENamespaceDef& aNamespaceDef )
+    {
+    CMdEEventDef* def = new( ELeave ) CMdEEventDef( aEventDef, aNamespaceDef );
+    CleanupStack::PushL( def );
+    def->ConstructL( aSchemaBuffer );
+    return def;
+    }
+
+void CMdEEventDef::ConstructL( CMdCSerializationBuffer& aSchemaBuffer )
+    {
+	aSchemaBuffer.PositionL( iEventDef.iName.iPtr.iOffset );
+	iName.Set( aSchemaBuffer.ReceivePtr16L() );
+    }
+
+CMdEEventDef::~CMdEEventDef()
+    {
+    }
+
+TDefId CMdEEventDef::Id() const
+    {
+    return iEventDef.iDefId;
+    }
+
+EXPORT_C CMdENamespaceDef& CMdEEventDef::NamespaceDef() const
+    {
+    return iNamespaceDef;
+    }
+
+EXPORT_C const TDesC& CMdEEventDef::Name() const
+    {
+    return iName;
+    }
+    
+EXPORT_C TInt CMdEEventDef::Compare( const CMdEEventDef& aEventDef ) const
+    {
+    TInt result = iNamespaceDef.Compare( aEventDef.iNamespaceDef );
+    if ( result == 0 )
+        {
+        result = iEventDef.iDefId - aEventDef.Id();
+        }
+    return result;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeeventquery.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Represents event query
+*
+*/
+
+#include "mdeeventquery.h"
+#include "mdeevent.h"
+
+
+CMdEEventQuery::CMdEEventQuery(CMdESession& aSession, CMdENamespaceDef& aNamespaceDef)
+        : CMdEQuery(EQueryTypeEvent, aSession, aNamespaceDef)
+    {
+    }
+
+
+void CMdEEventQuery::EventQueryConstructL()
+    {
+    QueryConstructL();
+    }
+
+
+CMdEEventQuery::~CMdEEventQuery()
+	{
+	}
+
+
+EXPORT_C CMdEEvent& CMdEEventQuery::Result(TInt aIndex) const
+    {
+    return static_cast<CMdEEvent&>( ResultItem(aIndex) );
+    }
+	
+void CMdEEventQuery::DoCancel() 
+    {
+    SetState( EStateError );
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeharvestersession.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,344 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Metadata engine Harverster Server client session
+*
+*/
+
+#include "mdeharvestersession.h"
+#include "mdesessionimpl.h"
+#include "mdcserializationbuffer.h"
+#include "harvesterlog.h"
+
+EXPORT_C CMdEHarvesterSession* CMdEHarvesterSession::NewL(CMdESession& aSession)
+	{
+	CMdEHarvesterSession* self = CMdEHarvesterSession::NewLC( aSession );
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+EXPORT_C CMdEHarvesterSession* CMdEHarvesterSession::NewLC(CMdESession& aSession)
+	{
+	CMdEHarvesterSession* self = new (ELeave) CMdEHarvesterSession( aSession );
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+	}
+
+CMdEHarvesterSession::CMdEHarvesterSession(CMdESession& aSession) : 
+	iSession( STATIC_CAST( CMdESessionImpl*, &aSession ) ),
+	iHarvestingPrioritizationSerializationBuffer( NULL )
+	{
+	}
+
+CMdEHarvesterSession::~CMdEHarvesterSession()
+	{
+	iHarvestingPrioritizationChunk.Close();
+	delete iHarvestingPrioritizationSerializationBuffer;
+	}
+
+void CMdEHarvesterSession::ConstructL()
+	{
+	}
+
+EXPORT_C void CMdEHarvesterSession::SetSession(CMdESession& aSession)
+{
+	iSession = STATIC_CAST( CMdESessionImpl*, &aSession );
+}
+
+EXPORT_C CMdESession& CMdEHarvesterSession::SessionRef()
+	{
+	return *iSession;
+	}
+
+EXPORT_C CMdESession* CMdEHarvesterSession::Session()
+	{
+	return iSession;
+	}
+
+EXPORT_C void CMdEHarvesterSession::AddMemoryCard(TUint32 aMediaId)
+	{
+	iSession->EngineSession().DoAddMemoryCard( aMediaId );
+	}
+
+EXPORT_C TBool CMdEHarvesterSession::GetMemoryCard(TUint32& aMediaId)
+	{
+	return iSession->EngineSession().DoGetMemoryCard( aMediaId );
+	}
+
+EXPORT_C TBool CMdEHarvesterSession::CheckMemoryCard(TUint32 aMediaId, 
+		TBool& aExist)
+	{
+	return iSession->EngineSession().DoCheckMemoryCard( aMediaId, aExist );
+	}
+
+EXPORT_C void CMdEHarvesterSession::SetMediaL(TUint32 aMediaId, TChar aDrive, 
+		TBool aPresentState)
+	{
+	iSession->EngineSession().DoSetMediaL( aMediaId, aDrive, aPresentState );
+	}
+
+EXPORT_C TBool CMdEHarvesterSession::GetMediaL(TUint32 aMediaId, TChar& aDrive, 
+		TBool& aPresentState)
+	{
+	return iSession->EngineSession().DoGetMediaL( aMediaId, aDrive, 
+			aPresentState );
+	}
+
+EXPORT_C void CMdEHarvesterSession::GetPresentMediasL(
+		RArray<TMdEMediaInfo>& aMedias)
+	{
+	iSession->EngineSession().DoGetPresentMediasL( aMedias );
+	}
+
+EXPORT_C TBool CMdEHarvesterSession::SetFileToPresent(TUint32 aMediaId, 
+		const TDesC& aUri, TMdSFileInfo& aFileInfo)
+	{
+	HBufC* uri = NULL;
+	uri = HBufC::New( aUri.Length() );
+	if( !uri )
+		{
+		return EFalse;
+		}
+
+	// Note: CopyLC doesn't push anything to cleanup stack
+	uri->Des().CopyLC( aUri );
+
+	const TBool ret = iSession->EngineSession().DoSetFileToPresent( 
+			aMediaId, *uri, aFileInfo );
+	
+	delete uri;
+
+	return ret;
+	}
+
+EXPORT_C void CMdEHarvesterSession::SetFilesToPresentL(TUint32 aMediaId, 
+		const RArray<TPtrC>& aUris, const RArray<TMdSFileInfo>& aFileInfos, 
+		RArray<TFilePresentStates>& aResults)
+	{
+	WRITELOG( "CMdEHarvesterSession::SetFilesToPresentL -- Start" );
+	if( aUris.Count() != aFileInfos.Count() )
+		{
+		WRITELOG2( "CMdEHarvesterSession::SetFilesToPresentL -- Leave (%d, %d)", 
+				aUris.Count(), aFileInfos.Count() );
+		User::Leave( KErrArgument );
+		}
+
+	const TInt fileCount = aUris.Count();
+	
+	TInt urisSize = CMdCSerializationBuffer::KRequiredSizeForTUint32;
+
+	WRITELOG( "CMdEHarvesterSession::SetFilesToPresentL -- Loop urisSize" );
+	for( TInt i = 0; i < fileCount; i++ )
+		{
+		urisSize += CMdCSerializationBuffer::RequiredSize( aUris[i] );
+		}
+
+	const TInt fileInfosSize = ( CMdCSerializationBuffer::KRequiredSizeForTUint32 +  
+					CMdCSerializationBuffer::KRequiredSizeForTInt64 ) * fileCount;
+	const TInt resultsSize = CMdCSerializationBuffer::KRequiredSizeForTUint8 * fileCount;
+
+	CMdCSerializationBuffer* uriBuffer = CMdCSerializationBuffer::NewLC( urisSize );
+	CMdCSerializationBuffer* fileInfosBuffer = CMdCSerializationBuffer::NewLC( fileInfosSize );
+	CMdCSerializationBuffer* resultsBuffer = CMdCSerializationBuffer::NewLC( resultsSize );
+
+	WRITELOG( "CMdEHarvesterSession::SetFilesToPresentL -- Loop fileinfos" );
+	for( TInt i = 0; i < fileCount; i++ )
+		{
+		const TDesC& uri = aUris[i];
+		uriBuffer->InsertL( CONST_CAST(TDesC&, uri) );
+
+		fileInfosBuffer->InsertL( aFileInfos[i].iModifiedTime );
+		fileInfosBuffer->InsertL( aFileInfos[i].iSize );
+		}
+	
+	TMdSMediaIdAndCount mediaIdAndCount = {aMediaId, (TUint32)fileCount};
+	
+	WRITELOG( "CMdEHarvesterSession::SetFilesToPresentL -- DoSetFilesToPresent start" );
+	TInt error = iSession->EngineSession().DoSetFilesToPresent( mediaIdAndCount, 
+			*uriBuffer->BufferConstPtr(), *fileInfosBuffer->BufferConstPtr(), 
+			*resultsBuffer->BufferPtr() );
+	WRITELOG1( "CMdEHarvesterSession::SetFilesToPresentL -- DoSetFilesToPresent end(%d)", error );
+	
+	User::LeaveIfError( error );
+
+	resultsBuffer->PositionL( KNoOffset );
+
+	aResults.ReserveL( fileCount );
+
+	WRITELOG( "CMdEHarvesterSession::SetFilesToPresentL -- loop results" );
+	for( TInt i = 0; i < fileCount; i++ )
+		{
+		TUint8 result;
+		resultsBuffer->ReceiveL( result );
+		aResults.Append( (TFilePresentStates)result );
+		}
+
+	WRITELOG( "CMdEHarvesterSession::SetFilesToPresentL -- End" );
+	CleanupStack::PopAndDestroy( resultsBuffer );
+	CleanupStack::PopAndDestroy( fileInfosBuffer );
+	CleanupStack::PopAndDestroy( uriBuffer );
+	}
+
+EXPORT_C void CMdEHarvesterSession::SetFilesToNotPresent(TUint32 aMediaId)
+	{
+	// only accept correct media IDs, other are silently ignored
+	if( aMediaId != 0 )
+		{
+		iSession->EngineSession().DoSetFilesToNotPresent( aMediaId, EFalse );
+		}
+	}
+
+EXPORT_C void CMdEHarvesterSession::RemoveFilesNotPresent(TUint32 aMediaId)
+	{
+	iSession->EngineSession().DoRemoveFilesNotPresent( aMediaId, EFalse );
+	}
+
+EXPORT_C void CMdEHarvesterSession::SetFilesToNotPresent(TUint32 aMediaId, 
+		TBool aStartUp)
+	{
+	iSession->EngineSession().DoSetFilesToNotPresent( aMediaId, aStartUp );
+	}
+
+EXPORT_C void CMdEHarvesterSession::RemoveFilesNotPresent(TUint32 aMediaId, 
+		TBool aStartUp)
+	{
+	iSession->EngineSession().DoRemoveFilesNotPresent( aMediaId, aStartUp );
+	}
+
+EXPORT_C void CMdEHarvesterSession::ResetDBL()
+	{
+	#ifdef _DEBUG
+	iSession->EngineSession().DoResetDBL();
+	iSession->LoadSchemaL();
+	#else
+	User::Leave( KErrNotSupported );
+	#endif
+	}
+
+EXPORT_C void CMdEHarvesterSession::SetHarvestingPrioritizationChunkL( 
+		TInt aSize )
+	{
+	const TInt error = 
+		iHarvestingPrioritizationChunk.CreateGlobal( KNullDesC, aSize, aSize );
+
+	User::LeaveIfError( error );
+
+	iSession->EngineSession().DoSetHarvestingPrioritizationChunkL( 
+		iHarvestingPrioritizationChunk );
+
+	iHarvestingPrioritizationSerializationBuffer = 
+		CMdCSerializationBuffer::NewL( 
+			iHarvestingPrioritizationChunk.Base(), 
+			iHarvestingPrioritizationChunk.Size() );
+	
+	iHarvestingPrioritizationSerializationBuffer->PositionL( 0 );
+	const TInt32 initialUriCount = 0;
+	iHarvestingPrioritizationSerializationBuffer->InsertL( initialUriCount );
+	}
+
+EXPORT_C void CMdEHarvesterSession::AddHarvestingPrioritizationObserver( 
+		TRequestStatus& aStatus )
+	{
+	iSession->EngineSession().DoAddHarvestingPrioritizationObserver( aStatus );
+	}
+
+EXPORT_C TInt CMdEHarvesterSession::CancelHarvestingPrioritizationObserver()
+	{
+	return iSession->EngineSession().DoCancelHarvestingPrioritizationObserver();
+	}
+
+EXPORT_C TInt CMdEHarvesterSession::HarvestingPrioritizationUriCountL()
+	{
+	if( !iHarvestingPrioritizationSerializationBuffer )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	iHarvestingPrioritizationSerializationBuffer->PositionL( 0 );
+
+	TInt32 count = 0;
+	iHarvestingPrioritizationSerializationBuffer->ReceiveL( count );
+
+	return count;
+	}
+
+EXPORT_C HBufC* CMdEHarvesterSession::HarvestingPrioritizationUriL( 
+		TInt aIndex )
+	{
+	if( !iHarvestingPrioritizationSerializationBuffer )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	const TUint32 offsetPosition = 
+		CMdCSerializationBuffer::KRequiredSizeForTInt32 + 
+		CMdCSerializationBuffer::KRequiredSizeForTUint32 * aIndex;
+
+	iHarvestingPrioritizationSerializationBuffer->PositionL( offsetPosition );
+
+	TUint32 uriOffset = 0;
+	iHarvestingPrioritizationSerializationBuffer->ReceiveL( uriOffset );
+
+	iHarvestingPrioritizationSerializationBuffer->PositionL( uriOffset );
+
+	return iHarvestingPrioritizationSerializationBuffer->ReceiveDes16L();
+	}
+
+EXPORT_C void CMdEHarvesterSession::AutoLockL( 
+		RPointerArray<CMdEObject>& aObjects )
+	{
+	const TInt objectCount = aObjects.Count();
+	
+	for( TInt i = 0; i < objectCount; i++ )
+		{
+		aObjects[i]->AutoLockL();
+		}
+	}
+
+EXPORT_C void CMdEHarvesterSession::ChangePath( 
+		const TDesC& aOldPath, const TDesC& aNewPath, TRequestStatus& aStatus )
+	{
+	iSession->EngineSession().DoChangePath( aOldPath, aNewPath, aStatus );
+	}
+
+EXPORT_C void CMdEHarvesterSession::ChangeCDriveMediaId()
+	{
+	iSession->EngineSession().DoChangeCDriveMediaId();
+	}
+
+EXPORT_C void CMdEHarvesterSession::SetPendingL( 
+		const RArray<TItemId>& aObjectIds )
+	{
+	iSession->EngineSession().DoSetPendingL( aObjectIds );
+	}
+
+EXPORT_C void CMdEHarvesterSession::ResetPendingL( 
+		const RArray<TItemId>& aObjectIds )
+	{
+	iSession->EngineSession().DoResetPendingL( aObjectIds );
+	}
+
+EXPORT_C TInt CMdEHarvesterSession::GetPendingCount( const CMdEObjectDef* aObjectDef )
+	{
+	return iSession->EngineSession().DoGetPendingCount( aObjectDef );
+	}
+	
+EXPORT_C TInt CMdEHarvesterSession::GetPending( 
+		const CMdEObjectDef* aObjectDef, TInt& aObjectIdCount, 
+		CMdCSerializationBuffer& aObjectIdBuffer )
+	{
+	return iSession->EngineSession().DoGetPending( aObjectDef, aObjectIdCount, 
+			aObjectIdBuffer );
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeinstanceitem.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#include "mdeinstanceitem.h"
+
+
+CMdEInstanceItem::CMdEInstanceItem(CMdESession* aSession, TItemId aId)
+		: CMdEItem(aSession, aId)
+	{
+	}
+
+
+void CMdEInstanceItem::InstanceItemBaseConstruct()
+	{
+	ItemBaseConstruct();
+	}
+
+
+CMdEInstanceItem::~CMdEInstanceItem()
+	{
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeitem.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,90 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#include "mdeitem.h"
+#include "mdepanic.h"
+
+
+CMdEItem::CMdEItem(CMdESession* aSession, TItemId aId)
+		: iSession(aSession), iId(aId)
+	{
+
+	}
+
+
+void CMdEItem::ItemBaseConstruct()
+	{
+	}
+
+
+CMdEItem::~CMdEItem()
+	{
+	}
+
+
+EXPORT_C TBool CMdEItem::BelongsToSession() const
+	{
+	return iSession ? ETrue : EFalse;
+	}
+
+
+EXPORT_C CMdESession& CMdEItem::Session() const
+	{
+	CheckSession();
+
+	return *iSession;
+	}
+
+
+void CMdEItem::CheckSession() const
+	{
+	__ASSERT_DEBUG(BelongsToSession(),
+					TMdEPanic::Panic(TMdEPanic::EItemDoesNotBelongToSession));
+	}
+
+
+void CMdEItem::SetSession(CMdESession& aSession)
+	{
+	iSession = &aSession;
+	}
+
+
+EXPORT_C TBool CMdEItem::InDatabase() const
+	{
+	if (iId != KNoId)
+		{
+		return ETrue;
+		}
+	else
+		{
+		return EFalse;
+		}
+	}
+
+
+EXPORT_C TItemId CMdEItem::Id() const
+	{
+	return iId;
+	}
+
+
+void CMdEItem::SetId(TItemId aId)
+	{
+	iId = aId;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdelogiccondition.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,491 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+#include "mdelogiccondition.h"
+#include "mdeobjectcondition.h"
+#include "mdeboolpropertycondition.h"
+#include "mderelationcondition.h"
+#include "mdeeventcondition.h"
+#include "mdcserializationbuffer.h"
+#include "mdcquery.h"
+
+#include "mdepanic.h"
+
+EXPORT_C CMdELogicCondition* CMdELogicCondition::NewL(TLogicConditionOperator aOperator)
+    {
+    CMdELogicCondition *self = NewLC(aOperator);
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+
+EXPORT_C CMdELogicCondition* CMdELogicCondition::NewLC(TLogicConditionOperator aOperator)
+    {
+    CMdELogicCondition *self = new(ELeave) CMdELogicCondition(aOperator);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    return self;    
+    }
+
+
+CMdELogicCondition::CMdELogicCondition(TLogicConditionOperator aOperator)
+        : CMdECondition(EConditionTypeLogic), iOperator(aOperator)
+    {
+    }
+
+
+void CMdELogicCondition::ConstructL()
+    {
+    // Base class construction.
+    ConditionConstruct();
+    }
+
+
+
+CMdELogicCondition::~CMdELogicCondition()
+    {
+    iChildren.ResetAndDestroy();
+    iChildren.Close();
+    }
+
+
+EXPORT_C TLogicConditionOperator CMdELogicCondition::Operator() const
+    {
+    return iOperator;
+    }
+
+
+EXPORT_C void CMdELogicCondition::SetOperator(TLogicConditionOperator aLogicOperator)
+    {
+    AssertNotLocked();
+    
+    __ASSERT_DEBUG(aLogicOperator > ELogicConditionOperatorFirst 
+                    && aLogicOperator < ELogicConditionOperatorLast,
+                    TMdEPanic::Panic(TMdEPanic::EInternal));
+    
+    iOperator = aLogicOperator;
+    }
+
+
+EXPORT_C TInt CMdELogicCondition::Count() const
+    {
+    return iChildren.Count();
+    }
+    
+
+EXPORT_C CMdECondition& CMdELogicCondition::Condition(TInt aIndex) const
+    {
+    __ASSERT_DEBUG(aIndex >= 0 && aIndex < Count(),
+                    TMdEPanic::Panic(TMdEPanic::EInternal));
+    
+    return *iChildren[aIndex];
+    }
+
+
+EXPORT_C void CMdELogicCondition::Remove(TInt aIndex)
+    {
+    AssertNotLocked();
+
+    __ASSERT_DEBUG(aIndex >= 0 && aIndex < Count(),
+                    TMdEPanic::Panic(TMdEPanic::EInternal));
+                    
+    iChildren.Remove(aIndex);
+    }
+
+void CMdELogicCondition::SetLocked(TBool aLocked)
+    {
+    // Base class locking.
+    CMdECondition::SetLocked(aLocked);    
+    
+    const TInt count = iChildren.Count();
+    
+    // Lock children as well.
+    for(TInt i = 0; i < count; ++i)
+        {
+        iChildren[i]->SetLocked(aLocked);
+        }
+    }
+
+TUint32 CMdELogicCondition::InternalQueryOptimizationFlags(TUint32& aFlags)
+	{
+	const TInt count = iChildren.Count();
+	
+	// get flag from childrens
+	for( TInt i = 0 ; i < count; i++)
+		{
+		iOptimizationFlags |= iChildren[i]->InternalQueryOptimizationFlags(aFlags);
+		}
+
+	return 0;
+	}
+
+
+TUint32 CMdELogicCondition::RequiredBufferSize() const
+	{
+	TUint32 bufferSize = sizeof( TMdCLogicCondition );
+
+	const TInt count = iChildren.Count();
+
+	// required size for children offsets (children count * TUint32)
+	bufferSize += count * CMdCSerializationBuffer::KRequiredSizeForTUint32;
+
+	// Required size for childrens
+	for( TInt i = 0 ; i < count; i++)
+		{
+		bufferSize += iChildren[i]->RequiredBufferSize();
+		}
+
+	return bufferSize;
+	}
+
+void CMdELogicCondition::SerializeL(CMdCSerializationBuffer& aBuffer, 
+		TMdCOffset& aFreespaceOffset) const
+	{
+	const TUint32 childrenCount = (TUint32)iChildren.Count();
+
+	// position after logic condition
+	const TUint32 conditionOffset = aBuffer.Position() + sizeof( TMdCLogicCondition );
+
+	TMdCLogicCondition condition;
+
+	condition.iConditionType = iType;
+	condition.iNegated = iNegated;
+	condition.iOperator = iOperator;
+	condition.iOptimizationFlags = iOptimizationFlags;
+	condition.iChildConditions.iPtr.iCount = childrenCount;
+	condition.iChildConditions.iPtr.iOffset = conditionOffset;
+
+	condition.SerializeL( aBuffer );
+
+	// begin position of child condition offsets
+	TUint32 childOffsetPosition = conditionOffset;
+
+	// begin position of child conditions
+	TUint32 childPosition = childOffsetPosition + 
+			CMdCSerializationBuffer::KRequiredSizeForTUint32 * childrenCount;
+
+	for( TInt i = 0 ; i < childrenCount; i++)
+		{
+		// Move to correct position of children offsets
+		aBuffer.PositionL( childOffsetPosition );
+
+		// Insert offset for current child
+		childOffsetPosition = aBuffer.InsertL( childPosition );
+
+		// Move to correct position of child
+		aBuffer.PositionL( childPosition );
+
+		// Insert current child
+		iChildren[i]->SerializeL( aBuffer, childPosition );		
+		}
+
+	// take position after subconditions
+	aFreespaceOffset = aBuffer.Position();
+	}
+
+EXPORT_C CMdELogicCondition& 
+CMdELogicCondition::AddLogicConditionL(TLogicConditionOperator aLogicOperator)
+    {
+    AssertNotLocked();
+
+    CMdELogicCondition* condition = NewLC(aLogicOperator);
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+
+EXPORT_C CMdEObjectCondition& 
+CMdELogicCondition::AddObjectConditionL(const CMdEObjectDef& aObjectDef)
+    {
+    AssertNotLocked();
+
+    CMdEObjectCondition* condition = CMdEObjectCondition::NewLC( 
+    		EObjectConditionCompareObjectDef,
+    		KNoId, &aObjectDef );
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;    
+    }
+
+
+EXPORT_C CMdEObjectCondition& 
+CMdELogicCondition::AddObjectConditionL(TItemId aObjectId)
+    {
+    AssertNotLocked();
+
+    CMdEObjectCondition* condition = CMdEObjectCondition::NewLC( 
+    		EObjectConditionCompareId, aObjectId );
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;    
+    }
+
+EXPORT_C CMdEObjectCondition& 
+CMdELogicCondition::AddObjectConditionL(const RArray<TItemId>& aObjectIds)
+    {
+    AssertNotLocked();
+
+    CMdEObjectCondition* condition = CMdEObjectCondition::NewLC( 
+    		EObjectConditionCompareIds, &aObjectIds );
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;    
+    }
+
+EXPORT_C CMdEObjectCondition& 
+CMdELogicCondition::AddObjectConditionL(TInt64 aObjectGuidHigh, TInt64 aObjectGuidLow)
+	{
+    AssertNotLocked();
+
+    CMdEObjectCondition* condition = CMdEObjectCondition::NewLC( 
+    		EObjectConditionCompareGuid, KNoId, NULL, aObjectGuidHigh, aObjectGuidLow);
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+	}
+
+EXPORT_C CMdEObjectCondition& 
+CMdELogicCondition::AddObjectConditionL(TObjectConditionCompareMethod aCompareMethod, 
+                                        const TDesC& aString)
+    {
+    AssertNotLocked();
+
+    CMdEObjectCondition* condition = CMdEObjectCondition::NewLC( 
+    		aCompareMethod, NULL, &aString );
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+EXPORT_C CMdEObjectCondition& 
+CMdELogicCondition::AddObjectConditionL(const TMdEUintRange& aRange)
+    {
+    AssertNotLocked();
+
+    CMdEObjectCondition* condition = CMdEObjectCondition::NewLC( 
+    		EObjectConditionCompareUsageCount, NULL, NULL, &aRange );
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+
+EXPORT_C CMdEPropertyCondition& 
+CMdELogicCondition::AddPropertyConditionL(const CMdEPropertyDef& aPropertyDef)
+    {
+    AssertNotLocked();
+
+    CMdEPropertyCondition* condition 
+        = CMdEPropertyCondition::NewLC(aPropertyDef);
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+
+EXPORT_C CMdEBoolPropertyCondition& 
+CMdELogicCondition::AddPropertyConditionL(const CMdEPropertyDef& aPropertyDef,
+                                          TBool aBoolValue)
+    {
+    AssertNotLocked();
+
+    CMdEBoolPropertyCondition* condition 
+        = CMdEBoolPropertyCondition::NewLC(aPropertyDef, aBoolValue);
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+    
+
+#define MDE_IMPLEMENT_ADD_RANGE_PROPERTY_CONDITION(RangeType) \
+EXPORT_C CMdE##RangeType##RangePropertyCondition& \
+CMdELogicCondition::AddPropertyConditionL(const CMdEPropertyDef& aPropertyDef, \
+                                          const TMdE##RangeType##Range& aRange) \
+    { \
+    AssertNotLocked(); \
+    CMdE##RangeType##RangePropertyCondition* condition  \
+        = CMdE##RangeType##RangePropertyCondition::NewLC(aPropertyDef, aRange); \
+    AddL(condition); \
+    CleanupStack::Pop(condition); \
+    return *condition; \
+    }
+
+MDE_IMPLEMENT_ADD_RANGE_PROPERTY_CONDITION(Int)
+MDE_IMPLEMENT_ADD_RANGE_PROPERTY_CONDITION(Int64)
+MDE_IMPLEMENT_ADD_RANGE_PROPERTY_CONDITION(Uint)
+MDE_IMPLEMENT_ADD_RANGE_PROPERTY_CONDITION(Real)
+MDE_IMPLEMENT_ADD_RANGE_PROPERTY_CONDITION(Time)
+
+EXPORT_C CMdETextPropertyCondition& 
+CMdELogicCondition::AddPropertyConditionL(const CMdEPropertyDef& aPropertyDef,
+                                          TTextPropertyConditionCompareMethod aCompareMethod,
+                                          const TDesC& aText)
+    {
+    AssertNotLocked();
+
+    CMdETextPropertyCondition* condition 
+        = CMdETextPropertyCondition::NewLC(aPropertyDef, aCompareMethod, aText);
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+EXPORT_C CMdERelationCondition& 
+CMdELogicCondition::AddRelationConditionL(TItemId aRelationId, TRelationConditionSide aSide)
+    {
+    AssertNotLocked();
+
+    CMdERelationCondition* condition = CMdERelationCondition::NewLC(aRelationId, NULL, aSide);
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+EXPORT_C CMdERelationCondition& CMdELogicCondition::AddRelationConditionL(
+		RArray<TItemId>& aRelationIds, TRelationConditionSide aSide)
+    {
+    AssertNotLocked();
+
+    CMdERelationCondition* condition = CMdERelationCondition::NewLC(
+    		KNoId, &aRelationIds, aSide);
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+EXPORT_C CMdERelationCondition& 
+CMdELogicCondition::AddRelationConditionL(TRelationConditionSide aSide)
+    {
+    AssertNotLocked();
+
+    CMdERelationCondition* condition = CMdERelationCondition::NewLC(KNoId, NULL, aSide);
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+    
+    
+EXPORT_C CMdERelationCondition& 
+CMdELogicCondition::AddRelationConditionL(const CMdERelationDef& aRelationDef,
+                                          TRelationConditionSide aSide)
+    {
+    AssertNotLocked();
+
+    CMdERelationCondition* condition = CMdERelationCondition::NewLC( 
+    		KNoId, NULL, aSide, &aRelationDef );
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+
+EXPORT_C CMdERelationCondition& 
+CMdELogicCondition::AddRelationConditionL(const CMdERelationDef& aRelationDef,
+    const TMdEIntRange& aParameterRange,
+    TRelationConditionSide aSide)
+    {
+    AssertNotLocked();
+
+    CMdERelationCondition* condition = CMdERelationCondition::NewLC( KNoId, 
+    		NULL, aSide, &aRelationDef, &aParameterRange );
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+EXPORT_C CMdEEventCondition& 
+CMdELogicCondition::AddEventConditionL(TItemId aEventId)
+    {
+    AssertNotLocked();
+
+    CMdEEventCondition* condition = CMdEEventCondition::NewLC(aEventId);
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+EXPORT_C CMdEEventCondition& 
+CMdELogicCondition::AddEventConditionL(const CMdEEventDef& aEventDef)
+    {
+    AssertNotLocked();
+
+    CMdEEventCondition* condition = CMdEEventCondition::NewLC(KNoId,&aEventDef);
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+
+EXPORT_C CMdEEventCondition& 
+CMdELogicCondition::AddEventConditionL()
+    {
+    AssertNotLocked();
+
+    CMdEEventCondition* condition = CMdEEventCondition::NewLC();
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+
+EXPORT_C CMdEEventCondition& 
+CMdELogicCondition::AddEventConditionL(const TMdETimeRange& aCreationTimeRange)
+    {
+    AssertNotLocked();
+
+    CMdEEventCondition* condition = CMdEEventCondition::NewLC(KNoId, NULL, &aCreationTimeRange);
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+
+EXPORT_C CMdEEventCondition& 
+CMdELogicCondition::AddEventConditionL(TEventConditionCompareMethod aCompareMethod, 
+                                       const TDesC& aString)
+    {
+    AssertNotLocked();
+
+    CMdEEventCondition* condition = CMdEEventCondition::NewLC(KNoId, NULL, NULL, aCompareMethod, &aString);
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+
+EXPORT_C CMdEEventCondition& 
+CMdELogicCondition::AddEventConditionL(const TMdETimeRange& aCreationTimeRange,
+                                       TEventConditionCompareMethod aCompareMethod, 
+                                       const TDesC& aString)
+    {
+    AssertNotLocked();
+
+    CMdEEventCondition* condition = CMdEEventCondition::NewLC(KNoId, NULL, &aCreationTimeRange, aCompareMethod, &aString);
+    AddL(condition);
+    CleanupStack::Pop(condition);
+    return *condition;
+    }
+
+
+CMdECondition& CMdELogicCondition::AddL(CMdECondition* aCondition)
+    {
+    AssertNotLocked();
+
+    iChildren.AppendL( aCondition );
+    return *aCondition;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdenamespacedef.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,252 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#include "mdenamespacedef.h"
+
+#include "mdcdef.h"
+#include "mdeobjectdef.h"
+#include "mderelationdef.h"
+#include "mdeeventdef.h"
+#include "mdcserializationbuffer.h"
+
+
+CMdENamespaceDef::CMdENamespaceDef( const CMdESession& aMdeSession, 
+		const TMdCNamespaceDef& aNamespaceDef )
+	: iMdeSession( aMdeSession ), iNamespaceDef( aNamespaceDef )
+	{
+	}
+
+CMdENamespaceDef* CMdENamespaceDef::NewL( const CMdESession& aMdeSession, 
+		const TMdCNamespaceDef& aNamespaceDef, 
+		CMdCSerializationBuffer& aSchemaBuffer )
+	{
+    CMdENamespaceDef* def = CMdENamespaceDef::NewLC( aMdeSession, 
+    		aNamespaceDef, aSchemaBuffer );
+    CleanupStack::Pop( def );
+    return def;
+    }
+
+CMdENamespaceDef* CMdENamespaceDef::NewLC( const CMdESession& aMdeSession, 
+		const TMdCNamespaceDef& aNamespaceDef, 
+		CMdCSerializationBuffer& aSchemaBuffer )
+	{
+    CMdENamespaceDef* def = new( ELeave ) CMdENamespaceDef( aMdeSession, 
+    		aNamespaceDef );
+    CleanupStack::PushL( def );
+    def->ConstructL( aSchemaBuffer );
+    return def;
+	}
+
+void CMdENamespaceDef::ConstructL(CMdCSerializationBuffer& aSchemaBuffer)
+	{
+	aSchemaBuffer.PositionL( iNamespaceDef.iName.iPtr.iOffset );
+	iName.Set( aSchemaBuffer.ReceivePtr16L() );
+	
+	TUint32 count = iNamespaceDef.iObjectDefs.iPtr.iCount;
+	TMdCOffset offset = iNamespaceDef.iObjectDefs.iPtr.iOffset;
+	iObjectDefs.ReserveL( count );
+	for ( TUint32 i = 0; i < count; ++i )
+		{
+		aSchemaBuffer.PositionL( offset + i * sizeof(TMdCObjectDef) );
+		const TMdCObjectDef& objectDef = TMdCObjectDef::GetFromBufferL(aSchemaBuffer);
+		iObjectDefs.AppendL( CMdEObjectDef::NewL( objectDef, aSchemaBuffer, *this ) );
+		}
+
+	count = iNamespaceDef.iEventDefs.iPtr.iCount;
+	offset = iNamespaceDef.iEventDefs.iPtr.iOffset;
+	iEventDefs.ReserveL( count );
+	for ( TUint32 i = 0; i < count; ++i )
+		{
+		aSchemaBuffer.PositionL( offset + i * sizeof(TMdCEventDef) );
+		const TMdCEventDef& eventDef = TMdCEventDef::GetFromBufferL(aSchemaBuffer);
+		iEventDefs.AppendL( CMdEEventDef::NewL( eventDef, aSchemaBuffer, *this ) );
+		}
+
+	count = iNamespaceDef.iRelationDefs.iPtr.iCount;
+	offset = iNamespaceDef.iRelationDefs.iPtr.iOffset;
+	iRelationDefs.ReserveL( count );
+	for ( TUint32 i = 0; i < count; ++i )
+		{
+		aSchemaBuffer.PositionL( offset + i * sizeof(TMdCRelationDef) );
+		const TMdCRelationDef& relationDef = TMdCRelationDef::GetFromBufferL(aSchemaBuffer);
+		iRelationDefs.AppendL( CMdERelationDef::NewL( relationDef, aSchemaBuffer, *this ) );
+		}
+	}
+
+CMdENamespaceDef::~CMdENamespaceDef()
+	{
+
+	iObjectDefs.ResetAndDestroy();
+	iObjectDefs.Close();
+
+	iEventDefs.ResetAndDestroy();
+	iEventDefs.Close();
+
+	iRelationDefs.ResetAndDestroy();
+	iRelationDefs.Close();
+	}
+
+TDefId CMdENamespaceDef::Id() const
+	{
+	return iNamespaceDef.iDefId;
+	}
+
+EXPORT_C TBool CMdENamespaceDef::ReadOnly() const
+	{
+	return iNamespaceDef.iReadOnly;
+	}
+
+EXPORT_C const TDesC& CMdENamespaceDef::Name() const
+	{
+	return iName;
+	}
+
+EXPORT_C TInt CMdENamespaceDef::Compare( const CMdENamespaceDef& aNamespaceDef ) const
+	{
+	return iNamespaceDef.iDefId - aNamespaceDef.Id();
+	}
+
+EXPORT_C TInt CMdENamespaceDef::ObjectDefCount() const
+	{
+	return iObjectDefs.Count();
+	}
+
+EXPORT_C CMdEObjectDef& CMdENamespaceDef::ObjectDefL(TInt aIndex)
+	{
+	return *iObjectDefs[aIndex];
+	}
+
+EXPORT_C CMdEObjectDef& CMdENamespaceDef::GetObjectDefL(const TDesC& aName)
+	{
+	const TInt objectDefsCount = iObjectDefs.Count();
+	for ( TInt i = 0; i < objectDefsCount; ++i )
+		{
+		if ( !aName.Compare( iObjectDefs[i]->Name() ) )
+			{
+			return ObjectDefL( i );
+			}
+		}
+
+	User::Leave( KErrNotFound );
+
+	// to stop compile warnings
+	CMdEObjectDef* objectDef = NULL;
+	return *objectDef;
+	}
+
+CMdEObjectDef* CMdENamespaceDef::GetObjectDefL(TDefId aId)
+	{
+	const TInt objectDefsCount = iObjectDefs.Count();
+	for ( TInt i = 0; i < objectDefsCount; ++i )
+		{
+		if ( aId == iObjectDefs[i]->Id() )
+			{
+			return &ObjectDefL( i );
+			}
+		}
+
+	return NULL;
+	}
+
+EXPORT_C TInt CMdENamespaceDef::RelationDefCount() const
+	{
+	return iRelationDefs.Count();
+	}
+
+EXPORT_C CMdERelationDef& CMdENamespaceDef::RelationDefL(TInt aIndex)
+	{
+	return *iRelationDefs[aIndex];
+	}
+
+EXPORT_C CMdERelationDef& CMdENamespaceDef::GetRelationDefL(const TDesC& aName)
+	{
+	const TInt relationDefCount = iRelationDefs.Count();
+	for ( TInt i = 0; i < relationDefCount; ++i )
+		{
+		if( !aName.Compare( iRelationDefs[i]->Name() ) )
+			{
+			return RelationDefL( i );
+			}
+		}
+
+	User::Leave( KErrNotFound );
+
+	// to stop compile warnings
+	CMdERelationDef* relationDef = NULL;
+	return *relationDef;
+	}
+
+CMdERelationDef* CMdENamespaceDef::GetRelationDefL(TDefId aId)
+	{
+	const TInt relationDefCount = iRelationDefs.Count();
+	for ( TInt i = 0; i < relationDefCount; ++i )
+		{
+		if( iRelationDefs[i]->Id() == aId )
+			{
+			return &RelationDefL( i );
+			}
+		}
+
+	return NULL;
+	}
+
+EXPORT_C TInt CMdENamespaceDef::EventDefCount() const
+	{
+	return iEventDefs.Count();
+	}
+
+EXPORT_C CMdEEventDef& CMdENamespaceDef::EventDefL(TInt aIndex)
+	{
+	return *iEventDefs[aIndex];
+	}
+
+EXPORT_C CMdEEventDef& CMdENamespaceDef::GetEventDefL(const TDesC& aName)
+	{
+	const TInt eventDefCount = iEventDefs.Count();
+	for ( TInt i = 0; i < eventDefCount; ++i )
+		{
+		if( !aName.Compare( iEventDefs[i]->Name() ) )
+			{
+			return EventDefL( i );
+			}
+		}
+	
+	User::Leave( KErrNotFound );
+	
+	// to stop compile warnings
+	CMdEEventDef* eventDef = NULL;
+	return *eventDef;
+	}
+
+CMdEEventDef* CMdENamespaceDef::GetEventDefL(TDefId aId)
+	{
+	const TInt eventDefCount = iEventDefs.Count();
+	for ( TInt i = 0; i < eventDefCount; ++i )
+		{
+		if( iEventDefs[i]->Id() == aId )
+			{
+			return &EventDefL( i );
+			}
+		}
+	return NULL;
+	}
+
+const CMdESession& CMdENamespaceDef::Session() const
+	{
+	return iMdeSession;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdenotifierao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,385 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Notifier client side active object
+*
+*/
+
+
+// INCLUDE FILES
+#include "mdenotifierao.h"
+
+#include "mdcresult.h"
+#include "mdeenginesession.h"
+#include "mdesessionimpl.h"
+#include "mdenamespacedef.h"
+#include "mdcserializationbuffer.h"
+#include "mdccommon.pan"
+
+// ========================= MEMBER FUNCTIONS ==================================
+
+CMdENotifierAO* CMdENotifierAO::NewL(
+    CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession )
+    {
+    CMdENotifierAO* self = CMdENotifierAO::NewLC( aSessionImpl, aSession );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+CMdENotifierAO* CMdENotifierAO::NewLC(
+    CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession )
+    {
+    CMdENotifierAO* self =
+        new ( ELeave ) CMdENotifierAO( aSessionImpl, aSession );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+
+CMdENotifierAO::CMdENotifierAO(
+    CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession )
+    : CActive( CActive::EPriorityUserInput )
+    , iSessionImpl( aSessionImpl )
+    , iSession( aSession )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+void CMdENotifierAO::ConstructL()
+    {
+    }
+
+
+CMdENotifierAO::~CMdENotifierAO()
+    {
+    Cancel(); // Causes call to DoCancel()
+    delete iDataBuffer;
+    iIdArray.Close();
+    iRelationItemArray.Close();
+    }
+
+
+void CMdENotifierAO::RegisterL( TUint32 aType, TAny* aObserver,
+    							CMdECondition* aCondition, CMdENamespaceDef& aNamespaceDef )
+    {
+    iObserver = aObserver;
+    iType = aType;
+    iNamespaceDefId = aNamespaceDef.Id();
+
+	CMdCSerializationBuffer* buffer = NULL;
+
+	if( aCondition )
+		{
+   		buffer = CMdCSerializationBuffer::NewLC( aCondition->RequiredBufferSize() );
+
+   		// only needed, because method needs it as parameter
+   		TUint32 freespaceOffset = 0;
+
+   		aCondition->SerializeL( *buffer, freespaceOffset );
+		}
+	else
+		{
+		// create empty serialized condition buffer
+		buffer = CMdCSerializationBuffer::NewLC( 0 );
+		}
+
+   	iSession.DoRegisterL( Id(), iType, *buffer, iNamespaceDefId );
+	CleanupStack::PopAndDestroy( buffer );
+
+    // listen for first event
+    iSession.DoListen( Id(), &iResultSize, iStatus );
+    SetActive();
+    }
+
+TBool CMdENotifierAO::Match( TUint32 aType, TAny* aObserver, CMdENamespaceDef& aNamespaceDef )
+    {
+    if( aNamespaceDef.Id() != iNamespaceDefId )
+    	{
+    	return EFalse;
+    	}
+
+    if ( iObserver != aObserver )
+    	{
+    	return EFalse;
+    	}
+    
+    return ( iType & aType );
+    }
+
+TInt CMdENotifierAO::Id()
+    {
+    return (TInt)this;
+    }
+
+void CMdENotifierAO::DoCancel()
+    {
+    TRAP_IGNORE( iSession.DoUnregisterL( Id() ) );
+    // the current pending call will return with KErrCancel
+    }
+
+void CMdENotifierAO::RunL()
+    {
+    const TInt status = iStatus.Int();
+
+    if ( status >= KErrNone )
+    	{
+	    if ( status & ( EObjectNotifyAdd | EObjectNotifyModify | EObjectNotifyRemove
+	    				| EObjectNotifyPresent | EObjectNotifyNotPresent
+	    				| ERelationNotifyAdd | ERelationNotifyModify | ERelationNotifyRemove
+	    				| ERelationNotifyPresent | ERelationNotifyNotPresent
+	    				| EEventNotifyAdd | EEventNotifyRemove ) )
+	    	{
+	    	if( !iDataBuffer )
+	    		{
+	    		iDataBuffer = CMdCSerializationBuffer::NewL( iResultSize() );
+	    		}
+	    	else if( iDataBuffer->Buffer().MaxSize() < iResultSize() )
+	    		{
+	    		delete iDataBuffer;
+	    		iDataBuffer = NULL;
+	    		iDataBuffer = CMdCSerializationBuffer::NewL( iResultSize() );
+	    		}
+	    	
+	    	if( iResultSize() )
+	    		{
+	        	iSession.DoGetDataL( *iDataBuffer, Id() ); // reads ids to the buffer
+	        	DecodeIdBufferL(); // decodes ids from the data buffer and puts them to iIdArray
+	        	
+	        	delete iDataBuffer;
+	        	iDataBuffer = NULL;
+	        	
+	            DoNotifyObserver(); // notifies the observer about the event with an array of ids
+	    		}
+	        iSession.DoListen( Id(), &iResultSize, iStatus );  // continue listening for events
+	        SetActive();
+	        }
+	    else if ( status & ( /*ERelationItemNotifyAdd | ERelationItemNotifyModify
+	                         |*/ ERelationItemNotifyRemove ) ) // a relation was removed
+	    	{
+	    	if( !iDataBuffer )
+	    		{
+	    		iDataBuffer = CMdCSerializationBuffer::NewL(iResultSize());
+	    		}
+	    	else if( iDataBuffer->Size() < (TUint32)iResultSize() )
+	    		{
+	    		delete iDataBuffer;
+	    		iDataBuffer = NULL;
+	    		iDataBuffer = CMdCSerializationBuffer::NewL(iResultSize());
+	    		}
+	    	
+	    	if(iResultSize())
+	    		{
+	        	iSession.DoGetDataL( *iDataBuffer, Id() ); // reads ids to the buffer
+	        	DecodeRelationItemBufferL(); // decodes ids from the data buffer and puts them to iIdArray
+	        	
+	        	delete iDataBuffer;
+	        	iDataBuffer = NULL;
+	        	
+	            DoNotifyObserver(); // notifies the observer about the event with an array of ids
+	    		}
+	        iSession.DoListen( Id(), &iResultSize, iStatus ); // continue listening for events
+	        SetActive();
+	        }
+	    else if ( status == ESchemaModify )  // schema has been modified
+	    	{
+	        DoNotifyObserver(); // notifies the observer about the event with an array of ids
+	        iSession.DoListen( Id(), &iResultSize, iStatus ); // continue listening for events
+	        SetActive();
+	    	}
+    	}
+    else
+        {
+        // error in notifier mechanism
+        if( status != KErrServerTerminated )
+        	{        
+        	iSession.DoUnregisterL( Id() ); // no response expected
+        	}
+        else
+        	{
+        	iSessionImpl.NotifyError( status );
+        	}
+        iSessionImpl.NotifierInError( this );
+        }
+    }
+
+TInt CMdENotifierAO::RunError(TInt aError)
+    {
+    if( aError == KErrServerTerminated )
+    	{
+    	iSessionImpl.NotifyError( aError );
+    	}
+    
+    // notifying observer failed - continue listening anyway.
+    iSessionImpl.NotifierInError( this );
+    return KErrNone;
+    }
+
+void CMdENotifierAO::DoNotifyObserver()
+    {
+    if( !iObserver )
+        {
+        return;
+        }
+    const TInt status = iStatus.Int();
+    switch( iType & status )
+        {
+        case EObjectNotifyAdd:
+        	{
+        	MMdEObjectObserver* obs = static_cast<MMdEObjectObserver*>( iObserver );
+        	obs->HandleObjectNotification( iSessionImpl, ENotifyAdd, iIdArray );
+            iIdArray.Reset();            
+        	break;
+        	}
+        case EObjectNotifyModify:
+        	{
+        	MMdEObjectObserver* obs = static_cast<MMdEObjectObserver*>( iObserver );
+        	obs->HandleObjectNotification( iSessionImpl, ENotifyModify, iIdArray );
+            iIdArray.Reset();            
+        	break;
+        	}
+        case EObjectNotifyRemove:
+        	{
+        	MMdEObjectObserver* obs = static_cast<MMdEObjectObserver*>( iObserver );
+        	obs->HandleObjectNotification( iSessionImpl, ENotifyRemove, iIdArray );
+            iIdArray.Reset();            
+        	break;
+        	}
+
+        case EObjectNotifyPresent:
+        	{
+	    	MMdEObjectPresentObserver* obs = static_cast<MMdEObjectPresentObserver*>( iObserver );
+            obs->HandleObjectPresentNotification( iSessionImpl, ETrue, iIdArray );
+            iIdArray.Reset();            
+	    	break;
+        	}
+        case EObjectNotifyNotPresent:
+        	{
+	    	MMdEObjectPresentObserver* obs = static_cast<MMdEObjectPresentObserver*>( iObserver );
+            obs->HandleObjectPresentNotification( iSessionImpl, EFalse, iIdArray );
+            iIdArray.Reset();            
+	    	break;
+        	}
+    	
+        case ERelationNotifyAdd:
+        	{
+	        MMdERelationObserver* obs = static_cast<MMdERelationObserver*>( iObserver );
+            obs->HandleRelationNotification( iSessionImpl, ENotifyAdd, iIdArray );
+            iIdArray.Reset();            
+	        break;
+        	}
+        case ERelationNotifyModify:
+        	{
+	        MMdERelationObserver* obs = static_cast<MMdERelationObserver*>( iObserver );
+            obs->HandleRelationNotification( iSessionImpl, ENotifyModify, iIdArray );
+            iIdArray.Reset();            
+	        break;
+        	}
+        case ERelationNotifyRemove:
+        	{
+	        MMdERelationObserver* obs = static_cast<MMdERelationObserver*>( iObserver );
+            obs->HandleRelationNotification( iSessionImpl, ENotifyRemove, iIdArray );
+            iIdArray.Reset();            
+	        break;
+        	}
+
+        case ERelationNotifyPresent:
+        	{
+	    	MMdERelationPresentObserver* obs = static_cast<MMdERelationPresentObserver*>( iObserver );
+            obs->HandleRelationPresentNotification( iSessionImpl, ETrue, iIdArray );
+            iIdArray.Reset();            
+	    	break;
+        	}
+        case ERelationNotifyNotPresent:
+        	{
+	    	MMdERelationPresentObserver* obs = static_cast<MMdERelationPresentObserver*>( iObserver );
+            obs->HandleRelationPresentNotification( iSessionImpl, EFalse, iIdArray );
+            iIdArray.Reset();            
+	    	break;
+        	}
+        	
+        case ERelationItemNotifyRemove:
+        	{
+        	MMdERelationItemObserver* obs = static_cast<MMdERelationItemObserver*>( iObserver );
+            obs->HandleRelationItemNotification( iSessionImpl, ENotifyRemove, iRelationItemArray );
+            iRelationItemArray.Reset();            
+        	break;
+        	}
+
+        case EEventNotifyAdd:
+        	{
+            MMdEEventObserver* obs = static_cast<MMdEEventObserver*>( iObserver );
+            obs->HandleEventNotification( iSessionImpl, ENotifyAdd, iIdArray);
+            iIdArray.Reset();            
+            break;
+        	}
+        case EEventNotifyRemove:
+        	{
+            MMdEEventObserver* obs = static_cast<MMdEEventObserver*>( iObserver );
+            obs->HandleEventNotification( iSessionImpl, ENotifyRemove, iIdArray);
+            iIdArray.Reset();            
+            break;
+        	}
+    	
+        case ESchemaModify:
+        	{
+            MMdESchemaObserver* obs = static_cast<MMdESchemaObserver*>( iObserver );
+            obs->HandleSchemaModified();
+        	break;
+        	}
+
+        default:
+        	// no observer to call - this should be skipped on server side!
+        	break;
+        }
+    }
+
+void CMdENotifierAO::DecodeIdBufferL()
+	{
+	// IDs are always stored in object IDs, 
+	// even if those are actually relation or event IDs
+	
+	iIdArray.Reset();
+	iDataBuffer->PositionL( KNoOffset );
+	const TMdCItemIds& itemIds = TMdCItemIds::GetFromBufferL( *iDataBuffer );
+	__ASSERT_DEBUG( iNamespaceDefId == itemIds.iNamespaceDefId, User::Panic( _L("Incorrect namespaceDef from returned items!"), KErrCorrupt ) );
+
+    iDataBuffer->PositionL( itemIds.iObjectIds.iPtr.iOffset );
+	for( TUint32 i = 0; i < itemIds.iObjectIds.iPtr.iCount; ++i )
+		{
+		TItemId id;
+		iDataBuffer->ReceiveL( id );
+		iIdArray.AppendL( id );
+		}
+	}
+
+void CMdENotifierAO::DecodeRelationItemBufferL()
+	{
+    iRelationItemArray.Reset();
+	iDataBuffer->PositionL( KNoOffset );
+	const TMdCItems& items = TMdCItems::GetFromBufferL( *iDataBuffer );
+	__ASSERT_DEBUG( iNamespaceDefId == items.iNamespaceDefId, User::Panic( _L("Incorrect namespaceDef from returned items!"), KErrCorrupt ) );
+
+    CMdENamespaceDef& namespaceDef = iSessionImpl.GetNamespaceDefL( iNamespaceDefId );
+    iDataBuffer->PositionL( items.iRelations.iPtr.iOffset );
+    TMdERelation relation;
+    for (TInt i = 0; i < items.iRelations.iPtr.iCount; ++i )
+    	{
+    	relation.DeSerializeL( *iDataBuffer, namespaceDef );
+    	if ( relation.Id() )
+    		{
+    		iRelationItemArray.Append( relation );
+    		}
+    	}
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeobject.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1035 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#include <mdeobject.h>
+
+#include <mdeproperty.h>
+#include <mdeobjectdef.h>
+#include <mdenamespacedef.h>
+#include <mdesession.h>
+#include "mdcitem.h"
+#include "mdscommoninternal.h"
+#include "mdcserializationbuffer.h"
+
+//////////////////////////////
+//                          //
+//        TMdEObject        //
+//                          //
+//////////////////////////////
+
+EXPORT_C TMdEObject::TMdEObject() : 
+	iDef( NULL )
+	{
+	}
+
+EXPORT_C TItemId TMdEObject::Id() const
+	{
+	return iId;
+	}
+
+EXPORT_C const CMdEObjectDef& TMdEObject::DefL() const
+	{
+	if( !iDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	return *iDef;
+	}
+
+EXPORT_C TBool TMdEObject::Confidential() const
+	{
+    return iFlags & EMdEObjectFlagConfidential ? ETrue : EFalse;
+	}
+
+EXPORT_C TBool TMdEObject::Placeholder() const
+	{
+	return iFlags & EMdEObjectFlagPlaceholder ? ETrue : EFalse;
+	}
+
+EXPORT_C TBool TMdEObject::Removed() const
+	{
+	return iFlags & EMdEObjectFlagRemoved ? ETrue : EFalse;
+	}
+
+EXPORT_C TBool TMdEObject::NotPresent() const
+	{
+	return iFlags & EMdEObjectFlagNotPresent ? ETrue : EFalse;
+	}
+
+TUint32 TMdEObject::RequiredBufferSize()
+	{
+	return sizeof(TMdCObject);
+	}
+
+void TMdEObject::DeSerializeL(CMdCSerializationBuffer& aBuffer, 
+		CMdENamespaceDef& aNamespaceDef)
+	{
+	const TMdCObject& object = TMdCObject::GetFromBufferL(aBuffer);
+
+	// ID
+	if ( object.iId == KNoId )
+		{
+		User::Leave( KErrNotFound );
+		}
+	iId = object.iId;
+
+	// definition
+	if ( object.iDefId == KNoDefId )
+		{
+		User::Leave( KErrNotFound );
+		}
+	iDef = aNamespaceDef.GetObjectDefL( object.iDefId );
+
+	// object flags	
+	iFlags = object.iFlags;
+	}
+
+//////////////////////////////
+//                          //
+//        CMdEObject        //
+//                          //
+//////////////////////////////
+
+CMdEObject* CMdEObject::NewL( CMdEObjectDef& aDef, const TDesC& aUri, TUint32 aMediaId )
+	{
+	CMdEObject* self = CMdEObject::NewLC( aDef, aUri, aMediaId );
+    CleanupStack::Pop( self );
+    return self;
+	}
+
+CMdEObject* CMdEObject::NewLC( CMdEObjectDef& aDef, const TDesC& aUri, TUint32 aMediaId )
+	{
+	CMdEObject* self = new ( ELeave ) CMdEObject( NULL, KNoId, aDef );
+    CleanupStack::PushL( self );
+    self->ConstructL( aUri, aMediaId );
+    return self;
+	}
+
+CMdEObject::CMdEObject(CMdESession* aSession, TItemId aId, CMdEObjectDef& aDef)
+		: CMdEInstanceItem( aSession, aId ), iDef( &aDef )
+	{
+	}
+
+void CMdEObject::ConstructL( const TDesC& aUri, TUint32 aMediaId )
+	{
+	InstanceItemBaseConstruct();
+
+	DoSetUriL( aUri );
+	
+	iMediaId = aMediaId;
+
+    iFlags = EMdEObjectFlagModOpen;
+   	}
+
+CMdEObject::~CMdEObject()
+	{
+	if ( OpenForModifications() && BelongsToSession() )
+		{
+		TRAP_IGNORE( Session().CancelObjectL( *this ) );
+		}
+
+	delete iUri;
+
+	iPropertyArray.ResetAndDestroy();
+	iPropertyArray.Close();
+
+	iFreeTextArray.ResetAndDestroy();
+	iFreeTextArray.Close();
+	}
+
+EXPORT_C CMdEObjectDef& CMdEObject::Def() const
+	{
+	__ASSERT_DEBUG( iDef, User::Panic( _L("Object def is NULL!"), KErrBadHandle ) );
+	
+	return *iDef;
+	}
+
+EXPORT_C void CMdEObject::SetDefL(CMdEObjectDef& aDef)
+	{
+	__ASSERT_DEBUG( iDef, User::Panic( _L("Object def is NULL!"), KErrBadHandle ) );
+
+	if( BelongsToSession() || ( iDef->Id() != KBaseObjectDefId ) )
+		{
+		User::Leave( KErrNotSupported );
+		}
+
+	iDef = &aDef;
+	}
+
+EXPORT_C const TDesC& CMdEObject::Uri() const
+	{
+	return *iUri;
+	}
+
+EXPORT_C void CMdEObject::SetUriL(const TDesC& aUri)
+	{
+	DoSetUriL(aUri);
+	}
+
+EXPORT_C TUint32 CMdEObject::MediaId() const
+	{
+	return iMediaId;
+	}
+
+EXPORT_C void CMdEObject::SetMediaId(TUint32 aMediaId)
+	{
+	iFlags |= EMdEObjectFlagModObject;
+	iMediaId = aMediaId;
+	}
+
+EXPORT_C TUint32 CMdEObject::UsageCount() const
+	{
+	return iUsageCount;
+	}
+
+EXPORT_C void CMdEObject::Guid( TInt64& aGuidHigh, TInt64& aGuidLow ) const
+	{
+	aGuidHigh = iGuidHigh;
+	aGuidLow  = iGuidLow;
+	}
+	
+EXPORT_C void CMdEObject::SetGuid( const TInt64& aGuidHigh, const TInt64& aGuidLow )
+	{
+	iFlags |= EMdEObjectFlagModObject;
+	iGuidHigh = aGuidHigh;
+	iGuidLow  = aGuidLow;
+	}
+
+
+EXPORT_C TBool CMdEObject::Confidential() const
+	{
+    return iFlags & EMdEObjectFlagConfidential ? ETrue : EFalse;
+	}
+
+EXPORT_C void CMdEObject::SetConfidential( TBool aValue )
+	{
+	//check if no change to value
+	if (Confidential() && aValue || !Confidential() && !aValue) // Confidential() == aValue
+		{
+		return;
+		}
+
+	if ( aValue )
+		{
+	    iFlags |= EMdEObjectFlagConfidential;
+		}
+	else
+		{
+	    iFlags &= ~EMdEObjectFlagConfidential;
+		}
+	iFlags |= EMdEObjectFlagModObject;
+	}
+
+EXPORT_C TBool CMdEObject::Placeholder() const
+	{
+	return iFlags & EMdEObjectFlagPlaceholder ? ETrue : EFalse;
+	}
+
+EXPORT_C void CMdEObject::SetPlaceholder( TBool aValue )
+	{
+	//check if no change to value
+	if ( Placeholder() && aValue || !Placeholder() && !aValue) // Placeholder() == aValue
+		{
+		return;
+		}
+
+	if ( aValue )
+		{
+		iFlags |= EMdEObjectFlagPlaceholder;
+		}
+	else
+		{
+		iFlags &= ~EMdEObjectFlagPlaceholder;
+		}
+	iFlags |= EMdEObjectFlagModObject;
+	}
+
+void CMdEObject::DoSetUriL(const TDesC& aUri)
+	{
+	if ( iUri )
+		{
+		if ( *iUri == aUri )
+			{
+			return;
+			}
+		else
+			{
+			delete iUri;
+			iUri = NULL;
+			}
+		}
+
+	iUri = HBufC::NewL( aUri.Length() );
+	iUri->Des().CopyLC( aUri );
+	iFlags |= EMdEObjectFlagModObject;
+	}
+
+EXPORT_C TInt CMdEObject::PropertyCount() const
+	{
+	const TInt propertyCount = iPropertyArray.Count();
+	if (!(iFlags & EMdEObjectFlagModObject))
+		{
+		return propertyCount;
+		}
+
+	TInt c = 0;
+	for (TInt i = 0; i < propertyCount; ++i)
+		{
+		if ( ! iPropertyArray[i]->Removed() )
+			{
+			++c;
+			}
+		}
+	return c;
+	}
+
+EXPORT_C CMdEProperty& CMdEObject::PropertyL(TInt aIndex) const
+	{
+	if ( aIndex < 0 || aIndex > PropertyCount() )
+		{
+		User::Leave( KErrArgument );
+		}
+	if (!(iFlags & EMdEObjectFlagModObject))
+		{
+		return *iPropertyArray[aIndex];
+		}
+	
+	TInt j = 0;
+	const TInt count = iPropertyArray.Count();
+	
+	for (TInt i = 0; i < count; ++i)
+		{
+		if ( ! iPropertyArray[i]->Removed() )
+			{
+			if (j == aIndex)
+				{
+				return *iPropertyArray[j];
+				}
+			++j;
+			}
+		}
+	User::Leave( KErrNotFound );
+	return *iPropertyArray[0]; // <-- just to stop compiler warnings!!
+	}
+
+EXPORT_C TInt CMdEObject::PropertyCount(const CMdEPropertyDef& aDef) const
+	{
+	TInt propCount = 0;
+	
+	const TInt count = iPropertyArray.Count();
+	
+	for (TInt i = 0; i < count; i++)
+		{
+        if( ! iPropertyArray[i]->Removed() &&
+            iPropertyArray[i]->Def().Compare( aDef ) == 0 )
+        	{
+        	++propCount;
+        	}
+		}
+    return propCount;
+	}
+
+EXPORT_C TInt CMdEObject::Property(const CMdEPropertyDef& aDef, CMdEProperty*& aProperty, TInt aStartAt) const
+    {
+    if (aStartAt <= 0)
+        {
+        const TInt i = iPropertyArray.FindInOrder(aDef, CMdEObject::CompareProperties );
+        if (i >= 0 && i < iPropertyArray.Count() && !iPropertyArray[i]->Removed())
+            {
+            aProperty = iPropertyArray[i];
+            return i;
+            }
+        }
+    return KErrNotFound;
+    }
+
+EXPORT_C CMdEProperty& CMdEObject::AddBoolPropertyL(CMdEPropertyDef& aDef, TBool aValue)
+	{
+    if( aDef.PropertyType() != EPropertyBool )
+    	{
+    	User::Leave( KErrArgument );
+    	}	
+	
+	CMdEProperty* property = CMdEProperty::NewLC(aDef, *this);
+	property->SetBoolValueL( aValue );
+	DoAddPropertyL(*property);
+	CleanupStack::Pop(property);
+
+	return *property;
+	}
+
+EXPORT_C CMdEProperty& CMdEObject::AddInt8PropertyL(CMdEPropertyDef& aDef, TInt8 aValue)
+	{
+    if( aDef.PropertyType() != EPropertyInt8 )
+    	{
+    	User::Leave( KErrArgument );
+    	}	
+	
+    CMdEProperty* property = CMdEProperty::NewLC(aDef, *this);
+    property->SetInt8ValueL( aValue );
+	DoAddPropertyL(*property);
+	CleanupStack::Pop(property);
+
+	return *property;
+	}
+
+EXPORT_C CMdEProperty& CMdEObject::AddUint8PropertyL(CMdEPropertyDef& aDef, TUint8 aValue)
+	{
+    if( aDef.PropertyType() != EPropertyUint8 )
+    	{
+    	User::Leave( KErrArgument );
+    	}	
+	
+    CMdEProperty* property = CMdEProperty::NewLC(aDef, *this);
+    property->SetUint8ValueL( aValue );
+	DoAddPropertyL(*property);
+	CleanupStack::Pop(property);
+
+	return *property;
+	}
+
+EXPORT_C CMdEProperty& CMdEObject::AddInt16PropertyL(CMdEPropertyDef& aDef, TInt16 aValue)
+	{
+    if( aDef.PropertyType() != EPropertyInt16 )
+    	{
+    	User::Leave( KErrArgument );
+    	}	
+	
+    CMdEProperty* property = CMdEProperty::NewLC(aDef, *this);
+    property->SetInt16ValueL( aValue );
+	DoAddPropertyL(*property);
+	CleanupStack::Pop(property);
+
+	return *property;
+	}
+
+EXPORT_C CMdEProperty& CMdEObject::AddUint16PropertyL(CMdEPropertyDef& aDef, TUint16 aValue)
+	{
+    if( aDef.PropertyType() != EPropertyUint16 )
+    	{
+    	User::Leave( KErrArgument );
+    	}	
+	
+    CMdEProperty* property = CMdEProperty::NewLC(aDef, *this);
+    property->SetUint16ValueL( aValue );
+	DoAddPropertyL(*property);
+	CleanupStack::Pop(property);
+
+	return *property;
+	}
+
+EXPORT_C CMdEProperty& CMdEObject::AddInt32PropertyL(CMdEPropertyDef& aDef, TInt32 aValue)
+	{
+    if( aDef.PropertyType() != EPropertyInt32 )
+    	{
+    	User::Leave( KErrArgument );
+    	}	
+
+    CMdEProperty* property = CMdEProperty::NewLC(aDef, *this);
+    property->SetInt32ValueL( aValue );
+	DoAddPropertyL(*property);
+	CleanupStack::Pop(property);
+
+	return *property;
+	}
+
+EXPORT_C CMdEProperty& CMdEObject::AddUint32PropertyL(CMdEPropertyDef& aDef, TUint32 aValue)
+	{
+    if( aDef.PropertyType() != EPropertyUint32 )
+    	{
+    	User::Leave( KErrArgument );
+    	}	
+
+    CMdEProperty* property = CMdEProperty::NewLC(aDef, *this);
+    property->SetUint32ValueL( aValue );
+	DoAddPropertyL(*property);
+	CleanupStack::Pop(property);
+
+	return *property;
+	}
+
+EXPORT_C CMdEProperty& CMdEObject::AddInt64PropertyL(CMdEPropertyDef& aDef, TInt64 aValue)
+	{
+    if( aDef.PropertyType() != EPropertyInt64 )
+	   	{
+    	User::Leave( KErrArgument );
+    	}
+
+    CMdEProperty* property = CMdEProperty::NewLC(aDef, *this);
+    property->SetInt64ValueL( aValue );
+	DoAddPropertyL(*property);
+	CleanupStack::Pop(property);
+
+	return *property;
+	}
+
+EXPORT_C CMdEProperty& CMdEObject::AddReal32PropertyL(CMdEPropertyDef& aDef, TReal32 aValue)
+	{
+    if( aDef.PropertyType() != EPropertyReal32 )
+    	{
+    	User::Leave( KErrArgument );
+    	}
+
+    CMdEProperty* property = CMdEProperty::NewLC(aDef, *this);
+    property->SetReal32ValueL( aValue );
+	DoAddPropertyL(*property);
+	CleanupStack::Pop(property);
+
+	return *property;
+	}
+
+EXPORT_C CMdEProperty& CMdEObject::AddReal64PropertyL(CMdEPropertyDef& aDef, TReal64 aValue)
+	{
+    if( aDef.PropertyType() != EPropertyReal64 )
+    	{
+    	User::Leave( KErrArgument );
+    	}
+
+    CMdEProperty* property = CMdEProperty::NewLC(aDef, *this);
+    property->SetReal64ValueL( aValue );
+	DoAddPropertyL(*property);
+	CleanupStack::Pop(property);
+
+	return *property;
+	}
+
+EXPORT_C CMdEProperty& CMdEObject::AddTextPropertyL(CMdEPropertyDef& aDef, const TDesC& aValue)
+	{
+    if( aDef.PropertyType() != EPropertyText )
+    	{
+    	User::Leave( KErrArgument );
+    	}
+	
+    CMdEProperty* property = CMdEProperty::NewLC(aDef, *this);
+    property->SetTextValueL( aValue );
+	DoAddPropertyL(*property);
+	CleanupStack::Pop(property);
+
+	return *property;
+	}
+
+EXPORT_C CMdEProperty& CMdEObject::AddTimePropertyL(CMdEPropertyDef& aDef, TTime aValue)
+	{
+    if( aDef.PropertyType() != EPropertyTime )
+    	{
+    	User::Leave( KErrArgument );
+    	}	
+
+    CMdEProperty* property = CMdEProperty::NewLC(aDef, *this);
+    property->SetTimeValueL( aValue );
+	DoAddPropertyL(*property);
+	CleanupStack::Pop(property);
+
+	return *property;
+	}
+
+void CMdEObject::DoAddPropertyL(CMdEProperty& aProperty)
+	{
+	TInt err = iPropertyArray.InsertInOrder(&aProperty, 
+								TLinearOrder<CMdEProperty>(CMdEObject::CompareProperties));
+	if (err == KErrAlreadyExists)
+		{
+		TInt f = iPropertyArray.FindInOrder(&aProperty,
+								TLinearOrder<CMdEProperty>(CMdEObject::CompareProperties));
+
+		// this must never happen
+		__ASSERT_DEBUG( f >= KErrNone, User::Panic( _L("AddProperty find!"), KErrGeneral ) );
+
+		if( ! iPropertyArray[f]->Removed() )
+			{
+			User::LeaveIfError( err );
+			}
+
+		CMdEProperty* oldProperty = iPropertyArray[f];
+		iPropertyArray[f] = &aProperty;
+		delete oldProperty;
+		}
+	else if (err < KErrNone)
+		{
+		User::Leave(err);
+		}
+
+	iFlags |= EMdEObjectFlagModProperty;
+	}
+
+EXPORT_C void CMdEObject::RemoveProperty(TInt aIndex)
+	{
+	const TInt propertyCount = iPropertyArray.Count();
+	if ( aIndex < 0 || aIndex >= propertyCount )
+		{
+		return;
+		}
+
+	TInt j = 0;
+	TBool found = EFalse;
+	for (TInt i = 0; i < propertyCount; ++i)
+		{
+		if ( ! iPropertyArray[i]->Removed() )
+			{
+			if (j == aIndex)
+				{
+				found = ETrue;
+				break;
+				}
+			++j;
+			}
+		}
+
+	if ( !found )
+		{
+		return;
+		}
+
+	CMdEProperty* property = iPropertyArray[j];
+	if( property->Def().ReadOnly() )
+    	{
+    	return;
+    	}
+
+	property->SetRemoved();
+
+	iFlags |= EMdEObjectFlagModProperty;
+	}
+
+TInt CMdEObject::CompareProperties(const CMdEProperty& aFirst, const CMdEProperty& aSecond)
+	{
+	return aFirst.Def().Compare( aSecond.Def() );
+	}
+
+EXPORT_C TInt CMdEObject::FreeTextCount() const
+	{
+	return iFreeTextArray.Count();
+	}
+
+EXPORT_C TPtrC CMdEObject::FreeText(TInt aIndex) const
+	{
+	return *iFreeTextArray[aIndex];
+	}
+
+EXPORT_C TInt CMdEObject::FreeTextIndex(const TDesC& aFreeText) const
+	{
+	const TInt count = iFreeTextArray.Count();
+	
+	for (TInt i = 0; i < count; i++)
+		{
+		if (aFreeText.Compare(*iFreeTextArray[i]) == 0)
+			{
+			return i;
+			}
+		}
+
+	return KErrNotFound;
+	}
+
+EXPORT_C void CMdEObject::AddFreeTextL(const TDesC& aFreeText)
+	{
+	HBufC* freeText = aFreeText.AllocLC();
+	if (DoAddFreeTextL(*freeText) == KErrNone)
+		{
+		CleanupStack::Pop(freeText);
+		}
+	else
+		{
+		CleanupStack::PopAndDestroy(freeText);
+		}
+	}
+
+TInt CMdEObject::DoAddFreeTextL(const HBufC& aFreeText)
+	{
+	TInt err = iFreeTextArray.InsertInOrder(&aFreeText, TLinearOrder<HBufC>(CMdEObject::CompareFreeTexts));
+
+	if (err == KErrNone)
+		{
+		iFlags |= EMdEObjectFlagModFreeText;
+		}
+	return err;
+	}
+
+EXPORT_C void CMdEObject::RemoveFreeText(TInt aIndex)
+	{
+	delete iFreeTextArray[aIndex];
+	iFreeTextArray[aIndex] = NULL;
+	iFreeTextArray.Remove(aIndex);
+	iFlags |= EMdEObjectFlagModFreeText;
+	}
+
+TInt CMdEObject::CompareFreeTexts(const HBufC& aFirst, const HBufC& aSecond)
+	{
+	return aFirst.Compare(aSecond);
+	}
+
+EXPORT_C void CMdEObject::MovePropertiesL(CMdEObject& aObject)
+	{
+	__ASSERT_DEBUG( iDef, User::Panic( _L("Object def is NULL!"), KErrBadHandle ) );
+	
+	// definitions must match
+	if ( iDef->Compare( *aObject.iDef ) )
+		{
+		User::Leave( KErrArgument );
+		}
+
+	// object must be open
+	if ( !OpenForModifications() )
+		{
+		User::Leave( KErrAccessDenied );
+		}
+
+	// and cannot contain any properties
+	ClearObject( EFalse );
+	if ( iPropertyArray.Count() )
+		{
+		User::Leave( KErrAlreadyExists );
+		}
+
+	const TInt arraySize = aObject.iPropertyArray.Count();
+	iPropertyArray.ReserveL( arraySize );
+
+	// add all properties to this object, 
+	// but don't remove yet from other object
+	for ( TInt i = 0; i < arraySize; ++i )
+		{
+		TRAPD( err, iPropertyArray.AppendL( aObject.iPropertyArray[i] ) );
+		if (err != KErrNone)
+			{
+			// restore this objects to original state
+			iPropertyArray.Reset();
+			User::Leave( err );
+			}
+		}
+
+	// remove properties from other object
+	aObject.iPropertyArray.Reset();
+
+	// mark all moved properties as modified
+	for ( TInt i = 0; i < arraySize; ++i )
+		{
+		CMdEProperty* property = iPropertyArray[i];
+		property->SetModified();
+		}
+
+	iFlags |= EMdEObjectFlagModProperty;
+	}
+
+
+TBool CMdEObject::ObjectModified() const
+    {
+    return iFlags & EMdEObjectFlagModObject ? ETrue : EFalse;
+    }
+
+TBool CMdEObject::FreeTextModified() const
+    {
+    return iFlags & EMdEObjectFlagModFreeText ? ETrue : EFalse;
+    }
+
+TBool CMdEObject::PropertyModified() const
+    {
+    return iFlags & EMdEObjectFlagModProperty ? ETrue : EFalse;
+    }
+
+void CMdEObject::AutoLockL() const
+	{
+	if( BelongsToSession() )
+		{
+		User::Leave( KErrAlreadyExists );
+		}
+	
+	iFlags |= EMdEObjectFlagAutoLock;
+	}
+
+EXPORT_C TBool CMdEObject::OpenForModifications() const
+	{
+	return iFlags & EMdEObjectFlagModOpen ? ETrue : EFalse;
+	}
+
+void CMdEObject::ClearObject( TBool aClearFlags )
+	{
+	// clear mod flags
+	if (aClearFlags)
+		{
+		iFlags &= ~(EMdEObjectFlagModObject | EMdEObjectFlagModProperty | EMdEObjectFlagModFreeText | EMdEObjectFlagModOpen);
+
+		// auto locked object's are marked back to open for modifications
+		if ( iFlags & EMdEObjectFlagAutoLock )
+			{
+			iFlags |= EMdEObjectFlagModOpen;
+			}
+		}
+
+	// clear mod flags in properties
+	for (TInt i = iPropertyArray.Count() - 1; i >= 0 ; --i)
+		{
+    	CMdEProperty* prop = iPropertyArray[i];
+        if ( prop->Removed() )
+        	{
+        	delete prop;
+        	iPropertyArray.Remove( i );
+        	continue;
+        	}
+        if (aClearFlags)
+        	{
+        	prop->ClearFlags();
+        	}
+		}
+	}
+
+void CMdEObject::SetNotOpenForModifications()
+	{
+	iFlags &= ~EMdEObjectFlagModOpen;
+	}
+
+TUint32 CMdEObject::ModifiedPropertiesCount() const
+	{
+	TUint32 modCount = 0;
+	const TInt count = iPropertyArray.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		if (iPropertyArray[i]->Modified())
+			{
+			++modCount;
+			}
+		}
+	return modCount;
+	}
+
+TUint32 CMdEObject::RequiredBufferSize() const
+	{
+	TUint32 bufferSize = sizeof( TMdCObject );
+
+	if (iUri)
+		{
+		bufferSize += CMdCSerializationBuffer::RequiredSize( *iUri );
+		}
+
+	TUint32 bufSave = bufferSize;
+	// properties
+	if ( iPropertyArray.Count() > 0 )
+		{
+		const TInt count = iPropertyArray.Count();
+		for ( TInt i = 0; i < count; ++i )
+			{
+			if (iPropertyArray[i]->Modified())
+				{
+				bufferSize += iPropertyArray[i]->RequiredBufferSize();
+				iFlags |= EMdEObjectFlagModProperty;
+				}
+			}
+		}
+	
+	if (!(iFlags & EMdEObjectFlagModProperty))
+		{
+		bufferSize = bufSave;
+		}
+	
+	// freetext
+	if ( iFlags & EMdEObjectFlagModFreeText && iFreeTextArray.Count() > 0 )
+		{
+		
+		const TInt count = iFreeTextArray.Count();
+		for ( TInt i = 0; i < count; ++i )
+			{
+			bufferSize += CMdCSerializationBuffer::RequiredSize( *iFreeTextArray[i] );
+			}
+		}
+
+	return bufferSize;
+	}
+
+TMdCOffset CMdEObject::SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreespaceOffset) const
+	{
+	__ASSERT_DEBUG( iDef, User::Panic( _L("Object def is NULL!"), KErrBadHandle ) );
+
+	const TMdCOffset objectOffset = aBuffer.Position();
+	TMdCObject object;
+	
+	// objectId
+	object.iId = Id();
+	// objectDefId
+	object.iDefId = iDef->Id();
+	// object flags
+	object.iFlags = iFlags;
+	// mediaId
+	object.iMediaId = iMediaId;
+	// usageCount
+	object.iUsageCount = iUsageCount;
+	// guid low
+	object.iGuidHigh = iGuidHigh;
+	// guid high
+	object.iGuidLow = iGuidLow;
+	// uri
+	object.iUri.iPtr.iCount = iUri->Length();
+	object.iUri.iPtr.iOffset = aFreespaceOffset;
+	
+	aBuffer.PositionL( aFreespaceOffset );
+	aFreespaceOffset = aBuffer.InsertL( *iUri );
+
+	// adding properties
+	if ( iFlags & EMdEObjectFlagModProperty && iPropertyArray.Count() > 0 )
+		{
+		// first set up offset and count to properties
+		object.iProperties.iPtr.iOffset = aFreespaceOffset;
+		object.iProperties.iPtr.iCount = ModifiedPropertiesCount();
+
+		// move after properties table
+		aFreespaceOffset += object.iProperties.iPtr.iCount * sizeof( TMdCProperty );
+
+		const TInt count = iPropertyArray.Count();
+		TInt modifiedPropertyCounter = 0;
+		// insert properties
+		for ( TInt i = 0; i < count; ++i )
+			{
+			if (!iPropertyArray[i]->Modified())
+				{
+				continue;
+				}
+			aBuffer.PositionL( object.iProperties.iPtr.iOffset + modifiedPropertyCounter * sizeof( TMdCProperty ) );
+			aFreespaceOffset = iPropertyArray[i]->SerializeL(aBuffer, aFreespaceOffset);
+			++modifiedPropertyCounter;
+			}
+		}
+	else
+		{
+		object.iProperties.iPtr.iOffset = KNoOffset;
+		object.iProperties.iPtr.iCount = 0;
+		}
+
+	// adding freetext
+	if ( iFlags & EMdEObjectFlagModFreeText && iFreeTextArray.Count() > 0 )
+		{
+		// first set up offset to freetext
+		object.iFreeTexts.iPtr.iOffset = aFreespaceOffset;
+		object.iFreeTexts.iPtr.iCount = iFreeTextArray.Count();
+
+		const TInt count = iFreeTextArray.Count();
+		
+		// insert freetext
+		aBuffer.PositionL( aFreespaceOffset );
+		for ( TInt i = 0; i < count; ++i )
+			{
+			aFreespaceOffset = aBuffer.InsertL( *iFreeTextArray[i] );
+			}
+		}
+	else
+		{
+		object.iFreeTexts.iPtr.iOffset = KNoOffset;
+		object.iFreeTexts.iPtr.iCount = 0;
+		}
+	
+	// store object informations
+	aBuffer.PositionL( objectOffset );
+	object.SerializeL( aBuffer );
+
+	return aFreespaceOffset;
+	}
+
+CMdEObject* CMdEObject::NewL( CMdESession* aSession, CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef )
+	{
+	CMdEObject* ret = CMdEObject::NewLC( aSession, aBuffer, aNamespaceDef );
+	CleanupStack::Pop( ret );
+	return ret;
+	}
+
+
+CMdEObject* CMdEObject::NewLC( CMdESession* aSession, CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef )
+	{
+	const TMdCObject& serializedObject = TMdCObject::GetFromBufferL( aBuffer );
+	
+	// objectid
+	if (serializedObject.iId == KNoId)
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	// objectDefId
+	if (serializedObject.iDefId == KNoDefId)
+		{
+		User::Leave( KErrNotFound );
+		}
+	CMdEObjectDef* newObjectDef = aNamespaceDef.GetObjectDefL( serializedObject.iDefId );
+	if( !newObjectDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	CMdEObject* newObject = new (ELeave) CMdEObject( aSession, serializedObject.iId, *newObjectDef );
+	CleanupStack::PushL( newObject );
+
+	// set correct variables
+	// object flags
+	newObject->iFlags = serializedObject.iFlags;
+	// mediaId
+	newObject->iMediaId = serializedObject.iMediaId;
+	// usage count
+	newObject->iUsageCount = serializedObject.iUsageCount;
+	// guid low
+	newObject->iGuidHigh = serializedObject.iGuidHigh;
+	// guid high
+	newObject->iGuidLow = serializedObject.iGuidLow;
+	// uri
+	if ( serializedObject.iUri.iPtr.iCount == 0 )
+		{
+		User::Leave( KErrNotFound );
+		}
+	aBuffer.PositionL( serializedObject.iUri.iPtr.iOffset );
+	newObject->iUri = aBuffer.ReceiveDes16L();
+
+	// read properties array
+	if ( serializedObject.iProperties.iPtr.iOffset != KNoOffset )
+		{
+		newObject->iPropertyArray.ReserveL( serializedObject.iProperties.iPtr.iCount );
+
+		for ( TUint32 i = 0; i < serializedObject.iProperties.iPtr.iCount; ++i )
+			{
+			aBuffer.PositionL( serializedObject.iProperties.iPtr.iOffset
+					+ i * sizeof(TMdCProperty) );
+
+			CMdEProperty* property = CMdEProperty::NewLC( *newObject, aBuffer );
+			newObject->iPropertyArray.AppendL( property );
+			CleanupStack::Pop( property );
+			}
+		}
+
+	// read freetext array
+	if ( serializedObject.iFreeTexts.iPtr.iOffset != KNoOffset )
+		{
+		aBuffer.PositionL( serializedObject.iFreeTexts.iPtr.iOffset );
+
+		newObject->iFreeTextArray.ReserveL( serializedObject.iFreeTexts.iPtr.iCount );
+		for ( TUint32 i = 0; i < serializedObject.iFreeTexts.iPtr.iCount; ++i )
+			{
+			HBufC16* hbuf = aBuffer.ReceiveDes16L();
+			CleanupStack::PushL( hbuf );
+			newObject->iFreeTextArray.AppendL( hbuf );
+			CleanupStack::Pop( hbuf );
+			}
+		}
+
+	return newObject;
+	}
+
+TMdEInstanceType CMdEObject::InstanceType() const
+	{
+	return EMdETypeObject;
+	}
+
+TInt CMdEObject::CompareProperties(const CMdEPropertyDef* aPropertyDef, const CMdEProperty& aProperty)
+    {
+    return aPropertyDef->Compare( aProperty.Def() );
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeobjectcondition.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,440 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+#include "mdeobjectcondition.h"
+#include "mdcserializationbuffer.h"
+#include "mdeobjectdef.h"
+#include "mdepanic.h"
+#include "mdscommoninternal.h"
+#include "mdcquery.h"
+
+
+CMdEObjectCondition* CMdEObjectCondition::NewL( TObjectConditionCompareMethod aCompareMethod,
+		TItemId aObjectId, const CMdEObjectDef* aObjectDef,
+		TInt64 aObjectGuidHigh, TInt64 aObjectGuidLow )
+	{
+	CMdEObjectCondition* self = CMdEObjectCondition::NewLC( aCompareMethod,
+			aObjectId, aObjectDef, aObjectGuidHigh, aObjectGuidLow );
+	CleanupStack::Pop( self );
+	return self;	
+	}
+
+CMdEObjectCondition* CMdEObjectCondition::NewLC( TObjectConditionCompareMethod aCompareMethod,
+		TItemId aObjectId, const CMdEObjectDef* aObjectDef,
+		TInt64 aObjectGuidHigh, TInt64 aObjectGuidLow )
+	{
+	CMdEObjectCondition* self = new (ELeave) CMdEObjectCondition( aCompareMethod,
+			aObjectId, aObjectDef, aObjectGuidHigh, aObjectGuidLow );
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+	}
+
+CMdEObjectCondition* CMdEObjectCondition::NewL( TObjectConditionCompareMethod aCompareMethod,
+		const RArray<TItemId>* aObjectIds, const TDesC* aString, const TMdEUintRange* aRange )
+	{
+	CMdEObjectCondition* self = CMdEObjectCondition::NewLC( aCompareMethod, aObjectIds, aString, aRange );
+	CleanupStack::Pop( self );
+	return self;	
+	}
+
+CMdEObjectCondition* CMdEObjectCondition::NewLC( TObjectConditionCompareMethod aCompareMethod,
+		const RArray<TItemId>* aObjectIds, const TDesC* aString, const TMdEUintRange* aRange )
+	{
+	CMdEObjectCondition* self = new (ELeave) CMdEObjectCondition( aCompareMethod );
+	CleanupStack::PushL( self );
+	self->ConstructL( aObjectIds, aString, aRange );
+	return self;
+	}
+
+
+CMdEObjectCondition::CMdEObjectCondition( TObjectConditionCompareMethod aCompareMethod,
+									TItemId aObjectId, const CMdEObjectDef* aObjectDef,
+									TInt64 aObjectGuidHigh, TInt64 aObjectGuidLow )
+	: CMdECondition(EConditionTypeObject), iObjectDef( aObjectDef ), 
+	  iObjectId( aObjectId ), iObjectIds( NULL ), 
+	  iString( NULL ), iCompareMethod( aCompareMethod ), iFlags( 0 ),
+	  iConfidentialityLevel(EObjectConditionLevelNormal),
+	  iGuidHigh( aObjectGuidHigh ), iGuidLow( aObjectGuidLow ),
+	  iRange( NULL )
+	{
+	#ifdef _DEBUG
+	if ( iObjectDef )
+		{
+		__ASSERT_DEBUG(aCompareMethod == EObjectConditionCompareObjectDef, TMdEPanic::Panic(TMdEPanic::EInternal));
+		}
+	else if ( iObjectId != KNoId )
+		{
+		__ASSERT_DEBUG(aCompareMethod == EObjectConditionCompareId, TMdEPanic::Panic(TMdEPanic::EInternal));
+		}
+	else if ( iGuidHigh != 0 || iGuidLow != 0 )
+		{
+		__ASSERT_DEBUG(aCompareMethod == EObjectConditionCompareGuid, TMdEPanic::Panic(TMdEPanic::EInternal));
+		}
+	else
+		{
+		__ASSERT_DEBUG(aCompareMethod == EObjectConditionCompareNone, TMdEPanic::Panic(TMdEPanic::EInternal));
+		}
+	
+	#endif
+	}
+
+CMdEObjectCondition::CMdEObjectCondition( TObjectConditionCompareMethod aCompareMethod )
+	: CMdECondition(EConditionTypeObject), iObjectDef( NULL ), 
+	  iObjectId( KNoId ), iObjectIds( NULL ), 
+	  iString( NULL ), iCompareMethod( aCompareMethod ), iFlags( 0 ),
+	  iConfidentialityLevel(EObjectConditionLevelNormal), iGuidHigh( 0 ), iGuidLow( 0 )
+	{
+	__ASSERT_DEBUG(iCompareMethod > EObjectConditionCompareFirst && iCompareMethod < EObjectConditionCompareLast, TMdEPanic::Panic(TMdEPanic::EInternal));
+	}
+
+void CMdEObjectCondition::ConstructL()
+    {
+    // Base class construction.
+    ConditionConstruct();
+    
+    // Non-confidential objects are queried by default
+    iConfidentialityLevel = EObjectConditionLevelNormal;
+    }
+
+void CMdEObjectCondition::ConstructL( const RArray<TItemId>* aObjectIds,
+		const TDesC* aString, const TMdEUintRange* aRange )
+	{
+	if ( aString )
+		{
+		iString = HBufC::NewL(aString->Length());
+		iString->Des().CopyLC( *aString );
+		}
+	else if ( aObjectIds )
+		{
+	    iObjectIds = new (ELeave) RArray<TItemId>;
+		
+	    const TInt objectIdCount = aObjectIds->Count();
+	    iObjectIds->ReserveL( objectIdCount );
+	    
+		for( TInt i = 0; i < objectIdCount; i++ )
+			{
+			iObjectIds->Append( (*aObjectIds)[i] );
+			}
+		}
+	else if ( aRange )
+		{
+		iRange = new(ELeave) TMdEUintRange(*aRange);
+		}
+	else
+		{
+		User::Leave( KErrArgument );
+		}
+	}
+
+CMdEObjectCondition::~CMdEObjectCondition()
+	{
+   	delete iString;
+
+   	if( iObjectIds )
+    	{
+    	iObjectIds->Close();
+    	
+    	delete iObjectIds;
+    	}
+    
+   	delete iRange;
+	}
+
+EXPORT_C const CMdEObjectDef* CMdEObjectCondition::ObjectDef() const
+    {
+    return iObjectDef;
+    }
+
+EXPORT_C TItemId CMdEObjectCondition::ObjectId() const
+    {
+    return iObjectId;
+    }
+
+EXPORT_C const RArray<TItemId>* CMdEObjectCondition::ObjectIds() const
+	{
+	return iObjectIds;
+	}
+
+EXPORT_C const TDesC* CMdEObjectCondition::String() const
+    {
+    return iString;
+    }
+
+
+EXPORT_C TObjectConditionCompareMethod CMdEObjectCondition::CompareMethod() const
+    {
+    return iCompareMethod;
+    }
+
+
+EXPORT_C TObjectConditionConfidentialityLevel CMdEObjectCondition::ConfidentialityLevel() const
+    {
+    return iConfidentialityLevel;
+    }
+
+EXPORT_C void CMdEObjectCondition::SetConfidentialityLevel( TObjectConditionConfidentialityLevel aLevel )
+    {
+    iConfidentialityLevel = aLevel;
+    }
+
+EXPORT_C TBool CMdEObjectCondition::NotPresent() const
+	{
+	return iFlags & EMdEObjectFlagNotPresent ? ETrue : EFalse;
+	}
+
+EXPORT_C void CMdEObjectCondition::SetNotPresent(TBool aNotPresent)
+	{
+	if( aNotPresent )
+		{
+		iFlags |= EMdEObjectFlagNotPresent; 
+		}
+	else
+		{
+		iFlags &= ~EMdEObjectFlagNotPresent;
+		}
+	}
+
+EXPORT_C TBool CMdEObjectCondition::NotPlaceholder() const
+	{
+	return iFlags & EMdEObjectFlagPlaceholder ? ETrue : EFalse;
+	}
+
+EXPORT_C void CMdEObjectCondition::SetNotPlaceholder(TBool aNotPlaceholder)
+	{
+	if( aNotPlaceholder )
+		{
+		iFlags |= EMdEObjectFlagPlaceholder; 
+		}
+	else
+		{
+		iFlags &= ~EMdEObjectFlagPlaceholder;
+		}
+	}
+
+EXPORT_C TBool CMdEObjectCondition::PlaceholderOnly() const
+    {
+    return iPlaceholdersOnly;
+    }
+
+EXPORT_C void CMdEObjectCondition::SetPlaceholderOnly(TBool aPlaceholderOnly )
+    {
+    iPlaceholdersOnly = aPlaceholderOnly;
+    }
+
+TUint32 CMdEObjectCondition::InternalQueryOptimizationFlags(TUint32& aFlags)
+	{
+	TUint32 optimizationFlags = EContainsObjectCondition;
+
+	if( iFlags & EMdEObjectFlagNotPresent )
+		{
+		optimizationFlags |= EContainsNotPresentCondition;
+		}
+
+	switch( iCompareMethod )
+		{
+        case EObjectConditionCompareFreeText:
+        case EObjectConditionCompareFreeTextContains:
+        case EObjectConditionCompareFreeTextBeginsWith:
+        case EObjectConditionCompareFreeTextEndsWith:
+			optimizationFlags |= EContainsFreetextCondition;
+			break;
+		default:
+			break;
+		}
+	
+	if( iPlaceholdersOnly )
+	    {
+	    optimizationFlags |= EContainsPlaceholdersOnly;
+	    }
+
+	aFlags |= optimizationFlags;
+	return optimizationFlags;
+	}
+
+TUint32 CMdEObjectCondition::RequiredBufferSize() const
+	{
+	TUint32 bufferSize = sizeof( TMdCObjectCondition );
+
+	switch( iCompareMethod )
+		{
+		case EObjectConditionCompareNone:
+			break;
+
+		case EObjectConditionCompareId:
+			{
+			// Required size for object ID
+			bufferSize += CMdCSerializationBuffer::KRequiredSizeForTItemId;
+			}
+			break;
+
+		case EObjectConditionCompareIds:
+			{
+			// Required size for object ID
+			bufferSize += CMdCSerializationBuffer::KRequiredSizeForTUint32; // count
+			if( iObjectIds )
+				{
+				bufferSize += CMdCSerializationBuffer::KRequiredSizeForTItemId * iObjectIds->Count();
+				}
+			}
+			break;
+
+	    case EObjectConditionCompareGuid:
+	    	{
+			// Required size for object GUID high (TInt64), object GUID low (TInt64)
+			bufferSize += 2 * CMdCSerializationBuffer::KRequiredSizeForTInt64;
+	    	}
+			break;
+
+	    case EObjectConditionCompareObjectDef:
+	    	{
+			// Required size for object def ID (TUint32)
+			bufferSize += CMdCSerializationBuffer::KRequiredSizeForTDefId;
+	    	}
+			break;
+
+	    case EObjectConditionCompareUri:
+	    case EObjectConditionCompareUriBeginsWith:
+	    case EObjectConditionCompareFreeText:
+	    case EObjectConditionCompareFreeTextContains:
+	    case EObjectConditionCompareFreeTextBeginsWith:
+	    case EObjectConditionCompareFreeTextEndsWith:
+	    	{
+			// Required size for string
+			bufferSize += CMdCSerializationBuffer::RequiredSize( *iString );
+	    	}
+			break;
+
+	    case EObjectConditionCompareUsageCount:
+	    	{
+	    	__ASSERT_DEBUG( iRange, User::Panic( _L("Incorrect range condition"), KErrArgument ) );
+	    	bufferSize += iRange->RequiredBufferSize();
+	    	}
+	    	break;
+
+	    default:
+			TMdEPanic::Panic( TMdEPanic::EInternal );
+			break;
+		}
+
+	return bufferSize;
+	}
+
+void CMdEObjectCondition::SerializeL(CMdCSerializationBuffer& aBuffer, 
+		TMdCOffset& aFreespaceOffset) const
+	{
+	const TUint32 conditionOffset = aBuffer.Position();
+	const TUint32 subConditionOffset = 
+			conditionOffset + sizeof( TMdCObjectCondition );
+
+	TMdCObjectCondition condition; 
+
+	condition.iConditionType = iType;
+	condition.iNegated = iNegated;
+	condition.iConfidentialityLevel = iConfidentialityLevel;
+	condition.iCompareMethod = iCompareMethod;
+	condition.iFlags = iFlags;
+	condition.iCondition = subConditionOffset;
+
+	aBuffer.PositionL( subConditionOffset );
+
+	switch( iCompareMethod )
+		{
+		case EObjectConditionCompareNone:
+			{
+			// nothing to compare, so "clear" condition offset
+			condition.iCondition = KNoOffset;
+			}
+			break;
+	
+		case EObjectConditionCompareId:
+			{
+			aBuffer.InsertL( iObjectId );
+			}
+			break;
+	
+		case EObjectConditionCompareIds:
+			{
+			if( iObjectIds )
+				{
+				const TInt count = iObjectIds->Count();
+				
+				aBuffer.InsertL( (TInt32)count );
+				
+				for( TInt i = 0; i < count; i++ )
+					{
+					aBuffer.InsertL( (*iObjectIds)[i] );
+					}
+				}
+			else
+				{
+				aBuffer.InsertL( TInt32( 0 ) );
+				}
+			}
+			break;
+	
+	    case EObjectConditionCompareGuid:
+			{
+			aBuffer.InsertL( iGuidHigh );
+			aBuffer.InsertL( iGuidLow );
+			}
+			break;
+
+	    case EObjectConditionCompareObjectDef:
+			{
+			aBuffer.InsertL( iObjectDef->Id() );
+			}
+			break;
+
+	    case EObjectConditionCompareUsageCount:
+			{
+			__ASSERT_DEBUG( iRange, User::Panic( 
+					_L("Incorrect range condition"), KErrArgument ) );
+			iRange->SerializeL( aBuffer );
+			}
+			break;
+
+	    case EObjectConditionCompareUri:
+	    case EObjectConditionCompareUriBeginsWith:
+	    case EObjectConditionCompareFreeText:
+	    case EObjectConditionCompareFreeTextContains:
+	    case EObjectConditionCompareFreeTextBeginsWith:
+	    case EObjectConditionCompareFreeTextEndsWith:
+			{
+			aBuffer.InsertL( *iString );
+			}
+			break;
+
+		default:
+			{
+#ifdef _DEBUG
+			TMdEPanic::Panic(TMdEPanic::EInternal);
+#endif
+			}
+			break;
+		}
+
+	// get position after sub condition
+	aFreespaceOffset = aBuffer.Position();
+
+	// serialize condition
+	aBuffer.PositionL( conditionOffset );
+	condition.SerializeL( aBuffer );
+	
+	// and move back to after sub condition
+	aBuffer.PositionL( aFreespaceOffset );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeobjectdef.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,194 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#include "mdeobjectdef.h"
+
+#include "mdcdef.h"
+#include "mdenamespacedef.h"
+#include "mdepropertydef.h"
+#include "mdcserializationbuffer.h"
+#include "mdscommoninternal.h"
+
+
+CMdEObjectDef::CMdEObjectDef( const TMdCObjectDef& aObjectDef, CMdENamespaceDef& aNamespaceDef )
+    : iObjectDef( aObjectDef ), iNamespaceDef(aNamespaceDef)
+    {
+    }
+
+CMdEObjectDef* CMdEObjectDef::NewL( const TMdCObjectDef& aObjectDef,
+		CMdCSerializationBuffer& aSchemaBuffer, CMdENamespaceDef& aNamespaceDef )
+    {
+    CMdEObjectDef* def = CMdEObjectDef::NewLC( aObjectDef, aSchemaBuffer, aNamespaceDef );
+    CleanupStack::Pop( def );
+    return def;
+    }
+
+CMdEObjectDef* CMdEObjectDef::NewLC( const TMdCObjectDef& aObjectDef,
+		CMdCSerializationBuffer& aSchemaBuffer, CMdENamespaceDef& aNamespaceDef )
+    {
+    CMdEObjectDef* def = new( ELeave ) CMdEObjectDef( aObjectDef, aNamespaceDef );
+    CleanupStack::PushL( def );
+    def->ConstructL(aSchemaBuffer);
+    return def;
+    }
+
+void CMdEObjectDef::ConstructL(CMdCSerializationBuffer& aSchemaBuffer)
+    {
+    const TUint32 propertyCount = iObjectDef.iPropertyDefs.iPtr.iCount;
+    const TUint32 propertyOffset = iObjectDef.iPropertyDefs.iPtr.iOffset;
+
+	aSchemaBuffer.PositionL( iObjectDef.iName.iPtr.iOffset );
+	iName.Set( aSchemaBuffer.ReceivePtr16L() );
+
+    iPropertyDefs.ReserveL( propertyCount );
+    for ( TUint32 i = 0; i < propertyCount; ++i )
+        {
+		aSchemaBuffer.PositionL( propertyOffset + i * sizeof(TMdCPropertyDef) );
+		const TMdCPropertyDef& propertyDef = TMdCPropertyDef::GetFromBufferL(aSchemaBuffer);
+		iPropertyDefs.AppendL( CMdEPropertyDef::NewL( propertyDef, aSchemaBuffer, *this ) );
+        }
+    }
+
+CMdEObjectDef::~CMdEObjectDef()
+    {
+    iPropertyDefs.ResetAndDestroy();
+    iPropertyDefs.Close();
+    }
+
+TDefId CMdEObjectDef::Id() const
+    {
+    return iObjectDef.iDefId;
+    }
+
+EXPORT_C CMdENamespaceDef& CMdEObjectDef::NamespaceDef() const
+    {
+    return iNamespaceDef;
+    }
+
+EXPORT_C CMdEObjectDef* CMdEObjectDef::ParentL()
+    {
+    if ( iObjectDef.iParentId == KNoDefId )
+        {
+        return NULL;
+        }
+    return iNamespaceDef.GetObjectDefL( iObjectDef.iParentId );
+    }
+
+EXPORT_C const TDesC& CMdEObjectDef::Name() const
+    {
+    return iName;
+    }
+
+EXPORT_C TInt CMdEObjectDef::Compare( const CMdEObjectDef& aObjectDef ) const
+    {
+    TInt result = iNamespaceDef.Compare( aObjectDef.iNamespaceDef );
+    if ( result == 0 )
+        {
+        result = iObjectDef.iDefId - aObjectDef.Id();
+        }
+    return result;
+    }
+
+EXPORT_C TInt CMdEObjectDef::PropertyDefCount() const
+    {
+    return iPropertyDefs.Count();
+    }
+
+EXPORT_C CMdEPropertyDef& CMdEObjectDef::PropertyDefL(TInt aIndex)
+	{
+	CMdEPropertyDef* propertyDef = PropertyDefL(aIndex, NULL);
+	if (!propertyDef)
+		{
+		User::Leave( KErrNotFound );
+		}
+	return *propertyDef;
+	}
+
+EXPORT_C CMdEPropertyDef& CMdEObjectDef::GetPropertyDefL( const TDesC& aName )
+	{
+	CMdEPropertyDef* propertyDef = GetPropertyDefL(aName, NULL);
+	if (!propertyDef)
+		{
+		User::Leave( KErrNotFound );
+		}
+	return *propertyDef;
+	}
+
+CMdEPropertyDef* CMdEObjectDef::GetPropertyDefL( const TDesC& aName, CMdEObjectDef* aChild )
+    {
+    const TInt propertyDefCount = iPropertyDefs.Count();
+    for ( TInt i = 0; i < propertyDefCount; ++i )
+        {
+        if( aName.Compare( iPropertyDefs[i]->Name() ) == 0 )
+        	{
+        	return &PropertyDefL(i);
+        	}
+        }
+
+    CMdEObjectDef* parent = ParentL();
+    if ( parent ) 
+        {
+        if( !aChild )
+            {
+            return parent->GetPropertyDefL( aName, this );
+            }
+        else
+            {
+            return parent->GetPropertyDefL( aName, aChild );
+            }
+        }
+    return NULL;
+    }
+
+CMdEPropertyDef* CMdEObjectDef::GetPropertyDefL(TDefId aId, CMdEObjectDef* aChild)
+    {
+    const TInt count = iPropertyDefs.Count();
+    
+    for ( TInt i = 0; i < count; ++i )
+        {
+        CMdEPropertyDef* propDef = iPropertyDefs[i];
+        
+        if( propDef && propDef->Id() == aId )
+        	{
+        	return propDef;
+        	}
+        }
+
+    CMdEObjectDef* parent = ParentL();
+    if ( parent ) 
+        {
+        if ( !aChild )
+            {                
+            return parent->GetPropertyDefL( aId, this );
+            }
+        else
+            {
+            return parent->GetPropertyDefL( aId, aChild );
+            }
+        }
+    return NULL;
+    }
+
+CMdEPropertyDef* CMdEObjectDef::PropertyDefL(TInt aIndex, CMdEObjectDef* /*aChild*/)
+	{
+	if ( aIndex < 0 || aIndex > iPropertyDefs.Count())
+	    {
+	    User::Leave( KErrArgument );
+	    }
+
+	return iPropertyDefs[aIndex];
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeobjectquery.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,77 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface for object query
+*
+*/
+
+
+#include "mdeobjectquery.h"
+#include "mdeobject.h"
+
+
+CMdEObjectQuery::CMdEObjectQuery(CMdESession& aSession, CMdENamespaceDef& aNamespaceDef, 
+		CMdEObjectDef& aObjectDef, RPointerArray<CMdEObjectDef>* aObjectDefs)
+        : CMdEQuery(EQueryTypeObject, aSession, aNamespaceDef), 
+          iObjectDef(aObjectDef), iObjectDefs(aObjectDefs),
+          iFreetextsInResult( ETrue )
+    {
+    }
+
+void CMdEObjectQuery::ObjectQueryConstructL()
+    {
+    QueryConstructL();
+    }
+
+CMdEObjectQuery::~CMdEObjectQuery()
+	{
+	// doesn't own property definitions, so only delete pointer array
+	iPropertyFilters.Close();
+	}
+
+EXPORT_C CMdEObject& CMdEObjectQuery::Result(TInt aIndex) const
+    {
+    return static_cast<CMdEObject&>( ResultItem(aIndex) );
+    }
+
+EXPORT_C CMdEObjectDef& CMdEObjectQuery::ObjectDef() const
+	{
+	return iObjectDef;
+	}
+
+EXPORT_C void CMdEObjectQuery::AddPropertyFilterL(const CMdEPropertyDef* aProperty)
+    {
+    iPropertyFilters.AppendL( aProperty );
+    }
+
+
+EXPORT_C void CMdEObjectQuery::ResetPropertyFilter()
+    {
+    iPropertyFilters.Reset();
+    }
+    
+RPointerArray<CMdEPropertyDef>& CMdEObjectQuery::PropertyFilter()
+	{
+	return iPropertyFilters;
+	}
+
+RPointerArray<CMdEObjectDef>* CMdEObjectQuery::ObjectDefs() const
+	{
+	return iObjectDefs;
+	}
+
+void CMdEObjectQuery::DoCancel() 
+    {
+    SetState( EStateError );
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeorderrule.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,114 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#include "mdeorderrule.h"
+#include "mdepanic.h"
+#include "mdepropertydef.h"
+#include "mdcserializationbuffer.h"
+#include "mdcquery.h"
+
+
+EXPORT_C TMdEOrderRule::TMdEOrderRule(TOrderRuleType aType, TBool aAscending)
+        : iType(aType), 
+          iAscending(aAscending),
+          iCaseSensitive(ETrue)
+    {
+    }
+        
+
+EXPORT_C TMdEOrderRule::TMdEOrderRule(const CMdEPropertyDef& aPropertyDef, TBool aAscending)
+        : iType(EOrderRuleTypeProperty), iPropertyDef(&aPropertyDef), 
+          iAscending(aAscending), iCaseSensitive(ETrue)
+    {
+    }
+
+
+EXPORT_C TOrderRuleType TMdEOrderRule::Type() const
+    {
+    return iType;
+    }
+
+
+EXPORT_C void TMdEOrderRule::SetType(TOrderRuleType aType)
+    {
+    iType = aType;
+    }
+
+
+EXPORT_C TBool TMdEOrderRule::Ascending() const
+    {
+    return iAscending;
+    }
+    
+
+EXPORT_C void TMdEOrderRule::SetAscending(TBool aAscending)
+    {
+    iAscending = aAscending;
+    }
+
+
+EXPORT_C const CMdEPropertyDef* TMdEOrderRule::PropertyDef() const
+    {
+    return iPropertyDef;
+    }
+
+
+EXPORT_C void TMdEOrderRule::SetPropertyDef(const CMdEPropertyDef& aPropertyDef)
+    {
+    iPropertyDef = &aPropertyDef;
+    }
+
+EXPORT_C void TMdEOrderRule::SetCaseSensitive(TBool aCaseSensitive)
+    {
+    iCaseSensitive = aCaseSensitive;
+    }
+
+EXPORT_C TBool TMdEOrderRule::CaseSensitive()
+    {
+    return iCaseSensitive;
+    }
+
+TUint32 TMdEOrderRule::RequiredBufferSize() const
+	{
+	return sizeof( TMdCOrderRule );
+	}
+
+void TMdEOrderRule::SerializeL(CMdCSerializationBuffer& aBuffer, 
+		TMdCOffset& aFreespaceOffset) const
+	{
+	TMdCOrderRule rule;
+
+	rule.iOrderRule = iType;
+	rule.iAscending = iAscending;
+	rule.iCaseSensitive = iCaseSensitive;
+
+	// If it's property order insert property def ID
+	if( EOrderRuleTypeProperty == iType )
+		{
+		const TDefId propertyDefId = iPropertyDef->Id();
+		rule.iPropertyDefId = propertyDefId;
+		}
+	else
+		{
+		rule.iPropertyDefId = KNoDefId;
+		}
+	
+	rule.SerializeL( aBuffer );
+	
+	aFreespaceOffset = aBuffer.Position();
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdepanic.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Panics the current thread with the
+*                Nokia Metadata Engine Client DLL panic category 
+*
+*/
+
+
+#include <e32std.h>
+
+#include "mdepanic.h"
+
+
+void TMdEPanic::Panic(TReason aReason)
+    {
+    _LIT( KMdEClient, "MDE CLIENT" );
+	User::Panic( KMdEClient, aReason );
+    }
+	
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdeproperty.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,625 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#include "mdeproperty.h"
+
+#include "mdcitem.h"
+#include "mdscommoninternal.h"
+#include "mdepropertydef.h"
+#include "mdcserializationbuffer.h"
+#include "mdeobject.h"
+#include "mdeobjectdef.h"
+#include "mdeerror.h"
+#include "mdesession.h"
+
+CMdEProperty::CMdEProperty(const CMdEPropertyDef& aDef, const CMdEObject& aObject)
+		: CMdEInstanceItem( CONST_CAST( CMdESession*, &aDef.NamespaceDef().Session() ), KNoId), 
+		iModFlags(EMdEPropertyModChange), iDef(aDef), iObject(aObject)
+	{
+	}
+
+CMdEProperty* CMdEProperty::NewL(const CMdEPropertyDef& aDef, const CMdEObject& aObject)
+    {
+    CMdEProperty* self = NewLC(aDef, aObject);
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+
+CMdEProperty* CMdEProperty::NewLC(const CMdEPropertyDef& aDef, const CMdEObject& aObject)
+    {
+    CMdEProperty* self = new (ELeave) CMdEProperty( aDef, aObject );
+    CleanupStack::PushL(self);
+    self->BaseConstructL();
+    return self;
+    }
+
+
+CMdEProperty* CMdEProperty::NewL( const CMdEObject& aObject, CMdCSerializationBuffer& aBuffer )
+	{
+	CMdEProperty* ret = CMdEProperty::NewLC( aObject, aBuffer );
+	CleanupStack::Pop( ret );
+	return ret;
+	}
+
+CMdEProperty* CMdEProperty::NewLC( const CMdEObject& aObject, CMdCSerializationBuffer& aBuffer )
+	{
+	const TMdCProperty& serializedProperty = TMdCProperty::GetFromBufferL( aBuffer );
+	CMdEPropertyDef* propDef = aObject.Def().GetPropertyDefL( serializedProperty.iPropertyDefId );
+	CMdEProperty* property = new(ELeave) CMdEProperty( *propDef, aObject );
+	CleanupStack::PushL( property );
+	property->BaseConstructL();
+
+	if ( propDef->PropertyType() == EPropertyText  && property )
+		{
+		__ASSERT_DEBUG( serializedProperty.iValue.iPtr.iCount > 0, User::Panic( _L("Empty text property!"), KErrCorrupt ));
+		aBuffer.PositionL( serializedProperty.iValue.iPtr.iOffset );
+		property->iValue.iText = aBuffer.ReceiveDes16L();
+		}
+	else if( property )
+		{
+		property->iValue = serializedProperty.iValue;
+		}
+	
+	// reset flags
+	if (property)
+		{
+		property->iModFlags = EMdEPropertyModNone;
+		}
+
+	return property;
+	}
+
+void CMdEProperty::BaseConstructL()
+	{
+	InstanceItemBaseConstruct();
+	}
+
+CMdEProperty::~CMdEProperty()
+	{
+	if (iDef.PropertyType() == EPropertyText)
+		{
+		delete iValue.iText;
+		}
+	}
+
+EXPORT_C const CMdEPropertyDef& CMdEProperty::Def() const
+	{
+	return iDef;
+	}
+
+EXPORT_C const CMdEObject& CMdEProperty::Object() const
+	{
+	return iObject;
+	}
+
+EXPORT_C TBool CMdEProperty::Modified() const
+	{
+	return iModFlags != EMdEPropertyModNone;
+	}
+
+TUint8 CMdEProperty::ModFlags() const
+	{
+	return iModFlags;
+	}
+
+void CMdEProperty::SetRemoved()
+	{
+	// remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+	
+	iModFlags |= EMdEPropertyModRemove;
+	}
+
+TBool CMdEProperty::Removed()
+	{
+	return iModFlags & EMdEPropertyModRemove;
+	}
+
+void CMdEProperty::ClearFlags()
+	{
+	// set ID to property -> CMdEItem::InDatabase returns ETrue
+	SetId( ~KNoId );
+	
+	iModFlags = EMdEPropertyModNone;
+	}
+
+void CMdEProperty::SetModified()
+	{
+	// remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+	
+	iModFlags |= EMdEPropertyModChange;
+	}
+
+TMdEInstanceType CMdEProperty::InstanceType() const
+	{
+	return EMdETypeProperty;
+	}
+
+EXPORT_C TBool CMdEProperty::BoolValueL() const
+	{
+	if ( iDef.PropertyType() != EPropertyBool )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+	return iValue.iInt32;
+	}
+
+EXPORT_C TInt8 CMdEProperty::Int8ValueL() const
+	{
+	if ( iDef.PropertyType() != EPropertyInt8 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+	return iValue.iInt32;
+	}
+
+EXPORT_C TUint8 CMdEProperty::Uint8ValueL() const
+	{
+	if ( iDef.PropertyType() != EPropertyUint8 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+	return iValue.iUint32;
+	}
+
+EXPORT_C TInt16 CMdEProperty::Int16ValueL() const
+	{
+	if ( iDef.PropertyType() != EPropertyInt16 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+	return iValue.iInt32;
+	}
+
+EXPORT_C TUint16 CMdEProperty::Uint16ValueL() const
+	{
+	if ( iDef.PropertyType() != EPropertyUint16 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+	return iValue.iUint32;
+	}
+
+EXPORT_C TInt32 CMdEProperty::Int32ValueL() const
+	{
+	if ( iDef.PropertyType() != EPropertyInt32 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+	return iValue.iInt32;
+	}
+
+EXPORT_C TUint32 CMdEProperty::Uint32ValueL() const
+	{
+	if ( iDef.PropertyType() != EPropertyUint32 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+	return iValue.iUint32;
+	}
+
+EXPORT_C TInt64 CMdEProperty::Int64ValueL() const
+	{
+	if ( iDef.PropertyType() != EPropertyInt64 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+	return iValue.iInt64;
+	}
+
+EXPORT_C TReal32 CMdEProperty::Real32ValueL() const
+	{
+	if ( iDef.PropertyType() != EPropertyReal32 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+	return iValue.iReal;
+	}
+
+EXPORT_C TReal64 CMdEProperty::Real64ValueL() const
+	{
+	if ( iDef.PropertyType() != EPropertyReal64 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+	return iValue.iReal;
+	}
+
+EXPORT_C TTime CMdEProperty::TimeValueL() const
+	{
+	if ( iDef.PropertyType() != EPropertyTime )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+	return TTime(iValue.iInt64);
+	}
+
+EXPORT_C const TDesC& CMdEProperty::TextValueL() const
+	{
+	if ( iDef.PropertyType() != EPropertyText )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+	return *iValue.iText;
+	}
+
+
+EXPORT_C void CMdEProperty::SetBoolValueL(TBool aValue)
+	{
+	if ( iDef.PropertyType() != EPropertyBool )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+#ifdef _DEBUG
+    TMdCValueUnion value;
+    value.iInt32 = aValue;
+    CheckValueMinMaxL( value );
+#endif
+	iValue.iInt32 = aValue;
+	
+	// remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+	
+    iModFlags = EMdEPropertyModChange;
+	}
+
+EXPORT_C void CMdEProperty::SetInt8ValueL(TInt8 aValue)
+	{
+	if ( iDef.PropertyType() != EPropertyInt8 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+#ifdef _DEBUG
+    TMdCValueUnion value;
+    value.iInt32 = aValue;
+    CheckValueMinMaxL( value );
+#endif
+	iValue.iInt32 = aValue;
+	
+	// remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+	
+    iModFlags = EMdEPropertyModChange;
+	}
+
+EXPORT_C void CMdEProperty::SetUint8ValueL(TUint8 aValue)
+	{
+	if ( iDef.PropertyType() != EPropertyUint8 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+#ifdef _DEBUG
+    TMdCValueUnion value;
+    value.iUint32 = aValue;
+    CheckValueMinMaxL( value );
+#endif
+	iValue.iUint32 = aValue;
+	
+	// remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+	
+    iModFlags = EMdEPropertyModChange;
+	}
+
+
+EXPORT_C void CMdEProperty::SetInt16ValueL(TInt16 aValue)
+	{
+	if ( iDef.PropertyType() != EPropertyInt16 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+#ifdef _DEBUG
+    TMdCValueUnion value;
+    value.iInt32 = aValue;
+    CheckValueMinMaxL( value );
+#endif
+	iValue.iInt32 = aValue;
+	
+	// remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+	
+    iModFlags = EMdEPropertyModChange;
+	}
+
+EXPORT_C void CMdEProperty::SetUint16ValueL(TUint16 aValue)
+	{
+	if ( iDef.PropertyType() != EPropertyUint16 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+#ifdef _DEBUG
+    TMdCValueUnion value;
+    value.iUint32 = aValue;
+    CheckValueMinMaxL( value );
+#endif
+	iValue.iUint32 = aValue;
+	
+	// remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+	
+    iModFlags = EMdEPropertyModChange;
+	}
+
+EXPORT_C void CMdEProperty::SetInt32ValueL(TInt32 aValue)
+	{
+	if ( iDef.PropertyType() != EPropertyInt32 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+#ifdef _DEBUG
+    TMdCValueUnion value;
+    value.iInt32 = aValue;
+    CheckValueMinMaxL( value );
+#endif
+	iValue.iInt32 = aValue;
+	
+	// remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+	
+    iModFlags = EMdEPropertyModChange;
+	}
+
+EXPORT_C void CMdEProperty::SetUint32ValueL(TUint32 aValue)
+	{
+	if ( iDef.PropertyType() != EPropertyUint32 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+#ifdef _DEBUG
+    TMdCValueUnion value;
+    value.iUint32 = aValue;
+    CheckValueMinMaxL( value );
+#endif
+	iValue.iUint32 = aValue;
+	
+	// remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+	
+    iModFlags = EMdEPropertyModChange;
+	}
+
+EXPORT_C void CMdEProperty::SetInt64ValueL(TInt64 aValue)
+	{
+	if ( iDef.PropertyType() != EPropertyInt64 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+#ifdef _DEBUG
+    TMdCValueUnion value;
+    value.iInt64 = aValue;
+    CheckValueMinMaxL( value );
+#endif
+	iValue.iInt64 = aValue;
+	
+	// remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+	
+    iModFlags = EMdEPropertyModChange;
+	}
+
+EXPORT_C void CMdEProperty::SetReal32ValueL(TReal32 aValue)
+	{
+	if ( iDef.PropertyType() != EPropertyReal32 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+#ifdef _DEBUG
+    TMdCValueUnion value;
+    value.iReal = aValue;
+    CheckValueMinMaxL( value );
+#endif
+	iValue.iReal = aValue;
+	
+	// remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+	
+    iModFlags = EMdEPropertyModChange;
+	}
+
+EXPORT_C void CMdEProperty::SetReal64ValueL(TReal64 aValue)
+	{
+	if ( iDef.PropertyType() != EPropertyReal64 )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+#ifdef _DEBUG
+    TMdCValueUnion value;
+    value.iReal = aValue;
+    CheckValueMinMaxL( value );
+#endif
+	iValue.iReal = aValue;
+	
+	// remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+	
+    iModFlags = EMdEPropertyModChange;
+	}
+
+EXPORT_C void CMdEProperty::SetTimeValueL(const TTime& aValue)
+	{
+	if ( iDef.PropertyType() != EPropertyTime )
+		{
+		User::Leave( KErrMdEIncorrectType );
+		}
+#ifdef _DEBUG
+    TMdCValueUnion value;
+    value.iInt64 = aValue.Int64();
+    CheckValueMinMaxL( value );
+#endif
+	iValue.iInt64 = aValue.Int64();
+	
+	// remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+	
+    iModFlags = EMdEPropertyModChange;
+	}
+
+EXPORT_C void CMdEProperty::SetTextValueL(const TDesC& aValue)
+    {
+#ifdef _DEBUG
+    TMdCValueUnion value;
+    value.iText = (HBufC*)&aValue;
+    CheckValueMinMaxL( value );
+#endif
+
+    DoSetTextValueL( aValue );
+    
+    // remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+    
+    iModFlags = EMdEPropertyModChange;
+    }
+
+#ifdef _DEBUG
+#include <e32debug.h>
+
+void CMdEProperty::CheckValueMinMaxL( const TMdCValueUnion& aValue ) const
+	{
+	_LIT( KFunctionName, "CMdEProperty::CheckValueMinMaxL" );
+    switch( iDef.PropertyType() )
+	    {
+	    case EPropertyBool:
+	    	break;
+	    case EPropertyInt8:
+	    case EPropertyInt16:
+	    case EPropertyInt32:
+	    	if ( !(iDef.MinInt32ValueL() <= aValue.iInt32 && aValue.iInt32 <= iDef.MaxInt32ValueL()) )
+	    		{
+#ifdef _DEBUG
+	    		RDebug::Print( _L("Incorrect property[%S] value: %d"), &iDef.Name(), aValue );
+#endif
+	    		User::Panic( KFunctionName, KErrArgument );
+	    		}
+	    	break;
+	    case EPropertyUint8:
+	    case EPropertyUint16:
+	    case EPropertyUint32:
+	    	if ( !(iDef.MinUint32ValueL() <= aValue.iUint32 && aValue.iUint32 <= iDef.MaxUint32ValueL()) )
+	    		{
+#ifdef _DEBUG
+	    		RDebug::Print( _L("Incorrect property[%S] value: %u"), &iDef.Name(), aValue );
+#endif
+	    		User::Panic( KFunctionName, KErrArgument );
+	    		}
+    		break;
+	    case EPropertyInt64:
+	    	if ( !(iDef.MinInt64ValueL() <= aValue.iInt64 && aValue.iInt64 <= iDef.MaxInt64ValueL()) )
+	    		{
+#ifdef _DEBUG
+	    		RDebug::Print( _L("Incorrect property[%S] value: %Ld"), &iDef.Name(), aValue );
+#endif
+	    		User::Panic( KFunctionName, KErrArgument );
+	    		}
+			break;
+	    case EPropertyTime:
+	    	if ( !(iDef.MinTimeValueL().Int64() <= aValue.iInt64 && aValue.iInt64 <= iDef.MaxTimeValueL().Int64()) )
+	    		{
+#ifdef _DEBUG
+	    		RDebug::Print( _L("Incorrect property[%S] value: %Ld"), &iDef.Name(), aValue );
+#endif
+	    		User::Panic( KFunctionName, KErrArgument );
+	    		}
+			break;
+	    case EPropertyReal32:
+	    case EPropertyReal64:
+	    	if ( !(iDef.MinRealValueL() <= aValue.iReal && aValue.iReal <= iDef.MaxRealValueL()) )
+	    		{
+#ifdef _DEBUG
+	    		RDebug::Print( _L("Incorrect property[%S] value: %.2f"), &iDef.Name(), aValue );
+#endif
+	    		User::Panic( KFunctionName, KErrArgument );
+	    		}
+			break;
+	    case EPropertyText:
+			const TInt valueLength = aValue.iText->Length();
+			if ( !(iDef.MinTextLengthL() <= valueLength && valueLength <= iDef.MaxTextLengthL()) )
+				{
+#ifdef _DEBUG
+				RDebug::Print( _L("Incorrect property[%S] value: \"%S\", length: %d"), &iDef.Name(), aValue.iText, valueLength );
+#endif
+				User::Panic( KFunctionName, KErrArgument );
+				}
+			break;
+	    }
+	}
+#endif
+
+void CMdEProperty::DoSetTextValueL(const TDesC& aValue)
+    {
+    if ( iValue.iText )
+    	{
+    	if ( iValue.iText->Size() == aValue.Size() )
+    		{
+    		TPtr16 ptr(iValue.iText->Des());
+    		ptr.Copy( aValue );
+    		}
+    	else
+    		{
+		    delete iValue.iText;
+		    iValue.iText = NULL;
+    		}
+    	}
+
+    if ( !iValue.iText )
+    	{
+    	iValue.iText = aValue.AllocL();
+    	}
+    
+    // remove ID from property -> CMdEItem::InDatabase returns EFalse
+	SetId( KNoId );
+    
+    iModFlags = EMdEPropertyModChange;
+    }
+
+TUint32 CMdEProperty::RequiredBufferSize() const
+	{
+	TUint32 size = sizeof( TMdCProperty );
+	if ( iDef.PropertyType() == EPropertyText )
+		{
+		size += CMdCSerializationBuffer::RequiredSize( *iValue.iText );
+		}
+	return size;
+	}
+
+TMdCOffset CMdEProperty::SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreespaceOffset) const
+	{
+	const TMdCOffset propertyOffset = aBuffer.Position();
+	TMdCProperty property;
+	property.iPropertyDefId = Def().Id();
+	property.iModFlags = iModFlags;
+	if ( iDef.PropertyType() == EPropertyText )
+		{
+		property.iValue.iPtr.iCount = iValue.iText->Length();
+		property.iValue.iPtr.iOffset = aFreespaceOffset;
+		aBuffer.PositionL( aFreespaceOffset );
+		aFreespaceOffset = aBuffer.InsertL( *iValue.iText );
+		}
+	else
+		{
+		property.iValue = iValue;
+		}
+	
+	// serialize property itself
+	aBuffer.PositionL( propertyOffset );
+	property.SerializeL( aBuffer );
+
+	return aFreespaceOffset;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdepropertycondition.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,92 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Represent property condition
+*
+*/
+
+#include "mdepropertycondition.h"
+#include "mdcserializationbuffer.h"
+#include "mdepropertydef.h"
+#include "mdeobjectdef.h"
+#include "mdscommoninternal.h"
+#include "mdcquery.h"
+
+CMdEPropertyCondition* CMdEPropertyCondition::NewL( const CMdEPropertyDef& aPropertyDef )
+    {
+    CMdEPropertyCondition* self = CMdEPropertyCondition::NewLC( aPropertyDef );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+CMdEPropertyCondition* CMdEPropertyCondition::NewLC( const CMdEPropertyDef& aPropertyDef )
+    {
+    CMdEPropertyCondition* self = new ( ELeave ) CMdEPropertyCondition( aPropertyDef );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+CMdEPropertyCondition::CMdEPropertyCondition(const CMdEPropertyDef& aPropertyDef)
+        : CMdECondition(EConditionTypeProperty), iPropertyDef(aPropertyDef)
+    {
+    }
+
+CMdEPropertyCondition::CMdEPropertyCondition(TConditionType aConditionType, 
+                                             const CMdEPropertyDef& aPropertyDef)
+        : CMdECondition(aConditionType), iPropertyDef(aPropertyDef)
+    {
+    }
+
+void CMdEPropertyCondition::ConstructL()
+    {
+    // Base class construction.
+    ConditionConstruct();
+    }
+
+CMdEPropertyCondition::~CMdEPropertyCondition()
+	{
+	}
+
+EXPORT_C const CMdEPropertyDef& CMdEPropertyCondition::PropertyDef() const
+    {
+    return iPropertyDef;
+    }
+
+TUint32 CMdEPropertyCondition::InternalQueryOptimizationFlags(TUint32& aFlags)
+	{
+	aFlags |= EContainsObjectCondition;
+	return EContainsObjectCondition;
+	}
+
+TUint32 CMdEPropertyCondition::RequiredBufferSize() const
+	{
+	// Required size for property condition
+	return sizeof( TMdCPropertyCondition );
+	}
+
+void CMdEPropertyCondition::SerializeL(CMdCSerializationBuffer& aBuffer,
+		TMdCOffset& aFreespaceOffset) const
+	{
+	TMdCPropertyCondition condition;
+
+	condition.iConditionType = iType;
+	condition.iNegated = iNegated;
+	condition.iObjectDefId = iPropertyDef.ObjectDefId();
+	condition.iPropertyDefId = iPropertyDef.Id();
+	condition.iCondition = KNoOffset;
+
+	condition.SerializeL( aBuffer );
+
+	aFreespaceOffset = aBuffer.Position();
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdepropertydef.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,235 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#include "mdepropertydef.h"
+
+#include "mdcdef.h"
+#include "mdeobjectdef.h"
+#include "mdenamespacedef.h"
+#include "mdscommoninternal.h"
+#include "mdcserializationbuffer.h"
+
+
+CMdEPropertyDef::CMdEPropertyDef( const TMdCPropertyDef& aPropertyDef, CMdEObjectDef& aObjectDef )
+    : iPropertyDef(aPropertyDef), iObjectDef(aObjectDef)
+    {
+    }
+
+CMdEPropertyDef* CMdEPropertyDef::NewL( const TMdCPropertyDef& aPropertyDef,
+    CMdCSerializationBuffer& aSchemaBuffer, CMdEObjectDef& aObjectDef )
+    {
+    CMdEPropertyDef* def = CMdEPropertyDef::NewLC( aPropertyDef, aSchemaBuffer, aObjectDef );
+    CleanupStack::Pop( def );
+    return def;
+    }
+
+CMdEPropertyDef* CMdEPropertyDef::NewLC( const TMdCPropertyDef& aPropertyDef,
+    CMdCSerializationBuffer& aSchemaBuffer, CMdEObjectDef& aObjectDef )
+    {
+    CMdEPropertyDef* def = new( ELeave ) CMdEPropertyDef( aPropertyDef, aObjectDef );
+    CleanupStack::PushL( def );
+    def->ConstructL( aSchemaBuffer );
+    return def;
+    }
+
+void CMdEPropertyDef::ConstructL( CMdCSerializationBuffer& aSchemaBuffer )
+    {
+	aSchemaBuffer.PositionL( iPropertyDef.iName.iPtr.iOffset );
+	iName.Set( aSchemaBuffer.ReceivePtr16L() );
+    }
+
+CMdEPropertyDef::~CMdEPropertyDef()
+    {
+    }
+
+TDefId CMdEPropertyDef::Id() const
+    {
+    return iPropertyDef.iDefId;
+    }
+
+TDefId CMdEPropertyDef::ObjectDefId() const
+	{
+	return iObjectDef.Id();
+	}
+
+EXPORT_C CMdEObjectDef& CMdEPropertyDef::ObjectDef() const
+    {
+    return iObjectDef;
+    }
+    
+EXPORT_C const TDesC& CMdEPropertyDef::Name() const
+    {
+    return iName;
+    }
+
+EXPORT_C TInt CMdEPropertyDef::Compare( const CMdEPropertyDef& aPropertyDef ) const
+    {
+    TInt result = iObjectDef.NamespaceDef().Compare( aPropertyDef.iObjectDef.NamespaceDef() );
+    if ( result == 0 )
+        {
+        result = iPropertyDef.iDefId - aPropertyDef.Id();
+        }
+    return result;
+    }
+
+EXPORT_C TPropertyType CMdEPropertyDef::PropertyType() const
+    {
+    return (TPropertyType)iPropertyDef.iValueType;
+    }
+
+EXPORT_C TBool CMdEPropertyDef::ReadOnly() const
+    {
+    return iPropertyDef.iFlags & EPropertyReadOnly ? ETrue : EFalse;
+    }
+
+EXPORT_C TBool CMdEPropertyDef::Mandatory() const
+	{
+	return iPropertyDef.iFlags & EPropertyMandatory ? ETrue : EFalse;
+	}
+
+EXPORT_C TInt32 CMdEPropertyDef::MinInt32ValueL() const
+    {
+    const TPropertyType type = PropertyType();
+    if ( type != EPropertyInt8 &&
+    	 type != EPropertyInt16 &&
+    	 type != EPropertyInt32 )
+    	{
+         User::Leave( KErrNotSupported );
+        }
+    return iPropertyDef.iMinValue.iInt32;
+    }
+
+EXPORT_C TInt32 CMdEPropertyDef::MaxInt32ValueL() const
+    {
+    const TPropertyType type = PropertyType();
+    if ( type != EPropertyInt8 &&
+    	 type != EPropertyInt16 &&
+    	 type != EPropertyInt32 )
+    	{
+        User::Leave( KErrNotSupported );
+        }
+    return iPropertyDef.iMaxValue.iInt32;
+    }
+
+EXPORT_C TUint32 CMdEPropertyDef::MinUint32ValueL() const
+    {
+    const TPropertyType type = PropertyType();
+    if ( type != EPropertyUint8 &&
+    	 type != EPropertyUint16 &&
+    	 type != EPropertyUint32 )
+    	{
+        User::Leave( KErrNotSupported );
+        }
+    return iPropertyDef.iMinValue.iUint32;
+    }
+
+EXPORT_C TUint32 CMdEPropertyDef::MaxUint32ValueL() const
+    {
+    const TPropertyType type = PropertyType();
+    if ( type != EPropertyUint8 &&
+    	 type != EPropertyUint16 &&
+     	 type != EPropertyUint32 )
+    	{
+        User::Leave( KErrNotSupported );
+        }
+    return iPropertyDef.iMaxValue.iUint32;
+    }
+
+EXPORT_C TInt64 CMdEPropertyDef::MinInt64ValueL() const
+    {
+    const TPropertyType type = PropertyType();
+    if ( type != EPropertyInt64 )
+    	{
+         User::Leave( KErrNotSupported );
+        }
+    return iPropertyDef.iMinValue.iInt64;
+    }
+
+EXPORT_C TInt64 CMdEPropertyDef::MaxInt64ValueL() const
+    {
+    const TPropertyType type = PropertyType();
+    if ( type != EPropertyInt64 )
+    	{
+         User::Leave( KErrNotSupported );        
+        }
+    return iPropertyDef.iMaxValue.iInt64;
+    }
+
+EXPORT_C TReal CMdEPropertyDef::MinRealValueL() const
+    {
+    const TPropertyType type = PropertyType();
+    if ( type != EPropertyReal32 && type != EPropertyReal64 )
+    	{
+         User::Leave( KErrNotSupported );
+        }
+    return iPropertyDef.iMinValue.iReal;
+    }
+
+EXPORT_C TReal CMdEPropertyDef::MaxRealValueL() const
+    {
+    const TPropertyType type = PropertyType();
+    if ( type != EPropertyReal32 && type != EPropertyReal64 )
+    	{
+         User::Leave( KErrNotSupported );
+        }
+    return iPropertyDef.iMaxValue.iReal;
+    }
+
+EXPORT_C TTime CMdEPropertyDef::MinTimeValueL() const
+    {
+    const TPropertyType type = PropertyType();
+    if ( type != EPropertyTime )
+        {
+        User::Leave( KErrNotSupported );
+        }
+    return TTime(iPropertyDef.iMinValue.iInt64);
+    }
+
+EXPORT_C TTime CMdEPropertyDef::MaxTimeValueL() const
+    {
+    const TPropertyType type = PropertyType();
+    if ( type != EPropertyTime )
+        {
+        User::Leave( KErrNotSupported );
+        }
+    return TTime(iPropertyDef.iMaxValue.iInt64);
+    }
+
+EXPORT_C TInt CMdEPropertyDef::MinTextLengthL() const
+    {
+    const TPropertyType type = PropertyType();
+    if ( type != EPropertyText )
+        {
+        User::Leave( KErrNotSupported );
+        }
+    return iPropertyDef.iMinValue.iInt32;
+    }
+
+EXPORT_C TInt CMdEPropertyDef::MaxTextLengthL() const
+    {
+    const TPropertyType type = PropertyType();
+    if ( type != EPropertyText )
+        {
+        User::Leave( KErrNotSupported );
+        }
+    return iPropertyDef.iMaxValue.iInt32;
+    }
+
+EXPORT_C CMdENamespaceDef& CMdEPropertyDef::NamespaceDef() const
+    {
+    return iObjectDef.NamespaceDef();
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdequery.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,591 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Query base class
+*
+*/
+
+
+#include "mdequery.h"
+
+#include "mdeorderrule.h"
+#include "mdeinstanceitem.h"
+#include "mdelogiccondition.h"
+#include "mdenamespacedef.h"
+#include "mdepanic.h"
+
+
+CMdEQuery::CMdEQuery(TQueryType aType, CMdESession& aSession, CMdENamespaceDef& aNamespaceDef)
+        : iQueryId( 0 ), iSession(aSession), iNamespaceDef(aNamespaceDef), iType(aType), 
+          iResultMode(EQueryResultModeItem), iState(EStateNew), iError(KErrNone), 
+          iObjectResult(NULL), iCountResult(0), iDistinctResults(NULL)
+    {
+    }
+
+
+void CMdEQuery::QueryConstructL()
+    {
+    iConditions = CMdELogicCondition::NewL(ELogicConditionOperatorAnd);
+    }
+
+
+CMdEQuery::~CMdEQuery()
+	{
+	Cancel();
+  
+    // This will destroy the entire conditions tree.
+   	delete iConditions;
+
+   	const TInt count = iResults.Count();
+   	
+    // Destroy all result items this query instance owns.
+    for(TInt i = 0; i < count; ++i)
+        {
+        if(iResults[i].iOwned)
+            {
+            delete iResults[i].iItem;
+            }
+        }
+
+    // Destroy object result item this query instance owns  
+    if(iObjectResult.iItem)
+        {
+        if(iObjectResult.iOwned)
+        	{
+        	delete iObjectResult.iItem;
+        	iObjectResult.iItem = NULL;
+        	}
+        }
+
+	iCountResult = 0;
+
+	iResults.Reset();
+	iResults.Close();
+	iIdResults.Reset();
+	iIdResults.Close();
+
+    iOrderRules.Close();
+    iObservers.Close();
+
+   	delete iDistinctResults;
+	}
+
+
+EXPORT_C TQueryType CMdEQuery::Type() const
+    {
+    return iType;
+    }
+
+EXPORT_C CMdENamespaceDef& CMdEQuery::NamespaceDef() const
+	{
+	return iNamespaceDef;
+	}
+    
+EXPORT_C CMdESession& CMdEQuery::Session() const
+    {
+    return iSession;
+    }
+
+
+EXPORT_C CMdELogicCondition& CMdEQuery::Conditions() const
+    {
+    __ASSERT_DEBUG(iConditions , 
+                    TMdEPanic::Panic(TMdEPanic::EInternal));
+    return *iConditions;
+    }
+    
+    
+EXPORT_C void CMdEQuery::AppendOrderRuleL(const TMdEOrderRule& aRule)
+    {
+    AssertInState(EStateNew);
+    iOrderRules.AppendL( aRule );
+    }
+
+
+EXPORT_C void CMdEQuery::InsertOrderRuleL(const TMdEOrderRule& aRule, TInt aPos)
+    {
+    AssertInState(EStateNew);
+    User::LeaveIfError( iOrderRules.Insert(aRule, aPos) );   
+    }
+
+
+EXPORT_C TInt CMdEQuery::OrderRuleCount() const
+    {
+    return iOrderRules.Count();    
+    }
+
+
+EXPORT_C void CMdEQuery::RemoveOrderRule(TInt aIndex)
+    {
+    AssertInState(EStateNew);
+    iOrderRules.Remove(aIndex);
+    }
+
+
+EXPORT_C TMdEOrderRule CMdEQuery::OrderRule(TInt aIndex) const
+    {
+    return iOrderRules[aIndex];        
+    }
+    
+
+EXPORT_C void CMdEQuery::FindL(TUint aMaxCount, TUint aNotifyCount)
+    {
+    AssertNotInState(EStateError);
+
+	// leave if query already running    
+    if(iState == EStateSearching)
+        {
+        User::Leave(KErrNotReady);
+        }
+    
+    const TInt count = iResults.Count();
+    
+	// clear old results
+	// Destroy all result items this query instance owns.
+    for(TInt i = 0; i < count; ++i)
+        {
+        if(iResults[i].iOwned)
+            {
+            delete iResults[i].iItem;
+            }
+        }
+	iResults.Reset();
+
+    // Destroy object result item this query instance owns  
+    if( iObjectResult.iItem )
+        {
+        if( iObjectResult.iOwned )
+        	{
+        	delete iObjectResult.iItem;
+        	iObjectResult.iItem = NULL;
+        	}
+        }
+
+	iIdResults.Reset();
+
+    if( iDistinctResults )
+    	{    	
+    	delete iDistinctResults;
+    	iDistinctResults = NULL;
+    	}
+
+	iCountResult = 0;
+	// end of clearing
+
+    DoFindL(aMaxCount, aNotifyCount);
+    }
+
+
+EXPORT_C void CMdEQuery::Cancel()
+    {
+    // is query incomplete before canceling
+    TBool incomplete = !IsComplete();
+    
+    if( incomplete )
+    	{
+    	DoCancel();
+    	}
+
+	if( iConditions )
+		{		
+    	iConditions->SetLocked( EFalse );
+		}
+    
+    if( incomplete || IsComplete() == EFalse )
+    	{
+    	iState = EStateError;
+    	NotifyCompleted( KErrCancel );
+    	}
+    }
+
+
+EXPORT_C TBool CMdEQuery::IsComplete() const
+    {
+    return iState != EStateSearching ? ETrue : EFalse;
+    }
+
+
+EXPORT_C TInt CMdEQuery::Error() const
+    {
+    return iError;
+    }
+
+
+EXPORT_C TInt CMdEQuery::Count() const
+    {
+    if ( iResultMode == EQueryResultModeItem || iResultMode == EQueryResultModeObjectWithFreetexts )
+        {
+        return iResults.Count();
+        }
+    else if ( iResultMode == EQueryResultModeId )
+        {
+        return iIdResults.Count();
+        }
+    else if ( iResultMode == EQueryResultModeDistinctValues )
+    	{
+    	if( iDistinctResults )
+    		{    		
+    		return iDistinctResults->Count();
+    		}
+    	else
+    		{
+    		return 0;
+    		}
+    	}
+    else // count query
+        {
+        return iCountResult;
+        }
+    }
+
+EXPORT_C CMdEItem& CMdEQuery::ResultItem(TInt aIndex) const
+    {
+    return *iResults[aIndex].iItem;
+    }
+
+
+EXPORT_C TItemId CMdEQuery::ResultId(TInt aIndex) const
+    {
+    return iIdResults[aIndex];
+    }
+
+EXPORT_C const RArray<TItemId>& CMdEQuery::ResultIds() const
+	{
+	return iIdResults;
+	}
+
+EXPORT_C CMdEItem* CMdEQuery::TakeOwnershipOfResult(TInt aIndex)
+    {
+    // Panic if an item is taken twice.
+    __ASSERT_DEBUG(iResults[aIndex].iOwned,
+                    TMdEPanic::Panic(TMdEPanic::EQueryDoesntOwnResult));
+
+    // Applies only instance ownership
+    if ( iResultMode == EQueryResultModeItem || iResultMode == EQueryResultModeObjectWithFreetexts )
+        {
+        iResults[aIndex].iOwned = EFalse;
+        return static_cast<CMdEItem*>( iResults[aIndex].iItem );
+        }
+    else
+    	{
+    	return NULL;
+    	}
+    }
+
+
+EXPORT_C TBool CMdEQuery::OwnsResult(TInt aIndex)
+    {
+    return iResults[aIndex].iOwned;
+    }
+
+
+EXPORT_C CMdEQuery::TState CMdEQuery::State() const
+    {
+    return iState;
+    }
+
+void CMdEQuery::DoCancel()
+    {
+    SetState( EStateError );
+    }
+
+void CMdEQuery::SetState(TState aState)
+    {
+    if(aState == iState)
+        {
+        // Already in the specified state.
+        return;
+        }
+        
+    // It's impossible to get out of the Error state.
+    AssertNotInState(EStateError);
+
+    // It's impossible to return to the New state.
+    __ASSERT_ALWAYS(aState > EStateFirst && aState < EStateLast && 
+                    aState != EStateNew, 
+                    TMdEPanic::Panic(TMdEPanic::EInternal));
+
+    // Move out of the old state.
+    switch(iState)
+        {
+        case EStateNew:
+            // Moving out of the New state causes the search conditions to 
+            // be locked.
+            iConditions->SetLocked();
+            break;    
+            
+        case EStateSearching:
+            // Searching has been completed.
+            break;
+
+        case EStateCompleted:
+            // Searching is been restarted.
+            break;
+            
+        default:
+            break;
+        }
+
+    // Set the new state.
+    iState = aState;
+
+    // Move into the new state.
+    switch(iState)
+        {
+        case EStateSearching:
+            // Searching has been started.
+            break;
+
+        case EStateCompleted:
+            // Searching has been completed.
+            break;
+
+        case EStateError:
+            // The query has entered the Error state.
+            break;
+            
+        default:
+            break;
+        }    
+    }
+
+
+void CMdEQuery::AssertInState(TState aState)
+    {
+    __ASSERT_ALWAYS(aState == iState,
+                    TMdEPanic::Panic(TMdEPanic::EQueryStateIllegalOperation));
+    }
+    
+
+void CMdEQuery::AssertNotInState(TState aState)
+    {
+    __ASSERT_ALWAYS(aState != iState,
+                    TMdEPanic::Panic(TMdEPanic::EQueryStateIllegalOperation));
+    }
+    
+
+void CMdEQuery::NotifyNewResultsL(const RPointerArray<CMdEInstanceItem>& aNewResults)
+    {
+    __ASSERT_ALWAYS(iState != EStateNew && iState != EStateError,
+                    TMdEPanic::Panic(TMdEPanic::EInternal));
+
+	TInt firstNewItemIndex = iResults.Count();
+	TInt i = 0;
+
+    // Query gets ownership of the results only if don't leave.
+    // If a leave occurs, the results array is restored to its original
+    // condition before any new results were added.
+
+    const TInt oldCount = iResults.Count();
+
+    TRAPD(err, AppendResultsL(aNewResults));
+    if (err != KErrNone)
+        {
+        // Cleanup: remove the ones that were added.
+        while (iResults.Count() > oldCount)
+            {
+            iResults.Remove(iResults.Count() - 1);
+            }
+        // Leave with the same error.
+        User::Leave(err);
+        }
+
+    // After this no leave can occur.
+
+    const TInt newCount = aNewResults.Count();
+    
+    // Transfer ownership of the results to the query.
+    for (i = 0; i < newCount; i++)
+        {
+        iResults[firstNewItemIndex + i].iOwned = ETrue;
+        }
+
+    const TInt observerCount = iObservers.Count();
+    
+	for (i = 0; i < observerCount; i++)
+		{
+		MMdEQueryObserver* observer = iObservers[i];
+		observer->HandleQueryNewResults( *this, firstNewItemIndex, newCount );
+		}
+    }
+
+
+void CMdEQuery::NotifyNewResultsL(const RArray<TItemId>& aNewResults)
+    {
+    __ASSERT_ALWAYS(iState != EStateNew && iState != EStateError,
+                    TMdEPanic::Panic(TMdEPanic::EInternal));
+
+	TInt firstNewItemIndex = iIdResults.Count();
+	TInt i = 0;
+
+    const TInt oldCount = iIdResults.Count();
+
+    TRAPD(err, AppendResultsL(aNewResults));
+    if (err != KErrNone)
+        {
+        // Cleanup: remove the ones that were added.
+        while (iIdResults.Count() > oldCount)
+            {
+            iIdResults.Remove(iIdResults.Count() - 1);
+            }
+        // Leave with the same error.
+        User::Leave(err);
+        }
+
+    const TInt observerCount = iObservers.Count();
+    
+	for (i = 0; i < observerCount; i++)
+		{
+		MMdEQueryObserver* observer = iObservers[i];
+		observer->HandleQueryNewResults(*this, firstNewItemIndex, 
+                                        aNewResults.Count());
+		}
+    }
+
+void CMdEQuery::NotifyNewResultsL( const CDesCArray& aNewResults )
+    {
+	TInt firstNewItemIndex = aNewResults.Count();
+	TInt i = 0;
+
+	TInt oldCount = 0;
+	if( iDistinctResults )
+		{
+		oldCount = iDistinctResults->Count();
+		}
+	else
+		{
+	    iDistinctResults = new (ELeave) CDesCArrayFlat( 8 );
+		}
+
+    TRAPD( err, AppendResultsL( aNewResults ) );
+    if( err != KErrNone )
+        {
+        // Cleanup: remove the ones that were added.
+        while( iDistinctResults->Count() > oldCount )
+            {
+            iDistinctResults->Delete( iDistinctResults->Count() - 1 );
+            }
+        // Leave with the same error.
+        User::Leave(err);
+        }
+
+    const TInt observerCount = iObservers.Count();
+    
+	for (i = 0; i < observerCount; i++)
+		{
+		MMdEQueryObserver* observer = iObservers[i];
+		observer->HandleQueryNewResults( *this, firstNewItemIndex, 
+                                         aNewResults.Count() );
+		}
+    }
+
+void CMdEQuery::NotifyNewResults(TUint32 aResult)
+	{
+    // Don't call observer here, since only one result
+    iCountResult = aResult;
+    }
+
+void CMdEQuery::AppendResultsL(const RPointerArray<CMdEInstanceItem>& aNewResults)
+    {
+    const TInt newResultCount = aNewResults.Count();
+    iResults.ReserveL( iResults.Count() + newResultCount );
+
+	for (TInt i = 0; i < newResultCount; ++i)
+        {
+        // At this point the ownership isn't transferred yet.
+        TResult result( aNewResults[i] );
+		iResults.AppendL( result );
+		}
+    }
+
+void CMdEQuery::AppendResultsL(const RArray<TItemId>& aNewResults)
+    {
+    const TInt newResultCount = aNewResults.Count();
+    iIdResults.ReserveL( iResults.Count() + newResultCount );
+
+	for (TInt i = 0; i < newResultCount; ++i)
+        {
+        // Add new results to query's list
+		iIdResults.AppendL( aNewResults[i] );
+		}
+    }
+
+void CMdEQuery::AppendResultsL( const CDesCArray& aNewResults )
+    {
+    const TInt count = aNewResults.Count();
+    
+    for ( TInt i = 0; i < count; ++i )
+    	{
+    	iDistinctResults->AppendL( aNewResults[i] );
+    	}
+    }
+    
+void CMdEQuery::NotifyCompleted(TInt aError)
+    {
+    // The implementation must move out of the Searching state before
+    // notifying the base class.
+    __ASSERT_ALWAYS(iState != EStateSearching, TMdEPanic::Panic(TMdEPanic::EInternal));
+
+    // Update the latest error code.
+    iError = aError;
+	for (TInt i = iObservers.Count() - 1; i >= 0; --i)
+		{
+		MMdEQueryObserver* observer = iObservers[i];
+		observer->HandleQueryCompleted(*this, aError);
+		}
+    }
+
+
+EXPORT_C void CMdEQuery::AddObserverL(MMdEQueryObserver& aObserver)
+	{
+	__ASSERT_ALWAYS(iObservers.Find(&aObserver) == KErrNotFound,
+				    TMdEPanic::Panic(TMdEPanic::EQueryDuplicateObserver));
+
+	iObservers.AppendL( &aObserver );
+	}
+
+
+EXPORT_C void CMdEQuery::RemoveObserver(MMdEQueryObserver& aObserver)
+	{
+	TInt index = iObservers.Find(&aObserver);
+
+	__ASSERT_ALWAYS(index != KErrNotFound,
+				    TMdEPanic::Panic(TMdEPanic::EQueryUnknownObserver));
+
+	iObservers.Remove(index);
+	}
+
+
+EXPORT_C void CMdEQuery::SetResultMode( TQueryResultMode aMode )
+    {    
+    iResultMode = aMode;
+    }
+
+EXPORT_C TQueryResultMode CMdEQuery::ResultMode() const
+    {
+    return iResultMode;
+    }
+EXPORT_C CMdEItem& CMdEQuery::ResultObjectItem() const
+    {
+    return *iObjectResult.iItem;
+    }
+
+EXPORT_C TPtrC16 CMdEQuery::ResultDistinctValue(TInt aIndex) const
+	{
+	return (*iDistinctResults)[aIndex];
+	}
+
+RArray<TMdEOrderRule>& CMdEQuery::OrderRules()
+	{
+	return iOrderRules;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdequerycriteriaserialization.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,291 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Serialize query criteria
+*
+*/
+
+
+#include "mdequerycriteriaserialization.h"
+#include "mdelogiccondition.h"
+#include "mdepropertydef.h"
+#include "mdenamespacedef.h"
+#include "mdeobjectdef.h"
+#include "mdcquery.h"
+#include "mdcserializationbuffer.h"
+
+
+CMdEQueryCriteriaSerialization* CMdEQueryCriteriaSerialization::NewL(
+	TQueryResultMode aResultMode, TQueryType aQueryType, 
+	CMdENamespaceDef& aNamespaceDef, 
+	CMdEObjectDef* aObjectDef, RPointerArray<CMdEObjectDef>* aObjectDefs, 
+	TUint32 aLimit, TUint32 aOffset, TUint32 aQueryOptimizationFlags,
+	CMdELogicCondition& aRootCondition, RArray<TMdEOrderRule>& aOrderRule, 
+	RPointerArray<CMdEPropertyDef>* aPropertyFilter)
+	{
+    CMdEQueryCriteriaSerialization* serialization = 
+    	CMdEQueryCriteriaSerialization::NewLC( aResultMode, aQueryType,
+    										   aNamespaceDef, aObjectDef, aObjectDefs, 
+    										   aLimit, aOffset, aQueryOptimizationFlags,
+    										   aRootCondition, aOrderRule,
+    										   aPropertyFilter );
+    CleanupStack::Pop( serialization );
+    return serialization;
+    }
+
+CMdEQueryCriteriaSerialization* CMdEQueryCriteriaSerialization::NewLC(
+	TQueryResultMode aResultMode, TQueryType aQueryType, 
+	CMdENamespaceDef& aNamespaceDef, 
+	CMdEObjectDef* aObjectDef, RPointerArray<CMdEObjectDef>* aObjectDefs, 
+	TUint32 aLimit, TUint32 aOffset, TUint32 aQueryOptimizationFlags, 
+	CMdELogicCondition& aRootCondition, RArray<TMdEOrderRule>& aOrderRule, 
+	RPointerArray<CMdEPropertyDef>* aPropertyFilter)
+	{
+    CMdEQueryCriteriaSerialization* serialization = 
+    	new( ELeave ) CMdEQueryCriteriaSerialization( ETrue ); // Owns serialized buffer
+    CleanupStack::PushL( serialization );
+    serialization->ConstructL( aResultMode, aQueryType,
+    						   aNamespaceDef, aObjectDef, aObjectDefs, 
+    						   aLimit, aOffset, aQueryOptimizationFlags,
+    						   aRootCondition, aOrderRule,
+    						   aPropertyFilter );
+    return serialization;
+	}
+
+CMdEQueryCriteriaSerialization* CMdEQueryCriteriaSerialization::NewL(
+	CMdCSerializationBuffer& aSerializationBuffer)
+	{
+    CMdEQueryCriteriaSerialization* serialization = 
+    	CMdEQueryCriteriaSerialization::NewLC( aSerializationBuffer );
+    CleanupStack::Pop( serialization );
+    return serialization;
+	}
+
+CMdEQueryCriteriaSerialization* CMdEQueryCriteriaSerialization::NewLC(
+	CMdCSerializationBuffer& aSerializationBuffer)
+	{
+    CMdEQueryCriteriaSerialization* serialization = 
+    	new( ELeave ) CMdEQueryCriteriaSerialization( EFalse ); // Doesn't own serialized buffer
+    CleanupStack::PushL( serialization );
+    serialization->iSerializedBuffer = &aSerializationBuffer;
+    return serialization;
+	}
+
+CMdEQueryCriteriaSerialization::~CMdEQueryCriteriaSerialization()
+	{
+	if( iOwnSerializedBuffer )
+		{
+		delete iSerializedBuffer;
+		}
+	}
+	
+TPtr8 CMdEQueryCriteriaSerialization::Buffer() const
+	{
+	return iSerializedBuffer->Buffer();
+	}
+
+const TPtr8* CMdEQueryCriteriaSerialization::BufferPtr() const
+	{
+	return iSerializedBuffer->BufferPtr();
+	}
+
+CMdCSerializationBuffer& CMdEQueryCriteriaSerialization::SerializationBuffer()
+	{
+	return *iSerializedBuffer;
+	}
+
+CMdEQueryCriteriaSerialization::CMdEQueryCriteriaSerialization(TBool aOwnSerializedBuffer)
+	: iSerializedBuffer( NULL ), iOwnSerializedBuffer( aOwnSerializedBuffer )
+	{
+	
+	}
+
+void CMdEQueryCriteriaSerialization::ConstructL(
+	TQueryResultMode aResultMode, TQueryType aQueryType, 
+	CMdENamespaceDef& aNamespaceDef, 
+	CMdEObjectDef* aObjectDef, RPointerArray<CMdEObjectDef>* aObjectDefs, 
+	TUint32 aLimit, TUint32 aOffset, TUint32 aQueryOptimizationFlags, 
+	CMdELogicCondition& aRootCondition, RArray<TMdEOrderRule>& aOrderRules, 
+	RPointerArray<CMdEPropertyDef>* aPropertyFilter)
+	{
+	// If aResultMode is EModeDistinctValues aQueryType must be CMdEQuery::ETypeObject
+	if( EQueryResultModeDistinctValues == aResultMode )
+		{
+		if( EQueryTypeObject != aQueryType )
+			{
+			User::Leave( KErrNotSupported );
+			}
+		else
+			{
+			// Order rules might also contain one order rule and it must be 
+			// same as defined in propery condition.
+			if( aOrderRules.Count() > 1 )
+				{
+				User::Leave( KErrCompletion );
+				}
+
+			// One property filter must exist and it must be same as property condition
+			if( aPropertyFilter )
+				{
+				if( aPropertyFilter->Count() != 1 )
+					{
+					User::Leave( KErrCompletion );
+					}
+				}
+			else
+				{
+				User::Leave( KErrCompletion);
+				}
+			}
+		}
+	
+	TUint32 criteriaBufferSize = sizeof( TMdCSearchCriteria );
+	
+	// Required size for object defs IDs
+	TUint32 objectDefIdCount = 0;
+	if( aObjectDefs )
+		{
+		objectDefIdCount = aObjectDefs->Count();
+
+		criteriaBufferSize += objectDefIdCount * 
+				CMdCSerializationBuffer::KRequiredSizeForTDefId;
+		}
+
+	// Required size for conditions
+	criteriaBufferSize += aRootCondition.RequiredBufferSize();
+
+	// Required size for order rule offsets
+	const TInt orderRuleCount = aOrderRules.Count();
+	criteriaBufferSize += orderRuleCount * 
+			CMdCSerializationBuffer::KRequiredSizeForTUint32;
+
+	// Required size for order rules
+	for( TInt i = 0; i < orderRuleCount; i++ )
+		{
+		criteriaBufferSize += aOrderRules[i].RequiredBufferSize();
+		}
+
+	// Required size for property filters
+	TUint32 propertyFilterCount = 0;
+	if( aPropertyFilter )
+		{
+		propertyFilterCount = aPropertyFilter->Count();
+		
+		criteriaBufferSize += propertyFilterCount * 
+			CMdCSerializationBuffer::KRequiredSizeForTDefId;
+		}
+
+	// Reserve buffer
+	iSerializedBuffer = CMdCSerializationBuffer::NewL( criteriaBufferSize );
+
+	// Insert data to search criteria
+
+	TMdCSearchCriteria criteria;
+	criteria.iQueryResultType = aResultMode;
+	criteria.iQueryType = aQueryType;
+	criteria.iNamespaceDefId = aNamespaceDef.Id();
+
+	if( aObjectDef )
+		{
+		criteria.iObjectDefId = aObjectDef->Id();
+		}
+	else
+		{
+		criteria.iObjectDefId = KNoDefId;
+		}
+
+	criteria.iObjectDefIds.iPtr.iCount = objectDefIdCount;
+	// init offset to "zero", will be updated later if needed
+	criteria.iObjectDefIds.iPtr.iOffset = KNoOffset;
+
+	criteria.iLimit = aLimit;
+	criteria.iOffset = aOffset;
+	criteria.iOptimizationFlags = aQueryOptimizationFlags;
+
+	// init offset to "zero", will be updated later
+	criteria.iRootCondition = KNoOffset;
+
+	criteria.iOrderRules.iPtr.iCount = orderRuleCount;
+	// init offset to "zero", will be updated later if needed
+	criteria.iOrderRules.iPtr.iOffset = KNoOffset;
+
+	criteria.iPropertyFilters.iPtr.iCount = propertyFilterCount;
+	// init offset to "zero", will be updated later if needed
+	criteria.iPropertyFilters.iPtr.iOffset = KNoOffset;
+
+	// Insert data to serialized buffer
+
+	// Position after search criteria
+	const TUint32 afterCriteriaOffset = sizeof( TMdCSearchCriteria );
+
+	// Move to position after search criteria
+	iSerializedBuffer->PositionL( afterCriteriaOffset );
+
+	if( aObjectDefs )
+		{
+		// Update object defs offset to search criteria
+		criteria.iObjectDefIds.iPtr.iOffset = afterCriteriaOffset;
+
+		// Update object defs count
+		for( TUint32 i = 0; i < objectDefIdCount; i++ )
+			{
+			TDefId defId = (*aObjectDefs)[i]->Id();
+			iSerializedBuffer->InsertL( defId );
+			}
+		}
+
+	// Update root condition offset to position after search criteria 
+	// (and possible object defs IDs)
+	criteria.iRootCondition = iSerializedBuffer->Position();
+
+	TUint32 offset = KNoOffset;
+	// Insert root condition to serialized buffer
+	aRootCondition.SerializeL( *iSerializedBuffer, offset );
+
+	// move position after conditions
+	iSerializedBuffer->PositionL( offset );
+	
+	if( orderRuleCount > 0 )
+		{
+		// Update order rule offset to position after search criteria 
+		// (and possible object defs IDs) and root condition
+		criteria.iOrderRules.iPtr.iOffset = iSerializedBuffer->Position();
+
+		for( TUint32 i = 0; i < orderRuleCount; i++)
+			{
+			// Insert current order rule
+			aOrderRules[i].SerializeL( *iSerializedBuffer, offset );
+			}
+		}
+
+	// move position after order rules
+	iSerializedBuffer->PositionL( offset );
+	
+	if( aPropertyFilter )
+		{
+		// Update order property filter offset to position after search 
+		// criteria (and possible object defs IDs), 
+		// root condition and order rules
+		criteria.iPropertyFilters.iPtr.iOffset = iSerializedBuffer->Position();
+
+		for( TUint32 i = 0; i < propertyFilterCount; i++ )
+			{
+			CMdEPropertyDef* propertyDef = (*aPropertyFilter)[i];
+			iSerializedBuffer->InsertL( propertyDef->Id() );
+			}
+		}
+
+	// move buffer to begin and serialize search criteria
+	iSerializedBuffer->PositionL( KNoOffset );
+	criteria.SerializeL( *iSerializedBuffer );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdequeryimpl.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,265 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of object, relation and event query
+*
+*/
+
+
+#include "mdequeryimpl.h"
+
+#include "mdesessionimpl.h"
+#include "mdeasynchronousfindao.h"
+#include "mdeobject.h"
+#include "mderelation.h"
+#include "mdeevent.h"
+
+
+
+CMdEObjectQueryImpl* CMdEObjectQueryImpl::NewL( CMdESessionImpl& aSessionImpl,
+		CMdENamespaceDef& aNamespaceDef, CMdEObjectDef& aObjectDef,
+		RPointerArray<CMdEObjectDef>* aObjectDefs, RMdEEngineSession& aSession )
+	{
+	CMdEObjectQueryImpl* self = CMdEObjectQueryImpl::NewLC( aSessionImpl, aNamespaceDef, 
+			aObjectDef, aObjectDefs, aSession );
+    CleanupStack::Pop( self );
+    return self;
+	}
+
+CMdEObjectQueryImpl* CMdEObjectQueryImpl::NewLC( CMdESessionImpl& aSessionImpl,
+		CMdENamespaceDef& aNamespaceDef, CMdEObjectDef& aObjectDef,
+		RPointerArray<CMdEObjectDef>* aObjectDefs, RMdEEngineSession& aSession  )
+	{
+	CMdEObjectQueryImpl* self = new ( ELeave ) CMdEObjectQueryImpl( aSessionImpl, aNamespaceDef, 
+			aObjectDef, aObjectDefs );
+    CleanupStack::PushL( self );
+    self->ConstructL( aSessionImpl, aSession );
+    return self;
+	}
+
+CMdEObjectQueryImpl::CMdEObjectQueryImpl( 
+		CMdESessionImpl& aSessionImpl, CMdENamespaceDef& aNamespaceDef, 
+		CMdEObjectDef& aObjectDef, RPointerArray<CMdEObjectDef>* aObjectDefs )
+    : CMdEObjectQuery( aSessionImpl, aNamespaceDef, aObjectDef, aObjectDefs )
+    {
+    }
+
+
+void CMdEObjectQueryImpl::ConstructL( CMdESessionImpl& aSessionImpl,
+    RMdEEngineSession& aSession )
+    {
+    ObjectQueryConstructL();
+    iAsyncFind = CMdEAsynchronousFindAO::NewL( *this, aSessionImpl, aSession );
+    }
+
+
+CMdEObjectQueryImpl::~CMdEObjectQueryImpl()
+    {
+    if( iAsyncFind )
+    	{    	
+    	iAsyncFind->Cancel();
+    	
+    	delete iAsyncFind;
+    	}
+    }
+
+
+void CMdEObjectQueryImpl::DoFindL( TUint aMaxCount, TUint aNotifyCount )
+    {
+    iAsyncFind->DoFindL( aMaxCount, aNotifyCount );
+    SetState( EStateSearching );
+    }
+
+
+void CMdEObjectQueryImpl::DoCancel()
+    {
+    // Stop searching.
+    iAsyncFind->Cancel();
+    SetState( EStateError );
+    }
+
+
+void CMdEObjectQueryImpl::DoNotifyResultsL( RPointerArray<CMdEInstanceItem>& aResultList )
+    {
+    NotifyNewResultsL( aResultList );
+    }
+
+
+void CMdEObjectQueryImpl::DoNotifyResultsL( RArray<TItemId>& aResultIdList )
+    {
+    NotifyNewResultsL( aResultIdList );
+    }
+
+void CMdEObjectQueryImpl::DoNotifyResultsL( CDesCArray& aResults )
+	{
+	NotifyNewResultsL( aResults );
+	}
+
+void CMdEObjectQueryImpl::DoNotifyResults( TInt aResultCount )
+    {
+    NotifyNewResults( aResultCount );
+    }
+
+void CMdEObjectQueryImpl::DoNotifyCompleted( TInt aError )
+    {
+    SetState( aError ? EStateError : EStateCompleted );
+    NotifyCompleted( aError );
+    }
+
+
+CMdERelationQueryImpl* CMdERelationQueryImpl::NewL( CMdESessionImpl& aSessionImpl,
+		CMdENamespaceDef& aNamespaceDef, RMdEEngineSession& aSession )
+	{
+	CMdERelationQueryImpl* self = CMdERelationQueryImpl::NewLC( aSessionImpl,
+			aNamespaceDef, aSession );
+    CleanupStack::Pop( self );
+    return self;
+	}
+
+CMdERelationQueryImpl* CMdERelationQueryImpl::NewLC( CMdESessionImpl& aSessionImpl,
+		CMdENamespaceDef& aNamespaceDef, RMdEEngineSession& aSession )
+	{
+	CMdERelationQueryImpl* self = new ( ELeave ) CMdERelationQueryImpl( aSessionImpl, aNamespaceDef );
+    CleanupStack::PushL( self );
+    self->ConstructL( aSessionImpl, aSession );
+    return self;
+	}
+
+CMdERelationQueryImpl::CMdERelationQueryImpl( CMdESessionImpl& aSessionImpl, CMdENamespaceDef& aNamespaceDef )
+    : CMdERelationQuery( aSessionImpl, aNamespaceDef )
+    {
+    }
+
+
+void CMdERelationQueryImpl::ConstructL( CMdESessionImpl& aSessionImpl,
+    RMdEEngineSession& aSession )
+    {
+    RelationQueryConstructL();
+    iAsyncFind = CMdEAsynchronousFindAO::NewL( *this, aSessionImpl, aSession );
+    }
+
+
+CMdERelationQueryImpl::~CMdERelationQueryImpl()
+    {
+	delete iAsyncFind;
+    }
+
+
+void CMdERelationQueryImpl::DoFindL( TUint aMaxCount, TUint aNotifyCount )
+    {
+    iAsyncFind->DoFindL( aMaxCount, aNotifyCount );
+    SetState( EStateSearching );
+    }
+
+    
+void CMdERelationQueryImpl::DoCancel()
+    {
+    // Stop searching.
+    iAsyncFind->Cancel();
+    SetState( EStateError );
+    }
+
+void CMdERelationQueryImpl::DoNotifyResultsL( RPointerArray<CMdEInstanceItem>& aResultList )
+    {
+    NotifyNewResultsL( aResultList );
+    }
+
+void CMdERelationQueryImpl::DoNotifyResultsL( RArray<TItemId>& aResultIdList )
+    {
+    NotifyNewResultsL( aResultIdList );
+    }
+
+void CMdERelationQueryImpl::DoNotifyResults( TUint32 aResultCount )
+    {
+    NotifyNewResults( aResultCount );
+    }
+
+void CMdERelationQueryImpl::DoNotifyCompleted( TInt aError )
+    {
+    SetState( aError ? EStateError : EStateCompleted );
+    NotifyCompleted( aError );
+    }
+
+
+CMdEEventQueryImpl::CMdEEventQueryImpl( CMdESessionImpl& aSessionImpl, CMdENamespaceDef& aNamespaceDef )
+    : CMdEEventQuery( aSessionImpl, aNamespaceDef )
+    {
+    }
+
+
+CMdEEventQueryImpl* CMdEEventQueryImpl::NewL( CMdESessionImpl& aSessionImpl,
+		CMdENamespaceDef& aNamespaceDef, RMdEEngineSession& aSession )
+	{
+	CMdEEventQueryImpl* self = CMdEEventQueryImpl::NewLC( aSessionImpl,
+			aNamespaceDef, aSession );
+    CleanupStack::Pop( self );
+    return self;
+	}
+
+CMdEEventQueryImpl* CMdEEventQueryImpl::NewLC( CMdESessionImpl& aSessionImpl,
+		CMdENamespaceDef& aNamespaceDef, RMdEEngineSession& aSession )
+	{
+	CMdEEventQueryImpl* self = new ( ELeave ) CMdEEventQueryImpl( aSessionImpl, aNamespaceDef );
+    CleanupStack::PushL( self );
+    self->ConstructL( aSessionImpl, aSession );
+    return self;
+	}
+
+void CMdEEventQueryImpl::ConstructL( CMdESessionImpl& aSessionImpl,
+    RMdEEngineSession& aSession )
+    {
+    EventQueryConstructL();
+    iAsyncFind = CMdEAsynchronousFindAO::NewL( *this, aSessionImpl, aSession );
+    }
+
+
+CMdEEventQueryImpl::~CMdEEventQueryImpl()
+    {
+	delete iAsyncFind;
+    }
+
+
+void CMdEEventQueryImpl::DoFindL( TUint aMaxCount, TUint aNotifyCount )
+    {
+    iAsyncFind->DoFindL( aMaxCount, aNotifyCount );
+    SetState( EStateSearching );
+    }
+
+
+void CMdEEventQueryImpl::DoCancel()
+    {
+    // Stop searching.
+    iAsyncFind->Cancel();
+    SetState( EStateError );
+    }
+
+void CMdEEventQueryImpl::DoNotifyResultsL( RPointerArray<CMdEInstanceItem>& aResultList )
+    {
+    NotifyNewResultsL( aResultList );
+    }
+
+void CMdEEventQueryImpl::DoNotifyResultsL( RArray<TItemId>& aResultIdList )
+    {
+    NotifyNewResultsL( aResultIdList );
+    }
+
+void CMdEEventQueryImpl::DoNotifyResults( TUint32 aResultCount )
+    {
+    NotifyNewResults( aResultCount );
+    }
+
+void CMdEEventQueryImpl::DoNotifyCompleted( TInt aError )
+    {
+    SetState( aError ? EStateError : EStateCompleted );
+    NotifyCompleted( aError );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mderange.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Serialization for mderange template class
+*
+*/
+
+#include "mderange.h"
+#include "mdcserializationbuffer.h"
+
+
+void TMdESerializeRange::SerializeL( CMdCSerializationBuffer& aBuffer, TMdERangeType aType,
+		void* aMin, void* aMax, TInt aValueSize )
+	{
+#ifdef _DEBUG
+	if ( aValueSize > sizeof(TMdCValueUnion) )
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("Incorrect type"), KErrMdEIncorrectType ) );
+		User::Leave( KErrMdEIncorrectType );
+		}
+#endif
+
+	aBuffer.InsertL( (TInt32)aType );
+
+	TMdCValueUnion min;
+	Mem::Copy( &min, aMin, aValueSize );
+	TMdCValueUnion max;
+	Mem::Copy( &max, aMax, aValueSize );
+
+	aBuffer.InsertL( min );
+	aBuffer.InsertL( max );
+	}
+
+TUint32 TMdESerializeRange::RequiredBufferSize( TInt 
+#ifdef _DEBUG		
+		aValueSize
+#endif
+		)
+	{
+#ifdef _DEBUG
+	if ( aValueSize > sizeof(TMdCValueUnion) )
+		{
+		User::Panic( _L("Incorrect type"), KErrMdEIncorrectType );
+		}
+#endif
+	
+	// Required size for type (TInt32), iMin and iMax (fixed size)
+	TUint32 bufferSize = CMdCSerializationBuffer::KRequiredSizeForTInt32
+			+ 2 * CMdCSerializationBuffer::KRequiredSizeForTMdCValueUnion;
+
+	return bufferSize;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mderangepropertycondition.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,77 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Serialization for mderange template class
+*
+*/
+
+#include "mderangepropertycondition.h"
+#include "mdcserializationbuffer.h"
+#include "mdepropertydef.h"
+#include "mdcquery.h"
+
+void TMdESerializeRangePropertyCondition::SerializeL( 
+		CMdCSerializationBuffer& aBuffer, 
+		const CMdEPropertyCondition& aPropertyCondition, TMdERangeType aType, 
+		const void* aMin, const void* aMax, TInt aValueSize, TMdCOffset& aFreespaceOffset )
+	{
+	if ( aValueSize > sizeof(TMdCValueUnion) )
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("Incorrect type"), KErrMdEIncorrectType ) );
+		User::Leave( KErrMdEIncorrectType );
+		}
+
+	TMdCPropertyCondition condition;
+
+	condition.iConditionType = aPropertyCondition.Type();
+	condition.iNegated = aPropertyCondition.Negate();
+	condition.iObjectDefId = aPropertyCondition.PropertyDef().ObjectDefId();
+	condition.iPropertyDefId = aPropertyCondition.PropertyDef().Id();
+	condition.iCondition = aBuffer.Position() + sizeof( TMdCPropertyCondition );
+
+	condition.SerializeL( aBuffer );
+	
+	aBuffer.InsertL( (TInt32)aType );
+
+	TMdCValueUnion min;
+	Mem::Copy( &min, aMin, aValueSize );
+	TMdCValueUnion max;
+	Mem::Copy( &max, aMax, aValueSize );
+
+	aBuffer.InsertL( min );
+	aBuffer.InsertL( max );
+	
+	aFreespaceOffset = aBuffer.Position();
+	}
+
+TUint32 TMdESerializeRangePropertyCondition::RequiredBufferSize( TInt  
+#ifdef _DEBUG	
+		aValueSize
+#endif
+		)
+	{
+#ifdef _DEBUG
+	if ( aValueSize > sizeof(TMdCValueUnion) )
+		{
+		User::Panic( _L("Incorrect type"), KErrMdEIncorrectType );
+		}
+#endif
+
+	TUint32 bufferSize = sizeof( TMdCPropertyCondition );
+
+	// Required size for type (TInt32), iMin and iMax (fixed size)
+	bufferSize += CMdCSerializationBuffer::KRequiredSizeForTInt32
+			+ 2 * CMdCSerializationBuffer::KRequiredSizeForTMdCValueUnion;
+
+	return bufferSize;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mderelation.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,268 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#include "mderelation.h"
+
+#include "mdcitem.h"
+#include "mdcserializationbuffer.h"
+#include "mderelationdef.h"
+#include "mdenamespacedef.h"
+
+
+//----------------------------------------------------------
+//               TMdERelation
+//----------------------------------------------------------
+
+TMdERelation::TMdERelation()
+	: iId( KNoId ), iLeftObjectId( KNoId ),
+	  iRightObjectId( KNoId ), iDef( NULL )
+	{
+	}
+
+EXPORT_C TItemId TMdERelation::Id() const
+	{
+	return iId;
+	}
+
+EXPORT_C CMdERelationDef& TMdERelation::DefL() const
+	{
+	if ( !iDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+	return *iDef;
+	}
+
+EXPORT_C TItemId TMdERelation::LeftObjectId() const
+	{
+	return iLeftObjectId;
+	}
+
+EXPORT_C TItemId TMdERelation::RightObjectId() const
+	{
+	return iRightObjectId;
+	}
+
+TUint32 TMdERelation::RequiredBufferSize() const
+	{
+	return sizeof(TMdCRelation);
+	}
+
+void TMdERelation::DeSerializeL(CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef)
+	{
+	const TMdCRelation& relation = TMdCRelation::GetFromBufferL( aBuffer );
+	iId = relation.iId;
+	iLeftObjectId = relation.iLeftObjectId;
+	iRightObjectId = relation.iRightObjectId;
+	if (iId == KNoId || iLeftObjectId == KNoId || iRightObjectId == KNoId)
+		{
+		User::Leave(KErrNotFound);
+		}
+	if(iLeftObjectId == iRightObjectId )
+		{
+		User::Leave( KErrArgument );
+		}
+	iDef = aNamespaceDef.GetRelationDefL( relation.iDefId );
+	}
+
+//----------------------------------------------------------
+//               CMdERelation
+//----------------------------------------------------------
+
+CMdERelation::CMdERelation(CMdESession* aSession, TItemId aId, 
+						   CMdERelationDef& aDef, TItemId aLeftObjectId, 
+						   TItemId aRightObjectId, TInt32 aParameter)
+		: CMdEInstanceItem(aSession, aId), iDef(aDef),
+		  iLeftObjectId(aLeftObjectId), iRightObjectId(aRightObjectId), 
+		  iParameter(aParameter), iGuidHigh( 0 ), iGuidLow( 0 ), iLastModifiedDate( 0 )
+	{
+	}
+
+
+void CMdERelation::ConstructL()
+	{
+	// Same object cannot be on both side of the relation
+	if(iLeftObjectId == iRightObjectId )
+		{
+		User::Leave( KErrArgument );
+		}
+
+	InstanceItemBaseConstruct();
+	}
+
+
+CMdERelation::~CMdERelation()
+	{
+	}
+
+CMdERelation* CMdERelation::NewL(CMdERelationDef& aDef, TItemId aLeftObjectId, 
+		 TItemId aRightObjectId, TInt32 aParameter)
+	{
+	CMdERelation* ret = CMdERelation::NewLC( aDef, aLeftObjectId, aRightObjectId, aParameter );
+	CleanupStack::Pop( ret );
+	return ret;
+	}
+
+CMdERelation* CMdERelation::NewLC(CMdERelationDef& aDef, TItemId aLeftObjectId, 
+		 TItemId aRightObjectId, TInt32 aParameter)
+	{
+	CMdERelation* ret = new (ELeave) CMdERelation( NULL, KNoId, aDef, aLeftObjectId, aRightObjectId, aParameter );
+	CleanupStack::PushL( ret );
+	ret->ConstructL();
+	return ret;
+	}
+
+CMdERelation* CMdERelation::NewL(CMdESession* aSession, CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef)
+	{
+	CMdERelation* ret = CMdERelation::NewLC( aSession, aBuffer, aNamespaceDef );
+	CleanupStack::Pop( ret );
+	return ret;
+	}
+
+CMdERelation* CMdERelation::NewLC(CMdESession* aSession, CMdCSerializationBuffer& aBuffer, CMdENamespaceDef& aNamespaceDef)
+	{
+	const TMdCRelation& serializedRelation = TMdCRelation::GetFromBufferL( aBuffer );
+	if (serializedRelation.iId == KNoId)
+		{
+		User::Leave( KErrNotFound );
+		}
+	if (serializedRelation.iDefId == KNoDefId)
+		{
+		User::Leave( KErrNotFound );
+		}
+	CMdERelationDef* relationDef = aNamespaceDef.GetRelationDefL( serializedRelation.iDefId );
+	if ( !relationDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+	if (serializedRelation.iLeftObjectId == KNoId)
+		{
+		User::Leave( KErrNotFound );
+		}
+	if (serializedRelation.iRightObjectId == KNoId)
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	CMdERelation* relation = new (ELeave) CMdERelation( aSession, serializedRelation.iId, *relationDef,
+			serializedRelation.iLeftObjectId, serializedRelation.iRightObjectId, serializedRelation.iParameter );
+	CleanupStack::PushL( relation );
+
+	relation->SetGuid( serializedRelation.iGuidHigh, serializedRelation.iGuidLow );
+
+	relation->SetLastModifiedDate( serializedRelation.iLastModifiedDate );
+
+	return relation;
+	}
+
+EXPORT_C CMdERelationDef& CMdERelation::Def() const
+	{
+	return iDef;
+	}
+
+
+EXPORT_C TItemId CMdERelation::LeftObjectId() const
+	{
+	return iLeftObjectId;
+	}
+
+
+EXPORT_C TItemId CMdERelation::RightObjectId() const
+	{
+	return iRightObjectId;
+	}
+	
+EXPORT_C TInt32 CMdERelation::Parameter() const
+	{
+	return iParameter;
+	}
+
+EXPORT_C void CMdERelation::SetParameter(TInt32 aParameter)
+	{
+	iParameter = aParameter;
+	}
+	
+EXPORT_C void CMdERelation::SetLeftObjectIdL( TItemId aLeftObjectId )
+	{
+	// Same object cannot be on both side of the relation
+	if( aLeftObjectId == iRightObjectId )
+		{
+		User::Leave( KErrArgument );
+		}
+
+	iLeftObjectId = aLeftObjectId;
+	}
+
+EXPORT_C void CMdERelation::SetRightObjectIdL( TItemId aRightObjectId )
+	{
+	// Same object cannot be on both side of the relation
+	if( aRightObjectId == iLeftObjectId )
+		{
+		User::Leave( KErrArgument );
+		}
+
+	iRightObjectId = aRightObjectId;
+	}
+
+EXPORT_C void CMdERelation::Guid(TInt64& aGuidHigh, TInt64& aGuidLow) const
+	{
+	aGuidHigh = iGuidHigh;
+	aGuidLow = iGuidLow;
+	}
+
+EXPORT_C void CMdERelation::SetGuid(const TInt64& aGuidHigh, const TInt64& aGuidLow)
+	{
+	iGuidHigh = aGuidHigh;
+	iGuidLow = aGuidLow;
+	}
+
+EXPORT_C TTime CMdERelation::LastModifiedDate() const
+	{
+	return iLastModifiedDate;
+	}
+
+EXPORT_C void CMdERelation::SetLastModifiedDate(TTime aLastModifiedDate)
+	{
+	iLastModifiedDate = aLastModifiedDate;
+	}
+
+TUint32 CMdERelation::RequiredBufferSize() const
+	{
+	return sizeof(TMdCRelation);
+	}
+
+TMdCOffset CMdERelation::SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreespaceOffset) const
+	{
+	TMdCRelation relation;
+	relation.iId = Id();
+	relation.iDefId = iDef.Id();
+	relation.iLeftObjectId = iLeftObjectId;
+	relation.iRightObjectId = iRightObjectId;
+	relation.iParameter = iParameter;
+	relation.iGuidHigh = iGuidHigh;
+	relation.iGuidLow = iGuidLow;
+	relation.iLastModifiedDate = iLastModifiedDate;
+	
+	relation.SerializeL( aBuffer );
+	return aFreespaceOffset;
+	}
+
+TMdEInstanceType CMdERelation::InstanceType() const
+	{
+	return EMdETypeRelation;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mderelationcondition.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,341 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+#include "mderelationcondition.h"
+#include "mderelationdef.h"
+#include "mdelogiccondition.h"
+#include "mdscommoninternal.h"
+#include "mdcserializationbuffer.h"
+#include "mdcquery.h"
+
+CMdERelationCondition* CMdERelationCondition::NewL( TItemId aRelationId,
+		const RArray<TItemId>* aRelationIds, TRelationConditionSide aSide,
+		const CMdERelationDef* aRelationDef, 
+		const TMdEIntRange* aParameterRange )
+	{
+	CMdERelationCondition* self = CMdERelationCondition::NewLC(
+			aRelationId, aRelationIds, aSide, aRelationDef, aParameterRange );
+    CleanupStack::Pop( self );
+    return self;
+	}
+
+CMdERelationCondition* CMdERelationCondition::NewLC( TItemId aRelationId,
+		const RArray<TItemId>* aRelationIds, TRelationConditionSide aSide,
+		const CMdERelationDef* aRelationDef, 
+		const TMdEIntRange* aParameterRange )
+	{
+	CMdERelationCondition* self = new ( ELeave ) CMdERelationCondition( 
+			aRelationId, aSide, aRelationDef );
+    CleanupStack::PushL( self );
+    self->ConstructL( aRelationIds, aParameterRange );
+    return self;
+	}
+
+CMdERelationCondition::CMdERelationCondition( TItemId aRelationId, 
+		TRelationConditionSide aSide, const CMdERelationDef* aRelationDef )
+		: CMdECondition( EConditionTypeRelation ), iRelationId( aRelationId ),
+		  iRelationDef( aRelationDef ), iSide( aSide )
+	{
+	iRelationIds = NULL;
+	iParameterRange = NULL;
+	iRightCondition = NULL;
+	iLeftCondition = NULL;
+	}
+
+void CMdERelationCondition::ConstructL(const RArray<TItemId>* aRelationIds, 
+		const TMdEIntRange* aParameterRange)
+    {
+    // Base class construction.
+    ConditionConstruct();
+
+    if( aRelationIds )
+    	{
+    	iRelationIds = new (ELeave) RArray<TItemId>();
+    	
+    	const TInt relationIdCount = aRelationIds->Count();
+    	iRelationIds->ReserveL( relationIdCount );
+    	
+    	for( TInt i = 0; i < relationIdCount; i++ )
+    		{
+    		iRelationIds->AppendL( (*aRelationIds)[i] );
+    		}
+    	}
+
+    if( aParameterRange )
+        {
+        // Make a copy of the parameter range.
+        iParameterRange = new (ELeave) TMdEIntRange(*aParameterRange);
+        }
+    }
+
+CMdERelationCondition::~CMdERelationCondition()
+    {
+   	delete iLeftCondition;
+   	delete iRightCondition;
+   	delete iParameterRange;
+	delete iLastModifiedDateRange;
+
+	if( iRelationIds )
+		{
+		iRelationIds->Close();
+		delete iRelationIds;
+		}
+    }
+
+EXPORT_C TItemId CMdERelationCondition::RelationId() const
+    {   
+    return iRelationId;
+    }
+
+EXPORT_C const RArray<TItemId>* CMdERelationCondition::RelationIds() const
+	{   
+	return iRelationIds;
+	}
+
+EXPORT_C const CMdERelationDef* CMdERelationCondition::RelationDef() const
+    {   
+    return iRelationDef;
+    }
+
+EXPORT_C CMdELogicCondition& CMdERelationCondition::LeftL()
+    {
+    if ( !iLeftCondition )
+    	{
+    	iLeftCondition = CMdELogicCondition::NewL(ELogicConditionOperatorAnd);
+    	}
+    
+    return *iLeftCondition;
+    }
+
+EXPORT_C CMdELogicCondition& CMdERelationCondition::RightL()
+    {
+    if ( !iRightCondition )
+    	{
+    	iRightCondition = CMdELogicCondition::NewL(ELogicConditionOperatorAnd);
+    	}
+
+    return *iRightCondition;
+    }
+
+TRelationConditionSide CMdERelationCondition::Side() const
+	{
+	return iSide;
+	}
+
+EXPORT_C void CMdERelationCondition::SetSide(TRelationConditionSide aSide)
+    {
+    iSide = aSide;
+    }
+
+
+EXPORT_C const TMdEIntRange* CMdERelationCondition::ParameterRange() const
+    {
+    return iParameterRange;
+    }
+
+EXPORT_C void CMdERelationCondition::SetGuid(const TInt64& aGuidHigh, const TInt64& aGuidLow)
+	{
+	iGuidHigh = aGuidHigh;
+	iGuidLow = aGuidLow;
+	}
+
+EXPORT_C TBool CMdERelationCondition::Guid(TInt64& aGuidHigh, TInt64& aGuidLow) const
+	{
+	if( iGuidHigh == 0 && iGuidLow == 0 )
+		{
+		return EFalse;
+		}
+	
+	aGuidHigh = iGuidHigh;
+	aGuidLow = iGuidLow;
+	return ETrue;
+	}
+
+EXPORT_C void CMdERelationCondition::SetLastModifiedDateRangeL(const TMdETimeRange& aLastModifiedDateRange)
+	{
+	if( !iLastModifiedDateRange )
+		{
+		iLastModifiedDateRange = new (ELeave) TMdETimeRange( aLastModifiedDateRange );
+		}
+	}
+
+EXPORT_C TBool CMdERelationCondition::LastModifiedDateRange(TMdETimeRange& aLastModifiedDateRange) const
+	{
+	if( iLastModifiedDateRange )
+		{		
+		aLastModifiedDateRange.SetType( iLastModifiedDateRange->Type() );
+		aLastModifiedDateRange.SetMin( iLastModifiedDateRange->Min() );
+		aLastModifiedDateRange.SetMax( iLastModifiedDateRange->Max() );
+		return ETrue;
+		}
+	
+	return EFalse;
+	}
+
+TUint32 CMdERelationCondition::InternalQueryOptimizationFlags(TUint32& aFlags)
+	{
+	aFlags |= EContainsRelationCondition;
+	return EContainsRelationCondition;
+	}
+
+TUint32 CMdERelationCondition::RequiredBufferSize() const
+	{
+	TUint32 bufferSize = sizeof( TMdCRelationCondition );
+
+	if( iRelationIds )
+		{
+		// count and IDs
+		bufferSize += CMdCSerializationBuffer::KRequiredSizeForTUint32 + 
+			iRelationIds->Count() * CMdCSerializationBuffer::KRequiredSizeForTItemId;
+		}	
+
+	if( iGuidHigh != 0 || iGuidLow != 0 )
+		{
+		bufferSize += 2 * CMdCSerializationBuffer::KRequiredSizeForTInt64;
+		}
+
+	if ( iParameterRange )
+		{
+		bufferSize += iParameterRange->RequiredBufferSize();
+		}
+
+	if ( iLeftCondition && iLeftCondition->Count() > 0 )
+		{
+		bufferSize += iLeftCondition->RequiredBufferSize();
+		}
+
+	if ( iRightCondition && iRightCondition->Count() > 0  )
+		{
+		bufferSize += iRightCondition->RequiredBufferSize();
+		}
+
+	if( iLastModifiedDateRange )
+		{
+		bufferSize += iLastModifiedDateRange->RequiredBufferSize();
+		}
+
+	return bufferSize;
+	}
+
+void CMdERelationCondition::SerializeL(CMdCSerializationBuffer& aBuffer,
+		TMdCOffset& aFreespaceOffset) const
+	{
+	TMdCRelationCondition condition;
+
+	condition.iConditionType = iType;
+	condition.iNegated = iNegated;
+	condition.iObjectSide = iSide;
+
+	if( iRelationDef )
+		{
+		condition.iRelationDefId = iRelationDef->Id();
+		}
+	else
+		{
+		condition.iRelationDefId = KNoDefId;
+		}
+
+	condition.iRelationId = iRelationId;
+
+	// updated later, if relation IDs exists
+	condition.iRelationIds.iPtr.iCount = 0;
+	condition.iRelationIds.iPtr.iOffset = KNoOffset;
+	// updated later, if GUID exists
+	condition.iGuid = KNoOffset;
+	// updated later, if parameter range exists
+	condition.iParameterRange = KNoOffset;
+	// updated later, if left object condition exists
+	condition.iLeftObjectCondition = KNoOffset;
+	// updated later, if right object condition exists
+	condition.iRightObjectCondition = KNoOffset;
+	// updated later, if last modified date range exists
+	condition.iLastModifiedDateRange = KNoOffset;
+
+	const TUint32 conditionOffset = aBuffer.Position();
+
+	// get position after condition
+	aFreespaceOffset = conditionOffset + sizeof( TMdCRelationCondition );
+	aBuffer.PositionL( aFreespaceOffset );
+
+	if( iRelationIds )
+		{
+		condition.iRelationIds.iPtr.iCount = iRelationIds->Count();
+		condition.iRelationIds.iPtr.iOffset = aFreespaceOffset;
+		
+		const TInt relationIdCount = iRelationIds->Count();
+		for( TInt i = 0; i < relationIdCount; i++ )
+			{
+			const TItemId relationId = (*iRelationIds)[i];
+			aBuffer.InsertL( relationId );
+			}
+		
+		aFreespaceOffset = aBuffer.Position();
+		}
+	
+	if( iGuidHigh != 0 || iGuidLow != 0 )
+		{
+		condition.iGuid = aFreespaceOffset;
+
+		aBuffer.InsertL( iGuidHigh );
+		aBuffer.InsertL( iGuidLow );
+		
+		aFreespaceOffset = aBuffer.Position();
+		}
+
+	if ( iParameterRange )
+		{
+		condition.iParameterRange = aFreespaceOffset;
+
+		iParameterRange->SerializeL( aBuffer );
+
+		aFreespaceOffset = aBuffer.Position();
+		}
+
+	if ( iLeftCondition && iLeftCondition->Count() > 0  )
+		{
+		condition.iLeftObjectCondition = aFreespaceOffset;
+
+		iLeftCondition->SerializeL( aBuffer, aFreespaceOffset );
+
+		aFreespaceOffset = aBuffer.Position();
+		}
+
+	if ( iRightCondition && iRightCondition->Count() > 0  )
+		{
+		condition.iRightObjectCondition = aFreespaceOffset;
+
+		iRightCondition->SerializeL( aBuffer, aFreespaceOffset );
+
+		aFreespaceOffset = aBuffer.Position();
+		}
+
+	if ( iLastModifiedDateRange )
+		{
+		condition.iLastModifiedDateRange = aFreespaceOffset;
+
+		iLastModifiedDateRange->SerializeL( aBuffer );
+
+		aFreespaceOffset = aBuffer.Position();
+		}
+
+	aBuffer.PositionL( conditionOffset );
+	
+	condition.SerializeL( aBuffer );
+	
+	// move back to after sub condition
+	aBuffer.PositionL( aFreespaceOffset );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mderelationdef.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,80 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#include "mderelationdef.h"
+
+#include "mdcdef.h"
+#include "mdenamespacedef.h"
+#include "mdcserializationbuffer.h"
+
+
+CMdERelationDef::CMdERelationDef( const TMdCRelationDef& aRelationDef, CMdENamespaceDef& aNamespaceDef )
+	: iRelationDef(aRelationDef), iNamespaceDef( aNamespaceDef )
+	{
+	}
+
+CMdERelationDef* CMdERelationDef::NewL( const TMdCRelationDef& aRelationDef, 
+    CMdCSerializationBuffer& aSchemaBuffer, CMdENamespaceDef& aNamespaceDef )
+	{
+    CMdERelationDef* def = CMdERelationDef::NewLC( aRelationDef, aSchemaBuffer, aNamespaceDef );
+    CleanupStack::Pop( def );
+    return def;
+    }
+
+CMdERelationDef* CMdERelationDef::NewLC( const TMdCRelationDef& aRelationDef, 
+    CMdCSerializationBuffer& aSchemaBuffer, CMdENamespaceDef& aNamespaceDef )
+	{
+    CMdERelationDef* def = new( ELeave ) CMdERelationDef( aRelationDef, aNamespaceDef);
+    CleanupStack::PushL( def );
+    def->ConstructL( aSchemaBuffer );
+    return def;
+	}
+
+void CMdERelationDef::ConstructL( CMdCSerializationBuffer& aSchemaBuffer )
+	{
+	aSchemaBuffer.PositionL( iRelationDef.iName.iPtr.iOffset );
+	iName.Set( aSchemaBuffer.ReceivePtr16L() );
+	}
+
+CMdERelationDef::~CMdERelationDef()
+	{
+	}
+
+TDefId CMdERelationDef::Id() const
+	{
+	return iRelationDef.iDefId;
+	}
+	
+EXPORT_C CMdENamespaceDef& CMdERelationDef::NamespaceDef() const
+	{
+	return iNamespaceDef;
+	}
+
+EXPORT_C const TDesC& CMdERelationDef::Name() const
+	{
+	return iName;
+	}
+
+EXPORT_C TInt CMdERelationDef::Compare( const CMdERelationDef& aRelationDef ) const
+	{
+	TInt result = iNamespaceDef.Compare( aRelationDef.iNamespaceDef );
+	if ( result == 0 )
+		{
+		result = iRelationDef.iDefId - aRelationDef.Id();
+		}
+	return result;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mderelationquery.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#include "mderelationquery.h"
+
+#include "mdepanic.h"
+#include "mderelation.h"
+
+
+/* Constuctors */
+
+CMdERelationQuery::CMdERelationQuery(CMdESession& aSession, CMdENamespaceDef& aNamespaceDef)
+        : CMdEQuery(EQueryTypeRelation, aSession, aNamespaceDef)
+    {
+    }
+
+
+void CMdERelationQuery::RelationQueryConstructL()
+    {
+    QueryConstructL();
+    }
+
+
+/* Destructor */
+
+CMdERelationQuery::~CMdERelationQuery()
+	{
+	}
+
+
+/* Methods */
+
+EXPORT_C CMdERelation& CMdERelationQuery::Result(TInt aIndex) const
+    {
+    return static_cast<CMdERelation&>( ResultItem(aIndex) );
+    }
+	
+void CMdERelationQuery::DoCancel() 
+    {
+    SetState( EStateError );
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdesession.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Metadata engine client session
+*
+*/
+
+
+#include "mdesession.h"
+
+#include "mdesessionimpl.h"
+
+
+EXPORT_C CMdESession* CMdESession::NewL(MMdESessionObserver& aObserver)
+	{
+	CMdESession* self = CMdESession::NewLC(aObserver);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+
+EXPORT_C CMdESession* CMdESession::NewLC(MMdESessionObserver& aObserver)
+	{
+	CMdESessionImpl* self = new (ELeave) CMdESessionImpl(aObserver);
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+	}
+
+
+CMdESession::CMdESession()
+	{
+	}
+
+
+void CMdESession::SessionConstruct()
+	{
+	}
+
+
+CMdESession::~CMdESession()
+	{
+	}
+	
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdesessionimpl.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,2931 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Metadata engine client session implementation*
+*/
+
+#include <etel3rdparty.h>
+#include <e32property.h> 
+
+#include "mdesessionimpl.h"
+#include "mdesessionstartupao.h"
+
+#include "mdcdef.h"
+#include "mdcitem.h"
+#include "mdcresult.h"
+#include "mdeobjectdef.h"
+#include "mderelationdef.h"
+#include "mdeeventdef.h"
+#include "mdeobject.h"
+#include "mderelation.h"
+#include "mdeevent.h"
+#include "mdepanic.h"
+#include "mdequeryimpl.h"
+#include "mdenotifierao.h"
+#include "mdeobjectdef.h"
+#include "mdenamespacedef.h"
+#include "mdccommon.pan"
+#include "mdedatabuffer.h"
+#include "mdcserializationbuffer.h"
+#include "mdequerycriteriaserialization.h"
+#include "mdelogiccondition.h"
+#include "mdeobjectcondition.h"
+#include "mdscommoninternal.h"
+
+RMdESessionAsyncRequest::RMdESessionAsyncRequest( TRequestType aRequestType, 
+	CMdCSerializationBuffer* aBuffer, CMdCSerializationBuffer& aResultBuffer,
+	TRequestStatus& aRequestStatus) : 
+	iRequestType(aRequestType), iBuffer(aBuffer), iResultBuffer(&aResultBuffer), 
+	iRequestStatus(&aRequestStatus)
+	{
+	*iRequestStatus = KRequestPending;
+	}
+
+void RMdESessionAsyncRequest::Close()
+	{
+	if (iBuffer)
+		{
+		delete iBuffer;
+		iBuffer = NULL;
+		}
+	}
+
+void CMdESessionAsyncHandler::AddRequest( CMdCSerializationBuffer* aBuffer,
+			CMdCSerializationBuffer& aResultBuffer, 
+			TRequestStatus& aRequestStatus )
+	{
+	RMdESessionAsyncRequest request = RMdESessionAsyncRequest( 
+			RMdESessionAsyncRequest::EAddRequest, 
+			aBuffer, aResultBuffer, aRequestStatus );
+
+	iRequests.Append(request);
+
+	if( !IsActive() )
+		{
+		iEngineSession.DoAddItemsAsync( *aBuffer, aResultBuffer, 
+				iStatus );
+		SetActive();
+		}
+	}
+
+void CMdESessionAsyncHandler::UpdateRequest( CMdCSerializationBuffer * aBuffer,
+			CMdCSerializationBuffer& aResultBuffer,
+			TRequestStatus& aRequestStatus )
+	{
+	RMdESessionAsyncRequest request = RMdESessionAsyncRequest( 
+			RMdESessionAsyncRequest::EUpdateRequest,
+			aBuffer, aResultBuffer, aRequestStatus);
+
+	iRequests.Append(request);
+
+	if( !IsActive() )
+		{
+		iEngineSession.DoUpdateItemsAsync(*aBuffer, aResultBuffer, 
+				iStatus);
+		SetActive();
+		}
+	}
+
+void CMdESessionAsyncHandler::RemoveRequest( CMdCSerializationBuffer* aBuffer,
+		CMdCSerializationBuffer& aResultBuffer,
+		TRequestStatus& aRequestStatus )
+	{
+	RMdESessionAsyncRequest request = RMdESessionAsyncRequest( 
+			RMdESessionAsyncRequest::ERemoveRequest, 
+			aBuffer, aResultBuffer, aRequestStatus);
+
+	iRequests.Append(request);
+
+	if( !IsActive() )
+		{
+		iEngineSession.DoRemoveItemsAsync( *aBuffer, aResultBuffer, 
+				iStatus );	
+		SetActive();
+		}
+	}
+
+CMdESessionAsyncHandler* CMdESessionAsyncHandler::NewL(CMdESessionImpl& aSession, 
+		RMdEEngineSession &aEngineSession)
+	{
+	CMdESessionAsyncHandler* self = CMdESessionAsyncHandler::NewLC(
+			aSession, aEngineSession);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+CMdESessionAsyncHandler* CMdESessionAsyncHandler::NewLC( CMdESessionImpl& aSession, 
+		RMdEEngineSession &aEngineSession )
+	{
+	CMdESessionAsyncHandler *self = new (ELeave) CMdESessionAsyncHandler(
+			aSession, aEngineSession);
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+	}
+
+CMdESessionAsyncHandler::~CMdESessionAsyncHandler()
+	{
+	Cancel();
+
+	const TInt count = iRequests.Count();
+
+	for (TInt i = 0; i < count; i++)
+		{
+		iRequests[i].Close();
+		}
+	iRequests.Close();		
+	}		
+
+void CMdESessionAsyncHandler::RunL()
+	{
+	//Remove first from array	
+	RMdESessionAsyncRequest& request = iRequests[0];
+	iRequests.Remove(0);
+
+	const TInt status = iStatus.Int();
+
+	User::RequestComplete( request.iRequestStatus, status );
+	request.Close();
+	
+	if (iRequests.Count() > 0)
+		{
+		request = iRequests[0];
+
+		iStatus = KRequestPending;
+		
+		switch( request.iRequestType )
+			{
+			case RMdESessionAsyncRequest::EAddRequest:
+				iEngineSession.DoAddItemsAsync( *(request.iBuffer),
+					*(request.iResultBuffer), iStatus);
+				break;
+			case RMdESessionAsyncRequest::EUpdateRequest:
+				iEngineSession.DoUpdateItemsAsync( *(request.iBuffer),
+					*(request.iResultBuffer), iStatus);
+				break;
+			case RMdESessionAsyncRequest::ERemoveRequest:
+				iEngineSession.DoRemoveItemsAsync( *(request.iBuffer),
+					*(request.iResultBuffer), iStatus);
+				break;
+			default:
+			    break;
+			}
+		SetActive();			
+		}						
+	}
+
+TInt CMdESessionAsyncHandler::RunError(TInt aError)
+	{
+	if( aError == KErrServerTerminated )
+		{
+		iSession.NotifyError( aError );
+		return KErrNone;
+		}
+	else
+		{
+		return aError;
+		}
+	}
+
+void CMdESessionAsyncHandler::DoCancel()
+	{
+	}
+
+CMdESessionAsyncHandler::CMdESessionAsyncHandler(CMdESessionImpl& aSession, 
+		RMdEEngineSession &aEngineSession)
+	: CActive( CActive::EPriorityStandard ), iSession( aSession ), 
+	iEngineSession(aEngineSession)
+	{
+	}
+
+void CMdESessionAsyncHandler::ConstructL()		
+	{
+	CActiveScheduler::Add(this);
+	}
+
+CMdESessionImpl::CMdESessionImpl(MMdESessionObserver& aObserver)
+	: iSessionStartupAO( NULL ), iSessionObserver(&aObserver), 
+	  iSchemaBuffer( NULL ), iAsyncHandler(NULL), iNextQueryId( 0 ),
+	  iSession( *this )
+	{
+	}
+
+CMdESessionImpl::~CMdESessionImpl()
+	{
+	Close();
+
+	delete iSchemaBuffer;
+
+	iNotifiers.ResetAndDestroy();
+	iNotifiers.Close();
+
+	iSession.Shutdown();
+	iSession.Close();
+	
+	iSchemaChunk.Close();
+	
+	iNamespaceDefs.ResetAndDestroy();
+	iNamespaceDefs.Close();
+	
+	delete iSessionStartupAO;
+		
+	delete iAsyncHandler;
+	}
+
+void CMdESessionImpl::ConstructL()
+	{
+    iSessionStartupAO = CMdESessionStartupAO::NewL( *this, iSession );
+    iAsyncHandler = CMdESessionAsyncHandler::NewL( *this, iSession );    
+    }
+
+void CMdESessionImpl::Close()
+	{
+	iSchemaObserverArray.Reset();
+	iSchemaObserverArray.Close();
+	}
+
+TInt CMdESessionImpl::NamespaceDefCount() const
+	{
+	return iNamespaceDefs.Count();
+	}
+
+CMdENamespaceDef& CMdESessionImpl::NamespaceDefL( TInt aIndex )
+	{
+	return *iNamespaceDefs[aIndex];
+	}
+
+CMdENamespaceDef& CMdESessionImpl::GetNamespaceDefL( const TDesC& aName )
+	{
+	const TInt KNamespaceCount = iNamespaceDefs.Count();
+	for ( TInt i = 0; i < KNamespaceCount; ++i )
+		{
+		if ( !aName.Compare( iNamespaceDefs[i]->Name() ) )
+			{
+			return NamespaceDefL( i );
+			}
+		}
+
+	User::Leave( KErrNotFound );
+	return NamespaceDefL( -1 ); // never reached
+	}
+
+CMdENamespaceDef& CMdESessionImpl::GetNamespaceDefL(TDefId aId)
+	{
+	const TInt KNamespaceCount = iNamespaceDefs.Count();
+	for ( TInt i = 0; i < KNamespaceCount; ++i )
+		{
+		if ( iNamespaceDefs[i]->Id() == aId )
+			{
+			return NamespaceDefL( i );
+			}
+		}
+
+	User::Leave( KErrNotFound );
+	return NamespaceDefL( -1 ); // never reached
+	}
+
+CMdENamespaceDef& CMdESessionImpl::GetDefaultNamespaceDefL()
+	{
+	return GetNamespaceDefL( KDefaultNamespaceDefId );
+	}
+
+CMdEObject* CMdESessionImpl::NewObjectL( CMdEObjectDef& aDef, const TDesC& aUri, TUint32 aMediaId )
+	{
+	CMdEObject* object = NewObjectLC( aDef, aUri, aMediaId );
+	CleanupStack::Pop(object);
+	return object;
+	}
+
+CMdEObject* CMdESessionImpl::NewObjectLC( CMdEObjectDef& aDef, const TDesC& aUri, TUint32 aMediaId )
+	{
+	CMdEObject* object = CMdEObject::NewLC( aDef, aUri, aMediaId );
+	return object;
+	}
+
+void CMdESessionImpl::CommitObjectL(CMdEObject& aObject)
+    {
+	// check state
+	// check that object is open for modifications
+	if (!aObject.OpenForModifications())
+		{
+		User::Leave( KErrMdENotLocked );
+		}
+
+	RPointerArray<CMdEInstanceItem> items;
+	CleanupClosePushL( items );
+	items.AppendL( &aObject );
+	UpdateItemsL( items );
+	CleanupStack::PopAndDestroy( &items );	
+    }
+
+void CMdESessionImpl::CommitObjectsL(RPointerArray<CMdEObject>& aObjects)
+    {
+	// check state
+	// check that object is open for modifications
+
+    RPointerArray<CMdEInstanceItem> items;
+    CleanupClosePushL( items );
+
+    const TInt objectsCount = aObjects.Count();
+    items.ReserveL( objectsCount );    
+    for (TInt i = 0; i < objectsCount; ++i)
+    	{
+    	CMdEObject* obj = aObjects[i];
+    	if ( !obj->OpenForModifications() )
+    		{
+    		User::Leave( KErrMdENotLocked );
+    		}
+		items.Append( obj );
+    	}
+
+    UpdateItemsL(items);
+
+    items.Reset();
+    CleanupStack::PopAndDestroy( &items );
+    }
+
+TItemId CMdESessionImpl::CancelObjectL(CMdEObject& aObject)
+    {
+    // check that object is open for modifications
+    if( !aObject.OpenForModifications() || !aObject.BelongsToSession() )
+    	{
+    	User::Leave( KErrMdENotLocked );
+    	}
+    
+	CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( 
+			sizeof(TMdCItemIds) + 
+			CMdCSerializationBuffer::KRequiredSizeForTItemId );
+	
+	TMdCItemIds itemIds;
+	itemIds.iNamespaceDefId = aObject.Def().NamespaceDef().Id();
+	itemIds.iObjectIds.iPtr.iCount = 1;
+	itemIds.iObjectIds.iPtr.iOffset = sizeof(TMdCItemIds);
+	itemIds.SerializeL( *buffer );
+
+	buffer->InsertL( aObject.Id() );
+
+    iSession.DoCancelObjectL( *buffer );
+
+    TItemId result;
+    buffer->PositionL( KNoOffset );
+    itemIds.DeserializeL( *buffer );
+	buffer->PositionL( itemIds.iObjectIds.iPtr.iOffset );
+	buffer->ReceiveL( result );
+
+	CleanupStack::PopAndDestroy( buffer ); // buffer
+
+	if (result == KNoId)
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	aObject.SetNotOpenForModifications();
+	return result;
+    }
+
+CMdERelation* CMdESessionImpl::NewRelationLC( CMdERelationDef& aDef, TItemId aLeftObjectId, 
+										      TItemId aRightObjectId, TInt32 aParameter )
+	{
+	return CMdERelation::NewLC(aDef, aLeftObjectId, aRightObjectId, aParameter);
+	}
+
+CMdERelation* CMdESessionImpl::NewRelationL( CMdERelationDef& aDef, TItemId aLeftObjectId, 
+										     TItemId aRightObjectId, TInt32 aParameter )
+	{
+	CMdERelation* rel = NewRelationLC( aDef, aLeftObjectId, aRightObjectId, aParameter );
+	CleanupStack::Pop( rel );
+	return rel;
+	}
+
+
+CMdEEvent* CMdESessionImpl::NewEventLC(CMdEEventDef& aDef, TItemId aObjectId, TTime aTime, const TDesC* aSource, const TDesC* aParticipant)
+	{
+	return CMdEEvent::NewLC(aDef, aObjectId, aTime, aSource, aParticipant );
+	}
+
+CMdEEvent* CMdESessionImpl::NewEventL(CMdEEventDef& aDef, TItemId aObjectId, TTime aTime, const TDesC* aSource, const TDesC* aParticipant)
+	{
+	CMdEEvent* event = NewEventLC( aDef, aObjectId, aTime, aSource, aParticipant );
+	CleanupStack::Pop( event );
+	return event;
+	}
+	
+void CMdESessionImpl::AddSchemaObserverL(MMdESchemaObserver& aObserver)
+	{
+	CheckOpened();
+
+	CMdENamespaceDef& defaultNamespaceDef = GetDefaultNamespaceDefL();
+
+	TInt err = FindNotifier( ESchemaModify, &aObserver, defaultNamespaceDef );
+	
+    if ( err != KErrNotFound )
+    	{
+    	if ( err >= 0 )
+    		{
+    		return;
+    		}
+    	User::LeaveIfError( err );
+    	}
+    
+    CMdENotifierAO* notifier = CMdENotifierAO::NewLC( *this, iSession );
+    notifier->RegisterL( ESchemaModify, &aObserver, NULL, defaultNamespaceDef );
+    User::LeaveIfError(iNotifiers.Append( notifier ));
+    CleanupStack::Pop( notifier );
+	}
+
+
+void CMdESessionImpl::RemoveSchemaObserverL(MMdESchemaObserver& aObserver)
+	{
+	CheckOpened();
+
+	CMdENamespaceDef& defaultNamespaceDef = GetDefaultNamespaceDefL();
+
+    TInt index = FindNotifier( ESchemaModify, &aObserver, defaultNamespaceDef );
+    if ( index != KErrNotFound )
+        {
+	    iNotifiers[index]->Cancel();
+	    delete iNotifiers[index];
+	    iNotifiers[index] = NULL;
+	    iNotifiers.Remove( index );
+        }
+    else
+    	{
+       	User::Leave( KErrNotFound );
+    	}
+	}
+
+void CMdESessionImpl::NotifySessionOpened(TInt aError)
+	{
+	__ASSERT_DEBUG(iSessionObserver != 0,
+				    TMdEPanic::Panic(TMdEPanic::EInternal));
+	if(!aError)
+		{
+		iSessionState = EMdESessionOpen;
+		}
+
+    if( iSessionObserver )
+        {
+        iSessionObserver->HandleSessionOpened(*this, aError);
+        }
+	}
+
+
+void CMdESessionImpl::NotifyError(TInt aError)
+	{
+	if(iSessionObserver)
+		{
+		iSessionObserver->HandleSessionError(*this, aError);
+		}
+	iSessionState = EMdESessionClosed;
+	}
+
+void CMdESessionImpl::LoadSchemaL()
+	{
+	DoLoadSchemaL();
+	}
+
+RMdEEngineSession& CMdESessionImpl::EngineSession()
+	{
+	return iSession;
+	}
+
+void CMdESessionImpl::DoLoadSchemaL()
+    {
+    TInt handle( 0 );
+    iSession.DoLoadSchemaL( handle );
+    
+   	TBuf<32> name( KSchemaChunkName );
+	name.AppendNum( handle );
+	iSchemaChunk.Close();
+	User::LeaveIfError( iSchemaChunk.OpenGlobal( name, ETrue ) );
+
+	CMdCSerializationBuffer* schemaBuffer = 
+		CMdCSerializationBuffer::NewLC( iSchemaChunk.Base(), iSchemaChunk.Size() );
+
+	if ( schemaBuffer->Size() == 0 )
+		{
+		User::Leave( KErrNotFound );
+		}
+	else
+		{
+		CleanupStack::Pop( schemaBuffer );
+		}
+
+	delete iSchemaBuffer;
+
+	iSchemaBuffer = schemaBuffer;
+	
+	iNamespaceDefs.ResetAndDestroy();
+	
+	// initialize namespacedefs
+	const TMdCSchema& schema = TMdCSchema::GetFromBufferL(*iSchemaBuffer);
+	const TUint32 namespaceCount = schema.iNamespaceDefs.iPtr.iCount;
+	const TMdCOffset namespaceOffset = schema.iNamespaceDefs.iPtr.iOffset;
+
+	iNamespaceDefs.ReserveL( namespaceCount );	
+	for ( TUint32 i = 0; i < namespaceCount; ++i )
+		{
+		iSchemaBuffer->PositionL( namespaceOffset + i * sizeof(TMdCNamespaceDef) );
+		const TMdCNamespaceDef& namespaceDef = TMdCNamespaceDef::GetFromBufferL(*iSchemaBuffer);
+		iNamespaceDefs.AppendL( CMdENamespaceDef::NewL( *this, namespaceDef, *iSchemaBuffer ) );
+		}
+    }
+
+void CMdESessionImpl::AddRelationDefL( const CMdENamespaceDef &aNamespaceDef, const TDesC &aName )
+	{
+	iSession.DoAddRelationDefL(aNamespaceDef.Id(), aName);
+	DoLoadSchemaL();
+	}
+
+void CMdESessionImpl::AddEventDefL( const CMdENamespaceDef &aNamespaceDef, const TDesC &aName )
+	{
+	iSession.DoAddEventDefL(aNamespaceDef.Id(), aName);
+	DoLoadSchemaL();
+	}
+
+/**
+* Get methods
+*/
+CMdEObject* CMdESessionImpl::GetObjectL(CMdEObjectDef& aObjectDef, 
+	const TItemId aId, const TInt64 aGuidHigh, const TInt64 aGuidLow, const TDesC& aUri, 
+	TMdCQueryLockType aLocktype, TBool aIncludeFreetexts )
+    {
+    if(aUri == KNullDesC && aGuidHigh == 0 && aGuidLow == 0 && aId == KNoId)
+    	{
+    	User::Leave(KErrNotSupported);
+    	}
+        
+    CMdENamespaceDef &namespacedef = aObjectDef.NamespaceDef();    
+    
+    CMdEObjectQuery* query = NewObjectQueryL(namespacedef,aObjectDef,NULL);
+    CleanupStack::PushL(query);
+    
+    query->SetResultMode(EQueryResultModeItem);
+        
+    if(aId != KNoId)
+    	{
+    	CMdEObjectCondition& cond = query->Conditions().AddObjectConditionL( aId );
+    	cond.SetConfidentialityLevel( EObjectConditionLevelIgnoreConfidentiality );
+    	}
+    else if(aGuidHigh != 0 && aGuidLow != 0)
+    	{
+    	CMdEObjectCondition& cond = query->Conditions().AddObjectConditionL( aGuidHigh, aGuidLow );
+    	cond.SetConfidentialityLevel( EObjectConditionLevelIgnoreConfidentiality );
+    	}
+    else if(aUri != KNullDesC)
+    	{
+    	CMdEObjectCondition& cond = query->Conditions().AddObjectConditionL( EObjectConditionCompareUri, aUri );
+    	cond.SetConfidentialityLevel( EObjectConditionLevelIgnoreConfidentiality );
+    	}
+    else
+    	{
+    	User::Leave( KErrArgument );
+    	}
+	
+	TUint32 optimizationFlags = EContainsObjectCondition;
+	
+	if( aIncludeFreetexts )
+		{
+		optimizationFlags |= EContainsFreetextCondition;
+		}
+	
+	if( aLocktype == ELock )
+		{
+		optimizationFlags |= EContainsObjectLocking;
+		}
+	
+	CMdEQueryCriteriaSerialization* buf = CMdEQueryCriteriaSerialization::NewLC( 
+											   query->ResultMode(),
+											   query->Type(), 
+    										   query->NamespaceDef(), 
+    										   &aObjectDef, 
+    										   NULL, 
+    										   1, //Max 1  
+    										   0, // 0 offset because it's not used now
+    										   optimizationFlags , 
+    										   query->Conditions(), 
+    										   query->OrderRules(),
+    										   NULL);    
+
+	CMdCSerializationBuffer* resbuf = iSession.DoFindSyncLC( 
+		query, 
+		*buf, aLocktype, 
+		KMdEQueryDefaultMaxCount );
+
+	RPointerArray<CMdEInstanceItem> items;
+	CleanupClosePushL( items );	
+
+	DeserializeQueryResultL( *resbuf, items );
+
+	CleanupStack::Pop( &items );
+
+   	CleanupStack::PopAndDestroy( resbuf );
+	CleanupStack::PopAndDestroy( buf );
+	CleanupStack::PopAndDestroy( query );
+
+	const TInt itemsCount( items.Count() );
+	if( itemsCount== 1 )
+		{
+		CMdEInstanceItem* item = items[0];
+		
+#ifdef _DEBUG
+		if( !item || item->InstanceType() != EMdETypeObject )
+			{
+			User::Leave( KErrCorrupt );
+			}
+#endif
+		
+		items.Close();
+
+		return (CMdEObject*)item;
+		}
+   	else if( itemsCount == 0 )
+   		{
+   		items.Close();
+
+   		return NULL;
+   		}
+
+#ifdef _DEBUG
+   	else
+   		{
+   		items.ResetAndDestroy();
+   		items.Close();
+
+   		User::Leave( KErrCorrupt );
+   		}
+#endif
+
+	return NULL; // <-- just to stop compile warnings!!
+    }
+
+CMdEObject* CMdESessionImpl::GetObjectL( const TItemId aId, CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef* namespaceDef = GetNamespaceDefL( aNamespaceDef );
+	
+	CMdEObjectDef* objectDef = namespaceDef->GetObjectDefL( KBaseObjectDefId );
+	if ( !objectDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+	return GetObjectL(*objectDef, aId, 0, 0, KNullDesC, EGet, EFalse);	
+	}
+	
+CMdEObject* CMdESessionImpl::GetFullObjectL( const TItemId aId, CMdENamespaceDef* aNamespaceDef )
+	{
+	TMdEObject object;
+
+	CheckObjectL( object, aId, aNamespaceDef );
+
+	if( object.NotPresent() || object.Removed() )
+		{
+		User::Leave( KErrNotFound );
+		}
+	
+	const CMdEObjectDef& objectDef = object.DefL();
+	
+	return GetObjectL( CONST_CAST( CMdEObjectDef&, objectDef ), aId, 0, 0, KNullDesC, EGet, ETrue );
+	}
+
+CMdEObject* CMdESessionImpl::GetObjectL( const TItemId aId, CMdEObjectDef& aObjectDef )
+	{
+	return GetObjectL(aObjectDef, aId, 0, 0, KNullDesC, EGet, EFalse);	
+	}
+
+CMdEObject* CMdESessionImpl::GetObjectL( const TInt64 aGuidHigh, const TInt64 aGuidLow, CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef* namespaceDef = GetNamespaceDefL( aNamespaceDef );
+
+	CMdEObjectDef* objectDef = namespaceDef->GetObjectDefL( KBaseObjectDefId );
+	if ( !objectDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+	return GetObjectL(*objectDef, KNoId, aGuidHigh, aGuidLow, KNullDesC, EGet, EFalse);	
+	}
+
+CMdEObject* CMdESessionImpl::GetFullObjectL( const TInt64 aGuidHigh, const TInt64 aGuidLow, CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdEObject* object = NULL;
+
+	object = GetObjectL( aGuidHigh, aGuidLow, aNamespaceDef );
+
+	if ( object )
+		{
+		CMdEObjectDef& objectDef = object->Def();
+		TItemId objId = object->Id();
+
+		delete object;
+		object = NULL;		
+		object = GetObjectL( objectDef, objId, 0, 0, KNullDesC, EGet, ETrue );
+		}
+
+	return object;
+	}
+
+CMdEObject* CMdESessionImpl::GetObjectL( const TInt64 aGuidHigh, const TInt64 aGuidLow, CMdEObjectDef& aObjectDef )
+	{
+	return GetObjectL(aObjectDef, KNoId, aGuidHigh, aGuidLow, KNullDesC, EGet, EFalse);	
+	}
+
+CMdEObject* CMdESessionImpl::OpenObjectL( const TItemId aId, CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef* namespaceDef = GetNamespaceDefL( aNamespaceDef );
+	
+	CMdEObjectDef* objectDef = namespaceDef->GetObjectDefL( KBaseObjectDefId );
+	if ( !objectDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	CMdEObject* object = GetObjectL(*objectDef, aId, 0, 0, KNullDesC, ELock, EFalse);
+	
+	if ( object && !object->OpenForModifications() )
+		{
+		delete object;
+		object = NULL;
+		User::Leave( KErrLocked );
+		}
+
+	return object;
+	}
+
+CMdEObject* CMdESessionImpl::OpenFullObjectL( const TItemId aId, CMdENamespaceDef* aNamespaceDef )
+	{
+	TMdEObject object;
+
+	CheckObjectL( object, aId, aNamespaceDef );
+
+	if( object.NotPresent() || object.Removed() )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	const CMdEObjectDef& objectDef = object.DefL();
+	
+	return GetObjectL( CONST_CAST( CMdEObjectDef&, objectDef ), aId, 0, 0, KNullDesC, ELock, ETrue );
+	}
+
+CMdEObject* CMdESessionImpl::OpenObjectL( const TItemId aId, CMdEObjectDef& aObjectDef )
+    {
+    CMdEObject* object = GetObjectL(aObjectDef, aId, 0, 0, KNullDesC, ELock, EFalse);
+
+	if( object && !object->OpenForModifications() )
+		{
+		delete object;
+		object = NULL;
+		User::Leave( KErrLocked );
+		}
+
+	return object;    
+    }
+
+CMdEObject* CMdESessionImpl::OpenObjectL( const TInt64 aGuidHigh, const TInt64 aGuidLow, CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef* namespaceDef = GetNamespaceDefL( aNamespaceDef );
+	
+	CMdEObjectDef* objectDef = namespaceDef->GetObjectDefL( KBaseObjectDefId );
+	if ( !objectDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	CMdEObject* object = GetObjectL(*objectDef, KNoId, aGuidHigh, aGuidLow, KNullDesC, ELock, EFalse);
+
+	if( object && !object->OpenForModifications() )
+		{
+		delete object;
+		object = NULL;
+		User::Leave( KErrLocked );
+		}
+
+	return object;
+	}
+
+CMdEObject* CMdESessionImpl::OpenFullObjectL( const TInt64 aGuidHigh, const TInt64 aGuidLow, CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdEObject* object = NULL;
+	
+	object = GetObjectL( aGuidHigh,  aGuidLow, aNamespaceDef );
+	
+	if( object )
+		{
+		CMdEObjectDef& objectDef = object->Def();
+		TItemId objId = object->Id();
+
+		delete object;
+		object = NULL;
+
+		object = GetObjectL( CONST_CAST( CMdEObjectDef&, objectDef ), objId, 0, 0, KNullDesC, ELock, ETrue );
+		}
+
+	return object;
+	}
+
+CMdEObject* CMdESessionImpl::OpenObjectL( const TInt64 aGuidHigh, const TInt64 aGuidLow, CMdEObjectDef& aObjectDef )
+    {
+    CMdEObject* object = GetObjectL(aObjectDef, KNoId, aGuidHigh, aGuidLow, KNullDesC, ELock, EFalse);
+
+	if( object && !object->OpenForModifications() )
+		{
+		delete object;
+		object = NULL;
+		User::Leave( KErrLocked );
+		}
+
+	return object;    
+    }
+
+EXPORT_C CMdEObject* CMdESessionImpl::GetObjectL( const TDesC& aUri, CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef* namespaceDef = aNamespaceDef;
+
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}
+
+	CMdEObjectDef* objectDef = namespaceDef->GetObjectDefL( KBaseObjectDefId );
+	if ( !objectDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	return GetObjectL(*objectDef, KNoId, 0, 0, aUri, EGet, EFalse);
+	}
+    
+CMdEObject* CMdESessionImpl::GetFullObjectL( const TDesC& aUri, CMdENamespaceDef* aNamespaceDef )
+	{
+	TMdEObject object;
+	
+	CheckObjectL( object, aUri, aNamespaceDef );
+	
+	if( object.NotPresent() || object.Removed() )
+		{
+		User::Leave( KErrNotFound );
+		}
+	
+	const CMdEObjectDef& objectDef = object.DefL();
+	TItemId objId = object.Id();
+	
+	return GetObjectL( CONST_CAST( CMdEObjectDef&, objectDef ), objId, 0, 0, KNullDesC, EGet, ETrue );
+	}
+    
+CMdEObject* CMdESessionImpl::GetObjectL( const TDesC& aUri, CMdEObjectDef& aObjectDef )
+    {
+    return GetObjectL( aObjectDef, KNoId, 0, 0, aUri, EGet, EFalse );
+    }
+
+    
+CMdEObject* CMdESessionImpl::OpenObjectL( const TDesC& aUri, CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef* namespaceDef = aNamespaceDef;
+	
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}
+
+	CMdEObjectDef* objectDef = namespaceDef->GetObjectDefL( KBaseObjectDefId );
+	if ( !objectDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	CMdEObject* object = GetObjectL(*objectDef, KNoId, 0, 0, aUri, ELock, EFalse);
+
+	if( object && !object->OpenForModifications() )
+		{
+		delete object;
+		object = NULL;
+		User::Leave( KErrLocked );
+		}
+
+	return object;
+	}
+
+CMdEObject* CMdESessionImpl::OpenFullObjectL( const TDesC& aUri, CMdENamespaceDef* aNamespaceDef )
+	{
+	TMdEObject object;
+	
+	CheckObjectL( object, aUri, aNamespaceDef );
+	
+	if( object.NotPresent() || object.Removed() )
+		{
+		User::Leave( KErrNotFound );
+		}
+	
+	const CMdEObjectDef& objectDef = object.DefL();
+	TItemId objId = object.Id();
+
+	return GetObjectL( CONST_CAST( CMdEObjectDef&, objectDef ), objId, 0, 0, KNullDesC, ELock, ETrue );
+	}
+
+CMdEObject* CMdESessionImpl::OpenObjectL( const TDesC& aUri, CMdEObjectDef& aObjectDef )
+    {
+    CMdEObject* object = GetObjectL(aObjectDef, KNoId, 0, 0, aUri, ELock, EFalse);
+
+	if( object && !object->OpenForModifications() )
+		{
+		delete object;
+		object = NULL;
+		User::Leave( KErrLocked );
+		}
+
+	return object;
+    }
+
+void CMdESessionImpl::CheckObjectL( TMdEObject& aObject, const TDesC& aUri, 
+		CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef& namespaceDef = *GetNamespaceDefL( aNamespaceDef );
+	
+	CMdCSerializationBuffer* object = 
+		CMdCSerializationBuffer::NewLC( aObject.RequiredBufferSize() );
+
+	iSession.DoCheckObjectL( *object, aUri, namespaceDef.Id() );
+
+	object->PositionL( KNoOffset );
+	aObject.DeSerializeL( *object, namespaceDef );
+
+	CleanupStack::PopAndDestroy( object );
+	}
+
+void CMdESessionImpl::CheckObjectL( TMdEObject& aObject, TItemId aId, 
+		CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef& namespaceDef = *GetNamespaceDefL( aNamespaceDef );
+
+	CMdCSerializationBuffer* object = 
+		CMdCSerializationBuffer::NewLC( aObject.RequiredBufferSize() );
+
+	iSession.DoCheckObjectL( *object, aId, namespaceDef.Id() );
+	
+	object->PositionL( KNoOffset );
+	aObject.DeSerializeL( *object, namespaceDef );
+	
+	CleanupStack::PopAndDestroy( object );
+	}
+
+void CMdESessionImpl::CheckObjectL( RArray<TMdEObject>& aObjects, 
+		const RArray<TItemId>& aIds, CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef& namespaceDef = *GetNamespaceDefL( aNamespaceDef );
+
+	const TUint32 idCount = (TUint32)aIds.Count();
+	
+	CMdCSerializationBuffer* objects = 
+		CMdCSerializationBuffer::NewLC( 
+				CMdCSerializationBuffer::KRequiredSizeForTUint32 + 
+				TMdEObject::RequiredBufferSize() * idCount );
+
+	CMdCSerializationBuffer* ids = 
+		CMdCSerializationBuffer::NewLC( 
+				CMdCSerializationBuffer::KRequiredSizeForTUint32 + 
+				CMdCSerializationBuffer::KRequiredSizeForTItemId * idCount );
+
+	ids->InsertL( idCount );
+	for( TUint32 i = 0; i < idCount; i++ )
+		{
+		ids->InsertL( aIds[i] );
+		}
+
+	iSession.DoCheckObjectL( *objects, *ids, namespaceDef.Id() );
+
+	objects->PositionL( KNoOffset );
+
+	TUint32 objectCount = 0;
+	objects->ReceiveL( objectCount );
+
+	aObjects.ReserveL( objectCount );
+
+	for( TUint32 i = 0; i < objectCount; i++ )
+		{
+		aObjects.AppendL( TMdEObject() );
+		aObjects[i].DeSerializeL( *objects, namespaceDef );
+		}
+	
+	CleanupStack::PopAndDestroy( ids );
+	CleanupStack::PopAndDestroy( objects );
+	}
+
+CMdERelation* CMdESessionImpl::GetRelationL(TItemId aId, CMdENamespaceDef* aNamespaceDef)
+    {
+    CMdERelationQuery* query = NewRelationQueryL( *GetNamespaceDefL( aNamespaceDef ), NULL );
+    query->SetResultMode( EQueryResultModeItem );
+    CleanupStack::PushL( query );
+
+    query->Conditions().AddRelationConditionL( aId );
+
+	CMdEQueryCriteriaSerialization* buf = CMdEQueryCriteriaSerialization::NewLC( 
+											   query->ResultMode(),
+											   query->Type(), 
+    										   query->NamespaceDef(), 
+    										   NULL, 
+    										   NULL, 
+    										   1, //Max 1  
+    										   0, // 0 offset because it's not used now
+    										   EContainsRelationCondition, 
+    										   query->Conditions(), 
+    										   query->OrderRules(),
+    										   NULL);
+
+
+	CMdCSerializationBuffer* resbuf = iSession.DoFindSyncLC(
+		query, 
+		*buf, EGet, 
+		KMdEQueryDefaultMaxCount);
+
+	RPointerArray<CMdEInstanceItem> items;
+	CleanupClosePushL( items );
+
+	DeserializeQueryResultL( *resbuf, items );
+
+	CleanupStack::Pop( &items );
+
+   	CleanupStack::PopAndDestroy(resbuf);
+	CleanupStack::PopAndDestroy( buf );
+	CleanupStack::PopAndDestroy( query );
+
+	const TInt itemsCount( items.Count() );
+	if( itemsCount== 1 )
+		{
+		CMdEInstanceItem* item = items[0];
+
+#ifdef _DEBUG
+		if ( !item || item->InstanceType() != EMdETypeRelation )
+			{
+			User::Leave( KErrCorrupt );
+			}
+#endif	
+		
+		items.Close();
+			
+		return (CMdERelation*)item;
+		}
+   	else if( itemsCount == 0 )
+   		{
+   		items.Close();
+   		return NULL;
+   		}
+#ifdef _DEBUG
+   	else
+   		{
+   		items.ResetAndDestroy();
+   		items.Close();
+   		
+   		User::Leave( KErrCorrupt );
+   		}
+#endif
+
+   	return NULL; // <-- just to stop compile warnings!!
+    }
+
+CMdEEvent* CMdESessionImpl::GetEventL(TItemId aId, 
+		CMdENamespaceDef* aNamespaceDef)
+    {
+	CMdENamespaceDef* namespaceDef = aNamespaceDef;
+	
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}
+    
+	CMdEEventQuery * query = NewEventQueryL(*namespaceDef,NULL);
+    query->SetResultMode(EQueryResultModeItem);
+    CleanupStack::PushL(query);
+
+	query->Conditions().AddEventConditionL(aId);
+	
+	CMdEQueryCriteriaSerialization* buf = CMdEQueryCriteriaSerialization::NewLC( 
+											   query->ResultMode(),
+											   query->Type(), 
+    										   query->NamespaceDef(), 
+    										   NULL, 
+    										   NULL, 
+    										   1, //Max 1  
+    										   0, // 0 offset because it's not used now
+    										   EContainsEventCondition,
+    										   query->Conditions(), 
+    										   query->OrderRules(),
+    										   NULL);    
+
+	CMdCSerializationBuffer* resbuf = iSession.DoFindSyncLC(
+			query, 
+			*buf, EGet,
+			KMdEQueryDefaultMaxCount);
+
+	RPointerArray<CMdEInstanceItem> items;
+	CleanupClosePushL( items );
+
+	DeserializeQueryResultL( *resbuf, items );
+
+	CleanupStack::Pop( &items );
+
+   	CleanupStack::PopAndDestroy(resbuf);
+	CleanupStack::PopAndDestroy( buf );
+	CleanupStack::PopAndDestroy( query );
+
+	const TInt itemsCount( items.Count() );
+	if( itemsCount == 1 )
+		{
+		CMdEInstanceItem* item = items[0];
+		
+#ifdef _DEBUG
+		if ( !item || item->InstanceType() != EMdETypeEvent )
+			{
+			User::Leave( KErrCorrupt );
+			}
+#endif
+		
+		items.Close();
+			
+		return (CMdEEvent*)item;
+		}
+   	else if( itemsCount == 0 )
+   		{
+   		items.Close();
+   		
+   		return NULL;
+   		}
+#ifdef _DEBUG
+	else
+   		{
+   		items.ResetAndDestroy();
+   		items.Close();
+   		
+   		User::Leave( KErrCorrupt );
+   		}
+#endif
+	
+	return NULL; // <-- just to stop compile warnings!!
+    }
+
+/**
+* Remove methods
+*/
+CMdCSerializationBuffer* CMdESessionImpl::RemoveCommonL( 
+		CMdENamespaceDef& aNamespaceDef, const RArray<TItemId>* aObjects,
+		const RArray<TItemId>* aEvents, const RArray<TItemId>* aRelations )
+	{
+	if ( !( (aObjects && aObjects->Count()) || 
+			(aEvents && aEvents->Count()) || 
+			(aRelations && aRelations->Count()) ) )
+		{
+		User::Leave( KErrArgument );
+		}
+
+	TMdCItemIds itemIds;
+	itemIds.iNamespaceDefId = aNamespaceDef.Id();
+	itemIds.iObjectUris.iPtr.iCount = 0;
+	itemIds.iObjectUris.iPtr.iOffset = KNoOffset;
+
+	// headerSize
+	TUint32 bufferSize = sizeof(TMdCItemIds);
+	
+	if ( aObjects )
+		{
+		bufferSize += aObjects->Count() * CMdCSerializationBuffer::KRequiredSizeForTItemId;
+		}
+	if ( aEvents )
+		{
+		bufferSize += aEvents->Count() * CMdCSerializationBuffer::KRequiredSizeForTItemId;
+		}
+	if ( aRelations )
+		{
+		bufferSize += aRelations->Count() * CMdCSerializationBuffer::KRequiredSizeForTItemId;
+		}
+
+	CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( bufferSize );
+
+	buffer->PositionL( sizeof(TMdCItemIds) );
+
+	// insert objects
+	if ( aObjects )
+		{
+		const TInt count = aObjects->Count();
+		itemIds.iObjectIds.iPtr.iCount = count;
+		itemIds.iObjectIds.iPtr.iOffset = buffer->Position();
+
+		for ( TInt i = 0; i < count; ++i )
+			{
+			buffer->InsertL( (*aObjects)[i] );
+			}
+		}
+	else
+		{
+		itemIds.iObjectIds.iPtr.iCount = 0;
+		itemIds.iObjectIds.iPtr.iOffset = KNoOffset;
+		}
+	
+	// insert events
+	if ( aEvents )
+		{
+		const TInt count = aEvents->Count();
+		itemIds.iEventIds.iPtr.iCount = count;
+		itemIds.iEventIds.iPtr.iOffset = buffer->Position();
+		
+		for ( TInt i = 0; i < count; ++i )
+			{
+			buffer->InsertL( (*aEvents)[i] );
+			}
+		}
+	else
+		{
+		itemIds.iEventIds.iPtr.iCount = 0;
+		itemIds.iEventIds.iPtr.iOffset = KNoOffset;
+		}
+
+	// insert relations
+	if ( aRelations )
+		{
+		const TInt count = aRelations->Count();
+		itemIds.iRelationIds.iPtr.iCount = count;
+		itemIds.iRelationIds.iPtr.iOffset = buffer->Position();
+		
+		for ( TInt i = 0; i < count; ++i )
+			{
+			buffer->InsertL( (*aRelations)[i] );
+			}
+		}
+	else
+		{
+		itemIds.iRelationIds.iPtr.iCount = 0;
+		itemIds.iRelationIds.iPtr.iOffset = KNoOffset;
+		}
+
+	// set up header correctly
+	buffer->PositionL( KNoOffset );
+	itemIds.SerializeL( *buffer );
+
+	CleanupStack::Pop( buffer );
+	return buffer;
+	}
+
+CMdCSerializationBuffer* CMdESessionImpl::RemoveCommonL( 
+		CMdENamespaceDef& aNamespaceDef, 
+		const RPointerArray<TDesC16>* aObjects,
+		const RArray<TItemId>* aEvents, const RArray<TItemId>* aRelations )
+	{
+	if ( !( (aObjects && aObjects->Count()) || 
+			(aEvents && aEvents->Count()) || 
+			(aRelations && aRelations->Count()) ) )
+		{
+		User::Leave( KErrArgument );
+		}
+
+	TMdCItemIds itemIds;
+	itemIds.iNamespaceDefId = aNamespaceDef.Id();
+	itemIds.iObjectIds.iPtr.iCount = 0;
+	itemIds.iObjectIds.iPtr.iOffset = KNoOffset;
+
+	// headerSize
+	TUint32 bufferSize = sizeof(TMdCItemIds);
+
+	if ( aObjects )
+		{
+		const TInt count = aObjects->Count();
+		for ( TInt i = 0; i < count; ++i )
+			{
+			bufferSize += CMdCSerializationBuffer::RequiredSize( *((*aObjects)[i]) );
+			}
+		}
+	if ( aEvents )
+		{
+		bufferSize += aEvents->Count() * CMdCSerializationBuffer::KRequiredSizeForTItemId;
+		}
+	if ( aRelations )
+		{
+		bufferSize += aRelations->Count() * CMdCSerializationBuffer::KRequiredSizeForTItemId;
+		}
+
+	CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( bufferSize );
+
+	buffer->PositionL( sizeof(TMdCItemIds) );
+
+	// insert objects
+	if ( aObjects )
+		{
+		const TInt count = aObjects->Count();
+		itemIds.iObjectUris.iPtr.iCount = count;
+		itemIds.iObjectUris.iPtr.iOffset = buffer->Position();
+
+		for ( TInt i = 0; i < count; ++i )
+			{
+			const TDesC& uri = *((*aObjects)[i]);
+			HBufC* lcUri = HBufC::NewLC( uri.Length() );
+			lcUri->Des().CopyLC( uri );
+			buffer->InsertL( *lcUri );
+			CleanupStack::PopAndDestroy( lcUri );
+			}
+		}
+	else
+		{
+		itemIds.iObjectUris.iPtr.iCount = 0;
+		itemIds.iObjectUris.iPtr.iOffset = KNoOffset;
+		}
+	
+	// insert events
+	if ( aEvents )
+		{
+		const TInt count = aEvents->Count();
+		itemIds.iEventIds.iPtr.iCount = count;
+		itemIds.iEventIds.iPtr.iOffset = buffer->Position();
+		
+		for ( TInt i = 0; i < count; ++i )
+			{
+			buffer->InsertL( (*aEvents)[i] );
+			}
+		}
+	else
+		{
+		itemIds.iEventIds.iPtr.iCount = 0;
+		itemIds.iEventIds.iPtr.iOffset = KNoOffset;
+		}
+
+	// insert relations
+	if ( aRelations )
+		{
+		const TInt count = aRelations->Count();
+		itemIds.iRelationIds.iPtr.iCount = count;
+		itemIds.iRelationIds.iPtr.iOffset = buffer->Position();
+		
+		for ( TInt i = 0; i < count; ++i )
+			{
+			buffer->InsertL( (*aRelations)[i] );
+			}
+		}
+	else
+		{
+		itemIds.iRelationIds.iPtr.iCount = 0;
+		itemIds.iRelationIds.iPtr.iOffset = KNoOffset;
+		}
+
+	// set up header correctly
+	buffer->PositionL( KNoOffset );
+	itemIds.SerializeL( *buffer );
+
+	CleanupStack::Pop( buffer );
+	return buffer;
+	}
+
+TInt CMdESessionImpl::DeserializeIdsL( RMdEDataBuffer& aSerializedItemIds, 
+		RArray<TItemId>* aResultObjects, RArray<TItemId>* aResultEvents, 
+		RArray<TItemId>* aResultRelations )
+	{
+	CMdCSerializationBuffer* buffer = aSerializedItemIds.GetBufferLC();
+	
+	const TMdCItemIds& itemIds = TMdCItemIds::GetFromBufferL( *buffer );
+
+    if ( itemIds.iObjectIds.iPtr.iCount > 0 && aResultObjects )
+    	{
+    	buffer->PositionL( itemIds.iObjectIds.iPtr.iOffset );
+    	TItemId objectId;
+    	aResultObjects->ReserveL( itemIds.iObjectIds.iPtr.iCount );
+    	for (TUint32 i = 0; i < itemIds.iObjectIds.iPtr.iCount; ++i)
+    		{
+    		buffer->ReceiveL( objectId );
+    		aResultObjects->AppendL( objectId );
+    		}
+    	}
+
+    if ( itemIds.iEventIds.iPtr.iCount > 0 && aResultEvents )
+    	{
+    	buffer->PositionL( itemIds.iEventIds.iPtr.iOffset );
+    	TItemId eventId;
+    	aResultEvents->ReserveL( itemIds.iEventIds.iPtr.iCount );
+    	for (TUint32 i = 0; i < itemIds.iEventIds.iPtr.iCount; ++i)
+    		{
+    		buffer->ReceiveL( eventId );
+    		aResultEvents->AppendL( eventId );
+    		}
+    	}
+
+    if ( itemIds.iRelationIds.iPtr.iCount > 0 && aResultRelations )
+    	{
+    	buffer->PositionL( itemIds.iRelationIds.iPtr.iOffset );
+    	TItemId relationId;
+    	aResultRelations->ReserveL( itemIds.iRelationIds.iPtr.iCount );
+    	for (TUint32 i = 0; i < itemIds.iRelationIds.iPtr.iCount; ++i)
+    		{
+    		buffer->ReceiveL( relationId );
+    		aResultRelations->AppendL( relationId );
+    		}
+    	}
+    
+    const TInt errorCode = itemIds.iErrorCode;
+    CleanupStack::PopAndDestroy( buffer );
+    
+    return errorCode;
+	}
+
+TItemId CMdESessionImpl::RemoveObjectL( TItemId aId, 
+		CMdENamespaceDef* aNamespaceDef )
+    {
+	CMdENamespaceDef* namespaceDef = aNamespaceDef;
+
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}    
+
+	RArray<TItemId> removeIdArray;
+	CleanupClosePushL( removeIdArray );
+	RArray<TItemId> resultObjectArray;
+	CleanupClosePushL( resultObjectArray );
+	removeIdArray.AppendL( aId );
+	User::LeaveIfError( RemoveObjectsL( removeIdArray, resultObjectArray, 
+			namespaceDef ) );
+	TItemId result = KNoId;
+	if ( resultObjectArray.Count() )
+		{
+		result = resultObjectArray[0];
+		}
+	CleanupStack::PopAndDestroy( 2, &removeIdArray ); // resultObjectArray, removeIdArray
+	return result;
+    }
+
+TItemId CMdESessionImpl::RemoveObjectL( const TDesC& aUri, 
+		CMdENamespaceDef* aNamespaceDef )
+    {
+	CMdENamespaceDef* namespaceDef = aNamespaceDef;
+
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}
+
+	RPointerArray<TDesC16> removeUriArray;
+	CleanupClosePushL( removeUriArray );
+	RArray<TItemId> resultObjectArray;
+	CleanupClosePushL( resultObjectArray );
+	removeUriArray.AppendL( &aUri );
+	User::LeaveIfError( RemoveObjectsL( removeUriArray, resultObjectArray, 
+			namespaceDef ) );
+	TItemId result = KNoId;
+	if ( resultObjectArray.Count() )
+		{
+		result = resultObjectArray[0];
+		}
+	CleanupStack::PopAndDestroy( 2, &removeUriArray ); // resultObjectArray, removeUriArray
+	return result;
+    }
+
+TInt CMdESessionImpl::RemoveObjectsL( const RArray<TItemId>& aId, 
+		RArray<TItemId>& aResult, CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef* namespaceDef = aNamespaceDef;
+	
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}
+
+	CMdCSerializationBuffer* buffer = RemoveCommonL( *namespaceDef, &aId, 
+			NULL, NULL  );
+	CleanupStack::PushL( buffer );
+	CMdCSerializationBuffer* resultBuffer = CMdCSerializationBuffer::NewLC( 
+			buffer->Size() );
+	RMdEDataBuffer dataBuffer;
+	dataBuffer.SetBufferL( resultBuffer );
+	CleanupStack::Pop( resultBuffer );
+	CleanupClosePushL( dataBuffer );
+	
+    iSession.DoRemoveItemsL( *buffer, *resultBuffer );
+    TInt32 firstItemError = DeserializeIdsL( dataBuffer, &aResult );
+    CleanupStack::PopAndDestroy( 2, buffer ); // successfulBuffer, buffer
+    return firstItemError;
+	}
+
+TInt CMdESessionImpl::RemoveObjectsL( const RPointerArray<TDesC>& aUri, 
+		RArray<TItemId>& aResult, CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef* namespaceDef = aNamespaceDef;
+	
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}    
+
+	CMdCSerializationBuffer* buffer = RemoveCommonL( *namespaceDef, &aUri, NULL, NULL  );
+	CleanupStack::PushL( buffer );
+    const TUint32 rbs = sizeof( TMdCItemIds )
+                        + ( aUri.Count() + 2 ) * CMdCSerializationBuffer::KRequiredSizeForTItemId;
+
+	CMdCSerializationBuffer* resultBuffer = CMdCSerializationBuffer::NewLC( rbs );
+	RMdEDataBuffer dataBuffer;
+	dataBuffer.SetBufferL( resultBuffer );
+	CleanupStack::Pop( resultBuffer );
+	CleanupClosePushL( dataBuffer );
+	
+    iSession.DoRemoveItemsL( *buffer, *resultBuffer );
+    TInt32 firstItemError = DeserializeIdsL( dataBuffer, &aResult );
+    CleanupStack::PopAndDestroy( &dataBuffer );
+    CleanupStack::PopAndDestroy( buffer );
+    return firstItemError;
+	}
+
+void CMdESessionImpl::RemoveObjectsAsyncL( 
+		const RArray<TItemId>& aId, TRequestStatus& aStatus, 
+		RMdEDataBuffer& aSerializedObjectIds, 
+		CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef* namespaceDef = aNamespaceDef;
+
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}
+
+	CMdCSerializationBuffer* buffer = RemoveCommonL( *namespaceDef, &aId, 
+			NULL, NULL  );
+	CleanupStack::PushL( buffer );
+	CMdCSerializationBuffer* resultBuffer = CMdCSerializationBuffer::NewLC( 
+			buffer->Size() );
+	aSerializedObjectIds.SetBufferL( resultBuffer );
+    CleanupStack::Pop( resultBuffer );
+	
+    CleanupStack::Pop( buffer );
+
+    iAsyncHandler->RemoveRequest( buffer, *resultBuffer, aStatus );
+	}
+	
+void CMdESessionImpl::RemoveObjectsAsyncL( 
+		const RPointerArray<TDesC>& aUri, TRequestStatus& aStatus, 
+		RMdEDataBuffer& aSerializedObjectIds, 
+		CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef* namespaceDef = aNamespaceDef;
+	
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}    
+
+	CMdCSerializationBuffer* buffer = RemoveCommonL( *namespaceDef, &aUri, 
+			NULL, NULL  );
+	CleanupStack::PushL( buffer );
+    const TUint32 rbs = sizeof( TMdCItemIds )
+                        + ( aUri.Count() + 2 ) * CMdCSerializationBuffer::KRequiredSizeForTItemId;
+
+	CMdCSerializationBuffer* resultBuffer = CMdCSerializationBuffer::NewLC( rbs );
+	aSerializedObjectIds.SetBufferL( resultBuffer );
+	CleanupStack::Pop( resultBuffer );
+	CleanupStack::Pop( buffer );
+
+    iAsyncHandler->RemoveRequest( buffer, *resultBuffer, aStatus );
+	}
+
+TItemId CMdESessionImpl::RemoveRelationL(TItemId aId, 
+		CMdENamespaceDef* aNamespaceDef)
+    {
+    RArray<TItemId> items;
+    CleanupClosePushL( items );
+    RArray<TItemId> successful;
+    CleanupClosePushL( successful );
+
+    items.AppendL( aId );
+    User::LeaveIfError( RemoveRelationsL( items, successful, aNamespaceDef ) );
+
+    TItemId result = KNoId;
+    if ( successful.Count() )
+    	{
+    	result = successful[0];
+    	}
+    CleanupStack::PopAndDestroy( 2, &items );
+    return result;
+    }
+
+TInt CMdESessionImpl::RemoveRelationsL(const RArray<TItemId>& aId, 
+		RArray<TItemId>& aSuccessful, CMdENamespaceDef* aNamespaceDef)
+	{
+	CMdENamespaceDef* namespaceDef = aNamespaceDef;
+
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}
+
+	CMdCSerializationBuffer* buffer = RemoveCommonL( *namespaceDef, 
+			(RArray<TItemId>*)NULL, NULL, &aId  );
+	CleanupStack::PushL( buffer );
+	CMdCSerializationBuffer* successfulBuffer = CMdCSerializationBuffer::NewLC(
+			buffer->Size() );
+    iSession.DoRemoveItemsL( *buffer, *successfulBuffer );
+    
+	RMdEDataBuffer dataBuffer;
+	dataBuffer.SetBufferL( successfulBuffer );
+	CleanupStack::Pop( successfulBuffer );
+	CleanupClosePushL( dataBuffer );
+    
+    TInt firstItemError = DeserializeIdsL( dataBuffer, NULL, NULL, 
+    		&aSuccessful );
+    CleanupStack::PopAndDestroy( &dataBuffer ); // successfulBuffer, buffer
+    CleanupStack::PopAndDestroy( buffer ); // successfulBuffer, buffer
+    return firstItemError;
+	}
+
+void CMdESessionImpl::RemoveRelationsAsyncL(
+		const RArray<TItemId>& aId, TRequestStatus& aStatus, 
+		RMdEDataBuffer& aSerializedRelationIds, 
+		CMdENamespaceDef* aNamespaceDef)
+	{
+	CMdENamespaceDef* namespaceDef = aNamespaceDef;
+
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}
+
+	CMdCSerializationBuffer* buffer = RemoveCommonL( *namespaceDef, 
+			(RArray<TItemId>*)NULL, NULL, &aId  );
+	CleanupStack::PushL( buffer );
+	CMdCSerializationBuffer* resultBuffer = CMdCSerializationBuffer::NewLC( 
+			buffer->Size() );
+	aSerializedRelationIds.SetBufferL( resultBuffer );
+    CleanupStack::Pop( resultBuffer );    
+    CleanupStack::Pop( buffer );
+
+    iAsyncHandler->RemoveRequest( buffer, *resultBuffer, aStatus );    
+	}
+
+/**
+* Add methods
+*/
+TItemId CMdESessionImpl::AddItemL( CMdEInstanceItem& aItem )
+	{
+	RPointerArray<CMdEInstanceItem> items;
+	CleanupClosePushL( items );
+	items.Append( &aItem );
+	User::LeaveIfError( AddItemsL( items ) );
+	CleanupStack::PopAndDestroy( &items );
+	return aItem.Id();
+	}
+
+CMdCSerializationBuffer* CMdESessionImpl::SerializeItemsL( 
+		RPointerArray<CMdEInstanceItem>& aItems )
+    {
+    const TInt itemsCount = aItems.Count();
+	if ( itemsCount == 0 )
+		{
+		User::Leave(KErrArgument);
+		return NULL;
+		}
+
+    TInt requiredBufferSize = sizeof(TMdCItems);
+
+	// counting items and required buffer size
+    TMdCItems items;
+    items.iNamespaceDefId = KNoDefId;
+    items.iErrorCode = KErrNone;
+    items.iObjects.iPtr.iCount = 0;
+    items.iObjects.iPtr.iOffset = 0;
+    items.iRelations.iPtr.iCount = 0;
+    items.iRelations.iPtr.iOffset = 0;
+    items.iEvents.iPtr.iCount = 0;
+    items.iEvents.iPtr.iOffset = 0;
+
+    for ( TInt i = 0; i < itemsCount; ++i )
+		{
+        switch (aItems[i]->InstanceType())
+        	{
+			case EMdETypeObject:
+	        	{
+	            requiredBufferSize += static_cast<CMdEObject*>(aItems[i])->RequiredBufferSize();
+				++items.iObjects.iPtr.iCount;
+				const TDefId nmspId = static_cast<CMdEObject*>(aItems[i])->Def().NamespaceDef().Id();
+				if (items.iNamespaceDefId == KNoDefId)
+					{
+					items.iNamespaceDefId = nmspId;
+					}
+				else if ( items.iNamespaceDefId != nmspId )
+					{
+					User::Leave(KErrArgument);
+					}
+	            break;
+	            }
+	        case EMdETypeRelation:
+	        	{
+	            requiredBufferSize += static_cast<CMdERelation*>(aItems[i])->RequiredBufferSize();
+				++items.iRelations.iPtr.iCount;
+				const TDefId nmspId = static_cast<CMdERelation*>(aItems[i])->Def().NamespaceDef().Id();
+				if (items.iNamespaceDefId == KNoDefId)
+					{
+					items.iNamespaceDefId = nmspId;
+					}
+				else if ( items.iNamespaceDefId != nmspId )
+					{
+					User::Leave(KErrArgument);
+					}
+	            break;
+	            }
+	        case EMdETypeEvent:
+	        	{
+	            requiredBufferSize += static_cast<CMdEEvent*>(aItems[i])->RequiredBufferSize();
+				++items.iEvents.iPtr.iCount;
+				const TDefId nmspId = static_cast<CMdEEvent*>(aItems[i])->Def().NamespaceDef().Id();
+				if (items.iNamespaceDefId == KNoDefId)
+					{
+					items.iNamespaceDefId = nmspId;
+					}
+				else if ( items.iNamespaceDefId != nmspId )
+					{
+					User::Leave(KErrArgument);
+					}
+	            break;
+	            }
+	        default:
+	        	{
+	        	User::Leave(KErrArgument);
+	        	}
+        	}
+		}
+
+	CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( requiredBufferSize );
+
+    // move after main header
+	TMdCOffset freespaceOffset = sizeof( TMdCItems );
+
+	if (items.iObjects.iPtr.iCount)
+		{
+		// add objects header
+		items.iObjects.iPtr.iOffset = freespaceOffset;
+		freespaceOffset += items.iObjects.iPtr.iCount * sizeof( TMdCObject );
+		}
+	if (items.iEvents.iPtr.iCount)
+		{
+		// add events header
+		items.iEvents.iPtr.iOffset = freespaceOffset;
+		freespaceOffset += items.iEvents.iPtr.iCount * sizeof( TMdCEvent );
+		}
+	if (items.iRelations.iPtr.iCount)
+		{
+		// add relations header
+		items.iRelations.iPtr.iOffset = freespaceOffset;
+		freespaceOffset += items.iRelations.iPtr.iCount * sizeof( TMdCRelation );
+		}
+
+	TUint32 objectCtr = 0;
+    TUint32 relationCtr = 0;
+    TUint32 eventCtr = 0;
+	for ( TInt i = 0; i < itemsCount; ++i )
+		{
+        const TUint32 actualPosition = buffer->Position();
+        switch (aItems[i]->InstanceType())
+        	{
+			case EMdETypeObject:
+	        	{
+	            CMdEObject* object = static_cast<CMdEObject*>(aItems[i]);
+	            // set right offset
+	            buffer->PositionL( items.iObjects.iPtr.iOffset + objectCtr * sizeof(TMdCObject) );
+	            freespaceOffset = object->SerializeL( *buffer, freespaceOffset );
+	            ++objectCtr;
+	            break;
+	            }
+	        case EMdETypeRelation:
+	        	{
+	            CMdERelation* relation = static_cast<CMdERelation*>(aItems[i]);
+	            // set right offset
+	            buffer->PositionL( items.iRelations.iPtr.iOffset + relationCtr * sizeof(TMdCRelation) );
+	            freespaceOffset = relation->SerializeL( *buffer, freespaceOffset );
+	            ++relationCtr;
+	            break;
+	            }
+	        case EMdETypeEvent:
+	        	{
+	            CMdEEvent* event = static_cast<CMdEEvent*>(aItems[i]);
+	            // set right offset
+	            buffer->PositionL( items.iEvents.iPtr.iOffset + eventCtr * sizeof(TMdCEvent) );
+	            freespaceOffset = event->SerializeL( *buffer, freespaceOffset );
+	            ++eventCtr;
+				break;
+	            }
+	        default:
+	        	{
+	        	User::Leave(KErrArgument);
+	        	}
+        	}
+		}
+
+    // insert namespaceid
+	buffer->PositionL( KNoOffset );
+	items.SerializeL( *buffer );
+
+    CleanupStack::Pop( buffer );
+    return buffer;
+    }
+
+void CMdESessionImpl::DeserializeQueryResultL( 
+		CMdCSerializationBuffer& aBuffer, 
+		RPointerArray<CMdEInstanceItem>& aItems )
+	{
+	const TMdCItems& items = TMdCItems::GetFromBufferL( aBuffer );
+
+    CMdENamespaceDef& namespaceDef = GetNamespaceDefL( items.iNamespaceDefId );
+
+    aItems.ReserveL( items.iObjects.iPtr.iCount + items.iEvents.iPtr.iCount 
+    		+ items.iRelations.iPtr.iCount );
+    
+	if ( items.iObjects.iPtr.iCount > 0 )
+		{
+		for ( TUint32 i = 0; i < items.iObjects.iPtr.iCount; ++i )
+			{
+			aBuffer.PositionL( items.iObjects.iPtr.iOffset + i * sizeof(TMdCObject) );
+			CMdEObject* object = CMdEObject::NewLC( this, aBuffer, 
+					namespaceDef );
+			aItems.AppendL( object );
+			CleanupStack::Pop( object );
+			}
+		}
+		
+	if ( items.iEvents.iPtr.iCount > 0 )
+		{
+		for ( TUint32 i = 0; i < items.iEvents.iPtr.iCount; ++i )
+			{
+			aBuffer.PositionL( items.iEvents.iPtr.iOffset + i * sizeof(TMdCEvent) );
+			CMdEEvent* event = CMdEEvent::NewLC( this, aBuffer, namespaceDef );
+			aItems.AppendL( event );
+			CleanupStack::Pop( event );
+			}
+		}
+
+	if ( items.iRelations.iPtr.iCount > 0 )
+		{
+		for ( TUint32 i = 0; i < items.iRelations.iPtr.iCount; ++i )
+			{
+			aBuffer.PositionL( items.iRelations.iPtr.iOffset + i * sizeof(TMdCRelation) );
+			CMdERelation* relation = CMdERelation::NewLC( this, aBuffer, 
+					namespaceDef );
+			aItems.AppendL( relation );
+			CleanupStack::Pop( relation );
+			}
+		}
+	}
+
+TItemId CMdESessionImpl::AddObjectL( CMdEObject& aObject )
+    {
+    AddItemL(aObject);
+    return aObject.Id();
+    }
+
+TInt CMdESessionImpl::AddObjectsL( RPointerArray<CMdEObject>& aObjects )
+    {
+    const TInt firstObjectError = AddItemsL( 
+    		(RPointerArray<CMdEInstanceItem>&)aObjects );
+
+    return firstObjectError;
+    }
+
+TItemId CMdESessionImpl::AddRelationL( CMdERelation& aRelation ) 
+    {
+	return AddItemL( aRelation );
+    }
+
+TItemId CMdESessionImpl::UpdateRelationL( CMdERelation& aRelation ) 
+    {
+	RPointerArray<CMdEInstanceItem> items;
+	CleanupClosePushL( items );
+	items.Append( &aRelation );
+	User::LeaveIfError( UpdateItemsL( items ) );
+	CleanupStack::PopAndDestroy( &items );
+	return aRelation.Id();
+    }
+
+TInt CMdESessionImpl::AddItemsL( RPointerArray<CMdEInstanceItem>& aItems )
+    {    
+    CMdCSerializationBuffer *buffer = SerializeItemsL( aItems );
+    CleanupStack::PushL( buffer );
+    CMdCSerializationBuffer* resultBuf = CMdCSerializationBuffer::NewLC( 
+    		+ sizeof(TMdCItemIds)
+    		+ aItems.Count() * CMdCSerializationBuffer::KRequiredSizeForTItemId );
+	RMdEDataBuffer dataBuffer;
+	dataBuffer.SetBufferL( resultBuf );
+	CleanupStack::Pop( resultBuf );
+	CleanupClosePushL( dataBuffer );    
+    
+    iSession.DoAddItemsL( *buffer, *resultBuf );
+    
+	const TInt firstItemError = DeserializeItemsL( dataBuffer, aItems );
+
+	CleanupStack::PopAndDestroy( &dataBuffer );
+    CleanupStack::PopAndDestroy( buffer );
+    
+    return firstItemError;
+    }
+
+void CMdESessionImpl::AddItemsAsyncL( 
+		RPointerArray<CMdEInstanceItem>& aItems, TRequestStatus& aStatus, 
+		RMdEDataBuffer& aSerializedItemIds )
+    {    
+    CMdCSerializationBuffer* buffer = SerializeItemsL( aItems );
+    CleanupStack::PushL( buffer );
+
+    CMdCSerializationBuffer* resultBuf = CMdCSerializationBuffer::NewLC( 
+    		+ sizeof(TMdCItemIds)
+    		+ aItems.Count() * CMdCSerializationBuffer::KRequiredSizeForTItemId );
+    aSerializedItemIds.SetBufferL( resultBuf );
+    CleanupStack::Pop( resultBuf );    
+    CleanupStack::Pop( buffer );
+
+    iAsyncHandler->AddRequest( buffer, *resultBuf, aStatus );
+    }
+
+TInt CMdESessionImpl::UpdateItemsL( RPointerArray<CMdEInstanceItem>& aItems )
+    {    
+    CMdCSerializationBuffer *buffer = SerializeItemsL( aItems );
+    CleanupStack::PushL( buffer );
+
+    CMdCSerializationBuffer* resultBuf = CMdCSerializationBuffer::NewLC( 
+    		+ sizeof(TMdCItemIds)
+    		+ aItems.Count() * CMdCSerializationBuffer::KRequiredSizeForTItemId );
+
+	RMdEDataBuffer dataBuffer;
+	dataBuffer.SetBufferL( resultBuf );
+	CleanupStack::Pop( resultBuf );
+	CleanupClosePushL( dataBuffer );
+
+    iSession.DoUpdateItemsL( *buffer, *resultBuf );
+
+	TInt firstItemError = DeserializeItemsL( dataBuffer, aItems );
+
+	CleanupStack::PopAndDestroy( &dataBuffer );
+    CleanupStack::PopAndDestroy( buffer );
+    return firstItemError;
+    }      
+
+void CMdESessionImpl::UpdateItemsAsyncL( 
+		RPointerArray<CMdEInstanceItem>& aItems, TRequestStatus& aStatus,
+		RMdEDataBuffer& aSerializedItemIds )
+    {
+    CMdCSerializationBuffer *buffer = SerializeItemsL( aItems );
+    CleanupStack::PushL( buffer );
+    CMdCSerializationBuffer* resultBuf = CMdCSerializationBuffer::NewLC( 
+    		+ sizeof(TMdCItemIds)
+    		+ aItems.Count() * CMdCSerializationBuffer::KRequiredSizeForTItemId );
+    aSerializedItemIds.SetBufferL( resultBuf );
+	CleanupStack::Pop( resultBuf );
+	CleanupStack::Pop( buffer );
+
+    iAsyncHandler->UpdateRequest( buffer, *resultBuf, aStatus );
+    }
+
+TInt CMdESessionImpl::DeserializeItemsL( RMdEDataBuffer& aSerializedItems, 
+		RPointerArray<CMdEInstanceItem>& aItems )
+	{
+	CMdCSerializationBuffer* buffer = aSerializedItems.GetBufferLC();
+
+	const TMdCItemIds& itemIds = TMdCItemIds::GetFromBufferL( *buffer );
+
+    TUint32 objectsIndex = 0;
+    TUint32 eventsIndex = 0;
+    TUint32 relationsIndex = 0;
+    TItemId id = 0;
+
+    const TInt count = aItems.Count();
+    
+    if ( count != itemIds.iObjectIds.iPtr.iCount
+    		+ itemIds.iRelationIds.iPtr.iCount + itemIds.iEventIds.iPtr.iCount )
+    	{
+    	User::Leave( KErrArgument );
+    	}
+
+    for ( TInt i = 0; i < count; ++i )
+    	{
+    	switch ( aItems[i]->InstanceType() )
+    		{
+    		case EMdETypeObject:
+    			buffer->PositionL( itemIds.iObjectIds.iPtr.iOffset
+				        + objectsIndex * CMdCSerializationBuffer::KRequiredSizeForTItemId );
+				buffer->ReceiveL( id );
+				aItems[i]->SetId( id );
+				aItems[i]->SetSession( *this );
+				static_cast<CMdEObject*>(aItems[i])->ClearObject();
+				++objectsIndex;
+    			break;
+
+    		case EMdETypeEvent:
+    			buffer->PositionL( itemIds.iEventIds.iPtr.iOffset
+    					+ eventsIndex * CMdCSerializationBuffer::KRequiredSizeForTItemId );
+				buffer->ReceiveL( id );
+				aItems[i]->SetId( id );
+				aItems[i]->SetSession( *this );
+				++eventsIndex;
+    			break;
+
+    		case EMdETypeRelation:
+    			buffer->PositionL( itemIds.iRelationIds.iPtr.iOffset
+    					+ relationsIndex * CMdCSerializationBuffer::KRequiredSizeForTItemId );
+    			buffer->ReceiveL( id );
+				aItems[i]->SetId( id );
+				aItems[i]->SetSession( *this );
+				++relationsIndex;
+    			break;
+
+    		default:
+    			User::Leave( KErrArgument );
+    			break;
+    		}
+    	}
+    
+    const TInt errorCode = itemIds.iErrorCode;
+    CleanupStack::PopAndDestroy( buffer );
+    
+    return errorCode;
+	}
+
+TItemId CMdESessionImpl::AddEventL( CMdEEvent& aEvent )
+    {
+	return AddItemL( aEvent );
+    }
+
+TItemId CMdESessionImpl::RemoveEventL( TItemId aId, 
+		CMdENamespaceDef* aNamespaceDef )
+    {
+    RArray<TItemId> items;
+    CleanupClosePushL( items );
+    RArray<TItemId> successful;
+    CleanupClosePushL( successful );
+
+    items.AppendL( aId );
+    User::LeaveIfError( RemoveEventsL( items, successful, aNamespaceDef ) );
+
+    TItemId result = KNoId;
+    if ( successful.Count() > 0 )
+    	{
+    	result = successful[0];
+    	}
+
+    CleanupStack::PopAndDestroy( &successful );
+    CleanupStack::PopAndDestroy( &items );
+
+    return result;
+    }
+
+TInt CMdESessionImpl::RemoveEventsL( const RArray<TItemId>& aId, 
+		RArray<TItemId>& aSuccessful, CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef* namespaceDef = aNamespaceDef;
+
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}
+
+	CMdCSerializationBuffer* buffer = RemoveCommonL( *namespaceDef, 
+			(RArray<TItemId>*)NULL, &aId, NULL  );
+	CleanupStack::PushL( buffer );
+	CMdCSerializationBuffer* successfulBuffer = CMdCSerializationBuffer::NewLC(
+			buffer->Size() );
+	
+	RMdEDataBuffer dataBuffer;
+	dataBuffer.SetBufferL( successfulBuffer );
+	CleanupStack::Pop( successfulBuffer );
+	CleanupClosePushL( dataBuffer );
+	
+    iSession.DoRemoveItemsL( *buffer, *successfulBuffer );
+    TInt firstItemError = DeserializeIdsL( dataBuffer, NULL, 
+    		&aSuccessful );
+
+    CleanupStack::PopAndDestroy( &dataBuffer );
+    CleanupStack::PopAndDestroy( buffer );
+    
+    return firstItemError;
+	}    
+	
+void CMdESessionImpl::RemoveEventsAsyncL( 
+		const RArray<TItemId>& aId, TRequestStatus& aStatus, 
+		RMdEDataBuffer& aSerializedEventIds, 
+		CMdENamespaceDef* aNamespaceDef )
+	{
+	CMdENamespaceDef* namespaceDef = aNamespaceDef;
+	
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}
+
+	CMdCSerializationBuffer* buffer = RemoveCommonL( *namespaceDef, 
+			(RArray<TItemId>*)NULL, &aId, NULL  );
+	CleanupStack::PushL( buffer );
+	CMdCSerializationBuffer* resultBuffer = CMdCSerializationBuffer::NewLC( 
+			buffer->Size() );
+	aSerializedEventIds.SetBufferL( resultBuffer );
+    CleanupStack::Pop( resultBuffer );    
+	
+    CleanupStack::Pop( buffer );
+
+    iAsyncHandler->RemoveRequest( buffer, *resultBuffer, aStatus );    
+	}
+	
+
+// Query 
+
+CMdEObjectQuery* CMdESessionImpl::NewObjectQueryL(
+		CMdENamespaceDef& aNamespaceDef, CMdEObjectDef& aObjectDef, 
+		MMdEQueryObserver* aObserver)
+    {
+    CMdEObjectQueryImpl* query = CMdEObjectQueryImpl::NewLC( *this, 
+    		aNamespaceDef, aObjectDef, NULL, iSession );
+    if( aObserver )
+        {
+        query->AddObserverL( *aObserver );
+        }
+    CleanupStack::Pop( query );
+
+    query->SetQueryId( iNextQueryId );
+    iNextQueryId++;
+    
+    return query;
+    }
+
+CMdEObjectQuery* CMdESessionImpl::NewObjectQueryL(
+		CMdEObjectDef& aObjectDef, RPointerArray<CMdEObjectDef>* aObjectDefs, 
+		MMdEQueryObserver* aObserver)
+	{
+	CleanupStack::PushL( aObjectDefs );
+
+	if( !aObjectDefs || ( aObjectDefs->Count() <= 0 ) )
+		{
+		User::Leave( KErrArgument );
+		}
+	
+    CMdEObjectQueryImpl* query = CMdEObjectQueryImpl::NewLC( *this, 
+    		aObjectDef.NamespaceDef(), aObjectDef, aObjectDefs, iSession );
+    if( aObserver )
+        {
+        query->AddObserverL( *aObserver );
+        }
+    CleanupStack::Pop( query );
+
+    CleanupStack::Pop( aObjectDefs );
+
+    query->SetQueryId( iNextQueryId );
+    iNextQueryId++;
+    
+    return query;
+	}
+
+CMdERelationQuery* CMdESessionImpl::NewRelationQueryL(
+		CMdENamespaceDef& aNamespaceDef, MMdEQueryObserver* aObserver)
+    {
+    CMdERelationQueryImpl* query = CMdERelationQueryImpl::NewLC( *this,
+    		aNamespaceDef, iSession );
+
+    if( aObserver )
+        {
+        query->AddObserverL( *aObserver );
+        }
+    CleanupStack::Pop( query );
+
+    query->SetQueryId( iNextQueryId );
+    iNextQueryId++;
+    
+    return query;
+    }
+
+CMdEEventQuery* CMdESessionImpl::NewEventQueryL(
+		CMdENamespaceDef& aNamespaceDef, MMdEQueryObserver* aObserver)
+    {
+    CMdEEventQueryImpl* query = CMdEEventQueryImpl::NewLC( *this,
+    		aNamespaceDef, iSession );
+
+    if( aObserver )
+        {
+        query->AddObserverL( *aObserver );
+        }
+    CleanupStack::Pop( query );
+
+    query->SetQueryId( iNextQueryId );
+    iNextQueryId++;
+    
+    return query;
+    }
+
+
+// Observer handling
+void CMdESessionImpl::AddObjectObserverL( MMdEObjectObserver& aObserver,
+    									  CMdELogicCondition* aCondition, 
+     									  TUint32 aNotificationType,
+    									  CMdENamespaceDef* aNamespaceDef )
+    {
+    CleanupStack::PushL( aCondition );
+    
+    // if condition is given, check that it is correct type
+	if( aCondition && ( EConditionTypeLogic != aCondition->Type() ) )
+		{
+		User::Leave( KErrArgument );
+		}
+
+	// if namespace is not given get default namespace definition
+    CMdENamespaceDef* namespaceDef = NULL;
+    if ( !aNamespaceDef )
+    	{
+    	namespaceDef = &GetDefaultNamespaceDefL();
+    	}
+    else
+    	{
+    	namespaceDef = aNamespaceDef;
+    	}
+
+	TUint32 type = 0;
+	if ( aNotificationType & ENotifyAdd )
+		{
+		type |= EObjectNotifyAdd;
+		}
+	if ( aNotificationType & ENotifyModify )
+		{
+		type |= EObjectNotifyModify;
+		}
+	if ( aNotificationType & ENotifyRemove )
+		{
+		type |= EObjectNotifyRemove;
+		}
+
+    TInt err = FindNotifier( type, &aObserver, *namespaceDef );
+    
+    if ( err != KErrNotFound )
+    	{
+    	if ( err >= 0 )
+    		{
+    		err = KErrAlreadyExists;
+    		}
+    	User::LeaveIfError( err );
+    	}
+
+    CMdENotifierAO* notifier = CMdENotifierAO::NewLC( *this, iSession );
+    notifier->RegisterL( type, &aObserver, aCondition, *namespaceDef );
+
+    CleanupStack::Pop( notifier );
+    iNotifiers.Append( notifier );
+    
+    CleanupStack::PopAndDestroy( aCondition );
+    }
+    
+void CMdESessionImpl::AddObjectPresentObserverL(
+		MMdEObjectPresentObserver& aObserver)
+	{
+    CMdENamespaceDef& namespaceDef = GetDefaultNamespaceDefL();
+
+    TInt err = FindNotifier( 
+    		EObjectNotifyPresent, &aObserver, namespaceDef );
+    
+    if ( err != KErrNotFound )
+    	{
+    	if ( err >= 0 )
+    		{
+    		err = KErrAlreadyExists;
+    		}
+    	User::LeaveIfError( err );
+    	}
+
+    CMdENotifierAO* notifier = CMdENotifierAO::NewLC( *this, iSession );
+    notifier->RegisterL( EObjectNotifyPresent | EObjectNotifyNotPresent,
+    		&aObserver, NULL, namespaceDef );
+
+    CleanupStack::Pop( notifier );
+    iNotifiers.Append( notifier );
+	}
+
+void CMdESessionImpl::AddRelationObserverL( MMdERelationObserver& aObserver,
+    										CMdECondition* aCondition, 
+    										TUint32 aNotificationType,
+    										CMdENamespaceDef* aNamespaceDef )
+    {
+    CleanupStack::PushL( aCondition );
+    
+    // if condition is given, check that it is correct type
+	if( aCondition && ( EConditionTypeRelation != aCondition->Type() ) )
+		{
+		User::Leave( KErrArgument );
+		}
+
+	// if namespace is not given get default namespace definition
+    CMdENamespaceDef* namespaceDef = NULL;
+    if ( !aNamespaceDef )
+    	{
+    	namespaceDef = &GetDefaultNamespaceDefL();
+    	}
+    else
+    	{
+    	namespaceDef = aNamespaceDef;
+    	}
+
+	TUint32 type = 0;
+	if ( aNotificationType & ENotifyAdd )
+		{
+		type |= ERelationNotifyAdd;
+		}
+	if ( aNotificationType & ENotifyModify )
+		{
+		type |= ERelationNotifyModify;
+		}
+	if ( aNotificationType & ENotifyRemove )
+		{
+		type |= ERelationNotifyRemove;
+		}
+
+	TInt err = FindNotifier( type, &aObserver, *namespaceDef );
+
+    if ( err != KErrNotFound )
+    	{
+    	if ( err >= 0 )
+    		{
+    		err = KErrAlreadyExists;
+    		}
+    	User::LeaveIfError( err );
+    	}
+    
+    CMdENotifierAO* notifier = CMdENotifierAO::NewLC( *this, iSession );
+    notifier->RegisterL( type, &aObserver, aCondition, *namespaceDef );
+
+    CleanupStack::Pop( notifier );
+    iNotifiers.Append( notifier );
+    
+    CleanupStack::PopAndDestroy( aCondition );
+    }
+
+void CMdESessionImpl::AddRelationItemObserverL( 
+		MMdERelationItemObserver& aObserver, CMdECondition* aCondition, 
+		TUint32 aNotificationType, CMdENamespaceDef* aNamespaceDef )
+	{
+    CleanupStack::PushL( aCondition );
+    
+	// if condition is given, check that it is correct type
+	if( aCondition && ( EConditionTypeRelation != aCondition->Type() ) )
+		{
+		User::Leave( KErrArgument );
+		}
+	
+	// if namespace is not given get default namespace definition
+	CMdENamespaceDef* namespaceDef = NULL;
+	if ( !aNamespaceDef )
+		{
+		namespaceDef = &GetDefaultNamespaceDefL();
+		}
+	else
+		{
+		namespaceDef = aNamespaceDef;
+		}
+	
+	TUint32 type = 0;
+	if ( aNotificationType & ENotifyAdd )
+		{		
+		User::Leave( KErrNotSupported );
+		}
+	if ( aNotificationType & ENotifyModify )
+		{		
+		User::Leave( KErrNotSupported );
+		}
+	if ( aNotificationType & ENotifyRemove )
+		{
+		type |= ERelationItemNotifyRemove;
+		}
+	
+	TInt err = FindNotifier( type, &aObserver, *namespaceDef );
+	
+	if ( err != KErrNotFound )
+		{
+		if ( err >= 0 )
+			{
+			err = KErrAlreadyExists;
+			}
+		User::LeaveIfError( err );
+		}
+	
+	CMdENotifierAO* notifier = CMdENotifierAO::NewLC( *this, iSession );
+	notifier->RegisterL( type, &aObserver, aCondition, *namespaceDef );
+	
+	CleanupStack::Pop( notifier );
+	iNotifiers.Append( notifier );
+	
+    CleanupStack::PopAndDestroy( aCondition );
+	}
+
+
+void CMdESessionImpl::AddRelationPresentObserverL(
+		MMdERelationPresentObserver& aObserver)
+	{
+    CMdENamespaceDef& namespaceDef = GetDefaultNamespaceDefL();
+
+    TInt err = FindNotifier( 
+    		ERelationNotifyPresent | ERelationNotifyNotPresent,
+    		&aObserver, namespaceDef );
+    
+    if ( err != KErrNotFound )
+    	{
+    	if ( err >= 0 )
+    		{
+    		err = KErrAlreadyExists;
+    		}
+    	User::LeaveIfError( err );
+    	}
+    
+    CMdENotifierAO* notifier = CMdENotifierAO::NewLC( *this, iSession );
+    notifier->RegisterL( ERelationNotifyPresent | ERelationNotifyNotPresent,
+    		&aObserver, NULL, namespaceDef );
+
+    CleanupStack::Pop( notifier );
+    iNotifiers.Append( notifier );
+	}
+
+void CMdESessionImpl::AddEventObserverL( MMdEEventObserver& aObserver,
+    									 CMdECondition* aCondition, 
+    									 TUint32 aNotificationType,
+    									 CMdENamespaceDef* aNamespaceDef )
+    {
+    CleanupStack::PushL( aCondition );
+    
+    // if condition is given, check that it is correct type
+	if( aCondition && ( EConditionTypeEvent != aCondition->Type() ) )
+		{
+		User::Leave( KErrArgument );
+		}
+
+	if ( aNotificationType & ENotifyModify )
+		{
+		User::Leave( KErrNotSupported );
+		}
+
+	// if namespace is not given get default namespace definition
+    CMdENamespaceDef* namespaceDef = NULL;
+    if ( !aNamespaceDef )
+    	{
+    	namespaceDef = &GetDefaultNamespaceDefL();
+    	}
+    else
+    	{
+    	namespaceDef = aNamespaceDef;
+    	}
+
+	TUint32 type = 0;
+	if ( aNotificationType & ENotifyAdd )
+		{
+		type |= EEventNotifyAdd;
+		}
+	if ( aNotificationType & ENotifyRemove )
+		{
+		type |= EEventNotifyRemove;
+		}
+	
+    TInt err = FindNotifier( type, &aObserver, *namespaceDef );
+    
+    if ( err != KErrNotFound )
+    	{
+    	if ( err >= 0 )
+    		{
+    		err = KErrAlreadyExists;
+    		}
+    	User::LeaveIfError( err );
+    	}
+
+    CMdENotifierAO* notifier = CMdENotifierAO::NewLC( *this, iSession );
+    notifier->RegisterL( type, &aObserver, aCondition, *namespaceDef );
+
+    CleanupStack::Pop( notifier );
+    iNotifiers.Append( notifier );
+    
+    CleanupStack::PopAndDestroy( aCondition );
+    }
+
+void CMdESessionImpl::RemoveObjectObserverL( 
+		MMdEObjectObserver& aObserver, CMdENamespaceDef* aNamespaceDef )
+    {
+	// if namespace is not given get default namespace definition
+    CMdENamespaceDef* namespaceDef = NULL;
+    if ( !aNamespaceDef )
+    	{
+    	namespaceDef = &GetDefaultNamespaceDefL();
+    	}
+    else
+    	{
+    	namespaceDef = aNamespaceDef;
+    	}
+
+    TInt index = FindNotifier( 
+    		EObjectNotifyAdd | EObjectNotifyModify | EObjectNotifyRemove,
+    		&aObserver, *namespaceDef );
+    if ( index != KErrNotFound )
+        {
+    	iNotifiers[index]->Cancel();
+    	delete iNotifiers[index];
+    	iNotifiers[index] = NULL;
+    	iNotifiers.Remove( index );
+        }
+    else
+    	{
+    	User::Leave( KErrNotFound );
+    	}
+    }
+
+void CMdESessionImpl::RemoveObjectPresentObserverL(
+		MMdEObjectPresentObserver& aObserver)
+	{
+	// if namespace is not given get default namespace definition
+    CMdENamespaceDef& namespaceDef = GetDefaultNamespaceDefL();
+
+    TInt index = FindNotifier( EObjectNotifyPresent | EObjectNotifyNotPresent,
+    		&aObserver, namespaceDef );
+    if ( index != KErrNotFound )
+        {
+    	iNotifiers[index]->Cancel();
+    	delete iNotifiers[index];
+    	iNotifiers[index] = NULL;
+    	iNotifiers.Remove( index );
+        }
+    else
+    	{
+    	User::Leave( KErrNotFound );
+    	}
+	}
+
+void CMdESessionImpl::RemoveRelationObserverL( 
+		MMdERelationObserver& aObserver, CMdENamespaceDef* aNamespaceDef )
+    {
+	// if namespace is not given get default namespace definition
+    CMdENamespaceDef* namespaceDef = NULL;
+    if ( !aNamespaceDef )
+    	{
+    	namespaceDef = &GetDefaultNamespaceDefL();
+    	}
+    else
+    	{
+    	namespaceDef = aNamespaceDef;
+    	}
+
+    TInt index = FindNotifier( 
+    		ERelationNotifyAdd | ERelationNotifyModify | ERelationNotifyRemove,
+    		&aObserver, *namespaceDef );
+    if ( index != KErrNotFound )
+        {
+    	iNotifiers[index]->Cancel();
+    	delete iNotifiers[index];
+    	iNotifiers[index] = NULL;
+    	iNotifiers.Remove( index );
+        }
+    else
+    	{
+    	User::Leave( KErrNotFound );
+    	}
+   }
+
+void CMdESessionImpl::RemoveRelationItemObserverL( 
+		MMdERelationItemObserver& aObserver, CMdENamespaceDef* aNamespaceDef )
+    {
+	// if namespace is not given get default namespace definition
+    CMdENamespaceDef* namespaceDef = NULL;
+    if ( !aNamespaceDef )
+    	{
+    	namespaceDef = &GetDefaultNamespaceDefL();
+    	}
+    else
+    	{
+    	namespaceDef = aNamespaceDef;
+    	}
+
+    TInt index = FindNotifier( 
+    		/*ERelationItemNotifyAdd | ERelationItemNotifyModify |*/ 
+    		ERelationItemNotifyRemove,
+    		&aObserver, *namespaceDef );
+    if ( index != KErrNotFound )
+        {
+    	iNotifiers[index]->Cancel();
+    	delete iNotifiers[index];
+    	iNotifiers[index] = NULL;
+    	iNotifiers.Remove( index );
+        }
+    else
+    	{
+    	User::Leave( KErrNotFound );
+    	}
+   }
+
+void CMdESessionImpl::RemoveRelationPresentObserverL(
+		MMdERelationPresentObserver& aObserver)
+	{
+	// if namespace is not given get default namespace definition
+    CMdENamespaceDef& namespaceDef = GetDefaultNamespaceDefL();
+
+    TInt index = FindNotifier( 
+    		ERelationNotifyPresent | ERelationNotifyNotPresent,
+    		&aObserver, namespaceDef );
+    if ( index != KErrNotFound )
+        {
+    	iNotifiers[index]->Cancel();
+    	delete iNotifiers[index];
+    	iNotifiers[index] = NULL;
+    	iNotifiers.Remove( index );
+        }
+    else
+    	{
+    	User::Leave( KErrNotFound );
+    	}
+	}
+
+void CMdESessionImpl::RemoveEventObserverL( 
+		MMdEEventObserver& aObserver, CMdENamespaceDef* aNamespaceDef )
+    {
+	// if namespace is not given get default namespace definition
+    CMdENamespaceDef* namespaceDef = NULL;
+    if ( !aNamespaceDef )
+    	{
+    	namespaceDef = &GetDefaultNamespaceDefL();
+    	}
+    else
+    	{
+    	namespaceDef = aNamespaceDef;
+    	}
+    
+    TInt index = FindNotifier( EEventNotifyAdd | EEventNotifyRemove,
+    		&aObserver, *namespaceDef );
+    if ( index != KErrNotFound )
+        {
+	    iNotifiers[index]->Cancel();
+	    delete iNotifiers[index];
+	    iNotifiers[index] = NULL;
+	    iNotifiers.Remove( index );
+        }
+    else
+    	{
+    	User::Leave( KErrNotFound );
+    	}
+    }
+
+TInt CMdESessionImpl::FindNotifier( TUint32 aNotifyType, TAny* aObserver, 
+									CMdENamespaceDef& aNamespaceDef )
+    {
+    const TInt notifiersCount = iNotifiers.Count();
+    for( TInt i = 0; i < notifiersCount; ++i )
+        {
+        if ( iNotifiers[i]->Match( aNotifyType, aObserver, aNamespaceDef ) )
+        	{
+        	return i;
+        	}
+        }
+    return KErrNotFound;
+    }
+
+void CMdESessionImpl::NotifierInError( CMdENotifierAO* aNotifier )
+    {
+    TInt index = iNotifiers.Find( aNotifier );
+    delete aNotifier;
+    iNotifiers.Remove( index );
+    }
+
+void CMdESessionImpl::ImportSchemaL( const TDesC& aFileName )
+    {
+    iSession.DoImportSchemaL( aFileName );
+    DoLoadSchemaL();  
+    }
+    
+TInt CMdESessionImpl::ImportMetadataL( const TDesC& aFileName )
+    {
+    return iSession.DoImportMetadataL( aFileName );
+    }
+
+void CMdESessionImpl::ImportMetadata( const TDesC& aFileName, 
+		TPckgBuf<TInt>& aResult, TRequestStatus& aStatus )
+	{
+	return iSession.DoImportMetadata( aFileName, aResult, aStatus );
+	}
+
+CMdCSerializationBuffer* CMdESessionImpl::ExportCommonL( 
+		const CMdENamespaceDef* aNamespaceDef,
+		const RPointerArray<CMdEObjectDef>* aObjectDefs,
+        const RPointerArray<CMdERelationDef>* aRelationDefs,
+        const RPointerArray<CMdEEventDef>* aEventDefs )
+	{
+	// headerSize
+	TUint32 bufferSize = sizeof(TMdCItemIds);
+	
+	TMdCItemIds itemIds;
+	if ( aNamespaceDef )
+		{
+		itemIds.iNamespaceDefId = aNamespaceDef->Id();
+		}
+	else
+		{
+		itemIds.iNamespaceDefId = KNoDefId;
+		}
+	itemIds.iObjectUris.iPtr.iCount = 0;
+	itemIds.iObjectUris.iPtr.iOffset = KNoOffset;
+	itemIds.iObjectIds.iPtr.iCount = 0;
+	itemIds.iObjectIds.iPtr.iOffset = KNoOffset;
+	itemIds.iEventIds.iPtr.iCount = 0;
+	itemIds.iEventIds.iPtr.iOffset = KNoOffset;
+	itemIds.iRelationIds.iPtr.iCount = 0;
+	itemIds.iRelationIds.iPtr.iOffset = KNoOffset;
+
+	if ( !aNamespaceDef || (!aObjectDefs && !aRelationDefs && !aEventDefs) )
+		{
+		CMdCSerializationBuffer* buffer = 
+				CMdCSerializationBuffer::NewLC( bufferSize );
+		itemIds.SerializeL( *buffer );
+		CleanupStack::Pop( buffer );
+		return buffer;
+		}
+
+	if ( aObjectDefs )
+		{
+		bufferSize += aObjectDefs->Count() * CMdCSerializationBuffer::KRequiredSizeForTItemId;
+		}
+	if ( aEventDefs )
+		{
+		bufferSize += aEventDefs->Count() * CMdCSerializationBuffer::KRequiredSizeForTItemId;
+		}
+	if ( aRelationDefs )
+		{
+		bufferSize += aRelationDefs->Count() * CMdCSerializationBuffer::KRequiredSizeForTItemId;
+		}
+
+	CMdCSerializationBuffer* buffer = 
+			CMdCSerializationBuffer::NewLC( bufferSize );
+
+	buffer->PositionL( sizeof(TMdCItemIds) );
+
+	// insert objects
+	if ( aObjectDefs )
+		{
+		itemIds.iObjectIds.iPtr.iOffset = buffer->Position();
+		itemIds.iObjectIds.iPtr.iCount = aObjectDefs->Count();
+		
+		for ( TInt i = 0; i < itemIds.iObjectIds.iPtr.iCount; ++i )
+			{
+			buffer->InsertL( (*aObjectDefs)[i]->Id() );
+			}
+		}
+
+	// insert events
+	if ( aEventDefs )
+		{
+		itemIds.iEventIds.iPtr.iOffset = buffer->Position();
+		itemIds.iEventIds.iPtr.iCount = aEventDefs->Count();
+
+		for ( TInt i = 0; i < itemIds.iEventIds.iPtr.iCount; ++i )
+			{
+			buffer->InsertL( (*aEventDefs)[i]->Id() );
+			}
+		}
+
+	// insert relations
+	if ( aRelationDefs )
+		{
+		itemIds.iRelationIds.iPtr.iOffset = buffer->Position();
+		itemIds.iRelationIds.iPtr.iCount = aRelationDefs->Count();
+
+		for ( TInt i = 0; i < itemIds.iRelationIds.iPtr.iCount; ++i )
+			{
+			buffer->InsertL( (*aRelationDefs)[i]->Id() );
+			}
+		}
+
+	// set up header correctly
+	buffer->PositionL( KNoOffset );
+	itemIds.SerializeL( *buffer );
+
+	CleanupStack::Pop( buffer );
+	return buffer;
+	}
+
+
+void CMdESessionImpl::ExportMetadataL( const TDesC& aFileName,
+    	const CMdENamespaceDef* aNamespaceDef,
+	    const RPointerArray<CMdEObjectDef>* aObjectDefs,
+        const RPointerArray<CMdERelationDef>* aRelationDefs,
+        const RPointerArray<CMdEEventDef>* aEventDefs )
+    {
+	CMdCSerializationBuffer* buffer = ExportCommonL( 
+			aNamespaceDef, aObjectDefs, aRelationDefs, aEventDefs );
+	CleanupStack::PushL( buffer );
+
+    // Export
+    iSession.DoExportMetadataL( aFileName, *buffer );
+       
+    // Cleanup
+	CleanupStack::PopAndDestroy( buffer );
+    }
+
+void CMdESessionImpl::ExportMetadataL( const TDesC& aFileName, 
+		TRequestStatus& aStatus, RMdEDataBuffer& aBuffer, 
+        const CMdENamespaceDef* aNamespaceDef, 
+	    const RPointerArray<CMdEObjectDef>* aObjectDefs, 
+        const RPointerArray<CMdERelationDef>* aRelationDefs, 
+        const RPointerArray<CMdEEventDef>* aEventDefs )
+    {
+	CMdCSerializationBuffer* buffer = ExportCommonL( 
+			aNamespaceDef, aObjectDefs, aRelationDefs, aEventDefs );
+	CleanupStack::PushL( buffer );
+
+    // Export
+    iSession.DoExportMetadataL( aFileName, *buffer, aStatus );
+
+    aBuffer.SetBufferL( buffer );
+    CleanupStack::Pop( buffer );
+    }
+
+void CMdESessionImpl::GetSchemaVersionL(
+		TInt& aMajorVersion, TInt& aMinorVersion)
+	{
+	return iSession.DoGetSchemaVersionL( aMajorVersion, aMinorVersion );
+	}
+
+void CMdESessionImpl::SetObjectToPresentByGuidL( 
+		const TInt64& aGuidHigh, const TInt64& aGuidLow )
+	{
+	return iSession.DoSetObjectToPresentByGuidL( aGuidHigh, aGuidLow );
+	}
+
+void CMdESessionImpl::CheckOpened() const
+	{
+	__ASSERT_ALWAYS(iSessionState == EMdESessionOpen,
+				    TMdEPanic::Panic(TMdEPanic::ESessionOpenInProgress));
+	}
+
+void CMdESessionImpl::GetCountL( CMdCSerializationBuffer* aBuffer, 
+		TUint32& aResult )
+	{
+	const TMdCItemCounts& itemCounts = TMdCItemCounts::GetFromBufferL( *aBuffer );
+
+	if( itemCounts.iObjects ) 
+	    {
+	    aResult = itemCounts.iObjects;
+	    __ASSERT_DEBUG( ( itemCounts.iEvents == 0 ) && ( itemCounts.iRelations == 0 ), MMdCCommon::Panic( KErrCorrupt ) );
+        }
+	
+	if( itemCounts.iEvents ) 
+	    {
+	    aResult = itemCounts.iEvents;
+	    __ASSERT_DEBUG( ( itemCounts.iObjects == 0 ) && ( itemCounts.iRelations == 0 ), MMdCCommon::Panic( KErrCorrupt ) );
+	    }
+
+	if( itemCounts.iRelations ) 
+	    {
+	    aResult = itemCounts.iRelations;
+	    __ASSERT_DEBUG( ( itemCounts.iObjects == 0 ) && ( itemCounts.iEvents == 0 ), MMdCCommon::Panic( KErrCorrupt ) );
+	    }
+	}
+
+void CMdESessionImpl::GetItemIdL( CMdCSerializationBuffer* aBuffer, 
+		RArray<TItemId>& aIdArray )
+	{
+	const TMdCItemIds& itemIds = TMdCItemIds::GetFromBufferL( *aBuffer );
+
+	if( itemIds.iObjectIds.iPtr.iCount > 0 ) 
+	    {
+	    aBuffer->PositionL( itemIds.iObjectIds.iPtr.iOffset );
+	    }
+	
+	if( itemIds.iRelationIds.iPtr.iCount > 0 ) 
+	    {
+	    aBuffer->PositionL( itemIds.iRelationIds.iPtr.iOffset );
+	    }
+
+	if( itemIds.iEventIds.iPtr.iCount > 0 ) 
+	    {
+	    aBuffer->PositionL( itemIds.iEventIds.iPtr.iOffset );
+	    }	
+
+	const TInt count = itemIds.iObjectIds.iPtr.iCount + itemIds.iRelationIds.iPtr.iCount
+		+ itemIds.iEventIds.iPtr.iCount;
+    aIdArray.ReserveL( count );
+	for( TUint32 i = 0; i < count; i++ )
+	    {
+	    TItemId id;
+	    aBuffer->ReceiveL( id );
+	    aIdArray.AppendL( id );
+	    }
+	}
+
+void CMdESessionImpl::GetDistinctValuesL( CMdCSerializationBuffer& aBuffer, 
+		CDesCArray& aResults )
+	{
+	const TMdCItemIds& itemIds = TMdCItemIds::GetFromBufferL( aBuffer );
+	aBuffer.PositionL( itemIds.iObjectUris.iPtr.iOffset );
+	for ( TUint32 i = 0; i < itemIds.iObjectUris.iPtr.iCount; ++i )
+		{
+		TPtrC16 value = aBuffer.ReceivePtr16L();
+		aResults.AppendL( value );
+		}
+	}
+
+CMdENamespaceDef* CMdESessionImpl::GetNamespaceDefL( 
+		CMdENamespaceDef* aNamespaceDef )
+	{
+    if ( aNamespaceDef )
+    	{
+    	return aNamespaceDef;
+    	}
+    else
+    	{
+    	return &GetDefaultNamespaceDefL();
+    	}
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdesessionstartupao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  MdE session startup active object*
+*/
+
+// INCLUDE FILES
+#include "mdesessionstartupao.h"
+
+#include "mdeenginesession.h"
+#include "mdesessionimpl.h"
+
+// ========================= MEMBER FUNCTIONS ==================================
+
+CMdESessionStartupAO* CMdESessionStartupAO::NewL(
+    CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession )
+    {
+    CMdESessionStartupAO* self = 
+    	CMdESessionStartupAO::NewLC( aSessionImpl, aSession );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+CMdESessionStartupAO* CMdESessionStartupAO::NewLC(
+    CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession )
+    {
+    CMdESessionStartupAO* self =
+        new ( ELeave ) CMdESessionStartupAO( aSessionImpl, aSession );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+CMdESessionStartupAO::CMdESessionStartupAO(
+    CMdESessionImpl& aSessionImpl, RMdEEngineSession& aSession )
+    : CActive( CActive::EPriorityStandard )
+    , iSessionImpl( aSessionImpl )
+    , iSession( aSession )
+    {
+    CActiveScheduler::Add( this );
+    
+    iState = EStartupOpenServer;
+    }
+
+void CMdESessionStartupAO::ConstructL()
+    {
+	SetActive();
+	TRequestStatus* status = &iStatus;
+	User::RequestComplete( status, KErrNone );
+    }
+
+CMdESessionStartupAO::~CMdESessionStartupAO()
+    {
+    Cancel(); // Causes call to DoCancel()
+    }
+
+void CMdESessionStartupAO::DoCancel()
+    {
+    iSession.OpenCancel( iStatus );
+    }
+
+void CMdESessionStartupAO::RunL()
+    {
+    const TInt status = iStatus.Int();
+    
+    switch ( iState )
+        {
+        case EStartupOpenServer:
+        	{
+        	iSession.OpenL( iStatus );
+
+			iState = EStartupConnect;
+
+        	SetActive();
+
+        	break;
+        	}
+        case EStartupConnect:
+        	{
+        	iSession.ConnectL();
+
+			iState = EStartupLoadSchema;
+
+			SetActive();
+			TRequestStatus* status = &iStatus;
+			User::RequestComplete( status, KErrNone );
+
+            break;
+            }
+        case EStartupLoadSchema:
+        	{
+        	iSessionImpl.DoLoadSchemaL();
+
+			iState = EStartupNotifyClient;
+
+			SetActive();
+			TRequestStatus* status = &iStatus;
+			User::RequestComplete( status, KErrNone );
+
+        	break;
+        	}
+        case EStartupNotifyClient:
+        	{
+        	iSessionImpl.NotifySessionOpened( KErrNone );
+
+        	break;
+        	}
+       	default:
+       		{
+       		User::Leave( KErrUnknown );
+       		break;
+       		}
+        }
+    }
+
+TInt CMdESessionStartupAO::RunError(TInt aError)
+    {
+    iSessionImpl.NotifyError( aError );
+
+    return KErrNone;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/client/src/mdetextpropertycondition.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,111 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+#include "mdetextpropertycondition.h"
+#include "mdcserializationbuffer.h"
+#include "mdepropertydef.h"
+#include "mdcquery.h"
+
+CMdETextPropertyCondition* 
+CMdETextPropertyCondition::NewL(const CMdEPropertyDef& aPropertyDef,
+                                TTextPropertyConditionCompareMethod aCompareMethod,
+                                const TDesC& aText)
+    {
+    CMdETextPropertyCondition* self = NewLC(aPropertyDef, aCompareMethod, aText);
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+
+CMdETextPropertyCondition* 
+CMdETextPropertyCondition::NewLC(const CMdEPropertyDef& aPropertyDef,
+                                 TTextPropertyConditionCompareMethod aCompareMethod,
+                                 const TDesC& aText)
+    {
+    CMdETextPropertyCondition* self 
+        = new(ELeave) CMdETextPropertyCondition(aPropertyDef, aCompareMethod);
+    CleanupStack::PushL(self);
+    self->ConstructL(aText);
+    return self;
+    }
+
+
+CMdETextPropertyCondition::CMdETextPropertyCondition(const CMdEPropertyDef& aPropertyDef, 
+                                                     TTextPropertyConditionCompareMethod aCompareMethod)
+        : CMdEPropertyCondition(EConditionTypePropertyText, aPropertyDef), 
+          iCompareMethod(aCompareMethod)
+    {
+    }
+
+
+void CMdETextPropertyCondition::ConstructL(const TDesC& aText)
+    {
+    // Make a copy of the string.
+    iText = aText.AllocL();
+    }
+
+
+CMdETextPropertyCondition::~CMdETextPropertyCondition()
+	{
+    delete iText;
+	}
+
+TUint32 CMdETextPropertyCondition::InternalQueryOptimizationFlags(TUint32& aFlags)
+	{
+	return CMdEPropertyCondition::InternalQueryOptimizationFlags(aFlags);
+	}
+
+TUint32 CMdETextPropertyCondition::RequiredBufferSize() const
+	{
+	// Required size for property condition
+	TUint32 bufferSize = sizeof( TMdCPropertyCondition );
+
+	// Required size for compare method (TUint32) and text
+	bufferSize += CMdCSerializationBuffer::KRequiredSizeForTUint32;
+	bufferSize += CMdCSerializationBuffer::RequiredSize( *iText );
+
+	return bufferSize;
+	}
+
+void CMdETextPropertyCondition::SerializeL(CMdCSerializationBuffer& aBuffer,
+		TMdCOffset& aFreespaceOffset) const
+	{
+	TMdCPropertyCondition property;
+
+	property.iConditionType = iType;
+	property.iNegated = iNegated;
+	property.iObjectDefId = iPropertyDef.ObjectDefId();
+	property.iPropertyDefId = iPropertyDef.Id();
+	property.iCondition = aBuffer.Position() + sizeof( TMdCPropertyCondition );
+
+	property.SerializeL( aBuffer );
+
+	aBuffer.InsertL( (TUint32)iCompareMethod );
+	aBuffer.InsertL( *iText );
+
+	aFreespaceOffset = aBuffer.Position();
+	}
+
+const TDesC& CMdETextPropertyCondition::Text() const
+	{
+	return *iText;
+	}
+
+TTextPropertyConditionCompareMethod CMdETextPropertyCondition::CompareMethod() const
+	{
+	return iCompareMethod;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/common/bwincw/mdccommonu.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,137 @@
+EXPORTS
+	?DeserializeL@TMdCEventCondition@@QAEXAAVCMdCSerializationBuffer@@@Z @ 1 NONAME ; void TMdCEventCondition::DeserializeL(class CMdCSerializationBuffer &)
+	?RequiredSize@CMdCSerializationBuffer@@SAKABVTDesC8@@@Z @ 2 NONAME ; unsigned long CMdCSerializationBuffer::RequiredSize(class TDesC8 const &)
+	?InsertL@CMdCSerializationBuffer@@QAEK_J@Z @ 3 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(long long)
+	?InsertL@CMdCSerializationBuffer@@QAEKAAVTMdCSerializationType@@K@Z @ 4 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(class TMdCSerializationType &, unsigned long)
+	?GetFromBufferL@TMdCObject@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 5 NONAME ; class TMdCObject const & TMdCObject::GetFromBufferL(class CMdCSerializationBuffer &)
+	?SerializeL@TMdCObjectDef@@QAEXAAVCMdCSerializationBuffer@@@Z @ 6 NONAME ; void TMdCObjectDef::SerializeL(class CMdCSerializationBuffer &)
+	?DeserializeL@TMdCNamespaceDef@@QAEXAAVCMdCSerializationBuffer@@@Z @ 7 NONAME ; void TMdCNamespaceDef::DeserializeL(class CMdCSerializationBuffer &)
+	?SerializeL@TMdCRelationDef@@QAEXAAVCMdCSerializationBuffer@@@Z @ 8 NONAME ; void TMdCRelationDef::SerializeL(class CMdCSerializationBuffer &)
+	??0TMdCRelationCondition@@QAE@XZ @ 9 NONAME ; TMdCRelationCondition::TMdCRelationCondition(void)
+	?Size@CMdCSerializationBuffer@@QBEKXZ @ 10 NONAME ; unsigned long CMdCSerializationBuffer::Size(void) const
+	?InsertL@CMdCSerializationBuffer@@QAEKI@Z @ 11 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(unsigned int)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAE@Z @ 12 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(unsigned char &)
+	?SerializeL@TMdCSchema@@QAEXAAVCMdCSerializationBuffer@@@Z @ 13 NONAME ; void TMdCSchema::SerializeL(class CMdCSerializationBuffer &)
+	?InsertL@CMdCSerializationBuffer@@QAEKVTTime@@@Z @ 14 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(class TTime)
+	?SerializeL@TMdCProperty@@QAEXAAVCMdCSerializationBuffer@@@Z @ 15 NONAME ; void TMdCProperty::SerializeL(class CMdCSerializationBuffer &)
+	?SerializeL@TMdCObject@@QAEXAAVCMdCSerializationBuffer@@@Z @ 16 NONAME ; void TMdCObject::SerializeL(class CMdCSerializationBuffer &)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAVTDes8@@@Z @ 17 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(class TDes8 &)
+	?DeserializeL@TMdCOrderRule@@QAEXAAVCMdCSerializationBuffer@@@Z @ 18 NONAME ; void TMdCOrderRule::DeserializeL(class CMdCSerializationBuffer &)
+	?GetFromBufferL@TMdCObjectCondition@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 19 NONAME ; class TMdCObjectCondition const & TMdCObjectCondition::GetFromBufferL(class CMdCSerializationBuffer &)
+	?DeserializeL@TMdCSearchCriteria@@QAEXAAVCMdCSerializationBuffer@@@Z @ 20 NONAME ; void TMdCSearchCriteria::DeserializeL(class CMdCSerializationBuffer &)
+	?ReceiveDes16L@CMdCSerializationBuffer@@QAEPAVHBufC16@@XZ @ 21 NONAME ; class HBufC16 * CMdCSerializationBuffer::ReceiveDes16L(void)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAM@Z @ 22 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(float &)
+	?InsertL@CMdCSerializationBuffer@@QAEKH@Z @ 23 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(int)
+	??0TMdCItemCounts@@QAE@XZ @ 24 NONAME ; TMdCItemCounts::TMdCItemCounts(void)
+	?SerializeL@TMdCOrderRule@@QAEXAAVCMdCSerializationBuffer@@@Z @ 25 NONAME ; void TMdCOrderRule::SerializeL(class CMdCSerializationBuffer &)
+	?SerializeL@TMdCPropertyDef@@QAEXAAVCMdCSerializationBuffer@@@Z @ 26 NONAME ; void TMdCPropertyDef::SerializeL(class CMdCSerializationBuffer &)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAN@Z @ 27 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(double &)
+	??0TMdCItems@@QAE@XZ @ 28 NONAME ; TMdCItems::TMdCItems(void)
+	?DeserializeL@TMdCItems@@QAEXAAVCMdCSerializationBuffer@@@Z @ 29 NONAME ; void TMdCItems::DeserializeL(class CMdCSerializationBuffer &)
+	?PositionL@CMdCSerializationBuffer@@QAEXK@Z @ 30 NONAME ; void CMdCSerializationBuffer::PositionL(unsigned long)
+	?InsertL@CMdCSerializationBuffer@@QAEKC@Z @ 31 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(signed char)
+	?GetFromBufferL@TMdCCondition@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 32 NONAME ; class TMdCCondition const & TMdCCondition::GetFromBufferL(class CMdCSerializationBuffer &)
+	?ReceivePtr8L@CMdCSerializationBuffer@@QAE?AVTPtrC8@@XZ @ 33 NONAME ; class TPtrC8 CMdCSerializationBuffer::ReceivePtr8L(void)
+	?Position@CMdCSerializationBuffer@@QBEKXZ @ 34 NONAME ; unsigned long CMdCSerializationBuffer::Position(void) const
+	??0TMdCProperty@@QAE@XZ @ 35 NONAME ; TMdCProperty::TMdCProperty(void)
+	?NewL@CMdCSerializationBuffer@@SAPAV1@J@Z @ 36 NONAME ; class CMdCSerializationBuffer * CMdCSerializationBuffer::NewL(long)
+	??0TMdCItemIds@@QAE@XZ @ 37 NONAME ; TMdCItemIds::TMdCItemIds(void)
+	?NewLC@CMdCSerializationBuffer@@SAPAV1@ABV1@@Z @ 38 NONAME ; class CMdCSerializationBuffer * CMdCSerializationBuffer::NewLC(class CMdCSerializationBuffer const &)
+	?SerializeL@TMdCEventCondition@@QAEXAAVCMdCSerializationBuffer@@@Z @ 39 NONAME ; void TMdCEventCondition::SerializeL(class CMdCSerializationBuffer &)
+	?DeserializeL@TMdCPropertyCondition@@QAEXAAVCMdCSerializationBuffer@@@Z @ 40 NONAME ; void TMdCPropertyCondition::DeserializeL(class CMdCSerializationBuffer &)
+	?GetFromBufferL@TMdCNamespaceDef@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 41 NONAME ; class TMdCNamespaceDef const & TMdCNamespaceDef::GetFromBufferL(class CMdCSerializationBuffer &)
+	??0TMdCObjectDef@@QAE@XZ @ 42 NONAME ; TMdCObjectDef::TMdCObjectDef(void)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAH@Z @ 43 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(int &)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAA_J@Z @ 44 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(long long &)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAI@Z @ 45 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(unsigned int &)
+	?DeserializeL@TMdCProperty@@QAEXAAVCMdCSerializationBuffer@@@Z @ 46 NONAME ; void TMdCProperty::DeserializeL(class CMdCSerializationBuffer &)
+	?DeserializeL@TMdCRelationDef@@QAEXAAVCMdCSerializationBuffer@@@Z @ 47 NONAME ; void TMdCRelationDef::DeserializeL(class CMdCSerializationBuffer &)
+	?InsertL@CMdCSerializationBuffer@@QAEKM@Z @ 48 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(float)
+	??0TMdCEventCondition@@QAE@XZ @ 49 NONAME ; TMdCEventCondition::TMdCEventCondition(void)
+	?GetFromBufferL@TMdCItemIds@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 50 NONAME ; class TMdCItemIds const & TMdCItemIds::GetFromBufferL(class CMdCSerializationBuffer &)
+	?SerializeL@TMdCPropertyCondition@@QAEXAAVCMdCSerializationBuffer@@@Z @ 51 NONAME ; void TMdCPropertyCondition::SerializeL(class CMdCSerializationBuffer &)
+	?SerializeL@TMdCEventDef@@QAEXAAVCMdCSerializationBuffer@@@Z @ 52 NONAME ; void TMdCEventDef::SerializeL(class CMdCSerializationBuffer &)
+	?NewLC@CMdCSerializationBuffer@@SAPAV1@ABVRMessage2@@H@Z @ 53 NONAME ; class CMdCSerializationBuffer * CMdCSerializationBuffer::NewLC(class RMessage2 const &, int)
+	?GetFromBufferL@TMdCItemCounts@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 54 NONAME ; class TMdCItemCounts const & TMdCItemCounts::GetFromBufferL(class CMdCSerializationBuffer &)
+	?GetFromBufferL@TMdCOrderRule@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 55 NONAME ; class TMdCOrderRule const & TMdCOrderRule::GetFromBufferL(class CMdCSerializationBuffer &)
+	??0TMdCRelation@@QAE@XZ @ 56 NONAME ; TMdCRelation::TMdCRelation(void)
+	?DeserializeL@TMdCRelationCondition@@QAEXAAVCMdCSerializationBuffer@@@Z @ 57 NONAME ; void TMdCRelationCondition::DeserializeL(class CMdCSerializationBuffer &)
+	?NewLC@CMdCSerializationBuffer@@SAPAV1@PAEJ@Z @ 58 NONAME ; class CMdCSerializationBuffer * CMdCSerializationBuffer::NewLC(unsigned char *, long)
+	?SerializeL@TMdCEvent@@QAEXAAVCMdCSerializationBuffer@@@Z @ 59 NONAME ; void TMdCEvent::SerializeL(class CMdCSerializationBuffer &)
+	?Buffer@CMdCSerializationBuffer@@QBE?AVTPtr8@@XZ @ 60 NONAME ; class TPtr8 CMdCSerializationBuffer::Buffer(void) const
+	?BufferConstPtr@CMdCSerializationBuffer@@QBEPBVTPtr8@@XZ @ 61 NONAME ; class TPtr8 const * CMdCSerializationBuffer::BufferConstPtr(void) const
+	?GetFromBufferL@TMdCEventCondition@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 62 NONAME ; class TMdCEventCondition const & TMdCEventCondition::GetFromBufferL(class CMdCSerializationBuffer &)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAVTTime@@@Z @ 63 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(class TTime &)
+	?SerializeL@TMdCLogicCondition@@QAEXAAVCMdCSerializationBuffer@@@Z @ 64 NONAME ; void TMdCLogicCondition::SerializeL(class CMdCSerializationBuffer &)
+	?DeserializeL@TMdCObjectDef@@QAEXAAVCMdCSerializationBuffer@@@Z @ 65 NONAME ; void TMdCObjectDef::DeserializeL(class CMdCSerializationBuffer &)
+	?DeserializeL@TMdCItemIds@@QAEXAAVCMdCSerializationBuffer@@@Z @ 66 NONAME ; void TMdCItemIds::DeserializeL(class CMdCSerializationBuffer &)
+	?SerializeL@TMdCItems@@QAEXAAVCMdCSerializationBuffer@@@Z @ 67 NONAME ; void TMdCItems::SerializeL(class CMdCSerializationBuffer &)
+	?DeserializeL@TMdCObject@@QAEXAAVCMdCSerializationBuffer@@@Z @ 68 NONAME ; void TMdCObject::DeserializeL(class CMdCSerializationBuffer &)
+	?GetFromBufferL@TMdCSchema@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 69 NONAME ; class TMdCSchema const & TMdCSchema::GetFromBufferL(class CMdCSerializationBuffer &)
+	?Panic@MMdCCommon@@SAXH@Z @ 70 NONAME ; void MMdCCommon::Panic(int)
+	?GetFromBufferL@TMdCEventDef@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 71 NONAME ; class TMdCEventDef const & TMdCEventDef::GetFromBufferL(class CMdCSerializationBuffer &)
+	?GetFromBufferL@TMdCObjectDef@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 72 NONAME ; class TMdCObjectDef const & TMdCObjectDef::GetFromBufferL(class CMdCSerializationBuffer &)
+	??0TMdCPropertyDef@@QAE@XZ @ 73 NONAME ; TMdCPropertyDef::TMdCPropertyDef(void)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAF@Z @ 74 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(short &)
+	??0TMdCEvent@@QAE@XZ @ 75 NONAME ; TMdCEvent::TMdCEvent(void)
+	?SerializeL@TMdCRelationCondition@@QAEXAAVCMdCSerializationBuffer@@@Z @ 76 NONAME ; void TMdCRelationCondition::SerializeL(class CMdCSerializationBuffer &)
+	?SerializeL@TMdCObjectCondition@@QAEXAAVCMdCSerializationBuffer@@@Z @ 77 NONAME ; void TMdCObjectCondition::SerializeL(class CMdCSerializationBuffer &)
+	?GetFromBufferL@TMdCProperty@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 78 NONAME ; class TMdCProperty const & TMdCProperty::GetFromBufferL(class CMdCSerializationBuffer &)
+	??0TMdCRelationDef@@QAE@XZ @ 79 NONAME ; TMdCRelationDef::TMdCRelationDef(void)
+	?InsertL@CMdCSerializationBuffer@@QAEKE@Z @ 80 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(unsigned char)
+	?InsertL@CMdCSerializationBuffer@@QAEKG@Z @ 81 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(unsigned short)
+	?SerializeL@TMdCRelation@@QAEXAAVCMdCSerializationBuffer@@@Z @ 82 NONAME ; void TMdCRelation::SerializeL(class CMdCSerializationBuffer &)
+	??0TMdCSearchCriteria@@QAE@XZ @ 83 NONAME ; TMdCSearchCriteria::TMdCSearchCriteria(void)
+	??0TMdCOrderRule@@QAE@XZ @ 84 NONAME ; TMdCOrderRule::TMdCOrderRule(void)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAATTMdCValueUnion@@@Z @ 85 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(union TMdCValueUnion &)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAVTMdCSerializationType@@K@Z @ 86 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(class TMdCSerializationType &, unsigned long)
+	?DeserializeL@TMdCPropertyDef@@QAEXAAVCMdCSerializationBuffer@@@Z @ 87 NONAME ; void TMdCPropertyDef::DeserializeL(class CMdCSerializationBuffer &)
+	?InsertL@CMdCSerializationBuffer@@QAEKN@Z @ 88 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(double)
+	?GetFromBufferL@TMdCPropertyDef@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 89 NONAME ; class TMdCPropertyDef const & TMdCPropertyDef::GetFromBufferL(class CMdCSerializationBuffer &)
+	??0TMdCLogicCondition@@QAE@XZ @ 90 NONAME ; TMdCLogicCondition::TMdCLogicCondition(void)
+	?InsertL@CMdCSerializationBuffer@@QAEKK@Z @ 91 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(unsigned long)
+	?NewL@CMdCSerializationBuffer@@SAPAV1@ABVRMessage2@@H@Z @ 92 NONAME ; class CMdCSerializationBuffer * CMdCSerializationBuffer::NewL(class RMessage2 const &, int)
+	?SerializeL@TMdCNamespaceDef@@QAEXAAVCMdCSerializationBuffer@@@Z @ 93 NONAME ; void TMdCNamespaceDef::SerializeL(class CMdCSerializationBuffer &)
+	?GetFromBufferL@TMdCSearchCriteria@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 94 NONAME ; class TMdCSearchCriteria const & TMdCSearchCriteria::GetFromBufferL(class CMdCSerializationBuffer &)
+	?NewL@CMdCSerializationBuffer@@SAPAV1@ABV1@@Z @ 95 NONAME ; class CMdCSerializationBuffer * CMdCSerializationBuffer::NewL(class CMdCSerializationBuffer const &)
+	??0TMdCEventDef@@QAE@XZ @ 96 NONAME ; TMdCEventDef::TMdCEventDef(void)
+	?RequiredSize@CMdCSerializationBuffer@@SAKABVTDesC16@@@Z @ 97 NONAME ; unsigned long CMdCSerializationBuffer::RequiredSize(class TDesC16 const &)
+	?DeserializeL@TMdCRelation@@QAEXAAVCMdCSerializationBuffer@@@Z @ 98 NONAME ; void TMdCRelation::DeserializeL(class CMdCSerializationBuffer &)
+	?NewL@CMdCSerializationBuffer@@SAPAV1@PAEJ@Z @ 99 NONAME ; class CMdCSerializationBuffer * CMdCSerializationBuffer::NewL(unsigned char *, long)
+	??0TMdCObjectCondition@@QAE@XZ @ 100 NONAME ; TMdCObjectCondition::TMdCObjectCondition(void)
+	?GetFromBufferL@TMdCEvent@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 101 NONAME ; class TMdCEvent const & TMdCEvent::GetFromBufferL(class CMdCSerializationBuffer &)
+	?GetFromBufferL@TMdCRelation@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 102 NONAME ; class TMdCRelation const & TMdCRelation::GetFromBufferL(class CMdCSerializationBuffer &)
+	?DeserializeL@TMdCObjectCondition@@QAEXAAVCMdCSerializationBuffer@@@Z @ 103 NONAME ; void TMdCObjectCondition::DeserializeL(class CMdCSerializationBuffer &)
+	?GetFromBufferL@TMdCLogicCondition@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 104 NONAME ; class TMdCLogicCondition const & TMdCLogicCondition::GetFromBufferL(class CMdCSerializationBuffer &)
+	??0TMdCPropertyCondition@@QAE@XZ @ 105 NONAME ; TMdCPropertyCondition::TMdCPropertyCondition(void)
+	?InsertL@CMdCSerializationBuffer@@QAEKAAVTDesC16@@@Z @ 106 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(class TDesC16 &)
+	?DeserializeL@TMdCEventDef@@QAEXAAVCMdCSerializationBuffer@@@Z @ 107 NONAME ; void TMdCEventDef::DeserializeL(class CMdCSerializationBuffer &)
+	?InsertL@CMdCSerializationBuffer@@QAEKAAVTDesC8@@@Z @ 108 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(class TDesC8 &)
+	?GetFromBufferL@TMdCPropertyCondition@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 109 NONAME ; class TMdCPropertyCondition const & TMdCPropertyCondition::GetFromBufferL(class CMdCSerializationBuffer &)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAG@Z @ 110 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(unsigned short &)
+	?BufferPtr@CMdCSerializationBuffer@@QBEPAVTPtr8@@XZ @ 111 NONAME ; class TPtr8 * CMdCSerializationBuffer::BufferPtr(void) const
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAK@Z @ 112 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(unsigned long &)
+	?DeserializeL@TMdCEvent@@QAEXAAVCMdCSerializationBuffer@@@Z @ 113 NONAME ; void TMdCEvent::DeserializeL(class CMdCSerializationBuffer &)
+	??0TMdCObject@@QAE@XZ @ 114 NONAME ; TMdCObject::TMdCObject(void)
+	?SerializeL@TMdCSearchCriteria@@QAEXAAVCMdCSerializationBuffer@@@Z @ 115 NONAME ; void TMdCSearchCriteria::SerializeL(class CMdCSerializationBuffer &)
+	??0TMdCSchema@@QAE@XZ @ 116 NONAME ; TMdCSchema::TMdCSchema(void)
+	?GetFromBufferL@TMdCItems@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 117 NONAME ; class TMdCItems const & TMdCItems::GetFromBufferL(class CMdCSerializationBuffer &)
+	?DeserializeL@TMdCSchema@@QAEXAAVCMdCSerializationBuffer@@@Z @ 118 NONAME ; void TMdCSchema::DeserializeL(class CMdCSerializationBuffer &)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAJ@Z @ 119 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(long &)
+	?DeserializeL@TMdCItemCounts@@QAEXAAVCMdCSerializationBuffer@@@Z @ 120 NONAME ; void TMdCItemCounts::DeserializeL(class CMdCSerializationBuffer &)
+	?SerializeL@TMdCItemIds@@QAEXAAVCMdCSerializationBuffer@@@Z @ 121 NONAME ; void TMdCItemIds::SerializeL(class CMdCSerializationBuffer &)
+	?NewLC@CMdCSerializationBuffer@@SAPAV1@J@Z @ 122 NONAME ; class CMdCSerializationBuffer * CMdCSerializationBuffer::NewLC(long)
+	?DeserializeL@TMdCLogicCondition@@QAEXAAVCMdCSerializationBuffer@@@Z @ 123 NONAME ; void TMdCLogicCondition::DeserializeL(class CMdCSerializationBuffer &)
+	?InsertL@CMdCSerializationBuffer@@QAEKAATTMdCValueUnion@@@Z @ 124 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(union TMdCValueUnion &)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAC@Z @ 125 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(signed char &)
+	?InsertL@CMdCSerializationBuffer@@QAEKF@Z @ 126 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(short)
+	??0TMdCNamespaceDef@@QAE@XZ @ 127 NONAME ; TMdCNamespaceDef::TMdCNamespaceDef(void)
+	?ReceiveL@CMdCSerializationBuffer@@QAEKAAVTDes16@@@Z @ 128 NONAME ; unsigned long CMdCSerializationBuffer::ReceiveL(class TDes16 &)
+	?SerializeL@TMdCItemCounts@@QAEXAAVCMdCSerializationBuffer@@@Z @ 129 NONAME ; void TMdCItemCounts::SerializeL(class CMdCSerializationBuffer &)
+	?InsertL@CMdCSerializationBuffer@@QAEKJ@Z @ 130 NONAME ; unsigned long CMdCSerializationBuffer::InsertL(long)
+	?ReceivePtr16L@CMdCSerializationBuffer@@QAE?AVTPtrC16@@XZ @ 131 NONAME ; class TPtrC16 CMdCSerializationBuffer::ReceivePtr16L(void)
+	?GetFromBufferL@TMdCRelationCondition@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 132 NONAME ; class TMdCRelationCondition const & TMdCRelationCondition::GetFromBufferL(class CMdCSerializationBuffer &)
+	?ReceiveDes8L@CMdCSerializationBuffer@@QAEPAVHBufC8@@XZ @ 133 NONAME ; class HBufC8 * CMdCSerializationBuffer::ReceiveDes8L(void)
+	?ReceiveDesciptorLength@CMdCSerializationBuffer@@QBEGXZ @ 134 NONAME ; unsigned short CMdCSerializationBuffer::ReceiveDesciptorLength(void) const
+	?GetFromBufferL@TMdCRelationDef@@SAABV1@AAVCMdCSerializationBuffer@@@Z @ 135 NONAME ; class TMdCRelationDef const & TMdCRelationDef::GetFromBufferL(class CMdCSerializationBuffer &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/common/eabi/mdccommonu.def	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,157 @@
+EXPORTS
+	_ZN10MMdCCommon5PanicEi @ 1 NONAME
+	_ZN10TMdCObject10SerializeLER23CMdCSerializationBuffer @ 2 NONAME
+	_ZN10TMdCObject12DeserializeLER23CMdCSerializationBuffer @ 3 NONAME
+	_ZN10TMdCObject14GetFromBufferLER23CMdCSerializationBuffer @ 4 NONAME
+	_ZN10TMdCObjectC1Ev @ 5 NONAME
+	_ZN10TMdCObjectC2Ev @ 6 NONAME
+	_ZN10TMdCSchema10SerializeLER23CMdCSerializationBuffer @ 7 NONAME
+	_ZN10TMdCSchema12DeserializeLER23CMdCSerializationBuffer @ 8 NONAME
+	_ZN10TMdCSchema14GetFromBufferLER23CMdCSerializationBuffer @ 9 NONAME
+	_ZN10TMdCSchemaC1Ev @ 10 NONAME
+	_ZN10TMdCSchemaC2Ev @ 11 NONAME
+	_ZN11TMdCItemIds10SerializeLER23CMdCSerializationBuffer @ 12 NONAME
+	_ZN11TMdCItemIds12DeserializeLER23CMdCSerializationBuffer @ 13 NONAME
+	_ZN11TMdCItemIds14GetFromBufferLER23CMdCSerializationBuffer @ 14 NONAME
+	_ZN11TMdCItemIdsC1Ev @ 15 NONAME
+	_ZN11TMdCItemIdsC2Ev @ 16 NONAME
+	_ZN12TMdCEventDef10SerializeLER23CMdCSerializationBuffer @ 17 NONAME
+	_ZN12TMdCEventDef12DeserializeLER23CMdCSerializationBuffer @ 18 NONAME
+	_ZN12TMdCEventDef14GetFromBufferLER23CMdCSerializationBuffer @ 19 NONAME
+	_ZN12TMdCEventDefC1Ev @ 20 NONAME
+	_ZN12TMdCEventDefC2Ev @ 21 NONAME
+	_ZN12TMdCProperty10SerializeLER23CMdCSerializationBuffer @ 22 NONAME
+	_ZN12TMdCProperty12DeserializeLER23CMdCSerializationBuffer @ 23 NONAME
+	_ZN12TMdCProperty14GetFromBufferLER23CMdCSerializationBuffer @ 24 NONAME
+	_ZN12TMdCPropertyC1Ev @ 25 NONAME
+	_ZN12TMdCPropertyC2Ev @ 26 NONAME
+	_ZN12TMdCRelation10SerializeLER23CMdCSerializationBuffer @ 27 NONAME
+	_ZN12TMdCRelation12DeserializeLER23CMdCSerializationBuffer @ 28 NONAME
+	_ZN12TMdCRelation14GetFromBufferLER23CMdCSerializationBuffer @ 29 NONAME
+	_ZN12TMdCRelationC1Ev @ 30 NONAME
+	_ZN12TMdCRelationC2Ev @ 31 NONAME
+	_ZN13TMdCCondition14GetFromBufferLER23CMdCSerializationBuffer @ 32 NONAME
+	_ZN13TMdCObjectDef10SerializeLER23CMdCSerializationBuffer @ 33 NONAME
+	_ZN13TMdCObjectDef12DeserializeLER23CMdCSerializationBuffer @ 34 NONAME
+	_ZN13TMdCObjectDef14GetFromBufferLER23CMdCSerializationBuffer @ 35 NONAME
+	_ZN13TMdCObjectDefC1Ev @ 36 NONAME
+	_ZN13TMdCObjectDefC2Ev @ 37 NONAME
+	_ZN13TMdCOrderRule10SerializeLER23CMdCSerializationBuffer @ 38 NONAME
+	_ZN13TMdCOrderRule12DeserializeLER23CMdCSerializationBuffer @ 39 NONAME
+	_ZN13TMdCOrderRule14GetFromBufferLER23CMdCSerializationBuffer @ 40 NONAME
+	_ZN13TMdCOrderRuleC1Ev @ 41 NONAME
+	_ZN13TMdCOrderRuleC2Ev @ 42 NONAME
+	_ZN14TMdCItemCounts10SerializeLER23CMdCSerializationBuffer @ 43 NONAME
+	_ZN14TMdCItemCounts12DeserializeLER23CMdCSerializationBuffer @ 44 NONAME
+	_ZN14TMdCItemCounts14GetFromBufferLER23CMdCSerializationBuffer @ 45 NONAME
+	_ZN14TMdCItemCountsC1Ev @ 46 NONAME
+	_ZN14TMdCItemCountsC2Ev @ 47 NONAME
+	_ZN15TMdCPropertyDef10SerializeLER23CMdCSerializationBuffer @ 48 NONAME
+	_ZN15TMdCPropertyDef12DeserializeLER23CMdCSerializationBuffer @ 49 NONAME
+	_ZN15TMdCPropertyDef14GetFromBufferLER23CMdCSerializationBuffer @ 50 NONAME
+	_ZN15TMdCPropertyDefC1Ev @ 51 NONAME
+	_ZN15TMdCPropertyDefC2Ev @ 52 NONAME
+	_ZN15TMdCRelationDef10SerializeLER23CMdCSerializationBuffer @ 53 NONAME
+	_ZN15TMdCRelationDef12DeserializeLER23CMdCSerializationBuffer @ 54 NONAME
+	_ZN15TMdCRelationDef14GetFromBufferLER23CMdCSerializationBuffer @ 55 NONAME
+	_ZN15TMdCRelationDefC1Ev @ 56 NONAME
+	_ZN15TMdCRelationDefC2Ev @ 57 NONAME
+	_ZN16TMdCNamespaceDef10SerializeLER23CMdCSerializationBuffer @ 58 NONAME
+	_ZN16TMdCNamespaceDef12DeserializeLER23CMdCSerializationBuffer @ 59 NONAME
+	_ZN16TMdCNamespaceDef14GetFromBufferLER23CMdCSerializationBuffer @ 60 NONAME
+	_ZN16TMdCNamespaceDefC1Ev @ 61 NONAME
+	_ZN16TMdCNamespaceDefC2Ev @ 62 NONAME
+	_ZN18TMdCEventCondition10SerializeLER23CMdCSerializationBuffer @ 63 NONAME
+	_ZN18TMdCEventCondition12DeserializeLER23CMdCSerializationBuffer @ 64 NONAME
+	_ZN18TMdCEventCondition14GetFromBufferLER23CMdCSerializationBuffer @ 65 NONAME
+	_ZN18TMdCEventConditionC1Ev @ 66 NONAME
+	_ZN18TMdCEventConditionC2Ev @ 67 NONAME
+	_ZN18TMdCLogicCondition10SerializeLER23CMdCSerializationBuffer @ 68 NONAME
+	_ZN18TMdCLogicCondition12DeserializeLER23CMdCSerializationBuffer @ 69 NONAME
+	_ZN18TMdCLogicCondition14GetFromBufferLER23CMdCSerializationBuffer @ 70 NONAME
+	_ZN18TMdCLogicConditionC1Ev @ 71 NONAME
+	_ZN18TMdCLogicConditionC2Ev @ 72 NONAME
+	_ZN18TMdCSearchCriteria10SerializeLER23CMdCSerializationBuffer @ 73 NONAME
+	_ZN18TMdCSearchCriteria12DeserializeLER23CMdCSerializationBuffer @ 74 NONAME
+	_ZN18TMdCSearchCriteria14GetFromBufferLER23CMdCSerializationBuffer @ 75 NONAME
+	_ZN18TMdCSearchCriteriaC1Ev @ 76 NONAME
+	_ZN18TMdCSearchCriteriaC2Ev @ 77 NONAME
+	_ZN19TMdCObjectCondition10SerializeLER23CMdCSerializationBuffer @ 78 NONAME
+	_ZN19TMdCObjectCondition12DeserializeLER23CMdCSerializationBuffer @ 79 NONAME
+	_ZN19TMdCObjectCondition14GetFromBufferLER23CMdCSerializationBuffer @ 80 NONAME
+	_ZN19TMdCObjectConditionC1Ev @ 81 NONAME
+	_ZN19TMdCObjectConditionC2Ev @ 82 NONAME
+	_ZN21TMdCPropertyCondition10SerializeLER23CMdCSerializationBuffer @ 83 NONAME
+	_ZN21TMdCPropertyCondition12DeserializeLER23CMdCSerializationBuffer @ 84 NONAME
+	_ZN21TMdCPropertyCondition14GetFromBufferLER23CMdCSerializationBuffer @ 85 NONAME
+	_ZN21TMdCPropertyConditionC1Ev @ 86 NONAME
+	_ZN21TMdCPropertyConditionC2Ev @ 87 NONAME
+	_ZN21TMdCRelationCondition10SerializeLER23CMdCSerializationBuffer @ 88 NONAME
+	_ZN21TMdCRelationCondition12DeserializeLER23CMdCSerializationBuffer @ 89 NONAME
+	_ZN21TMdCRelationCondition14GetFromBufferLER23CMdCSerializationBuffer @ 90 NONAME
+	_ZN21TMdCRelationConditionC1Ev @ 91 NONAME
+	_ZN21TMdCRelationConditionC2Ev @ 92 NONAME
+	_ZN23CMdCSerializationBuffer12ReceiveDes8LEv @ 93 NONAME
+	_ZN23CMdCSerializationBuffer12ReceivePtr8LEv @ 94 NONAME
+	_ZN23CMdCSerializationBuffer12RequiredSizeERK6TDesC8 @ 95 NONAME
+	_ZN23CMdCSerializationBuffer12RequiredSizeERK7TDesC16 @ 96 NONAME
+	_ZN23CMdCSerializationBuffer13ReceiveDes16LEv @ 97 NONAME
+	_ZN23CMdCSerializationBuffer13ReceivePtr16LEv @ 98 NONAME
+	_ZN23CMdCSerializationBuffer4NewLEPhl @ 99 NONAME
+	_ZN23CMdCSerializationBuffer4NewLERK9RMessage2i @ 100 NONAME
+	_ZN23CMdCSerializationBuffer4NewLERKS_ @ 101 NONAME
+	_ZN23CMdCSerializationBuffer4NewLEl @ 102 NONAME
+	_ZN23CMdCSerializationBuffer5NewLCEPhl @ 103 NONAME
+	_ZN23CMdCSerializationBuffer5NewLCERK9RMessage2i @ 104 NONAME
+	_ZN23CMdCSerializationBuffer5NewLCERKS_ @ 105 NONAME
+	_ZN23CMdCSerializationBuffer5NewLCEl @ 106 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLE5TTime @ 107 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLER14TMdCValueUnion @ 108 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLER21TMdCSerializationTypem @ 109 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLER6TDesC8 @ 110 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLER7TDesC16 @ 111 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLEa @ 112 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLEd @ 113 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLEf @ 114 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLEh @ 115 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLEi @ 116 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLEj @ 117 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLEl @ 118 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLEm @ 119 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLEs @ 120 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLEt @ 121 NONAME
+	_ZN23CMdCSerializationBuffer7InsertLEx @ 122 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLER14TMdCValueUnion @ 123 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLER21TMdCSerializationTypem @ 124 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLER5TDes8 @ 125 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLER5TTime @ 126 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLER6TDes16 @ 127 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLERa @ 128 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLERd @ 129 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLERf @ 130 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLERh @ 131 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLERi @ 132 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLERj @ 133 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLERl @ 134 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLERm @ 135 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLERs @ 136 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLERt @ 137 NONAME
+	_ZN23CMdCSerializationBuffer8ReceiveLERx @ 138 NONAME
+	_ZN23CMdCSerializationBuffer9PositionLEm @ 139 NONAME
+	_ZN9TMdCEvent10SerializeLER23CMdCSerializationBuffer @ 140 NONAME
+	_ZN9TMdCEvent12DeserializeLER23CMdCSerializationBuffer @ 141 NONAME
+	_ZN9TMdCEvent14GetFromBufferLER23CMdCSerializationBuffer @ 142 NONAME
+	_ZN9TMdCEventC1Ev @ 143 NONAME
+	_ZN9TMdCEventC2Ev @ 144 NONAME
+	_ZN9TMdCItems10SerializeLER23CMdCSerializationBuffer @ 145 NONAME
+	_ZN9TMdCItems12DeserializeLER23CMdCSerializationBuffer @ 146 NONAME
+	_ZN9TMdCItems14GetFromBufferLER23CMdCSerializationBuffer @ 147 NONAME
+	_ZN9TMdCItemsC1Ev @ 148 NONAME
+	_ZN9TMdCItemsC2Ev @ 149 NONAME
+	_ZNK23CMdCSerializationBuffer14BufferConstPtrEv @ 150 NONAME
+	_ZNK23CMdCSerializationBuffer22ReceiveDesciptorLengthEv @ 151 NONAME
+	_ZNK23CMdCSerializationBuffer4SizeEv @ 152 NONAME
+	_ZNK23CMdCSerializationBuffer6BufferEv @ 153 NONAME
+	_ZNK23CMdCSerializationBuffer8PositionEv @ 154 NONAME
+	_ZNK23CMdCSerializationBuffer9BufferPtrEv @ 155 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/common/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+mdccommon.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/common/group/mdccommon.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION         10.0
+TARGET          mdccommon.dll
+TARGETTYPE      dll
+TARGETPATH 	    SHARED_LIB_DIR
+UID             0x1000008d 0x200009F2
+
+CAPABILITY	    CAP_GENERAL_DLL
+VENDORID        VID_DEFAULT
+
+#if defined(WINSCW)
+    deffile ../bwincw/mdccommonu.def
+#elif defined(ARMCC)
+    deffile ../eabi/mdccommonu.def
+#endif
+nostrictdef
+
+USERINCLUDE     ../../../inc
+
+SOURCEPATH  	../src
+SOURCE      	mdccommon.cpp
+SOURCE		mdcserializationbuffer.cpp
+SOURCE		mdcitem.cpp
+SOURCE		mdcdef.cpp
+SOURCE		mdcquery.cpp
+SOURCE		mdcresult.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         	euser.lib
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+OPTION ARMCC -O3 -OTime
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/common/src/mdccommon.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  common utilities*
+*/
+
+#include <e32std.h>
+
+#include "mdccommon.h"
+#include "mdccommon.pan"
+
+// ---------------------------------------------------------------------------
+// Panic
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void MMdCCommon::Panic( TInt aPanicCode )
+    {
+    User::Panic( KMetadataEngine, aPanicCode );
+    }
+
+// ---------------------------------------------------------------------------
+// E32Dll
+// ---------------------------------------------------------------------------
+//
+TBool E32Dll()
+    {
+    return ETrue;
+    }
+	
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/common/src/mdcdef.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,216 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  common definition for MdE*
+*/
+
+#include "mdcdef.h"
+
+/////////////////////
+//  TMdCObjectDef  //
+/////////////////////
+
+EXPORT_C TMdCObjectDef::TMdCObjectDef() : TMdCDef( EMdCObject )
+	{
+	}
+
+EXPORT_C void TMdCObjectDef::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCObjectDef::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+EXPORT_C const TMdCObjectDef& TMdCObjectDef::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCObjectDef* objectDef = (TMdCObjectDef*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (objectDef->iType != EMdCObject)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCObjectDef!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCObjectDef) % 2 ? sizeof(TMdCObjectDef)+1 : sizeof(TMdCObjectDef);
+	aBuffer.PositionL( bufferPosition + size );
+	return *objectDef;
+	}
+
+
+///////////////////////
+//  TMdCRelationDef  //
+///////////////////////
+
+EXPORT_C TMdCRelationDef::TMdCRelationDef() : TMdCDef( EMdCRelationDef )
+	{
+	}
+
+EXPORT_C void TMdCRelationDef::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCRelationDef::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+EXPORT_C const TMdCRelationDef& TMdCRelationDef::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCRelationDef* relationDef = (TMdCRelationDef*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (relationDef->iType != EMdCRelationDef)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCRelationDef!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCRelationDef) % 2 ? sizeof(TMdCRelationDef)+1 : sizeof(TMdCRelationDef);
+	aBuffer.PositionL( bufferPosition + size );
+	return *relationDef;
+	}
+
+
+////////////////////
+//  TMdCEventDef  //
+////////////////////
+
+EXPORT_C TMdCEventDef::TMdCEventDef() : TMdCDef( EMdCEventDef )
+	{
+	}
+
+EXPORT_C void TMdCEventDef::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCEventDef::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+EXPORT_C const TMdCEventDef& TMdCEventDef::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCEventDef* eventDef = (TMdCEventDef*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (eventDef->iType != EMdCEventDef)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCEventDef!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCEventDef) % 2 ? sizeof(TMdCEventDef)+1 : sizeof(TMdCEventDef);
+	aBuffer.PositionL( bufferPosition + size );
+	return *eventDef;
+	}
+
+
+///////////////////////
+//  TMdCPropertyDef  //
+///////////////////////
+
+EXPORT_C TMdCPropertyDef::TMdCPropertyDef() : TMdCDef( EMdCPropertyDef )
+	{
+	}
+
+EXPORT_C void TMdCPropertyDef::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCPropertyDef::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+EXPORT_C const TMdCPropertyDef& TMdCPropertyDef::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCPropertyDef* propertyDef = (TMdCPropertyDef*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (propertyDef->iType != EMdCPropertyDef)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCPropertyDef!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCPropertyDef) % 2 ? sizeof(TMdCPropertyDef)+1 : sizeof(TMdCPropertyDef);
+	aBuffer.PositionL( bufferPosition + size );
+	return *propertyDef;
+	}
+
+
+////////////////////////
+//  TMdCNamespaceDef  //
+////////////////////////
+
+EXPORT_C TMdCNamespaceDef::TMdCNamespaceDef() : TMdCDef( EMdCNamespaceDef )
+	{
+	}
+
+EXPORT_C void TMdCNamespaceDef::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCNamespaceDef::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCNamespaceDef& TMdCNamespaceDef::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCNamespaceDef* namespaceDef = (TMdCNamespaceDef*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (namespaceDef->iType != EMdCNamespaceDef)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCNamespaceDef!"), KErrCorrupt ) );
+
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCNamespaceDef) % 2 ? sizeof(TMdCNamespaceDef)+1 : sizeof(TMdCNamespaceDef);
+	aBuffer.PositionL( bufferPosition + size );
+	return *namespaceDef;
+	}
+
+
+//////////////////
+//  TMdCSchema  //
+//////////////////
+
+EXPORT_C TMdCSchema::TMdCSchema() : TMdCSerializationType( EMdCSchema )
+	{
+	}
+
+EXPORT_C void TMdCSchema::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCSchema::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+EXPORT_C const TMdCSchema& TMdCSchema::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCSchema* schema = (TMdCSchema*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (schema->iType != EMdCSchema)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCSchema!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCSchema) % 2 ? sizeof(TMdCSchema)+1 : sizeof(TMdCSchema);
+	aBuffer.PositionL( bufferPosition + size );
+	return *schema;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/common/src/mdcitem.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,151 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  common item object for MdE*
+*/
+
+#include "mdcitem.h"
+
+///////////////////
+//  TMdCObject
+///////////////////
+
+EXPORT_C TMdCObject::TMdCObject() : TMdCItem( EMdCObject )
+	{
+	}
+
+EXPORT_C void TMdCObject::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCObject::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCObject& TMdCObject::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCObject* object = (TMdCObject*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (object->iType != EMdCObject)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCObject!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCObject) % 2 ? sizeof(TMdCObject)+1 : sizeof(TMdCObject);
+	aBuffer.PositionL( bufferPosition + size );
+	return *object;
+	}
+
+///////////////////
+//  TMdCRelation
+///////////////////
+
+EXPORT_C TMdCRelation::TMdCRelation() : TMdCItem( EMdCRelation )
+	{
+	}
+
+EXPORT_C void TMdCRelation::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCRelation::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCRelation& TMdCRelation::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCRelation* relation = (TMdCRelation*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (relation->iType != EMdCRelation)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCRelation!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCRelation) % 2 ? sizeof(TMdCRelation)+1 : sizeof(TMdCRelation);
+	aBuffer.PositionL( bufferPosition + size );
+	return *relation;
+	}
+
+
+///////////////////
+//  TMdCEvent
+///////////////////
+
+EXPORT_C TMdCEvent::TMdCEvent() : TMdCItem( EMdCEvent )
+	{
+	}
+
+EXPORT_C void TMdCEvent::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCEvent::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCEvent& TMdCEvent::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCEvent* event = (TMdCEvent*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (event->iType != EMdCEvent)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCEvent!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCEvent) % 2 ? sizeof(TMdCEvent)+1 : sizeof(TMdCEvent);
+	aBuffer.PositionL( bufferPosition + size );
+	return *event;
+	}
+
+
+///////////////////
+//  TMdCProperty
+///////////////////
+
+EXPORT_C TMdCProperty::TMdCProperty() : TMdCSerializationType( EMdCProperty )
+	{
+	}
+
+EXPORT_C void TMdCProperty::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCProperty::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCProperty& TMdCProperty::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCProperty* property = (TMdCProperty*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (property->iType != EMdCProperty)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCProperty!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCProperty) % 2 ? sizeof(TMdCProperty)+1 : sizeof(TMdCProperty);
+	aBuffer.PositionL( bufferPosition + size );
+	return *property;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/common/src/mdcquery.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,268 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  common query and condition definitions for MdE*
+*/
+
+#include "mdcquery.h"
+
+
+/////////////////////
+//  TMdCCondition  //
+/////////////////////
+
+EXPORT_C const TMdCCondition& TMdCCondition::GetFromBufferL( 
+		CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCCondition* condition = (TMdCCondition*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	return *condition;
+	}
+
+
+//////////////////////////
+//  TMdCLogicCondition  //
+//////////////////////////
+
+EXPORT_C TMdCLogicCondition::TMdCLogicCondition() : TMdCCondition( EMdCLogicCondition )
+	{
+	}
+
+EXPORT_C void TMdCLogicCondition::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCLogicCondition::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCLogicCondition& TMdCLogicCondition::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCLogicCondition* logicCondition = (TMdCLogicCondition*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (logicCondition->iType != EMdCLogicCondition)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCLogicCondition!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCLogicCondition) % 2 ? sizeof(TMdCLogicCondition)+1 : sizeof(TMdCLogicCondition);
+	aBuffer.PositionL( bufferPosition + size );
+	return *logicCondition;
+	}
+
+
+///////////////////////////
+//  TMdCObjectCondition  //
+///////////////////////////
+
+EXPORT_C TMdCObjectCondition::TMdCObjectCondition() : TMdCCondition( EMdCObjectCondition )
+	{
+	}
+
+EXPORT_C void TMdCObjectCondition::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCObjectCondition::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCObjectCondition& TMdCObjectCondition::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCObjectCondition* objectCondition = (TMdCObjectCondition*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (objectCondition->iType != EMdCObjectCondition)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCObjectCondition!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCObjectCondition) % 2 ? sizeof(TMdCObjectCondition)+1 : sizeof(TMdCObjectCondition);
+	aBuffer.PositionL( bufferPosition + size );
+	return *objectCondition;
+	}
+
+
+//////////////////////////
+//  TMdCEventCondition  //
+//////////////////////////
+
+EXPORT_C TMdCEventCondition::TMdCEventCondition() : TMdCCondition( EMdCEventCondition )
+	{
+	}
+
+EXPORT_C void TMdCEventCondition::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCEventCondition::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCEventCondition& TMdCEventCondition::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCEventCondition* eventCondition = (TMdCEventCondition*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (eventCondition->iType != EMdCEventCondition)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCEventCondition!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCEventCondition) % 2 ? sizeof(TMdCEventCondition)+1 : sizeof(TMdCEventCondition);
+	aBuffer.PositionL( bufferPosition + size );
+	return *eventCondition;
+	}
+
+
+/////////////////////////////
+//  TMdCPropertyCondition  //
+/////////////////////////////
+
+EXPORT_C TMdCPropertyCondition::TMdCPropertyCondition() : TMdCCondition( EMdCPropertyCondition )
+	{
+	}
+
+EXPORT_C void TMdCPropertyCondition::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCPropertyCondition::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCPropertyCondition& TMdCPropertyCondition::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCPropertyCondition* propertyCondition = (TMdCPropertyCondition*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (propertyCondition->iType != EMdCPropertyCondition)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCPropertyCondition!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCPropertyCondition) % 2 ? sizeof(TMdCPropertyCondition)+1 : sizeof(TMdCPropertyCondition);
+	aBuffer.PositionL( bufferPosition + size );
+	return *propertyCondition;
+	}
+
+
+/////////////////////////////
+//  TMdCRelationCondition  //
+/////////////////////////////
+
+EXPORT_C TMdCRelationCondition::TMdCRelationCondition() : TMdCCondition( EMdCRelationCondition )
+	{
+	}
+
+EXPORT_C void TMdCRelationCondition::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCRelationCondition::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCRelationCondition& TMdCRelationCondition::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCRelationCondition* relationCondition = (TMdCRelationCondition*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (relationCondition->iType != EMdCRelationCondition)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCRelationCondition!"), KErrCorrupt ) );
+
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCRelationCondition) % 2 ? sizeof(TMdCRelationCondition)+1 : sizeof(TMdCRelationCondition);
+	aBuffer.PositionL( bufferPosition + size );
+	return *relationCondition;
+	}
+
+
+//////////////////////////
+//  TMdCSearchCriteria  //
+//////////////////////////
+
+EXPORT_C TMdCSearchCriteria::TMdCSearchCriteria() : TMdCSerializationType( EMdCSearchCriteria )
+	{
+	}
+
+EXPORT_C void TMdCSearchCriteria::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCSearchCriteria::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCSearchCriteria& TMdCSearchCriteria::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCSearchCriteria* searchCriteria = (TMdCSearchCriteria*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (searchCriteria->iType != EMdCSearchCriteria)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCSearchCriteria!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCSearchCriteria) % 2 ? sizeof(TMdCSearchCriteria)+1 : sizeof(TMdCSearchCriteria);
+	aBuffer.PositionL( bufferPosition + size );
+	return *searchCriteria;
+	}
+
+/////////////////////
+//  TMdCOrderRule  //
+/////////////////////
+
+EXPORT_C TMdCOrderRule::TMdCOrderRule() : TMdCSerializationType( EMdCOrderRule )
+	{
+	}
+
+EXPORT_C void TMdCOrderRule::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCOrderRule::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCOrderRule& TMdCOrderRule::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCOrderRule* orderRule = (TMdCOrderRule*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (orderRule->iType != EMdCOrderRule)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCOrderRule!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCOrderRule) % 2 ? sizeof(TMdCOrderRule)+1 : sizeof(TMdCOrderRule);
+	aBuffer.PositionL( bufferPosition + size );
+	return *orderRule;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/common/src/mdcresult.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,118 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  common item result definitions for MdE*
+*/
+
+#include "mdcresult.h"
+
+/////////////////
+//  TMdCItems  //
+/////////////////
+
+EXPORT_C TMdCItems::TMdCItems() : TMdCSerializationType( EMdCItems )
+	{
+	}
+
+EXPORT_C void TMdCItems::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCItems::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCItems& TMdCItems::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCItems* items = (TMdCItems*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (items->iType != EMdCItems)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCItems!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCItems) % 2 ? sizeof(TMdCItems)+1 : sizeof(TMdCItems);
+	aBuffer.PositionL( bufferPosition + size );
+	return *items;
+	}
+
+
+///////////////////
+//  TMdCItemIds  //
+///////////////////
+
+EXPORT_C TMdCItemIds::TMdCItemIds() : TMdCSerializationType( EMdCItemIds )
+	{
+	}
+
+EXPORT_C void TMdCItemIds::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCItemIds::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCItemIds& TMdCItemIds::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCItemIds* itemIds = (TMdCItemIds*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (itemIds->iType != EMdCItemIds)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCItemIds!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCItemIds) % 2 ? sizeof(TMdCItemIds)+1 : sizeof(TMdCItemIds);
+	aBuffer.PositionL( bufferPosition + size );
+	return *itemIds;
+	}
+
+
+//////////////////////
+//  TMdCItemCounts  //
+//////////////////////
+
+EXPORT_C TMdCItemCounts::TMdCItemCounts() : TMdCSerializationType( EMdCItemCount )
+	{
+	}
+
+EXPORT_C void TMdCItemCounts::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::SerializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C void TMdCItemCounts::DeserializeL(CMdCSerializationBuffer& aBuffer)
+	{
+	TMdCSerializationType::DeserializeL( aBuffer, sizeof(*this) );
+	}
+
+EXPORT_C const TMdCItemCounts& TMdCItemCounts::GetFromBufferL( CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt bufferPosition = aBuffer.Position();
+	TMdCItemCounts* itemCounts = (TMdCItemCounts*)(aBuffer.Buffer().Ptr() + bufferPosition);
+	if (itemCounts->iType != EMdCItemCount)
+		{
+		__ASSERT_DEBUG( EFalse, User::Panic( _L("No TMdCItemCounts!"), KErrCorrupt ) );
+	
+		User::Leave( KErrCorrupt );
+		}
+	const TInt size = sizeof(TMdCItemCounts) % 2 ? sizeof(TMdCItemCounts)+1 : sizeof(TMdCItemCounts);
+	aBuffer.PositionL( bufferPosition + size );
+	return *itemCounts;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/common/src/mdcserializationbuffer.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1113 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Serialize and deserialize data between client and server
+*
+*/
+
+// INCLUDE FILES
+#include <e32def.h>
+
+#include "mdcserializationbuffer.h"
+#include "mdcserializationtype.h"
+
+#ifdef _DEBUG
+#include <e32debug.h>
+_LIT( KCMdCSerializationBuffer, "CMdCSerializationBuffer" );
+
+enum TSerializedBufferType
+	{
+	ESerializedBufferTBool,
+	ESerializedBufferTInt8,
+	ESerializedBufferTUint8,
+	ESerializedBufferTInt16,
+	ESerializedBufferTUint16,
+	ESerializedBufferTInt32,
+	ESerializedBufferTUint32,
+	ESerializedBufferTUint,
+	ESerializedBufferTInt64,
+	ESerializedBufferTReal32,
+	ESerializedBufferTReal64,
+	ESerializedBufferTTime,
+	ESerializedBufferTText8,
+	ESerializedBufferTText16,
+	ESerializedBufferTMdCValueUnion,
+	ESerializedBufferTText, // DON'T USE, special case ONLY for ReceiveDesciptorLength
+	};
+#endif
+
+const TUint32 KRealRequiredSizeForTUint8  = CMdCSerializationBuffer::KRequiredSizeForTUint16 - CMdCSerializationBuffer::KRequiredSizeForTypeCheck;
+const TUint32 KRealRequiredSizeForTInt16  = CMdCSerializationBuffer::KRequiredSizeForTInt16 - CMdCSerializationBuffer::KRequiredSizeForTypeCheck;
+const TUint32 KRealRequiredSizeForTUint16 = CMdCSerializationBuffer::KRequiredSizeForTUint16 - CMdCSerializationBuffer::KRequiredSizeForTypeCheck;
+const TUint32 KRealRequiredSizeForTInt32  = CMdCSerializationBuffer::KRequiredSizeForTInt32 - CMdCSerializationBuffer::KRequiredSizeForTypeCheck;
+const TUint32 KRealRequiredSizeForTUint32 = CMdCSerializationBuffer::KRequiredSizeForTUint32 - CMdCSerializationBuffer::KRequiredSizeForTypeCheck;
+const TUint32 KRealRequiredSizeForTInt64  = CMdCSerializationBuffer::KRequiredSizeForTInt64 - CMdCSerializationBuffer::KRequiredSizeForTypeCheck;
+const TUint32 KRealRequiredSizeForTReal32 = CMdCSerializationBuffer::KRequiredSizeForTReal32 - CMdCSerializationBuffer::KRequiredSizeForTypeCheck;
+const TUint32 KRealRequiredSizeForTReal64 = CMdCSerializationBuffer::KRequiredSizeForTReal64 - CMdCSerializationBuffer::KRequiredSizeForTypeCheck;
+const TUint32 KRealRequiredSizeForTTime   = CMdCSerializationBuffer::KRequiredSizeForTTime - CMdCSerializationBuffer::KRequiredSizeForTypeCheck;
+
+// artificial types
+const TUint32 KRealRequiredSizeForEmptyText = CMdCSerializationBuffer::KRequiredSizeForEmptyText - CMdCSerializationBuffer::KRequiredSizeForTypeCheck;
+const TUint32 KRealRequiredSizeForTMdCValueUnion = CMdCSerializationBuffer::KRequiredSizeForTMdCValueUnion - CMdCSerializationBuffer::KRequiredSizeForTypeCheck;
+
+
+EXPORT_C TUint32 CMdCSerializationBuffer::RequiredSize( const TDesC8& aDes )
+	{
+	TInt desLength = aDes.Length();
+
+	if( KSerializedDesMaxLength < desLength )
+		{
+		desLength = KSerializedDesMaxLength;
+		}
+
+	// Required size for lenght of the descriptor, actual descriptor data and
+	// possible needed 1 byte padding
+	return KRequiredSizeForEmptyText
+	       + (desLength % 2 ? desLength + sizeof( KPadding8 ) : desLength) * KRealRequiredSizeForTUint8;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::RequiredSize( const TDesC16& aDes )
+	{
+	TInt desLength = aDes.Length();
+
+	if( KSerializedDesMaxLength < desLength )
+		{
+		desLength = KSerializedDesMaxLength;
+		}
+
+	// Required size for lenght of the descriptor and actual descriptor data
+	return KRequiredSizeForEmptyText + desLength * KRealRequiredSizeForTUint16;
+	}
+
+EXPORT_C CMdCSerializationBuffer* CMdCSerializationBuffer::NewL( TInt32 aSize )
+	{
+    CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( aSize );
+    CleanupStack::Pop( buffer );
+    return buffer;
+    }
+
+EXPORT_C CMdCSerializationBuffer* CMdCSerializationBuffer::NewLC( TInt32 aSize )
+	{
+    CMdCSerializationBuffer* buffer = new( ELeave ) CMdCSerializationBuffer();
+    CleanupStack::PushL( buffer );
+    buffer->ConstructL( aSize );
+    return buffer;
+	}
+
+EXPORT_C CMdCSerializationBuffer* CMdCSerializationBuffer::NewL( TUint8* aBuffer, TInt32 aSize )
+	{
+    CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( aBuffer, aSize );
+    CleanupStack::Pop( buffer );
+    return buffer;
+    }
+
+EXPORT_C CMdCSerializationBuffer* CMdCSerializationBuffer::NewLC( TUint8* aBuffer, TInt32 aSize )
+	{
+    CMdCSerializationBuffer* buffer = new( ELeave ) CMdCSerializationBuffer();
+    CleanupStack::PushL( buffer );
+    buffer->ConstructL( aBuffer, aSize );
+    return buffer;
+	}
+
+EXPORT_C CMdCSerializationBuffer* CMdCSerializationBuffer::NewLC( const RMessage2 &aMsg, TInt aIndex )
+	{
+	const TInt newDesLength = aMsg.GetDesLength( aIndex );
+	if ( newDesLength < 0 )
+		{
+		User::Leave( KErrBadDescriptor );
+		}
+
+    CMdCSerializationBuffer* buf = new (ELeave)CMdCSerializationBuffer(); 
+    CleanupStack::PushL(buf);
+    buf->ConstructL(newDesLength);
+	
+    TPtr8 bufferPtr(buf->Buffer());
+	aMsg.ReadL( aIndex, bufferPtr );
+
+	return buf;
+	}
+
+EXPORT_C CMdCSerializationBuffer* CMdCSerializationBuffer::NewL( const RMessage2 &aMsg, TInt aIndex )	
+	{
+	CMdCSerializationBuffer* buf = CMdCSerializationBuffer::NewLC(aMsg, aIndex);
+	CleanupStack::Pop(buf);
+	return buf;
+	}
+
+EXPORT_C CMdCSerializationBuffer* CMdCSerializationBuffer::NewLC( const CMdCSerializationBuffer& aBuffer )
+	{
+	const TInt newDesLength = aBuffer.Size();
+	CMdCSerializationBuffer* buf = CMdCSerializationBuffer::NewLC( newDesLength );
+	TPtr8 bufferPtr( buf->Buffer() );
+	bufferPtr.Copy( aBuffer.Buffer() );
+	return buf;
+	}
+
+EXPORT_C CMdCSerializationBuffer* CMdCSerializationBuffer::NewL( const CMdCSerializationBuffer& aBuffer )
+	{
+	CMdCSerializationBuffer* buf = CMdCSerializationBuffer::NewLC(aBuffer);
+	CleanupStack::Pop(buf);
+	return buf;
+	}
+
+CMdCSerializationBuffer::~CMdCSerializationBuffer()
+	{
+	delete iHeapBuffer;
+	}
+
+EXPORT_C TPtr8 CMdCSerializationBuffer::Buffer() const
+	{	
+	return iBuffer;
+	}
+
+EXPORT_C TPtr8* CMdCSerializationBuffer::BufferPtr() const
+	{
+	return (TPtr8*)&iBuffer;
+	}
+
+EXPORT_C const TPtr8* CMdCSerializationBuffer::BufferConstPtr() const
+	{
+	return &iBuffer;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::Size() const
+	{
+	return (TUint32)iBuffer.Length();
+	}
+
+EXPORT_C void CMdCSerializationBuffer::PositionL( TUint32 aPosition )
+	{
+	__ASSERT_DEBUG( aPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrTooBig ) );
+	__ASSERT_DEBUG( aPosition % 2 == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	
+	if( aPosition <= Size() )
+		{
+		iPosition = aPosition;
+		return;
+		}
+	else
+		{
+		User::Leave( KErrTooBig );
+		}
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::Position() const
+	{
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TBool aValue )
+	{
+	INSERTTYPE(ESerializedBufferTBool);
+	
+	TInt32 value = aValue;
+	return InsertL( value );
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TInt8 aValue )
+	{
+	INSERTTYPE(ESerializedBufferTInt8);
+	
+	TInt16 value = aValue;
+	return InsertL( value );
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TUint8 aValue )
+	{
+	INSERTTYPE(ESerializedBufferTUint8);
+	
+	TUint16 value = aValue;
+	return InsertL( value );
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TInt16 aValue )
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	INSERTTYPE(ESerializedBufferTInt16);
+
+	TInt16* ptr = (TInt16*)(iBuffer.Ptr() + iPosition);
+	
+	Mem::Copy(ptr, &aValue, sizeof(aValue));
+
+	iPosition += KRealRequiredSizeForTInt16;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TUint16 aValue )
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	INSERTTYPE(ESerializedBufferTUint16);
+
+	TUint16* ptr = (TUint16*)(iBuffer.Ptr() + iPosition);
+	
+	Mem::Copy(ptr, &aValue, sizeof(aValue));
+
+	iPosition += KRealRequiredSizeForTUint16;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TInt32 aValue )
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	INSERTTYPE(ESerializedBufferTInt32);
+
+	TInt32* ptr = (TInt32*)(iBuffer.Ptr() + iPosition);
+	
+	Mem::Copy(ptr, &aValue, sizeof(aValue));
+
+	iPosition += KRealRequiredSizeForTInt32;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TUint32 aValue )
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	INSERTTYPE(ESerializedBufferTUint32);
+
+	TUint32* ptr = (TUint32*)(iBuffer.Ptr() + iPosition);
+	
+	Mem::Copy(ptr, &aValue, sizeof(aValue));
+
+	iPosition += KRealRequiredSizeForTUint32;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TInt64 aValue )
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	INSERTTYPE(ESerializedBufferTInt64);
+
+	TInt64* ptr = (TInt64*)(iBuffer.Ptr() + iPosition);
+
+	Mem::Copy(ptr, &aValue, sizeof(aValue));
+
+	iPosition += KRealRequiredSizeForTInt64;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TUint aValue )
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	INSERTTYPE(ESerializedBufferTUint);
+
+	TUint* ptr = (TUint*)(iBuffer.Ptr() + iPosition);
+	
+	Mem::Copy(ptr, &aValue, sizeof(aValue));
+
+	iPosition += sizeof( TUint );
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TReal32 aValue )
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	INSERTTYPE(ESerializedBufferTReal32);
+
+	TReal32* ptr = (TReal32*)(iBuffer.Ptr() + iPosition);
+
+	Mem::Copy(ptr, &aValue, sizeof(aValue));
+
+	iPosition += KRealRequiredSizeForTReal32;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TReal64 aValue )
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	INSERTTYPE(ESerializedBufferTReal64);
+
+	TReal64* ptr = (TReal64*)(iBuffer.Ptr() + iPosition);
+	
+	Mem::Copy(ptr, &aValue, sizeof(aValue));
+
+	iPosition += KRealRequiredSizeForTReal64;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TTime aValue )
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	INSERTTYPE(ESerializedBufferTTime);
+
+	TInt64* ptr = (TInt64*)(iBuffer.Ptr() + iPosition);
+
+	TInt64 value = aValue.Int64();
+	
+	Mem::Copy(ptr, &value, sizeof(value));
+
+	iPosition += KRealRequiredSizeForTTime;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TDesC8& aValue )
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	INSERTTYPE(ESerializedBufferTText8);
+
+	const TInt desLength = aValue.Length();
+	
+	if( KSerializedDesMaxLength < desLength )
+		{
+		User::Leave( KErrTooBig );
+		}
+
+	TSerializedDesLength* ptr = (TSerializedDesLength*)(iBuffer.Ptr() + iPosition);
+
+	const TSerializedDesLength serDesLength = (TSerializedDesLength)desLength;
+	Mem::Copy( ptr, &serDesLength, sizeof( serDesLength ) );
+
+	iPosition += KRealRequiredSizeForEmptyText;
+
+	if( desLength == 0 )
+		{
+		return iPosition;
+		}
+
+	TUint8* bufPtr = (TUint8*)(iBuffer.Ptr() + iPosition);
+	
+	TPtrC8 desPtrC8 ((TUint8*)aValue.Ptr(), aValue.Length());
+	TUint8* desPtr = (TUint8*)desPtrC8.Ptr();
+
+	Mem::Copy( bufPtr, desPtr, desLength * sizeof( TUint8 ) );
+
+	iPosition += desLength * KRealRequiredSizeForTUint8;
+
+	// If position is odd, add padding and goto next even position
+	if( iPosition & 1 )
+		{
+		iPosition += sizeof( KPadding8 );
+		}
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TDesC16& aValue )
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	INSERTTYPE(ESerializedBufferTText16);
+
+	const TInt desLength = aValue.Length();
+	
+	if( KSerializedDesMaxLength < desLength )
+		{
+		User::Leave( KErrTooBig );
+		}
+
+	TSerializedDesLength* ptr = (TSerializedDesLength*)(iBuffer.Ptr() + iPosition);
+
+	const TSerializedDesLength serDesLength = (TSerializedDesLength)desLength;
+	Mem::Copy(ptr, &serDesLength, sizeof(serDesLength));
+
+	iPosition += KRealRequiredSizeForEmptyText;
+
+	if( desLength == 0 )
+		{
+		return iPosition;
+		}
+
+	TUint16* bufPtr = (TUint16*)(iBuffer.Ptr() + iPosition);
+
+	TPtrC16 desPtrC16 ((TUint16*)aValue.Ptr(), aValue.Length());
+	TUint16* desPtr = (TUint16*)desPtrC16.Ptr();
+
+	Mem::Copy(bufPtr, desPtr, desLength*sizeof(TUint16));
+
+	iPosition += desLength * KRealRequiredSizeForTUint16;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL( TMdCValueUnion& aValue )
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	INSERTTYPE(ESerializedBufferTMdCValueUnion);
+
+	TMdCValueUnion* ptr = (TMdCValueUnion*)(iBuffer.Ptr() + iPosition);
+
+	Mem::Copy(ptr, &aValue, sizeof(aValue));
+
+	iPosition += KRealRequiredSizeForTMdCValueUnion;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+
+	}
+EXPORT_C TUint32 CMdCSerializationBuffer::InsertL(TMdCSerializationType& aValue,
+		TUint32 aSize)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	void* ptr = (void*)(iBuffer.Ptr() + iPosition);
+
+	TMdCSerializationType* value = &aValue;
+
+	Mem::Copy(ptr, value, aSize);
+
+	iPosition += aSize;
+
+	// If position is odd, add padding and goto next even position
+	if( iPosition & 1 )
+		{
+		iPosition += sizeof( KPadding8 );
+		}
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TBool& aDestination)
+	{
+	CHECKTYPE(ESerializedBufferTBool);
+
+	TInt32 value;
+	ReceiveL(value);
+	aDestination = value ? ETrue : EFalse;
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TInt8& aDestination)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTInt8);
+
+	TInt16 value;
+	ReceiveL(value);
+	aDestination = (TInt8)value;
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TUint8& aDestination)
+	{
+	CHECKTYPE(ESerializedBufferTUint8);
+
+	TUint16 value;
+	ReceiveL(value);
+	aDestination = (TUint8)value;
+	return iPosition;
+	}
+	
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TInt16& aDestination)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTInt16);
+
+	TInt16* ptr = (TInt16*)(iBuffer.Ptr() + iPosition);
+
+	Mem::Copy(&aDestination, ptr, sizeof(aDestination));
+
+	iPosition += KRealRequiredSizeForTInt16;
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TUint16& aDestination)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTUint16);
+
+	TUint16* ptr = (TUint16*)(iBuffer.Ptr() + iPosition);
+
+	Mem::Copy(&aDestination, ptr, sizeof(aDestination));
+
+	iPosition += KRealRequiredSizeForTUint16;
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TInt32& aDestination)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTInt32);
+
+	TInt32* ptr = (TInt32*)(iBuffer.Ptr() + iPosition);
+
+	Mem::Copy(&aDestination, ptr, sizeof(aDestination));
+
+	iPosition += KRealRequiredSizeForTInt32;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TUint32& aDestination)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTUint32);
+
+	TUint32* ptr = (TUint32*)(iBuffer.Ptr() + iPosition);
+
+	Mem::Copy(&aDestination, ptr, sizeof(aDestination));  
+	
+	aDestination = *ptr;
+
+	iPosition += KRealRequiredSizeForTUint32;
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TInt64& aDestination)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTInt64);
+
+	TInt64* ptr = (TInt64*)(iBuffer.Ptr() + iPosition);
+
+	Mem::Copy(&aDestination, ptr, sizeof(aDestination));
+
+	iPosition += KRealRequiredSizeForTInt64;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TUint& aDestination)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTUint);
+
+	TUint* ptr = (TUint*)(iBuffer.Ptr() + iPosition);
+
+	Mem::Copy(&aDestination, ptr, sizeof(aDestination));
+
+	iPosition += sizeof( TUint );
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TReal32& aDestination)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTReal32);
+
+	TReal32* ptr = (TReal32*)(iBuffer.Ptr() + iPosition);
+
+	Mem::Copy(&aDestination, ptr, sizeof(aDestination));
+
+	iPosition += KRealRequiredSizeForTReal32;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TReal64& aDestination)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTReal64);
+
+	TReal64* ptr = (TReal64*)(iBuffer.Ptr() + iPosition);
+
+	Mem::Copy(&aDestination, ptr, sizeof(aDestination));
+
+	iPosition += KRealRequiredSizeForTReal64;
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TTime& aDestination)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTTime);
+
+	TInt64* ptr = (TInt64*)(iBuffer.Ptr() + iPosition);
+
+	TInt64 value;
+	Mem::Copy(&value, ptr, sizeof(value));
+
+	aDestination = value;
+
+	iPosition += KRealRequiredSizeForTInt64;
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TMdCValueUnion& aDestination)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTMdCValueUnion);
+
+	TMdCValueUnion* ptr = (TMdCValueUnion*)(iBuffer.Ptr() + iPosition);
+
+	Mem::Copy(&aDestination, ptr, sizeof(aDestination));
+
+	iPosition += KRealRequiredSizeForTMdCValueUnion;
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TMdCSerializationType& aDestination,
+		TUint32 aSize)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	void* ptr = (void*)(iBuffer.Ptr() + iPosition);
+
+	TMdCSerializationType* value = &aDestination;
+
+	Mem::Copy(value, ptr, aSize);
+
+	iPosition += aSize;
+
+	// If position is odd, add padding and goto next even position
+	if( iPosition & 1 )
+		{
+		iPosition += sizeof( KPadding8 );
+		}
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+
+EXPORT_C TSerializedDesLength CMdCSerializationBuffer::ReceiveDesciptorLength() const
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	TSerializedDesLength* ptr = (TSerializedDesLength*)(iBuffer.Ptr() + KRequiredSizeForTypeCheck + iPosition);
+
+	TSerializedDesLength desLength;
+	Mem::Copy(&desLength, ptr, sizeof(desLength));
+
+	return desLength;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TDes8& aDestination)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTText8);
+
+	TSerializedDesLength* ptr = (TSerializedDesLength*)(iBuffer.Ptr() + iPosition);
+
+	TSerializedDesLength desLength;
+	Mem::Copy(&desLength, ptr, sizeof(desLength));
+
+	iPosition += KRealRequiredSizeForEmptyText;
+
+	TUint8* bufPtr = (TUint8*)(iBuffer.Ptr() + iPosition);
+
+	aDestination.SetLength( desLength );
+
+	TPtrC8 desPtrC8((TUint8*)aDestination.Ptr(), aDestination.Length());
+	TUint8* desPtr = (TUint8*)desPtrC8.Ptr();
+
+	Mem::Copy(desPtr, bufPtr, desLength*sizeof(TUint8));
+
+	iPosition += desLength * KRealRequiredSizeForTUint8;
+
+	// If position is odd, add padding and goto next even position
+	if( iPosition & 1 )
+		{
+		iPosition += sizeof( KPadding8 );
+		}
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C TUint32 CMdCSerializationBuffer::ReceiveL(TDes16& aDestination)
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTText16);
+
+	TSerializedDesLength* ptr = (TSerializedDesLength*)(iBuffer.Ptr() + iPosition);
+
+	TSerializedDesLength desLength;
+	Mem::Copy(&desLength, ptr, sizeof(desLength));
+
+	iPosition += KRealRequiredSizeForEmptyText;
+
+	TUint16* bufPtr = (TUint16*)(iBuffer.Ptr() + iPosition);
+
+	aDestination.SetLength( desLength );
+
+	TPtrC16 desPtrC16((TUint16*)aDestination.Ptr(), aDestination.Length());
+	TUint16* desPtr = (TUint16*)desPtrC16.Ptr();
+
+	Mem::Copy(desPtr, bufPtr, desLength*sizeof(TUint16));
+
+	iPosition += desLength * KRealRequiredSizeForTUint16;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return iPosition;
+	}
+
+EXPORT_C HBufC8* CMdCSerializationBuffer::ReceiveDes8L()
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTText8);
+
+	TSerializedDesLength* ptr = (TSerializedDesLength*)(iBuffer.Ptr() + iPosition);
+
+	TSerializedDesLength desLength;
+	Mem::Copy(&desLength, ptr, sizeof(desLength));
+
+	iPosition += KRealRequiredSizeForEmptyText;
+	
+	if( desLength == 0 )
+		{
+		return NULL;
+		}
+	
+	TUint8* bufPtr = (TUint8*)(iBuffer.Ptr() + iPosition);
+	
+	HBufC8* desBuf = HBufC8::NewL( desLength );
+	desBuf->Des().SetLength( desLength );
+	
+	TPtrC8 desPtrC8((TUint8*)desBuf->Ptr(), desBuf->Length());
+	TUint8* desPtr = (TUint8*)desPtrC8.Ptr();
+
+	Mem::Copy(desPtr, bufPtr, desLength*sizeof(TUint8));
+
+	iPosition += desLength * KRealRequiredSizeForTUint8;
+
+	if( iPosition & 1 )
+		{
+		iPosition += sizeof( KPadding8 );
+		}
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return desBuf;
+	}
+
+EXPORT_C HBufC16* CMdCSerializationBuffer::ReceiveDes16L()
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTText16);
+
+	TSerializedDesLength* ptr = (TSerializedDesLength*)(iBuffer.Ptr() + iPosition);
+
+	TSerializedDesLength desLength;
+	Mem::Copy(&desLength, ptr, sizeof(desLength));
+
+	iPosition += KRealRequiredSizeForEmptyText;
+	
+	if( desLength == 0 )
+		{
+		return NULL;
+		}
+	
+	TUint16* bufPtr = (TUint16*)(iBuffer.Ptr() + iPosition);
+	
+	HBufC16* desBuf = HBufC16::NewL( desLength );
+	desBuf->Des().SetLength( desLength );
+
+	TPtrC16 desPtrC16((TUint16*)desBuf->Ptr(), desBuf->Length());
+	TUint16* desPtr = (TUint16*)desPtrC16.Ptr();
+
+	Mem::Copy(desPtr, bufPtr, desLength*sizeof(TUint16));
+
+	iPosition += desLength * KRealRequiredSizeForTUint16;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	
+	return desBuf;
+	}
+
+EXPORT_C TPtrC8 CMdCSerializationBuffer::ReceivePtr8L()
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTText8);
+
+	TSerializedDesLength* ptr = (TSerializedDesLength*)(iBuffer.Ptr() + iPosition);
+
+	TSerializedDesLength desLength;
+	Mem::Copy(&desLength, ptr, sizeof(desLength));
+
+	iPosition += KRealRequiredSizeForEmptyText;
+
+	TPtrC8 bufPtr8((const TUint8*)(iBuffer.Ptr() + iPosition), (TInt)desLength);
+
+	iPosition += desLength * KRealRequiredSizeForTUint8;
+
+	if( iPosition & 1 )
+		{
+		iPosition += sizeof( KPadding8 );
+		}
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+
+	return bufPtr8;
+	}
+
+EXPORT_C TPtrC16 CMdCSerializationBuffer::ReceivePtr16L()
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	CHECKTYPE(ESerializedBufferTText16);
+
+	TSerializedDesLength* ptr = (TSerializedDesLength*)(iBuffer.Ptr() + iPosition);
+
+	TSerializedDesLength desLength;
+	Mem::Copy(&desLength, ptr, sizeof(desLength));
+
+	iPosition += KRealRequiredSizeForEmptyText;
+
+	TPtrC16 bufPtr16((const TUint16*)(iBuffer.Ptr() + iPosition), (TInt)desLength);
+
+	iPosition += desLength * KRealRequiredSizeForTUint16;
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+
+	return bufPtr16;
+	}
+
+CMdCSerializationBuffer::CMdCSerializationBuffer() 
+	: iHeapBuffer( NULL ), iBuffer( NULL, 0 ), iPosition( 0 )
+	{
+	}
+
+void CMdCSerializationBuffer::ConstructL( TInt32 aSize )
+	{
+   	if(aSize < 0)
+		{
+		User::Leave( KErrBadDescriptor );
+		}	
+	
+    iHeapBuffer = HBufC8::NewL( aSize );
+	iHeapBuffer->Des().SetLength( aSize );
+
+    iBuffer.Set( iHeapBuffer->Des() );
+
+#ifdef _DEBUG
+    // for testing initilize to 0x99
+    TUint8* ptr = (TUint8*)(iBuffer.Ptr());
+    for(TInt32 i = 0; i < aSize; i++)
+    	{
+    	ptr[i] = 0x99;
+    	}
+#endif
+	}
+
+void CMdCSerializationBuffer::ConstructL( TUint8* aBuffer, TInt32 aSize )
+	{
+   	if(aSize < 0)
+		{
+		User::Leave( KErrBadDescriptor );
+		}	
+	
+    iBuffer.Set( aBuffer, aSize, aSize );
+	}
+
+#ifdef _DEBUG
+void CMdCSerializationBuffer::InsertTypeL( TUint16 aType )
+	{
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	TUint16* ptr = (TUint16*)(iBuffer.Ptr() + iPosition);
+	
+	Mem::Copy(ptr, &aType, sizeof(aType));
+
+	iPosition += KRealRequiredSizeForTUint16;
+	
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+	}
+
+void CMdCSerializationBuffer::CheckTypeL( TUint16 aType )
+	{
+	_LIT( KErrDescription, "Incorrect types!" );
+	TUint16 type;
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+
+	TUint16* ptr = (TUint16*)(iBuffer.Ptr() + iPosition);
+
+	Mem::Copy(&type, ptr, sizeof(type));
+
+	iPosition += KRealRequiredSizeForTUint16;
+
+	__ASSERT_DEBUG( (iPosition & 1) == 0, User::Panic( KCMdCSerializationBuffer, KErrCorrupt ) );
+	__ASSERT_DEBUG( iPosition <= Size(), User::Panic( KCMdCSerializationBuffer, KErrOverflow ) );
+
+	
+	if ( aType == ESerializedBufferTText && (type == ESerializedBufferTText8 || type == ESerializedBufferTText16) )
+		{
+		aType = type;
+		}
+
+#ifdef _DEBUG
+	if (type != aType)
+		{
+		RDebug::Print( _L("Incorrect serialization buffer types, actual: %S, wanted: %S, position: %u"),
+				&GetPropertyName(type), &GetPropertyName(aType), iPosition );
+		}
+#endif
+	__ASSERT_DEBUG( type == aType, User::Panic( KErrDescription, KErrArgument ) );
+	}
+
+const TDesC& CMdCSerializationBuffer::GetPropertyName( TUint16 aType )
+	{
+	_LIT( KSerializeTBool, "TBool" );
+	_LIT( KSerializeTInt8, "TInt8" );
+	_LIT( KSerializeTUint8, "TUint8" );
+	_LIT( KSerializeTInt16, "TInt16" );
+	_LIT( KSerializeTUint16, "Uint16" );
+	_LIT( KSerializeTInt32, "TInt32" );
+	_LIT( KSerializeTUint32, "TUint32" );
+	_LIT( KSerializeTUint, "TUint" );
+	_LIT( KSerializeTInt64, "TInt64" );
+	_LIT( KSerializeTReal32, "TReal32" );
+	_LIT( KSerializeTReal64, "TReal64" );
+	_LIT( KSerializeTTime, "TTime" );
+	_LIT( KSerializeTText8, "TText8" );
+	_LIT( KSerializeTText16, "TText16" );
+	_LIT( KSerializeTMdCValueUnion, "TMdCValueUnion" );
+
+	switch (aType)
+		{
+		case ESerializedBufferTBool:
+			return KSerializeTBool;
+		case ESerializedBufferTInt8:
+			return KSerializeTInt8;
+		case ESerializedBufferTUint8:
+			return KSerializeTUint8;
+		case ESerializedBufferTInt16:
+			return KSerializeTInt16;
+		case ESerializedBufferTUint16:
+			return KSerializeTUint16;
+		case ESerializedBufferTInt32:
+			return KSerializeTInt32;
+		case ESerializedBufferTUint32:
+			return KSerializeTUint32;
+		case ESerializedBufferTUint:
+			return KSerializeTUint;
+		case ESerializedBufferTInt64:
+			return KSerializeTInt64;
+		case ESerializedBufferTReal32:
+			return KSerializeTReal32;
+		case ESerializedBufferTReal64:
+			return KSerializeTReal64;
+		case ESerializedBufferTTime:
+			return KSerializeTTime;
+		case ESerializedBufferTText8:
+			return KSerializeTText8;
+		case ESerializedBufferTText16:
+			return KSerializeTText16;
+		case ESerializedBufferTMdCValueUnion:
+			return KSerializeTMdCValueUnion;
+		default:
+			User::Panic( _L("Unknown serialization type!"), KErrNotFound );
+		}
+	return KSerializeTText16;
+	}
+#endif
Binary file metadataengine/data/200009F3.txt has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/data/2000717d.rss	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+// 2000717D.RSS
+
+#include "RegistryInfoV2.rh"
+
+// Declares info for one test implementation
+RESOURCE REGISTRY_INFO theInfo
+	{
+	
+  // resource_format_version must always be set as follows
+  resource_format_version = RESOURCE_FORMAT_VERSION_2;
+	
+	// UID for the DLL 0x2000717D
+	dll_uid = 0x2000717D;
+	// Declare array of interface info
+	interfaces = 
+		{
+		INTERFACE_INFO
+			{
+			// UID of interface that is implemented  0x20000A17
+			interface_uid = 0x20000A17;
+			implementations = 
+				{
+				// Info for TextSearcherPlugin 0x20000A18;
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x20000A18;
+					version_no = 1;
+					display_name = "Text Searcher plugin";
+					default_data = "";
+					opaque_data = "";
+                    rom_only = 0;
+					}
+				};
+			}
+		};
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/data/Create_STUB_SIS.bat	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,17 @@
+rem
+rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+rem All rights reserved.
+rem This component and the accompanying materials are made available
+rem under the terms of "Eclipse Public License v1.0"
+rem which accompanies this distribution, and is available
+rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+rem
+rem Initial Contributors:
+rem Nokia Corporation - initial contribution.
+rem
+rem Contributors:
+rem
+rem Description:
+rem
+
+makesis -s MetadataEngine_Stub.pkg MetadataEngine_Stub.sis
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/data/MdS_Server_settings.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,11 @@
+<!DOCTYPE Feature SYSTEM "CT_XMLData.dtd">
+<Feature Name="Metadata Server 2.5 settings" Plugin="CRPlugin" Group="MdS 2.5" Desc="">
+	<Settings>
+		<Setting Name="Metadata Server major version" Key="0x1" Type="Int" ref="Variant/MdS/MajorVrsion" Desc="">2</Setting>
+		<Setting Name="Metadata Server minor version" Key="0x2" Type="Int" ref="Variant/MdS/MinorVersion" Desc="">5</Setting>
+    </Settings>
+	<Rules>
+		<CenRepfile Name1="\epoc32\data\z\private\10202BE9\200009F3.txt">1</CenRepfile>
+		<Ibyfile Name1="\epoc32\rom\include\S60Cenrep_variant.iby">1</Ibyfile>
+	</Rules>
+</Feature>
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/data/MetadataEngine_Stub.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+; Languages
+&EN
+
+; Header
+#{"Metadata Engine"}, (0x200009F1), 1, 0, 0, TYPE=SA
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+;Files
+""-"z:\sys\bin\mdeclient.dll"
+""-"z:\sys\bin\mdccommon.dll"
+""-"z:\sys\bin\mdsserver.exe"
\ No newline at end of file
Binary file metadataengine/data/MetadataEngine_Stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/data/defaultimportfile.mde	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,11 @@
+object http://sw.nokia.com/MdE Album "defaultalbum_favourites" 0
+property Type 2
+property LastModifiedDate 20080101000000
+property CreationDate 20080101000000
+property ItemType "application/vnd.nokia.mde.album"
+
+object http://sw.nokia.com/MdE Album "defaultalbum_captured" 0
+property Type 3
+property LastModifiedDate 20080101000000
+property CreationDate 20080101000000
+property ItemType "application/vnd.nokia.mde.album"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/data/metadataengine.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Metadata Engine"},(0x200009F1),1,0,0, TYPE=SA, RU
+
+; Localised vendor name
+%{"Nokia"}
+
+; Unique vendor name
+:"Nokia"
+
+;Files
+"\EPOC32\RELEASE\ARMV5\UREL\mdeclient.dll" -"!:\sys\bin\mdeclient.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\mdccommon.dll" -"!:\sys\bin\mdccommon.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\mdsserver.exe" -"!:\sys\bin\mdsserver.exe"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/data/schema.mde	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,264 @@
+//
+// NOTES:
+// 1. "//" at the beginning means a comment for the rest of the line
+// 2. There is the difference between using small and capital letters
+//    so it means that "Video" and "video" are not the same
+// 3. Layout of schema should looks like this:
+//    namespace_1
+//       ...
+//    namespace_n
+//     object_1
+//      property_1
+//        ...
+//      property_n
+//     object_2
+//      property_1
+//        ...
+//      property_n
+//    namespace_n+1
+//       ...
+//    namespace_n+n
+//     object_1
+//      property_1
+//        ...
+//      property_n
+//     object_2
+//      property_1
+//        ...
+//      property_n
+//    namespace_n+n+n .........
+//
+// VERSION: (OPTIONAL)
+// version <number>
+//    <number>   = version number in format major_version.minor_version
+//
+// NAMESPACE:
+// ----------------
+// namespace   <name> <readonly>
+//    <name>     = any string
+//    <readonly> = if true, it is prohibited to add new items into this namespace
+//
+//
+// OBJECT DEF:
+// ----------------
+// object   <namespace> <name> <parent> <flags>
+//    <namespace> = name of namespace
+//    <name>      = any string
+//    <parent>    = name of the parent
+//    <flags>     = object definition's flags
+//                  0 = no flags
+//                  1 = removable, object is removed when all relations pointing to it are removed
+//
+//
+// PROPERTY DEF:
+// ----------------
+// property   <name> <readonly> <mandatory> <type> <minv> <maxv> [<indexed>]
+//    <name>      = any string
+//    <readonly>  = if true, users are not allowed to modify this value once written
+//    <mandatory> = if true, this property is mandatory
+//    <type>      = datatype of the property, numeric value (see table below)
+//    <minv>      = minimum value of the property (format depends on type)
+//    <maxv>      = maximum value of the property (format depends on type)
+//	  <indexed>   = flag indicating should this property be indexed (optional, only for text properties)
+//                  1 = create an index for this property
+//
+//    THERE ARE DEFINED min AND max VALUE, WHICH ALWAYS SET CORRECT VALUE FOR ITS TYPE
+//
+//    EPropertyBool     = 0,   min/max = no effect (always set internal to 0 and 1)
+//    EPropertyInt8     = 1,   min/max = numeric values
+//    EPropertyUint8    = 2,   min/max = numeric values
+//    EPropertyInt16    = 3,   min/max = numeric values
+//    EPropertyUint16   = 4,   min/max = numeric values
+//    EPropertyInt32    = 5,   min/max = numeric values
+//    EPropertyUint32   = 6,   min/max = numeric values
+//    EPropertyInt64    = 7,   min/max = numeric values
+//    EPropertyReal32   = 8,   min/max = numeric values
+//    EPropertyReal64   = 9,   min/max = numeric values
+//    EPropertyTime     = 10,  min/max = Time format: YYYYMMDDhhmmss (for instance 20050629163021)
+//    EPropertyText     = 11,  min/max = numeric values, indicating minimum and maximum length of string 
+//                                       (minimum and maximum values must be between 1 and 65535)
+//
+// RELATION DEF:
+// ----------------
+// relationdef <namespace> <name>
+//    <namespace> = name of namespace
+//    <name>      = any string
+//
+// EVENT DEF:
+// ----------------
+// eventdef <namespace> <name> <priority>
+//    <namespace> = name of namespace
+//    <name>      = any string
+//    <priority>  = event priority, numeric value
+//
+//
+
+version 2.0
+
+
+namespace http://sw.nokia.com/MdE 0
+
+
+object http://sw.nokia.com/MdE Location Object 1
+property   CellID                         0    0        6    min   max
+property   LocationAreaCode               0    0        6    min   max
+property   Speed                          0    0        8    min   max
+property   Direction                      0    0        8    min   max
+property   Quality                        0    0        8    min   max
+property   Latitude                       0    0        9    min   max
+property   Longitude                      0    0        9    min   max
+property   Altitude                       0    0        9    min   max
+property   CountryCodeStr                 0    0        11   min   max
+property   NetworkCodeStr                 0    0        11   min   max
+property   Satellites                     0    0        11   min   max
+property   Country                        0    0        11   min   max
+property   CellName                       0    0        11   min   max
+
+
+object http://sw.nokia.com/MdE Calendar Object 1
+property   CalendarType                   0    0        2    min   max
+property   LocalUid                       0    0        6    min   max
+property   StartTime                      0    0        10   min   max
+property   EndTime                        0    0        10   min   max
+property   Location                       0    0        11   min   max
+property   vCalendar                      0    0        11   min   max
+
+
+object http://sw.nokia.com/MdE Contact Object 1
+property   Number                         0    0        11   min   max
+property   EmailAddress                   0    0        11   min   max
+property   Company                        0    0        11   min   max
+property   JobTitle                       0    0        11   min   max
+property   Address                        0    0        11   min   max
+property   ContactURL                     0    0        11   min   max
+property   vCard                          0    0        11   min   max
+
+
+object http://sw.nokia.com/MdE Message Object 0
+property   Received                       0    0        0    min   max
+property   ToWhom                         0    0        11   min   max
+property   Sender                         0    0        11   min   max
+
+
+object http://sw.nokia.com/MdE Album Object 0
+property   Ordered                        0    0        0    min   max
+property   Type                           0    0        4    min   max
+
+
+object http://sw.nokia.com/MdE Tag Object 0
+
+
+object http://sw.nokia.com/MdE MediaObject Object 0
+property   Protected                      0    0        0    min   max
+property   DRM                            0    0        0    min   max
+property   ThumbnailPresent               0    0        0    min   max
+property   Resized                        0    0        0    min   max
+property   Sample                         0    0        0    min   max
+property   Rating                         0    0        2    min   max
+property   Privacy                        0    0        4    min   max
+property   ResolutionUnit                 0    0        4    min   max
+property   Bitrate                        0    0        4    min   max
+property   Width                          0    0        4    min   max
+property   Height                         0    0        4    min   max
+property   Preinstalled                   0    0        5    min   max
+property   AccessCount                    0    0        6    min   max
+property   DownloadID                     0    0        6    min   max
+property   Duration                       0    0        8    min   max
+property   ReleaseDate                    0    0        10   min   max
+property   CaptureDate                    0    0        10   min   max
+property   Artist                         0    0        11   min   max 
+property   Author                         0    0        11   min   max
+property   Copyright                      0    0        11   min   max
+property   Legal                          0    0        11   min   max
+property   Description                    0    0        11   min   max
+property   Comment                        0    0        11   min   max
+property   Genre                          0    0        11   min   max 
+property   Track                          0    0        4    min   max
+property   AudioFourCC                    0    0        6    min   max
+
+
+object http://sw.nokia.com/MdE Video MediaObject 0
+property   AgeProfile                     0    0        5    min   max
+property   RecordingFlags                 0    0        6    min   max
+property   LastPlayPosition               0    0        8    min   max
+property   Framerate                      0    0        8    min   max
+property   AudioLanguage                  0    0        11   min   max
+
+
+object http://sw.nokia.com/MdE Image MediaObject 0
+property   Draft                          0    0        0    min   max
+property   FocalPlaneResolutionUnit       0    0        4    min   max
+property   ExposureProgram                0    0        4    min   max
+property   FocalLengthIn35mmFilm          0    0        4    min   max
+property   ISOSpeedRatings                0    0        4    min   max
+property   MeteringMode                   0    0        4    min   max
+property   WhiteBalance                   0    0        4    min   max
+property   Flash                          0    0        4    min   max
+property   ColourSpace                    0    0        4    min   max
+property   Orientation                    0    0        4    min   max
+property   SamplesPerPixel                0    0        4    min   max
+property   BitsPerSample                  0    0        4    min   max
+property   YCbCrPositioning               0    0        4    min   max
+property   ThumbCompression               0    0        4    min   max
+property   ThumbResolutionUnit            0    0        4    min   max
+property   ThumbOrientation               0    0        4    min   max
+property   FrameCount                     0    0        5    min   max
+property   PixelXDimension                0    0        6    min   max
+property   PixelYDimension                0    0        6    min   max
+property   ExifVersion                    0    0        6    min   max
+property   ComponentsConfiguration        0    0        6    min   max
+property   FlashPixVersion                0    0        6    min   max
+property   ThumbXResolution               0    0        6    min   max
+property   ThumbYResolution               0    0        6    min   max
+property   FocalPlaneXResolution          0    0        8    min   max
+property   FocalPlaneYResolution          0    0        8    min   max
+property   ExposureTime                   0    0        8    min   max
+property   ExposureBiasValue              0    0        8    min   max
+property   FNumber                        0    0        8    min   max
+property   FocalLength                    0    0        8    min   max
+property   ApertureValue                  0    0        8    min   max
+property   MaxAperture                    0    0        8    min   max
+property   ShutterSpeedValue              0    0        8    min   max
+property   XResolution                    0    0        8    min   max
+property   YResolution                    0    0        8    min   max
+property   DateTime                       0    0        10   min   max
+property   DateTimeDigitized              0    0        10   min   max
+property   DateTimeOriginal               0    0        10   min   max
+property   Model                          0    0        11   min   max
+property   Make                           0    0        11   min   max
+property   RelatedSoundFile               0    0        11   min   max
+
+
+object http://sw.nokia.com/MdE Audio MediaObject 0
+property   SamplingFrequency              0    0        8    min   max
+property   Album                          0    0        11   min   max 
+property   Composer                       0    0        11   min   max 
+property   OriginalArtist                 0    0        11   min   max
+property   AlbumArtist                    0    0        11   min   max
+
+
+object http://sw.nokia.com/MdE TrackLog Object 0
+property   Length                         0    0        6    min   max
+property   StartTime                      0    0        10   min   max
+property   StopTime                       0    0        10   min   max
+
+
+
+eventdef    http://sw.nokia.com/MdE   Created        1
+eventdef    http://sw.nokia.com/MdE   Deleted        1
+eventdef    http://sw.nokia.com/MdE   Opened         2
+eventdef    http://sw.nokia.com/MdE   Played         2
+eventdef    http://sw.nokia.com/MdE   Edited         2
+eventdef    http://sw.nokia.com/MdE   Sent           2
+eventdef    http://sw.nokia.com/MdE   Received       2
+
+
+
+relationdef    http://sw.nokia.com/MdE    Contains
+relationdef    http://sw.nokia.com/MdE    Replaces
+relationdef    http://sw.nokia.com/MdE    IsVersionOf
+relationdef    http://sw.nokia.com/MdE    Requires
+relationdef    http://sw.nokia.com/MdE    Uses
+relationdef    http://sw.nokia.com/MdE    References
+relationdef    http://sw.nokia.com/MdE    Summarises
+relationdef    http://sw.nokia.com/MdE    ContainsLocation
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+#include "../common/group/bld.inf"
+#include "../server/group/bld.inf"
+#include "../client/group/bld.inf"
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+../data/200009F3.txt /epoc32/data/z/private/10202BE9/200009F3.txt
+../data/200009F3.txt /epoc32/WINSCW/C/private/10202BE9/200009F3.txt
+../data/schema.mde 				/epoc32/winscw/c/private/200009F3/schema.mde
+../data/defaultimportfile.mde 	/epoc32/winscw/c/private/200009F3/defaultimportfile.mde
+mde_backup_registration.xml		/epoc32/winscw/c/private/200009F3/backup_registration.xml
+../data/schema.mde 				/epoc32/data/z/private/200009F3/schema.mde
+../data/defaultimportfile.mde 	/epoc32/data/z/private/200009F3/defaultimportfile.mde
+mde_backup_registration.xml		/epoc32/data/z/private/200009F3/backup_registration.xml
+
+../sis/metadataengine_stub.sis  /epoc32/data/z/system/install/metadataengine_stub.sis
+
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/group/mde_backup_registration.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,4 @@
+<?xml version="1.0" standalone="yes" ?>
+<backup_registration version="1.0">
+  <proxy_data_manager SID="0x10281E17" />
+</backup_registration>
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file
+*
+*/
+
+PRJ_PLATFORMS
+    DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+mdsserver.mmp
+
+PRJ_TESTMMPFILES
+
+PRJ_TESTEXPORTS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/group/mdsserver.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,100 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION           10.0
+TARGET            mdsserver.exe
+TARGETTYPE        exe
+UID               0x0 0x200009F3
+TARGETPATH	      SHARED_LIB_DIR
+
+EPOCSTACKSIZE     0x5000
+#ifdef WINS
+EPOCHEAPSIZE      0x4000 0x200000 
+#else
+EPOCHEAPSIZE      0x8000 0x400000 
+#endif
+
+CAPABILITY        CAP_SERVER AllFiles
+VENDORID        	VID_DEFAULT
+
+//MACRO             LOG_MASTER_FLAG
+MACRO             LOG_QUERY
+MACRO          	  LOG_DB
+// MACRO          LOG_MUTEX
+MACRO             LOG_SERVER
+
+SYSTEMINCLUDE     /epoc32/include/ecom
+SYSTEMINCLUDE	  /epoc32/include/connect
+USERINCLUDE       ../../../inc
+USERINCLUDE       ../inc
+
+SOURCEPATH        ../src
+SOURCE            mdsserver.cpp
+SOURCE            mdsserversession.cpp
+SOURCE            mdsmanipulationengine.cpp
+SOURCE            mdsfindengine.cpp
+SOURCE            mdsfindsequence.cpp
+SOURCE            mdssqliteconnection.cpp
+SOURCE            mdssqlobjectmanipulate.cpp
+SOURCE            mdssqldbmaintenance.cpp
+SOURCE            mdsmaintenanceengine.cpp
+SOURCE            mdsdbconnectionpool.cpp
+SOURCE            mdssqlfindoperation.cpp
+SOURCE            mdsclausebuffer.cpp
+SOURCE            mdsobjectlocklist.cpp
+SOURCE            mdsnotifier.cpp
+SOURCE            mdsnotifycomparator.cpp
+SOURCE            mdslogger.cpp
+SOURCE            mdsindexer.cpp
+SOURCE            mdsgarbagecollector.cpp
+SOURCE            mdsfindsqlclause.cpp
+SOURCE            mdsschema.cpp
+SOURCE            mdsimportexport.cpp
+SOURCE            mdsnamespacedef.cpp
+SOURCE            mdsitemdef.cpp
+SOURCE            mdsobjectdef.cpp
+SOURCE            mdspropertydef.cpp
+SOURCE            mdseventdef.cpp
+SOURCE            mdsrelationdef.cpp
+SOURCE            mdsdiskspacenotifier.cpp
+SOURCE            mdspreferences.cpp
+SOURCE            mdsgetimeiao.cpp
+SOURCE            mdsquerycriteriadeserialization.cpp
+SOURCE            mdebackuprestorewatcher.cpp
+SOURCE            mdsshutdownobserver.cpp
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY           euser.lib 
+LIBRARY           mdccommon.lib
+LIBRARY           sqldb.lib
+LIBRARY           efsrv.lib 
+LIBRARY           estor.lib
+LIBRARY           charconv.lib
+LIBRARY           bafl.lib
+LIBRARY		etel3rdparty.lib
+LIBRARY           flogger.lib
+LIBRARY           hash.lib
+LIBRARY			  inetprotutil.lib
+
+UNPAGED
+
+OPTION ARMCC -O3 -OTime
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdebackuprestoreobserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c)  Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Backup/restore observer interface
+*
+*/
+
+#ifndef __MDEBACKUPRESTOREOBSERVER_H__
+#define __MDEBACKUPRESTOREOBSERVER_H__
+
+class MMdEBackupRestoreObserver
+	{
+	public:
+		// Called when backup & restore watcher notices starting back up.
+		virtual void HandleBackup() = 0;
+		// Called when backup & restore watcher notices starting restore.
+		virtual void HandleRestore() = 0;
+		// Called when backup or watcher is completed and normal operation continues.
+		virtual void ResumeOperation() = 0;
+	};
+	
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdebackuprestorewatcher.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class for observing backup/restore events
+*
+*/
+
+#ifndef __MDEBACKUPRESTOREWATCHER_H__
+#define __MDEBACKUPRESTOREWATCHER_H__
+
+#include <e32base.h>
+#include <e32cmn.h>
+#include <e32property.h>
+
+#include "mdebackuprestoreobserver.h"
+
+class CMdEBackupRestoreWatcherAO : public CActive
+	{
+	public:
+		static CMdEBackupRestoreWatcherAO* NewL(MMdEBackupRestoreObserver& aObserver);
+
+		static CMdEBackupRestoreWatcherAO* NewLC(MMdEBackupRestoreObserver& aObserver);
+
+		virtual ~CMdEBackupRestoreWatcherAO();
+
+	private: // private methods
+		CMdEBackupRestoreWatcherAO(MMdEBackupRestoreObserver& aObserver);
+		void ConstructL();
+		
+		/**
+	    * RunL from CActive
+		*/
+		void RunL();
+		 
+	    /**
+		* DoCancel from CActive
+		*/
+		void DoCancel();
+
+	    /**
+		* Run by active scheduler in case of an error.
+		* @param aError Code of the occurred error
+		* @return Error code after RunError().
+		*/
+		TInt RunError(TInt aError);
+
+	private: // private data
+		MMdEBackupRestoreObserver& iObserver;
+		RProperty iProperty;
+	};
+	
+#endif // __MDEBACKUPRESTOREWATCHER_H__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsclausebuffer.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,118 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A unicode des buffer with automatic memory*
+*/
+
+#ifndef __MDSCLAUSEBUFFER_H__
+#define __MDSCLAUSEBUFFER_H__
+
+// INCLUDE FILES
+#include <e32base.h>
+
+
+/**
+ * An automatic clause buffer class. The class provides Descriptor 
+ * functionality, plus automatic memory handling so that it reserves
+ * the required space automatically as the size grows.
+ */
+class CMdsClauseBuffer: public CBase
+    {
+    public: // public definitions
+
+        /**
+         * Static constructor
+         * @param aInitialSize size of the buffer
+         * @return buffer instance
+         */
+        IMPORT_C static CMdsClauseBuffer* NewL( TInt aInitialSize );
+
+        /**
+         * Static constructor
+         * @param aInitialSize size of the buffer
+         * @return buffer instance
+         */
+        IMPORT_C static CMdsClauseBuffer* NewLC( TInt aInitialSize );
+
+        virtual ~CMdsClauseBuffer();
+
+    private:
+
+        /**
+         * Default constructor
+         */
+        CMdsClauseBuffer();
+
+        /**
+         * 2nd phase constructor
+         * @param aInitialSize size of the buffer
+         */
+        void ConstructL( TInt aInitialSize );
+
+    public:
+
+        /**
+         * Appends a descriptor at the end of this descriptor.
+         * Increases the size of the descriptor if needed.
+         * @param aDes descriptor which is appended
+         */
+        void AppendL( const TDesC16& aDes );
+
+        /**
+         * Appends a descriptor at the end of this descriptor.
+         * Increases the size of the descriptor if needed.
+         * @param aDes descriptor which is appended
+         * @param aAdditionl 
+         */
+        void AppendL( const TDesC16& aDes, const TInt aAdditional );
+
+        /**
+         * Makes sure the buffer max size is AT LEAST given required bytes.
+         * @param aRequired required buffer total size
+         * @return ETrue if the buffer was re-allocated
+         */
+        TBool ReserveSpaceL( TInt aRequired );
+    
+        /**
+         * Return buffer.
+         * 
+         * @return buffer
+         * 
+		 * @leave KErrNotFound Buffer is NULL.
+         */
+        TPtr BufferL() const;
+        
+        /**
+         * Return const reference to buffer.
+         * 
+         * @return const reference to buffer
+         * 
+		 * @leave KErrNotFound Buffer is NULL.
+         */
+        const TDesC& ConstBufferL() const;
+        
+    private:
+
+        /**
+         * The heap buffer
+         */
+        HBufC* iBuffer;
+
+        /**
+         * Current size of the buffer
+         */
+        TInt iCurrentBufSize;
+    };
+
+
+#endif // __MDSCLAUSEBUFFER_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsdbconnectionpool.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A pool of database connections
+*
+*/
+
+#ifndef __DBCONNECTIONPOOL_H__
+#define __DBCONNECTIONPOOL_H__
+
+#include <e32base.h>
+
+class CMdSSqLiteConnection;
+
+
+/**
+ * A pool that handles interthread use of shared
+ * database connections.
+ * Current implementation uses only one shared
+ * connection
+ */
+class MMdSDbConnectionPool
+    {
+    public: // Constructors and destructor
+
+        static void SetDefaultDB( CMdSSqLiteConnection* aConnection );
+        static CMdSSqLiteConnection& GetDefaultDBL();
+    private:
+    	friend class CMdSMaintenanceEngine;
+        static void DisconnectAll();
+        static void ConnectAllL();
+
+
+    private: // Member data
+        
+        static CMdSSqLiteConnection* iConnection;
+        static TBool iDBValid;
+    };
+
+
+#endif	// __DBCONNECTIONPOOL_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsdiskspacenotifier.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,160 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is disk space notifier for Metadata server.*
+*/
+
+#ifndef __MDSDISKSPACENOTIFIER_H__
+#define __MDSDISKSPACENOTIFIER_H__
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <f32file.h>
+
+/**
+* MMdSDiskSpaceNotifierObserver
+* Observer interface for a disk space notifier.
+*/
+class MMdSDiskSpaceNotifierObserver
+	{
+	public :
+		enum TDiskSpaceDirection
+			{
+			/** Disk space is larger than threshold level */
+			EMore,
+
+			/** Disk space is smaller than threshold level */
+			ELess
+			};
+
+		/**
+		 * Called to notify the observer that disk space has crossed the specified threshold value.
+		 *
+		 * @param aCrossDirection threshold cross direction
+		 */
+		virtual void HandleDiskSpaceNotificationL(TDiskSpaceDirection aDiskSpaceDirection) = 0;
+
+		/**
+		 * Called to if disk space notifier has an error situation.
+		 *
+		 * @param aError error code
+		 */
+		virtual void HandleDiskSpaceError(TInt aError) = 0;
+	};
+
+/**
+* CMSDiskSpaceNotifierAO.
+* A disk space notifier class
+*/
+class CMdSDiskSpaceNotifierAO : public CActive
+    {
+    public:
+    	enum TDiskSpaceNotifierState
+    		{
+    		ENormal,
+    		EIterate
+    		};
+
+    public : // Constructors and destructors
+	    /**
+	     * Constructs a disk space notifier implementation.
+	     *
+	     * @param aThreshold minimum free disk space threshold level in bytes
+	     * @param aFilename filename which defines monitored drive's number
+	     * @return  metadata server implementation
+	     */
+        static CMdSDiskSpaceNotifierAO* NewL(
+        	MMdSDiskSpaceNotifierObserver& aObserver, 
+        	TInt64 aThreshold, const TDesC& aFilename);
+
+	    /**
+	     * Constructs a disk space notifier implementation and leaves it
+	     * in the cleanup stack.
+	     *
+	     * @param aThreshold minimum free disk space threshold level in bytes
+	     * @param aFilename filename which defines monitored drive's number
+	     * @return  metadata server implementation
+	     */
+        static CMdSDiskSpaceNotifierAO* NewLC(        
+        	MMdSDiskSpaceNotifierObserver& aObserver, 
+        	TInt64 aThreshold, const TDesC& aFilename);
+
+	    /**
+	    * Destructor.
+	    */
+        virtual ~CMdSDiskSpaceNotifierAO();
+
+        TBool DiskFull() const;
+
+    protected: // Functions from base classes
+        /**
+         * From CActive
+         * Callback function.
+         * Invoked to handle responses from the server.
+         */
+        void RunL();
+
+        /**
+         * From CActive
+         * Handles errors that occur during notifying the observer.
+         */
+        TInt RunError(TInt aError);
+
+        /**
+         * From CActive
+         * Cancels any outstanding operation.
+         */
+        void DoCancel();
+
+    private: // Constructors and destructors
+
+        /**
+         * constructor
+         */
+        CMdSDiskSpaceNotifierAO(
+        	MMdSDiskSpaceNotifierObserver& aObserver,
+        	TInt64 aThreshold, TDriveNumber aDrive);
+
+        /**
+         * 2nd phase constructor
+	     * @param aThreshold minimum free disk space threshold level in bytes
+	     * @param aDrive monitored drive's number
+         */
+        void ConstructL();
+
+    private: // New methods
+
+		void StartNotifier();
+
+		static TDriveNumber GetDriveNumberL( const TDesC& aFilename );
+
+    private: // Data
+
+        MMdSDiskSpaceNotifierObserver& iObserver;
+        
+        RFs iFileServerSession;
+        
+        const TInt64 iThreshold;
+        
+        const TDriveNumber iDrive;
+        
+        TDiskSpaceNotifierState iState;
+        
+        TInt iIterationCount;
+        
+        TBool iDiskFull;
+    };
+
+#endif // __CMDSSERVER_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdseventdef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,113 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one event definition
+*
+*/
+
+#ifndef __MDSEVENTDEF_H__
+#define __MDSEVENTDEF_H__
+
+#include "mdsitemdef.h"
+
+
+/**
+ *  Metadata eventdef class
+ *
+ *  This class is responsible for holding information one event
+ *
+ */
+class CMdsEventDef : public CMdsItemDef
+    {
+    friend class CMdsNamespaceDef;
+public:
+	/**
+	 * Create new event object
+	 * @param aId id of event
+	 * @param aName name of event
+	 * @param aPriority priority of event
+	 * @return pointer to new created event
+	 */
+    static CMdsEventDef* NewL( const TDesC& aName, const TInt32 aPriority );
+
+	/**
+	 * Create new event object
+	 * @param aId id of event
+	 * @param aName name of event
+	 * @param aPriority priority of event
+	 * @return pointer to new created event
+	 */
+    static CMdsEventDef* NewLC( const TDesC& aName, const TInt32 aPriority );
+
+    /**
+     * Stores event definition to DB
+     * @param aNamespaceDefId namespace definition
+     * @param aConnection connection to database
+     */
+ 	void StoreToDBL( const TInt aNamespaceDefId );
+
+ 	/**
+ 	 * Destructor
+ 	 */
+    virtual ~CMdsEventDef();
+
+	TBool operator==( const CMdsEventDef& aEventDef ) const;
+
+	inline TBool operator!=( const CMdsEventDef& aEventDef ) const;
+
+	/**
+	 * Get object priority
+	 * @return object priority
+	 */
+	inline TInt32 GetPriority() const;
+
+    /**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+    TUint32 RequiredBufferSize();
+
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling) and return new position of serialized buffer.
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    TMdCOffset SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreeSpace);
+
+private:
+	/**
+	 * Default constructor
+	 */
+    inline CMdsEventDef()
+    	{}
+
+	/**
+	 * 2nd phase construction
+	 * @param aName name of event
+	 * @param aPriority priority of event
+	 */
+    void ConstructL( const TDesC& aName, TInt32 aPriority );
+
+private: // data
+	
+	/**
+	 * event priority
+	 */
+	TInt32 iPriority;
+    };
+
+#include "mdseventdef.inl"
+    
+#endif // __MDSEVENTDEF_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdseventdef.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one event definition
+*
+*/
+
+
+inline TBool CMdsEventDef::operator!=( const CMdsEventDef& aEventDef ) const
+	{
+	return !( *this == aEventDef );
+	}
+
+/**
+ * Get object priority
+ * @return object priority
+ */
+inline TInt32 CMdsEventDef::GetPriority() const
+	{
+	return iPriority;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsfindengine.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,208 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is find engine to manage object searching,*
+*/
+
+#ifndef __MDSFINDENGINE_H__
+#define __MDSFINDENGINE_H__
+
+#include <e32base.h>
+
+#include "mdscommoninternal.h"
+
+// FORWARD DECLARATIONS
+class CMdSFindSequence;
+class CMdSServerSession;
+class CMdSObjectLockList;
+class CMdCSerializationBuffer;
+class CMdsSchema;
+class CMdSServer;
+
+// CLASS DECLARATION
+/**
+* CMdSFindEngine.
+*  Class for searching objects from metadata database.
+*/
+class CMdSFindEngine : public CBase
+    {
+    public: // Constructors and destructors
+
+        /**
+        * NewL.
+        * Two-phased constructor.
+        * @param aQueryId query id
+        * @param aParent the session back reference
+        * @param aLockList list of locked objects
+        * @param aSchemaNew schema reference
+        * 
+        * @return Pointer to created CMdSFindEngine object.
+        */
+        static CMdSFindEngine* NewL(
+        	TUint32 aQueryId, 
+            CMdSServerSession& aParent,
+            CMdSObjectLockList& aLockList,
+            CMdsSchema& aSchemaNew);
+
+        /**
+        * NewLC.
+        * Two-phased constructor.
+        * @param aQueryId query id
+        * @param aParent the session back reference
+        * @param aLockList list of locked objects
+        * @param aSchemaNew schema reference
+        * @return Pointer to created CMdSFindEngine object.
+        */
+        static CMdSFindEngine* NewLC(
+        	TUint32 aQueryId, 
+            CMdSServerSession& aParent,
+            CMdSObjectLockList& aLockList,
+            CMdsSchema& aSchemaNew);
+
+        /**
+        * 2nd phase constructor
+        */
+        void ConstructL( CMdsSchema& aSchema );
+
+        /**
+        * ~CMdSFindEngine.
+        * Destructor.
+        */
+        virtual ~CMdSFindEngine();
+
+    public:
+
+	    /**
+	    * Returns query's ID
+	    * @return query ID
+	    */
+	    TUint32 QueryId();
+
+        /**
+        * Creates the result set and sets message pointer
+        * @param aMessage message for asynchronous client messaging
+        */
+        void CreateResultSet(RMessage2 aMessage);
+
+        /**
+        * Sets parameters for the find. Ownership is transferred.
+        */
+        void SetFindParams( TUint32 aNotifyCount );
+
+        /**
+        * Sets serialized criteria buffer for the find. Ownership is transferred.
+        */
+        void SetFindCriteria( CMdCSerializationBuffer* aSerializedCriteria );
+
+	    /**
+	    * Initiates find
+	    * @param aUserLevel defines user's access rights
+	    * @return error code or KErrNone
+	    */
+        TInt FindL( TUserLevel aUserLevel );
+
+	    /**
+	    * Continues ongoing sync find
+        * @return error code or KErrNone
+	    */
+        TInt ContinueL();
+
+	    /** 
+	    * Initiates asynchronous find
+        * @param aUserLevel defines user's access rights
+	    */
+        void FindAsyncL( TUserLevel aUserLevel );
+
+	    /** 
+	    * Continues ongoing find
+	    */
+	    void ContinueAsync();
+
+	    /** 
+	    * Cancels find
+	    */
+        void Cancel( TInt aError );
+
+        /**
+        * Transfer result set to client
+        * @aError error code or KErrNone
+        */
+        void SetComplete( TInt aError );
+
+        /**
+        * Transfer results to client and completes find
+        * @aError error code or KErrNone
+        */
+        void FindComplete( TInt aError );
+
+		const CMdCSerializationBuffer& ResultsL() const;
+
+		/**
+		 * Locks query result objects.
+		 * @param aLockList list of objects that must be locked
+		 */
+		void LockFindResultObjectsL( CMdSObjectLockList& aLockList );
+
+		/**
+		 * Sets result mode.
+		 * @param aResultModeItems ETrue if result mode is item mode
+		 */
+		void SetResultMode( TBool aResultModeItems );
+
+	    /**
+	    * Returns whether find engine is complete or not.
+	    * Completed sequence can be safely delete.
+	    */
+		TBool IsComplete() const;
+
+	    /**
+	    * Returns whether find engine's query is complete or not.
+	    */
+		TBool IsQueryComplete();
+
+		CMdSServer& GetServer() const;
+
+    private: // Constructors and destructors
+
+        /**
+        * CMdSManipulationEngine.
+        * C++ default constructor.
+        * @param .
+        */
+        CMdSFindEngine(
+        	TUint32 aQueryId, 
+            CMdSServerSession& aParent,
+            CMdSObjectLockList& aLockList);
+
+    private: // Data
+    
+    	TUint32 iQueryId;
+
+        CMdSServerSession& iParent;
+
+        CMdSObjectLockList& iLockList;
+
+        CMdSFindSequence* iSequence;
+
+		CMdCSerializationBuffer* iSerializedCriteria;
+
+        RMessage2 iMessage;
+
+        TBool iAsyncPending;
+        
+        // if last query result was Items result
+        TBool iLastResultModeItems;
+
+    };
+
+#endif //__MDSFINDENGINE_H__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsfindsequence.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,266 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Manages object search from database using SQL,
+*
+*/
+
+#ifndef __MDSFINDSEQUENCE_H__
+#define __MDSFINDSEQUENCE_H__
+
+#include <e32base.h>
+#include <badesca.h>
+
+#include "mdscommoninternal.h"
+
+// FORWARD DECLARATIONS
+class CMdsSchema;
+class CMdSServer;
+class CMdSSqLiteConnection;
+class CMdSFindEngine;
+class CMdSSqlFindOperation;
+class CMdCSerializationBuffer;
+
+// CONSTANTS
+const TInt KFindSetReady = 1;
+
+/**
+* CMdSFindSequence.
+* Handles on sequence of find.
+* A sequence is a logical operation, which may consist
+* of several parallel physical operations from different
+* physical entities (tables)
+*/
+class CMdSFindSequence : public CActive
+    {
+    public: // Constructors and destructor
+
+        /**
+        * NewL.
+        * Two-phased constructor.
+        * @param aServer reference to server
+        * @param aSchema the schema
+        * @param aObserver reference to find engine observer
+        * @return Pointer to created CMdSManipulationEngine object.
+        */
+        static CMdSFindSequence* NewL( 
+        	CMdSServer& aServer, CMdsSchema& aSchema, CMdSFindEngine& aObserver );
+
+        /**
+        * NewLC.
+        * Two-phased constructor.
+        * @param aServer reference to server
+        * @param aSchema the schema
+        * @param aObserver reference to find engine observer
+        * @return Pointer to created CMdSManipulationEngine object.
+        */
+        static CMdSFindSequence* NewLC( 
+        	CMdSServer& aServer, CMdsSchema& aSchema, CMdSFindEngine& aObserver );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CMdSFindSequence();
+
+    private: // Private constructors
+
+        /**
+        * 2nd phase constructor
+        */
+        void ConstructL();
+
+        /**
+        * C++ default constructor.
+        * @param aServer reference to server
+        * @param aSchema the schema
+        * @param aObserve reference to find engine observer
+        */
+        CMdSFindSequence( 
+        	CMdSServer& aServer, CMdsSchema& aSchema, CMdSFindEngine& aObserve );
+
+    public:
+
+		void SetFindParams( TUint32 aNotifyCount );
+
+	    /**
+	    * Finds objects synchronously
+	    * @param aConnection database connection to use in find
+	    * @param aSerializedCriteria serialized criteria buffer
+	    * @param aUserLevel client's access level
+        * @return KErrNone or KSetReady
+	    */
+        TInt FindL( CMdCSerializationBuffer& aSerializedCriteria,
+            TUserLevel aUserLevel );
+
+	    /**
+	    * Continues ongoing synchronous find with the next set
+	    * @param aConnection database connection to use in find
+        * @return KErrNone or KSetReady
+	    */
+        TInt ContinueL();
+
+	    /**
+	    * Start Find objects asynchronously
+	    * @param aSerializedCriteria serialized criteria buffer
+	    */
+        void FindAsync( CMdCSerializationBuffer& aSerializedCriteria,
+            TUserLevel aUserLevel );
+
+	    /**
+	    * Continues ongoing asynchronous find with the next set
+	    */
+	    void ContinueAsync();
+
+	    /**
+	    * Returns whether find sequence is complete or not.
+	    * Completed sequence can be safely delete.
+	    */
+		TBool IsComplete() const;
+
+	    /**
+	    * Returns whether find sequence's query is complete or not.
+	    */
+		TBool IsQueryComplete() const;
+
+    public: // methods called by CMdSFindOperation
+
+        /** access to the schema */
+        const CMdsSchema& Schema() const;
+
+        /** access to the server */
+        CMdSServer& Server() const;
+
+        /** access to the result buffer */
+        CMdCSerializationBuffer& ResultsL() const;
+
+		void SetResultMode( TBool aResultModeItems );
+
+    protected: // From CActive
+
+        /**
+        * Handles an active object’s request completion event.
+        * CMdEFindSequence calls this methot by itself.
+        */
+        void RunL();
+
+        /**
+        * Handles a leave occurring in the RunL(). The active
+        * scheduler calls this function RunL() function leaves.
+        * @param aError leave code
+        * @return KErrNone. Returning any other value results
+        *  in the active scheduler function CActiveScheduler::Error()
+        *  being called.
+        */
+        TInt RunError( TInt aError );
+
+	    /**
+	    * Implementation of asynchronous loop canceling.
+        * calls Cancel method in FindOperation and then
+        * ExecuteL (or ContinueL) should finish pretty soon.
+	    */
+        void DoCancel();
+
+    protected: // Find sequence's new methods
+        /**
+        * creates the find operation
+        * @param aResults find results container
+        * @param aCriteria find criteria
+        * @param aRules find rules
+        * @param aConnection the database connection reserved for the find
+        * @return the created operation
+        */    
+        CMdSSqlFindOperation* CreateOperationLC(
+            CMdCSerializationBuffer& aSerializedCriteria );
+
+        /**
+        * creates the find operation
+        */
+        CMdSSqlFindOperation* CreateOperationL(
+            CMdCSerializationBuffer& aSerializedCriteria );
+
+		/**
+		 * Helper function for PostProcessL
+		 * return freetext which belongs to object(id)
+		 */
+		void GetFreeTextForObjectL( CDesCArray& aResultWordBuffer,
+				TDefId aNamespaceDefId, TItemId aObjectId );
+
+
+        /**
+        * Post-processing of found objects.
+        * This routine may launch sub-operations based on the results.
+        * @param aSerializedResultBuffer found objects serialized in buffer
+        */
+        void PostProcessL( CMdCSerializationBuffer& aSerializedResultBuffer );
+
+        /**
+        * Deletes iFindOperation and iFindResults.
+        */
+        void CleanUp();
+
+	private:
+
+		/**
+		* Sort objects by free text hit count if no text search plug-in found
+		* @param aFreeTextArray array which contains all free texts in criteria 
+		* @param aObjGroup found object by criterias
+		*/
+		TUint32 GetFreeTextHitCountL(const CDesCArray& aObjectFreeText, 
+				const RPointerArray<HBufC>& aSearchFreeText);
+
+    private:
+
+    	/**
+    	 * server
+    	 */
+    	CMdSServer& iServer;
+
+        /**
+         * the schema 
+         */
+        CMdsSchema& iSchema;
+
+		TUint32 iNotifyCount;
+
+        /**
+        * the find results
+        */
+        CMdCSerializationBuffer* iFindResults;
+        
+        /**
+        * Serialized criteria buffer. Not owned by CMdSFindSequence.
+        */        
+        CMdCSerializationBuffer* iSerializedCriteria;
+
+        /**
+        * asynchronous operation observer
+        */
+        CMdSFindEngine* iObserver;
+
+        /**
+        * Database connection for asynchronous use
+        */
+        CMdSSqlFindOperation* iFindOperation;
+
+		TDesC8* iFindSqlClauseBuffer;
+
+        // if last query result was Items result
+        TBool iLastResultModeItems;
+
+        // client application's user level
+        TUserLevel iUserLevel;
+	};
+
+
+#endif //__MDSFINDSEQUENCE_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsfindsqlclause.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,476 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Constructs SQL clauses for object find*
+*/
+
+#ifndef __MDSFINDSQLCLAUSE_H__
+#define __MDSFINDSQLCLAUSE_H__
+
+#include <e32base.h>
+#include <badesca.h>
+
+#include "mdccommon.h"
+#include "mdssqliteconnection.h"
+
+// FORWARD DECLARATIONS
+class CMdCSerializationBuffer;
+class CMdsSchema;
+class CMdsNamespaceDef;
+class CMdsObjectDef;
+class CMdsClauseBuffer;
+class CMdsPropertyDef;
+class TMdCSearchCriteria;
+class TMdCRelationCondition;
+
+// CLASS DECLARATION
+/**
+* CMdSFindSqlClause.
+* Class constructs SQL search clauses.
+*/
+class CMdSFindSqlClause : public CBase
+    //public MMdSFindCriteria
+    {
+    private:
+		enum TAppendIn
+		{
+			EAppendInFalse,
+			EAppendInTrue,
+			EAppendInRelationLeft,
+			EAppendInRelationRight
+		};
+
+		enum TRangeValueType
+		{
+			EInt32RangeValue,
+			EUint32RangeValue,
+			EInt64RangeValue
+		};
+		
+    public: // Constructors and destructor
+
+        /**
+        * NewL.
+        * Two-phased constructor.
+        * @param aSchema reference to metadata server's internal schema.
+        * @return Pointer to created CMdSFindEngine object.
+        */
+        static CMdSFindSqlClause* NewL(CMdsSchema& aSchema);
+
+        /**
+        * NewLC.
+        * Two-phased constructor.
+        * @param aSchema reference to metadata server's internal schema.
+        * @return Pointer to created CMdSManipulationEngine object.
+        */
+        static CMdSFindSqlClause* NewLC(CMdsSchema& aSchema);
+
+        /**
+        * Destructor.
+        */
+        virtual ~CMdSFindSqlClause();
+
+    private: // Private constructors
+
+        /**
+        * CMdSSqlClause.
+        * C++ default constructor.
+        * @param aSchema reference to metadata server's internal schema.
+        */
+        CMdSFindSqlClause(CMdsSchema& aSchema);
+
+        /**
+        * ConstructL.
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+    public: // Public functions
+
+	    /**
+	    * Constructs criteria the LONG way. ALL criteria and rule params
+	    * are taken in account.
+	    * @param aSerializedCriteria search criteria in serialized form.
+	    * @param aUserLevel
+	    */
+        void CreateL( 
+        	CMdCSerializationBuffer& aSerializedCriteria,
+        	TUserLevel aUserLevel );
+
+        /**
+	    * Returns the decoded value as some kind of textual description
+	    * @return search clause as TDesC8 descriptor
+	    */
+        const TDesC& AsTextL() const;
+
+        /**
+        * Returns constructed variable stack.
+	    * @return clause variables.
+        */
+        RRowData& Variables();
+
+        /**
+        * Returns constructed result row stack.
+	    * @return clause variables.
+        */
+        RRowData& ResultRow();
+
+        /**
+        * Returns limit count.
+	    * @return limit.
+        */
+		TUint32 Limit();
+
+		/**
+		* Does SQL clause include freetext count and total length
+		* @return SQL clause includes freetext count and total length
+		*/
+		TBool IncludesFreetexts();
+
+        /**
+        * Returns object query's object definition.
+        * @return Object definition if query is object query else NULL.
+        */
+        CMdsObjectDef* ObjectDef();
+
+        /**
+        * Returns object query's property denitions used in property filter.
+        * @return Object definition if query is object query else NULL.
+        */
+        RPointerArray<CMdsPropertyDef>& PropertyFilters();
+
+        /**
+        * Returns query's namespace definition.
+        * @return Namespace definition if NULL query buffer is corrupted.
+        */
+        CMdsNamespaceDef* NamespaceDef();
+
+        /**
+        * Returns query type.
+        * @return Query type
+        */
+        TQueryType QueryType();
+
+        /**
+        * Returns query result mode.
+        * @return Query result mode
+        */
+        TQueryResultMode ResultMode();
+
+        /**
+         * Returns query freetext array
+         * @return freetext array
+         */
+        RPointerArray<HBufC>& QueryFreeText();
+
+        /**
+         * Result objects are not locked
+         * @return object locking status
+         */
+        TBool NoObjectLocking();
+        
+    private: // Private functions
+
+        /**
+        * appends an array of OR'ed aColumn=ID conditions.
+        * @param aColumn A column of variable set where id is appended
+        * @param aSet container of item ids
+        */
+        void AppendArrayL( /*const TDesC& aColumn, const RArray<TItemId>& aSet*/ );
+
+		void AppendPropertyFiltersL( TBool aDistinct = EFalse );
+
+        /**
+        * Creates "SELECT column list FROM table name" SQL clause query
+        * based on iType.
+        */
+        void AppendSelectStatementL();
+
+        /**
+        * Creates "SELECT count(*) FROM table name" SQL clause query
+        * based on iType.
+        */
+        void AppendSelectCountStatementL();
+        
+        /**
+        * Creates "SELECT * FROM table name" SQL clause query
+        * based on iType.
+        */
+        void AppendSelectAllFromEventStatementL();
+        
+        void AppendSelectAllFromRelationStatementL();
+        
+        void AppendSelectEventItemStatementL();
+        
+        void AppendSelectRealtionItemStatementL();
+        
+        /**
+        * Creates "SELECT DISTINCT "wanted property's column" FROM table name" 
+        * SQL clause query based on iType.
+        */
+        void AppendSelectDistinctStatementL();
+
+		void AppendSelectObjectItemStatementL();
+
+		void AppendSelectObjectIdStatementL();
+		
+		void AppendFromForObjectL();
+
+	    void AppendFromForEventL();
+		
+		void AppendFromForRelationL();
+		
+		/**
+		* Creates "WHERE(...)"
+		*/
+		void AppendWhereStatementL();
+
+        /**
+        * Helper which creates "SELECT statement for object query.
+        */
+        void AppendSelectForObjectL();
+
+        /**
+        * Helper which creates "SELECT statement for relation query.
+        * @param aRules find rules
+        */
+        void AppendSelectForRelationL( /*const TMdCFolder& aRules*/ );
+
+        /**
+        * Helper which creates "SELECT statement for event query.
+        * @param aRules find rules
+        */
+        void AppendSelectForEventL( /*const TMdCFolder& aRules*/ );
+
+        /**
+        * Help method for where clause parsing and is used recursively.
+        */
+        void WhereStatementL();
+
+		void ConditionStatementL(TBool aNegated = EFalse, TAppendIn aAppendIdIn = EAppendInTrue);
+
+		void AppendObjectIdL();
+		
+		void AppendIdInL();
+
+        /**
+        * Help method for appending logic condition.
+        * @param aNegated is condition negated
+        */
+		void AppendLogicConditionL(TBool aNegated, TAppendIn aAppendIdIn = EAppendInTrue);
+
+        /**
+        * Help method for appending object condition.
+        * @param aNegated is condition negated
+        */
+		void AppendObjectConditionL(TBool aNegated);
+
+		/**
+		 * Help method for appending range.
+		 * @param aRangeValueType type of range's values
+		 */
+		void AppendRangeL(TRangeValueType aRangeValueType);
+
+        /**
+        * Help method for appending property condition.
+        *
+        * @param aNegated is condition negated
+        */
+		void AppendPropertyConditionL(TBool aNegated);
+
+		/** 
+		 * Helper method for getting object definition for property condition.
+		 * 
+		 * @param aObjectDefId property condition's object definition
+		 * 
+		 * @return object definition for query
+		 */
+		TDefId ObjectDefForPropertyCondition(TDefId aObjectDefId);
+		
+        /**
+        * Help method for appending property range condition.
+        *
+        * @param aNegated is condition negated
+        */
+		void AppendPropertyRangeConditionL(TBool aNegated);
+
+        /**
+        * Help method for appending property text condition.
+        * @param aNegated is condition negated
+        */
+		void AppendPropertyTextConditionL(TBool aNegated);
+
+        /**
+        * Help method for appending property bool condition.
+        * @param aNegated is condition negated
+        */
+		void AppendPropertyBoolConditionL(TBool aNegated);
+
+        /**
+        * Help method for appending event condition for object query.
+        * @param aNegated is condition negated
+        */
+		void AppendEventConditionL(TBool aNegated);
+
+        /**
+        * Help method for appending relation condition for object query.
+        * @param aNegated is condition negated
+        */
+		void AppendRelationConditionL(TBool aNegated);
+
+		void AppendRelationSideConditionL(TBool aRelationConditions, 
+				const TMdCRelationCondition& aRelationCondition, 
+				TBool aLeftSide, TUint32 aRelationObjectConditionOffset);
+
+        /**
+        * Help method for searching object definition's table,
+        * based on object definition's ID, and appending those to buffer.
+        * @param aObjectDefId object definition's ID
+        */
+		void AppendTableByObjectDefIdL(TDefId aObjectDefId);
+
+        /**
+        * Help method for searching property definition's column,
+        * based on property definition's ID, and appending those to buffer.
+        * @param aPropertyDefId property definition's ID
+        * @param aObjectDefId object definition's ID
+        * @param aResult append property to expected result row
+        */
+		void AppendColumnByPropertyDefIdL(TDefId aPropertyDefId, TDefId aObjectDefId = KNoDefId, TBool aResult = EFalse);
+
+        /**
+        * Help method which appends GROUP BY statements.
+        */
+        void AppendGroupByL();
+
+        /**
+        * Help method which appends ORDER BY statements.
+        */
+        void AppendOrderByL();
+
+        /**
+        * Help method which appends LIMIT and OFFSET.
+        */
+        void AppendLimitAndOffsetL();
+
+        /** 
+        * Help method that copies the rightmost part of the variables to
+        * RowData. The function does not cut or remove any data but doubles
+        * a number of variables.
+        * @param aStart index of the first variable to be copied.
+        * @param aEnd index of the last variable to be copied.
+        */
+        void CopyVariablesL( TInt aStart, TInt aEnd );
+
+    private: // Member data
+
+        /**
+        * variables used in the clause.
+        * Note: RRowData constructor cannot leave, since it is initialized (aInStack==EFalse)
+        */
+        RRowData iVariables;
+
+        /**
+        * Expected result row from the clause.
+        * Note: RRowData constructor cannot leave, since it is initialized (aInStack==EFalse)
+        */
+        RRowData iResultRow;
+
+        /**
+        * Text buffer for whole query clause. CMdsClauseBuffer class takes care
+        * of memory allocation for buffer.
+        */
+        CMdsClauseBuffer* iQueryBuf;
+
+		/**
+		* Metadata Server's internal schema
+		*/
+		CMdsSchema& iSchema;
+
+		/**
+		* Serialized query critertia 
+		*/
+		TMdCSearchCriteria* iSearchCriteria;
+
+		/**
+		* Serialized query critertia 
+		*/
+		CMdCSerializationBuffer* iSerializedBuffer;       
+
+		/**
+		* Client application's user level
+		*/
+		TUserLevel iUserLevel;
+
+		/**
+		* Namespace definition where to search
+		*/
+		CMdsNamespaceDef* iNamespaceDef;
+
+        /**
+        * Object definition for where to (WHERE expression) search in object 
+        * queries
+        */
+        CMdsObjectDef* iObjectDef;
+
+        /**
+         * Object definition for what to (SELECT result and FROM table list) 
+         * search in object queries
+         */
+        CMdsObjectDef* iSourceObjectDef;
+
+        /**
+         * Object definitions IDs for what to (SELECT result and FROM table list) 
+         * search in object queries
+         */
+        RArray<TDefId>* iSourceObjectDefs;
+        
+        /**
+         * Append columns to result row (ETrue only for first ID from iSourceObjectDefs).
+         */
+        TBool iAppendToResultRow;
+        
+        /**
+        * Descriptor which contains namespace definition's ID in text format
+        */
+        TBuf16<16> iNamespaceIdDes;                
+        
+        /**
+        * Filter property definition references
+        */
+        RPointerArray<CMdsPropertyDef> iPropertyFilters;
+
+		/**
+		* Include freetexts to result.
+		*/
+		TBool iIncludeFreetexts;
+		
+		/**
+		* Include not present items to result.
+		*/
+		TBool iIncludeNotPresent;
+
+		/**
+		 * Free text which belong to query.
+		 */
+		RPointerArray<HBufC> iFreeText;
+		
+		/**
+		 * Result objects are not locked.
+		 */
+		TBool iNoObjectLocking;
+		
+		TBool iPlaceholdersOnly;
+        };
+
+#endif //__MDSFINDSQLCLAUSE_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsfindsqlclausedef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,246 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Includes predefined SQL clauses for usage of*
+*/
+
+#ifndef __MDSFINDSQLCLAUSEDEF_H__
+#define __MDSFINDSQLCLAUSEDEF_H__
+
+// ---------------------------------------------------------------------------
+// Misc definitions
+// ---------------------------------------------------------------------------
+//
+
+_LIT( KEmpty, "" );
+_LIT( KSpace, " " );
+_LIT( KLeftBracket, "(" );
+_LIT( KRightBracket, ")" );
+_LIT( KComma, "," );
+_LIT( KSemicolon, ";" );
+_LIT( KVariable, "?" );
+_LIT( KWildcard, "%" );
+_LIT( KEmptyTrue, "1" ); // used from always pass true tests
+
+_LIT( KCommaVariable, ",?" );
+
+_LIT( KNotIn, " NOT IN" );
+_LIT( KIn, " IN" );
+_LIT( KOrderBy, " ORDER BY " );
+_LIT( KNoCaseSensitive, " COLLATE NOCASE ");
+_LIT( KLimit, "LIMIT " );
+_LIT( KOffset, "OFFSET " );
+_LIT( KAsc, " ASC");
+_LIT( KDesc, " DESC" );
+
+_LIT( KIsNull,  " ISNULL" );
+_LIT( KNotNull, " NOTNULL" );
+
+_LIT( KUnion, " UNION " );
+_LIT( KIntersect, " INTERSECT " );
+
+_LIT( KUnionAll, " UNION ALL " );
+
+_LIT( KAsBoJoin, " AS BO JOIN " );
+
+_LIT( KBaseObjectObjectId, "BO.ObjectId" );
+_LIT( KObjectObjectId,     "O.ObjectId" );
+
+_LIT( KRelationId, "RelationId" );
+_LIT( KEventId,    "EventId" );
+
+_LIT( KSelectPropertyFilterBegin, "SELECT BO.ObjectId,BO.ObjectDefId,BO.Flags,BO.MediaId,BO.UsageCount,BO.GuidHigh,BO.GuidLow,BO.URI" );
+
+_LIT( KBaseObjectDot, "BO." );
+_LIT( KObjectDot,     "O." );
+
+_LIT( KGroupByObjectId, "GROUP BY BO.ObjectId " );
+
+// ---------------------------------------------------------------------------
+// Object flags
+// ---------------------------------------------------------------------------
+//
+
+_LIT( KGetFlagAnd, "(Flags&?)AND " );        // Flag is set
+_LIT( KGetNotFlagAnd, "(NOT Flags&?)AND " ); // Flag is not set
+
+_LIT( KGetNotFlag, "(NOT Flags&?) " );        // Flag is not set
+
+_LIT( KWhereNotFlag, "WHERE(NOT Flags&?)" ); // Flag is not set
+
+// ---------------------------------------------------------------------------
+// SELECT clauses
+// ---------------------------------------------------------------------------
+//
+
+_LIT( KSelect, "SELECT " );
+
+_LIT( KSelectCount, 
+	"SELECT count(*) "
+	);
+
+_LIT( KSelect1,
+	"SELECT 1 "
+	);
+
+_LIT( KSelectObjectIds,
+    "SELECT BO.ObjectId "
+    );
+
+_LIT( KSelectAllFromBaseObject, 
+	"SELECT BO.* "
+	);
+
+_LIT( KAllFromObject, 
+	",O.* "
+	);
+
+_LIT( KSelectFreeTextCountAndTotalLength, 
+	",count(D.Word),sum(length(D.Word)) "
+	);
+
+// distict queries
+_LIT( KSelectDistinct, 
+	"SELECT DISTINCT "
+	);
+
+_LIT( KSelectAllFrom, 
+	"SELECT * "
+	);
+
+_LIT( KSelectEventIds, 
+	"SELECT Event"
+	);
+
+_LIT( KDotEventId, 
+	".EventId "
+	);
+
+_LIT( KSelectRelationIds, 
+	"SELECT Relations"
+	);
+
+_LIT( KDotRelationId, 
+	".RelationId "
+	);
+
+
+// ---------------------------------------------------------------------------
+// FROM clauses
+// ---------------------------------------------------------------------------
+//
+
+_LIT( KFromBaseObject, 
+	"FROM Object"
+	);
+
+_LIT( KAsBaseObject, 
+	" AS BO "
+	);
+
+_LIT( KAsObjectOnEqual, 
+	" AS O ON BO.ObjectId=O.ObjectId "
+	);
+
+_LIT( KFreeTextLeftJoinBegin,
+	"LEFT JOIN TextSearchDictionary"
+	);
+
+_LIT( KFreeTextLeftJoinMiddle,
+	" AS D ON D.WordId IN(SELECT WordId FROM TextSearch"
+	);
+
+_LIT( KFreeTextLeftJoinEnd,
+	" WHERE BO.ObjectId=ObjectId) "
+	);
+
+_LIT( KFromEvent, 
+    "FROM Event"
+    );
+
+_LIT( KFromRealtions, 
+    "FROM Relations"
+    );
+
+// ---------------------------------------------------------------------------
+// WHERE statement and comparison operators
+// ---------------------------------------------------------------------------
+//
+_LIT( KWhere, "WHERE" );
+
+// Comparison operators
+_LIT( KEqual,          "=?" );
+_LIT( KNotEqual,       "!=?" );
+_LIT( KLess,           "<?" );
+_LIT( KLessOrEqual,    "<=?" );
+_LIT( KGreater,        ">?" );
+_LIT( KGreaterOrEqual, ">=?" );
+_LIT( KBetween,        " BETWEEN ? AND ?" );
+_LIT( KNotBetween,     " NOT BETWEEN ? AND ?" );
+_LIT( KLike,           " LIKE ?" );
+
+// Logic operators
+_LIT( KAnd,          "AND " );
+_LIT( KOr,           "OR "  );
+_LIT( KSpaceWithNot, " NOT" );
+_LIT( KNotWithSpace, "NOT " );
+_LIT( KNot, "NOT" );
+
+// Object conditions
+_LIT( KObjectIdEqual,       "ObjectId=?" );
+_LIT( KObjectIdIn,          "ObjectId IN" );
+_LIT( KObjectDefIdEqual,    "ObjectDefId=?" );
+_LIT( KObjectGuidEqual,     "(GuidHigh=? AND GuidLow=?)" );
+_LIT( KObjectUsageCount,    "UsageCount" );
+_LIT( KObjectUriEqual,      "URI=?" );
+_LIT( KObjectUriBeginsWith, "URI LIKE ?" );
+
+_LIT( KBaseObjectIdIn,    "BO.ObjectId IN" );
+_LIT( KBaseObjectIdNotIn, "BO.ObjectId NOT IN" );
+
+// Object searches
+_LIT( KSelectObjectIdFromBaseObject, "SELECT ObjectId FROM Object" );
+
+_LIT( KSelectObjectIdFrom, "SELECT ObjectId FROM " );
+
+// Freetext searches
+_LIT( KObjectFreeTextSearchStart,           "(ObjectId IN(SELECT ObjectID FROM TextSearch");
+_LIT( KObjectFreeTextSearchWhere,           " WHERE WordId IN(SELECT WordId FROM TextSearchDictionary");
+_LIT( KObjectFreeTextSearchDictionaryWhere, " WHERE Word" );
+_LIT( KObjectFreeTextSearchEnd,             ")))" );
+
+// Event searches
+_LIT( KSelectEventIdFromEvent,  "SELECT EventId FROM Event" );
+_LIT( KSelectObjectIdFromEvent, "SELECT ObjectId FROM Event" );
+_LIT( KEventObjectIdIn,         "ObjectId IN" );
+_LIT( KEventTimeStamp,          "TimeStamp" );
+_LIT( KEventIdEqual,            "EventId=?" );
+_LIT( KEventDefIdEqual,         "EventDefId=?" );
+_LIT( KEventSourceEqual,        "Source=?" );
+_LIT( KEventParticipantEqual,   "Participant=?" );
+
+// Relation searches
+_LIT( KSelectRelationIdFromRelation,    "SELECT RelationId FROM Relations" );
+_LIT( KSelectLeftObjectIdFromRelation,  "SELECT LeftObjectId FROM Relations" );
+_LIT( KSelectRightObjectIdFromRelation, "SELECT RightObjectId FROM Relations" );
+_LIT( KRelationIdEqual,                 "RelationId=?" );
+_LIT( KRelationIdIn,                  	"RelationId IN" );
+_LIT( KRelationDefIdEqual,              "RelationDefId=?" );
+_LIT( KRelationGuidEqual,               "GuidHigh=? AND GuidLow=?" );
+_LIT( KRelationParameter,               "Parameter" );
+_LIT( KRelationLastModifiedDate,        "LastModifiedDate" );
+_LIT( KRelationLeftObjectIdIn,          "LeftObjectId IN" );
+_LIT( KRelationRightObjectIdIn,         "RightObjectId IN" );
+
+
+#endif // __MDSFINDSQLCLAUSEDEF_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsgarbagecollector.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,86 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is garbage colletion class which sends*
+*/
+
+#ifndef _MDSGARBAGECOLLECTOR_H_
+#define _MDSGARBAGECOLLECTOR_H_
+
+#include <e32std.h>
+#include <e32base.h>
+
+class MMdSGarbageCollectorObserver
+	{
+	public:
+		/*
+		 * @return if the garbage collection need to be started again
+		 */
+		virtual TBool StartGarbageCollectionL() = 0;
+	};
+
+class CMdSGarbageCollector : public CActive
+{
+public:
+	virtual ~CMdSGarbageCollector();
+	/**
+	 * Two phase constructor.
+	 * @param aObserver an observer which will be notified when the garbage collector starts.
+	 * @return an instance of CMdSGarbageCollector
+	 */
+	static CMdSGarbageCollector* NewL(MMdSGarbageCollectorObserver& aObserver);
+	
+	/**
+	 * Two phase constructor.
+	 * @param aObserver an observer which will be notified when the garbage collector starts.
+ 	 * @return an instance of CMdSGarbageCollector
+	 */
+	static CMdSGarbageCollector* NewLC(MMdSGarbageCollectorObserver& aObserver);
+	
+	/**
+	 * Starts garbage connection with a delay. The same value will also be used as interval between
+	 * following garbage collections if the observer returns ETrue when StartGarbageCollectionL()
+	 * is called.
+	 * 
+	 * @param aDelay delay before garbage collection starts
+	 */
+	void Start( TInt aDelay );
+	
+	/**
+	 * Pauses garbage collection.
+	 */
+	void Pause();
+	
+	/**
+	 * Resumes garbage collection.
+	 */
+	void Resume();
+
+private:
+	CMdSGarbageCollector(MMdSGarbageCollectorObserver& aObserver);
+	void ConstructL();
+	
+	virtual void RunL();
+	virtual void DoCancel();
+	virtual TInt RunError( TInt aError );
+	
+private:
+	RTimer iTimer;
+
+	TTimeIntervalMicroSeconds32 iDelay;
+	TTimeIntervalMicroSeconds32 iNewDelay;
+
+	MMdSGarbageCollectorObserver& iObserver;
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsgetimeiao.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Helper class to get IMEI number. 
+*
+*/
+
+#ifndef _MDSGETIMEIAO_H_
+#define _MDSGETIMEIAO_H_
+
+#include <e32base.h>
+#include <etel3rdparty.h>
+
+
+class CMdsGetImeiAO: public CActive
+	{
+	private:
+		CTelephony *iTelephony;
+		CTelephony::TPhoneIdV1 iV1;	
+		TBuf<CTelephony::KPhoneSerialNumberSize> iImei;
+		CActiveSchedulerWait iAsw;
+	public:
+	   	virtual ~CMdsGetImeiAO();
+	   	static CMdsGetImeiAO* NewL();
+	   	static CMdsGetImeiAO* NewLC();
+		void GetIMEI(TDes &aImei);
+		TInt64 GetIMEI();
+
+		void DoCancel();
+
+		void RunL();
+
+	private:
+		CMdsGetImeiAO(): CActive(CActive::EPriorityStandard), iTelephony(NULL)
+		{}
+		void ConstructL();
+
+	};
+
+#endif //_MDSGETIMEIAO_H_
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsimportexport.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,526 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Metadata import/export metadata and schema files
+*
+*/
+
+#ifndef __MDSIMPORTEXPORT_H__
+#define __MDSIMPORTEXPORT_H__
+
+#include <e32base.h>
+#include <s32file.h>
+#include <flogger.h>
+
+#include "mdccommon.h"
+
+
+class CMdsNamespaceDef;
+class CMdsObjectDef;
+class CMdsRelationDef;
+class CMdsEventDef;
+class CCnvCharacterSetConverter;
+class CMdsClauseBuffer;
+class CMdsSchema;
+class CMdSSqlObjectManipulate;
+class CMdCSerializationBuffer;
+class CDesC16ArrayFlat;
+class RRowData;
+
+// declarations
+const TInt KMdsMaxLineLenght = 1024;
+const TInt KPropertyMinValue = 1;
+const TInt KPropertyMaxValue = 2;
+const TInt KPropertyDefValue = 3;
+
+/**
+ *  Metadata schema container within server
+ *
+ *  This class is responsible for read MDE schema file and store all
+ *  information into one memory place.
+ *
+ */
+class CMdsImportExport : public CBase
+    {
+//    friend class CMdsSchema;
+public:
+	/**
+	 * Create new SchemaImport class
+	 * @return new created class
+	 */
+    static CMdsImportExport* NewL();
+
+	/**
+	 * Create new SchemaImport class
+	 * @return new created class
+	 */
+    static CMdsImportExport* NewLC();
+
+	/**
+	 * Destructor
+	 */
+    virtual ~CMdsImportExport();
+
+    /**
+     * Reads and process schema file to classess hierarchy.
+     *
+     * @param aFileName filename to read from
+     * @param aSchema schema where to read file ontology
+     */
+    void ImportSchemaFromFileL( const TDesC& aFileName, CMdsSchema& aSchema, TUint32 aVendorId );
+
+    /**
+     * Reads schema from DB
+     *
+     * @param aConnection connection to DB
+     * @param aSchema returning schema
+     */
+    void ImportSchemaFromDBL( CMdsSchema& aSchema );
+
+	/**
+	 * Checks for schema version information
+	 * @return ETrue if match, otherwise EFalse
+	 */
+	TBool ImportCheckVersionInfoL();
+
+    /**
+     * Import items from file and add them do DB
+     *
+     * @return failed count
+     */
+    TInt ImportMetadataL( CMdSSqlObjectManipulate& aManipulate, CMdsSchema& aSchemaNew, const TDesC16& aFileName );
+
+	/**
+	 * Export all (without confidential) items to file
+	 */    
+    void ExportMetadataL( CMdsSchema& aSchemaNew, const TDesC16& aFileName,
+						  CMdCSerializationBuffer& aItems );
+
+protected:
+
+
+	/*
+	    IMPORT SCHEMA FILE
+	 */
+
+    /**
+     * Imports a single schema file line
+     * @param aParser a TLex8 object that parses a line of stream
+     */
+    void ImportSchemaLineL( TLex8& aParser );
+
+    /**
+     * imports a namespace
+     * @param aParser the remaining parameters
+     */
+    void ImportSchemaNamespaceL( TLex8& aParser );
+
+    /**
+     * imports an object def
+     * @param aParser the remaining parameters
+     */
+    void ImportSchemaObjectDefL( TLex8& aParser );
+
+	/**
+	* imports a property definition
+	* @param aParser the remaining parameters
+	*/
+	void ImportSchemaPropertyDefL( TLex8& aParser );
+
+	/**
+	* imports a relation definition
+	* @param aParser the remaining parameters
+	*/
+	void ImportSchemaRelationDefL( TLex8& aParser );
+
+	/**
+	* imports a event definition
+	* @param aParser the remaining parameters
+	*/
+	void ImportSchemaEventDefL( TLex8& aParser );
+
+	/**
+	* imports a version number
+	* @param aParser the remaining parameters
+	*/
+	void ImportSchemaVersionL( TLex8& aParser );
+	
+	/**
+	 * Checks that no more parameters are given in the current schema line.
+	 * @param aParser the remaining parameters
+	 */
+	void CheckNoMoreNumericParametersL( TLex8& aParser );
+
+	/*
+	    IMPORT METADATA FILE
+	 */
+    /**
+     * Reads a single metadata file line
+     * @return if reading is still possible (not end of file)
+     */
+    TBool ReadMetadataFileLineL();
+	
+	/**
+	 * add object to DB
+	 */
+	void AddObjectToDBL( CMdSSqlObjectManipulate& aManipulate, CMdsNamespaceDef* aNamespaceDef );
+
+    /**
+     * Imports a single metadata item
+     * @param aParser a TLex8 object that parses a line of stream
+     */
+    void ImportMetadataItemL( TLex8& aParser, CMdSSqlObjectManipulate& aManipulate );
+
+	/**
+	 * imports an metadata file object
+	 * @param aParser the remaining parameters
+	 */
+	void ImportMetadataFileObjectL( TLex8& aParser, CMdSSqlObjectManipulate& aManipulate );
+
+	/**
+	 * imports an metadata file property
+	 * @param aParser the remaining parameters
+	 */
+	TMdCOffset ImportMetadataFilePropertyL( TLex8& aParser, TMdCOffset aFreespaceOffset );
+
+	/**
+	 * imports an metadata file freetext
+	 * @param aParser the remaining parameters
+	 */
+	void ImportMetadataFileFreeTextL( TLex8& aParser, CDesC16ArrayFlat& aFreeTextArray );
+
+	/**
+	 * imports an metadata file relation
+	 * @param aParser the remaining parameters
+	 */
+	void ImportMetadataFileRelationL( TLex8& aParser, CMdSSqlObjectManipulate& aManipulate );
+
+	/**
+	 * imports an metadata file event
+	 * @param aParser the remaining parameters
+	 */
+	void ImportMetadataFileEventL( TLex8& aParser, CMdSSqlObjectManipulate& aManipulate );
+
+
+	/*
+	    EXPORT MATADATA FILE
+	 */
+	// objects
+	void ExportMetadataMakeSqlObjectClauseL( const CMdsNamespaceDef& aNamespaceDef, const CMdsObjectDef& aObjectDef,
+									  		CMdsClauseBuffer& aClause, RRowData& aDataRow );
+
+	void ExportMetadataMakeFreeTextSqlClauseL( const CMdsNamespaceDef& aNamespaceDef,
+									  		  CMdsClauseBuffer& aFreeTextClause, RRowData& aFreeTextRow );
+
+	void ExportMetadataWriteObjectInfoL( const CMdsNamespaceDef& aNamespaceDef, const CMdsObjectDef& aObjectDef,
+										CMdsClauseBuffer& aClause, RRowData& aDataRow,
+										CMdsClauseBuffer& aFreeTextClause, RRowData& aFreeTextRow );
+
+	// relations
+	void ExportMetadataMakeSqlRelationClauseL( const CMdsNamespaceDef& aNamespaceDef,
+									  		  CMdsClauseBuffer& aClause, RRowData& aDataRow );
+
+	void ExportMetadataWriteRelationInfoL( const CMdsNamespaceDef& aNamespaceDef, const CMdsRelationDef& aRelationDef,
+										  CMdsClauseBuffer& aClause, RRowData& aDataRow );
+
+	// events
+	void ExportMetadataMakeSqlEventClauseL( const CMdsNamespaceDef& aNamespaceDef,
+									  	   CMdsClauseBuffer& aClause, RRowData& aDataRow );
+
+	void ExportMetadataWriteEventInfoL( const CMdsNamespaceDef& aNamespaceDef, const CMdsEventDef& aEventDef,
+										CMdsClauseBuffer& aClause, RRowData& aDataRow );
+
+
+    //
+    // Helpers
+    //
+
+	/**
+	* Parses a safe TUint32 from the lexical parser.
+	* The type is assumed to be decimal.
+	* @param aValue parsed TUint32 value
+	* @param aParser the remaining patameters
+	* @return system wide error code
+	*/
+	TInt ImportUInt32( TUint32& aValue, TLex8& aParser );
+	
+	/**
+	 * Parses mediaID from the lexical parser.
+	 * The type is assumed to be decimal.
+	 * @param aValue parsed TUint32 value
+	 * @param aParser the remaining patameters
+	 * @param aDriveLetter drive letter of the drive where the file under processing is located
+	 * @return system wide error code
+	*/
+	TInt ImportMediaId( TUint32& aValue, TLex8& aParser, TChar& aDriveLetter );
+
+	/**
+	* Parses a safe TInt64 from the lexical parser.
+	* The type is assumed to be decimal.
+	* @param aValue parsed TInt64 value
+	* @param aParser the remaining patameters
+	* @return system wide error code
+	*/
+	TInt ImportInt64( TInt64& aValue, TLex8& aParser );
+
+	/**
+	* Parses a safe TTime from the lexical parser.
+	* implemented using GetNumericL template method.
+	* @param aValue parsed TTime value
+	* @param aParser the remaining patameters
+	* @return system wide error code
+	*/
+	TInt ImportTime( TTime& aValue, TLex8& aParser );
+
+	/**
+	* Parses a safe descriptor from the lexical parser.
+	* @param aValue parsed descriptor
+	* @param aParser the remaining patameters
+	* @return system wide error code
+	*/
+	TInt ImportText( TDes16& aBuffer, TLex8& aParser );
+
+	/**
+	* Parses a safe number type from given lexical parser.
+	* The number type is given in a template parameter.
+	* @param aValue parsed value of number type
+	* @param aParser the remaining patameters
+	* @return system wide error code
+	*/
+	template<class NumberType>
+	TInt ImportNum( NumberType& aValue, TLex8& aParser )
+		{
+		TLex8 tokenParser( aParser.NextToken() );
+		aParser.SkipSpace();
+		if ( tokenParser.Val( aValue ) != KErrNone )
+			{
+			return KErrCorrupt;
+			}
+		return KErrNone;
+		}
+	
+	TInt ImportNum( TReal32& aValue, TLex8& aParser )
+		{
+		TLex8 tokenParser( aParser.NextToken() );
+		aParser.SkipSpace();
+		if ( tokenParser.Val( aValue,TChar(TUint('.')) ) != KErrNone )
+			{
+			return KErrCorrupt;
+			}
+		return KErrNone;
+		}
+	
+	TInt ImportNum( TReal64& aValue, TLex8& aParser )
+		{
+		TLex8 tokenParser( aParser.NextToken() );
+		aParser.SkipSpace();
+		if ( tokenParser.Val( aValue,TChar(TUint('.')) ) != KErrNone )
+			{
+			return KErrCorrupt;
+			}
+		return KErrNone;
+		}
+	/**
+	* Converts from UTF8 -> Unicode
+	* @param aUtf8 input descriptor
+	* @param aBuffer result buffer
+	* @return descriptor of TDesC16 type
+	*/
+	TDesC16& Conv8To16( const TDesC8& aUtf8, TDes16& aBuffer );
+
+	/**
+	* Converts from Unicode -> UTF8
+	* @param aUnicode input descriptor
+	* @param aBuffer result buffer
+	* @return descriptor of TDesC8 type
+	*/
+	TDesC8& Conv16To8( const TDesC16& aUnicode, TDes8& aBuffer );
+
+	
+	/**	PROPERTY READING HELPER FUNCTIONS */
+
+	/**
+	 * Parses Uint32 value or check for one of min, max or def
+	 * constant value
+	 * @return depending on result: 
+	 *            1 for min
+	 *            2 for max
+	 *            3 for default
+	 *       -value for errors
+	 */
+	TInt CheckForConstant( TLex8& aParser );
+
+	/**
+	 * Parses Uint32 value or check for one of min, max or def
+	 * constant value
+	 */
+	TInt ImportPropertyUInt32( TUint32& aValue, TLex8& aParser );
+
+	/**
+	 * Parses a safe TInt64 from the lexical parser.
+	 * The type is assumed to be decimal.
+	 * @param aValue parsed TInt64 value
+	 * @param aParser parser
+	 */
+	TInt ImportPropertyInt64( TInt64& aValue, TLex8& aParser );
+
+	/**
+	* Parses a safe TTime from the lexical parser.
+	* implemented using GetNumericL template method.
+	* @param aValue parsed TTime value
+	* @param aParser the remaining patameters
+	* @return system wide error code
+	*/
+	TInt ImportPropertyTime( TTime& aValue, TLex8& aParser );
+
+	/**
+	* Parses a safe number type from given lexical parser.
+	* The number type is given in a template parameter.
+	* @param aValue parsed value of number type
+	* @param aParser the remaining patameters
+	* @return system wide error code
+	*/
+	template<class NumberType>
+	TInt SetMinMaxDefValueL( TInt aError, NumberType& aValue,
+			const NumberType& aMinValue, const NumberType& aMaxValue,
+			const NumberType& aDefValue )
+		{
+		if ( aError < KErrNone )
+			{
+			return aError;
+			}
+		if ( aError == KPropertyMinValue)
+			{
+			aValue = aMinValue;
+			return KErrNone;
+			}
+		else if ( aError == KPropertyMaxValue )
+			{
+			aValue = aMaxValue;
+			return KErrNone;
+			}
+		else if ( aError == KPropertyDefValue )
+			{
+			aValue = aDefValue;
+			return KErrNone;
+			}
+		return KErrArgument;
+		}
+private:
+
+    CMdsImportExport();
+
+	void ImportNamespaceFromDBL();
+	/*
+	 * 2nd phase constructor
+	 */
+    void ConstructL();
+    
+    /**
+     * Data import error logger
+     * @param aMessage a message to be logged
+     */
+    void LogError( const TDesC& aMessage );
+    
+private:
+    /**
+     * Store every namespace read from schema file.
+     */
+	CMdsSchema* iSchema;
+
+	/**
+	 * default schema
+	 * not own - do not delete
+	 */
+	CMdsSchema* iDefaultSchema;
+
+    /**
+     * Last read objectdef, where new properties should go.
+     * Just for speed access to property add access time.
+     * !! DO NOT DELETE !! - NOT OWN
+     */
+	CMdsObjectDef* iLastObjectDef;
+
+    /**
+     * Unicode<->UTF8 converter
+     */
+    CCnvCharacterSetConverter* iConverter;
+
+    /** logs import errors to file */
+    RFileLogger iLog;
+
+	/**
+	 *	File stream used for reading the import file
+	 */
+	RFileReadStream iReadStream;
+
+	/**
+	 *	File stream used for reading the import file
+	 */
+	RFileWriteStream iWriteStream;
+
+
+	/**
+	 * Handle to actual processing file
+	 */
+    RFs iFs;
+
+	/**
+	 * current parsing filename
+	 */
+	TFileName iFileName;
+
+	/**
+	 * current verdor id
+	 */
+	TUint32 iVendorId;
+
+	/**
+	 * current parsing line buffer
+	 */
+	TBuf8<KMdsMaxLineLenght> iLine;
+
+	/**
+	 * buffer for reading metadata file
+	 */
+	CMdCSerializationBuffer* iBuffer;
+
+	/**
+	 * indicated if last line was processed
+	 */
+	TBool iLastLineProcessed;
+
+    /**
+     * current parsing line number
+     */
+    TInt iLineNumber;
+
+	/**
+	 * import failed count
+	 */
+    TUint32 iFailed;
+
+	enum TImportVersionFlags
+		{
+		EVersionNone = 0x0000,
+		EVersionAlreadyRead = 0x0001,
+		};
+    TUint32 iVersionFlags;
+    
+    TInt iLastDriveNumber;
+    
+    TVolumeInfo iLastVolumeInfo;
+    };
+
+
+#endif // __MDSIMPORTEXPORT_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsindexer.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,89 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A singleton that provides system unique ID's*
+*/
+
+#ifndef __MDSINDEXER_H__
+#define __MDSINDEXER_H__
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32cmn.h>
+
+#include "mdccommon.h"
+
+// FORWARD DECLARATIONS
+class RRowData;
+
+
+// CLASS DECLARATION
+/**
+* A static class that is used to provide system unique
+* ID's for database storage purposes. 
+*/
+class MMdSIndexer
+    {
+    public: // Public functions
+
+    	/**
+    	 * Gets last object id from DB
+    	 * MUST be called once, when connection to DB is established
+    	 */
+    	static TItemId StartIndexL();
+
+    	/**
+	     * Provides a new system unique ID
+	     * @return a new system-wide unique ID
+	     */
+	    static TItemId GetIndex( );
+
+	    /**
+	     * Reverts system ID to previous state
+	     * used when add item failed
+	     */
+	    static void RevertIndex( );
+
+	    /**
+	     * Executes a SQL clause and returns the ID of the last object in DB.
+	     * @param aSqlClause SQL clause to execute
+	     * @param aRowData query parameters
+	     * @return result of last_insert_rowid()
+	     */
+	    static TItemId ExecuteAndGetIndexL(const TDesC &aSqlClause, const RRowData &aRowData );	    	
+
+	private:
+		static TItemId GetIndexL();
+
+		static void GetLastItemIdL();
+
+		static TItemId iId;
+	};
+
+class RSQLIndex
+	{
+	public:
+		RSQLIndex();
+
+		const TItemId& GetId() const;
+
+		void Commit();
+
+		void Close();
+
+	private:
+		const TItemId iId;
+		TBool iCommit;
+	};
+
+#endif // __MDSINDEXER_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsitemdef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,171 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one item definition
+*
+*/
+
+#ifndef __MDSITEMDEF_H__
+#define __MDSITEMDEF_H__
+
+#include "mdscommoninternal.h"
+
+class CMdCSerializationBuffer;
+
+/*
+ * All item definitions should inherit from this one
+ */
+class CMdsItemDef : public CBase
+	{
+	public:
+	 	/**
+	 	 * Destructor
+	 	 */
+	    virtual ~CMdsItemDef();
+	
+		/**
+		 * Get object name
+		 * @return object name
+		 */
+		inline const TDesC& GetName() const;
+	
+		/**
+		 * Get object Id
+		 * @return object Id
+		 */
+		inline TDefId GetId() const;
+	
+		/**
+		 * Sets object Id
+		 * param aId id which is assigned to event
+		 */		
+		inline void SetId(const TDefId aId);
+	
+		/*
+		 * Set that item is already stored in DB
+		 */	
+		inline void SetAllNotStoredInDB();
+
+		/**
+		 * Sets EStoredFlagsDB flag on.
+		 */
+		inline void SetStoredInDB();
+		
+		/**
+		 * @return ETrue if EStoredFlagsDB flag is set.
+		 */
+		inline TBool GetStoredInDB() const;
+
+		/**
+		 * Sets EStoredFlagsTable flag on.
+		 */
+		inline void SetTableStoredInDB();
+		
+		/**
+		 * @return ETrue if EStoredFlagsTable flag is set.
+		 */
+		inline TBool GetTableStoredInDB() const;
+
+		/**
+		 * stores defined flag
+		 */
+		inline void SetFlag( TStoredFlags aFlag );
+		inline TBool GetFlag( TStoredFlags aFlag ) const;
+		
+	    /**
+	     * Get required size of serialized buffer when this is serialized.
+	     *
+	     * @return required size of serialized buffer
+	     */
+	    TUint32 RequiredBufferSize();
+	
+	    /**
+	     * Serialize own data to serialized buffer (correct position must be set 
+	     * before calling) and return new position of serialized buffer.
+		 *
+	     * @param aBuffer  serialized buffer.
+	     */
+	    TMdCOffset SerializeL(CMdCSerializationBuffer& aBuffer);
+			
+	protected:
+		/**
+		 * Default constructor
+		 */
+	    inline CMdsItemDef()
+	    	{}
+	
+		/**
+		 * 2nd phase construction
+		 * @param aName name of event
+		 * @param aPriority priority of event
+		 */
+	    void ConstructL( const TDesC& aName );
+	    
+		/**
+		 * Check name of schema definition against allowed characters 
+		 * (A-Z, a-z, 0-9). First character can't be number. 
+		 *
+		 * Leaves with error code not equal to KErrNone if aName contains 
+		 * forbidden character(s).
+		 *
+		 * @param aName name of schema definition
+		 * @param aAllowNumbers are numbers allowed
+		 */
+	    void CheckAllowerCharatersL( const TDesC& aName, TBool aAllowNumbers );
+
+	private:
+		/**
+		 * Check name of schema definition against reserved word. 
+		 * 
+		 * Leaves with error code not equal to KErrNone if aName is reserved 
+		 * word.
+		 * 
+		 * @param aName name of schema definition
+		 */
+		void CheckReservedWordsL( const TDesC& aName );
+
+		/**
+		 * Check that character is allowed alphabet (A-Z, a-z).
+		 * 
+		 * @param aChar character to be checked
+		 */
+		void CheckAlphabetL( TUint16 aChar );
+
+		/**
+		 * Check that character is allowed alphabet (A-Z, a-z) or number (0-9).
+		 * 
+		 * @param aChar character to be checked
+		 */
+		void CheckAlphabetOrNumberL( TUint16 aChar );
+
+	private: // data
+	
+		/**
+		 * ObjectDef Name
+		 */
+		HBufC* iName;
+	
+		/**
+		 * ItemDef Id
+		 */
+		TDefId iId;
+	
+		/**
+		 * Tells if object is stored in DB
+		 */
+		TUint32 iStoredFlags;
+	};
+
+#include "mdsitemdef.inl"
+	
+#endif /*__MDSITEMDEF_H__*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsitemdef.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,94 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one item definition
+*
+*/
+
+
+/**
+ * Get object name
+ * @return object name
+ */
+inline const TDesC& CMdsItemDef::GetName() const
+	{
+	return *iName;
+	}
+
+/**
+ * Get object Id
+ * @return object Id
+ */
+inline TDefId CMdsItemDef::GetId() const
+	{
+	return iId;
+	}
+
+inline void CMdsItemDef::SetId(TDefId aId)
+	{
+	iId = aId;
+	}	
+
+inline void CMdsItemDef::SetFlag( TStoredFlags aFlag )
+	{
+	iStoredFlags |= aFlag;
+	}
+
+inline TBool CMdsItemDef::GetFlag( TStoredFlags aFlag ) const
+	{
+	return iStoredFlags & aFlag;
+	}
+
+inline void CMdsItemDef::SetStoredInDB()
+	{
+	iStoredFlags |= EStoredFlagsDB;
+	}
+
+inline void CMdsItemDef::SetAllNotStoredInDB()
+	{
+	iStoredFlags = EStoredFlagsNone;
+	}
+
+inline void CMdsItemDef::SetTableStoredInDB()
+	{
+	iStoredFlags |= EStoredFlagsTable;
+	}
+
+inline TBool CMdsItemDef::GetStoredInDB() const
+	{
+	return iStoredFlags & EStoredFlagsDB;
+	}
+
+inline TBool CMdsItemDef::GetTableStoredInDB() const
+	{
+	return iStoredFlags & EStoredFlagsTable;
+	}
+
+inline void CMdsItemDef::CheckAlphabetL( TUint16 aChar )
+	{	
+	if( !( ( 0x0041 <= aChar && aChar <= 0x005a ) || 
+		   ( 0x0061 <= aChar && aChar <= 0x007a ) ) )
+		{
+		User::Leave( KErrGeneral );
+		}
+	}
+
+inline void CMdsItemDef::CheckAlphabetOrNumberL( TUint16 aChar )
+	{
+	if( !( ( 0x0041 <= aChar && aChar <= 0x005a ) || 
+		   ( 0x0061 <= aChar && aChar <= 0x007a ) || 
+		   ( 0x0030 <= aChar && aChar <= 0x0039 ) ) )
+		{
+		User::Leave( KErrGeneral );
+		}	
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdslogger.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,197 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This class is for Server logging usage*
+*/
+
+#ifndef __MDSLOGGER_H__
+#define __MDSLOGGER_H__
+
+#include <e32std.h>
+#include <e32base.h>
+#include <s32file.h>
+#include <charconv.h>
+#include <convgeneratedcpp.h>
+
+#include "flogger.h"
+#include "harvesterlog.h"
+
+class CMdsClauseBuffer;
+class RRowData;
+class TColumn;
+
+/**
+* Logging categories.
+* If adding new categories, remember to add:
+* - a new activation flag to MMP file
+* - activation flag recognition code to logger.cpp
+*/
+enum TLogCategory
+    {
+    ELogAlways      = 0x0001, // logged always (if feature is on)
+    ELogQuery       = 0x0002, // DB queries
+    ELogDb          = 0x0004, // DB interface activity
+    ELogMutex       = 0x0008, // mutex
+    ELogServer      = 0x0010, // client/server commands
+    };
+
+
+#ifdef LOG_MASTER_FLAG
+
+const TChar KNewLine = '\n';
+const TInt KLineLength = 80;
+const TInt KLineBuffer = 512;
+const TUint32 KLogfileMaxLength = 10240;
+
+_LIT(KDirectory, "Metadata");
+_LIT(KFilename, "server.txt");
+_LIT(KAltFilename, "server2.txt");
+
+#define MDE_FILE_LOGGING
+
+// CLASS DECLARATION
+/**
+* CMdSLogger.
+* Class created log for server.
+*/
+class CMdSLogger : public CBase
+    {
+    public: // Constructors and destructor
+
+	    /**
+	    * Constructs a new logger implementation.
+	    *
+	    * @return  metadata logger implementation
+	    */
+        static CMdSLogger* NewInstanceL();
+
+        virtual ~CMdSLogger();
+
+        /**
+	    * Writes text to logfile, active version
+	    */
+        void LogLit( const TDesC8& aText );
+
+        /**
+	    * Writes text to logfile, active version
+	    */
+        void LogLit( const TDesC16& aText );
+
+        /**
+        * returns a reference to the file logger resource
+        */
+        inline RFileLogger& Log();
+
+        /**
+        * tests if a logging category is active
+        */
+        inline TBool IsActive( TLogCategory aCategory );
+
+        /**
+        * activates a certain logging category
+        */
+        inline void Activate( TLogCategory aCategory );
+
+        /**
+        * deactivates a certain logging category
+        */
+        inline void Deactivate( TLogCategory aCategory );
+
+        /**
+        * Checks if size exceeds maximum limit
+        * @param aLines how many lines has been added since last update
+        */
+        void CheckSize( TInt aLines );
+
+		// used for logging
+		CMdsClauseBuffer* DescribeL( const CMdsClauseBuffer& aBuffer, const RRowData& aRowData );
+	
+		CMdsClauseBuffer* DescribeFullL( const TDesC& aBuffer, const RRowData& aRowData );
+	
+		void LogVariableL( CMdsClauseBuffer& aBuf, const TColumn& aColumn );
+
+    private: // Private constructors
+
+        /**
+        * CMdSLogger.
+        * C++ default constructor.
+        */
+        CMdSLogger();
+
+        /**
+        * ConstructL.
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+    private:
+
+        /** the file logger resource */
+        RFileLogger iLog;
+
+        /** counter for lines */
+        TUint32 iLineCounter;
+
+        /**
+        * currently active logging categories (masked)
+        */
+        TUint32 iActiveCategories;
+        
+        TBool iAltFileFlag;
+        
+        TBool iValid;
+    };
+
+#include "mdslogger.inl"
+    
+    #define __DEFINE_LOGGER             class CMdSLogger* gLogger;
+    #define __USES_LOGGER               extern CMdSLogger* gLogger;
+    #define __INIT_LOGGER               gLogger = CMdSLogger::NewInstanceL();
+    #define __DESTROY_LOGGER            {if(gLogger){delete gLogger;gLogger=NULL;}}
+	#define __LOGLB(CATEGORY,A)         {if (gLogger->IsActive(CATEGORY)) { gLogger->LogLit( _L(A) ); }}
+	#define __LOG(CATEGORY,A)           {if (gLogger->IsActive(CATEGORY)) { gLogger->LogLit( A ); }}
+#ifdef MDE_FILE_LOGGING
+    #define __LOG1(CATEGORY,A,B)        {if (gLogger->IsActive(CATEGORY)) { gLogger->Log().WriteFormat( _L(A), B ); gLogger->CheckSize( 1 ); }}
+    #define __LOG2(CATEGORY,A,B,C)      {if (gLogger->IsActive(CATEGORY)) { gLogger->Log().WriteFormat( _L(A), B, C ); gLogger->CheckSize( 1 ); }}
+    #define __LOG3(CATEGORY,A,B,C,D)    {if (gLogger->IsActive(CATEGORY)) { gLogger->Log().WriteFormat( _L(A), B, C, D ); gLogger->CheckSize( 1 ); }}
+#else
+	#define __LOG1(CATEGORY,A,B)        {if (gLogger->IsActive(CATEGORY)) { RDebug::Print( _L(A), B ); }}
+	#define __LOG2(CATEGORY,A,B,C)      {if (gLogger->IsActive(CATEGORY)) { RDebug::Print( _L(A), B, C ); }}
+	#define __LOG3(CATEGORY,A,B,C,D)    {if (gLogger->IsActive(CATEGORY)) { RDebug::Print( _L(A), B, C, D ); }}
+#endif
+
+	#ifdef LOG_QUERY
+	    #define __LOGQUERY_16(INFO, BUFFER, ROWDATA) \
+	    	{__LOG( ELogQuery, INFO); \
+	        CMdsClauseBuffer* queryText = gLogger->DescribeFullL(BUFFER,ROWDATA); \
+	        if ( queryText ) { __LOG( ELogQuery, queryText->ConstBufferL() ); \
+	        delete queryText;} }
+	#else //LOG_QUERY
+	    #define __LOGQUERY_16(INFO, BUFFER, ROWDATA)
+	#endif //LOG_QUERY
+
+#else
+    #define __DEFINE_LOGGER 
+    #define __USES_LOGGER
+    #define __INIT_LOGGER
+    #define __DESTROY_LOGGER
+    #define __LOGLB(CATEGORY,A)
+    #define __LOG(CATEGORY,A)
+    #define __LOG1(CATEGORY,A,B)
+    #define __LOG2(CATEGORY,A,B,C)
+    #define __LOG3(CATEGORY,A,B,C,D)
+	#define __LOGQUERY_16(INFO, BUFFER, ROWDATA)
+#endif  // METADATA_LOG
+
+
+#endif  //__MDSLOGGER_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdslogger.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Metadata server logger class
+*
+*/
+
+
+inline RFileLogger& CMdSLogger::Log()
+	{
+	return iLog;
+	}
+
+/**
+* tests if a logging category is active
+*/
+inline TBool CMdSLogger::IsActive( TLogCategory aCategory )
+    {
+    return ( iActiveCategories & aCategory );
+    }
+
+/**
+* activates a certain logging category
+*/
+inline void CMdSLogger::Activate( TLogCategory aCategory )
+    {
+    iActiveCategories |= aCategory;
+    }
+
+/**
+* deactivates a certain logging category
+*/
+inline void CMdSLogger::Deactivate( TLogCategory aCategory )
+    {
+    iActiveCategories &= ~aCategory;
+    }
+    
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsmaintenanceengine.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,144 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class for database import/export and maintenance*
+*/
+
+#ifndef __MDSMAINTENANCEENGINE_H__
+#define __MDSMAINTENANCEENGINE_H__
+
+#include <e32base.h>
+
+#include "mdccommon.h"
+
+// DEFINITIONS
+_LIT( KSchemaImportFile, "C:\\Private\\200009F3\\schema.mde" );
+_LIT( KSchemaRomImportFile, "Z:\\Private\\200009F3\\schema.mde" );
+
+// forward declarations
+class CMdsSchema;
+class CMdSManipulationEngine;
+class CMdCSerializationBuffer;
+class CMdSSqlDbMaintenance;
+
+/**
+* Abstract class for validating and creating tables.
+*/
+class CMdSMaintenanceEngine : public CBase
+    {
+    public: // Constructors and destructor
+
+        /**
+        * NewL.
+        * Two-phased constructor.
+        */
+        static CMdSMaintenanceEngine* NewL();
+
+        /**
+        * NewL.
+        * Two-phased constructor.
+        */
+        static CMdSMaintenanceEngine* NewLC();
+
+        virtual ~CMdSMaintenanceEngine();
+
+    public: // Operations
+        
+  	    /**
+	    * Imports external schema to database.
+        * @param aSchema schema that is on phone currently
+        * @param aFileName name of the import file
+	    */        
+        void ImportSchemaL( CMdsSchema& aSchema, const TDesC16& aFileName, TUint32 aVendorId );
+
+        CMdsSchema* ImportSchemaTestL( const TDesC16& aFileName );
+
+
+  	    /**
+	    * Imports metadata to database.
+        * @param aSchema schema that is on phone currently
+        * @param aFileName name of the import file
+	    */        
+        TInt ImportMetadataL( CMdSManipulationEngine& aManipulate, 
+        					     CMdsSchema& aSchema, const TDesC16& aFileName );
+
+  	    /**
+	    * Exports metadata to file.
+        * @param aFileName name of the file where to export
+        * @param aSchema current schema
+        * @param aHierarchyArray an array of criteria what to export
+	    */        
+        void ExportMetadataL( CMdsSchema& aSchema, const TDesC16& aFileName, 
+                              CMdCSerializationBuffer& aItems );
+        
+        /**
+         * Stores C-drive media id to the DB.
+         */
+        void StoreCDriveMediaIdL();
+
+  	    /**
+	    * Creates metadata tables to database.
+	    */
+	    void InstallL( CMdSManipulationEngine& aManipulate, CMdsSchema& aSchema );
+
+        /**
+        * Loads schema from database
+        */
+        void LoadSchemaL( CMdsSchema& aSchema );
+        
+        /**
+         * performs initialization (at server start) for default database
+         */
+        static void InitConnectionL();
+
+        /**
+         * closes default database
+         */
+        static void CloseDatabase();
+
+        /**
+         * close and delete default database
+         */
+		static void DeleteDatabase();
+
+		TInt FailedImports() const
+			{
+			return iFailedImports;
+			};
+
+    private: // Constructors and destructors
+
+        /**
+        * CMdSManipulationEngine.
+        * C++ default constructor.
+        * @param .
+        */
+        CMdSMaintenanceEngine();
+
+        /**
+        * ConstructL.
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+	private: // Member data
+
+        /**
+         * database validation and creation
+         */
+        CMdSSqlDbMaintenance* iMaintenance;
+
+        TInt iFailedImports;
+    };
+    
+#endif // __MDSMAINTENANCEENGINE_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsmanipulationengine.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,334 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is Manipulation engine to manage adding,*
+*/
+
+#ifndef __MDSMANIPULATIONENGINE_H__
+#define __MDSMANIPULATIONENGINE_H__
+
+#include <e32base.h>
+
+#include "mdscommoninternal.h"
+#include "mdsgarbagecollector.h"
+
+// FORWARD DECLARATIONS
+class CMdSSchema;
+class CMdsSchema;
+class CMdSNotifier;
+class CMdSServerSession;
+class CMdSObjectLockList;
+class CMdCSerializationBuffer;
+class CMdSSqlObjectManipulate;
+
+// CONSTANT DECLARATION
+const TInt KGarbageCollectionDelay = 60; // test 1 minute
+
+// CLASS DECLARATION
+
+/**
+* CMdSManipulationEngine.
+*  Class for manipulating metadata database entries.
+*/
+class CMdSManipulationEngine : public CBase, public MMdSGarbageCollectorObserver
+    {
+    public: // Constructors and destructors
+
+        /**
+        * NewL.
+        * Two-phased constructor.
+        * @param aObjectManipulate pointer to object manipulator
+        * @return Pointer to created CMdSManipulationEngine object.
+        */
+        static CMdSManipulationEngine* NewL( CMdsSchema& aSchema, 
+            CMdSNotifier& aNotifier, CMdSObjectLockList& aLockList );
+
+        /**
+         * NewLC.
+         * Two-phased constructor.
+         * @param aObjectManipulate pointer to object manipulator
+         * @return Pointer to created CMdSManipulationEngine object.
+         */
+         static CMdSManipulationEngine* NewLC( CMdsSchema& aSchema,
+             CMdSNotifier& aNotifier, CMdSObjectLockList& aLockList );
+
+        /**
+        * ~CMdSManipulationEngine.
+        * Destructor.
+        */
+        virtual ~CMdSManipulationEngine();
+
+    public:
+
+		/** 
+		 * Adds object to DB from serialized buffer and put a result item IDs 
+		 * to result buffer 
+		 */
+		void AddL( CMdCSerializationBuffer& aBuffer, 
+				CMdCSerializationBuffer& aResultBuffer,
+				const CMdSServerSession* aServerSession );
+
+	    /** 
+	     * Removes items from the database
+	     * @param aBuffer serialized TMdCItemIds object
+	     * @param aSuccessfulBuffer successfully removed objects
+	     */
+	    void RemoveL( CMdCSerializationBuffer& aBuffer, 
+	    		CMdCSerializationBuffer& aSuccessfulBuffer );
+	    
+	    /** 
+	     * Updates items to database
+	     */
+	    void UpdateL( CMdCSerializationBuffer& aBuffer, 
+	    		CMdCSerializationBuffer& aResultBuffer );
+
+	    /**
+	     * Gets object id, object def and flags in serialization buffer.
+	     * @param aResultBufferSize size of result buffer
+	     * @param aUri object URI
+	     * @param aNamespaceDefId namespace id
+	     * 
+	     * @return serialization buffer that contains object id, object def id and object flags
+	     */
+		CMdCSerializationBuffer* CheckObjectL( TInt aResultBufferSize, 
+				const TDesC& aUri, TDefId aNamespaceDefId );
+
+		/**
+	     * Gets object def and flags in serialization buffer.
+	     * @param aResultBufferSize size of result buffer
+	     * @param aId object id
+	     * @param aNamespaceDefId namespace id
+	     * 
+	     * @return serialization buffer that contains object def id and object flags
+	     */
+		CMdCSerializationBuffer* CheckObjectL( TInt aResultBufferSize, 
+				TItemId aId, TDefId aNamespaceDefId );
+
+		/**
+	     * Gets object def and flags in serialization buffer.
+	     * @param aResultBufferSize size of result buffer
+	     * @param aIds list of object ids in serialization buffer
+	     * @param aNamespaceDefId namespace id
+	     * 
+	     * @return serialization buffer that contains object id, object def id and object flags for
+	     * all objects
+	     */
+		CMdCSerializationBuffer* CheckObjectL( TInt aResultBufferSize, 
+				CMdCSerializationBuffer& aIds, TDefId aNamespaceDefId );
+
+	    /**
+         * Give a reference to the manipulator object
+         */
+		CMdSSqlObjectManipulate& Manipulate();
+
+	    /**
+	     * Give a reference to the manipulator object
+	     */
+        CMdSGarbageCollector& GarbageCollector();
+
+		/**
+        * Add memory card media ID
+        * @param aMediaId Memory card's media ID
+        */
+		void AddMemoryCardL(TUint32 aMediaId);
+
+        /**
+        * Get the lastest memory card's media ID
+        * @param aMediaId Returned the latest memory card's media ID
+		* @leave KErrNotFound Not memory cards exist at all
+        */
+        void GetMemoryCardL(TUint32& aMediaId);
+
+        /**
+         * Checks if memory card's with given media ID exists
+         * @param aMediaId memory card's media ID
+         * @return memory card exists or not
+         */
+        TBool CheckMemoryCardL(TUint32 aMediaId);
+
+        /**
+         * Set media's media ID, drive and present state to DB.
+         * 
+         * @param aMediaId media ID
+         * @param aMediaId drive
+         * @param aMediaId present state
+         */
+        void SetMediaL(TUint32 aMediaId, TChar aDrive, TBool aPresentState);
+
+        /**
+         * Check if the media's with given media ID exist in DB and return 
+         * drive and present state.
+         * 
+         * @param aMediaId given media ID
+         * @param aMediaId drive
+         * @param aMediaId present state
+         * 
+         * @return does media exist
+         */
+        TBool GetMediaL(TUint32 aMediaId, TChar& aDrive, TBool& aPresentState);
+
+        /**
+         * Get present medias' media IDs and drives.
+         * 
+         * @param aMediaInfoBuffer buffer where media infos are written
+         * 
+         * @return present media count
+         */
+        TInt32 GetPresentMediasL(TDes8& aMediaInfoBuffer);
+
+        /**
+         * Sets files object to present state.
+         * @param aMediaId Memory card's media ID
+         * @param aFileCount File count
+         * @param aUris Files' URIs
+         * @param aFileInfos Files' file infos
+         * @param aResults TFilePresentStates results (casted to TUint8)
+         */
+        void SetFilesToPresentL(TUint32 aMediaId, TUint32 aFileCount, 
+        		CMdCSerializationBuffer& aUris, CMdCSerializationBuffer& aFileInfos,
+        		CMdCSerializationBuffer& aResults);
+        
+        
+        /**
+        * Sets all file objects which has given media ID to not present state.
+        * @param aMediaId Memory card's media ID
+        * @param aStartUp start up not present
+        */
+        void SetFilesToNotPresentL(TUint32 aMediaId, TBool aStartUp);
+        
+        /**
+        * Removes all file objects which has given media ID and are in not 
+        * present.
+        *
+        * @param aMediaId Memory card's Media ID
+        * @param aStartUp start up not present
+        */
+        void RemoveFilesNotPresentL(TUint32 aMediaId, TBool aStartUp);
+
+		/**
+		 * Get schema version
+		 */
+		void GetSchemaVersionL(TInt& aMajorVersion, TInt& aMinorVersion);
+
+		/**
+		 * Set object to "present" state bu GUID
+		 * 
+		 * @leave KErrNotFound MdE can't find object in "not present" state 
+		 *                     with matching GUID
+		 */
+		void SetObjectToPresentByGuidL( 
+				const TInt64& aGuidHigh, const TInt64& aGuidLow );
+
+		/**
+		 * Change a path of a media object to another.
+		 * @param aOldPath old path
+		 * @param aNewPath new path
+		 */
+		void ChangePathL(const TDesC& aOldPath, const TDesC& aNewPath);
+		
+		/**
+		 * Updates C drive media id for all objects with the old media id. 
+		 */
+		void ChangeMediaIdL();
+		
+		/**
+		 * Adds new relation definition to the DB.
+		 * @param aNamespaceId namespace id
+		 * @param aRelationDefName name of the new relation def
+		 */
+		void AddRelationDefL( TDefId aNamespaceId, const TDesC& aRelationDefName );
+		
+		/**
+		 * Adds new event definition to the DB.
+		 * @param aNamespaceId namespace id
+		 * @param aEventDefName name of the new event def
+		 */
+		void AddEventDefL( TDefId aNamespaceId, const TDesC& aEventDefName );
+
+		/**
+		 * Set the "pending" flag for objects. The pending flag means that composing to binary is 
+		 * pending for the object.
+		 * @param aObjectIds list of object ids
+		 */
+		void SetPendingL(const RArray<TItemId>& aObjectIds);
+		
+		/**
+		 * Resets the "pending" flag for objects.
+		 * @param aObjectIds list of object ids.
+		 */
+		void ResetPendingL(const RArray<TItemId>& aObjectIds);
+		
+		/**
+		 * Gets count of objects pending.
+		 * @param aObjectDefId type of objects
+		 * @return count of pending objects
+		 */
+		TInt GetPendingCountL( TDefId aObjectDefId );
+		
+		/**
+		 * Gets ids of pending objects of type defined with aObjectDefId.
+		 * @param aObjectDefId objects definition id
+		 * @param aBufferSize max count of object ids in aObjectIds
+		 * @param aObjectIds on return contains ids of pending objects
+		 * 
+		 * @return 1 if there were more pending objects than could be appended to the array,
+		 * 	0 otherwise
+		 */
+		TInt GetPendingL( TDefId aObjectDefId, TInt aBufferSize, 
+				RArray<TItemId>& aObjectIds );
+		
+	protected:
+		TBool StartGarbageCollectionL();
+
+    private: // Constructors and destructors
+
+        /**
+        * CMdSManipulationEngine.
+        * C++ default constructor.
+        * @param .
+        */
+        CMdSManipulationEngine( CMdsSchema& aSchema, CMdSNotifier& aNotifier, 
+        		CMdSObjectLockList& aLockList );
+
+        /**
+        * ConstructL.
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+    private: // Methods for own use
+
+    private: // Data
+
+       /**
+        * Object adding, removing and modification.
+        * Provides DB coding.
+        */
+    	CMdSSqlObjectManipulate* iManipulate;
+
+        /**
+        * Schema
+        */
+        CMdsSchema& iSchema;
+
+        /**
+        * Notifier
+        */
+        CMdSNotifier& iNotifier;
+
+		CMdSGarbageCollector* iGarbageCollector;
+		
+		CMdSObjectLockList& iLockList;
+	};
+
+#endif //__MDSMANIPULATIONENGINE_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsnamespacedef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,255 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one namespace and every objects,
+*                properties and events it holds.
+*
+*/
+
+#ifndef __MDSNAMESPACE_H__
+#define __MDSNAMESPACE_H__
+
+#include <e32base.h>
+#include <s32file.h>
+
+#include "mdsitemdef.h"
+
+class CMdsObjectDef;
+class CMdsEventDef;
+class CMdsRelationDef;
+class CMdCSerializationBuffer;
+class CMdsPropertyDef;
+class CMdsSchema;
+
+/**
+ *  Metadata namespace class
+ *
+ *  This class is responsible for holding information about everything
+ *  which namespace can contain (name, objects, event, relations)
+ *
+ */
+class CMdsNamespaceDef : public CMdsItemDef
+    {
+    friend class CMdsSchema;
+    friend class CMdsImportExport;
+
+public:
+	/**
+	 * Create new namespace object
+	 * @param aId id of namespace
+	 * @param aName name of namespace
+	 * @param aReadOnly read-only namespace flag
+	 * @return pointer to new created namespace
+	 */
+    static CMdsNamespaceDef* NewL( TDefId aId, const TDesC& aName, TBool aReadOnly,
+    		TUint32 aVendorId );
+
+	/**
+	 * Create new namespace object
+	 * @param aId id of namespace
+	 * @param aName name of namespace
+	 * @param aReadOnly read-only namespace flag
+	 * @return pointer to new created namespace
+	 */
+    static CMdsNamespaceDef* NewLC( TDefId aId, const TDesC& aName, TBool aReadOnly,
+    		TUint32 aVendorId );
+
+    virtual ~CMdsNamespaceDef();
+
+	inline TBool GetReadOnly() const;
+
+	inline TBool GetFirstRead() const;
+
+	inline void UnsetFirstRead();
+
+	inline void SetBaseObject( CMdsObjectDef* const aBaseObject );
+
+	inline TInt32 GetVendorId() const;
+
+	inline void SetVendorId(TInt32 aVendorId);
+
+	/**
+	 * Add object to namespace and return pointer to it,
+	 * if object already exist function leaves with KErrAlreadyExists
+	 * @param objName name of the object definition
+	 * @param parName name of the object parent
+	 * @return pointer to new object definition or leave with error
+	 */
+	CMdsObjectDef* AddObjectDefL( const TDesC& aObjectName, const TDesC& aParentName, CMdsSchema* aDefaultSchema );
+	
+	/**
+	 * Add relation to array
+	 * @param relName name of relation
+	 */
+	void AddRelationDefL( const TDesC& aRelationName );
+	
+	/**
+	 * Add event to event array
+	 * @param objName name of event
+	 * @param aPriority priority of event
+	 */
+	void AddEventDefL( const TDesC& aEventName, TInt32 aPriority );
+	
+	/**
+	 * Gets object def by object def id.
+	 * @param aId objectdef id
+	 * @return a pointer to object definition
+	 */
+	const CMdsObjectDef* GetObjectByIdL( TDefId aId ) const;
+	
+	/**
+	 * Gets event def by devent def id.
+	 * @param aId eventdef id
+	 * @return a pointer to event definition
+	 */
+	const CMdsEventDef* GetEventByIdL( TDefId aId ) const;
+	
+	/**
+	 * Gets relation def by relation def id.
+	 * @param aId relationdef id
+	 * @return a pointer to relation definition
+	 */
+	const CMdsRelationDef* GetRelationByIdL( TDefId aId ) const;
+	
+	/**
+	 * Gets property def by property def id.
+	 * @param aId property id
+	 * @return a pointer to relation property
+	 */
+	const CMdsPropertyDef* GetPropertyL( TDefId aId ) const;
+	
+	/**
+	 * Import object, event and relation defs from default DB.
+	 */
+	void ImportFromDBL();
+	
+	/**
+	 * Adds new object definition to DB.
+	 * @param aId object def id
+	 * @param aParentId parent object def id
+	 * @param aFlags flags for the new object
+	 * @param aName new object def name
+	 */
+	void AddObjectDefL( TDefId aId, TDefId aParentId, TInt aFlags, const TDesC& aName );
+	
+	/**
+	 * Adds new relation definition to DB.
+	 * @param aId relation def id
+	 * @param aRelationName new relation name
+	 */
+	void AddRelationDefL( TDefId aId, const TDesC& aRelationName );
+	
+	/**
+	 * Adds new event definition to DB.
+	 * @param aId event def id
+	 * @param aEventName new event name
+	 * @param aPriority
+	 */
+	void AddEventDefL( TDefId aId, const TDesC& aEventName, TInt32 aPriority );
+	
+    /**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+    TUint32 RequiredBufferSize();
+
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling) and return new position of serialized buffer.
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    TMdCOffset SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreeSpace);
+    
+	/**
+	 * Search for relation, using name
+	 * @param objName name of object to search for
+	 * @return pointer to found object or NULL
+	 */
+	CMdsRelationDef* GetRelationDef( const TDesC& aRelationName ) const;
+
+	/**
+	 * Search for event, using name
+	 * @param objName name of object to search for
+	 * @return pointer to found object or NULL
+	 */
+	CMdsEventDef* GetEventDef( const TDesC& aEventName ) const;
+
+	/**
+	 * Search for object, using name
+	 * @param objName name of object to search for
+	 * @return pointer to found object or NULL
+	 */
+	CMdsObjectDef* GetObjectDef( const TDesC& aObjectName ) const;
+
+
+private:
+
+	/**
+	 * default constructor
+	 */
+    inline CMdsNamespaceDef( TDefId aId, TBool aReadOnly,
+    		                 TUint32 aVendorId );
+
+	/**
+	 * Second phase constructor
+	 * @param aName name of namespace
+	 */
+    void ConstructL( const TDesC& aName );
+
+	void StoreToDBL(TBool aStoreOnlyNamespace = EFalse );
+	void MergeObjectsL( CMdsNamespaceDef* aNamespace, const TBool& aDryRun );
+	void MergeRelationsL( CMdsNamespaceDef* aNamespace, const TBool& aDryRun );
+	void MergeEventsL( CMdsNamespaceDef* aNamespace, const TBool& aDryRun );
+
+private:
+enum TNamespaceDefFlags
+	{
+	ENamespaceDefFlagsReadOnly  = 0x0001,
+	ENamespaceDefFlagsFirstRead = 0x0002,
+	};
+
+private:
+    /**
+     * Store every namespace read from schema file.
+     */
+	RPointerArray<CMdsObjectDef> iObjectDefs;
+
+   /**
+     * Store every namespace read from schema file.
+     */
+	RPointerArray<CMdsEventDef> iEventDefs;
+
+   /**
+     * Store every namespace read from schema file.
+     */
+	RPointerArray<CMdsRelationDef> iRelationDefs;
+
+	TInt32 iVendorId;
+
+	/**
+	 * Namespace flags: readOnly, firstRead
+	 */
+	TUint32 iFlags;
+
+	/**
+	 * Pointer to base object
+	 * DO NOT DELETE, NOT OWN !!!
+	 */
+	static CMdsObjectDef* iBaseObject;
+    };
+
+#include "mdsnamespacedef.inl"
+
+#endif // __MDSNAMESPACE_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsnamespacedef.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one namespace and every objects,
+*                properties and events it holds.
+*
+*/
+
+
+inline CMdsNamespaceDef::CMdsNamespaceDef( TDefId aId, TBool aReadOnly, TUint32 aVendorId )
+   : iVendorId(aVendorId), iFlags(ENamespaceDefFlagsFirstRead)
+   	{
+   	SetId( aId );
+   	if (aReadOnly)
+   		{
+   		iFlags |= ENamespaceDefFlagsReadOnly;
+   		}
+   	}
+
+inline TBool CMdsNamespaceDef::GetReadOnly() const
+	{
+	return iFlags&ENamespaceDefFlagsReadOnly ? ETrue : EFalse;
+	}
+
+inline TBool CMdsNamespaceDef::GetFirstRead() const
+	{
+	return iFlags&ENamespaceDefFlagsFirstRead ? ETrue : EFalse;
+	}
+
+inline void CMdsNamespaceDef::UnsetFirstRead()
+	{
+	iFlags &= ~ENamespaceDefFlagsFirstRead;
+	}
+
+inline void CMdsNamespaceDef::SetBaseObject( CMdsObjectDef* const aBaseObject )
+	{
+	iBaseObject = aBaseObject;
+	}
+
+inline TInt32 CMdsNamespaceDef::GetVendorId() const
+	{
+	return iVendorId;
+	}
+
+inline void CMdsNamespaceDef::SetVendorId(TInt32 aVendorId)
+	{
+	iVendorId = aVendorId;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsnotifier.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,348 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Notifier engine*
+*/
+
+#ifndef __MDSNOTIFIER_H__
+#define __MDSNOTIFIER_H__
+
+#include <e32base.h>
+
+#include "mdscommoninternal.h"
+
+
+// forward declarations
+class CMdSServerSession;
+class CMdSNotifyComparator;
+class CMdSSchema;
+class CMdCSerializationBuffer;
+
+/**
+* A class that contains notification profiles for clients.
+* The class compares events against each profile and
+* triggers the client side which then calls back the observer.
+*/
+class CMdSNotifier : public CBase
+    {
+    public: // public construction
+
+        /** static construction */
+        static CMdSNotifier* NewL();
+        static CMdSNotifier* NewLC();
+
+        /** destructor */
+        virtual ~CMdSNotifier();
+
+    private: // private construction
+
+        /** constructor */        
+        CMdSNotifier();
+
+        /** 2nd phase constructor */
+        void ConstructL();
+
+    public: // methods
+
+        /**
+        * An inner class for an entry in the array of listeners to
+        * notify for different notification profiles.Each entry
+        * contains the notification profiles against which to
+        * compare the event and the parameters required to perform
+        * the asynchronous notification.
+        */
+        class TEntry
+            {
+            friend class CMdSNotifier; // accessible by host
+
+            public:
+
+                /**
+                * sets the entry up for asynchronous callback
+                * @param aMessage the asynchronous message
+                * @param aRemoteSize the pointer to remote message size buffer
+                */
+                void SetupForCallback( RMessage2 aMessage, TInt aRemoteSizeMsgSlot );
+
+                /**
+                * Whether or not this entry has an asynchronous message
+                * pending
+                */
+                TBool IsPending() { return ( iRemoteSizeMsgSlot!=KErrNotFound ); }
+
+                /** the criteria folder */
+                CMdCSerializationBuffer& Condition() 
+                	{ 
+                	return *iSerializedCondition; 
+                	}
+
+				/**
+				*	Does this entry allow confidential data
+				*	@return EFalse if not allowed
+				*/
+				TBool AllowConfidential()
+					{
+					return iConfidential;
+					}
+				
+				/**
+				*	Return the id of this entry
+				*	@return The id
+				*/
+				TInt Id()
+					{
+					return iId;
+					}
+
+				/**
+				*	Return the id of this entry
+				*	@return The id
+				*/
+				TDefId NamespaceDefId()
+					{
+					return iNamespaceDefId;
+					}
+					
+				/**
+				*	Trigger a previously cached notification
+				*	@param aCompleteCode The code to complete the message
+				*	@param aData The data hierarchy to send to the client,
+				*                ownership changes only if method doesn't leave
+				*	@return none
+				*/			
+				void TriggerCachedL(TUint32 aCompleteCode, CMdCSerializationBuffer* aData);
+
+				/**
+				*	Get the data buffer
+				*	@return the serialised data buffer
+				*/
+				CMdCSerializationBuffer* GetDataBuffer();
+
+            private: // methods for host class
+
+                /** constructor */
+                TEntry( TInt aId, TConditionType aType,
+                    CMdCSerializationBuffer* aSerializedBuffer,
+                    TDefId aNamespaceDefId, 
+                    CMdSServerSession& aSession, TBool aConfidential );
+
+                /**
+                * Triggers the notifier causing the observer to be
+                * notifier with the given code.
+                * @param aCompleteCode either added/removed/modified
+                * @param aItem the target of the event
+                */
+                void TriggerL( TUint32 aCompleteCode,
+                    const RArray<TItemId>& aIdArray );
+
+                /**
+                 * Triggers the notifier causing the observer to be
+                 * notifier with the given code.
+                 * 
+                 * @param aCompleteCode either added/removed/modified
+                 * @param aBuffer relation items of the event
+                 * @param aRelationIdArray matched relation ids
+                 */
+                void TriggerRelationItemsL( TUint32 aCompleteCode,
+                		CMdCSerializationBuffer& aBuffer,
+                		const RArray<TItemId>& aRelationIdArray );
+
+				/**
+				 * Trigger a notification of a schema change
+				 */
+				void TriggerSchema();
+
+				/**
+				 *	The entry has currently no message active, 
+				 *	wait until one is available.
+				 */
+                void CacheL(TUint32 aCompleteCode, const RArray<TItemId>& aIdArray );
+
+                /**
+				 *	The entry has currently no message active, 
+				 *	wait until one is available.
+				 */
+                void CacheRelationItemsL(TUint32 aCompleteCode,
+                		CMdCSerializationBuffer& aBuffer,
+                		const RArray<TItemId>& aRelationIdArray);
+
+                /**
+				 *	cache schema notification
+				 */
+                void CacheL(TUint32 aCompleteCode);
+				
+                /**
+                 * Triggers the notifier with an error code
+                 * @param aErrorCode one of system-wide error codes
+                 */
+                void TriggerError( TInt aErrorCode );
+
+				/**
+				 * Copy all IDs from the array in to the buffer
+				 * 
+				 * @param aIdArray ID array
+				 * @return new buffer
+				 */
+				CMdCSerializationBuffer* CopyToBufferL(
+						const RArray<TItemId>& aIdArray);
+
+				/**
+				 * Copy matched relation IDs to a buffer
+				 * 
+				 * @param aRelationItemsBuffer serialized items
+				 * @param aIdArray matched IDs
+				 * @return new buffer
+				 */
+				CMdCSerializationBuffer* CopyItemsToBufferL(
+						CMdCSerializationBuffer& aRelationItemsBuffer, 
+						const RArray<TItemId>& aIdArray);
+            private:
+
+                /** id */
+                TInt iId;
+
+                /** type of the notification */
+                TUint32 iType;
+
+				/** namespace definition ID */
+                TDefId iNamespaceDefId;
+
+                /** actual serialized condition */
+                CMdCSerializationBuffer* iSerializedCondition;
+
+				/**
+				* serialised id or relation items buffer.
+				* Used instead of iDataObject when 
+				* sending object ids to the clients
+				*/
+                CMdCSerializationBuffer* iDataBuffer;
+				
+                /** asynchronous message */
+                RMessage2 iMessage;
+
+                /** pointer to remote size buffer */
+                TInt iRemoteSizeMsgSlot;
+
+                /** the session */
+                CMdSServerSession& iSession;
+
+                TBool iConfidential;
+            };
+
+       /**
+        * creates a notifier entry
+        * @param aId id of the entry to be created
+        * @param aType type of the notifier (object/relation/event)
+        * @param aCriteria the serialized criteria to compare against
+        * @param aSession the session that owns the notificant
+        * @param aConfidential Does the session get notifications of confidential items 
+        * @return reference to the created entry
+        */
+        TEntry& CreateEntryL( TInt aId, TConditionType aType,
+            CMdCSerializationBuffer* aSerializedBuffer, TDefId aNamespaceDefId,
+            CMdSServerSession& aSession, TBool aConfidential);
+
+       /**
+        * finds an entry by its id, if not found leaves with KErrNotFound
+        * @param aId id of the entry
+        * @return reference to the entry found
+        */
+        TEntry& FindEntryL( TInt aId );
+
+       /**
+        * removes a notifier entry, if not found leaves with KErrNotFound
+        * @param aId id of the entry to be removed
+        */
+        void RemoveEntryL( TInt aId );
+
+       /**
+        * removes all notifier entries that belong to a certain session
+        * @param aSession session who's notify entries are to be removed
+        */
+        void RemoveEntriesBySession(const CMdSServerSession& aSession );
+
+       /**
+        * notifiers that items has been added
+        * @param aSerializedItems serialized items
+        * @param aSerializedItemIds serialized item IDs
+        */
+        void NotifyAddedL(CMdCSerializationBuffer& aSerializedItems, 
+        				  CMdCSerializationBuffer& aSerializedItemIds);
+
+       /**
+        * notifiers that items has been modified
+        * @param aSerializedItems serialized items
+        * @param aSerializedItemIds serialized item IDs
+        */
+        void NotifyModifiedL(CMdCSerializationBuffer& aSerializedItems, 
+							 CMdCSerializationBuffer& aSerializedItemIds);
+
+       /**
+        * notifiers that items has been modified
+        * @param aObjectIds object IDs
+        */
+        void NotifyModifiedL(const RArray<TItemId>& aObjectIds);
+
+	   /**
+        * notifiers that objects has been set to present or not present state
+        * @param aPresent are object present state changed to present or not present
+        * @param aObjectIds object IDs
+		*/
+		void NotifyObjectPresent(TBool aPresent, const RArray<TItemId>& aObjectIds);
+
+	   /**
+        * notifiers that objects has been set to present or not present state
+        * @param aPresent are object present state changed to present or not present
+        * @param aObjectIds object IDs
+		*/
+		void NotifyRelationPresent(TBool aPresent, const RArray<TItemId>& aObjectIds);
+
+	   /**
+		* notify about removed relation items
+		* 
+		* @param aRemovedRelations removed relations
+		* @param aAdditionalRemovedRelations possible additional removed relations
+		*/
+		void NotifyRemovedRelationItemsL( CMdCSerializationBuffer& aBuffer );
+		
+		/**
+		 * Notifiers that items has been removed. 
+		 * Can be only used for default namespace.
+		 * 
+		 * @param aItemIdArray modified item IDs
+		 */
+		void NotifyRemovedL(const RArray<TItemId>& aItemIdArray);
+		
+		/**
+        * notifiers that items has been removed
+        * @param aSerializedItemIds serialized item IDs
+        * @param aItemIsConfidential are items confidential
+        */
+        void NotifyRemovedL(CMdCSerializationBuffer& aSerializedItemIds, TBool aItemIsConfidential );
+
+		void NotifySchemaAddedL();
+		
+		TBool CheckForNotifier( TUint32 aNotifyTypes );
+	
+	private: // data members
+
+        /** the entry array */
+        RArray<TEntry> iEntries;
+
+        /** the comparator */
+        CMdSNotifyComparator* iComparator;
+        
+        TInt iDataAccessCount;
+    };
+
+#endif	// __MDSNOTIFIER_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsnotifycomparator.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,254 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Comparator algorithms for notifier*
+*/
+
+#ifndef __MDSNOTIFYCOMPARATOR_H__
+#define __MDSNOTIFYCOMPARATOR_H__
+
+#include <e32base.h>
+
+#include "mdccommon.h"
+
+class CMdCSerializationBuffer;
+class TMdCRelation;
+class TMdCRelationCondition;
+
+/**
+* A collection of algorithms for comparing events against
+* criteria profile of notifier. The event either does not
+* or does match the profile set by the given criteria.
+*/
+class CMdSNotifyComparator : public CBase
+    {
+    public: // public construction
+
+        /** static construction */
+        static CMdSNotifyComparator* NewL();
+        static CMdSNotifyComparator* NewLC();
+
+        /** destructor */
+        virtual ~CMdSNotifyComparator();
+
+    private: // private construction
+
+        /** constructor */        
+        CMdSNotifyComparator();
+
+        /** 2nd phase constructor */
+        void ConstructL();
+
+    public: // methods
+
+        /**
+        * Matches items against the given condition
+        * 
+        * @param aType listener's type
+        * @param aSerializedCondition serialized condition to be matched 
+        *                             against
+        * @param aSerializedItems the items to compare
+        * @param aSerializedItemIds the item IDs (successful and failed IDs)
+        * @param aMatchingItemIdArray matching object IDs
+        * 
+        * @return If true at least some item matches.
+        */
+        TBool MatchL(TDefId aNamespaceId, TUint32 aType,
+        		CMdCSerializationBuffer& aSerializedCondition,
+        		CMdCSerializationBuffer& aSerializedItems,
+		    	CMdCSerializationBuffer& aSerializedItemIds,
+		    	RArray<TItemId>& aMatchingItemIdArray, 
+		    	TBool aAllowConfidential);
+
+		/**
+        * Matches object against the given condition. This variant matches only
+        * object conditions.
+        * 
+        * @param aSerializedCondition serialized condition to be matched 
+        *                             against
+        * @param aSerializedItem the object to compare (buffer's position is 
+        *                        in the begin of object)
+        * @param aObjectId object ID
+        * @param aAllowConfidential allow confidential objects
+        * 
+        * @return Does object match with condition.
+		*/
+		TBool MatchObjectL(CMdCSerializationBuffer& aSerializedCondition,
+		    	CMdCSerializationBuffer& aSerializedItem,
+		    	TItemId aObjectId, TBool aAllowConfidential);
+
+		/**
+        * Matches event against the given condition. This variant matches only
+        * event conditions.
+        * 
+        * @param aSerializedCondition serialized condition to be matched 
+        *                             against
+        * @param aSerializedItem the event to compare (buffer's position is in 
+        *                        the begin of event)
+        * @param aEventId event ID
+        * 
+        * @return Does event match with condition.
+		*/
+		TBool MatchEventL(CMdCSerializationBuffer& aSerializedCondition,
+		    	CMdCSerializationBuffer& aSerializedItem, TItemId aEventId);
+
+		/**
+        * Matches relation against the given condition. This variant matches 
+        * only relation conditions.
+        * 
+        * @param aSerializedCondition serialized condition to be matched 
+        *                             against
+        * @param aSerializedItem the relation to compare (buffer's position is 
+        *                        in the begin of relation)
+        * @param aRelationId relation ID
+        * 
+        * @return Does relation match with condition.
+		*/
+		TBool MatchRelationL(CMdCSerializationBuffer& aSerializedCondition,
+		    	CMdCSerializationBuffer& aSerializedItem, TItemId aRelationId);
+
+        /**
+        * Matches object IDs against the given condition. This variant matches 
+        * only object ID conditions.
+        * 
+        * @param aSerializedCondition serialized condition to be matched 
+        *                             against
+        * @param aItemIdArray the object IDs to compare
+        * @param aMatchingItemIdArray matching object IDs
+        * 
+        * @return If true all objects matches and result is same as 
+        *         aItemIdArray, so aMatchingItemIdArray might not contain any 
+        *         IDs in that case.
+        */
+		TBool MatchObjectIdsL(CMdCSerializationBuffer& aSerializedCondition,
+		    	const RArray<TItemId>& aItemIdArray,
+		    	RArray<TItemId>& aMatchingItemIdArray);
+
+		/**
+	     * Matches relation items against the given condition.
+	     * This variant matches only relation conditions.
+	     * 
+	     * @param aSerializedCondition serialized condition to be matched 
+	     *                             against
+	     * @param aSerializedItems the relation to compare (buffer's position 
+	     *                         is in the begin of relation)
+	     * @param aMatchingItemIdArray relation ID array
+	     * 
+	     * @return Does relation match with condition.
+		 */
+		TBool MatchRelationItemsL(CMdCSerializationBuffer& aSerializedCondition,
+				CMdCSerializationBuffer& aSerializedItems,
+			    RArray<TItemId>& aMatchingItemIdArray);
+
+		/**
+	     * Matches relation items against the given condition.
+	     * This variant matches only relation conditions.
+	     * 
+	     * @param aSerializedCondition serialized condition to be matched 
+	     *                             against
+	     * @param aRelation relation
+	     * 
+	     * @return Does relation match with condition.
+		 */
+		TBool MatchRelationItemL(CMdCSerializationBuffer& aSerializedCondition,
+				const TMdCRelation& aRelation);
+
+    private:
+        /**
+        * Compare string begins against the given string
+        * @param aDes contains reference to the string  
+        * @param aCompareDes reference to the compared string
+        * @return compare result
+        */
+	    TBool CompareDesBeginsWith( TDesC16& aDes, TDesC16& aCompareDes );
+
+        /**
+        * Compare string ends with the given string
+        * @param aDes contains reference to the string  
+        * @param aCompareDes reference to the compared string
+        * @return compare result
+        */
+        TBool CompareDesEndsWith( TDesC16& aDes, TDesC16& aCompareDes );
+
+        /**
+        * Finds string with the given string
+        * @param aDes contains reference to the string  
+        * @param aCompareDes reference to the searched string
+        * @return compare result
+        */
+ 		TBool FindDes( TDesC16& aDes, TDesC16& aFindDes );
+
+		/**
+         * Matches object ID against the given logic condition which contains 
+         * object ID conditions. Caller must set condition buffer to begin of 
+         * the logic condition.
+         * 
+         * @param aSerializedCondition serialized logic condition to be 
+         *                             matched against
+         * @param aObjectId object ID
+         * 
+         * @return Does relation match with condition.
+		 */
+		TBool MatchObjectIdToObjectIdConditionsL(
+				CMdCSerializationBuffer& aSerializedCondition, 
+				TItemId aObjectId);
+
+		/**
+         * Matches object ID against the given logic condition which contains 
+         * object ID conditions. Caller must set condition buffer to begin of 
+         * the logic condition.
+         * 
+         * @param aSerializedCondition serialized logic condition to be 
+         *                             matched against
+         * @param aSerializedItem serializad object
+         * @param aAllowConfidential is confidential objects allowed
+         * 
+         * @return Does object match with condition.
+		 */
+        TBool CheckObjectL( CMdCSerializationBuffer& aSerializedCondition, 
+        		CMdCSerializationBuffer& aSerializedItem,
+        		TBool aAllowConfidential );
+		/**
+         * Matches object's property against the given logic condition which 
+         * contains object ID conditions.
+         * 
+         * @param aSerializedCondition serialized logic condition to be 
+         *                             matched against
+         * @param aSerializedItem serializad object
+         * 
+         * @return Does object's propertys match with condition.
+		 */
+        TBool CheckPropertyL( CMdCSerializationBuffer& aSerializedCondition,
+    			CMdCSerializationBuffer& aSerializedItem );
+
+        /**
+         * Matches relation IDs in given condition against given one.
+         * 
+         * @param aRelationCondition relation condition
+         * @param aSerializedCondition serialized ids to be matched against
+         * @param aRelationId the relation IDs to compare
+         * 
+         * @return ETrue if relation match
+         */
+        TBool MatchRelationIdsL(
+        		const TMdCRelationCondition& aRelationCondition, 
+        		CMdCSerializationBuffer& aSerializedCondition,
+        		TItemId aRelationId);
+
+        inline TBool BoolEqual( TBool aLeft, TBool aRight )
+        	{
+        	return (aLeft && aRight || !aLeft && !aRight);
+        	}
+    };
+
+#endif	// __MDSNOTIFYCOMPARATOR_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsobjectdef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,269 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one object and it's properties
+*
+*/
+
+#ifndef __MDSOBJECTDEF_H__
+#define __MDSOBJECTDEF_H__
+
+#include <e32base.h>
+#include "mdsitemdef.h"
+
+class CMdsPropertyDef;
+
+
+/**
+ *  Metadata object class
+ *
+ *  This class is responsible for holding information about one object
+ *
+ */
+class CMdsObjectDef : public CMdsItemDef
+    {
+    friend class CMdsSchema;
+    friend class CMdsNamespaceDef;
+
+public:
+
+	struct TMdsColumnOrder
+		{
+		TInt32 iColumnId;
+		const CMdsPropertyDef& iPropertyDef;
+		};
+
+	enum TObjectDefFlags
+		{
+		EObjectDefFlagsNone    = 0x0000,
+		EObjectDefFlagsContext = 0x0001,
+		};
+
+	/**
+	 * Create new objectdef object
+	 * @param aId id of object
+	 * @param aName name of object
+	 * @param aParent parent to actual object
+	 * @return pointer to new created object
+	 */
+    static CMdsObjectDef* NewL( const TDesC& aName, const CMdsObjectDef* aParent );
+
+	/**
+	 * Create new objectdef object
+	 * @param aId id of object
+	 * @param aName name of object
+	 * @param aParent parent to actual object
+	 * @return pointer to new created object
+	 */
+    static CMdsObjectDef* NewLC( const TDesC& aName, const CMdsObjectDef* aParent );
+
+    virtual ~CMdsObjectDef();
+    
+	/**
+	 * Add property to property array
+	 * @see CommonAddPropertyL
+	 * @see AddMinMaxValue
+	 */
+	
+	void AddPropertyL( const TDesC& aName, TPropertyType aType,
+			  const TMdCValueUnion& aMinAdd, const TMdCValueUnion& aMaxAdd,
+			  TBool aReadOnly, TBool aMandatory, TBool aIndexed );
+
+	/**
+	 * Add property to property array
+	 * @see CommonAddPropertyL
+	 * @see AddMinMaxValue
+	 */
+	void AddPropertyL( const TDesC& aName, TPropertyType aType,
+            TInt32 aMinAdd, TInt32 aMaxAdd,
+            TBool aReadOnly, TBool aMandatory, TBool aIndexed );
+
+	/**
+	 * Add property to property array
+	 * @see CommonAddPropertyL
+	 * @see AddMinMaxValue
+	 */
+	void AddPropertyL( const TDesC& aName, TPropertyType aType,
+            TUint32 aMinAdd, TUint32 aMaxAdd,
+            TBool aReadOnly, TBool aMandatory, TBool aIndexed );
+
+	/**
+	 * Add property to property array
+	 * @see CommonAddPropertyL
+	 * @see AddMinMaxValue
+	 */
+	void AddPropertyL( const TDesC& aName, TPropertyType aType,
+            const TInt64& aMinAdd, const TInt64& aMaxAdd,
+            TBool aReadOnly, TBool aMandatory, TBool aIndexed );
+
+	/**
+	 * Add property to property array
+	 * @see CommonAddPropertyL
+	 * @see CMdsPropertyDef::AddMinMaxValue
+	 */
+	void AddPropertyL( const TDesC& aName, TPropertyType aType,
+            const TReal& aMinAdd, const TReal& aMaxAdd,
+            TBool aReadOnly, TBool aMandatory, TBool aIndexed );
+    
+    const CMdsPropertyDef* GetPropertyByIdL( TDefId aId ) const;
+
+	CMdsPropertyDef* GetProperty( TUint32 aIndex ) const;
+
+	CMdsPropertyDef* GetProperty( const TDesC& aName ) const;
+
+	/**
+	 * How many properties have object
+	 * return properties.Count()
+	 */
+	inline TInt GetPropertiesCount() const;
+
+	/**
+	 * Gets property count of object including it's parents
+	 *
+	 * @return property count
+	 */
+	TInt GetAllPropertiesCount() const;
+
+	/**
+	 * Get property count of mandatory properties.
+	 * 
+	 * @return mandatory property count
+	 */
+	TInt GetMandatoryPropertyCount() const;
+	
+	void SetStoredEveryInDB();
+
+	void SetNotStoredEveryInDB();
+
+	/*
+	 * Set that object is already stored in DB
+	 */	
+	inline void SetC2PStoredInDB();
+
+	inline TBool GetC2PStoredInDB() const;
+
+	/*
+	 * Gets parent of the object
+	 */
+	inline const CMdsObjectDef* GetParent() const;
+
+	/**
+	 * Get property column Id
+	 *
+	 * @param aPropertyNo number of property in property array
+	 * @return ColumnId
+	 */
+	inline const TMdsColumnOrder& GetPropertyColumnL( TInt aIndex ) const;
+
+	void ImportFromDBL();
+
+	/**
+	 * Def flags support
+	 */
+	inline void ResetFlags();
+
+	inline TObjectDefFlags GetFlags() const;
+
+	inline void SetFlags(TObjectDefFlags aFlags);
+
+    /**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+    TUint32 RequiredBufferSize();
+
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling) and return new position of serialized buffer.
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    TMdCOffset SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreeSpace);
+		
+protected:
+
+	/**
+	 * Create and add property to array
+	 * @param aName name of property
+	 * @param aType type of property
+	 * @param aReadOnly if property is read-only
+	 * @param aReadOnly if property is mandatory
+	 * @param aId property id
+	 * @return pointer to new created property (on error - leave)
+	 */
+	CMdsPropertyDef* CommonAddPropertyL( const TDesC& aName, TPropertyType aType,
+			TBool aReadOnly, TBool aMandatory, TBool aIndexed );
+	
+	CMdsPropertyDef* CommonAddPropertyL( const TDesC& aName, TPropertyType aType,
+			TUint32 aFlags, TDefId aId );
+
+	void MergeL( CMdsObjectDef* aObjectDef, const TBool& aDryRun );
+
+	void AddPropertyL( const TDefId aId, TPropertyType aType, TUint32 aFlags,
+            const TDesC& aMinAdd, const TDesC& aMaxAdd, const TDesC& aName );
+
+	void StoreToDBL( TDefId aNamespaceDefId );
+
+	/**
+	 * Searching for property only in actual object (not in parents)
+	 *
+	 * @param aName name of property to find
+	 * @return finded property or NULL
+	 */
+    CMdsPropertyDef* FindProperty( const TDesC& aName ) const;
+	
+private:
+    inline CMdsObjectDef( const CMdsObjectDef* aParent );
+
+	/**
+	 * 2nd phase constructor
+	 * @param aName name of property
+	 */
+    void ConstructL( const TDesC& aName );
+
+private: // data
+
+    /**
+     * Store every property read from schema file.
+     */
+	RPointerArray<CMdsPropertyDef> iPropertyDefs;
+
+	/**
+	 * store bind between column and property in object
+	 */
+	RArray<TMdsColumnOrder> iCol2Prop;
+
+	/**
+	 * ObjectDef parent, there is no exist object without parent
+	 * (exeption is Object as an ancesor to everyone, but it's created in code
+	 *  and cannot be read from file)
+	 * DO NOT DELETE, NOT OWN !!!
+	 */
+	const CMdsObjectDef* iParent;
+
+	/**
+	 * object flags (e.g. context object)
+	 * check TObjectDefFlags
+	 */
+	TObjectDefFlags iFlags;
+	
+	/**
+	 * Count of mandatory properties.
+	 */
+	TInt iMandatoryPropertyCount;
+    };
+
+#include "mdsobjectdef.inl"
+
+#endif // __MDSOBJECTDEF_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsobjectdef.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,74 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one object and it's properties
+*
+*/
+
+/**
+ * How many properties have object
+ * return properties.Count()
+ */
+inline TInt CMdsObjectDef::GetPropertiesCount() const
+	{
+	return iPropertyDefs.Count();
+	}
+
+inline void CMdsObjectDef::SetC2PStoredInDB()
+	{
+	SetFlag( EStoredFlagsC2P );
+	}
+
+inline TBool CMdsObjectDef::GetC2PStoredInDB() const
+	{
+	return GetFlag( EStoredFlagsC2P );
+	}
+
+/*
+ * Gets parent of the object
+ */
+inline const CMdsObjectDef* CMdsObjectDef::GetParent() const
+	{
+	return iParent;
+	}
+
+/**
+ * Get property column Id
+ *
+ * @param aPropertyNo number of property in property array
+ * @return ColumnId
+ */
+inline const CMdsObjectDef::TMdsColumnOrder& CMdsObjectDef::GetPropertyColumnL( TInt aIndex ) const
+	{
+	if (aIndex < 0 || aIndex >= iCol2Prop.Count())
+		{
+		User::Leave( KErrNotFound );
+		}
+	return iCol2Prop[aIndex];
+	}
+
+inline void CMdsObjectDef::ResetFlags()
+	{
+	iFlags = EObjectDefFlagsNone;
+	}
+
+inline CMdsObjectDef::TObjectDefFlags CMdsObjectDef::GetFlags() const
+	{
+	return iFlags;
+	}
+
+inline void CMdsObjectDef::SetFlags(TObjectDefFlags aFlags)
+	{
+	iFlags = aFlags;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsobjectlocklist.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,129 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Object locking features*
+*/
+
+#ifndef __MDSOBJECTLOCKLIST_H__
+#define __MDSOBJECTLOCKLIST_H__
+
+#include <e32base.h>
+
+#include "mdscommoninternal.h"
+
+class TMdSLockEntry;
+class CMdSServerSession;
+class CMdsNamespaceDef;
+
+/**
+* Metadata object locking.
+* When opening objects for modifications, objects
+* is locked so that no other session can modify the
+* same object at same time.
+*/
+class CMdSObjectLockList : public CBase
+    {
+    public: // Constructors and destructor
+
+        virtual ~CMdSObjectLockList();
+
+        static CMdSObjectLockList* NewL();
+        static CMdSObjectLockList* NewLC();
+
+    private: // Private constructors
+
+        void ConstructL();
+
+    public: // Public functions
+        /**
+        * Locks object for modifying.
+        * @param aSession   Session where object is being modified.
+        * @param aNamespace Object's owner namespace
+        * @param aObjId     Object id that is being modified.
+        * @return           Returns whether object could be locked or not.
+        */
+        void LockObjectL( const CMdSServerSession& aSession, 
+        		const CMdsNamespaceDef& aNamespace, const TItemId aObjectId );
+
+        /**
+        * Unlocks all locked objects of particular session.
+        * @param aSession   Session which locked objects are to be released.
+        */
+        void UnlockBySession( const CMdSServerSession& aSession );
+
+        /**
+        * Unlocks locked object by Id.
+        * @param aNamespace Object's owner namespace
+        * @param aObjId     Object id that is being modified.
+        */
+        void UnlockById( const CMdsNamespaceDef& aNamespace, 
+        		const TItemId aObjectId );
+
+        /**
+        * Checks if object is locked for modifying.
+        * @param aNamespace Object's owner namespace
+        * @param aObjId     An objects id which is going to be checked.
+        * @return           <code>ETrue</code> if locked.
+        *                   <code>EFalse</code> if not.
+        */
+        TBool IsLocked( const CMdsNamespaceDef& aNamespace, 
+        		const TItemId aObjectId ) const;
+
+    	/**
+    	 * Empties the object lock list.
+    	 */
+        void Reset();
+
+	protected:
+		TInt Find( const CMdsNamespaceDef& aNamespace, 
+				const TItemId aObjectId ) const;
+
+    private:
+        /**
+         * Array which have the locked objects.
+         */
+        RArray<TMdSLockEntry> iLockListArray;
+    };
+
+/**
+ * Internal data structure for storing information about locked objects.
+ */
+class TMdSLockEntry
+    {
+    public:
+        /**
+    	* Constructs a new lock list object.
+        *
+    	* @param aSession   session to which object id belongs
+        * @param aNamespace Object's owner namespace
+    	* @param aId        object id being modified
+    	*/
+    	TMdSLockEntry( const CMdSServerSession* aSession, 
+    			const CMdsNamespaceDef& aNamespace, const TItemId aId )
+    	: iSession( aSession ) , iNamespace( aNamespace ), iId( aId )
+    	    {}
+
+		static TInt Compare( const TMdSLockEntry& aFirst, 
+				const TMdSLockEntry& aSecond );
+    public:
+        /* Session where object is being modified */
+        const CMdSServerSession* iSession;
+
+        /* Object's owner namespace */
+        const CMdsNamespaceDef& iNamespace;
+
+        /* Object's id which is being modified */
+        TItemId iId;
+    };
+
+#endif  // __MDSOBJECTLOCKLIST_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdspreferences.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,410 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Stores and load preference values to and from DB
+*
+*/
+
+#ifndef __MDSPREFERENCES_H__
+#define __MDSPREFERENCES_H__
+
+#include <e32base.h>
+#include "mdsclausebuffer.h"
+#include "mdssqliteconnection.h"
+#include "mdsdbconnectionpool.h"
+#include "mdsfindsqlclausedef.h"
+
+_LIT( KMdsPreferencesDeleteKey,   "DELETE FROM MdE_Preferences WHERE Key = ?;");
+
+/**
+ *  Metadata preference class
+ *
+ *  This class is responsible for storing and loading preferences to and from DB
+ *
+ */
+class MMdsPreferences
+    {
+public:
+
+	enum TMdsPreferencesFlags
+		{
+		EPreferenceNone          = 0x00000000,
+		EPreferenceValueSet      = 0x00000001,
+		EPreferenceValueGet      = 0x00000002,
+		EPreferenceExtraSet      = 0x00000004,
+		EPreferenceExtraGet      = 0x00000008,
+		EPreferenceValueSortAsc  = 0x00000010,
+		EPreferenceValueSortDesc = 0x00000020,
+		EPreferenceExtraSortAsc  = 0x00000040,
+		EPreferenceExtraSortDesc = 0x00000080,
+		EPreferenceBothSet       = EPreferenceValueSet | EPreferenceExtraSet,
+		EPreferenceBothGet       = EPreferenceValueGet | EPreferenceExtraGet,
+		EPreferenceValueUse      = EPreferenceValueSet | EPreferenceValueGet,
+		EPreferenceExtraUse      = EPreferenceExtraSet | EPreferenceExtraGet,
+		EPreferenceAllUse        = EPreferenceValueUse | EPreferenceExtraUse
+		};
+
+	/**
+	 * HOW TO USE
+    _LIT( KTestNameValue, "TestNameValue" );
+    _LIT( KTestNameExtra, "TestNameExtra" );
+    _LIT( KTestNameAll,   "TestNameAll" );
+    CMdsPreferences::InsertToDefaultDBL( db, KTestNameValue, CMdsPreferences::EPreferenceValueSet, 12.5f );
+    CMdsPreferences::InsertToDefaultDBL( db, KTestNameExtra, CMdsPreferences::EPreferenceExtraSet, 99 );
+    CMdsPreferences::InsertToDefaultDBL( db, KTestNameAll, CMdsPreferences::EPreferenceBothSet, KTestNameExtra, -10 );
+    
+    CMdsPreferences::UpdateDefaultDBL( db, KTestNameValue, CMdsPreferences::EPreferenceValueSet, 578 );
+    CMdsPreferences::UpdateDefaultDBL( db, KTestNameExtra, CMdsPreferences::EPreferenceExtraSet, 12 );
+    CMdsPreferences::UpdateDefaultDBL( db, KTestNameAll, CMdsPreferences::EPreferenceBothSet, 345.64f, -666 );
+
+    CMdsPreferences::DeleteFromDefaultDBL( db, KTestNameValue );
+    CMdsPreferences::DeleteFromDefaultDBL( db, KTestNameValue, CMdsPreferences::EPreferenceValueSet, 578 );
+    CMdsPreferences::DeleteFromDefaultDBL( db, KTestNameExtra, CMdsPreferences::EPreferenceExtraSet, 12 );
+    CMdsPreferences::DeleteFromDefaultDBL( db, KTestNameAll, CMdsPreferences::EPreferenceBothSet, 345.64f, -666 );
+    */
+
+
+	template<class T>
+	static TInt InsertL( const TDesC& aKey, TUint32 aFlags, const T& aValue, TInt64 aExtraValue = 0 )
+		{
+		_LIT( KMdsPreferencesInsertValue,   "INSERT INTO MdE_Preferences(Key, Value) VALUES(?, ?);");
+		_LIT( KMdsPreferencesInsertAll,     "INSERT INTO MdE_Preferences(Key, Value, ExtraValue) VALUES(?, ?, ?);");
+		
+		TInt result = 0;
+		RRowData data;
+		CleanupClosePushL( data );
+		data.AppendL( TColumn(aKey) );
+		data.AppendL( TColumn(aValue) );
+		
+		CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+		if ( aFlags & EPreferenceValueSet && aFlags & EPreferenceExtraSet )
+			{
+			data.AppendL( TColumn(aExtraValue) );
+			result = connection.ExecuteL( KMdsPreferencesInsertAll, data );
+			}
+		else if ( aFlags & EPreferenceValueSet )
+			{
+			result = connection.ExecuteL( KMdsPreferencesInsertValue, data );
+			}
+		
+		else
+			{
+			User::Leave( KErrCorrupt );
+			}
+		
+		CleanupStack::PopAndDestroy( &data );
+		return result;
+		}
+
+	template<class T>
+	static TInt UpdateL( const TDesC& aKey, TUint32 aFlags, const T& aValue, TInt64 aExtraValue = 0 )
+		{
+		_LIT( KMdsPreferencesUpdateValue, "UPDATE MdE_Preferences SET Value = ? WHERE Key = ?;");
+		_LIT( KMdsPreferencesUpdateExtra, "UPDATE MdE_Preferences SET ExtraValue = ? WHERE Key = ? AND Value = ?;");
+		_LIT( KMdsPreferencesUpdateBoth,  "UPDATE MdE_Preferences SET Value = ?, ExtraValue = ? WHERE Key = ?;");
+		
+		TInt result = 0;
+		RRowData data;
+		CleanupClosePushL( data );
+		
+		CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+		if ( aFlags & EPreferenceValueSet && aFlags & EPreferenceExtraSet )
+			{
+			data.AppendL( TColumn(aValue) );
+			data.AppendL( TColumn(aExtraValue) );
+			data.AppendL( TColumn(aKey) );
+			result = connection.ExecuteL( KMdsPreferencesUpdateBoth, data );
+			}
+		else if ( aFlags & EPreferenceValueSet )
+			{
+			data.AppendL( TColumn(aValue) );
+			data.AppendL( TColumn(aKey) );
+			result = connection.ExecuteL( KMdsPreferencesUpdateValue, data );
+			}
+		else if ( aFlags & EPreferenceExtraSet )
+			{
+			data.AppendL( TColumn(aExtraValue) );
+			data.AppendL( TColumn(aKey) );
+			data.AppendL( TColumn(aValue) );
+			result = connection.ExecuteL( KMdsPreferencesUpdateExtra, data );
+			}
+		else
+			{
+			User::Leave( KErrCorrupt );
+			}
+		
+		CleanupStack::PopAndDestroy( &data );
+		return result;
+		}
+
+	template<class T>
+	static TInt DeleteL( const TDesC& aKey )
+		{	
+		TInt result = 0;
+		RRowData data;
+		CleanupClosePushL( data );
+		data.AppendL( TColumn(aKey) );
+		
+		CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+		result = connection.ExecuteL( KMdsPreferencesDeleteKey, data );
+		
+		CleanupStack::PopAndDestroy( &data );
+		return result;
+		}
+
+	template<class T>
+	static TInt DeleteL( const TDesC& aKey, TUint32 aFlags, const T& aValue, TInt64 aExtraValue = 0 )
+		{
+		_LIT( KMdsPreferencesDeleteValue, "DELETE FROM MdE_Preferences WHERE Key = ? AND Value = ?;");
+		_LIT( KMdsPreferencesDeleteExtra, "DELETE FROM MdE_Preferences WHERE Key = ? AND ExtraValue = ?;");
+		_LIT( KMdsPreferencesDeleteAll,   "DELETE FROM MdE_Preferences WHERE Key = ? AND Value = ? AND ExtraValue = ?;");
+		
+		TInt result = 0;
+		RRowData data;
+		CleanupClosePushL( data );
+		data.AppendL( TColumn(aKey) );
+		
+		CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+		if ( aFlags == EPreferenceNone )
+			{
+			result = connection.ExecuteL( KMdsPreferencesDeleteKey, data );
+			}
+		else if ( aFlags & EPreferenceValueSet && aFlags & EPreferenceExtraSet )
+			{
+			data.AppendL( TColumn(aValue) );
+			data.AppendL( TColumn(aExtraValue) );
+			result = connection.ExecuteL( KMdsPreferencesDeleteAll, data );
+			}
+		else if ( aFlags & EPreferenceValueSet )
+			{
+			data.AppendL( TColumn(aValue) );
+			result = connection.ExecuteL( KMdsPreferencesDeleteValue, data );
+			}
+		else if ( aFlags & EPreferenceExtraSet )
+			{
+			data.AppendL( TColumn(aExtraValue) );
+			result = connection.ExecuteL( KMdsPreferencesDeleteExtra, data );
+			}
+		else
+			{
+			User::Leave( KErrCorrupt );
+			}
+		
+		CleanupStack::PopAndDestroy( &data );
+		return result;
+		}
+
+	template<class T>
+	static TInt GetL( const TDesC& aKey, TUint32 aFlags, T& aValue, TInt64* aExtraValue = NULL )
+		{
+		_LIT( KMdsPreferencesGetKey,        "SELECT Value, ExtraValue FROM MdE_Preferences WHERE Key = ? ");
+
+		_LIT( KMdsPreferencesGetValue,      "AND Value = ? ");
+		_LIT( KMdsPreferencesGetExtra,      "AND ExtraValue = ? ");
+		_LIT( KMdsPreferencesGetAll,        "AND Value = ? AND ExtraValue = ? ");
+
+		_LIT( KMdsPreferencesSortBegin,     "ORDER BY ");
+		_LIT( KMdsPreferencesSortValueAsc,  "Value ASC ");
+		_LIT( KMdsPreferencesSortValueDesc, "Value DESC ");
+		_LIT( KMdsPreferencesSortExtraAsc,  "ExtraValue ASC ");
+		_LIT( KMdsPreferencesSortExtraDesc, "ExtraValue DESC ");
+		_LIT( KMdsPreferencesSortEnd,       "LIMIT 1;");
+
+		const TUint32 KSortFlags = 	EPreferenceValueSortAsc  | 
+									EPreferenceValueSortDesc | 
+									EPreferenceExtraSortAsc  | 
+									EPreferenceExtraSortDesc;
+
+		CMdsClauseBuffer* sortBuffer = CMdsClauseBuffer::NewLC( 8 ); // estimated minimum lenght for sort rules
+
+		// check if there is some order rules
+		if( KSortFlags & aFlags )
+			{
+			sortBuffer->AppendL( KMdsPreferencesSortBegin );
+			
+			TBool notFirstOrderRule = EFalse;
+			
+			if( EPreferenceValueSortAsc & aFlags )
+				{
+				sortBuffer->AppendL( KMdsPreferencesSortValueAsc );
+				
+				notFirstOrderRule = ETrue;
+				}
+			
+			if( EPreferenceValueSortDesc & aFlags )
+				{
+				if( notFirstOrderRule )
+					{
+					sortBuffer->AppendL( KComma );
+					}
+				sortBuffer->AppendL( KMdsPreferencesSortValueDesc );
+				notFirstOrderRule = ETrue;
+				}
+			
+			if( EPreferenceExtraSortAsc & aFlags )
+				{
+				if( notFirstOrderRule )
+					{
+					sortBuffer->AppendL( KComma );
+					}
+				sortBuffer->AppendL( KMdsPreferencesSortExtraAsc );
+				notFirstOrderRule = ETrue;
+				}
+
+			if( EPreferenceExtraSortDesc & aFlags )
+				{
+				if( notFirstOrderRule )
+					{
+					sortBuffer->AppendL( KComma );
+					}
+				sortBuffer->AppendL( KMdsPreferencesSortExtraDesc );
+				notFirstOrderRule = ETrue;
+				}
+			}
+
+		// always added because it limits result count to 1
+		sortBuffer->AppendL( KMdsPreferencesSortEnd );
+
+		CMdsClauseBuffer* selectBuffer = CMdsClauseBuffer::NewLC( 
+				64 + sortBuffer->ConstBufferL().Length() ); // estimated minimum lenght for select and sort rules
+		
+		/// always added default select
+		selectBuffer->AppendL( KMdsPreferencesGetKey );
+
+		TInt result = 0;
+		RRowData data;
+		CleanupClosePushL( data );
+		data.AppendL( TColumn(aKey) );
+		
+		RRowData getData;
+		CleanupClosePushL( getData );
+		getData.AppendL( TColumn(aValue) );
+		getData.AppendL( TColumn(EColumnInt64) );
+		
+		if ( !aExtraValue && (aFlags & EPreferenceExtraSet || aFlags & EPreferenceExtraGet) )
+			{
+			User::Leave( KErrArgument );
+			}
+		
+		CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+		RMdsStatement query;
+		CleanupClosePushL( query );
+		if ( aFlags == EPreferenceNone )
+			{
+			// do nothing
+			}
+		else if ( aFlags & EPreferenceValueSet && aFlags & EPreferenceExtraSet )
+			{
+			data.AppendL( TColumn(aValue) );
+			data.AppendL( TColumn(*aExtraValue) );
+			
+			selectBuffer->AppendL( KMdsPreferencesGetAll );
+			selectBuffer->AppendL( sortBuffer->ConstBufferL() );
+
+			connection.ExecuteQueryL( selectBuffer->ConstBufferL(), query, data );
+			
+			
+			if ( connection.NextRowL( query, getData ) )
+				{
+				result = 1;
+				if (aFlags & EPreferenceValueGet)
+					{
+					getData.Column( 0 ).Get( aValue );
+					}
+				
+				if (aFlags & EPreferenceExtraGet)
+					{
+					getData.Column( 1 ).Get( *aExtraValue );
+					}
+				}
+			}
+		else if ( aFlags & EPreferenceValueSet )
+			{
+			data.AppendL( TColumn(aValue) );
+			
+			selectBuffer->AppendL( KMdsPreferencesGetValue );
+			selectBuffer->AppendL( sortBuffer->ConstBufferL() );
+			
+			connection.ExecuteQueryL( selectBuffer->ConstBufferL(), query, data );
+			if ( connection.NextRowL( query, getData ) )
+				{
+				result = 1;
+				if (aFlags & EPreferenceValueGet)
+					{
+					getData.Column( 0 ).Get( aValue );
+					}
+				
+				if (aFlags & EPreferenceExtraGet)
+					{
+					getData.Column( 1 ).Get( *aExtraValue );
+					}
+				}
+			}
+		else if ( aFlags & EPreferenceExtraSet )
+			{
+			data.AppendL( TColumn(*aExtraValue) );
+			
+			selectBuffer->AppendL( KMdsPreferencesGetExtra );
+			selectBuffer->AppendL( sortBuffer->ConstBufferL() );
+
+			connection.ExecuteQueryL( selectBuffer->ConstBufferL(), query, data );
+			if ( connection.NextRowL( query, getData ) )
+				{
+				result = 1;
+				if (aFlags & EPreferenceValueGet)
+					{
+					getData.Column( 0 ).Get( aValue );
+					}
+				
+				if (aFlags & EPreferenceExtraGet)
+					{
+					getData.Column( 1 ).Get( *aExtraValue );
+					}
+				}
+			}
+		else
+			{
+			selectBuffer->AppendL( sortBuffer->ConstBufferL() );
+
+			connection.ExecuteQueryL( selectBuffer->ConstBufferL(), query, data );
+			if ( connection.NextRowL( query, getData ) )
+				{
+				result = 1;
+				if (aFlags & EPreferenceValueGet)
+					{
+					getData.Column( 0 ).Get( aValue );
+					}
+				
+				if (aFlags & EPreferenceExtraGet)
+					{
+					getData.Column( 1 ).Get( *aExtraValue );
+					}
+				}
+			}
+
+		CleanupStack::PopAndDestroy( &query );
+		CleanupStack::PopAndDestroy( &getData );
+		CleanupStack::PopAndDestroy( &data );
+		
+		CleanupStack::PopAndDestroy( selectBuffer );
+		CleanupStack::PopAndDestroy( sortBuffer );
+
+		return result;
+		}    
+    
+private:
+
+    };
+
+
+#endif // __MDSPREFERENCES_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdspropertydef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,264 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one property
+*
+*/
+
+#ifndef __MDSPROPERTYDEF_H__
+#define __MDSPROPERTYDEF_H__
+
+#include "mdsitemdef.h"
+#include "mdssqliteconnection.h"
+
+class CMdCSerializationBuffer;
+
+
+/**
+ *  Metadata namespace class
+ *
+ *  This class is responsible for holding information about one property
+ *
+ */
+class CMdsPropertyDef : public CMdsItemDef
+    {
+    friend class CMdsSchema;
+    friend class CMdsObjectDef;
+public:
+
+	/**
+	 * Create new property object
+	 * @param aId id of property
+	 * @param aName name of property
+	 * @param aType type of property
+	 * @param aMandatory mandatory flag
+	 * @param aReadOnly read-only flag
+	 * @param aIndexed should this property be indexed or not
+	 * @return pointer to new created property
+	 */
+    static CMdsPropertyDef* NewL( const TDesC& aName, TPropertyType aType,
+    		 TBool aReadOnly, TBool aMandatory, TBool aIndexed );
+
+	/**
+	 * Create new property object
+	 * @param aId id of property
+	 * @param aName name of property
+	 * @param aType type of property
+	 * @param aMandatory mandatory flag
+	 * @param aReadOnly read-only flag
+	 * @param aIndexed should this property be indexed or not
+	 * @return pointer to new created property
+	 */
+    static CMdsPropertyDef* NewLC( const TDesC& aName, TPropertyType aType,
+    		TBool aReadOnly, TBool aMandatory, TBool aIndexed );
+
+	/**
+	 * Create new property object
+	 * @param aId id of property
+	 * @param aName name of property
+	 * @param aType type of property
+	 * @param aFlags property flag
+	 * @return pointer to new created property
+	 */
+    static CMdsPropertyDef* NewL( const TDesC& aName, TPropertyType aType,
+    		TUint32 aFlags );
+
+	/**
+	 * Create new property object
+	 * @param aId id of property
+	 * @param aName name of property
+	 * @param aType type of property
+	 * @param aFlags property flag
+	 * @return pointer to new created property
+	 */
+    static CMdsPropertyDef* NewLC( const TDesC& aName, TPropertyType aType,
+    		TUint32 aFlags );
+
+    
+    virtual ~CMdsPropertyDef();
+    
+    
+    void StoreToDBL( TDefId aObjectDefId );
+    
+	/**
+	 * Add minimun and maximum value to property
+	 *  leave on type mismatch
+	 * @param aMinValue min value
+	 * @param aMaxValue max value
+	 */
+	void AddMinMaxValueL( const TInt32& aMinValue, const TInt32& aMaxValue );
+
+	/**
+	 * Add minimun and maximum value to property
+	 *  leave on type mismatch
+	 * @param aMinValue min value
+	 * @param aMaxValue max value
+	 */
+	void AddMinMaxValueL( const TUint32& aMinValue, const TUint32& aMaxValue );
+
+	/**
+	 * Add minimun and maximum value to property
+	 *  leave on type mismatch
+	 * @param aMinValue min value
+	 * @param aMaxValue max value
+	 */
+	void AddMinMaxValueL( const TInt64& aMinValue, const TInt64& aMaxValue );
+
+	/**
+	 * Add minimun and maximum value to property
+	 *  leave on type mismatch
+	 * @param aMinValue min value
+	 * @param aMaxValue max value
+	 */
+	void AddMinMaxValueL( const TReal& aMinValue, const TReal& aMaxValue );
+
+	/**
+	 * Check if property's value is between allowed minimum and maximum value.
+	 * 
+	 * @param aValue property's value
+	 * 
+	 * @return is value between allowed minimum and maximum value
+	 */
+	inline TBool CheckMinMaxValue( TInt32 aValue ) const;
+
+	/**
+	 * Check if property's value is between allowed minimum and maximum value.
+	 * 
+	 * @param aValue property's value
+	 * 
+	 * @return is value between allowed minimum and maximum value
+	 */
+	inline TBool CheckMinMaxValue( TUint32 aValue ) const;
+
+	/**
+	 * Check if property's value is between allowed minimum and maximum value.
+	 * 
+	 * @param aValue property's value
+	 * 
+	 * @return is value between allowed minimum and maximum value
+	 */
+	inline TBool CheckMinMaxValue( const TInt64& aValue ) const;
+
+	/**
+	 * Check if property's value is between allowed minimum and maximum value.
+	 * 
+	 * @param aValue property's value
+	 * 
+	 * @return is value between allowed minimum and maximum value
+	 */
+	inline TBool CheckMinMaxValue( const TReal& aValue ) const;
+
+	/**
+	 * Get SQLite type name
+	 * @return type name
+	 */
+	const TDesC& GetSqlTypeName() const;
+
+	/**
+	 * Get SQLite property type
+	 * @return property type
+	 */
+	TColumnDataType GetSqlType() const;
+
+	/**
+	 * Get property type
+	 * @return property type
+	 */
+	inline TPropertyType GetType() const;
+
+	/**
+	 * Get property read-only
+	 * @return property read-only
+	 */
+	inline TBool GetReadOnly() const;
+
+	/**
+	 * Get property mandatory
+	 * @return is property mandatory
+	 */
+	inline TBool GetMandatory() const;
+	
+	/**
+	 * Get property indexed flag
+	 * @return is property indexed
+	 */
+	inline TBool GetIndexed() const;
+
+	TBool operator==( const CMdsPropertyDef& aPropertyDef ) const;
+
+	inline TBool operator!=( const CMdsPropertyDef& aPropertyDef ) const;
+	
+    /**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+    TUint32 RequiredBufferSize();
+
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling) and return new position of serialized buffer.
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    TMdCOffset SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreeSpace);
+	
+	
+private:
+	/**
+	 * default constructor
+	 */
+    inline CMdsPropertyDef(  TPropertyType aType );
+
+	/**
+	 * 2nd phase constructor
+	 * @param aName name of property
+	 * @param aMinCount min count of property
+	 * @param aMaxCount max count of property
+	 * @param aMandatory mandatory property
+	 * @param aIndexed create an index of this property
+	 */
+    void ConstructL( const TDesC& aName, TBool aReadOnly, TBool aMandatory, TBool aIndexed );
+
+
+private:
+
+	/**
+	 * type of property
+	 */
+	const TPropertyType iType;
+	
+	/**
+	 * Minimum value for property
+	 */	
+	TMdCValueUnion iMinValue;
+
+	/**
+	 * Maximum value for property
+	 */
+	TMdCValueUnion iMaxValue;
+	
+	/**
+	 * property read-only flag
+	 */
+	TUint32 iPropertyFlags;
+	
+	/**
+	 * Should this property be indexed or not.
+	 */
+	TBool iIndexed;
+    };
+
+#include "mdspropertydef.inl"
+
+#endif // __MDSPROPERTYDEF_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdspropertydef.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one property
+*
+*/
+
+
+inline TBool CMdsPropertyDef::CheckMinMaxValue( TInt32 aValue ) const
+	{
+	return ( aValue >= iMinValue.iInt32 && aValue <= iMaxValue.iInt32 );
+	}
+
+inline TBool CMdsPropertyDef::CheckMinMaxValue( TUint32 aValue ) const
+	{
+	return ( aValue >= iMinValue.iUint32 && aValue <= iMaxValue.iUint32 );
+	}
+
+inline TBool CMdsPropertyDef::CheckMinMaxValue( const TInt64& aValue ) const
+	{
+	return ( aValue >= iMinValue.iInt64 && aValue <= iMaxValue.iInt64 );
+	}
+
+inline TBool CMdsPropertyDef::CheckMinMaxValue( const TReal& aValue ) const
+	{
+	return ( aValue >= iMinValue.iReal && aValue <= iMaxValue.iReal );
+	}
+
+/**
+ * Get property type
+ * @return property type
+ */
+inline TPropertyType CMdsPropertyDef::GetType() const
+	{
+	return iType;
+	}
+	
+/**
+ * Get property read-only
+ * @return property read-only
+ */
+inline TBool CMdsPropertyDef::GetReadOnly() const
+	{
+	return iPropertyFlags & EPropertyReadOnly;
+	}
+
+/**
+ * Get property mandatory
+ * @return is property mandatory
+ */
+inline TBool CMdsPropertyDef::GetMandatory() const
+	{
+	return iPropertyFlags & EPropertyMandatory;
+	}
+
+/**
+ * Get property indexed flag
+ * @return is property indexed
+ */
+inline TBool CMdsPropertyDef::GetIndexed() const
+	{
+	return iIndexed;
+	}
+
+inline TBool CMdsPropertyDef::operator!=( const CMdsPropertyDef& aPropertyDef ) const
+	{
+	return !( *this == aPropertyDef );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsquerycriteriadeserialization.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,177 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to deserialize client query cliteria
+*
+*/
+
+#ifndef __MDSQUERYCRITERIADESERIALIZATION_H__
+#define __MDSQUERYCRITERIADESERIALIZATION_H__
+
+#include <e32cmn.h>
+#include <e32def.h>
+#include <e32des8.h>
+
+#include "mdccommon.h"
+#include "mdcserializationbuffer.h"
+// added for serialization definitions !!
+#include "mdscommoninternal.h"
+// end
+
+/**
+ * Query criteria serialization.
+ */
+class CMdSQueryCriteriaDeserialization : public CBase
+	{
+	friend class CMdSFindSqlClause;
+	
+public:
+
+	/* Constructors and destructor. */
+
+	/**
+	 * Constructs a new serialized query criteria.
+	 * @param aCondition  root logic condition to serialize
+	 *
+	 * @return  query criteria serialization instance
+	 *
+	 * @leave KErrNotSupported result mode and query type don't match
+	 * @leave KErrCompletion   result mode is EModeDistinctValues and query 
+	 *                         criteria is incorrect
+	 */
+	static CMdSQueryCriteriaDeserialization* NewL(CMdCSerializationBuffer& aSerializationBuffer);
+
+	/**
+	 * Constructs a new serialized query criteria and leaves it in the
+	 * cleanup stack.
+	 * @param aCondition  root logic condition to serialize
+	 *
+	 * @return  query criteria serialization instance
+	 *
+	 * @leave KErrNotSupported result mode and query type don't match
+	 * @leave KErrCompletion   result mode is EModeDistinctValues and query 
+	 *                         criteria is incorrect
+	 */
+	static CMdSQueryCriteriaDeserialization* NewLC(CMdCSerializationBuffer& aSerializationBuffer);
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CMdSQueryCriteriaDeserialization();
+
+    /**
+    * Returns pointer to the serialized data (read only)
+    */
+    TPtr8 Buffer() const;
+
+    /**
+    * Returns pointer to the serialized data (read only)
+    */
+    const TPtr8* BufferPtr() const;
+    
+    /**
+    * Returns pointer to the serialization buffer
+    */
+    CMdCSerializationBuffer& SerializationBuffer();
+
+protected:
+
+	/**
+	* Returns query's result mode.
+	*
+	* @return query result mode
+	*/
+	TQueryResultMode ResultModeL();
+
+	/**
+	* Returns query's type.
+	*
+	* @return query type
+	*/
+	TQueryType QueryTypeL();
+
+	/**
+	* Returns query's namespace definition ID.
+	*
+	* @return namespace definition ID
+	*/
+	TDefId NamespaceDefIdL();
+
+	/**
+	* Returns query's object definition ID.
+	*
+	* @return object definition ID
+	*/
+	TDefId ObjectDefIdL();
+
+	/**
+	* Moves position to begin of query's object definitions IDs.
+	* 
+	* @return if offset is KNoOffset return EFalse, else return ETrue and move 
+	*         to that position
+	*/
+	TBool ObjectDefsIdsL();
+
+	/**
+	* Returns query's result's limit value.
+	*
+	* @return limit value
+	*/
+	TUint32 LimitL();
+
+	/**
+	* Returns query's internal optimization flags.
+	*
+	* @return query's internal optimization flags
+	*/
+	TUint32 OptimizationFlagsL();
+
+	/**
+	* Returns query's result's offset value.
+	*
+	* @return offset value
+	*/
+	TUint32 OffsetL();
+
+	/**
+	* Moves position to begin of query's root condition.
+	*/
+	void RootConditionL();
+
+	/**
+	* Moves position to begin of query's order rules.
+	*/
+	void OrderRulesL();
+
+	/**
+	* Moves position to begin of query's property filter.
+	*/
+	void PropertyFiltersL();
+
+private:
+
+	/* Constructors. */
+
+	/**
+	 * Constructor.
+	 */
+	CMdSQueryCriteriaDeserialization(CMdCSerializationBuffer& aSerializedBuffer);
+	
+private:
+
+    /** Serialized query criteria. */
+    CMdCSerializationBuffer& iSerializedBuffer;
+	};
+
+
+#endif  // __MDEQUERYCRITERIASERIALIZATION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsrelationdef.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,92 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one relation
+*
+*/
+
+#ifndef __MDSRELATIONDEF_H__
+#define __MDSRELATIONDEF_H__
+
+#include <e32base.h>
+
+#include "mdsitemdef.h"
+
+
+class CMdCSerializationBuffer;
+
+
+/**
+ *  Metadata relationdef class
+ *
+ *  This class is responsible for holding information about one relation
+ *
+ */
+class CMdsRelationDef : public CMdsItemDef
+    {
+    friend class CMdsNamespaceDef;
+public:
+	/**
+	 * Create new relation object
+	 * @param aId id of relation
+	 * @param aName name of relation
+	 * @return pointer to new created relation
+	 */
+    static CMdsRelationDef* NewL( const TDesC& aName );
+
+	/**
+	 * Create new relation object
+	 * @param aId id of relation
+	 * @param aName name of relation
+	 * @return pointer to new created relation
+	 */
+    static CMdsRelationDef* NewLC( const TDesC& aName );
+
+    virtual ~CMdsRelationDef();
+    
+
+    TBool operator==( const CMdsRelationDef& aRelationDef ) const;
+
+	inline TBool operator!=( const CMdsRelationDef& aRelationDef ) const;
+
+	void StoreToDBL( const TDefId aNamespaceDefId );
+
+	/**
+     * Get required size of serialized buffer when this is serialized.
+     *
+     * @return required size of serialized buffer
+     */
+    TUint32 RequiredBufferSize();
+
+    /**
+     * Serialize own data to serialized buffer (correct position must be set 
+     * before calling) and return new position of serialized buffer.
+	 *
+     * @param aBuffer  serialized buffer.
+     */
+    TMdCOffset SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreeSpace);
+
+private:
+	/**
+	 * 2nd phase construction
+	 * @param aName name of event
+	 */
+    void ConstructL( const TDesC& aName );
+
+private: // data
+
+    };
+
+#include "mdsrelationdef.inl"
+
+#endif // __MDSRELATIONDEF_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsrelationdef.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,22 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one relation
+*
+*/
+
+inline TBool CMdsRelationDef::operator!=( const CMdsRelationDef& aRelationDef ) const
+	{
+	return !( *this == aRelationDef );
+	}
+	
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsschema.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,201 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about schema
+*
+*/
+
+#ifndef __MDSSCHEMA_H__
+#define __MDSSCHEMA_H__
+
+#include <e32base.h>
+#include "mdccommon.h"
+
+class CMdsNamespaceDef;
+class CMdsObjectDef;
+class CMdsClauseBuffer;
+
+
+
+/**
+ *  Metadata object class
+ *
+ *  This class is responsible for holding information about one object
+ *
+ */
+class CMdsSchema : public CBase
+    {
+    friend class CMdsImportExport;
+
+public:
+	/**
+	 * Create new objectdef object
+	 * @param aId id of object
+	 * @param aName name of object
+	 * @param aParent parent to actual object
+	 * @return pointer to new created object
+	 */
+    static CMdsSchema* NewL( );
+
+	/**
+	 * Create new objectdef object
+	 * @param aId id of object
+	 * @param aName name of object
+	 * @param aParent parent to actual object
+	 * @return pointer to new created object
+	 */
+    static CMdsSchema* NewLC( );
+
+    virtual ~CMdsSchema();
+
+    /**
+     * Create tables to store whole Schema into DB
+     */
+    void StoreToDBL();
+    
+    /**
+     * Check and return namespace searching by Id
+     */
+    const CMdsNamespaceDef* GetNamespaceByIdL( TDefId aId );
+
+    /**
+     * Check if namespace exists to avoid duplication
+     * @param aName namespace name to search for
+     * @return address of existing namespace or NULL
+     */
+	CMdsNamespaceDef* GetNamespace( const TDesC& aName );
+
+    /**
+     * Adds default BaseObject "Object"
+     */
+    void AddDefaultObjectL();
+
+    /**
+     * Adds default KMdEDefaultNameSpace 
+     */
+    void AddDefaultNamespaceL();
+
+    /**
+     * Returns NamespaceDefsCount  
+     */
+    TInt NamespaceDefsCount() const;
+
+    /**
+     * Returns reference to the NamespaceDefs  
+     */
+    const RPointerArray<CMdsNamespaceDef>& NamespaceDefs() const;
+
+	void SerializeToSharedMemoryL();
+	
+	TInt SharedMemoryHandleL();
+
+protected:
+
+	/**
+	 * Add object and it's parents properties names and types to clause
+	 * parameters
+	 * @param aObject object which properties should be add
+	 * @param aClause clause where add instructions to sql execute
+	 */
+	void AddObjectToSqlClauseL( CMdsObjectDef* aObject, CMdsClauseBuffer* aClause,
+	                            const TBool& aAddText );
+
+    /**
+     * Add namespace to array of existing ones
+     * @param aName namespace name
+     * @param aReadOnly namespace read-only flag
+     * @param aNamespaceDefId namespaceDefd, or zero (none) to get automatic one
+     * @return new added namespace
+     */
+	CMdsNamespaceDef* NamespaceAddL( const TDesC& aName, const TBool aReadOnly,
+			TInt32 aVendorId, TDefId aNamespaceDefId = 0 );
+
+	/**
+	 * Combine two schemas and put it to one in aSchema
+	 * @param aSchema schema where to add readed schema
+	 */
+    void MergeNamespacesL( CMdsSchema& aSchema );
+
+	void MergeElementsL( CMdsSchema& aSchema, const TBool& aDryRun );
+
+    /**
+     * Create tables to store whole Schema into DB (internal)
+     */
+    void StoreSchemaToDBL();
+
+	void StoreNamespacesAndBaseObjectL();
+
+	void CreateCol2PropTableL();
+
+	void AddCol2PropObjectL( CMdsObjectDef* aObject, CMdsObjectDef* aChildObject,
+							 TUint32& aPropertyColumnCounter, TBool aText );
+
+    /**
+     * Create tables for objects
+     */
+    void CreateObjectTablesL();
+
+private:
+    inline CMdsSchema();
+
+	/**
+	 * 2nd phase constructor
+	 * @param aName name of property
+	 */
+    void ConstructL();
+
+	/**
+	 * Deletes all namespaces and clean it's array
+	 */
+	void Reset();
+	
+	/**
+	 * Creates property index for a object table.
+	 */
+	void CreatePropertyIndexL( const TDesC& aPropertyName, const TDesC& aTableName, TDefId aNamespaceId );
+	
+	class TPropertyInfo
+		{
+	public:
+		TPropertyInfo( const TDesC& aTableName, const TDesC& aPropertyName, TDefId aNamespaceId ) :
+			iTableName( aTableName ), iPropertyName( aPropertyName )
+		{
+		iNamespaceId = aNamespaceId;
+		}
+		
+		TPtrC iTableName;
+		TPtrC iPropertyName;
+		TDefId iNamespaceId;
+		};
+
+private: // data
+    /**
+     * Store every namespace read from schema file.
+     */
+	RPointerArray<CMdsNamespaceDef> iNamespaceDefs;
+	
+	RArray<TPropertyInfo> iProperties;
+
+	/**
+	 * Default base object, parent to all others
+	 */
+	CMdsObjectDef* iBaseObject;
+	
+	RChunk iSerializedSchema;
+	
+	TBool iSerialized;
+	
+	TInt iSchemaHandle;
+    };
+
+#endif // __MDSSCHEMA_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,339 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is Metadata engine server file*
+*/
+
+#ifndef __MDSSERVER_H__
+#define __MDSSERVER_H__
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32cmn.h>
+
+#include "mdccommon.pan"
+
+#include "mdsdiskspacenotifier.h"
+#include "mdebackuprestoreobserver.h"
+#include "mdsshutdownobserver.h"
+
+// FORWARD DECLARATIONS
+class CMdSObjectLockList;
+class CMdSNotifier;
+class CMdSMaintenanceEngine;
+class CMdSManipulationEngine;
+class CMdSSqLiteConnection;
+class CMdEBackupRestoreWatcherAO;
+class CMdsSchema;
+class CMdCSerializationBuffer;
+
+// CLASS DECLARATION
+
+/**
+* CMdSServer.
+*  An instance of class CMdSServer is the main server class
+*/
+class CMdSServer : public CPolicyServer, public MMdSDiskSpaceNotifierObserver, 
+                   public MMdEBackupRestoreObserver,
+                   public MMDSShutdownObserver
+                   
+    {
+    public : // From MMdSDiskSpaceNotifierObserver
+    	void HandleDiskSpaceNotificationL(TDiskSpaceDirection aCrossDirection);
+
+		void HandleDiskSpaceError(TInt aError);
+		
+	public: // From MMdEBackupRestoreObserver
+		// Called when backup & restore watcher notices starting back up.
+		void HandleBackup();
+		// Called when backup & restore watcher notices starting restore.
+		void HandleRestore();
+		// Called when backup or watcher is completed and normal operation continues.
+		void ResumeOperation();	
+		
+	public: // MMDSShutdownObserver
+	        
+	        void ShutdownNotification();
+	        
+	        void RestartNotification();
+    
+    public : // Constructors and destructors
+
+	    /**
+	    * Constructs a new metadata server implementation.
+	    *
+	    * @return  metadata server implementation
+	    */
+        static CMdSServer* NewL();
+
+	    /**
+	    * Constructs a new metadata server implementation and leaves the server implementation
+	    * in the cleanup stack.
+	    *
+	    * @return  metadata server implementation
+	    */
+        static CMdSServer* NewLC();
+
+	    /**
+	    * Destructor.
+	    */
+        virtual ~CMdSServer();
+
+    public: // New functions
+
+        /**
+        * ThreadFunction.
+        * Main function for the server thread.
+        * @param aStarted A semaphore to be flagged when server
+        *                 has been started.
+        * @return Error code.
+        */
+        static TInt ThreadFunction( TAny* aStarted );
+
+        /**
+        * IncrementSessions.
+        * Increments the count of the active sessions for this server.
+        */
+        void IncrementSessions();
+
+        /**
+        * DecrementSessions.
+        * Decrements the count of the active sessions for this server.
+        * If no more sessions are in use the server terminates.
+        */
+        void DecrementSessions();
+
+        /**
+        * Reference to the schema
+        */
+        CMdsSchema& Schema();
+
+        /**
+        * Get lock list
+        */
+        CMdSObjectLockList& LockList();
+
+        /**
+        * Get notifier
+        */
+        CMdSNotifier& Notifier();
+
+        /**
+        * Get maintenance engine
+        */
+        
+        CMdSMaintenanceEngine& Maintenance();
+        
+        /**
+        * Get manipulator engine
+        */
+        
+        CMdSManipulationEngine& Manipulate();
+
+        /**
+        * PanicClient.
+        * Panics the client.
+        * @param aMessage The message channel to the client.
+        * @param aReason The reason code for the panic.
+        */
+        static void PanicClient( const RMessage2& aMessage, TInt aReason );
+        
+        TBool DiskFull() const;
+        
+        TBool BackupOrRestoreRunning() const;
+
+        TInt SetHarvestingPrioritizationChunkL( const RMessagePtr2 aMessage, TInt aParam );
+
+        TInt AddHarvestingPrioritizationObserver( RMessagePtr2 aMessage );
+
+        TInt CancelHarvestingPrioritizationObserver();
+
+        TBool ReserveSpaceHarvestingPrioritizationUri( const TDesC16& aUri );
+
+        TBool StartAddingHarvestingPrioritizationUrisL();
+        
+        TBool AddHarvestingPrioritizationUriL( TDesC16& aUri );
+
+        void NotifyHarvestingPrioritizationObserver( TInt aStatus ) const;
+
+        /** 
+         * ResetDBL
+         * resets DB, should be called only in DEBUG build
+         */
+        TInt ResetDBL();
+
+    protected: // Functions from base classes
+
+        /**
+        * From CActive, RunError.
+        * Processes any errors.
+        * @param aError The leave code reported.
+        * @result return KErrNone if leave is handled.
+        */
+        TInt RunError( TInt aError );
+        
+        /**
+        * From CPolicyServer.
+        * Handles capability checking for certain server requests.
+        * @result return one of TCustomResult set {EPass, EFail, EAsync}.
+        */
+        CPolicyServer::TCustomResult CustomSecurityCheckL( 
+                                                const RMessage2 &aMsg,
+                                                TInt &aAction,
+                                                TSecurityInfo &aMissing);
+
+        /**
+        * From CPolicyServer.
+        * Handles xxxx.
+        * @result return one of TCustomResult set {EPass, EFail, EAsync}.
+        */
+        CPolicyServer::TCustomResult CustomFailureActionL(
+                                                const RMessage2 &aMsg,
+                                                TInt aAction,
+                                                const TSecurityInfo &aMissing);
+
+
+    private: // Constructors and destructors
+
+        /**
+         * CMdEServer.
+         * C++ default constructor.
+         * @param aPriority priority for this thread.
+         */
+        CMdSServer( TInt aPriority );
+
+        /**
+         * ConstructL.
+         * 2nd phase constructor.
+         */
+        void ConstructL();
+
+        /**
+         * InitializeL
+         * Do part of internal resources initializations
+         * used together with DeInitialize to ResetDB functionality
+         */
+        void InitializeL();
+
+        /**
+         * DeInitializeL
+         * Do part of internal resources deinitializations
+         * used together with Initialize to ResetDB functionality
+         */
+        void DeInitializeL();
+        
+        void CheckInitSriptL();
+        
+    private: // New methods
+
+        /**
+        * PanicServer.
+        * Panics the server.
+        * @param aPanic The panic code.
+        */
+        static void PanicServer( TMetadataPanic aPanic );
+
+        /**
+        * ThreadFunctionL.
+        * Second stage startup for the server thread.
+        */
+        static void ThreadFunctionL();
+
+        friend TInt E32Main();
+
+    private: // Functions from base classes
+
+        /**
+        * From CServer, NewSessionL.
+        * Creates a time server session.
+        * @param aVersion The client version.
+        * @return Pointer to new session.
+        */
+        CSession2* NewSessionL( const TVersion& aVersion, const RMessage2& aMessage ) const;
+
+    private: // Data
+
+        /**
+        * iSessionCount, the number of session owned by this server.
+        */
+        TInt iSessionCount;
+        
+        /**
+        * class for installing and maintaining the database
+        */
+        CMdSMaintenanceEngine* iMaintenance;
+
+		/**
+		* Default DB connection for default namespace.
+		*/
+		CMdSSqLiteConnection* iDefaultDBConnection;
+
+        /**
+        * The internal schema
+        */
+        CMdsSchema* iSchema;
+
+        /**
+        * Server status. If other than KErrNone, prevents client sessions.
+        */
+        TInt iServerErrorStatus;
+        
+        /**
+        * Locked object list.
+        */
+       	CMdSObjectLockList* iLockList;
+       
+		/**
+		* Notifier engine
+		*/
+		CMdSNotifier* iNotifier;
+
+        /**
+        * Object adding, removing and modification.
+        * upper proxy layer, provides validation and such.
+        */
+        CMdSManipulationEngine* iManipulate;
+        
+        /**
+        * Garbage collector notifier for situations where free disk space is getting low.
+        */
+        CMdSDiskSpaceNotifierAO* iDiskSpaceGarbageCollectorNotifier;
+        
+        /**
+        * Notifier for situations where free disk space runs out.
+        */
+        CMdSDiskSpaceNotifierAO* iDiskFullNotifier;
+        
+        CMdEBackupRestoreWatcherAO* iBURWatcher;
+        
+        TBool iBackupOrRestoreRunning;
+        
+        RChunk iHarvestingPrioritizationChunk;
+        CMdCSerializationBuffer* iHarvestingPrioritizationSerializationBuffer;
+        TUint32 iHarvestingPrioritizationLimit;
+        TInt32 iHarvestingPrioritizationUriCount;
+        TBool iHarvestingPrioritizationLocked; // adding of new URIs allowed
+
+        TInt32 iHarvestingPrioritizationBufferUriCount;
+        TUint32 iHarvestingPrioritizationBufferUriOffset;
+
+        RMessagePtr2 iHarvestingPrioritizationObserver;
+        
+        CMDSShutdownObserver* iShutdownObserver;
+        
+        TBool iShutdown;
+    };
+
+#endif // __MDSSERVER_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsserversession.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,436 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is Metadata engine server session file*
+*/
+
+
+#ifndef __MDESERVERSESSION_H__
+#define __MDESERVERSESSION_H__
+
+// INCLUDE FILES
+#include <e32base.h>
+
+#include "mdscommoninternal.h"
+#include "mdcserializationbuffer.h"
+
+// FORWARD DECLARATIONS
+class CMdSServer;
+class CMdSFindEngine;
+class CMdCSerializationBuffer;
+
+// CLASS DECLARATION
+/**
+* CServerSession.
+*  An instance of class CServerSession is created for each client.
+*/
+class CMdSServerSession : public CSession2
+    {
+    public: // Constructors and destructors
+
+        /**
+        * NewL.
+        * Two-phased constructor.
+        * @param aClient The Client's thread.
+        * @param aServer The server.
+        * @return Pointer to created CMdEServerSession object.
+        */
+        static CMdSServerSession* NewL( CMdSServer& aServer );
+
+        /**
+        * NewLC.
+        * Two-phased constructor.
+        * @param aClient The Client's thread.
+        * @param aServer The server.
+        * @return Pointer to created CMdEServerSession object.
+        */
+        static CMdSServerSession* NewLC( CMdSServer& aServer );
+
+        /**
+        * ~CMdEServerSession.
+        * Destructor.
+        */
+        virtual ~CMdSServerSession();
+
+		/**
+		* Cache a notification for an entry;
+		* @param aId notification ID
+		* @param aCompleteCode complete code
+		* @param aData serialized notification data, ownership of data changes 
+		*              even if method leaves
+		*/
+		void CacheNotificationL(TInt aId, TUint32 aCompleteCode, CMdCSerializationBuffer* aData);
+		
+		CMdSServer& GetServer() const;
+	
+	private: // Internal helper methods
+		/**
+		* Check that all queries are complete.
+		*/ 
+		void QueriesCompleteL();
+
+    protected: // Methods for own use
+
+        /**
+        * Adds items to database.
+        * @param aMessage Message from client
+        */
+        void AddL( const RMessage2& aMsg );
+
+		/**
+		* Adds relation to database.
+		* @param aMessage message from client
+		*/
+		void AddRelationDefL(const RMessage2 &aMsg);
+
+		/**
+		* Adds event to database.
+		* @param aMessage message from client
+		*/		
+		void AddEventDefL(const RMessage2 &aMsg);
+
+        /**
+        * Removes item from database.
+        * @param aMessage Message from client
+        */
+        void RemoveL( const RMessage2& aMsg );
+
+        /**
+        * Removes item from database.
+        * @param aMessage Message from client
+        */
+        void RemoveByUriL( const RMessage2& aMsg, TBool aRemoveEvents );
+ 
+        /**
+        * Finds item from database.
+        * @param aMessage Message from client
+        */
+        void FindL( const RMessage2& aMsg );
+
+        /**
+        * Finds item from database.
+        * @param aMessage Message from client
+        */
+        void FindAsyncL( const RMessage2& aMsg );
+
+        /**
+        * Finds item from database.
+        * @param aMessage Message from client
+        */
+        void FindContinueAsyncL( const RMessage2& aMsg );
+
+        /**
+        * Finds item from database and completes message.
+        * @param aMessage Message from client
+        */
+        void FindCancel( const RMessage2& aMsg, TInt aError );
+
+        /**
+         * Get object's "base" values from database and completes message.
+         * @param aMessage Message from client
+         */
+        void CheckObjectL( const RMessage2& aMsg );
+        
+        /**
+        * Transfers data from server to client.
+        * @param aMessage Message from client
+        */
+        void GetDataL( const RMessage2& aMsg );
+
+        /**
+        * Cancels the modifying of object and unlocks the object.
+        * @param aMessage Message from client
+        */
+        void CancelObjectL( const RMessage2& aMsg );
+
+        /**
+        * Commits the modified items to database.
+        * @param aMessage Message from client
+        */
+        void UpdateL( const RMessage2& aMsg );
+
+        /**
+        * Registers the client for notifications.
+        * @param aMessage Message from client
+        */
+        void RegisterL( const RMessage2& aMsg );
+
+        /**
+        * Continues registration for an existing client.
+        * @param aMessage Message from client
+        */
+        void ListenL( const RMessage2& aMsg );
+
+        /**
+        * Unregisters a client for notifications.
+        * @param aMessage Message from client
+        */
+        void UnregisterL( const RMessage2& aMsg );
+
+        /**
+        * Executes session shutdown.
+        * @param aMessage Message from client
+        */
+        void ShutdownL( const RMessage2& aMsg );
+
+        /**
+        * Import metadata.
+        * @param aMessage Message from client
+        */
+        void ImportMetadataL( const RMessage2& aMsg );
+
+        /**
+        * Export metadata
+        * @param aMessage Message from client
+        */
+        void ExportMetadataL( const RMessage2& aMsg );
+
+        /**
+        * Import schema
+        */
+        void ImportSchemaL( const RMessage2& aMsg );
+
+        /**
+        * Add memory card media ID
+        * @param aMessage Message from client where first argument is media ID
+        */
+		void AddMemoryCardL(const RMessage2& aMessage);
+        
+        /**
+        * Get the latest memory card's media ID
+        *
+        * @param aMessage Message from client where first argument is returned 
+        *                 Media ID
+		* @leave KErrNotFound Not memory cards exist at all 
+        */
+        void GetMemoryCardL(const RMessage2& aMessage);
+        
+        /**
+         * Check if the memory card's media ID exist in DB
+         * @param aMessage Message from client where first argument is media ID
+         *                 and second is exists boolean value
+         */
+        void CheckMemoryCardL(const RMessage2& aMessage);
+
+        /**
+         * Set media's media ID, drive and present state to DB.
+         * 
+         * @param aMessage Message from client where first argument is media ID
+         *                 and second is drive and third is present state
+         */
+        void SetMediaL(const RMessage2& aMessage);
+
+        /**
+         * Check if the media's with given media ID exist in DB and return 
+         * drive and present state.
+         * 
+         * @param aMessage Message from client where first argument is media 
+         * 				   ID, second is media ID, third is drive and fourth 
+         *                 is exists boolean value
+         */
+        void GetMediaL(const RMessage2& aMessage);
+
+        /**
+         * Get present medias' media IDs and drives.
+         * 
+         * @param aMessage Message from client where first argument is media 
+         * 				   count and second is media infos
+         */
+        void GetPresentMediasL(const RMessage2& aMessage);
+        
+        /**
+         * Sets files object to present state.
+         * @param aMessage Message from client where first argument is media ID 
+         *                 and file count, second argument is URIs, third 
+         *                 argument is TMdSFileInfos and fourth argument is
+         *                 result buffer, which are sent back to client
+         */
+        void SetFilesToPresentL(const RMessage2& aMessage);
+        
+        /**
+        * Sets all file objects which has given media ID to not present state.
+        *
+        * @param aMessage Message from client where first argument is media ID
+        */
+        void SetFilesToNotPresentL(const RMessage2& aMessage);
+        
+        /**
+        * Removes all file objects which has given media ID and are in not 
+        * present.
+        *
+        * @param aMessage Message from client where first argument is media ID
+        */
+        void RemoveFilesNotPresentL(const RMessage2& aMessage);
+        
+        /**
+         * Gets schema version.
+         *
+         * @param aMessage message from client where first argument is major 
+         *                 version number and second is minor version number
+         */
+        void GetSchemaVersionL(const RMessage2& aMessage);
+        
+        /**
+         * Set object to "present" state by GUID.
+         *
+         * @param aMessage message from client where first argument is GUID 
+         *                 high and second is GUID low
+         * 
+		 * @leave KErrNotFound MdE can't find object in "not present" state 
+		 *                     with matching GUID
+         */
+        void SetObjectToPresentByGuidL(const RMessage2& aMessage);
+        
+        /**
+         * Change path of objects, which match to the old path, to the new 
+         * path.
+         * 
+         * @param aMessage message from client where first argument is the old 
+         *                 path and second is the new path
+         */
+        void ChangePathL(const RMessage2& aMessage);
+        
+        /**
+         * Change C-drive media id to MdS_Medias table and update all objects that have the old id.
+         */
+        void ChangeMediaIdL( const RMessage2& aMessage );
+        
+        /**
+         * Set "binary composing to file" pending flag to objects.
+         * 
+         * @param aMessage message from client where first argument is 
+         *                 serialized array of object IDs
+         */
+        void SetPendingL(const RMessage2& aMessage);
+
+        /**
+         * Reset "binary composing to file" pending flag to objects.
+         * 
+         * @param aMessage message from client where first argument is 
+         *                 serialized array of object IDs
+         */
+        void ResetPendingL(const RMessage2& aMessage);        
+        
+        /**
+		 * Get count of objects with "binary composing to file" pending flag
+		 *
+         * @param aMessage message from client where first argument is 
+         *                 serialized object def ID
+         * 
+		 * @return if >= 0, object count is returned, otherwise error code is 
+		 *         returned
+		 */
+		TInt GetPendingCountL(const RMessage2& aMessage);
+		
+		/**
+		 * Get IDs from objects with "binary composing to file" pending flag
+		 *
+         * @param aMessage message from client where first argument is 
+         *                 serialized object def ID and second argument is
+         *                 returned object ID count and third is serialized 
+         *                 array for object IDs
+		 *
+		 * @return if > 0, buffer is not large enough for objects ID from DB,
+		 *         otherwise error code is returned
+		 */
+		TInt GetPendingL(const RMessage2& aMessage);
+        
+    public: // Functions from base classes
+
+        /**
+         * From CSession2, ServiceL.
+         * Service request from client.
+         * @param aMessage Message from client
+         *                 (containing requested operation and any data).
+         */
+        void ServiceL( const RMessage2& aMessage );
+
+        /**
+         * SizeToRemoteL.
+         * Writes size to slave process.
+         * @param aMessage Message from client
+         * @param aRemote, pointer to client's variable.
+         * @param aHierarchy hierarchy that's size is to be transmitted
+         */
+        static void SizeToRemoteL( const RMessage2& aMsg, TInt aMessageSlot, TInt aSize);
+
+    private: // Constructors and destructors
+
+        /**
+        * CMdSServerSession.
+        * C++ default constructor.
+        * @param aClient The Client's thread.
+        * @param aServer The server.
+        */
+        CMdSServerSession( CMdSServer& aServer );
+
+        /**
+        * ConstructL.
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+        /**
+        * Internal function to handle service request from client.
+        * @param aMessage Message from client
+        *                 (containing requested operation and any data).
+        */
+        void ServiceFunctionL( const RMessage2& aMessage );        
+        
+        CMdCSerializationBuffer* CombineBuffersL(
+        		CMdCSerializationBuffer& aLeftBuffer, CMdCSerializationBuffer& aRightBuffer );
+
+        CMdCSerializationBuffer* CombineItemBuffersL(
+        		CMdCSerializationBuffer& aLeftBuffer, CMdCSerializationBuffer& aRightBuffer );
+        
+    private: // Data
+
+        /**
+        * iServer, reference to the server.
+        */
+        CMdSServer& iServer;
+        
+       /**
+        * Find engine
+        */
+        RPointerArray<CMdSFindEngine> iFindEngines;
+
+	    class CNotificationCacheItem : public CBase
+	    	{
+	    	public:
+	    		CNotificationCacheItem( TInt aId, TUint32 aCode, 
+	    			CMdCSerializationBuffer* aData ) : 
+		    		iId( aId ), 
+		    		iCode( aCode ),
+		    		iData( aData )
+		    		{
+		    		}
+		    	
+		    	~CNotificationCacheItem()
+			    	{
+			    	delete iData;
+			    	}
+
+	    	public:
+		    	const TInt iId;
+		    	const TUint32 iCode;
+		    	CMdCSerializationBuffer* iData;
+	    	};
+
+       /**
+        * Cache of notification events
+        */        
+    	RPointerArray<CNotificationCacheItem> iNotificationCache;
+    };
+
+#endif // __MDESERVERSESSION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdsshutdownobserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,113 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is Metadata engine server session file
+*
+*/
+
+#ifndef MDSSHUTDOWNOBSERVER_H
+#define MDSSHUTDOWNOBSERVER_H
+
+#include <e32base.h>
+#include <w32std.h>
+#include <e32property.h> 
+
+
+/**
+ * Observer interface for signaling the need for shutdown
+ */
+class MMDSShutdownObserver
+    {
+public:
+
+    virtual void ShutdownNotification() = 0;
+    
+    virtual void RestartNotification() = 0;
+    };
+
+/**
+ *  Active object for observing P&S keys
+ *
+ *  @since S60 v5.0
+ */
+class CMDSShutdownObserver  : public CActive
+    {
+public:
+
+    /**
+     * Two-phased constructor.
+     *
+     * @since S60 v5.0
+     * @return Instance of CTMShutdownObserver.
+     */
+    IMPORT_C static CMDSShutdownObserver* NewL( MMDSShutdownObserver& aObserver/*, const TUid& aKeyCategory*/ );
+
+    /**
+     * Destructor
+     *
+     * @since S60 v5.0
+     */
+    virtual ~CMDSShutdownObserver();
+
+public:
+
+	 /**
+	 * return iad update status
+	 */ 
+	 TBool UpdateInProgress();
+    
+protected:
+
+    /**
+     * Handles an active object's request completion event.
+     *
+     * @since S60 v5.0
+     */
+    void RunL();
+
+    /**
+     * Implements cancellation of an outstanding request.
+     *
+     * @since S60 v5.0
+     */
+    void DoCancel();
+    
+    TInt RunError( TInt aError );
+
+private:
+
+    /**
+     * C++ default constructor
+     *
+     * @since S60 v5.0
+     * @return Instance of CShutdownObserver.
+     */
+    CMDSShutdownObserver( MMDSShutdownObserver& aObserver/*, const TUid& aKeyCategory*/ );
+
+    /**
+     * Symbian 2nd phase constructor can leave.
+     *
+     * @since S60 v5.0
+     */
+    void ConstructL();
+
+private:
+    
+    // not own
+    MMDSShutdownObserver& iObserver;
+    
+    RProperty iProperty;
+	TInt iValue;
+};
+
+#endif // SHUTDOWNOBSERVER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdssqldbmaintenance.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class for SQL database creation*
+*/
+
+#ifndef __MDSSQLDBMAINTENANCE_H__
+#define __MDSSQLDBMAINTENANCE_H__
+
+#include <e32base.h>
+
+// FORWARD DECLARATIONS
+class CMdSSchema;
+
+
+_LIT( KMdsSchemaVersionName, "SchemaVersion" );
+_LIT( KMdsDBVersionName, "DBVersion" );
+
+// CLASS DECLARATION
+/**
+* Class for validating and creating tables in database.
+*/
+class CMdSSqlDbMaintenance : public CBase
+    {
+    public: // Constructors and destructor
+        virtual ~CMdSSqlDbMaintenance();
+        
+        static CMdSSqlDbMaintenance* NewL();
+        static CMdSSqlDbMaintenance* NewLC();
+
+    private: // Private constructors
+
+        CMdSSqlDbMaintenance();
+        void ConstructL( );
+
+    public: // Personal methods
+
+        /**
+        * Validates the existence of database
+        * @return ETrue if the database exists, EFalse if needs to be created.
+        */
+        TBool ValidateL();
+
+        /**
+        * Drops and re-creates tables
+        */
+        void CreateDatabaseL();
+    };
+
+#endif // __MDSSQLDBMAINTENANCE_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdssqlfindoperation.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,259 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Manages object search from database using SQL,*
+*/
+
+#ifndef __MDSSQLFINDOPERATION_H__
+#define __MDSSQLFINDOPERATION_H__
+
+#include <e32base.h>
+
+#include "mdccommon.h"
+#include "mdssqliteconnection.h"
+
+// FORWARD DECLARATIONS
+class CMdSSqLiteConnection;
+class CMdSFindSqlClause;
+class CMdSFindSequence;
+class CMdCSerializationBuffer;
+class CDesC16Array;
+class RRowData;
+
+
+/**
+* Find operation class represents a single synchronous
+* or asynchronous find.
+*/
+class CMdSSqlFindOperation: public CBase
+    {
+    public:
+	    /** state of operation */
+	    enum TOperationState
+	    	{
+	        EStateIdle,     // not working
+	        EStateRunning,  // active state
+	        EStateStop,     // stop instructed
+	        EStateDead,     // find stopped
+	        };
+
+        /**
+        * constructs a find operation        
+        * @param aFind the master class that runs this operation        
+        * @param aSetSize maximum size of a single result set
+        */
+        static CMdSSqlFindOperation* NewL(            
+            CMdSFindSequence& aFind,            
+            TUint aSetSize
+             );
+
+        /**
+        * constructs a find operation, leaves in cleanup stack.
+        */
+        static CMdSSqlFindOperation* NewLC(            
+            CMdSFindSequence& aFind,            
+            TUint aSetSize
+             );
+
+        virtual ~CMdSSqlFindOperation();
+
+        /**
+        * from MMdSFindOperation
+        */
+        TInt ExecuteL();
+
+        /**
+        * from MMdSFindOperation
+        */
+        TInt ContinueL();
+
+        /**
+        * from MMdSFindOperation
+        */
+        TInt State();
+
+        /**
+        * from MMdSFindOperation
+        */
+        void Cancel();
+
+        /**
+        * from MMdSFindOperation
+        */
+        CMdSFindSqlClause& FindCriteria();
+
+        /**
+        * Moves ownership of the result buffer to caller
+        */
+        CMdCSerializationBuffer* Results();
+
+		void SetLimit(TUint32 aLimit);
+
+		void SetOffset(TUint32 aOffset);
+
+        /**
+         * Returns query freetext array from CMdSFindSqlClause
+         * @return freetext array
+         */
+        RPointerArray<HBufC>& QueryFreeText();
+
+    private: // private construction for friends only
+
+        /**
+        * Construction
+        */
+        CMdSSqlFindOperation(            
+            CMdSFindSequence& aFind,
+            TUint aSetSize = KMaxTUint
+             );
+
+        /** 2nd phase constructor */
+        void ConstructL();
+
+    private: // Private functions
+
+        /**
+        * iterates results from database,
+        * places them in results container
+        * @return error code, KErrNone or KSetReady
+        */
+        TInt FetchResultsL();
+
+		TInt EstimateBaseResultSize();
+
+		TInt EstimateResultRowSizeL( RRowData& aRow );
+
+        /**
+        * Gets query results from the rowbuffer, creates
+        * corresponding object structure and adds into the
+        * results container.
+        * @param aDb database connection
+        * @param aRow database row to add into container
+        * @return true, if data was added to container
+        */
+	    void AddToContainerL();
+
+        /**
+        * Special treatment for Object, which is complicated
+        * because of heavy optimization
+        * @param aRow database row to add into container
+        * @param aFreespaceOffset offset to free space in buffer
+        */
+	    TMdCOffset AddObjectToContainerL( RRowData& aRow, TMdCOffset aFreespaceOffset );
+
+        /**
+        * Marks the current database rows consumed
+        */
+        void ConsumeRows();
+        
+        /**
+        * Add data to container 
+        * @param aRow database row to add into container
+        * @param aFreespaceOffset offset to free space in buffer
+        */
+        TMdCOffset AddItemToContainerL( RRowData &aRow, TMdCOffset aFreespaceOffset );
+    
+        /**
+        * Add data to container 
+        * @param aId item ID to add into container
+        */
+        void AddIdToContainerL( TItemId aId );
+    
+        /**
+        * Creates Item for serialization
+        */
+        void CreateItemL();
+    
+        /**
+        * Creates count for serialization
+        */
+        void CreateCountL();
+    
+        /**
+        * Creates Id for serialization
+        */
+        void CreateIdL();
+                
+        /**
+        * Creates distinct properties for serialization
+        */
+        void CreateDistinctL();
+    
+    private: // Member data
+    
+        /** Find type */
+        TQueryType iQueryType;
+
+		/** Result mode */
+		TQueryResultMode iResultMode;
+
+        /**
+        * Data row in find.
+        * Note: RRowData constructor cannot leave, since it is initialized (aInStack==EFalse)
+        */
+		RRowData* iResultRow;
+
+        /**
+        * Fetched result rows. Used when result mode is items or distinct.
+        * Note: RRowData constructor cannot leave, since it is initialized (aInStack==EFalse)
+        */
+        RPointerArray<RRowData> iResultRows;
+
+        /**
+        * Fetched result IDs. Used when result mode is IDs.
+        */
+        RArray<TItemId> iResultIds;
+
+        /**
+        * Fetched result count. Used when result mode is count.
+        */
+        TUint32 iResultCount;
+
+        /** container for result objects */
+        CMdCSerializationBuffer* iResults;
+
+        /** the object find back reference */
+        CMdSFindSequence& iFind;
+
+        /** the find SQL clause */
+        CMdSFindSqlClause* iFindClause;
+
+        /** asynchronous run state */
+        TOperationState iState;
+
+        /** the query ID */
+        RMdsStatement iQueryId;
+
+        /** maximum size of a single set */
+        const TUint32 iSetSize;
+
+        /** counter for results in this set */
+        TUint iSetCounter;
+
+        /** maximum size of the whole search */
+        TUint iLimit;
+
+        /** maximum size of the whole search */
+        TUint iLimitCounter;
+
+        /** offset from beginning of the sequence */
+        TUint iOffset;
+
+        /** used memory from set buffer */
+        TInt iMemoryLimit;
+        
+        /** harvesting prioritization URI count */
+        TInt iHarvestingPrioritizationCount;
+    };
+
+#endif // __MDSSQLFINDOPERATION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdssqlobjectmanipulate.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,574 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Add, update and remove items in DB.*
+*/
+
+#ifndef __MDSSQLOBJECTMANIPULATE_H__
+#define __MDSSQLOBJECTMANIPULATE_H__
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <hash.h>
+
+#include "mdscommoninternal.h"
+
+#include "mdsclausebuffer.h"
+
+// FORWARD DECLARATION
+class CMdSSqLiteConnection;
+class CMdsSchema;
+class CMdCFolder;
+class RMdsStatement;
+class CMdsNamespaceDef;
+class CMdsObjectDef;
+class CMdsPropertyDef;
+class CMdCSerializationBuffer;
+class CMdsClauseBuffer;
+class RRowData;
+class TColumn;
+class CMdSObjectLockList;
+class CMdSServerSession;
+class RMdsStatement;
+
+// CLASS DECLARATION
+/**
+ *
+ */
+class CMdSIdentifierGenerator: public CBase
+	{
+    public: // Constructors and destructor
+	    /**
+	    * Two-phased constructor.
+	    * @param aPool, reference to pool for reserve database connection.
+        * @return Pointer to CMdSIdentifierGenerator object.
+	    */
+        static CMdSIdentifierGenerator* NewL();
+
+	    /**
+	    * Two-phased constructor.
+	    * @param aPool, reference to pool for reserve database connection.
+	    * @return Pointer to CMdSIdentifierGenerator object.
+	    */
+        static CMdSIdentifierGenerator* NewLC();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CMdSIdentifierGenerator();
+
+		/**
+		 * Set guid to generated ones if both are 0
+		 */
+		void GenerateGuid( TInt64& aGuidHigh, TInt64& aGuidLow );
+
+		/**
+		 * Return unique uri
+		 * method require unique guid's
+		 */
+		HBufC* GenerateUriL( const CMdsObjectDef& aObjectDef, 
+				const TInt64& aGuidHigh, const TInt64& aGuidLow ) const;
+
+    private: // Private constructors
+        /**
+        * CMdSIdentifierGenerator.
+        * C++ default constructor.
+        */        
+        CMdSIdentifierGenerator( )
+        	{
+        	iDigest = NULL;
+        	}
+
+        /**
+        * ConstructL.
+        * 2nd phase constructor.
+        */        
+        void ConstructL( );
+
+	private: //Internal variables
+		TInt64 iImei;
+		TInt64 iLastTime;
+		
+		CMessageDigest* iDigest;
+	};
+
+
+/**
+ * CMdSSqlObjectManipulate converts object handling  
+ * instructions to an SQL clause.
+ */
+class CMdSSqlObjectManipulate: public CBase
+	{
+    public: // Constructors and destructor
+
+	    /**
+	    * Two-phased constructor.
+	    * @param aPool, reference to pool for reserve database connection.
+        * @return Pointer to CMdSSqlObjectManipulate object.
+	    */
+        static CMdSSqlObjectManipulate* NewL( const CMdsSchema& aSchema, 
+        		CMdSObjectLockList& aLockList );
+
+	    /**
+	    * Two-phased constructor.
+	    * @param aPool, reference to pool for reserve database connection.
+	    * @return Pointer to CMdSSqlObjectManipulate object.
+	    */
+        static CMdSSqlObjectManipulate* NewLC( const CMdsSchema& aSchema, 
+        		CMdSObjectLockList& aLockList );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CMdSSqlObjectManipulate();
+
+
+    private: // Private constructors
+    
+        /**
+        * CSqlObjectManipulate.
+        * C++ default constructor.
+        */        
+        CMdSSqlObjectManipulate( const CMdsSchema& aSchema, 
+        		CMdSObjectLockList& aLockList );
+        
+        /**
+        * ConstructL.
+        * 2nd phase constructor.
+        */        
+        void ConstructL( );
+
+
+    public: // Public functions
+
+		/**
+		 * Add new object to DB (not using any transaction system)
+		 *
+		 * @param aBuffer serialized object with properties and freeText
+		 * @return new added object id
+		 */
+		TItemId AddObjectL( CMdSSqLiteConnection& aConnection, 
+				CMdCSerializationBuffer& aBuffer, 
+				RMdsStatement& aMdsBaseObjStatement, RMdsStatement& aMdsObjStatement,
+				const CMdSServerSession* aServerSession = NULL );
+
+		/**
+		 * Really add freetext to DB
+		 * 
+		 * @param aWord word to add
+		 * @param aObjectId owner of freetext object id
+		 * @param aPosition position
+		 * @param aSearch search for existing freetext in DB
+		 */
+		TUint32 AddFreeTextToDBL( TPtrC16& aWord, TItemId aObjectId, 
+				TInt32 aPosition, TBool aSearch = ETrue );
+
+		/**
+		 * Add new freeText to DB (not using any transaction system)
+		 *  (check if FreeText is in DB and in this case don't add it)
+		 *
+		 * @param aBuffer serialized object with FreeText
+		 * @param aFreeTextCount freetext count
+		 * @param aObjectId freetext owner object ID
+		 * @return how many freeText was added to DB
+		 */
+		TInt AddFreeTextL( CMdCSerializationBuffer& aBuffer, TInt aFreeTextCount, TItemId aObjectId );
+
+		/**
+		 *	remove object by URI - just for internal use!
+		 */
+		void RemoveObjectForceL( const TDesC16& aUri, TItemId aObjectId );
+
+		/**
+		 * USE RemoveObjectForceL WITH CAUTION !!!
+		 * THIS FUNCTION REMOVES OBJECT WITHOUT ANY CHECKING
+		 * ONLY FOR INTERNAL USE !!!
+		 */
+		void RemoveObjectForceL( TItemId aObjectId );
+
+		CMdCSerializationBuffer* CheckObjectL( TInt aResultBufferSize, 
+				const TDesC& aUri, TDefId aNamespaceDefId );
+
+		CMdCSerializationBuffer* CheckObjectL( TInt aResultBufferSize, 
+				TItemId aId, TDefId aNamespaceDefId );
+
+		CMdCSerializationBuffer* CheckObjectL( TInt aResultBufferSize, 
+				CMdCSerializationBuffer& aIds, TDefId aNamespaceDefId );
+
+		void CollectRemovedItemsL( RArray<TItemId>& aRemoveIds, 
+				RArray<TItemId>& aObjectIds, RArray<TItemId>& aRelationIds, 
+				RArray<TItemId>& aEventIds );
+
+		/**
+		 * Remove object using it's id
+		 *
+		 * @param aBuffer id's to remove
+		 * @param aCount id's count
+		 * @param aIdArray result id's
+		 * @param aUserLevel not used - delete
+		 * @param aLockList list of locked objects
+		 */
+		void RemoveObjectsByIdL( CMdCSerializationBuffer& aBuffer, TInt aCount,
+				RArray<TItemId>& aIdArray, RArray<TItemId>& aRelationIds, 
+				RArray<TItemId>& aEventIds );
+
+		/**
+		 * Remove object using it's URI's
+		 *
+		 * @param aBuffer URI's to remove
+		 * @param aCount URI's count
+		 * @param aIdArray result id's
+		 * @param aUserLevel not used - delete
+		 * @param aLockList list of locked objects
+		 */
+		void RemoveObjectsByUriL( CMdCSerializationBuffer& aBuffer, TInt aCount,
+				RArray<TItemId>& aIdArray, RArray<TItemId>& aRelationIds, 
+				RArray<TItemId>& aEventIds );
+
+		/**
+		 * search for object uri
+		 *
+		 * @param aUri object uri to search for
+		 * @param aFlags return found object flags
+		 * @return object id
+		 */
+		TItemId SearchObjectByUriL( const TDesC16& aUri, TUint32& aFlags );
+
+		/**
+		 * update freetext (add and remove)
+		 */
+		void UpdateFreeTextL( CMdCSerializationBuffer& aBuffer, TInt aCount,
+				TItemId aObjectId );
+
+		/**
+		 * Update object
+		 *
+		 * @param aBuffer objects to update
+		 * @param aLockList list of locked objects
+		 */
+		TItemId UpdateObjectL( CMdSSqLiteConnection& aConnection, 
+				CMdCSerializationBuffer& aBuffer );
+		
+ 	    /**
+ 	    * Runs garbage collection to database
+ 		* @param aDb The database connection
+ 		* @return next garbage collection start is needed?
+ 	    */
+        TBool GarbageCollectionL();
+        
+		/**
+		 * Set namespace for processing functions
+		 */
+        void SetNamespace( const CMdsNamespaceDef* aNamespaceDef );
+
+        TItemId AddEventL( CMdSSqLiteConnection& aConnection, 
+        		CMdCSerializationBuffer& aBuffer );
+
+        TItemId AddRelationL( CMdSSqLiteConnection& aConnection, 
+        		CMdCSerializationBuffer& aBuffer );
+
+        void RemoveEventsL( CMdCSerializationBuffer& aBuffer, TInt aCount,
+        		RArray<TItemId>& aIdArray );
+
+        void RemoveRelationsL( CMdCSerializationBuffer& aBuffer, TInt aCount,
+        		RArray<TItemId>& aIdArray );
+
+        TItemId UpdateRelationsL( CMdSSqLiteConnection& aConnection, 
+        		CMdCSerializationBuffer& aBuffer );
+
+		/**
+        * Add memory card media ID
+		* @param aDb The database connection
+        * @param aMediaId Memory card's media ID
+        */
+		void AddMemoryCardL(TUint32 aMediaId);
+
+        /**
+         * Get the latest memory card's media ID
+ 		 * @param aDb The database connection
+         * @param aMediaId Returns the latest memory card's media ID
+ 		 * @leave KErrNotFound Not memory cards exist at all
+         */
+        void GetMemoryCardL(TUint32& aMediaId);
+
+        /**
+         * Checks if memory card's with given media ID exists
+         * @param aMediaId memory card's media ID
+         * @return memory card exists or not
+         */
+        TBool CheckMemoryCardL(TUint32 aMediaId);
+
+        /**
+         * Set media's media ID, drive and present state to DB.
+         * 
+         * @param aMediaId media ID
+         * @param aMediaId drive
+         * @param aMediaId present state
+         */
+        void SetMediaL(TUint32 aMediaId, TChar aDrive, TBool aPresentState);
+
+        /**
+         * Check if the media's with given media ID exist in DB and return 
+         * drive and present state.
+         * 
+         * @param aMediaId given media ID
+         * @param aMediaId drive
+         * @param aMediaId present state
+         * 
+         * @return does media exist
+         */
+        TBool GetMediaL(TUint32 aMediaId, TChar& aDrive, TBool& aPresentState);
+
+        /**
+         * Get present medias' media IDs and drives.
+         * 
+         * @param aMediaInfoBuffer buffer where media infos are written
+         * 
+         * @return present media count
+         */
+        TInt32 GetPresentMediasL(TDes8& aMediaInfoBuffer);
+        
+        /**
+         * Search file object which is in not present state.
+ 		 *
+ 		 * @param aDb The database connection
+         * @param aMediaId Memory card's media ID
+         * @param aUri File's URI
+         * @param aFileInfo File information
+         *
+ 		 * @leave KErrNotFound If not present state file object doesn't exist 
+ 		 *                     with given URI and media ID
+         */
+		TItemId SearchNotPresentFileL(TUint32 aMediaId, TDesC16& aUri, 
+									  TMdSFileInfo& aFileInfo,
+									  TFilePresentStates& aPlaceHolder, TBool& aNotPresentState);
+
+        /** from MMdSObjectManipulate */
+        void SetFilesToPresentL(const RArray<TItemId>& aObjectIds);
+		
+        /**
+         * Sets object's relation to present state.
+         * @param aObjectId object ID
+         * @param aIdArray marked relations ID's
+         */
+        void SetRelationsToPresentL(TItemId aObjectId, 
+        		RArray<TItemId>& aIdArray);
+
+        /**
+         * Sets all file objects from last memory card to not present state.
+ 		 * @param aMediaId Memory card's media ID
+         * @param aObjectIds Object IDs of those object which are set to not 
+         *                   present state
+         */
+        void SetFilesToNotPresentL(TUint32 aMediaId, TBool aStartUp, RArray<TItemId>& aObjectIds);
+
+        /**
+         * Sets file objects relations from last memory card to not present 
+         * state.
+         *
+         * @param aMediaId Memory card's media ID
+         * @param aRelationIds changed relation id's
+         */
+        void SetRelationsToNotPresentL(TUint32 aMediaId, 
+        		RArray<TItemId>& aRelationIds);
+
+        /**
+         * Removes all file objects which has given media ID and are in not 
+         * present.
+ 		 *
+         * @param aMediaId Memory card's media ID
+         */
+        void RemoveFilesNotPresentL(TUint32 aMediaId, RArray<TItemId>* aObjectIds);
+
+		/**
+		 * Get schema version from DB
+		 * @param aConnection The database connection
+		 * @param aMajorVersion schema major version
+		 * @param aMinorVersion schema minor version
+		 */
+		void GetSchemaVersionL(TInt& aMajorVersion, TInt& aMinorVersion);
+
+		/**
+		 * Set object to "present" state bu GUID
+		 *
+		 * @leave KErrNotFound MdE can't find object in "not present" state 
+		 *                     with matching GUID
+		 */
+		void SetObjectToPresentByGuidL( 
+				const TInt64& aGuidHigh, const TInt64& aGuidLow );
+		
+		/**
+         * Change path of objects, which match to the old path, to the new 
+         * path.
+         *
+         * @param aOldPath the old path 
+         * @param aNewPath the new path
+         * @param aObjectIds IDs of the change objects
+         */
+		void ChangePathL(const TDesC& aOldPath, const TDesC& aNewPath, 
+				RArray<TItemId>& aObjectIds);
+		
+		/**
+		 * Change C-drive media id and update it to all objects that have the old id.
+		 */
+		void ChangeMediaIdL();
+		
+		/**
+		 * Get removed relation items
+		 * 
+		 * @param aBuffer buffer to fill with returned items
+		 * @param aRemovedRelations removed relations
+		 * @param aAdditionalRemovedRelations possible additional removed relations
+		 */
+		void GetRemovedRelationItemsL( CMdCSerializationBuffer& aBuffer,
+				const RArray<TItemId>& aRemovedRelations,
+				const RArray<TItemId>& aAdditionalRemovedRelations );
+
+		/**
+		 * Set/reset "binary composing to file" pending flag to objects
+		 * 
+		 * @param aObjectIds object IDs
+		 * @param aReset when EFalse flags are setted and when ETrue flags are 
+		 *               resetted
+		 */
+		void SetPendingL(const RArray<TItemId>& aObjectIds, TBool aReset);
+		
+		/**
+		 * Get count of objects with "binary composing to file" pending flag
+		 * 
+		 * @param aObjectDefId object def ID
+		 * 
+		 * @return if >= 0, object count is returned, otherwise error code is 
+		 *         returned
+		 */
+		TInt GetPendingCountL(TDefId aObjectDefId);
+		
+		/**
+		 * Get objects with "binary composing to file" pending flag
+		 * 
+		 * @param aObjectDefId object def ID
+		 * @param aBufferSize maximum ID count of buffer
+		 * @param aObjectIds returned object IDs
+		 * 
+		 * @return if > 0, there was not enough space in buffer, otherwise 
+		 *         error code is returned
+		 */
+		TInt GetPendingL(TDefId aObjectDefId, TInt aBufferSize, 
+				RArray<TItemId>& aObjectIds);
+		
+    protected: // personal methods
+
+		/**
+		 * Add single property from aBuffer and adds it to proper clause and 
+		 * row data.
+		 *
+		 * @param aBuffer serialized property
+		 * @param aObjectDef definition of current object
+		 * @param aBaseObjectClause clause describing base object
+		 * @param aObjectClause clause describing current object
+		 * @param aBaseObjectDataRow data row contains base object values
+		 * @param aObjectDataRow data row contains current object values
+		 * @return new property definition
+		*/		 
+		const CMdsPropertyDef& ReadPropertyL( 
+				CMdCSerializationBuffer& aBuffer, 
+				const CMdsObjectDef& aObjectDef, 
+				CMdsClauseBuffer& aBaseObjectClause, 
+				CMdsClauseBuffer& aObjectClause,
+                RRowData& aBaseObjectDataRow, RRowData& aObjectDataRow, 
+                TUint8& aFlags );
+
+		/**
+		 * Search in DB for freeText
+		 *
+		 * @param aFreeText freetext to search for
+		 * @return if find ETrue, else EFalse
+		 */
+		TItemId FindFreeTextInDbL( TPtrC16 aFreeText );
+		
+        /**
+	    * Deletes BaseObject.
+	    */	   	    
+        TBool DoGarbageCollectionL();    
+        
+	private: // Member data
+		struct TLockBuffer
+			{
+			CMdsClauseBuffer* iBuffer;
+			TBool iLock;
+			};
+
+    	TRequestStatus iTextSearcherDeleteFreeTextStatus;
+
+    	TItemId iTextSearcherDeleteFreeTextObjectId;
+
+    	TRequestStatus iTextSearcherAddFreeTextStatus;
+
+    	TItemId iTextSearcherAddFreeTextObjectId;
+
+		TItemId iCreationEventId;
+
+		TItemId iDeletionEventId;
+
+        /**
+         * pointer to actual processing namespace
+         */
+        const CMdsNamespaceDef* iNamespaceDef;
+        
+        /**
+         * common usage buffers (initial size = 1024)
+         * NOT THREAD SAFE!
+         */
+        RArray<TLockBuffer> iBuffers;
+
+		/**
+		 * BaseObject definition, used in addobject and addproperty
+		 */
+		const CMdsObjectDef* iBaseObjectDef;
+	
+	    /**
+        * Store every namespace read from schema file.
+        */
+	    const CMdsSchema& iSchema;
+	    
+	    /**
+	     * guid generator
+	     */
+	    CMdSIdentifierGenerator* iGenerator;
+
+	    CMdSObjectLockList& iLockList;
+	    
+	    TBuf<256> iLastAddedObjName;
+	    
+	private:
+		class RClauseBuffer
+					// NOT THREAD SAFE !!!!!
+			{
+			public:
+				RClauseBuffer(CMdSSqlObjectManipulate& aSOM, TInt aSize = 1024);
+				
+				CMdsClauseBuffer& BufferL();
+
+				void Close();
+
+			private:
+				RArray<TLockBuffer>& iBuffers;
+				CMdsClauseBuffer* iBuffer;
+				TInt iNr;
+				const TInt iSize;
+			};
+	};
+
+#include "mdssqlobjectmanipulate.inl"
+
+#endif	// __MDSSQLOBJECTMANIPULATE_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/inc/mdssqlobjectmanipulate.inl	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,23 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Add, update and remove items in DB.
+*                Basic DB manipulation engine.
+*
+*/
+
+/*inline TInt CMdSSqlObjectManipulate::TNumber2PropertyOrder( const TNumber2Property& aLeft, const TNumber2Property& aRight )
+	{
+	return aLeft.iPropertyNo - aRight.iPropertyNo;
+	}*/
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdebackuprestorewatcher.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,145 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#include "mdebackuprestorewatcher.h"
+
+#ifdef _DEBUG
+#include <e32debug.h>
+#endif
+
+#include <e32property.h>
+#include <sbdefs.h>
+
+CMdEBackupRestoreWatcherAO* CMdEBackupRestoreWatcherAO::NewL(MMdEBackupRestoreObserver& aObserver)
+	{
+	CMdEBackupRestoreWatcherAO* self = CMdEBackupRestoreWatcherAO::NewLC( aObserver );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+CMdEBackupRestoreWatcherAO* CMdEBackupRestoreWatcherAO::NewLC(MMdEBackupRestoreObserver& aObserver)
+	{
+	CMdEBackupRestoreWatcherAO* self = new(ELeave) CMdEBackupRestoreWatcherAO( aObserver );
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+	}
+
+
+CMdEBackupRestoreWatcherAO::CMdEBackupRestoreWatcherAO(MMdEBackupRestoreObserver& aObserver) 
+	: CActive(CActive::EPriorityStandard), iObserver( aObserver )
+	{
+	}
+
+void CMdEBackupRestoreWatcherAO::ConstructL()
+	{
+	#ifdef _DEBUG
+	RDebug::Print(_L("CMdEBackupRestoreWatcherAO::ConstructL()"));
+	#endif
+
+	CActiveScheduler::Add( this );
+
+	iStatus = KRequestPending;
+	iProperty.Attach( KUidSystemCategory, conn::KUidBackupRestoreKey );
+	iProperty.Subscribe( iStatus );
+	SetActive();
+	}
+
+CMdEBackupRestoreWatcherAO::~CMdEBackupRestoreWatcherAO()
+	{
+	#ifdef _DEBUG
+	RDebug::Print(_L("CMdEBackupRestoreWatcherAO::~CMdEBackupRestoreWatcherAO()"));	
+	#endif
+
+	Cancel();
+
+	iProperty.Close();	
+	}
+
+void CMdEBackupRestoreWatcherAO::RunL()
+	{
+	#ifdef _DEBUG
+	RDebug::Print(_L("CMdEBackupRestoreWatcherAO::RunL"));
+	#endif
+
+	iProperty.Subscribe( iStatus );
+	SetActive();
+
+	TInt backupStateValue = conn::EBURUnset;
+	iProperty.Get( backupStateValue );
+
+	backupStateValue &= conn::KBURPartTypeMask;
+
+	switch ( backupStateValue )
+		{
+		case conn::EBURBackupFull:
+		case conn::EBURBackupPartial:
+			{
+			#ifdef _DEBUG
+			RDebug::Print(_L("CMdEBackupRestoreWatcherAO::RunL - BackupFull/BackupPartial"));
+			#endif
+		
+			// Notify all observers about backup.
+			iObserver.HandleBackup();
+			break;
+			}
+		case conn::EBURRestoreFull:
+		case conn::EBURRestorePartial:
+			{
+			#ifdef _DEBUG
+			RDebug::Print(_L("CMdEBackupRestoreWatcherAO::RunL - RestoreFull/RestorePartial"));
+			#endif
+		
+			// Notify all observers about restore.
+			iObserver.HandleRestore();
+			break;
+			}
+		case conn::EBURNormal:
+		case conn::EBURUnset:
+		default:
+			{
+#ifdef _DEBUG
+			RDebug::Print(_L("CMdEBackupRestoreWatcherAO::RunL - Normal"));
+#endif
+		
+			// Backup or restore is completed. Resume normal operation.
+			iObserver.ResumeOperation();
+			}
+		}
+	}
+
+void CMdEBackupRestoreWatcherAO::DoCancel()
+	{
+	#ifdef _DEBUG
+	RDebug::Print(_L("CMdEBackupRestoreWatcherAO::DoCancel"));
+	#endif
+
+	iProperty.Cancel();
+	}
+
+#ifdef _DEBUG	
+TInt CMdEBackupRestoreWatcherAO::RunError(TInt aError)
+#else
+TInt CMdEBackupRestoreWatcherAO::RunError(TInt /*aError*/)
+#endif
+	{
+	#ifdef _DEBUG
+	RDebug::Print(_L("CMdEBackupRestoreWatcherAO::RunError() - error %d"), aError);
+	#endif
+
+	// start again?
+	return KErrNone;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsclausebuffer.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,141 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A unicode des buffer with automatic memory handling*
+*/
+
+#include "mdsclausebuffer.h"
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CMdsClauseBuffer* CMdsClauseBuffer::NewL( TInt aInitialSize )
+    {
+    CMdsClauseBuffer* that = CMdsClauseBuffer::NewLC( aInitialSize );
+    CleanupStack::Pop( that );
+    return that;
+    }
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CMdsClauseBuffer* CMdsClauseBuffer::NewLC( TInt aInitialSize )
+    {
+    CMdsClauseBuffer* that = new( ELeave ) CMdsClauseBuffer();
+    CleanupStack::PushL( that );
+    that->ConstructL( aInitialSize );
+    return that;
+    }
+
+// ---------------------------------------------------------------------------
+// CMdCAutoBuf
+// ---------------------------------------------------------------------------
+//
+CMdsClauseBuffer::CMdsClauseBuffer()
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// ~CMdCAutoBuf
+// ---------------------------------------------------------------------------
+//
+CMdsClauseBuffer::~CMdsClauseBuffer()
+    {
+    delete iBuffer;
+    }
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CMdsClauseBuffer::ConstructL( TInt aInitialSize )
+    {
+    if ( aInitialSize < 1 )
+    	{
+    	aInitialSize = 1;
+    	}
+    iCurrentBufSize = aInitialSize;
+    if (aInitialSize > 100000 || aInitialSize < 0)
+    	{
+    	aInitialSize = 0;
+    	}
+
+    iBuffer = HBufC::NewL( iCurrentBufSize );
+    }
+
+// ---------------------------------------------------------------------------
+// AppendL
+// ---------------------------------------------------------------------------
+//
+void CMdsClauseBuffer::AppendL( const TDesC& aDes )
+    {
+    AppendL( aDes, 0 );
+    }
+
+void CMdsClauseBuffer::AppendL( const TDesC& aDes, const TInt aAdditional )
+	{
+	ReserveSpaceL( iBuffer->Size() + aDes.Length() + 1 + aAdditional );
+
+	iBuffer->Des().Append( aDes );
+	}
+
+
+// ---------------------------------------------------------------------------
+// ReserveSpaceL
+// ---------------------------------------------------------------------------
+//
+TBool CMdsClauseBuffer::ReserveSpaceL( TInt aRequired )
+    {
+    // check if the current buffer is enough
+    if ( iCurrentBufSize >= aRequired  )
+        {
+        return EFalse;
+        }
+
+	iCurrentBufSize = aRequired;
+
+    // realloc and copy
+    iBuffer = iBuffer->ReAllocL( iCurrentBufSize );
+
+    return ETrue;
+    }
+
+// ---------------------------------------------------------------------------
+// BufferL
+// ---------------------------------------------------------------------------
+//
+TPtr CMdsClauseBuffer::BufferL() const
+	{
+	if( !iBuffer )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	return iBuffer->Des();
+	}
+
+// ---------------------------------------------------------------------------
+// ConstBufferL
+// ---------------------------------------------------------------------------
+//
+const TDesC& CMdsClauseBuffer::ConstBufferL() const
+	{
+	if( !iBuffer )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	return *iBuffer;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsdbconnectionpool.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,65 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementations of methods for connection pool*
+*/
+
+// INCLUDE FILES
+#include "mdsdbconnectionpool.h"
+#include "mdssqliteconnection.h"
+#include "mdsindexer.h"
+#include "mdccommon.h"
+#include "mdccommon.pan"
+
+void MMdSDbConnectionPool::DisconnectAll()
+	{
+	iConnection->CloseDb();
+	iDBValid = EFalse;
+	}
+        
+void MMdSDbConnectionPool::ConnectAllL()
+	{
+	if ( iConnection && !iDBValid )
+		{
+		iConnection->OpenDbL( KMdsSqlDbDefaultName );
+		iDBValid = ETrue;
+
+	    MMdSIndexer::StartIndexL();
+		}
+	else
+		{
+		User::Leave( KErrBadHandle );
+		}
+	}
+
+void MMdSDbConnectionPool::SetDefaultDB( CMdSSqLiteConnection* aConnection )
+	{
+   	iConnection = aConnection;
+	}
+
+CMdSSqLiteConnection& MMdSDbConnectionPool::GetDefaultDBL()
+	{
+	__ASSERT_DEBUG( iConnection, User::Panic( _L("Incorrect DB connection"), KErrArgument ) );
+	if ( !iConnection || !iDBValid )
+		{
+		User::Leave( KErrBadHandle );
+		}
+   	return *iConnection;
+	}
+
+//----------------------------------------------
+// INITIALIZE STATIC DATA
+//----------------------------------------------
+
+CMdSSqLiteConnection* MMdSDbConnectionPool::iConnection = NULL;
+TBool MMdSDbConnectionPool::iDBValid = EFalse;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsdiskspacenotifier.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,195 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is disk space notifier for Metadata server.*
+*/
+
+// INCLUDE FILES
+#include "mdsdiskspacenotifier.h"
+
+
+CMdSDiskSpaceNotifierAO* CMdSDiskSpaceNotifierAO::NewL(
+	MMdSDiskSpaceNotifierObserver& aObserver, TInt64 aThreshold, const TDesC& aFilename)
+	{
+	CMdSDiskSpaceNotifierAO* self = 
+		CMdSDiskSpaceNotifierAO::NewLC( aObserver, aThreshold, aFilename );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+CMdSDiskSpaceNotifierAO* CMdSDiskSpaceNotifierAO::NewLC(
+	MMdSDiskSpaceNotifierObserver& aObserver, TInt64 aThreshold, const TDesC& aFilename)
+	{
+	TDriveNumber driveNumber = GetDriveNumberL( aFilename );
+
+    CMdSDiskSpaceNotifierAO* self = 
+    	new ( ELeave ) CMdSDiskSpaceNotifierAO( aObserver, aThreshold, driveNumber );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+	}
+
+CMdSDiskSpaceNotifierAO::~CMdSDiskSpaceNotifierAO()
+	{
+	Cancel();
+
+	iFileServerSession.Close();
+	}
+
+void CMdSDiskSpaceNotifierAO::RunL()
+	{	
+	TVolumeInfo volumeInfo;
+
+	if ( iState == CMdSDiskSpaceNotifierAO::ENormal )
+		{
+		TInt status = iStatus.Int();
+		
+		switch( status )
+			{
+			case KErrNone:
+				iFileServerSession.Volume( volumeInfo, iDrive );
+				
+				// Check if free space is less than threshold level
+				if( volumeInfo.iFree < iThreshold )
+					{
+					iObserver.HandleDiskSpaceNotificationL( MMdSDiskSpaceNotifierObserver::ELess );
+					iDiskFull = ETrue;
+					iState = EIterate;
+					iIterationCount = 0;
+					SetActive();
+					TRequestStatus* status = &iStatus;
+					User::RequestComplete( status, KErrNone );
+					return;
+					}
+				else
+					{
+					iObserver.HandleDiskSpaceNotificationL( MMdSDiskSpaceNotifierObserver::EMore );
+					iDiskFull = EFalse;
+					}
+				StartNotifier();
+				break;
+
+			case KErrArgument:
+				User::Leave( status );
+				break;
+			default:
+				break;
+			}
+		}
+	else if ( iState == CMdSDiskSpaceNotifierAO::EIterate )
+		{
+		const TInt KMaxIterations = 10;
+		
+		iFileServerSession.Volume( volumeInfo, iDrive );
+		if ( volumeInfo.iFree < iThreshold )
+			{
+			iObserver.HandleDiskSpaceNotificationL( MMdSDiskSpaceNotifierObserver::ELess );
+			++iIterationCount;
+			if ( iIterationCount < KMaxIterations )
+				{
+				SetActive();
+				TRequestStatus* status = &iStatus;
+				User::RequestComplete( status, KErrNone );
+				return;
+				}
+			else
+				{
+				iFileServerSession.Volume( volumeInfo, iDrive );
+				if ( volumeInfo.iFree >= iThreshold )
+					{
+					iDiskFull = EFalse;
+					}
+				}
+			}
+		else
+			{
+			iDiskFull = EFalse;
+			}
+		iState = ENormal;
+		iIterationCount = 0;
+		StartNotifier();			
+		}
+	else
+		{
+		User::Leave( KErrGeneral );
+		}
+	}
+
+TInt CMdSDiskSpaceNotifierAO::RunError(TInt aError)
+	{
+	iObserver.HandleDiskSpaceError( aError );
+	
+	return KErrNone;
+	}
+
+void CMdSDiskSpaceNotifierAO::DoCancel()
+	{
+	if( IsActive() )
+		{	
+		iFileServerSession.NotifyDiskSpaceCancel();
+		}
+	}
+
+CMdSDiskSpaceNotifierAO::CMdSDiskSpaceNotifierAO(
+	MMdSDiskSpaceNotifierObserver& aObserver, TInt64 aThreshold, TDriveNumber aDrive)
+	: CActive( CActive::EPriorityStandard ), 
+	iObserver( aObserver ), iThreshold( aThreshold ), iDrive( aDrive ), iState( CMdSDiskSpaceNotifierAO::ENormal ), iDiskFull( EFalse )
+	{
+	CActiveScheduler::Add( this );
+	}
+
+void CMdSDiskSpaceNotifierAO::ConstructL()
+	{	
+	TInt KMessageSlotCount = 2; // slots for NotifyDiskSpace and NotifyDiskSpaceCancel
+
+	User::LeaveIfError( iFileServerSession.Connect( KMessageSlotCount ) );
+	
+	TVolumeInfo volumeInfo;
+	iFileServerSession.Volume( volumeInfo, iDrive );	
+	if ( volumeInfo.iFree < iThreshold )
+		{
+		iDiskFull = ETrue;
+		}
+
+	StartNotifier();
+	}
+
+void CMdSDiskSpaceNotifierAO::StartNotifier()
+	{	
+	iFileServerSession.NotifyDiskSpace( iThreshold, iDrive, iStatus );
+	
+	SetActive();
+	}
+
+TDriveNumber CMdSDiskSpaceNotifierAO::GetDriveNumberL( const TDesC& aFilename )
+	{
+	TLex driveParser( aFilename );
+	
+	TChar driveChar = driveParser.Get();
+
+	if( 0 == driveChar || TChar( ':' ) != driveParser.Peek() )
+		{
+		User::Leave( KErrArgument );
+		}
+		
+	TInt driveNumber;
+	
+	RFs::CharToDrive( driveChar, driveNumber );
+	
+	return (TDriveNumber)driveNumber;
+	}
+
+TBool CMdSDiskSpaceNotifierAO::DiskFull() const
+	{
+	return iDiskFull;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdseventdef.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,109 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one object and it's properties
+*
+*/
+
+#include "mdseventdef.h"
+
+#include "mdcdef.h"
+#include "mdssqliteconnection.h"
+#include "mdsindexer.h"
+
+/**
+ * NewLC
+ */
+CMdsEventDef* CMdsEventDef::NewLC( const TDesC& aName, const TInt32 aPriority )
+	{
+	CMdsEventDef* ret = new( ELeave ) CMdsEventDef(  );
+	CleanupStack::PushL( ret );
+	ret->ConstructL( aName, aPriority );
+	return ret;
+	}
+	
+/**
+ * NewL
+ */
+CMdsEventDef* CMdsEventDef::NewL( const TDesC& aName, const TInt32 aPriority )
+	{
+	CMdsEventDef* ret = CMdsEventDef::NewLC( aName, aPriority );
+	CleanupStack::Pop( ret );
+	return ret;
+	}
+
+/**
+ * ConstructL
+ */
+void CMdsEventDef::ConstructL( const TDesC& aName, TInt32 aPriority )
+	{
+	// check that only allowed characters (A-Z, a-z) are used
+	CheckAllowerCharatersL( aName, EFalse );
+
+	CMdsItemDef::ConstructL( aName );
+	iPriority = aPriority;
+	}
+
+/**
+ * Destructor
+ */
+CMdsEventDef::~CMdsEventDef()
+	{
+	}
+	
+void CMdsEventDef::StoreToDBL( const TInt aNamespaceDefId )
+	{
+	_LIT( KMdsSqlClauseAddEventDef, "INSERT INTO EventDef (NamespaceDefId, Priority, Name ) Values(?, ?, ?);" );	
+	
+	if ( GetStoredInDB() )
+		{
+		return;
+		}
+
+    RRowData rowData;
+    CleanupClosePushL( rowData );
+	rowData.AppendL( TColumn( aNamespaceDefId ) );
+	rowData.AppendL( TColumn( iPriority ) );
+	rowData.AppendL( TColumn( GetName().AllocL() ) );
+
+	TDefId id = MMdSIndexer::ExecuteAndGetIndexL(KMdsSqlClauseAddEventDef, rowData );
+
+	SetId( id );
+ 	SetStoredInDB();
+
+	CleanupStack::PopAndDestroy( &rowData );
+	}
+
+TBool CMdsEventDef::operator==( const CMdsEventDef& aEventDef ) const
+	{
+	return GetName() == aEventDef.GetName() && iPriority == aEventDef.iPriority;
+	}
+
+TUint32 CMdsEventDef::RequiredBufferSize()
+	{
+	return sizeof(TMdCEventDef) + CMdsItemDef::RequiredBufferSize();
+	}
+
+TMdCOffset CMdsEventDef::SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreeSpace)
+	{
+	TMdCEventDef eventDef;
+	eventDef.iDefId = GetId();
+	
+	// store name
+	eventDef.iName.iPtr.iCount = GetName().Length();
+	eventDef.iName.iPtr.iOffset = aFreeSpace;
+	eventDef.SerializeL( aBuffer );
+	
+	aBuffer.PositionL( aFreeSpace );
+	return CMdsItemDef::SerializeL( aBuffer );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsfindengine.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,412 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Manages object search from database*
+*/
+
+#include "mdsfindengine.h"
+
+#include "mdcresult.h"
+#include "mdcitem.h"
+#include "mdsdbconnectionpool.h"
+#include "mdsobjectlocklist.h"
+#include "mdsserversession.h"
+#include "mdsfindsequence.h"
+#include "mdslogger.h"
+#include "mdcserializationbuffer.h"
+#include "mdsschema.h"
+#include "mdsserver.h"
+
+__USES_LOGGER
+
+
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CMdSFindEngine* CMdSFindEngine::NewL(
+	TUint32 aQueryId, 
+    CMdSServerSession& aParent,
+    CMdSObjectLockList& aLockList,
+    CMdsSchema& aSchemaNew )
+    {
+    CMdSFindEngine* self = CMdSFindEngine::NewLC(
+        aQueryId, aParent, aLockList, aSchemaNew );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+CMdSFindEngine* CMdSFindEngine::NewLC(
+	TUint32 aQueryId, 
+    CMdSServerSession& aParent,
+    CMdSObjectLockList& aLockList,
+    CMdsSchema& aSchemaNew )
+    {
+    CMdSFindEngine* self = new ( ELeave ) CMdSFindEngine(
+        aQueryId, aParent, aLockList );
+    CleanupStack::PushL( self );
+    self->ConstructL( aSchemaNew );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Default constructor
+// ---------------------------------------------------------------------------
+//
+CMdSFindEngine::CMdSFindEngine(
+	TUint32 aQueryId, 
+    CMdSServerSession& aParent,
+    CMdSObjectLockList& aLockList )
+    : iQueryId( aQueryId )
+    , iParent( aParent )
+    , iLockList( aLockList )
+    , iSequence( NULL )
+    , iSerializedCriteria( NULL )
+    , iAsyncPending( EFalse )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CMdSFindEngine::ConstructL( CMdsSchema& aSchema )
+    {
+    iSequence = CMdSFindSequence::NewL( iParent.GetServer(), aSchema, *this );
+    }
+
+// ---------------------------------------------------------------------------
+// QueryId
+// ---------------------------------------------------------------------------
+//
+TUint32 CMdSFindEngine::QueryId()
+	{
+	return iQueryId;
+	}
+
+// ---------------------------------------------------------------------------
+// SetFindParams
+// ---------------------------------------------------------------------------
+//
+void CMdSFindEngine::SetFindParams( TUint32 aNotifyCount )
+    {
+    iSequence->SetFindParams( aNotifyCount );
+    }
+
+// ---------------------------------------------------------------------------
+// SetFindCriteria
+// ---------------------------------------------------------------------------
+//
+void CMdSFindEngine::SetFindCriteria( CMdCSerializationBuffer* aSerializedCriteria )
+    {
+    iSerializedCriteria = aSerializedCriteria;
+    }
+
+// ---------------------------------------------------------------------------
+// CreateResultSetL
+// ---------------------------------------------------------------------------
+//
+void CMdSFindEngine::CreateResultSet(RMessage2 aMessage)
+    {
+    iMessage = aMessage;
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CMdSFindEngine::~CMdSFindEngine()
+    {
+   	delete iSerializedCriteria;
+   	delete iSequence;
+    }
+
+// ---------------------------------------------------------------------------
+// FindL
+// ---------------------------------------------------------------------------
+//
+TInt CMdSFindEngine::FindL( TUserLevel aUserLevel )
+    {
+    const TInt result = iSequence->FindL( *iSerializedCriteria, aUserLevel );
+
+    if( result == KErrNone && iMessage.IsNull() == EFalse )
+    	{
+    	TPckgBuf<TInt> sizeBuf( iSequence->ResultsL().Size() );
+    	iMessage.WriteL( 2, sizeBuf );
+    	}
+    
+    return result;
+    }
+
+// ---------------------------------------------------------------------------
+// ContinueL
+// ---------------------------------------------------------------------------
+//
+TInt CMdSFindEngine::ContinueL()
+    {
+    const TInt result = iSequence->ContinueL();
+    
+    if( result == KErrNone && iMessage.IsNull() == EFalse )
+    	{
+    	TPckgBuf<TInt> sizeBuf( iSequence->ResultsL().Size() );
+    	iMessage.WriteL( 2, sizeBuf );
+    	}
+        
+    return result;
+    }
+
+// ---------------------------------------------------------------------------
+// FindAsyncL
+// ---------------------------------------------------------------------------
+//
+void CMdSFindEngine::FindAsyncL( TUserLevel aUserLevel )
+    {
+    iAsyncPending = ETrue;
+    iSequence->FindAsync( *iSerializedCriteria, aUserLevel );
+    }
+
+// ---------------------------------------------------------------------------
+// ContinueAsync
+// ---------------------------------------------------------------------------
+//
+void CMdSFindEngine::ContinueAsync()
+    {
+    iAsyncPending = ETrue;
+    iSequence->ContinueAsync();
+    }
+
+// ---------------------------------------------------------------------------
+// Cancel
+// ---------------------------------------------------------------------------
+//
+void CMdSFindEngine::Cancel( TInt aError )
+    {
+    TBool toComplete = iAsyncPending;
+    iAsyncPending = EFalse;
+    iSequence->Cancel();
+
+    if( iMessage.IsNull() == EFalse )
+    	{
+    	if ( toComplete ) 
+    		{
+    		iMessage.Complete( KErrCancel );
+    		}
+    	else 
+    		{
+    		iMessage.Complete( aError );
+    		}
+    	}
+    }
+
+// ---------------------------------------------------------------------------
+// SetComplete
+// ---------------------------------------------------------------------------
+//
+void CMdSFindEngine::SetComplete( TInt aError )
+    {
+    TBool toComplete = iAsyncPending;
+    __LOG1( ELogServer, "<- Find Set Complete (%d)", aError );
+
+    if( aError == KErrNone )
+        {
+        TUint32 resultSize = 0;
+
+        TInt err = KErrNone;
+
+        TRAP( err, resultSize = iSequence->ResultsL().Size() );
+
+       	if( err )
+       		{
+       		if ( toComplete && iMessage.IsNull() == EFalse ) 
+       			{
+       			iMessage.Complete( err );
+       			}
+       		return;
+       		}
+
+        iAsyncPending = EFalse;
+
+       	if ( iMessage.IsNull() == EFalse )
+       		{
+       		TPckgBuf<TInt> sizeBuf( resultSize );
+
+       		err = iMessage.Write( 2, sizeBuf );
+       		}
+
+       	if( err )
+       		{
+       		if ( toComplete && iMessage.IsNull() == EFalse ) 
+       			{
+       			iMessage.Complete( err );
+       			}
+       		return;
+       		}
+       	else
+       		{        	
+       		if ( toComplete && iMessage.IsNull() == EFalse ) 
+       			{
+       			iMessage.Complete( EAsyncFindSetReady );
+       			}
+       		}
+        }
+    else
+        {
+       	if ( toComplete && iMessage.IsNull() == EFalse ) 
+       		{
+       		iMessage.Complete( aError );
+       		}
+       	return;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// FindComplete
+// ---------------------------------------------------------------------------
+//
+void CMdSFindEngine::FindComplete( TInt aError )
+    {
+    TBool toComplete = iAsyncPending;
+    __LOG1( ELogServer, "<- Find Complete (%d)", aError );
+
+    if( aError == KErrNone )
+        {
+        TUint32 resultSize = 0;
+
+        TInt err = KErrNone;
+
+        TRAP( err, resultSize = iSequence->ResultsL().Size() );
+
+       	if( err )
+       		{
+       		if ( toComplete && iMessage.IsNull() == EFalse )
+       			{
+       			iMessage.Complete( err );
+       			}
+       		return;
+       		}
+
+        iAsyncPending = EFalse;
+        
+        if ( iMessage.IsNull() == EFalse )
+        	{
+        	TPckgBuf<TInt> sizeBuf( resultSize );    	
+
+        	err = iMessage.Write( 2, sizeBuf );
+        	}
+
+       	if( err )
+       		{
+       		if ( toComplete && iMessage.IsNull() == EFalse ) 
+       			{
+       			iMessage.Complete( err );
+       			}
+       		return;
+       		}
+       	else
+			{
+        	if ( toComplete && iMessage.IsNull() == EFalse ) 
+        		{
+        		iMessage.Complete( EAsyncFindComplete );
+        		}
+			}
+        }
+    else
+        {
+       	if ( toComplete && iMessage.IsNull() == EFalse ) 
+       		{
+       		iMessage.Complete( aError );
+       		}
+       	return;
+        }
+    }
+
+const CMdCSerializationBuffer& CMdSFindEngine::ResultsL() const
+	{
+	return iSequence->ResultsL();
+	}
+
+void CMdSFindEngine::SetResultMode( TBool aResultModeItems )
+	{
+	iLastResultModeItems = aResultModeItems;
+	}
+
+TBool CMdSFindEngine::IsComplete() const
+	{
+	if( iSequence )
+		{		
+		return iSequence->IsComplete();
+		}
+	else
+		{
+		return ETrue;
+		}
+	}
+	
+TBool CMdSFindEngine::IsQueryComplete()
+	{
+	if( iSequence )
+		{		
+		return iSequence->IsQueryComplete();
+		}
+	else
+		{
+		return ETrue;
+		}
+	}	
+
+CMdSServer& CMdSFindEngine::GetServer() const
+	{
+	return iParent.GetServer();
+	}
+
+void CMdSFindEngine::LockFindResultObjectsL( CMdSObjectLockList& aLockList )
+	{
+	if (!iLastResultModeItems)
+		{
+		return;
+		}
+
+	CMdsSchema& schema = iParent.GetServer().Schema();
+	CMdCSerializationBuffer& buffer = iSequence->ResultsL();
+	buffer.PositionL( KNoOffset );
+	TMdCItems items;
+	items.DeserializeL( buffer );
+
+	const CMdsNamespaceDef* namespaceDef = schema.GetNamespaceByIdL( items.iNamespaceDefId );
+
+	for(TInt32 i = 0; i < items.iObjects.iPtr.iCount; ++i)
+		{
+		buffer.PositionL( items.iObjects.iPtr.iOffset + i * sizeof(TMdCObject) );
+		TMdCObject object;
+		object.DeserializeL( buffer );
+
+		if ( aLockList.IsLocked( *namespaceDef, object.iId ) )
+			{
+			object.iFlags &= ~EMdEObjectFlagModOpen;
+			}
+		else
+			{
+			aLockList.LockObjectL( iParent, *namespaceDef, object.iId );
+			object.iFlags |= EMdEObjectFlagModOpen;
+			}
+
+		buffer.PositionL( items.iObjects.iPtr.iOffset + i * sizeof(TMdCObject) );
+		object.SerializeL( buffer );
+		}
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsfindsequence.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,642 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Manages object search from database*
+*/
+
+#include <badesca.h>
+
+#include "mdsfindsequence.h"
+
+#include "mdcitem.h"
+#include "mdcresult.h"
+#include "mdcserializationbuffer.h"
+#include "mdsschema.h"
+#include "mdslogger.h"
+#include "mdsfindengine.h"
+#include "mdssqlfindoperation.h"
+#include "mdssqliteconnection.h"
+#include "mdsfindsqlclause.h"
+#include "mdsdbconnectionpool.h"
+#include "mdsclausebuffer.h"
+
+
+/** logging instance */
+__USES_LOGGER
+
+
+// ------------------------------------------------
+// NewL
+// ------------------------------------------------
+//
+CMdSFindSequence* CMdSFindSequence::NewL( 
+	CMdSServer& aServer, CMdsSchema& aSchema, CMdSFindEngine& aObserver )
+    {
+    CMdSFindSequence* self = CMdSFindSequence::NewLC( aServer, aSchema, aObserver );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ------------------------------------------------
+// NewLC
+// ------------------------------------------------
+//
+CMdSFindSequence* CMdSFindSequence::NewLC( 
+	CMdSServer& aServer, CMdsSchema& aSchema, CMdSFindEngine& aObserver )
+    {
+    CMdSFindSequence* self = new(ELeave) CMdSFindSequence( aServer, aSchema, aObserver );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// ------------------------------------------------
+// Default constructor
+// ------------------------------------------------
+//
+CMdSFindSequence::CMdSFindSequence( 
+	CMdSServer& aServer, CMdsSchema& aSchema, CMdSFindEngine& aObserver )
+    : CActive( CActive::EPriorityStandard )
+    , iServer( aServer )
+    , iSchema( aSchema )
+    , iObserver( &aObserver )
+    , iUserLevel( EUserLevelNone )
+    {
+	iNotifyCount = KMaxTUint32;
+
+    iFindOperation = NULL;
+    }
+
+// ------------------------------------------------
+// ConstructL
+// ------------------------------------------------
+//
+void CMdSFindSequence::ConstructL()
+    {
+    CActiveScheduler::Add( this );
+    __INIT_LOGGER;
+    }
+
+// ------------------------------------------------
+// Destructor
+// ------------------------------------------------
+//
+CMdSFindSequence::~CMdSFindSequence()
+    {
+    CleanUp();
+    
+    Cancel();
+    }
+
+void CMdSFindSequence::SetFindParams( TUint32 aNotifyCount )
+	{
+	iNotifyCount = aNotifyCount;
+	}
+
+// ------------------------------------------------
+// FindL
+// ------------------------------------------------
+//
+TInt CMdSFindSequence::FindL(
+    CMdCSerializationBuffer& aSerializedCriteria,
+    TUserLevel aUserLevel )
+    {
+    __ASSERT_DEBUG( !iFindOperation, MMdCCommon::Panic( KErrCorrupt ) );
+
+	iUserLevel = aUserLevel;
+
+	iSerializedCriteria = &aSerializedCriteria;
+
+	if( iFindResults )
+		{
+		delete iFindResults;
+		iFindResults = NULL;
+		}
+ 
+    iFindOperation = CreateOperationL( aSerializedCriteria );
+
+    TInt result = KErrNone;
+    result = iFindOperation->ExecuteL();
+    
+    iFindResults = iFindOperation->Results();
+    
+    if( iFindResults )
+    	{
+    	PostProcessL( *iFindResults );
+    	}
+
+    return result;
+    }
+
+// ------------------------------------------------
+// ContinueL
+// ------------------------------------------------
+//
+TInt CMdSFindSequence::ContinueL()
+    {
+    __ASSERT_DEBUG( iFindOperation, MMdCCommon::Panic( KErrCorrupt ) );
+
+	if( iFindResults )
+		{
+		delete iFindResults;
+		iFindResults = NULL;
+		}
+    
+    TInt result = iFindOperation->ContinueL();
+
+    if ( result == KErrNone )
+        {
+        iFindResults = iFindOperation->Results();
+
+		if( iFindResults )
+			{
+			PostProcessL( *iFindResults );
+			}
+        }
+
+    return result;
+    }
+
+// ------------------------------------------------
+// FindAsync
+// ------------------------------------------------
+//
+void CMdSFindSequence::FindAsync(CMdCSerializationBuffer& aSerializedCriteria,
+		TUserLevel aUserLevel )
+    {
+    __ASSERT_DEBUG( !iFindOperation, MMdCCommon::Panic( KErrCorrupt ) );
+    
+    iUserLevel = aUserLevel;
+
+	if( iFindResults )
+		{
+		delete iFindResults;
+		iFindResults = NULL;
+		}
+
+    iSerializedCriteria = &aSerializedCriteria;
+
+    SetActive();
+    TRequestStatus* pStatus = &iStatus;
+    User::RequestComplete( pStatus, EAsyncFind );
+    }
+
+// ------------------------------------------------
+// ContinueAsync
+// ------------------------------------------------
+//
+void CMdSFindSequence::ContinueAsync()
+    {
+    __ASSERT_DEBUG( iFindOperation, MMdCCommon::Panic( KErrCorrupt ) );
+
+	if( iFindResults )
+		{
+		delete iFindResults;
+		iFindResults = NULL;
+		}
+
+    SetActive();
+    TRequestStatus* pStatus = &iStatus;
+    User::RequestComplete( pStatus, EContinueAsyncFind );
+    }
+
+// ------------------------------------------------
+// Results
+// ------------------------------------------------
+//
+CMdCSerializationBuffer& CMdSFindSequence::ResultsL() const
+    {
+    if( !iFindResults )
+    	{
+    	User::Leave( KErrCorrupt );
+    	}
+
+    return *iFindResults;
+    }
+
+// ------------------------------------------------
+// SetResultMode
+// ------------------------------------------------
+//
+void CMdSFindSequence::SetResultMode( TBool aResultModeItems )
+	{
+	iLastResultModeItems = aResultModeItems;
+	iObserver->SetResultMode( aResultModeItems );
+	}
+
+// ------------------------------------------------
+// RunL
+// ------------------------------------------------
+//
+void CMdSFindSequence::RunL()
+    {
+    TInt result = 0;
+
+    switch ( iStatus.Int() )
+        {
+        case EAsyncFind:
+            {
+            iFindOperation = CreateOperationL( *iSerializedCriteria );
+            result = iFindOperation->ExecuteL();
+            break;
+            }
+        case EContinueAsyncFind:
+            {
+            if( iFindOperation )
+            	{
+            	result = iFindOperation->ContinueL();
+            	}
+            else
+            	{
+            	result = KErrNotFound;
+            	}
+            break;
+            }
+        default:
+            {
+#ifdef _DEBUG
+            User::Panic( _L("MdSFSRun") , KErrCorrupt );
+#endif            
+            User::Leave( KErrCorrupt );
+            }
+        }
+    if( result == KErrNone || result == KFindSetReady )
+        {
+        iFindResults = iFindOperation->Results();
+
+        if( iFindResults )
+        	{        	
+        	PostProcessL( *iFindResults );
+        	}
+        }
+
+    if ( result == KFindSetReady )
+        {
+        CMdSFindEngine* obs = iObserver;
+        if ( obs )
+        	{
+        	obs->SetComplete( KErrNone );
+        	}
+        }
+    else if ( result == KErrCancel )
+        {
+        CleanUp();
+        // do NOT notify observer
+        }
+    else
+        {
+        CMdSFindEngine* obs = iObserver;
+        if ( obs )
+        	{
+        	obs->FindComplete( result );
+        	}
+        }
+    }
+
+// ------------------------------------------------
+// RunError
+// ------------------------------------------------
+//
+TInt CMdSFindSequence::RunError( TInt aError )
+    {
+    // Cleanup if RunL() leaves
+    CMdSFindEngine* obs = iObserver;
+    CleanUp();
+    obs->FindComplete( aError );
+    return KErrNone;
+    }
+
+// ------------------------------------------------
+// DoCancel
+// ------------------------------------------------
+//
+void CMdSFindSequence::DoCancel()
+    {
+    if ( !iFindOperation )
+        {
+        // already finished
+        CleanUp();
+        return;
+        }
+    TInt state = iFindOperation->State();
+    if ( state == CMdSSqlFindOperation::EStateIdle )
+        {
+        // loop is idle - safe to clean up.
+        CleanUp();
+        }
+    else if ( state == CMdSSqlFindOperation::EStateRunning )
+        {
+        // interrupt loop.
+        iFindOperation->Cancel();
+        }
+    else if ( state == CMdSSqlFindOperation::EStateDead )
+        {
+        // loop is already ending.
+        }
+    return;
+    }
+
+// ------------------------------------------------
+// CreateOperationL
+// ------------------------------------------------
+//
+CMdSSqlFindOperation* CMdSFindSequence::CreateOperationL(
+		CMdCSerializationBuffer& aSerializedCriteria )
+    {
+    CMdSSqlFindOperation* operation = CreateOperationLC( aSerializedCriteria );
+    CleanupStack::Pop( operation );
+    return operation;
+    }
+
+// ------------------------------------------------
+// CreateOperationLC
+// ------------------------------------------------
+//
+CMdSSqlFindOperation* CMdSFindSequence::CreateOperationLC(
+    CMdCSerializationBuffer& aSerializedCriteria )
+    {
+    CMdSSqlFindOperation* operation = CMdSSqlFindOperation::NewLC( *this, iNotifyCount );
+
+	CMdSFindSqlClause& findSqlClause = operation->FindCriteria();
+
+	if( aSerializedCriteria.Buffer().Ptr() && aSerializedCriteria.Buffer().Length() != 0 )
+		{		
+   		findSqlClause.CreateL( aSerializedCriteria, iUserLevel );
+
+		operation->SetLimit( findSqlClause.Limit() );
+
+   		__LOGQUERY_16( _L("Execute query:"), operation->FindCriteria().AsTextL(), operation->FindCriteria().Variables() );
+		}
+	else
+		{
+		User::Leave( KErrBadDescriptor );
+		}
+
+    return operation;
+    }
+
+struct TObjectHitCount
+	{
+	TInt iCount;
+	TUint32 iObjectOffset;
+	};
+
+static TInt SortValues(const TObjectHitCount& aFirst, const TObjectHitCount& aSecond)
+	{
+	TInt result = aSecond.iCount - aFirst.iCount;
+	if (result == 0)
+		{
+		result = aFirst.iObjectOffset - aSecond.iObjectOffset;
+		}
+	return result;
+	}
+
+void CMdSFindSequence::GetFreeTextForObjectL( CDesCArray& aResultWordBuffer,
+		TDefId aNamespaceDefId, TItemId aObjectId )
+	{
+	_LIT( KMdSFindSeqWords, "SELECT Word FROM TextSearch%u AS ts, TextSearchDictionary%u AS tsd ON tsd.WordId = ts.WordId WHERE ObjectId = ? ORDER BY Position ASC;" );
+
+	CMdsClauseBuffer* buffer = CMdsClauseBuffer::NewLC( KMdSFindSeqWords.iTypeLength + 20 ); // two int
+	buffer->BufferL().Format( KMdSFindSeqWords, aNamespaceDefId, aNamespaceDefId );
+	
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	
+	RRowData data;
+    CleanupClosePushL( data );
+	data.AppendL( TColumn( aObjectId ) );
+	RMdsStatement query;
+    CleanupClosePushL( query );
+	connection.ExecuteQueryL( buffer->ConstBufferL(), query, data );
+	TPtrC16 word;
+	data.Column(0).Set( word );
+	while (connection.NextRowL(query, data))
+		{
+		data.Column(0).Get( word );
+		aResultWordBuffer.AppendL( word );
+		data.Free();
+		}
+
+	CleanupStack::PopAndDestroy( 3, buffer ); // query, data, buffer
+	}
+
+// ------------------------------------------------
+// PostProcessL
+// ------------------------------------------------
+//
+void CMdSFindSequence::PostProcessL( CMdCSerializationBuffer& aSerializedResultBuffer )
+    {
+#ifdef _DEBUG    
+	_LIT( KFindFunctionName, "CMdSFindSequence::PostProcessL" );
+#endif
+
+    // process only on items result
+    if (!iLastResultModeItems)
+    	{
+    	return;
+    	}
+    
+    if(iFindOperation && iFindOperation->FindCriteria().IncludesFreetexts() == EFalse )
+   		{
+    	return;
+    	}
+    
+    if (!iFindOperation)
+        {
+        return;
+        }
+    
+    RPointerArray<HBufC>& searchFreeText = iFindOperation->QueryFreeText();
+    // to through every object and check freetext
+    aSerializedResultBuffer.PositionL( KNoOffset );
+    const TMdCItems& items = TMdCItems::GetFromBufferL( aSerializedResultBuffer );
+    const TBool needToSort = searchFreeText.Count() != 0 
+    		&& items.iObjects.iPtr.iCount > 1;
+
+    RArray<TObjectHitCount> hitCountArray;
+    CleanupClosePushL( hitCountArray );
+
+    TObjectHitCount hitCount;
+    for( TUint32 i = 0; i < items.iObjects.iPtr.iCount; ++i )
+    	{
+    	aSerializedResultBuffer.PositionL( items.iObjects.iPtr.iOffset 
+    			+ i * sizeof(TMdCObject) );
+    	const TMdCObject& object = TMdCObject::GetFromBufferL( aSerializedResultBuffer );
+    	// check all objects
+
+		// jump to freetext
+		if ( object.iFreeTexts.iPtr.iCount == 0 )
+			{
+			continue;
+			}
+
+		CDesC16ArrayFlat* resultWordBuffer = new(ELeave) CDesC16ArrayFlat( object.iFreeTexts.iPtr.iCount );
+		CleanupStack::PushL( resultWordBuffer );
+		// get freetext for object
+		GetFreeTextForObjectL( *resultWordBuffer, items.iNamespaceDefId, object.iId );
+		__ASSERT_DEBUG( object.iFreeTexts.iPtr.iCount == resultWordBuffer->Count(), User::Panic( KFindFunctionName, KErrCorrupt) );
+
+	    if (needToSort)
+	    	{
+ 		   	hitCount.iObjectOffset = items.iObjects.iPtr.iOffset + i * sizeof(TMdCObject);
+			hitCount.iCount = GetFreeTextHitCountL( *resultWordBuffer, searchFreeText );
+    		hitCountArray.AppendL( hitCount );
+	    	}
+		
+		aSerializedResultBuffer.PositionL( object.iFreeTexts.iPtr.iOffset );
+		for ( TUint32 f = 0; f < object.iFreeTexts.iPtr.iCount; ++f )
+			{
+			// insert freeText here
+			TPtrC16 word = (*resultWordBuffer)[f];
+			aSerializedResultBuffer.InsertL( word );
+			}
+		CleanupStack::PopAndDestroy( resultWordBuffer );
+		}
+
+    if ( needToSort && hitCountArray.Count() > 1 )
+    	{
+		hitCountArray.Sort( TLinearOrder<TObjectHitCount>( SortValues ) );
+
+		RArray<TMdCObject> objectArray;
+		CleanupClosePushL( objectArray );
+		objectArray.Reserve( items.iObjects.iPtr.iCount );
+		// store objects in array in correct order
+		for( TInt i = 0; i < items.iObjects.iPtr.iCount; ++i )
+			{
+			aSerializedResultBuffer.PositionL( hitCountArray[i].iObjectOffset );
+			const TMdCObject& object = TMdCObject::GetFromBufferL( aSerializedResultBuffer );
+			objectArray.AppendL( object );
+			}
+		// set them back in serialized buffer
+		aSerializedResultBuffer.PositionL( items.iObjects.iPtr.iOffset );
+		for (TInt i = 0; i < items.iObjects.iPtr.iCount; ++i)
+			{
+			objectArray[i].SerializeL( aSerializedResultBuffer );
+			}
+		CleanupStack::PopAndDestroy( &objectArray );
+    	}
+
+	CleanupStack::PopAndDestroy( &hitCountArray );
+    }
+
+// ------------------------------------------------
+// CleanUp
+// ------------------------------------------------
+//
+void CMdSFindSequence::CleanUp()
+    {
+    // clean up rubbish
+	if( iFindOperation )
+		{
+	   	delete iFindOperation;
+		iFindOperation = NULL;
+		}
+
+    iObserver = NULL;
+
+	if( iFindResults )
+		{
+		delete iFindResults;
+		iFindResults = NULL;
+		}
+    }
+
+// ------------------------------------------------
+// IsCleaned
+// ------------------------------------------------
+//
+TBool CMdSFindSequence::IsComplete() const
+	{
+	// not failed or query still running
+	if( //iObserver || 
+		( iFindOperation && iFindOperation->State() != CMdSSqlFindOperation::EStateDead ) )
+		{
+		return EFalse;
+		}
+		
+	return ETrue;
+	}
+    
+// ------------------------------------------------
+// IsComplete
+// ------------------------------------------------
+//
+TBool CMdSFindSequence::IsQueryComplete() const
+	{
+	if ( iFindOperation )
+		{
+		return ( iFindOperation->State() == CMdSSqlFindOperation::EStateDead );
+		}
+	else
+		{
+		return ETrue;
+		}
+	}
+
+const CMdsSchema& CMdSFindSequence::Schema() const
+	{
+	return iSchema;
+	}
+
+CMdSServer& CMdSFindSequence::Server() const
+	{
+	return iServer;
+	}
+
+// ------------------------------------------------
+// GetFreeTextHitCountL
+// ------------------------------------------------
+//
+TUint32 CMdSFindSequence::GetFreeTextHitCountL(
+		const CDesCArray& aObjectFreeText, 
+		const RPointerArray<HBufC>& aSearchFreeText)
+	{
+	TUint32 hitCount = 0;
+
+	const TInt objectFreeTextCount = aObjectFreeText.Count();
+
+	for(TInt i = 0; i < objectFreeTextCount; ++i)
+		{
+		TInt length = aObjectFreeText[i].Length();
+		const TDesC& objectText = aObjectFreeText[i];
+		const TInt32 objectTextLength = objectText.Length();
+		const TInt searchFreeTextCount = aSearchFreeText.Count();
+
+    	for( TInt j = 0; j < searchFreeTextCount; ++j )
+	    	{
+			const TDesC& searchText = *aSearchFreeText[j];
+			const TInt32 searchTextLength = searchText.Length();
+
+			if (searchTextLength > objectTextLength)
+				{
+				continue;
+				}
+			TInt32 searchStart = 0;
+			while(objectTextLength - searchStart >= searchTextLength)
+				{
+				const TInt retValue = objectText.Mid(searchStart, 
+						objectTextLength - searchStart).FindF(searchText);
+
+				if(retValue != KErrNotFound)
+					{
+					searchStart += retValue+searchTextLength;
+					hitCount++;
+					}
+				else
+					{
+					break;
+					}
+				}
+	    	}
+    	}
+    return hitCount;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsfindsqlclause.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,2915 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class constructs SQL search clauses for MdS.*
+*/
+
+// INCLUDE FILES
+#include "mdsfindsqlclause.h"
+#include "mdsfindsqlclausedef.h"
+#include "mdsclausebuffer.h"
+#include "mdcserializationbuffer.h"
+#include "mdsquerycriteriadeserialization.h"
+#include "mdsobjectdef.h"
+#include "mderange.h"
+#include "mdsschema.h"
+#include "mdsnamespacedef.h"
+#include "mdspropertydef.h"
+#include "mdcquery.h"
+#include "mdeinternalerror.h"
+
+const TInt KQueryBufInitialSize = 512;
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CMdSFindSqlClause* CMdSFindSqlClause::NewL(CMdsSchema& aSchema)
+    {
+    CMdSFindSqlClause* self = NewLC(aSchema);
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+CMdSFindSqlClause* CMdSFindSqlClause::NewLC(CMdsSchema& aSchema)
+    {
+    CMdSFindSqlClause* self = new ( ELeave ) CMdSFindSqlClause(aSchema);
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// ~CMdSSqlClause
+// ---------------------------------------------------------------------------
+//
+CMdSFindSqlClause::~CMdSFindSqlClause()
+    {
+    delete iQueryBuf;
+
+    iResultRow.Close();
+    iVariables.Close();
+
+    // doesn't own property definitions
+	iPropertyFilters.Close();
+	
+	iFreeText.ResetAndDestroy();
+	iFreeText.Close();
+	
+	if( iSourceObjectDefs )
+		{
+		iSourceObjectDefs->Close();
+
+		delete iSourceObjectDefs;
+		}
+    }
+
+// ---------------------------------------------------------------------------
+// CMdSSqlClause
+// ---------------------------------------------------------------------------
+//
+CMdSFindSqlClause::CMdSFindSqlClause(CMdsSchema& aSchema) : 
+    iVariables(), iQueryBuf( NULL ), iSchema( aSchema ), 
+    iSearchCriteria( NULL ), iSerializedBuffer( NULL ), 
+    iUserLevel( EUserLevelNone ), iNamespaceDef( NULL ), iObjectDef( NULL ), 
+    iSourceObjectDef ( NULL ), iSourceObjectDefs( NULL ), 
+    iAppendToResultRow( ETrue ), iIncludeFreetexts( ETrue ), 
+    iIncludeNotPresent( EFalse ), iNoObjectLocking( ETrue ), iPlaceholdersOnly( EFalse )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::ConstructL()
+    {
+    // Construct empty buffer for sql query
+    iQueryBuf = CMdsClauseBuffer::NewL( KQueryBufInitialSize );
+    iQueryBuf->AppendL( KEmpty );
+    }
+
+// ---------------------------------------------------------------------------
+// AsText           Returns sql clause
+// ---------------------------------------------------------------------------
+//
+const TDesC& CMdSFindSqlClause::AsTextL() const
+    {
+    return iQueryBuf->ConstBufferL();
+    }
+
+// ---------------------------------------------------------------------------
+// Variables        Query variables
+// ---------------------------------------------------------------------------
+//
+RRowData& CMdSFindSqlClause::Variables()
+    {
+    return iVariables;
+    }
+
+// ---------------------------------------------------------------------------
+// Variables        Query result row
+// ---------------------------------------------------------------------------
+//
+RRowData& CMdSFindSqlClause::ResultRow()
+    {
+    return iResultRow;
+    }
+
+// ---------------------------------------------------------------------------
+// Limit        Query row limit
+// ---------------------------------------------------------------------------
+//
+TUint32 CMdSFindSqlClause::Limit()
+	{
+	return iSearchCriteria->iLimit;
+	}
+	
+TBool CMdSFindSqlClause::IncludesFreetexts()
+	{
+	return iIncludeFreetexts;
+	}
+
+TQueryType CMdSFindSqlClause::QueryType()
+	{
+	return (TQueryType)iSearchCriteria->iQueryType;
+	}
+
+TQueryResultMode CMdSFindSqlClause::ResultMode()
+	{
+	return (TQueryResultMode)iSearchCriteria->iQueryResultType;
+	}
+
+RPointerArray<HBufC>& CMdSFindSqlClause::QueryFreeText()
+	{
+	return iFreeText;
+	}
+
+TBool CMdSFindSqlClause::NoObjectLocking()
+	{
+	return iNoObjectLocking;
+	}
+
+// ---------------------------------------------------------------------------
+// ObjectDef        Query object definition
+// ---------------------------------------------------------------------------
+//
+CMdsObjectDef* CMdSFindSqlClause::ObjectDef()
+	{
+	return iObjectDef;
+	}
+
+RPointerArray<CMdsPropertyDef>& CMdSFindSqlClause::PropertyFilters()
+	{
+	return iPropertyFilters;
+	}
+
+// ---------------------------------------------------------------------------
+// NamespaceDef        Query namespace definition
+// ---------------------------------------------------------------------------
+//
+CMdsNamespaceDef* CMdSFindSqlClause::NamespaceDef()
+	{
+	return iNamespaceDef;
+	}
+
+// ---------------------------------------------------------------------------
+// CreateL          Creates whole sql clause
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::CreateL( 
+	CMdCSerializationBuffer& aSerializedCriteria, 
+	TUserLevel aUserLevel )
+    {
+    iUserLevel = aUserLevel;
+
+    iSerializedBuffer = &aSerializedCriteria;
+
+    iSearchCriteria = CONST_CAST( TMdCSearchCriteria*, 
+    		&TMdCSearchCriteria::GetFromBufferL( aSerializedCriteria ) );
+
+	// can freetexts drop from results
+	if( ( iSearchCriteria->iOptimizationFlags & EContainsFreetextCondition ) == 0 )
+		{
+		iIncludeFreetexts = EFalse;
+		}
+
+	if( iSearchCriteria->iOptimizationFlags & EContainsNotPresentCondition )
+		{
+		iIncludeNotPresent = ETrue;
+		}
+
+	if( iSearchCriteria->iOptimizationFlags & EContainsObjectLocking )
+		{
+		iNoObjectLocking = EFalse;
+		}
+	
+	if( iSearchCriteria->iOptimizationFlags & EContainsPlaceholdersOnly )
+        {
+        iPlaceholdersOnly = ETrue;
+        }
+	
+
+	// get namespace def from new schema definition
+	iNamespaceDef = const_cast<CMdsNamespaceDef*>(iSchema.GetNamespaceByIdL( 
+			iSearchCriteria->iNamespaceDefId ));
+
+	if ( iNamespaceDef )
+		{
+		iNamespaceIdDes.Num( iNamespaceDef->GetId() );
+		}
+	else
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+
+	iObjectDef = NULL;
+
+	if( iSearchCriteria->iObjectDefId != KNoDefId )
+		{
+		// get object def from new schema definition
+		iObjectDef = CONST_CAST( CMdsObjectDef*, 
+				iNamespaceDef->GetObjectByIdL( iSearchCriteria->iObjectDefId ) );
+
+		if ( !iObjectDef )
+			{
+			User::Leave( KErrMdEUnknownObjectDef );
+			}
+		}
+
+	iSourceObjectDef = NULL;
+	iSourceObjectDefs = NULL;
+
+	if ( iSearchCriteria->iObjectDefIds.iPtr.iCount > 0 )
+		{
+		iSourceObjectDefs = new (ELeave) RArray<TDefId>( 
+				iSearchCriteria->iObjectDefIds.iPtr.iCount );
+		iSourceObjectDefs->ReserveL( iSearchCriteria->iObjectDefIds.iPtr.iCount );
+
+		iSerializedBuffer->PositionL( iSearchCriteria->iObjectDefIds.iPtr.iOffset );
+
+		for( TUint32 i = 0; i < iSearchCriteria->iObjectDefIds.iPtr.iCount; i++ )
+			{
+			TDefId objectDefId;
+			iSerializedBuffer->ReceiveL( objectDefId );			
+			iSourceObjectDefs->Append( objectDefId );
+			}
+		}
+	else
+		{
+		iSourceObjectDef = iObjectDef;
+		}
+
+	if( !iSourceObjectDefs )
+		{
+		// Construct beginning of the select clause 
+		// Format: SELECT [column list/count(*)] FROM table name
+		AppendSelectStatementL();
+
+		AppendWhereStatementL();
+
+		// if query type is object query and freetext are included
+		// "GROUP BY BO.ObjectId"
+		if( iIncludeFreetexts )
+			{
+		    AppendGroupByL();
+			}
+		}
+	else
+		{
+		const TInt sourceObjectDefsCount = iSourceObjectDefs->Count();
+		for( TInt i = 0; i < sourceObjectDefsCount; i++ )
+			{
+			const TDefId sourceObjectDefId = (*iSourceObjectDefs)[i];
+			iSourceObjectDef = CONST_CAST( CMdsObjectDef*, 
+					iNamespaceDef->GetObjectByIdL( sourceObjectDefId ) );
+
+			if( i > 0 )
+				{
+				iAppendToResultRow = EFalse;
+				iQueryBuf->AppendL( KUnionAll );
+				}
+
+			// Construct beginning of the select clause 
+			// Format: SELECT [column list/count(*)] FROM table name
+			AppendSelectStatementL();
+			
+			AppendWhereStatementL();
+			    
+			// if query type is object query and freetext are included
+			// "GROUP BY BO.ObjectId"
+			if( iIncludeFreetexts )
+				{
+			    AppendGroupByL();
+				}
+			}
+		}
+
+    // ORDER BY clause (if such exists)
+    AppendOrderByL();
+
+    // LIMIT and OFFSET clauses (if such exists)
+    AppendLimitAndOffsetL();
+
+    // SQL clause must end to semicolon
+    iQueryBuf->AppendL( KSemicolon );
+    }
+
+// ---------------------------------------------------------------------------
+// AppendPropertyFiltersL       Appends the property filters
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendPropertyFiltersL( TBool aDistinct )
+	{
+	if( iSearchCriteria->iPropertyFilters.iPtr.iCount > 0 )
+		{
+		iSerializedBuffer->PositionL( 
+				iSearchCriteria->iPropertyFilters.iPtr.iOffset );
+
+		for ( TUint32 i = 0; i < iSearchCriteria->iPropertyFilters.iPtr.iCount; ++i )
+			{
+			TDefId id;
+			iSerializedBuffer->ReceiveL( id );
+
+			if ( !aDistinct )
+				{
+				iQueryBuf->AppendL( KComma );
+				}
+
+			AppendColumnByPropertyDefIdL( id, KNoDefId, ETrue );
+			}
+
+		iQueryBuf->AppendL( KSpace );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// AppendSelectStatementL       Appends the SELECT statements
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendSelectStatementL()
+    {
+    switch( iSearchCriteria->iQueryType )
+    	{
+    	case EQueryTypeObject:
+    		AppendSelectForObjectL();
+    		AppendFromForObjectL();
+	    	break;
+	    case EQueryTypeRelation:
+	    	AppendSelectForRelationL();
+	    	AppendFromForRelationL();
+	    	break;
+        case EQueryTypeEvent:
+	    	AppendSelectForEventL();
+  	 		AppendFromForEventL();
+	    	break;
+	    default:
+#ifdef _DEBUG
+            User::Panic( _L("MdSFCASS") , KErrMdEUnknownQueryType );
+#endif
+	    	User::Leave( KErrMdEUnknownQueryType );
+    	}
+    }
+
+// ---------------------------------------------------------------------------
+// AppendSelectCountStatementL        SELECT statements for count query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendSelectCountStatementL()
+    {
+    // if result rows needs to be grouped return just "1"
+    if( iIncludeFreetexts )
+		{
+		// "SELECT 1 "
+		iQueryBuf->AppendL( KSelect1 );
+		}
+	else
+		{
+		// "SELECT count(*) "
+    	iQueryBuf->AppendL( KSelectCount );
+		}
+
+	// expected result count
+    if( iAppendToResultRow )
+    	{
+    	iResultRow.AppendL( TColumn( EColumnUint32 ) );
+    	}
+    }
+
+// ---------------------------------------------------------------------------
+// AppendSelectDistinctStatementL   SELECT statements for distinct value query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendSelectDistinctStatementL()
+	{
+	// "SELECT DISTINCT "
+	iQueryBuf->AppendL( KSelectDistinct );
+
+	const TUint32 position = iSerializedBuffer->Position();
+
+	// "column name" (from property filter)
+	AppendPropertyFiltersL( ETrue );
+
+	iSerializedBuffer->PositionL( position );
+	}
+
+// ---------------------------------------------------------------------------
+// AppendSelectObjectIdStatementL        SELECT statements for object id query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendSelectObjectIdStatementL()
+	{
+	// "SELECT BO.ObjectId "
+	iQueryBuf->AppendL( KSelectObjectIds );
+
+	// expected result object ID
+	if( iAppendToResultRow )
+		{
+		iResultRow.AppendL( TColumn( EColumnTItemId ) );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// AppendSelectEventAllStatementL        SELECT statements for event query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendSelectAllFromEventStatementL()
+	{
+	// "SELECT * "
+	iQueryBuf->AppendL( KSelectAllFrom );
+
+	if( iAppendToResultRow )
+		{
+		// expected result Events 
+	    iResultRow.AppendL( TColumn( EColumnTItemId ) );
+	    iResultRow.AppendL( TColumn( EColumnTItemId ) );
+	    iResultRow.AppendL( TColumn( EColumnTDefId ) );
+	    iResultRow.AppendL( TColumn( EColumnTime ) );
+	    iResultRow.AppendL( TColumn( EColumnDes16 ) );
+	    iResultRow.AppendL( TColumn( EColumnDes16 ) );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// AppendSelectRelationAllStatementL        SELECT statements for Relaltion query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendSelectAllFromRelationStatementL()
+	{
+	// "SELECT * "
+	iQueryBuf->AppendL( KSelectAllFrom );
+
+	if( iAppendToResultRow )
+		{
+		// expected result Relation
+	    iResultRow.AppendL( TColumn( EColumnTItemId ) );
+	    iResultRow.AppendL( TColumn( EColumnUint32 ) );
+	    iResultRow.AppendL( TColumn( EColumnTDefId ) );
+	    iResultRow.AppendL( TColumn( EColumnTItemId ) );
+	    iResultRow.AppendL( TColumn( EColumnTItemId ) );
+	    iResultRow.AppendL( TColumn( EColumnInt32 ) );
+	    iResultRow.AppendL( TColumn( EColumnInt64 ) );
+	    iResultRow.AppendL( TColumn( EColumnInt64 ) );
+	    iResultRow.AppendL( TColumn( EColumnTime ) );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// AppendSelectEventItemStatementL        SELECT statements for event id query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendSelectEventItemStatementL()
+    {
+	// "SELECT Event + NamespaceId.EventId "
+	iQueryBuf->AppendL( KSelectEventIds );
+	iQueryBuf->AppendL( iNamespaceIdDes );
+	iQueryBuf->AppendL( KDotEventId );
+
+	if( iAppendToResultRow )
+		{
+		// expected result event
+	    iResultRow.AppendL( TColumn( EColumnTItemId ) );
+		}
+    }
+
+// ---------------------------------------------------------------------------
+// AppendSelectRealtionItemStatementL        SELECT statements for Realtion id query
+// ---------------------------------------------------------------------------
+//AppendSelectRelationItemStatementL
+void CMdSFindSqlClause::AppendSelectRealtionItemStatementL()
+    {
+	 //"SELECT Relation.EventId "
+	iQueryBuf->AppendL( KSelectRelationIds );
+    iQueryBuf->AppendL( iNamespaceIdDes );
+    iQueryBuf->AppendL( KDotRelationId );
+	
+	if( iAppendToResultRow )
+		{
+		//expected result relation
+		iResultRow.AppendL( TColumn( EColumnTItemId ) );
+		}
+    }
+
+// ---------------------------------------------------------------------------
+// AppendSelectObjectItemStatementL    SELECT statements for object item query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendSelectObjectItemStatementL()
+	{
+	if( iAppendToResultRow )
+		{
+		// add expected fixed "base" object's columns
+		iResultRow.AppendL( TColumn( EColumnTItemId ) ); // object ID
+		iResultRow.AppendL( TColumn( EColumnTDefId ) ); // object definition ID
+		iResultRow.AppendL( TColumn( EColumnUint32 ) ); // flags
+		iResultRow.AppendL( TColumn( EColumnUint32 ) ); // media ID
+		iResultRow.AppendL( TColumn( EColumnUint32 ) ); // UsageCount
+		iResultRow.AppendL( TColumn( EColumnInt64 ) );  // GUID high
+		iResultRow.AppendL( TColumn( EColumnInt64 ) );  // GUID low
+		iResultRow.AppendL( TColumn( EColumnDes16 ) );  // URI
+		}
+
+	if( iSearchCriteria->iPropertyFilters.iPtr.iCount > 0 )
+		{
+		// "SELECT BO...."
+		iQueryBuf->AppendL( KSelectPropertyFilterBegin );
+
+		const TUint32 position = iSerializedBuffer->Position();
+
+		AppendPropertyFiltersL();
+
+		iSerializedBuffer->PositionL( position );
+		}
+	else
+		{
+		// No property filters so get all properties
+		
+		// "SELECT BO.* "
+		iQueryBuf->AppendL( KSelectAllFromBaseObject );
+	
+		const TInt propCount = iObjectDef->GetAllPropertiesCount();
+		TBool addBaseObjectId = EFalse;
+		
+		if( KBaseObjectDefId != iObjectDef->GetId() )
+			{
+			if( !iSourceObjectDefs )
+				{
+				// ",O.* "
+				iQueryBuf->AppendL( KAllFromObject );
+				}
+			else
+				{
+				// ",O.ObjectId"
+				iQueryBuf->AppendL( KComma );
+				iQueryBuf->AppendL( KObjectObjectId );
+
+				// no filters, so add all property names
+				const TInt lookupObjectPropertyCount = 
+					iObjectDef->GetPropertiesCount();
+				
+				for( TInt i = 0; i < lookupObjectPropertyCount; i++)
+					{
+					iQueryBuf->AppendL( KComma );
+					const CMdsPropertyDef* propDef = iObjectDef->GetProperty( i );
+					iQueryBuf->AppendL( propDef->GetName() );
+					}
+				iQueryBuf->AppendL( KSpace );
+				}
+			addBaseObjectId = ETrue;
+			}
+
+		if (propCount > 0)
+			{
+			// add base object properties, object ID and the rest properties
+			for( TUint32 i = 0; i < propCount; i++ )
+				{
+				const CMdsPropertyDef& propDef = iObjectDef->GetPropertyColumnL( i ).iPropertyDef;
+
+				// add column for object ID when object definition is not "base" object
+				if( addBaseObjectId && KBaseObjectBasicValueColumnOffset < propDef.GetId() )
+					{
+					if( iAppendToResultRow )
+						{
+			    	    // add expected column for object ID
+						iResultRow.AppendL( TColumn( EColumnTItemId ) ); // object ID
+						}
+					addBaseObjectId = EFalse;
+					}
+
+				if( iAppendToResultRow )
+					{
+					// add expected columns	from object
+					iResultRow.AppendL( TColumn( propDef.GetSqlType() ) );
+					}
+				}
+				
+			if( addBaseObjectId )
+				{
+				if( iAppendToResultRow )
+					{
+					// add expected column for object ID
+					iResultRow.AppendL( TColumn( EColumnTItemId ) ); // object ID
+					}
+				}
+			}
+		}
+
+	if( iIncludeFreetexts )
+		{
+		// ",count(D.Word),sum(length(D.Word)) "
+		iQueryBuf->AppendL( KSelectFreeTextCountAndTotalLength );
+
+		if( iAppendToResultRow )
+			{
+			iResultRow.AppendL( TColumn( EColumnUint32 ) );
+			iResultRow.AppendL( TColumn( EColumnUint32 ) );
+			}
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// AppendFromForObjectL           FROM statements for object query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendFromForObjectL()
+	{
+	// "FROM BaseObject" + namespace def id + " AS BO "
+	iQueryBuf->AppendL( KFromBaseObject );
+	iQueryBuf->AppendL( iNamespaceIdDes );
+	iQueryBuf->AppendL( KAsBaseObject );
+
+	// if object definitions is BaseObject
+	if( KBaseObjectDefId != iSourceObjectDef->GetId() )
+		{
+		// "," + object def's table + namespace def id + " AS O ON BO.ObjectId=O.ObjectId "
+        iQueryBuf->AppendL( KComma );
+
+		AppendTableByObjectDefIdL( iSourceObjectDef->GetId() );
+
+        iQueryBuf->AppendL( KAsObjectOnEqual );
+		}
+
+	if( iIncludeFreetexts )
+		{
+		// Append free text join
+		// "LEFT JOIN TextSearchDictionary" + namespace def id + " 
+		// AS D ON D.WordId IN(SELECT WordId FROM TextSearch" + 
+		// namespace def id + " WHERE BO.ObjectId=ObjectId) "
+		iQueryBuf->AppendL( KFreeTextLeftJoinBegin );
+		iQueryBuf->AppendL( iNamespaceIdDes );
+		iQueryBuf->AppendL( KFreeTextLeftJoinMiddle );
+		iQueryBuf->AppendL( iNamespaceIdDes );
+		iQueryBuf->AppendL( KFreeTextLeftJoinEnd );
+		}
+	}
+
+
+// ---------------------------------------------------------------------------
+// AppendFromForObjectL           FROM statements for Event query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendFromForEventL()
+    {
+   	iQueryBuf->AppendL( KFromEvent );
+	iQueryBuf->AppendL( iNamespaceIdDes );
+   	iQueryBuf->AppendL( KSpace );
+    }
+
+// ---------------------------------------------------------------------------
+// AppendFromForRelationL           FROM statements for Relation query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendFromForRelationL()
+    {
+   	iQueryBuf->AppendL( KFromRealtions );
+	iQueryBuf->AppendL( iNamespaceIdDes );
+	iQueryBuf->AppendL( KSpace );
+    }
+
+
+// ---------------------------------------------------------------------------
+// AppendWhereStatementL           WHERE statements for query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendWhereStatementL()
+	{
+	// move position to begin of the root condition
+	iSerializedBuffer->PositionL( iSearchCriteria->iRootCondition );
+
+	const TMdCLogicCondition& condition = TMdCLogicCondition::GetFromBufferL( 
+			*iSerializedBuffer );
+
+	if( EConditionTypeLogic == condition.iConditionType )
+		{
+		// if root condition's child count is more than zero add where statement
+		if( condition.iChildConditions.iPtr.iCount > 0 )
+			{
+			// "WHERE("root condition")"
+			iQueryBuf->AppendL( KWhere );
+
+			if( EQueryTypeObject == iSearchCriteria->iQueryType )
+				{
+				// remove "deleted" objects from result
+				iQueryBuf->AppendL( KGetNotFlagAnd );
+				iVariables.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+
+				if( EUserLevelDeviceAccess != iUserLevel )
+					{
+					if( iIncludeNotPresent )
+						{
+						// If client application doesn't have device capability limit to
+						// only non-confidential (confidential flag is not set)
+						// "(NOT Flags&?)AND "
+						iQueryBuf->AppendL( KGetNotFlagAnd );
+						iVariables.AppendL( TColumn( EMdEObjectFlagConfidential ) );
+						}
+					else
+						{
+						// If client application doesn't have device capability limit to
+						// only non-confidential (confidential flag is not set)
+						// and not present objects
+						// "(NOT Flags&?)AND "
+						iQueryBuf->AppendL( KGetNotFlagAnd );
+						iVariables.AppendL( TColumn( EMdEObjectFlagConfidential | EMdEObjectFlagNotPresent ) );
+						}
+					}
+				else
+					{
+					if( !iIncludeNotPresent )
+						{
+						// Drop not present objects
+						// "(NOT Flags&?)AND "
+						iQueryBuf->AppendL( KGetNotFlagAnd );
+						iVariables.AppendL( TColumn( EMdEObjectFlagNotPresent ) );
+						}
+					}
+				}
+
+			if ( EQueryTypeRelation == iSearchCriteria->iQueryType )
+				{
+				// add "(NOT Flags&?)AND " with not present flag
+				iQueryBuf->AppendL( KGetNotFlagAnd );
+				iVariables.AppendL( TColumn( EMdERelationFlagNotPresent ) );
+				// add "(NOT Flags&?)AND " with deleted flag
+				iQueryBuf->AppendL( KGetNotFlagAnd );
+				iVariables.AppendL( TColumn( EMdERelationFlagDeleted ) );
+				}
+
+			iQueryBuf->AppendL( KLeftBracket );
+
+			// move position to begin of the root condition
+			iSerializedBuffer->PositionL( iSearchCriteria->iRootCondition );
+
+			ConditionStatementL();
+
+			iQueryBuf->AppendL( KRightBracket );
+			}
+		else if( EQueryTypeObject == iSearchCriteria->iQueryType )
+			{
+			// remove "deleted" objects from result
+			iQueryBuf->AppendL( KWhereNotFlag );
+			iVariables.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+
+			if( EUserLevelDeviceAccess != iUserLevel )
+				{
+				if( iIncludeNotPresent )
+					{
+					// If client application doesn't have device capability limit to
+					// only non-confidential (confidential flag is not set)
+					// "WHERE(NOT Flags&?)"
+					iQueryBuf->AppendL( KAnd );
+					iQueryBuf->AppendL( KGetNotFlag );
+					iVariables.AppendL( TColumn( EMdEObjectFlagConfidential ) );
+					}
+				else
+					{
+					// If client application doesn't have device capability limit to
+					// only non-confidential (confidential flag is not set)
+					// and not present objects
+					// "WHERE(NOT Flags&?)"
+					iQueryBuf->AppendL( KAnd );
+					iQueryBuf->AppendL( KGetNotFlag );
+					iVariables.AppendL( TColumn( EMdEObjectFlagConfidential | EMdEObjectFlagNotPresent ) );
+					}
+				}
+			else
+				{
+				if( !iIncludeNotPresent )
+					{
+					// Drop not present objects
+					// "WHERE(NOT Flags&?)"
+					iQueryBuf->AppendL( KAnd );
+					iQueryBuf->AppendL( KGetNotFlag );
+					iVariables.AppendL( TColumn( EMdEObjectFlagNotPresent ) );
+					}
+				}
+			}
+		else if ( EQueryTypeRelation == iSearchCriteria->iQueryType )
+			{
+			// add "WHERE(NOT Flags&?)" with not present flag
+			iQueryBuf->AppendL( KWhereNotFlag );
+			iVariables.AppendL( TColumn( EMdERelationFlagNotPresent ) );
+			// add "AND (NOT Flags&?)" with deleted flag
+			iQueryBuf->AppendL( KAnd );
+			iQueryBuf->AppendL( KGetNotFlag );
+			iVariables.AppendL( TColumn( EMdERelationFlagDeleted ) );
+			}
+		}
+	else
+		{
+		User::Leave( KErrMdEUnknownConditionType );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// AppendSelectForObjectGroupL      SELECT statements for object query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendSelectForObjectL()
+    {
+    switch( iSearchCriteria->iQueryResultType )
+	    {
+	    case EQueryResultModeCount:
+	        // Format: SELECT count(*) FROM
+	        AppendSelectCountStatementL();
+	        break;
+	    case EQueryResultModeDistinctValues:
+	        // Format: SELECT "wanted property's column" FROM
+	        AppendSelectDistinctStatementL();
+	        break;
+	    case EQueryResultModeItem:
+	    	AppendSelectObjectItemStatementL();
+	    	break;
+	    case EQueryResultModeId:
+	    	AppendSelectObjectIdStatementL();
+	    	break;
+
+	    default:
+	    	{
+#ifdef _DEBUG
+            User::Panic( _L("MdSFCSeO") , KErrMdEUnknownQueryResultMode );
+#endif
+	    	User::Leave( KErrMdEUnknownQueryResultMode );
+	    	}
+	    }
+    }
+
+// ---------------------------------------------------------------------------
+// AppendSelectForRelationGroupL        SELECT statements for relation query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendSelectForRelationL()
+    {
+    switch( iSearchCriteria->iQueryResultType )
+        {
+	    case EQueryResultModeCount:
+	        // Format: SELECT count(*) FROM
+	        AppendSelectCountStatementL();
+	        break;
+	    case EQueryResultModeItem:
+	    	// Format: SELECT * FROM   //  SELECT * FROM Relation
+	    	AppendSelectAllFromRelationStatementL();
+	    	break;
+	    case EQueryResultModeId:
+	    	// SELECT Relation.RelationId FROM // SELECT 
+	    	AppendSelectRealtionItemStatementL();
+	    	break;
+
+	    default:
+	    	{
+#ifdef _DEBUG
+            User::Panic( _L("MdSFCSeR") , KErrMdEUnknownQueryResultMode );
+#endif
+	    	User::Leave( KErrMdEUnknownQueryResultMode );
+	    	}
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// AppendSelectForEventL()       SELECT statements for event query
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendSelectForEventL()
+    {
+    switch( iSearchCriteria->iQueryResultType )
+        {
+	    case EQueryResultModeCount:
+	        // Format: SELECT count(*) FROM
+	        AppendSelectCountStatementL();
+	        break;
+	    case EQueryResultModeItem:
+	    	// Format: SELECT * FROM   //  SELECT * FROM Event
+	    	AppendSelectAllFromEventStatementL();
+	    	break;
+	    case EQueryResultModeId:
+	    	// SELECT EventDef.EventId FROM // SELECT EventDef.EventDefId FROM Event
+	    	AppendSelectEventItemStatementL();
+	    	break;
+
+	    default:
+	    	{
+#ifdef _DEBUG
+            User::Panic( _L("MdSFCSeE") , KErrMdEUnknownQueryResultMode );
+#endif	    	
+	    	User::Leave( KErrMdEUnknownQueryResultMode );
+	    	}
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// ConditionStatementL       Recursive parsing of condition statements
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::ConditionStatementL(TBool aNegated, TAppendIn aAppendIdIn)
+    {
+    const TMdCCondition& condition = TMdCCondition::GetFromBufferL( *iSerializedBuffer );
+
+    TBool negated = condition.iNegated;
+
+	if( aNegated )
+		{
+		negated = !negated;
+		}
+
+	const TConditionType conditionType = (TConditionType)condition.iConditionType;
+
+	if( aAppendIdIn != EAppendInFalse )
+		{
+		if ( EConditionTypeLogic != conditionType )
+			{
+			if ( aAppendIdIn == EAppendInTrue )
+				{
+				AppendIdInL();
+				}
+			else if (aAppendIdIn == EAppendInRelationLeft)
+				{
+				iQueryBuf->AppendL( KRelationLeftObjectIdIn );
+				}
+			else if (aAppendIdIn == EAppendInRelationRight)
+				{
+				iQueryBuf->AppendL( KRelationRightObjectIdIn );
+				}
+			else
+				{
+#ifdef _DEBUG
+				User::Panic( _L("MdSFCCo1") , KErrCorrupt );
+#endif
+				User::Leave( KErrCorrupt );
+				}
+			}
+
+		// Add recursive child criteria surrounded by "("child")".
+		iQueryBuf->AppendL( KLeftBracket );
+		}
+
+	switch( conditionType )
+		{
+		case EConditionTypeLogic:
+			AppendLogicConditionL( negated, aAppendIdIn );
+			break;
+		case EConditionTypeObject:
+			AppendObjectConditionL( negated );
+			break;
+		case EConditionTypeProperty:
+			AppendPropertyConditionL( negated );
+			break;
+		case EConditionTypePropertyIntRange:
+		case EConditionTypePropertyInt64Range:
+		case EConditionTypePropertyUintRange:
+		case EConditionTypePropertyRealRange:
+		case EConditionTypePropertyTimeRange:
+			AppendPropertyRangeConditionL( negated );
+			break;
+		case EConditionTypePropertyText:
+			AppendPropertyTextConditionL( negated );
+			break;
+		case EConditionTypePropertyBool:
+			AppendPropertyBoolConditionL( negated );
+			break;
+		case EConditionTypeRelation:
+			AppendRelationConditionL( negated );
+			break;
+		case EConditionTypeEvent:
+			AppendEventConditionL( negated );
+			break;
+		default: // Unknown condition type
+#ifdef _DEBUG
+            User::Panic( _L("MdSFCCo2") , KErrMdEUnknownConditionType );
+#endif
+			User::Leave( KErrMdEUnknownConditionType );
+		}
+
+	if( aAppendIdIn )
+		{		
+		iQueryBuf->AppendL( KRightBracket );
+		}
+    }
+
+// ---------------------------------------------------------------------------
+// AppendObjectId        Help method for appending object ID clause.
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendObjectIdL()
+	{
+	if( KBaseObjectDefId == iObjectDef->GetId() )
+		{
+		// "BO.ObjectId"
+		iQueryBuf->AppendL( KBaseObjectObjectId );
+		}
+	else
+		{
+		// "O.ObjectId"
+		iQueryBuf->AppendL( KObjectObjectId );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// AppendIdIn                    			Help method for appending object, 
+//											event or relation ID IN clause.
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendIdInL()
+	{
+	switch( iSearchCriteria->iQueryType )
+		{
+		case EQueryTypeObject:
+			// "BO.ObjectId" or "O.ObjectId"
+			AppendObjectIdL();
+			break;
+		case EQueryTypeRelation:
+			iQueryBuf->AppendL( KRelationId );
+			break;
+		case EQueryTypeEvent:
+			iQueryBuf->AppendL( KEventId );
+			break;
+		default:
+#ifdef _DEBUG
+            User::Panic( _L("MdSFCAII") , KErrMdEUnknownQueryType );
+#endif
+			User::Leave( KErrMdEUnknownQueryType );
+		}
+
+	// " IN"
+	iQueryBuf->AppendL( KIn );
+	}
+
+
+// ---------------------------------------------------------------------------
+// AppendLogicConditionL        Help method for appending logic condition.
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendLogicConditionL(TBool aNegated, TAppendIn aAppendIdIn)
+	{
+	const TMdCLogicCondition& condition = TMdCLogicCondition::GetFromBufferL( 
+			*iSerializedBuffer );
+
+    // Add recursive all children.
+    for( TUint32 i = 0; i < condition.iChildConditions.iPtr.iCount; i++)
+		{
+		// get offset and move position to begin of child condition
+		iSerializedBuffer->PositionL( condition.iChildConditions.iPtr.iOffset + 
+				CMdCSerializationBuffer::KRequiredSizeForTUint32 * i );
+
+		TUint32 childOffset;
+		iSerializedBuffer->ReceiveL( childOffset );
+
+		iSerializedBuffer->PositionL( childOffset );
+
+		// If not first add operator
+		if( i > 0 )
+			{
+			switch( condition.iOperator )
+				{
+				case ELogicConditionOperatorAnd:
+					iQueryBuf->AppendL( KAnd );
+					break;
+				case ELogicConditionOperatorOr:
+					iQueryBuf->AppendL( KOr );
+					break;
+				default:
+#ifdef _DEBUG
+					User::Panic( _L("MdSFCALC") , KErrMdEUnknownConditionCompareMethod );
+#endif
+					User::Leave( KErrMdEUnknownConditionCompareMethod ); 
+				}
+			}
+
+		ConditionStatementL( aNegated, aAppendIdIn );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// AppendObjectConditionL        Help method for appending object condition.
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendObjectConditionL(TBool aNegated)
+	{
+	const TMdCObjectCondition& condition = TMdCObjectCondition::GetFromBufferL( 
+			*iSerializedBuffer );
+
+	// "SELECT ObjectId FROM BaseObject"namespace def ID" WHERE(...)"
+	iQueryBuf->AppendL( KSelectObjectIdFromBaseObject );
+	iQueryBuf->AppendL( iNamespaceIdDes );
+	iQueryBuf->AppendL( KSpace );
+	iQueryBuf->AppendL( KWhere );
+
+	iQueryBuf->AppendL( KLeftBracket );
+
+	// remove "deleted" objects from result
+	iQueryBuf->AppendL( KGetNotFlagAnd );
+	iVariables.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+	
+   if( iPlaceholdersOnly )
+        {
+        // Drop non-placeholder  objects
+        // "(Flags&?)AND "
+        iQueryBuf->AppendL( KGetFlagAnd );
+        iVariables.AppendL( TColumn( EMdEObjectFlagPlaceholder ) );
+        }
+
+	if( EUserLevelDeviceAccess == iUserLevel )
+		{
+		switch( condition.iConfidentialityLevel )
+			{
+			// Only non-confidential (confidential flag is not set)
+			// "(NOT Flags&?)AND "
+			case EObjectConditionLevelNormal:
+				iQueryBuf->AppendL( KGetNotFlagAnd );
+				iVariables.AppendL( TColumn( EMdEObjectFlagConfidential ) );
+				break;
+			// Only confidential (confidential flag is set)
+			// "(Flags&?)AND "
+			case EObjectConditionLevelConfidential:
+				iQueryBuf->AppendL( KGetFlagAnd );
+				iVariables.AppendL( TColumn( EMdEObjectFlagConfidential ) );
+				break;
+
+			case EObjectConditionLevelIgnoreConfidentiality:
+				// no implementation needed
+				break;
+
+		    default:
+		    	{
+#ifdef _DEBUG
+				User::Panic( _L("MdSFCAO1") , KErrMdEUnknownConfidentialityLevel );
+#endif
+		    	User::Leave( KErrMdEUnknownConfidentialityLevel );
+		    	}
+			}
+		}
+	else
+		{
+		// If client application doesn't have device capability limit to
+		// only non-confidential (confidential flag is not set)
+		// "(NOT Flags&?)AND "
+		iQueryBuf->AppendL( KGetNotFlagAnd );
+		iVariables.AppendL( TColumn( EMdEObjectFlagConfidential ) );
+		}
+
+	if( ( condition.iFlags & EMdEObjectFlagNotPresent ) == EFalse )
+		{
+		// Not present flag is not set
+		// "NOT(Flags&?)AND "
+		iQueryBuf->AppendL( KGetNotFlagAnd );
+		iVariables.AppendL( TColumn( EMdEObjectFlagNotPresent ) );
+		}
+
+	if( ( condition.iFlags & EMdEObjectFlagPlaceholder ) )
+		{
+		// Placeholder flag is not set
+		// "NOT(Flags&?)AND "
+		iQueryBuf->AppendL( KGetNotFlagAnd );
+		iVariables.AppendL( TColumn( EMdEObjectFlagPlaceholder ) );
+		}
+
+	if( aNegated )
+		{
+		// "NOT "
+		iQueryBuf->AppendL( KNotWithSpace );
+		}
+
+	// move position to begin of compare condition
+	iSerializedBuffer->PositionL( condition.iCondition );
+
+	switch( condition.iCompareMethod )
+		{
+		case EObjectConditionCompareNone:
+			break;
+		case EObjectConditionCompareId:
+			{
+			TItemId objectId;
+			iSerializedBuffer->ReceiveL( objectId );
+
+			iQueryBuf->AppendL( KObjectIdEqual );
+			iVariables.AppendL( TColumn( objectId ) );
+			}
+			break;
+		case EObjectConditionCompareIds:
+			{
+			TInt32 objectIdCount;
+			iSerializedBuffer->ReceiveL( objectIdCount );
+
+			if( objectIdCount == 1 )
+				{
+				TItemId objectId;
+				iSerializedBuffer->ReceiveL( objectId );
+
+				iQueryBuf->AppendL( KObjectIdEqual );
+				iVariables.AppendL( TColumn( objectId ) );
+				}
+			else if( objectIdCount > 1 )
+				{
+				iQueryBuf->AppendL( KObjectIdIn );
+				iQueryBuf->AppendL( KLeftBracket );
+
+				TItemId objectId;
+				iSerializedBuffer->ReceiveL( objectId );
+
+				iQueryBuf->AppendL( KVariable );
+				iVariables.AppendL( TColumn( objectId ) );
+
+				for( TInt32 i = 1; i < objectIdCount; i++ )
+					{
+					iSerializedBuffer->ReceiveL( objectId );
+
+					iQueryBuf->AppendL( KCommaVariable );
+					iVariables.AppendL( TColumn( objectId ) );
+					}
+
+				iQueryBuf->AppendL( KRightBracket );
+				}
+			}
+			break;
+		case EObjectConditionCompareGuid:
+			{
+			TInt64 guidHigh;
+			iSerializedBuffer->ReceiveL( guidHigh );			
+			TInt64 guidLow;
+			iSerializedBuffer->ReceiveL( guidLow );			
+
+			iQueryBuf->AppendL( KObjectGuidEqual );
+			iVariables.AppendL( TColumn( guidHigh ) );
+			iVariables.AppendL( TColumn( guidLow ) );
+			}
+			break;
+		case EObjectConditionCompareObjectDef:
+			{
+			TDefId objectDefId;
+			iSerializedBuffer->ReceiveL( objectDefId );
+
+			iQueryBuf->AppendL( KObjectDefIdEqual );
+			iVariables.AppendL( TColumn( objectDefId ) );
+			}
+			break;
+		case EObjectConditionCompareUsageCount:
+			{
+			iQueryBuf->AppendL( KObjectUsageCount );
+			AppendRangeL( EUint32RangeValue );
+			}
+			break;
+		case EObjectConditionCompareUri:
+			{
+			TPtrC16 uriPtr = iSerializedBuffer->ReceivePtr16L();
+
+			iQueryBuf->AppendL( KObjectUriEqual );
+			iVariables.AppendL( TColumn( uriPtr ) );
+			}
+			break;
+		case EObjectConditionCompareUriBeginsWith:
+			{
+			TPtrC16 uriPtr = iSerializedBuffer->ReceivePtr16L();
+
+			HBufC16* pattern = HBufC16::NewLC( uriPtr.Length() + 1 );  // prepare for uri%
+
+	        TPtr16 modPattern = pattern->Des();
+
+			// add wildcard after URI "uri%"
+			modPattern.Append( uriPtr );
+			modPattern.Append( KWildcard );
+
+			iVariables.AppendL( TColumn( pattern ) );
+
+			CleanupStack::Pop( pattern );
+
+			iQueryBuf->AppendL( KObjectUriBeginsWith );			
+			}
+			break;
+		case EObjectConditionCompareFreeText:
+			{
+			TPtrC16 freetextPtr = iSerializedBuffer->ReceivePtr16L();
+
+			HBufC* freetext = freetextPtr.AllocLC();
+			iFreeText.AppendL( freetext );
+			CleanupStack::Pop( freetext );
+
+			iQueryBuf->AppendL( KObjectFreeTextSearchStart );
+			iQueryBuf->AppendL( iNamespaceIdDes );
+			iQueryBuf->AppendL( KObjectFreeTextSearchWhere );
+			iQueryBuf->AppendL( iNamespaceIdDes );
+			iQueryBuf->AppendL( KObjectFreeTextSearchDictionaryWhere );
+			iQueryBuf->AppendL( KEqual );
+			iQueryBuf->AppendL( KObjectFreeTextSearchEnd );
+			iVariables.AppendL( TColumn( freetextPtr ) );
+			}
+			break;
+		case EObjectConditionCompareFreeTextContains:
+			{
+			TPtrC16 freetextPtr = iSerializedBuffer->ReceivePtr16L();
+
+			HBufC* freetext = freetextPtr.AllocLC();
+			iFreeText.AppendL( freetext );
+			CleanupStack::Pop( freetext );
+
+			iQueryBuf->AppendL( KObjectFreeTextSearchStart );
+			iQueryBuf->AppendL( iNamespaceIdDes );
+			iQueryBuf->AppendL( KObjectFreeTextSearchWhere );
+			iQueryBuf->AppendL( iNamespaceIdDes );
+			iQueryBuf->AppendL( KObjectFreeTextSearchDictionaryWhere );
+			
+			HBufC16* pattern = HBufC16::NewLC( freetextPtr.Length() + 2 );  // prepare for %freetext%
+
+	        TPtr16 modPattern = pattern->Des();
+
+			// add wildcard before and after freetext "%freetext%"
+			modPattern.Append( KWildcard );
+			modPattern.Append( freetextPtr );
+			modPattern.Append( KWildcard );
+
+			iVariables.AppendL( TColumn( pattern ) );
+
+			CleanupStack::Pop( pattern );
+
+			iQueryBuf->AppendL( KLike );
+
+			iQueryBuf->AppendL( KObjectFreeTextSearchEnd );
+			}
+			break;
+		case EObjectConditionCompareFreeTextBeginsWith:
+			{
+			TPtrC16 freetextPtr = iSerializedBuffer->ReceivePtr16L();
+
+			HBufC* freetext = freetextPtr.AllocLC();
+			iFreeText.AppendL( freetext );
+			CleanupStack::Pop( freetext );
+
+			iQueryBuf->AppendL( KObjectFreeTextSearchStart );
+			iQueryBuf->AppendL( iNamespaceIdDes );
+			iQueryBuf->AppendL( KObjectFreeTextSearchWhere );
+			iQueryBuf->AppendL( iNamespaceIdDes );
+			iQueryBuf->AppendL( KObjectFreeTextSearchDictionaryWhere );
+
+			HBufC16* pattern = HBufC16::NewLC( freetextPtr.Length() + 1 );  // prepare for freetext%
+
+	        TPtr16 modPattern = pattern->Des();
+
+			// add wildcard after freetext "freetext%"
+			modPattern.Append( freetextPtr );
+			modPattern.Append( KWildcard );
+
+			iVariables.AppendL( TColumn( pattern ) );
+
+			CleanupStack::Pop( pattern );
+
+			iQueryBuf->AppendL( KLike );
+
+			iQueryBuf->AppendL( KObjectFreeTextSearchEnd );
+			}
+			break;
+		case EObjectConditionCompareFreeTextEndsWith:
+			{
+			TPtrC16 freetextPtr = iSerializedBuffer->ReceivePtr16L();
+
+			HBufC* freetext = freetextPtr.AllocLC();
+			iFreeText.AppendL( freetext );
+			CleanupStack::Pop( freetext );
+
+			iQueryBuf->AppendL( KObjectFreeTextSearchStart );
+			iQueryBuf->AppendL( iNamespaceIdDes );
+			iQueryBuf->AppendL( KObjectFreeTextSearchWhere );
+			iQueryBuf->AppendL( iNamespaceIdDes );
+			iQueryBuf->AppendL( KObjectFreeTextSearchDictionaryWhere );
+
+			HBufC16* pattern = HBufC16::NewLC( freetextPtr.Length() + 1 );  // prepare for %freetext
+
+	        TPtr16 modPattern = pattern->Des();
+
+			// add wildcard before freetext "%freetext"
+			modPattern.Append( KWildcard );
+			modPattern.Append( freetextPtr );
+
+			iVariables.AppendL( TColumn( pattern ) );
+
+			CleanupStack::Pop( pattern );
+
+			iQueryBuf->AppendL( KLike );
+
+			iQueryBuf->AppendL( KObjectFreeTextSearchEnd );
+			}
+			break;
+		default:
+#ifdef _DEBUG
+			User::Panic( _L("MdSFCAO2") , KErrMdEUnknownConditionCompareMethod );
+#endif
+			User::Leave( KErrMdEUnknownConditionCompareMethod );
+		}
+
+	iQueryBuf->AppendL( KRightBracket );
+	}
+
+// ---------------------------------------------------------------------------
+// AppendRangeL                    Help method for appending range.
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendRangeL(TRangeValueType aRangeValueType)
+	{
+	TInt32 rangeTypeValue;
+	iSerializedBuffer->ReceiveL( rangeTypeValue );
+	const TMdERangeType rangeType = (TMdERangeType)rangeTypeValue;
+
+	TMdCValueUnion minValue;
+	iSerializedBuffer->ReceiveL( minValue );
+
+	TMdCValueUnion maxValue;
+	iSerializedBuffer->ReceiveL( maxValue );
+
+	TInt64 minIntegerValue = KMaxTInt64;
+	TInt64 maxIntegerValue = 0;
+
+	switch( aRangeValueType )
+		{
+		case EInt32RangeValue:
+			minIntegerValue = maxValue.iInt32;
+			maxIntegerValue = maxValue.iInt32;
+			break;
+		case EUint32RangeValue:
+			minIntegerValue = maxValue.iUint32;
+			maxIntegerValue = maxValue.iUint32;
+			break;
+		case EInt64RangeValue:
+			minIntegerValue = maxValue.iInt64;
+			maxIntegerValue = maxValue.iInt64;
+			break;
+		default:		
+		    break;
+		}
+	
+	switch( rangeType )
+		{
+		case EMdERangeTypeAny:
+			break;
+		case EMdERangeTypeEqual:
+			iQueryBuf->AppendL( KEqual );
+			iVariables.AppendL( TColumn( minIntegerValue ) );
+			break;
+		case EMdERangeTypeNotEqual:
+			iQueryBuf->AppendL( KNotEqual );
+			iVariables.AppendL( TColumn( minIntegerValue ) );
+			break;
+		case EMdERangeTypeLess:
+			iQueryBuf->AppendL( KLess );
+			iVariables.AppendL( TColumn( maxIntegerValue ) );
+			break;
+		case EMdERangeTypeLessOrEqual:
+			iQueryBuf->AppendL( KLessOrEqual );
+			iVariables.AppendL( TColumn( maxIntegerValue ) );
+			break;
+		case EMdERangeTypeGreater:
+			iQueryBuf->AppendL( KGreater );
+			iVariables.AppendL( TColumn( minIntegerValue ) );
+			break;
+		case EMdERangeTypeGreaterOrEqual:
+			iQueryBuf->AppendL( KGreaterOrEqual );
+			iVariables.AppendL( TColumn( minIntegerValue ) );
+			break;
+		case EMdERangeTypeBetween:
+			iQueryBuf->AppendL( KBetween );
+			iVariables.AppendL( TColumn( minIntegerValue ) );
+			iVariables.AppendL( TColumn( maxIntegerValue ) );
+			break;
+		case EMdERangeTypeNotBetween:
+			iQueryBuf->AppendL( KNotBetween );
+			iVariables.AppendL( TColumn( minIntegerValue ) );
+			iVariables.AppendL( TColumn( maxIntegerValue ) );
+			break;
+		default:
+#ifdef _DEBUG
+			User::Panic( _L("MdSFCARa") , KErrMdEUnknownRangeType );
+#endif
+			User::Leave( KErrMdEUnknownRangeType );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// AppendPropertyConditionL      Help method for appending property condition.
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendPropertyConditionL(TBool aNegated)
+	{
+	const TMdCPropertyCondition& condition = 
+		TMdCPropertyCondition::GetFromBufferL( *iSerializedBuffer );
+	
+	// "SELECT ObjectId FROM "
+	iQueryBuf->AppendL( KSelectObjectIdFrom );
+
+	TDefId objectDefId = condition.iObjectDefId;
+
+	// get object def ID for source object def if 
+	// condition is not from "Object" def and 
+	// (not multi object query or (multi object query and WHERE to search from 
+	// doesn't match with WHAT to search))
+	if( KBaseObjectDefId != objectDefId && ( !iSourceObjectDefs || 
+			( iSourceObjectDefs && iObjectDef != iSourceObjectDef ) ) )
+		{
+		objectDefId = iSourceObjectDef->GetId();
+		}
+	AppendTableByObjectDefIdL( objectDefId );
+
+	// "WHERE(...)"
+	iQueryBuf->AppendL( KSpace );
+	iQueryBuf->AppendL( KWhere );
+
+	iQueryBuf->AppendL( KLeftBracket );
+
+	AppendColumnByPropertyDefIdL( condition.iPropertyDefId );
+
+	if( aNegated )
+		{
+		// If negated search objects without specified property
+
+		// " ISNULL"
+		iQueryBuf->AppendL( KIsNull );
+		}
+	else
+		{
+		// " NOTNULL"
+		iQueryBuf->AppendL( KNotNull );
+		}
+
+	iQueryBuf->AppendL( KRightBracket );
+	}
+
+// ---------------------------------------------------------------------------
+// ObjectDefForPropertyCondition        Helper method for getting object 
+//                                      definition for property condition.
+// ---------------------------------------------------------------------------
+//
+TDefId CMdSFindSqlClause::ObjectDefForPropertyCondition(TDefId aObjectDefId)
+	{
+	// if object def is not base object def
+	if( KBaseObjectDefId != aObjectDefId )
+		{
+		const CMdsObjectDef* parent = iSourceObjectDef->GetParent();
+
+		// check if property's object def belongs to 
+		// any of source object def's parents
+		while( parent )
+			{
+			// if property's object def belongs to 
+			// any parent, use source object def's ID
+			if( aObjectDefId == parent->GetId() )
+				{
+				return iSourceObjectDef->GetId();
+				}
+
+			// get parent's parent
+			parent = parent->GetParent();
+			}
+		}
+
+	return aObjectDefId;
+	}
+
+// ---------------------------------------------------------------------------
+// AppendPropertyRangeConditionL        Help method for appending property 
+//                                      range condition.
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendPropertyRangeConditionL(TBool aNegated)
+	{
+	const TMdCPropertyCondition& condition = 
+		TMdCPropertyCondition::GetFromBufferL( *iSerializedBuffer );
+
+	// "SELECT ObjectId FROM "
+	iQueryBuf->AppendL( KSelectObjectIdFrom );
+
+	TDefId objectDefId = ObjectDefForPropertyCondition( 
+			condition.iObjectDefId );
+
+	AppendTableByObjectDefIdL( objectDefId );
+
+	// "WHERE(...)"
+	iQueryBuf->AppendL( KSpace );
+	iQueryBuf->AppendL( KWhere );
+
+	iQueryBuf->AppendL( KLeftBracket );
+
+	if( aNegated )
+		{
+		// "NOT "
+		iQueryBuf->AppendL( KNotWithSpace );
+		}
+
+	AppendColumnByPropertyDefIdL( condition.iPropertyDefId, objectDefId );
+
+	// move position to begin of compare condition
+	iSerializedBuffer->PositionL( condition.iCondition );
+	
+	TInt32 rangeTypeValue;
+	iSerializedBuffer->ReceiveL( rangeTypeValue );
+	const TMdERangeType rangeType = (TMdERangeType)rangeTypeValue;
+
+	TMdCValueUnion minValue;
+	iSerializedBuffer->ReceiveL( minValue );
+
+	TMdCValueUnion maxValue;
+	iSerializedBuffer->ReceiveL( maxValue );
+
+	TBool integerValue = ETrue;
+	TInt64 minIntegerValue = 0;
+	TInt64 maxIntegerValue = 0;
+
+	// get correct value and value's type
+	switch( condition.iConditionType )
+	{
+		case EConditionTypePropertyIntRange:
+			minIntegerValue = minValue.iInt32;
+			maxIntegerValue = maxValue.iInt32;
+			break;
+		case EConditionTypePropertyUintRange:
+			minIntegerValue = minValue.iUint32;
+			maxIntegerValue = maxValue.iUint32;
+			break;
+		case EConditionTypePropertyInt64Range:
+		case EConditionTypePropertyTimeRange:
+			minIntegerValue = minValue.iInt64;
+			maxIntegerValue = maxValue.iInt64;
+			break;
+		case EConditionTypePropertyRealRange:
+			integerValue = EFalse;
+			break;
+		default:
+#ifdef _DEBUG
+			User::Panic( _L( "MdSFCAR1" ), KErrMdEUnknownConditionType );
+#endif
+			User::Leave( KErrMdEUnknownConditionType );
+			break;
+	};
+	
+	switch( rangeType )
+		{
+		case EMdERangeTypeAny:
+			break;
+		case EMdERangeTypeEqual:
+			iQueryBuf->AppendL( KEqual );
+			if( integerValue )
+				{
+				iVariables.AppendL( TColumn( minIntegerValue ) );
+				}
+			else
+				{
+				iVariables.AppendL( TColumn( minValue.iReal ) );
+				}
+			break;
+		case EMdERangeTypeNotEqual:
+			iQueryBuf->AppendL( KNotEqual );
+			if( integerValue )
+				{
+				iVariables.AppendL( TColumn( minIntegerValue ) );
+				}
+			else
+				{
+				iVariables.AppendL( TColumn( minValue.iReal ) );
+				}
+
+			break;
+		case EMdERangeTypeLess:
+			iQueryBuf->AppendL( KLess );
+			if( integerValue )
+				{
+				iVariables.AppendL( TColumn( maxIntegerValue ) );
+				}
+			else
+				{
+				iVariables.AppendL( TColumn( maxValue.iReal ) );
+				}
+			break;
+		case EMdERangeTypeLessOrEqual:
+			iQueryBuf->AppendL( KLessOrEqual );
+			if( integerValue )
+				{
+				iVariables.AppendL( TColumn( maxIntegerValue ) );
+				}
+			else
+				{
+				iVariables.AppendL( TColumn( maxValue.iReal ) );
+				}
+			break;
+		case EMdERangeTypeGreater:
+			iQueryBuf->AppendL( KGreater );
+			if( integerValue )
+				{
+				iVariables.AppendL( TColumn( minIntegerValue ) );
+				}
+			else
+				{
+				iVariables.AppendL( TColumn( minValue.iReal ) );
+				}
+			break;
+		case EMdERangeTypeGreaterOrEqual:
+			iQueryBuf->AppendL( KGreaterOrEqual );
+			if( integerValue )
+				{
+				iVariables.AppendL( TColumn( minIntegerValue ) );
+				}
+			else
+				{
+				iVariables.AppendL( TColumn( minValue.iReal ) );
+				}
+			break;
+		case EMdERangeTypeBetween:
+			iQueryBuf->AppendL( KBetween );
+			if( integerValue )
+				{
+				iVariables.AppendL( TColumn( minIntegerValue ) );
+				iVariables.AppendL( TColumn( maxIntegerValue ) );
+				}
+			else
+				{
+				iVariables.AppendL( TColumn( minValue.iReal ) );
+				iVariables.AppendL( TColumn( maxValue.iReal ) );
+				}
+			break;
+		case EMdERangeTypeNotBetween:
+			iQueryBuf->AppendL( KNotBetween );
+			if( integerValue )
+				{
+				iVariables.AppendL( TColumn( minIntegerValue ) );
+				iVariables.AppendL( TColumn( maxIntegerValue ) );
+				}
+			else
+				{
+				iVariables.AppendL( TColumn( minValue.iReal ) );
+				iVariables.AppendL( TColumn( maxValue.iReal ) );
+				}
+			break;
+		default:
+#ifdef _DEBUG
+			User::Panic( _L( "MdSFCAR2" ), KErrMdEUnknownRangeType );
+#endif
+			User::Leave( KErrMdEUnknownRangeType );
+		}
+
+	iQueryBuf->AppendL( KRightBracket );
+	}
+
+// ---------------------------------------------------------------------------
+// AppendPropertyTextConditionL            Help method for appending property 
+//                                         text condition.
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendPropertyTextConditionL(TBool aNegated)
+	{
+	const TMdCPropertyCondition& condition = 
+		TMdCPropertyCondition::GetFromBufferL( *iSerializedBuffer );
+
+	// "SELECT ObjectId FROM "
+	iQueryBuf->AppendL( KSelectObjectIdFrom );
+
+	TDefId objectDefId = ObjectDefForPropertyCondition( 
+			condition.iObjectDefId );
+
+	AppendTableByObjectDefIdL( objectDefId );
+
+	// "WHERE(...)"
+	iQueryBuf->AppendL( KSpace );
+	iQueryBuf->AppendL( KWhere );
+
+	iQueryBuf->AppendL( KLeftBracket );
+
+	if( aNegated )
+		{
+		// "NOT "
+		iQueryBuf->AppendL( KNotWithSpace );
+		}
+
+	AppendColumnByPropertyDefIdL( condition.iPropertyDefId );
+
+	// move position to begin of compare condition
+	iSerializedBuffer->PositionL( condition.iCondition );
+
+	TUint32 compareMethodValue;
+	iSerializedBuffer->ReceiveL( compareMethodValue );
+	const TTextPropertyConditionCompareMethod compareMethod = 
+		(TTextPropertyConditionCompareMethod)compareMethodValue;
+
+	TPtrC16 textPtr = iSerializedBuffer->ReceivePtr16L();
+
+	switch( compareMethod )
+		{
+		case ETextPropertyConditionCompareEquals:
+			iQueryBuf->AppendL( KEqual );
+			iVariables.AppendL( TColumn( textPtr ) );
+			break;
+		case ETextPropertyConditionCompareContains:
+			{
+			HBufC16* pattern = HBufC16::NewLC( textPtr.Length() + 2 );  // prepare for %text%
+
+	        TPtr16 modPattern = pattern->Des();
+
+			// add wildcard before and after text "%text%"
+			modPattern.Append( KWildcard );
+			modPattern.Append( textPtr );
+			modPattern.Append( KWildcard );
+
+			iVariables.AppendL( TColumn( pattern ) );
+
+			CleanupStack::Pop( pattern );
+
+			iQueryBuf->AppendL( KLike );
+			}
+			break;
+		case ETextPropertyConditionCompareBeginsWith:
+			{
+			HBufC16* pattern = HBufC16::NewLC( textPtr.Length() + 1 );  // prepare for text%
+
+	        TPtr16 modPattern = pattern->Des();
+
+			// add wildcard after text "text%"
+			modPattern.Append( textPtr );
+			modPattern.Append( KWildcard );
+
+			iVariables.AppendL( TColumn( pattern ) );
+
+			CleanupStack::Pop( pattern );
+
+			iQueryBuf->AppendL( KLike );
+			}
+			break;
+		case ETextPropertyConditionCompareEndsWith:
+			{
+			HBufC16* pattern = HBufC16::NewLC( textPtr.Length() + 1 );  // prepare for %text
+
+	        TPtr16 modPattern = pattern->Des();
+
+			// add wildcard before text "%text"
+			modPattern.Append( KWildcard );
+			modPattern.Append( textPtr );
+
+			iVariables.AppendL( TColumn( pattern ) );
+
+			CleanupStack::Pop( pattern );
+
+			iQueryBuf->AppendL( KLike );
+			}
+			break;
+		default:
+#ifdef _DEBUG
+			User::Panic( _L( "MdSFCATC" ), KErrMdEUnknownConditionCompareMethod );
+#endif
+			User::Leave( KErrMdEUnknownConditionCompareMethod );
+		}
+
+	iQueryBuf->AppendL( KRightBracket );
+	}
+
+// ---------------------------------------------------------------------------
+// AppendPropertyBoolConditionL            Help method for appending property 
+//                                         bool condition.
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendPropertyBoolConditionL(TBool aNegated)
+	{
+	const TMdCPropertyCondition& condition = 
+		TMdCPropertyCondition::GetFromBufferL( *iSerializedBuffer );
+
+	// "SELECT ObjectId FROM "
+	iQueryBuf->AppendL( KSelectObjectIdFrom );
+
+	TDefId objectDefId = ObjectDefForPropertyCondition( 
+			condition.iObjectDefId );
+
+	AppendTableByObjectDefIdL( objectDefId );
+
+	// "WHERE(...)"
+	iQueryBuf->AppendL( KSpace );
+	iQueryBuf->AppendL( KWhere );
+
+	iQueryBuf->AppendL( KLeftBracket );
+
+	if( aNegated )
+		{
+		// "NOT "
+		iQueryBuf->AppendL( KNotWithSpace );
+		}
+
+	AppendColumnByPropertyDefIdL( condition.iPropertyDefId );
+
+	// move position to begin of compare condition
+	iSerializedBuffer->PositionL( condition.iCondition );
+	
+	TBool boolValue;
+	iSerializedBuffer->ReceiveL( boolValue );
+
+	iQueryBuf->AppendL( KEqual );
+	iVariables.AppendL( TColumn( boolValue ) );
+
+	iQueryBuf->AppendL( KRightBracket );
+	}
+
+// ---------------------------------------------------------------------------
+// AppendEventConditionL                   Help method for appending event 
+//                                         condition for object query.
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendEventConditionL(TBool aNegated)
+	{
+	const TMdCEventCondition& condition = TMdCEventCondition::GetFromBufferL( 
+			*iSerializedBuffer );
+
+	if( EQueryTypeEvent == iSearchCriteria->iQueryType )
+		{
+		// "SELECT EventId FROM Event"
+		iQueryBuf->AppendL( KSelectEventIdFromEvent );
+		}
+	else
+		{
+		// "SELECT ObjectId FROM Event"
+		iQueryBuf->AppendL( KSelectObjectIdFromEvent );
+		}
+
+	// ""namespace def ID" WHERE"
+	iQueryBuf->AppendL( iNamespaceIdDes );
+	iQueryBuf->AppendL( KSpace ); 
+	iQueryBuf->AppendL( KWhere );
+
+	// " NOT"
+	if( aNegated )
+		{
+		iQueryBuf->AppendL( KSpaceWithNot );
+		}
+
+	iQueryBuf->AppendL( KLeftBracket );
+
+	TBool firstEventCondition = ETrue;
+
+	if( condition.iEventId != KNoId )
+		{
+		firstEventCondition = EFalse;
+
+		// "EventId="eventId""
+		iQueryBuf->AppendL( KEventIdEqual );
+		iVariables.AppendL( TColumn( condition.iEventId ) );
+		}
+
+	if( condition.iEventDefId != KNoDefId )
+		{
+		if( firstEventCondition == EFalse )
+			{
+			iQueryBuf->AppendL( KSpace );
+			iQueryBuf->AppendL( KAnd );
+			}
+		firstEventCondition = EFalse;
+
+		// "EventDefId="eventDefId""
+		iQueryBuf->AppendL( KEventDefIdEqual );
+		iVariables.AppendL( TColumn( condition.iEventDefId ) );
+		}
+
+	if( condition.iCreationTimeRange != KNoOffset )
+		{
+		if( firstEventCondition == EFalse )
+			{
+			iQueryBuf->AppendL( KSpace );
+			iQueryBuf->AppendL( KAnd );
+			}
+		firstEventCondition = EFalse;
+
+		// "TimeStamp"
+		iQueryBuf->AppendL( KEventTimeStamp );
+		iSerializedBuffer->PositionL( condition.iCreationTimeRange );		
+		AppendRangeL( EInt64RangeValue );
+		}
+
+	if( condition.iObjectCondition != KNoOffset )
+		{
+		if( firstEventCondition == EFalse )
+			{
+			iQueryBuf->AppendL( KSpace );
+			iQueryBuf->AppendL( KAnd );
+			}
+		firstEventCondition = EFalse;
+
+		iQueryBuf->AppendL( KEventObjectIdIn );
+		iSerializedBuffer->PositionL( condition.iObjectCondition );		
+		iQueryBuf->AppendL( KLeftBracket );
+		ConditionStatementL( EFalse, EAppendInFalse );
+		iQueryBuf->AppendL( KRightBracket );
+		}
+
+	if( condition.iSourceCondition != KNoOffset )
+		{
+		if( firstEventCondition == EFalse )
+			{
+			iQueryBuf->AppendL( KSpace );
+			iQueryBuf->AppendL( KAnd );
+			}
+		firstEventCondition = EFalse;
+
+		iSerializedBuffer->PositionL( condition.iSourceCondition );		
+		ConditionStatementL( EFalse, EAppendInFalse );
+		}
+
+	if( condition.iParticipantCondition != KNoOffset )
+		{
+		if( firstEventCondition == EFalse )
+			{
+			iQueryBuf->AppendL( KSpace );
+			iQueryBuf->AppendL( KAnd );
+			}
+		firstEventCondition = EFalse;
+
+		iSerializedBuffer->PositionL( condition.iParticipantCondition );		
+		ConditionStatementL( EFalse, EAppendInFalse );
+		}
+
+	// check event condition has URI comparsion
+	if( EEventConditionCompareNone != condition.iCompareMethod
+			&& KNoOffset != condition.iUriCondition )
+		{
+		if( firstEventCondition == EFalse )
+			{
+			iQueryBuf->AppendL( KSpace );
+			iQueryBuf->AppendL( KAnd );
+			}
+		firstEventCondition = EFalse;
+
+		switch( condition.iCompareMethod )
+			{
+			case EEventConditionCompareSourceURI:
+	        	// "Source="URI""
+	        	iQueryBuf->AppendL( KEventSourceEqual );
+	        	break;
+
+	        case EEventConditionCompareParticipantURI:
+	        	// "Participant="URI""
+		        iQueryBuf->AppendL( KEventParticipantEqual );
+				break;
+
+	        default:
+#ifdef _DEBUG
+	        	User::Panic( _L( "MdSFCAEC" ), KErrMdEUnknownConditionCompareMethod );
+#endif
+	        	User::Leave( KErrMdEUnknownConditionCompareMethod );
+			}
+
+		iSerializedBuffer->PositionL( condition.iUriCondition );
+		TPtrC16 eventUri = iSerializedBuffer->ReceivePtr16L();
+		iVariables.AppendL( TColumn( eventUri ) );		
+		}
+
+	iQueryBuf->AppendL( KRightBracket );
+	}
+
+// ---------------------------------------------------------------------------
+// AppendRelationConditionL                Help method for appending relation 
+//                                         condition for object query.
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendRelationConditionL(TBool aNegated)
+	{
+	const TMdCRelationCondition& condition = 
+			TMdCRelationCondition::GetFromBufferL( *iSerializedBuffer );
+
+	if( ( ERelationConditionSideLeft == condition.iObjectSide ) || 
+		( ERelationConditionSideRight == condition.iObjectSide ) )
+		{
+		if( EQueryTypeRelation == iSearchCriteria->iQueryType )
+			{
+			// "SELECT RelationId FROM Relations"
+			iQueryBuf->AppendL( KSelectRelationIdFromRelation );
+			}
+		else
+			{
+			if( ERelationConditionSideLeft == condition.iObjectSide )
+				{
+				// "SELECT LeftObjectId FROM Relations"
+				iQueryBuf->AppendL( KSelectLeftObjectIdFromRelation );
+				}
+			else
+				{
+				// "SELECT RightObjectId FROM Relations"
+				iQueryBuf->AppendL( KSelectRightObjectIdFromRelation );
+				}
+			}
+
+		// ""namespace def ID" "
+		iQueryBuf->AppendL( iNamespaceIdDes );
+		iQueryBuf->AppendL( KSpace );
+		
+		// "WHERE(NOT Flags&?)"
+		iQueryBuf->AppendL( KWhereNotFlag );
+		iVariables.AppendL( TColumn( 
+				EMdERelationFlagNotPresent | 
+				EMdERelationFlagDeleted | 
+				EMdERelationFlagGarbageDeleted ) );
+
+		if( condition.iLeftObjectCondition != KNoOffset )
+			{
+			// "AND "
+			iQueryBuf->AppendL( KAnd );
+
+			// "NOT"
+			if( aNegated )
+			{
+				iQueryBuf->AppendL( KNot );
+			}
+
+			iQueryBuf->AppendL( KLeftBracket );
+
+			iQueryBuf->AppendL( KLeftBracket );
+			// append relation condition and left object condition
+			AppendRelationSideConditionL( ETrue, condition, 
+					ETrue, condition.iLeftObjectCondition );
+			iQueryBuf->AppendL( KRightBracket );
+
+			// append right object condition if it exists
+			if( condition.iRightObjectCondition != KNoOffset )
+				{
+				// "AND "
+				iQueryBuf->AppendL( KAnd );
+
+				iQueryBuf->AppendL( KLeftBracket );
+				// append only right object condition
+				AppendRelationSideConditionL( EFalse, condition, 
+						EFalse, condition.iRightObjectCondition );
+				iQueryBuf->AppendL( KRightBracket );
+				}
+
+			iQueryBuf->AppendL( KRightBracket );
+			}
+		else
+			{
+			// append right object condition if it exists
+			if( condition.iRightObjectCondition != KNoOffset )
+				{
+				// "AND "
+				iQueryBuf->AppendL( KAnd );
+				
+				// "NOT"
+				if( aNegated )
+				{
+					iQueryBuf->AppendL( KNot );
+				}
+
+				iQueryBuf->AppendL( KLeftBracket );
+				// append relation condition and right object condition
+				AppendRelationSideConditionL( ETrue, condition, 
+						EFalse, condition.iRightObjectCondition );
+				iQueryBuf->AppendL( KRightBracket );
+				}
+			}
+		}
+	else if( ERelationConditionSideEither == condition.iObjectSide )
+		{
+		// relation query
+		if( EQueryTypeRelation == iSearchCriteria->iQueryType )
+			{
+			// "SELECT RelationId FROM Relations"namespace def ID" "
+			iQueryBuf->AppendL( KSelectRelationIdFromRelation );
+			iQueryBuf->AppendL( iNamespaceIdDes );
+			iQueryBuf->AppendL( KSpace );
+		
+			// "WHERE(NOT Flags&?)"
+			iQueryBuf->AppendL( KWhereNotFlag );
+			iVariables.AppendL( TColumn( 
+					EMdERelationFlagNotPresent | 
+					EMdERelationFlagDeleted | 
+					EMdERelationFlagGarbageDeleted ) );
+			
+			// append left object condition if it exists
+			if( condition.iLeftObjectCondition != KNoOffset )
+				{
+				// "AND "
+				iQueryBuf->AppendL( KAnd );
+
+				// "NOT"
+				if( aNegated )
+					{
+					iQueryBuf->AppendL( KNot );
+					}
+
+				iQueryBuf->AppendL( KLeftBracket );
+
+				iQueryBuf->AppendL( KLeftBracket );
+				// append relation condition and left object condition
+				AppendRelationSideConditionL( ETrue, condition, 
+						ETrue, condition.iLeftObjectCondition );
+				iQueryBuf->AppendL( KRightBracket );
+
+				// append right object condition if it exists
+				if( condition.iRightObjectCondition != KNoOffset )
+					{
+					// "OR "
+					iQueryBuf->AppendL( KOr );
+
+					iQueryBuf->AppendL( KLeftBracket );
+					// append only right object condition
+					AppendRelationSideConditionL( EFalse, condition, 
+							EFalse, condition.iRightObjectCondition );
+					iQueryBuf->AppendL( KRightBracket );
+					}
+
+				iQueryBuf->AppendL( KRightBracket );
+				}
+			// append right object condition if it exists
+			else if( condition.iRightObjectCondition != KNoOffset )
+				{
+				// "AND "
+				iQueryBuf->AppendL( KAnd );
+
+				// "NOT"
+				if( aNegated )
+					{
+					iQueryBuf->AppendL( KNot );
+					}
+
+				iQueryBuf->AppendL( KLeftBracket );
+				// append relation condition and right object condition
+				AppendRelationSideConditionL( ETrue, condition, 
+						EFalse, condition.iRightObjectCondition );
+				iQueryBuf->AppendL( KRightBracket );
+				}
+			// append only relation conditions
+			else 
+				{
+				// "AND "
+				iQueryBuf->AppendL( KAnd );
+
+				// "NOT"
+				if( aNegated )
+					{
+					iQueryBuf->AppendL( KNot );
+					}
+
+				iQueryBuf->AppendL( KLeftBracket );
+				// append relation conditions
+				AppendRelationSideConditionL( ETrue, condition, 
+						EFalse, KNoOffset ); // no object condition
+				iQueryBuf->AppendL( KRightBracket );
+				}
+			}
+		// object or event query
+		else
+			{
+			if( condition.iLeftObjectCondition != KNoOffset )
+				{
+				// "SELECT LeftObjectId FROM Relations"namespace def ID" "
+				iQueryBuf->AppendL( KSelectLeftObjectIdFromRelation );
+				iQueryBuf->AppendL( iNamespaceIdDes );
+				iQueryBuf->AppendL( KSpace );
+
+				// "WHERE(NOT Flags&?)"
+				iQueryBuf->AppendL( KWhereNotFlag );
+				iVariables.AppendL( TColumn( 
+						EMdERelationFlagNotPresent | 
+						EMdERelationFlagDeleted | 
+						EMdERelationFlagGarbageDeleted ) );
+
+				// "AND "
+				iQueryBuf->AppendL( KAnd );
+				
+				// "NOT"
+				if( aNegated )
+					{
+					iQueryBuf->AppendL( KNot );
+					}
+
+				iQueryBuf->AppendL( KLeftBracket );
+				AppendRelationSideConditionL( ETrue, condition, 
+						ETrue, condition.iLeftObjectCondition );
+				iQueryBuf->AppendL( KRightBracket );
+
+				if( condition.iRightObjectCondition != KNoOffset )
+					{
+					// " UNION "
+					iQueryBuf->AppendL( KUnion );
+
+					// "SELECT RightObjectId FROM Relations"namespace def ID" "
+					iQueryBuf->AppendL( KSelectRightObjectIdFromRelation );
+					iQueryBuf->AppendL( iNamespaceIdDes );
+					iQueryBuf->AppendL( KSpace );
+					
+					// "WHERE(NOT Flags&?)"
+					iQueryBuf->AppendL( KWhereNotFlag );
+					iVariables.AppendL( TColumn( 
+							EMdERelationFlagNotPresent | 
+							EMdERelationFlagDeleted | 
+							EMdERelationFlagGarbageDeleted ) );
+
+					// "AND "
+					iQueryBuf->AppendL( KAnd );
+					
+					// "NOT"
+					if( aNegated )
+						{
+						iQueryBuf->AppendL( KNot );
+						}
+
+					iQueryBuf->AppendL( KLeftBracket );
+					AppendRelationSideConditionL( ETrue, condition, 
+							EFalse, condition.iRightObjectCondition );
+					iQueryBuf->AppendL( KRightBracket );
+					}
+				}
+			else
+				{
+				// "SELECT RightObjectId FROM Relations"namespace def ID" "
+				iQueryBuf->AppendL( KSelectRightObjectIdFromRelation );
+				iQueryBuf->AppendL( iNamespaceIdDes );
+				iQueryBuf->AppendL( KSpace );
+
+				// "WHERE(NOT Flags&?)"
+				iQueryBuf->AppendL( KWhereNotFlag );
+				iVariables.AppendL( TColumn( 
+						EMdERelationFlagNotPresent | 
+						EMdERelationFlagDeleted | 
+						EMdERelationFlagGarbageDeleted ) );
+
+				// "AND "
+				iQueryBuf->AppendL( KAnd );
+				
+				// "NOT"
+				if( aNegated )
+					{
+					iQueryBuf->AppendL( KNot );
+					}
+
+				iQueryBuf->AppendL( KLeftBracket );
+				AppendRelationSideConditionL( ETrue, condition, 
+						EFalse, condition.iRightObjectCondition );
+				iQueryBuf->AppendL( KRightBracket );
+				}
+			}
+		}
+	else
+		{
+		// unknown relation condition side
+#ifdef _DEBUG
+		User::Panic( _L("MdSFCARC") , KErrCorrupt );
+#endif
+		User::Leave( KErrCorrupt );
+		}
+	}
+
+void CMdSFindSqlClause::AppendRelationSideConditionL(
+		TBool aRelationConditions, 
+		const TMdCRelationCondition& aRelationCondition, 
+		TBool aLeftSide, TUint32 aRelationObjectConditionOffset)
+	{
+	TBool firstEventCondition = ETrue;
+
+	if( aRelationConditions )
+		{
+		if( aRelationCondition.iRelationId != KNoId )
+			{
+			firstEventCondition = EFalse;
+	
+			// "RelationId="relationID""
+			iQueryBuf->AppendL( KRelationIdEqual );
+			iVariables.AppendL( TColumn( aRelationCondition.iRelationId ) );
+			}
+	
+		if( aRelationCondition.iRelationIds.iPtr.iCount > 0 && 
+				aRelationCondition.iRelationIds.iPtr.iOffset != KNoOffset )
+			{
+			if( firstEventCondition == EFalse )
+				{
+				iQueryBuf->AppendL( KSpace );
+				iQueryBuf->AppendL( KAnd );
+				}
+			firstEventCondition = EFalse;
+	
+			// "RelationId IN("relationIDs")"
+			iQueryBuf->AppendL( KRelationIdIn );
+	
+			iQueryBuf->AppendL( KLeftBracket );
+	
+			iSerializedBuffer->PositionL( 
+					aRelationCondition.iRelationIds.iPtr.iOffset );
+	
+			TItemId relationId;
+			iSerializedBuffer->ReceiveL( relationId );
+			iQueryBuf->AppendL( KVariable );
+			iVariables.AppendL( TColumn( relationId ) );
+	
+			for( TInt32 i = 1; i < aRelationCondition.iRelationIds.iPtr.iCount; i++ )
+				{
+				iSerializedBuffer->ReceiveL( relationId );
+				iQueryBuf->AppendL( KCommaVariable );
+				iVariables.AppendL( TColumn( relationId ) );
+				}
+	
+			iQueryBuf->AppendL( KRightBracket );
+			}
+		
+		if( aRelationCondition.iRelationDefId != KNoDefId )
+			{
+			if( firstEventCondition == EFalse )
+				{
+				iQueryBuf->AppendL( KSpace );
+				iQueryBuf->AppendL( KAnd );
+				}
+			firstEventCondition = EFalse;
+	
+			// "RelationDefId="relationDefId""
+			iQueryBuf->AppendL( KRelationDefIdEqual );
+			iVariables.AppendL( TColumn( aRelationCondition.iRelationDefId ) );
+			}
+	
+		if( aRelationCondition.iGuid != KNoOffset )
+			{
+			if( firstEventCondition == EFalse )
+				{
+				iQueryBuf->AppendL( KSpace );
+				iQueryBuf->AppendL( KAnd );
+				}
+			firstEventCondition = EFalse;
+	
+			iSerializedBuffer->PositionL( aRelationCondition.iGuid );
+			
+			TInt64 guidHigh;
+			iSerializedBuffer->ReceiveL( guidHigh );
+			TInt64 guidLow;
+			iSerializedBuffer->ReceiveL( guidLow );
+			
+			// "RelationGuidHigh="relationGuidHigh" AND 
+			// RelationGuidLow="relationGuidLow""
+			iQueryBuf->AppendL( KRelationGuidEqual );
+			iVariables.AppendL( TColumn( guidHigh ) );
+			iVariables.AppendL( TColumn( guidLow ) );
+			}
+	
+		if( aRelationCondition.iParameterRange != KNoOffset )
+			{
+			if( firstEventCondition == EFalse )
+				{
+				iQueryBuf->AppendL( KSpace );
+				iQueryBuf->AppendL( KAnd );
+				}
+			firstEventCondition = EFalse;
+	
+			// "Parameter"
+			iQueryBuf->AppendL( KRelationParameter );
+			iSerializedBuffer->PositionL( aRelationCondition.iParameterRange );
+			AppendRangeL( EInt32RangeValue );
+			}
+	
+		if( aRelationCondition.iLastModifiedDateRange != KNoOffset )
+			{
+			if( firstEventCondition == EFalse )
+				{
+				iQueryBuf->AppendL( KSpace );
+				iQueryBuf->AppendL( KAnd );
+				}
+			firstEventCondition = EFalse;
+	
+			// "LastModifiedDate"
+			iQueryBuf->AppendL( KRelationLastModifiedDate );
+			iSerializedBuffer->PositionL( aRelationCondition.iLastModifiedDateRange );		
+			AppendRangeL( EInt64RangeValue );
+			}
+		}
+
+	// object condition on left or right side
+	if( aRelationObjectConditionOffset != KNoOffset )
+		{
+		if( firstEventCondition == EFalse )
+			{
+			iQueryBuf->AppendL( KSpace );
+			iQueryBuf->AppendL( KAnd );
+			}
+		firstEventCondition = EFalse;
+
+		iSerializedBuffer->PositionL( aRelationObjectConditionOffset );
+
+		if ( aLeftSide )
+			{
+			ConditionStatementL( EFalse, EAppendInRelationLeft );
+			}
+		else
+			{
+			ConditionStatementL( EFalse, EAppendInRelationRight );
+			}
+		}
+
+	// if there was no any condition add "empty" true condition
+	if( firstEventCondition )
+		{
+		iQueryBuf->AppendL( KEmptyTrue );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// AppendTableByObjectDefIdL               Help method for searching object 
+//                                         definition's table, based on 
+//                                         object definition's ID, and 
+//                                         appending those to buffer.
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendTableByObjectDefIdL(TDefId aObjectDefId)
+	{
+	const CMdsObjectDef* objectDef = iNamespaceDef->GetObjectByIdL( aObjectDefId );
+
+	if ( !objectDef )
+		{
+#ifdef _DEBUG
+		User::Panic( _L("MdSFCAT1") , KErrMdEUnknownObjectDef );
+#endif
+		User::Leave( KErrMdEUnknownObjectDef );
+		}
+
+	iQueryBuf->AppendL( objectDef->GetName() );
+	iQueryBuf->AppendL( iNamespaceIdDes );
+	}
+
+// ---------------------------------------------------------------------------
+// AppendColumnByPropertyDefIdL            Help method for searching property 
+//                                         definition's column, based on 
+//                                         property definition's ID, and 
+//                                         appending those to buffer.
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendColumnByPropertyDefIdL(TDefId aPropertyDefId, 
+		TDefId aObjectDefId, TBool aResult)
+	{
+	CMdsPropertyDef* propDef = NULL;
+
+	if( aObjectDefId == KNoDefId )
+		{
+		if ( !iObjectDef )
+			{
+			const CMdsObjectDef* baseObjectDef = iNamespaceDef->GetObjectByIdL(
+					KBaseObjectDefId );
+	
+			// base object definition must always exist
+			if ( !baseObjectDef )
+				{
+#ifdef _DEBUG
+				User::Panic( _L("MdSFCAC1") , KErrMdEUnknownObjectDef );
+#endif				
+				User::Leave( KErrMdEUnknownObjectDef );
+				}
+
+			propDef = CONST_CAST( CMdsPropertyDef*, 
+					baseObjectDef->GetPropertyByIdL( aPropertyDefId ) );
+
+			// if property definition doesn't exist in base object definition 
+			// search from whole namespace
+			if ( !propDef )
+				{
+				propDef = CONST_CAST( CMdsPropertyDef*, 
+						iNamespaceDef->GetPropertyL( aPropertyDefId ) );
+				}
+			}
+		else
+			{
+			propDef = CONST_CAST( CMdsPropertyDef*, 
+					iObjectDef->GetPropertyByIdL( aPropertyDefId ) );
+			}
+		}
+	else
+		{
+		const CMdsObjectDef* objDef = iNamespaceDef->GetObjectByIdL( 
+				aObjectDefId );
+		propDef = CONST_CAST( CMdsPropertyDef*, 
+				objDef->GetPropertyByIdL( aPropertyDefId ) );
+		}
+
+	if( propDef )
+		{
+		iQueryBuf->AppendL( propDef->GetName() );
+
+		if( aResult )
+			{
+			if( iAppendToResultRow )
+				{
+				// expected result for property's type
+			    iResultRow.AppendL( TColumn( propDef->GetSqlType() ) );
+
+			    iPropertyFilters.Append( propDef );
+				}
+			}
+		}
+	// object definition must always exist for given property definition ID
+	else
+		{
+#ifdef _DEBUG
+		User::Panic( _L("MdSFCAC2") , KErrMdEUnknownObjectDef );
+#endif
+		User::Leave( KErrMdEUnknownObjectDef );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// AppendGroupByL           Appends Group BY statements
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendGroupByL()
+	{
+	// if query type is object query
+	if ( EQueryTypeObject == iSearchCriteria->iQueryType )
+		{
+		switch( iSearchCriteria->iQueryResultType )
+			{
+			case EQueryResultModeItem:
+			case EQueryResultModeId:
+			case EQueryResultModeCount:
+				{
+				// "GROUP BY BO.ObjectId "
+				iQueryBuf->AppendL( KGroupByObjectId );
+				}
+				break;
+
+			default:
+#ifdef _DEBUG
+				User::Panic( _L("MdSFCAGB") , KErrMdEUnknownQueryResultMode );
+#endif
+				User::Leave( KErrMdEUnknownQueryResultMode );
+			}
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// AppendOrderByL           Appends ORDER BY statements
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendOrderByL()
+    {
+	if( iSearchCriteria->iOrderRules.iPtr.iCount > 0 )
+		{
+		iQueryBuf->AppendL( KOrderBy );
+
+		iSerializedBuffer->PositionL( iSearchCriteria->iOrderRules.iPtr.iOffset );
+
+		// Add recursive all children.
+	    for( TUint32 i = 0; i < iSearchCriteria->iOrderRules.iPtr.iCount; i++)
+			{
+			if( i > 0 )
+				{
+				iQueryBuf->AppendL( KComma );
+				}
+
+			const TMdCOrderRule& orderRule = TMdCOrderRule::GetFromBufferL( 
+					*iSerializedBuffer );
+
+			switch( iSearchCriteria->iQueryType )
+				{
+				case EQueryTypeObject:
+					switch( orderRule.iOrderRule )
+						{
+						case EOrderRuleTypeProperty:
+							AppendColumnByPropertyDefIdL( orderRule.iPropertyDefId );
+							break;
+
+						case EOrderRuleTypeItemID:
+							iQueryBuf->AppendL( KBaseObjectObjectId );
+							break;
+
+						case EOrderRuleTypeObjectURI:
+							_LIT( KQueryBaseObjectURI, "BO.URI");
+							iQueryBuf->AppendL( KQueryBaseObjectURI );
+							break;
+
+						case EOrderRuleTypeObjectDef:
+							_LIT( KQueryBaseObjectDefId, "BO.ObjectDefId");
+							iQueryBuf->AppendL( KQueryBaseObjectDefId );
+							break;
+
+						case EOrderRuleTypeUsageCount:
+							_LIT( KQueryBaseObjectUsageCount, "BO.UsageCount");
+							iQueryBuf->AppendL( KQueryBaseObjectUsageCount );
+							break;
+
+						default:
+							User::Leave( KErrNotSupported );
+						}
+					break;
+
+				case EQueryTypeRelation:
+					switch( orderRule.iOrderRule )
+						{
+						case EOrderRuleTypeItemID:
+							iQueryBuf->AppendL( KRelationId );
+							break;
+
+						case EOrderRuleTypeLastModifiedDate:
+							iQueryBuf->AppendL( KRelationLastModifiedDate );
+							break;
+
+						case EOrderRuleTypeParameterValue:
+							iQueryBuf->AppendL( KRelationParameter );
+							break;
+
+						case EOrderRuleTypeLeftObjectID:
+							_LIT( KQueryRelationLeftObjectId, "LeftObjectId");
+							iQueryBuf->AppendL( KQueryRelationLeftObjectId );
+							break;
+
+						case EOrderRuleTypeRightObjectID:
+							_LIT( KQueryRelationRightObjectId, "RightObjectId");
+							iQueryBuf->AppendL( KQueryRelationRightObjectId );
+							break;
+
+						case EOrderRuleTypeRelationDef:
+							_LIT( KQueryRelationDef, "RelationDefId");
+							iQueryBuf->AppendL( KQueryRelationDef );
+							break;
+
+						default:
+							User::Leave( KErrNotSupported );
+						}
+					break;
+
+				case EQueryTypeEvent:
+					switch( orderRule.iOrderRule )
+						{
+						case EOrderRuleTypeItemID:
+							iQueryBuf->AppendL( KEventId );
+							break;
+
+						case EOrderRuleTypeCreationTime:
+							iQueryBuf->AppendL( KEventTimeStamp );
+							break;
+
+						case EOrderRuleTypeSourceURI:
+							_LIT( KQueryEventSource, "Source");
+							iQueryBuf->AppendL( KQueryEventSource );
+							break;
+
+						case EOrderRuleTypeParticipantURI:
+							_LIT( KQueryEventParticipant, "Participant");
+							iQueryBuf->AppendL( KQueryEventParticipant );
+							break;
+
+						case EOrderRuleTypeTargetObjectID:
+							_LIT( KQueryEventObjectId, "ObjectId");
+							iQueryBuf->AppendL( KQueryEventObjectId );
+							break;
+
+						case EOrderRuleTypeEventDef:
+							_LIT( KQueryEventDef, "EventDefId");
+							iQueryBuf->AppendL( KQueryEventDef );
+							break;
+
+						default:
+							User::Leave( KErrNotSupported );
+						}
+					break;
+
+				default:
+#ifdef _DEBUG
+					User::Panic( _L("MdSFCAOB") , KErrMdEUnknownQueryType );
+#endif
+					User::Leave( KErrMdEUnknownQueryType );
+				}
+
+			if ( !orderRule.iCaseSensitive )
+				{
+				iQueryBuf->AppendL( KNoCaseSensitive );
+				}
+
+			if( orderRule.iAscending )
+				{
+				iQueryBuf->AppendL( KAsc );
+				}
+			else
+				{
+				iQueryBuf->AppendL( KDesc );
+				}
+			}
+		
+		iQueryBuf->AppendL( KSpace );				
+		}
+    }
+
+// ---------------------------------------------------------------------------
+// AppendLimitAndOffsetL            LIMIT and OFFSET statements
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::AppendLimitAndOffsetL()
+    {
+    if ( iSearchCriteria->iOffset > 0 )
+    	{
+    	// 10 is maximum length of text format TUint32
+    	iQueryBuf->ReserveSpaceL( iQueryBuf->ConstBufferL().Length() + 
+    			2 * 10 );
+
+    	iQueryBuf->AppendL( KLimit );
+    	iQueryBuf->BufferL().AppendNum( iSearchCriteria->iLimit );
+    	iQueryBuf->AppendL( KComma );
+    	iQueryBuf->BufferL().AppendNum( iSearchCriteria->iOffset );
+    	}
+    else if ( iSearchCriteria->iLimit != KMaxTUint32 )
+    	{
+    	// 10 is maximum length of text format TUint32
+    	iQueryBuf->ReserveSpaceL( iQueryBuf->ConstBufferL().Length() + 
+    			10 );
+    	
+    	iQueryBuf->AppendL( KLimit );
+    	iQueryBuf->BufferL().AppendNum( iSearchCriteria->iLimit );
+    	}
+    }
+
+// ---------------------------------------------------------------------------
+// CopyVariablesL   Copies number of variables from variable table to the
+//                  end of the variable table
+// ---------------------------------------------------------------------------
+//
+void CMdSFindSqlClause::CopyVariablesL( TInt aStart, TInt aEnd )
+    {
+    TColumn column;
+    
+    for ( TInt i(aStart); i<aEnd; ++i )
+        {
+        column = iVariables.Column(i);
+        
+        switch( column.Type() )
+            {
+            case EColumnBool:
+                {
+                TBool v=0;
+                column.Get( v );
+                iVariables.AppendL( TColumn( v ) );
+                break;
+                }
+            case EColumnInt32:
+                {
+                TInt32 v=0;
+                column.Get( v );
+                iVariables.AppendL( TColumn( v ) );
+                break;
+                }
+            case EColumnUint32:
+                {
+                TUint32 v=0;
+                column.Get( v );
+                iVariables.AppendL( TColumn( v ) );
+                break;
+                }
+            case EColumnTime:
+                {
+                TTime v(0);
+                column.Get( v );
+                iVariables.AppendL( TColumn( v ) );
+                break;
+                }
+            case EColumnInt64:
+                {
+                TInt64 v=0;
+                column.Get( v );
+                iVariables.AppendL( TColumn( v ) );
+                break;
+                }
+            case EColumnReal32:
+                {
+                TReal32 v=0;
+                column.Get( v );
+                iVariables.AppendL( TColumn( v ) );
+                break;
+                }
+            case EColumnReal64:
+                {
+                TReal64 v=0;
+                column.Get( v );
+                iVariables.AppendL( TColumn( v ) );
+                break;
+                }
+            case EColumnDes16:
+                {
+                TPtrC16 v = TPtr16((TUint16*)0, 0); //KNullPtr16;
+                column.Get( v );
+                iVariables.AppendL( TColumn( v ) );
+                break;
+                }
+            default:
+#ifdef _DEBUG
+				User::Panic( _L("MdSFCCoV") , KErrMdEUnknownPropertyType );
+#endif            	
+                User::Leave( KErrMdEUnknownPropertyType );
+            }
+        }
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsgarbagecollector.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,158 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementations of methods of CMdSGarbageCollector class*
+*/
+
+#include "mdsgarbagecollector.h"
+
+#include <e32svr.h> // RDebug
+
+CMdSGarbageCollector::CMdSGarbageCollector(MMdSGarbageCollectorObserver& aObserver)
+	: CActive( CActive::EPriorityLow ), iDelay(0), iNewDelay(0), iObserver( aObserver )
+	{
+	CActiveScheduler::Add( this );
+	}
+
+CMdSGarbageCollector::~CMdSGarbageCollector()
+	{
+	Cancel();
+	iTimer.Close();
+	}
+	
+void CMdSGarbageCollector::ConstructL()
+	{
+	User::LeaveIfError( iTimer.CreateLocal() );
+	}
+
+CMdSGarbageCollector* CMdSGarbageCollector::NewL(MMdSGarbageCollectorObserver& aObserver)
+	{
+    CMdSGarbageCollector* self = CMdSGarbageCollector::NewLC(aObserver);
+    CleanupStack::Pop( self );
+    return self;
+	}
+
+CMdSGarbageCollector* CMdSGarbageCollector::NewLC(MMdSGarbageCollectorObserver& aObserver)
+	{
+	CMdSGarbageCollector* self = new ( ELeave ) CMdSGarbageCollector(aObserver);
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+	}
+
+void CMdSGarbageCollector::Start( TInt aDelay )
+	{
+	#ifdef _DEBUG
+	RDebug::Print( _L("CMdSGarbageCollector::Start - delay: %d"), aDelay );
+	#endif
+	if ( aDelay < 0 )
+		{
+		return;
+		}
+
+	const TInt KSecondsToMicroseconds = 1000000;
+	const TInt KMaxInterval = KMaxTInt / KSecondsToMicroseconds;
+
+	if( IsActive() )
+		{
+		if ( iNewDelay.Int() == 0 )
+			{
+			// check if interval is less or equal to 2147 seconds (35 minutes and 47 seconds)
+			if( aDelay <= KMaxInterval )	
+				iNewDelay = aDelay * KSecondsToMicroseconds;
+			else
+				iNewDelay = KMaxTInt;
+			}
+		return;
+		}
+
+	#ifdef _DEBUG
+	RDebug::Print( _L("CMdSGarbageCollector::Start(%d)"), aDelay ); // test
+	#endif
+
+	// check if interval is less or equal to 2147 seconds (35 minutes and 47 seconds)
+	if( aDelay <= KMaxInterval )	
+		iDelay = aDelay * KSecondsToMicroseconds;
+	else
+		iDelay = KMaxTInt;
+
+	iTimer.After( iStatus, iDelay ); // start timer
+
+	SetActive();
+	}
+
+void CMdSGarbageCollector::RunL()
+	{
+	if( iStatus == KErrNone )
+		{
+		const TBool startAgain = iObserver.StartGarbageCollectionL();
+
+		if ( startAgain )
+			{
+			iTimer.After( iStatus, iDelay ); // start timer
+			SetActive();
+			}
+		else if ( iNewDelay.Int() > 0 )
+			{
+			iDelay = iNewDelay;
+			iNewDelay = 0;
+			iTimer.After( iStatus, iDelay ); // start timer
+			SetActive();
+			}
+		}
+	}
+
+void CMdSGarbageCollector::DoCancel()
+	{
+	#ifdef _DEBUG
+	RDebug::Print( _L("CMdSGarbageCollector::DoCancel") );
+	#endif
+	iTimer.Cancel();
+	}
+
+#ifdef _DEBUG
+TInt CMdSGarbageCollector::RunError( TInt aError )
+	{
+#else
+TInt CMdSGarbageCollector::RunError( TInt /*aError*/ )
+	{
+#endif
+	#ifdef _DEBUG
+	RDebug::Print( _L("CMdSGarbageCollector::RunError %d"), aError );
+	#endif
+	return KErrNone;
+	}
+
+void CMdSGarbageCollector::Pause()
+	{
+	#ifdef _DEBUG
+	RDebug::Print( _L("CMdSGarbageCollector::Pause") );
+	#endif
+	DoCancel();
+	}
+
+void CMdSGarbageCollector::Resume()
+	{
+	#ifdef _DEBUG
+	RDebug::Print( _L("CMdSGarbageCollector::Resume") );
+	#endif
+	
+	if( !IsActive() )
+	    {
+	    if ( iDelay.Int() > 0 )
+	         {
+	         iTimer.After( iStatus, iDelay ); // start timer
+	         SetActive();
+	         }
+	    }
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsgetimeiao.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,84 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Helper class to get IMEI number.
+*
+*/
+
+/**
+ * Only used in CMdESessionImpl::GetImei() method.
+ */
+
+#include "mdsgetimeiao.h"
+
+CMdsGetImeiAO* CMdsGetImeiAO::NewL()
+	{
+	CMdsGetImeiAO *self = CMdsGetImeiAO::NewLC();
+	CleanupStack::Pop();
+	return self;
+	}
+
+CMdsGetImeiAO* CMdsGetImeiAO::NewLC()
+	{
+	CMdsGetImeiAO *self = new (ELeave) CMdsGetImeiAO();
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+	}
+
+void CMdsGetImeiAO::ConstructL()
+   {
+   iTelephony = CTelephony::NewL();
+   CActiveScheduler::Add(this);
+   }
+
+CMdsGetImeiAO::~CMdsGetImeiAO()
+	{
+	Cancel();
+
+	delete iTelephony;
+	}
+
+TInt64 CMdsGetImeiAO::GetIMEI()
+	{	
+	const TInt64 KRandomImei = 123456789012345;
+	TInt64 serial = KRandomImei;
+
+#ifdef __ARMV5__ // skip getting IMEI for emulator
+	CTelephony::TPhoneIdV1Pckg phoneIdPckg( iV1 ); 	
+	
+	iTelephony->GetPhoneId( iStatus, phoneIdPckg );
+	SetActive();
+	iAsw.Start();
+	Deque();
+	TLex imeiConverter(iImei);
+	
+    imeiConverter.Val(serial, EDecimal);
+#endif
+    
+    return serial;
+	}
+
+void CMdsGetImeiAO::DoCancel()
+	{
+	iTelephony->CancelAsync(CTelephony::EGetPhoneIdCancel);
+	}
+   
+void CMdsGetImeiAO::RunL()
+	{
+	if(iStatus == KErrNone)
+    	{
+    	iImei = iV1.iSerialNumber;
+    	}
+    iAsw.AsyncStop();
+   	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsimportexport.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,2509 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Metadata schema container within server
+*
+*/
+
+#include <e32cmn.h>
+#include <charconv.h>
+#include <convgeneratedcpp.h>
+#include <badesca.h>
+#include <e32math.h>
+#include <pathinfo.h>
+
+#include <mdeconstants.h>
+
+#include "mdsimportexport.h"
+
+#include "mdcresult.h"
+#include "mdcitem.h"
+#include "mdcdef.h"
+#include "mdsnamespacedef.h"
+#include "mdsobjectdef.h"
+#include "mdccommon.h"
+#include "mdspropertydef.h"
+#include "mdsschema.h"
+#include "mdssqliteconnection.h"
+#include "mdsdbconnectionpool.h"
+#include "mdcserializationbuffer.h"
+#include "mdssqlobjectmanipulate.h"
+#include "mdsrelationdef.h"
+#include "mdseventdef.h"
+#include "mdsfindsqlclausedef.h"
+#include "mdsclausebuffer.h"
+#include "mdsmaintenanceengine.h"
+#include "mdssqldbmaintenance.h"
+#include "mdspreferences.h"
+#include "mdscommoninternal.h"
+
+const TInt KMdsMaxUriLenght = KMaxFileName;
+const TChar KMdsLineFeed = '\n';
+
+const TInt KMdsMaxLogLineLenght( 2056 );
+
+_LIT( KMdsErrorLogDirectory, "Metadata" );
+_LIT( KMdsErrorLogFilename, "importerror.log" );
+
+// keyword definitions in import file
+_LIT8( KMdsKeywordComment,     "//" );
+_LIT8( KMdsKeywordNamespace,   "namespace" );
+_LIT8( KMdsKeywordObjectDef,   "object" );
+_LIT8( KMdsKeywordPropertyDef, "property" );
+_LIT8( KMdsKeywordRelationDef, "relationdef" );
+_LIT8( KMdsKeywordEventDef,    "eventdef" );
+
+_LIT8( KMdsKeywordVersion, "version" );
+
+_LIT8( KMdsKeywordObject,   "object" );
+_LIT8( KMdsKeywordProperty, "property" );
+_LIT8( KMdsKeywordFreeText, "freetext" );
+_LIT8( KMdsKeywordRelation, "relation" );
+_LIT8( KMdsKeywordEvent,    "event" );
+
+_LIT8( KExportMetadataNewLine, "\r\n" );
+_LIT8( KExportMetadataSpace, " " );
+_LIT8( KExportMetadataQuotationMark, "\"" );
+_LIT8( KExportMetadataTimeFormat, "%04d%02d%02d%02d%02d%02d" );
+
+
+_LIT( KMdsKeywordMinValue, "min" );
+_LIT( KMdsKeywordMaxValue, "max" );
+_LIT( KMdsKeywordDefValue, "def" );
+
+/**
+ * NewLC
+ */
+CMdsImportExport* CMdsImportExport::NewLC()
+	{
+	CMdsImportExport* ret = new(ELeave) CMdsImportExport();
+	CleanupStack::PushL( ret );
+	ret->ConstructL();
+	return ret;
+	}
+	
+/**
+ * NewL
+ */
+CMdsImportExport* CMdsImportExport::NewL()
+	{
+	CMdsImportExport* ret = CMdsImportExport::NewLC();
+	CleanupStack::Pop( ret );
+	return ret;
+	}
+	
+/**
+ * Constructor
+ */
+CMdsImportExport::CMdsImportExport() : iLastDriveNumber ( -1 )
+	{
+	}
+	
+/**
+ * Default destructor
+ */
+CMdsImportExport::~CMdsImportExport()
+	{
+   	delete iConverter;
+
+    iLog.CloseLog(); 
+    iLog.Close();
+    iFs.Close();
+
+   	delete iBuffer;
+
+   	delete iSchema;
+	}
+
+/**
+ * ConstructL
+ */
+void CMdsImportExport::ConstructL()
+	{
+	iSchema = CMdsSchema::NewL();
+    iConverter = CCnvCharacterSetConverter::NewL();
+
+    User::LeaveIfError( iFs.Connect() );
+    iConverter->PrepareToConvertToOrFromL( KCharacterSetIdentifierUtf8, iFs );
+    
+    User::LeaveIfError( iLog.Connect( ) );
+    iLog.CreateLog( KMdsErrorLogDirectory, KMdsErrorLogFilename, EFileLoggingModeOverwrite );
+    iLog.SetDateAndTime(EFalse, ETrue);
+
+	iBuffer = NULL;
+    iLastObjectDef = NULL;
+	}
+
+void CMdsImportExport::ImportSchemaFromFileL( const TDesC& aFileName,
+							CMdsSchema& aSchema, TUint32 aVendorId )
+    {
+    iDefaultSchema = &aSchema;
+    iVendorId = aVendorId;
+
+    if ( !iDefaultSchema->iBaseObject )
+    	{
+    	// If the default schema doesn't already have a base object, add one to iSchema together
+    	// with default namespace.
+    	iSchema->AddDefaultObjectL();
+		iDefaultSchema->iBaseObject = iSchema->iBaseObject;
+		iSchema->AddDefaultNamespaceL();
+    	}
+    else
+    	{
+    	iSchema->iBaseObject = iDefaultSchema->iBaseObject;
+    	}
+
+	iReadStream.PushL();
+	// Read the schema file.
+	TInt fileOpenStatus = iReadStream.Open( iFs, aFileName, EFileStreamText );
+	if (fileOpenStatus != KErrNone)
+		{
+	    iSchema->iBaseObject = NULL;
+	    iDefaultSchema = NULL;
+	    _LIT( KError, "Failed to open schema file" );
+    	LogError( KError );
+		User::Leave( fileOpenStatus );
+		}
+    iFileName.Copy( aFileName );
+
+    iLineNumber = 0;
+    iLastObjectDef = NULL;
+    if ( aFileName == KSchemaImportFile || aFileName == KSchemaRomImportFile )
+    	{
+    	iVersionFlags = EVersionNone;
+    	}
+    else
+    	{
+    	iVersionFlags = EVersionAlreadyRead;
+    	}
+
+    // start reading lines from the schema file
+    while( ETrue )
+        {
+        TRAPD( e, iReadStream.ReadL( iLine, KMdsLineFeed ) );
+        if ( e == KErrEof ) break; // succesful exit
+        else if ( e != KErrNone )
+            {
+		    iSchema->iBaseObject = NULL;
+		    iDefaultSchema = NULL;
+		    _LIT( KError, "Failed to read line from schema file" );
+ 	   		LogError( KError );
+			User::Leave( e );
+            }
+
+        ++iLineNumber;
+        if ( iLine.Length() > 0 )
+            {
+            // parse the line
+            TLex8 parser( iLine );
+            TRAP( e, ImportSchemaLineL( parser ) );
+            if ( e != KErrNone )
+            	{
+			    iSchema->iBaseObject = NULL;
+			    iDefaultSchema = NULL;
+			    _LIT( KError, "Schema corrupted" );
+            	LogError( KError );
+            	User::Leave( e );
+            	}
+            }
+        }
+    
+    CleanupStack::PopAndDestroy( &iReadStream ); // Closes stream.
+
+    TRAPD( err, aSchema.MergeNamespacesL( *iSchema ) );
+
+    iSchema->iBaseObject = NULL;
+    iDefaultSchema = NULL;
+    iVendorId = 0;
+
+    if ( err != KErrNone )
+    	{
+    	User::Leave( err );
+    	}
+    }
+
+/**
+ * ImportL imports a single line of data
+ */
+void CMdsImportExport::ImportSchemaLineL( TLex8& aParser )
+    {
+    TPtrC8 token = aParser.NextToken();
+
+    // valid keywords in beginning of line
+    if ( token.Length() == 0 || token.Left(2) == KMdsKeywordComment )
+        {
+        // ignore
+        return;
+        }
+    else if ( token == KMdsKeywordVersion )
+        {
+        ImportSchemaVersionL( aParser );
+        }
+    else if ( !(iVersionFlags & EVersionAlreadyRead ) )
+        {
+        User::Leave( KErrCorrupt );
+        }
+    else if ( token == KMdsKeywordNamespace )
+        {
+        ImportSchemaNamespaceL( aParser );
+        return;
+        }
+    else if ( token == KMdsKeywordObjectDef )
+        {        
+        ImportSchemaObjectDefL( aParser );
+        }
+    else if(token == KMdsKeywordPropertyDef )
+    	{
+    	ImportSchemaPropertyDefL( aParser );
+    	}
+    else if ( token == KMdsKeywordRelationDef )
+        {
+        ImportSchemaRelationDefL( aParser );
+        }
+    else if ( token == KMdsKeywordEventDef )
+        {
+        ImportSchemaEventDefL( aParser );
+        }
+    else
+        {
+        _LIT( KError, "Keyword not recognized" );
+        LogError( KError );
+        User::Leave( KErrCorrupt );
+        }
+    TPtrC8 tokenLast = aParser.NextToken();
+    if ( tokenLast.Length() != 0 && tokenLast.Left(2) != KMdsKeywordComment )
+    	{
+    	_LIT( KMdsUnknownToken, "Undefined schema item" );
+    	LogError( KMdsUnknownToken );
+    	User::Leave( KErrCorrupt );
+    	}
+    }
+
+/**
+ * Schema import checklist:
+ *	1. Are all the namespaces new? If not, discard any duplicates
+ *	2. Do all the (object/event/relation) defs about to be imported actually 
+ *	   belong to a proper namespace (which is also not read-only)? If not, discard
+ */
+// ------------------------------------------------
+// ImportSchemaNamespaceL
+// ------------------------------------------------
+//
+void CMdsImportExport::ImportSchemaNamespaceL( TLex8& aParser )
+    {
+    // namespace <name> <readonly>
+    TBuf16<KMdsMaxUriLenght> name;
+    User::LeaveIfError( ImportText( name, aParser ) );
+    
+    TInt ro = 0;
+    TBool readOnly = EFalse;
+    User::LeaveIfError( ImportNum( ro, aParser ) );
+    readOnly = ro ? ETrue : EFalse;
+
+    // Check out if the namespace already exists
+	if ( iSchema->GetNamespace( name ) )
+		{
+		return;
+		}
+	
+	// in case there is namespace in old schema
+	CMdsNamespaceDef* actualNamespace = iDefaultSchema->GetNamespace( name );
+	if ( actualNamespace )
+		{
+		iSchema->NamespaceAddL( actualNamespace->GetName(),
+                actualNamespace->GetReadOnly(), actualNamespace->GetVendorId(),
+                actualNamespace->GetId() );
+		return;
+		}
+
+	// Ok, the namespace is new
+	iSchema->NamespaceAddL( name, readOnly, iVendorId );
+    }
+
+// ------------------------------------------------
+// ImportSchemaObjectDefL
+// ------------------------------------------------
+//
+void CMdsImportExport::ImportSchemaObjectDefL( TLex8& aParser )
+    {
+    // First read the name of the namespace.
+    TBuf16<KMdsMaxUriLenght> name;
+    User::LeaveIfError( ImportText( name, aParser ) );
+
+	CMdsNamespaceDef* actualNamespace = iSchema->GetNamespace( name );
+	if ( !actualNamespace )
+		{
+        actualNamespace = iDefaultSchema->GetNamespace( name );
+		if ( !actualNamespace )
+			{
+			_LIT( KMdsNamespaceNotFound, "Namespace not found !!!" );
+			LogError( KMdsNamespaceNotFound );
+	    	User::Leave( KErrAccessDenied );
+			}
+		CMdsNamespaceDef* nmsp = iSchema->NamespaceAddL(
+                actualNamespace->GetName(), actualNamespace->GetReadOnly(),
+				actualNamespace->GetVendorId() );
+		if ( !actualNamespace->GetFirstRead() )
+			{
+			nmsp->UnsetFirstRead();
+			}
+		actualNamespace = nmsp;
+		}
+
+    if ( actualNamespace->GetReadOnly() && !actualNamespace->GetFirstRead() )
+    	{
+    	iLastObjectDef = NULL;
+    	_LIT( KError, "Namespace not allowed" );
+    	LogError( KError );
+    	User::Leave( KErrAccessDenied );
+    	}
+
+    // Next read the name of the object.
+    TBuf16<KMdsMaxUriLenght> nameObject;
+    User::LeaveIfError( ImportText( nameObject, aParser ) );
+    if ( nameObject == MdeConstants::Object::KBaseObject )
+    	{
+    	_LIT( KError, "Cannot redefine Object" );
+		LogError( KError );
+    	User::Leave( KErrArgument );
+    	}
+
+    // Next read the name of the parent object.
+    User::LeaveIfError( ImportText( name, aParser ) );
+
+    // Add new object definition to the DB.
+    TRAPD( err, iLastObjectDef = actualNamespace->AddObjectDefL( nameObject, name, iDefaultSchema ) );
+
+    if ( err != KErrNone && err != KErrAlreadyExists  )
+   		{
+   		User::Leave( err );
+    	}
+
+    // Finally read object flags (currently only two values: 0/1).
+    TInt flags;
+    CMdsObjectDef::TObjectDefFlags objFlags = CMdsObjectDef::EObjectDefFlagsNone;
+    User::LeaveIfError( ImportNum(flags, aParser) );
+    switch( flags )
+    	{
+    	case CMdsObjectDef::EObjectDefFlagsNone:
+    		objFlags = CMdsObjectDef::EObjectDefFlagsNone;
+    		break;
+
+    	case CMdsObjectDef::EObjectDefFlagsContext:
+    		objFlags = CMdsObjectDef::EObjectDefFlagsContext;
+    		break;
+
+    	default:
+    		_LIT( KUnsupportedFlag, "Unsupported flag" );
+    		LogError( KUnsupportedFlag );
+    		User::Leave( KErrCorrupt );
+    	}
+    iLastObjectDef->SetFlags( objFlags );
+    }
+
+// ------------------------------------------------
+// ImportSchemaPropertyDefL
+// ------------------------------------------------
+//
+void CMdsImportExport::ImportSchemaPropertyDefL( TLex8& aParser )
+	{
+	// property  <name>  <readonly> <mandatory>  <type> <minv> <maxv>
+    _LIT( KMinMaxWrongValue, "Min value is bigger then max" );
+    _LIT( KWrongValue,       "Min or max value is incorrect" );
+    _LIT( KTextWrongValue,   "Min or max text value is incorrect" );
+
+    // Property definitions always come immediately after object definitions in a schema file.
+    // If there is no object definition before property definitions, it's an error.
+	if ( !iLastObjectDef )
+		{
+		_LIT( KNoLastObject, "Try to add to no existing object" );
+		LogError( KNoLastObject );
+		User::Leave( KErrNotFound );
+		}
+
+	// Read property name.
+    TBuf16<KMdsMaxUriLenght> name;
+    User::LeaveIfError( ImportText( name, aParser ) );
+    if ( iLastObjectDef->GetProperty( name ) )
+    	{
+    	_LIT( KError, "Property already exists" );
+		LogError( KError );
+		User::Leave( KErrArgument );
+    	}
+
+    // Read read-only and mandatory flags.
+    TBool readOnly, mandatory;
+	User::LeaveIfError( ImportNum( readOnly, aParser ) );
+	User::LeaveIfError( ImportNum( mandatory, aParser ) );
+
+	// Read property type.
+    TPropertyType type;
+    TInt32 readType;
+    User::LeaveIfError( ImportNum( readType, aParser ) );
+    type = static_cast<TPropertyType>(readType);
+ 
+    // Depending on the property type read the next two parameters with the correct data type.
+    TInt error = KErrNone;
+    switch( type )	
+    	{
+    	case EPropertyBool:
+    		{
+    		TInt32  minVal32,
+    		        maxVal32;
+    		error = SetMinMaxDefValueL<TInt32>( CheckForConstant(aParser), minVal32, 0, 1, 0 );
+       		if ( error < KErrNone )
+    			{
+    			User::LeaveIfError( ImportNum( minVal32, aParser ) );
+    			}
+    		error = SetMinMaxDefValueL<TInt32>( CheckForConstant(aParser), maxVal32, 0, 1, 1 );
+       		if ( error < KErrNone )
+    			{
+    			User::LeaveIfError( ImportNum( maxVal32, aParser ) );
+    			}
+       		
+       		CheckNoMoreNumericParametersL( aParser );
+       		
+    		// boolean cannot have different values
+    		minVal32 = 0;
+    		maxVal32 = 1;
+    		// Add this property to the previously defined object.
+    		iLastObjectDef->AddPropertyL( name, type, minVal32, maxVal32, readOnly, mandatory, EFalse );
+    		break;
+    		}
+    	case EPropertyInt8:
+    	case EPropertyUint8:
+    	case EPropertyInt16:
+    	case EPropertyUint16:
+    	case EPropertyInt32:
+    		{
+    		TInt32  minVal32,
+    		        maxVal32;
+    		const TInt32 KMinVal32 = type == EPropertyInt8 ? KMinTInt8 :
+    		                          type == EPropertyInt16 ? KMinTInt16 :
+    		                           type == EPropertyInt32 ? KMinTInt32 : 0;
+    		const TInt32 KMaxVal32 = type == EPropertyInt8 ? KMaxTInt8 :
+    		                          type == EPropertyUint8 ? KMaxTUint8 :
+    		                           type == EPropertyInt16 ? KMaxTInt16 :
+    		                            type == EPropertyUint16 ? KMaxTUint16 : KMaxTInt32;
+   			error = SetMinMaxDefValueL<TInt32>( CheckForConstant(aParser),
+   					minVal32, KMinVal32, KMaxVal32, 0 );
+       		if ( error < KErrNone )
+    			{
+    		    User::LeaveIfError( ImportNum( minVal32, aParser ) );
+    			}
+   			error = SetMinMaxDefValueL<TInt32>( CheckForConstant(aParser),
+   					maxVal32, KMinVal32, KMaxVal32, KMaxVal32 );
+       		if ( error < KErrNone )
+    			{
+        		User::LeaveIfError( ImportNum( maxVal32, aParser ) );
+    			}
+		    if ( minVal32 > maxVal32 )
+		    	{
+		    	LogError( KMinMaxWrongValue );
+		    	User::Leave( KErrCorrupt );
+		    	}
+		    if ( ( type == EPropertyInt8 && ( minVal32 < KMinTInt8 || maxVal32 > KMaxTInt8 ) ) ||
+		         ( type == EPropertyUint8 && ( minVal32 < 0 || maxVal32 > KMaxTUint8 ) ) ||
+		         ( type == EPropertyInt16 && ( minVal32 < KMinTInt16 || maxVal32 > KMaxTInt16 ) ) ||
+		         ( type == EPropertyUint16 && ( minVal32 < 0 || maxVal32 > KMaxTUint16 ) ) )
+		    	{
+		    	LogError( KWrongValue );
+		    	User::Leave( KErrCorrupt );
+		    	}
+		    
+		    CheckNoMoreNumericParametersL( aParser );
+    		// Add this property to the previously defined object.
+    		iLastObjectDef->AddPropertyL( name, type, minVal32, maxVal32, readOnly, mandatory, EFalse );
+    		break;
+    		}
+    	case EPropertyText:
+    		{
+    		TInt32  minVal32,
+    		        maxVal32;
+   			error = SetMinMaxDefValueL<TInt32>( CheckForConstant(aParser),
+   					minVal32, 1, KSerializedDesMaxLength, 1 );
+       		if ( error < KErrNone )
+    			{
+    			User::LeaveIfError( ImportNum( minVal32, aParser ) );
+    			}
+   			error = SetMinMaxDefValueL<TInt32>( CheckForConstant(aParser),
+   					maxVal32, 1, KSerializedDesMaxLength, 256 );
+       		if ( error < KErrNone )
+    			{
+    			User::LeaveIfError( ImportNum( maxVal32, aParser ) );
+    			}
+		    if ( minVal32 > maxVal32 )
+		    	{
+		    	LogError( KMinMaxWrongValue );
+		    	User::Leave( KErrCorrupt );
+		    	}
+		    if ( minVal32 < 1 || minVal32 > KSerializedDesMaxLength ||
+		         maxVal32 < 1 || maxVal32 > KSerializedDesMaxLength )
+		    	{
+		    	LogError( KTextWrongValue );
+		    	User::Leave( KErrCorrupt );
+		    	}
+		    
+		    // Text properties may have an extra flag: index flag.
+		    TBool indexed( EFalse );
+		    ImportNum( indexed, aParser );
+    		// Add this property to the previously defined object.
+    		iLastObjectDef->AddPropertyL( name, type, minVal32, maxVal32, readOnly, mandatory, indexed );
+    		break;
+    		}
+    	case EPropertyUint32:
+    		{
+    		TUint32  minVal32,
+    		         maxVal32;
+   			error = SetMinMaxDefValueL<TUint32>( CheckForConstant(aParser),
+   					minVal32, 0, KMaxTUint32, 0 );
+       		if ( error < KErrNone )
+    			{
+    			User::LeaveIfError( ImportUInt32( minVal32, aParser ) );
+    			}
+   			error = SetMinMaxDefValueL<TUint32>( CheckForConstant(aParser),
+   					maxVal32, 0, KMaxTUint32, KMaxTUint32 );
+       		if ( error < KErrNone )
+    			{
+    			User::LeaveIfError( ImportUInt32( maxVal32, aParser ) );
+    			}
+		    if ( minVal32 > maxVal32 )
+		    	{
+		    	LogError( KMinMaxWrongValue );
+		    	User::Leave( KErrCorrupt );
+		    	}
+		    
+		    CheckNoMoreNumericParametersL( aParser );
+    		// Add this property to the previously defined object.
+    		iLastObjectDef->AddPropertyL( name, type, minVal32, maxVal32, readOnly, mandatory, EFalse );
+    		break;
+    		}
+    	case EPropertyInt64:
+    		{
+    		TInt64 minVal64, maxVal64;
+   			error = SetMinMaxDefValueL<TInt64>( CheckForConstant(aParser),
+   					minVal64, KMinTInt64, KMaxTInt64, 0 );
+       		if ( error < KErrNone )
+       			{
+       			User::LeaveIfError( ImportInt64( minVal64, aParser ) );
+       			}
+   			error = SetMinMaxDefValueL<TInt64>( CheckForConstant(aParser),
+   					maxVal64, KMinTInt64, KMaxTInt64, KMaxTInt64 );
+       		if ( error < KErrNone )
+       			{
+       			User::LeaveIfError( ImportInt64( maxVal64, aParser ) );
+       			}
+		    if ( minVal64 > maxVal64 )
+		    	{
+		    	LogError( KMinMaxWrongValue );
+		    	User::Leave( KErrCorrupt );
+		    	}
+		    
+		    CheckNoMoreNumericParametersL( aParser );
+    		// Add this property to the previously defined object.
+    		iLastObjectDef->AddPropertyL( name, type, minVal64, maxVal64, readOnly, mandatory, EFalse );
+    		break;
+    		}
+    	case EPropertyTime:
+    		{
+    		TTime minTime, maxTime;
+   			error = SetMinMaxDefValueL<TTime>( CheckForConstant(aParser),
+   					minTime, 0, KMaxTInt64, 0 );
+       		if ( error < KErrNone )
+       			{
+       			User::LeaveIfError( ImportTime( minTime, aParser ) );
+       			}
+   			error = SetMinMaxDefValueL<TTime>( CheckForConstant(aParser),
+   					maxTime, 0, KMaxTInt64, KMaxTInt64 );
+       		if ( error < KErrNone )
+       			{
+       			User::LeaveIfError( ImportTime( maxTime, aParser ) );
+       			}
+		    if ( minTime > maxTime )
+		    	{
+		    	LogError( KMinMaxWrongValue );
+		    	User::Leave( KErrCorrupt );
+		    	}
+		    
+		    CheckNoMoreNumericParametersL( aParser );
+    		// Add this property to the previously defined object.
+    		iLastObjectDef->AddPropertyL( name, type, minTime.Int64(), maxTime.Int64(), readOnly, 
+    				mandatory, EFalse );
+    		break;
+    		}
+    	case EPropertyReal32:
+    		{
+    		TReal32 minReal, maxReal;
+   			error = SetMinMaxDefValueL<TReal32>( CheckForConstant(aParser),
+   					minReal, -KMaxTReal32, KMaxTReal32, 0 );
+       		if ( error < KErrNone )
+       			{
+       			User::LeaveIfError( ImportNum( minReal, aParser ) );
+       			}
+   			error = SetMinMaxDefValueL<TReal32>( CheckForConstant(aParser),
+   					maxReal, -KMaxTReal32, KMaxTReal32, KMaxTReal32 );
+       		if ( error < KErrNone )
+       			{
+       			User::LeaveIfError( ImportNum( maxReal, aParser ) );
+       			}
+		    if ( minReal > maxReal )
+		    	{
+		    	LogError( KMinMaxWrongValue );
+		    	User::Leave( KErrCorrupt );
+		    	}
+		    
+		    CheckNoMoreNumericParametersL( aParser );
+    		// Add this property to the previously defined object.
+    		iLastObjectDef->AddPropertyL( name, type, minReal, maxReal, readOnly, mandatory, EFalse );
+    		break;
+    		}
+    	case EPropertyReal64:
+    		{
+    		const TReal64 KMDSMaxTReal64( 1.79769313486200E+308 );
+    		TReal64 minReal, maxReal;
+   			error = SetMinMaxDefValueL<TReal64>( CheckForConstant(aParser),
+   					minReal, -KMDSMaxTReal64, KMDSMaxTReal64, 0 );
+       		if ( error < KErrNone )
+       			{
+       			User::LeaveIfError( ImportNum( minReal, aParser ) );
+       			}
+   			error = SetMinMaxDefValueL<TReal64>( CheckForConstant(aParser),
+   					maxReal, -KMDSMaxTReal64, KMDSMaxTReal64, KMDSMaxTReal64 );
+       		if ( error < KErrNone )
+       			{
+       			User::LeaveIfError( ImportNum( maxReal, aParser ) );
+       			}
+		    if ( minReal > maxReal )
+		    	{
+		    	LogError( KMinMaxWrongValue );
+		    	User::Leave( KErrCorrupt );
+		    	}
+		    
+		    CheckNoMoreNumericParametersL( aParser );
+    		// Add this property to the previously defined object.
+    		iLastObjectDef->AddPropertyL( name, type, minReal, maxReal, readOnly, mandatory, EFalse );
+    		break;
+    		}
+    	default:
+    		User::Leave( KErrNotFound );
+    	}
+	}
+
+// ------------------------------------------------
+// CheckNoIndexFlagL
+// ------------------------------------------------
+//
+void CMdsImportExport::CheckNoMoreNumericParametersL( TLex8& aParser )
+	{
+	// This function is used to check that indexing flag is not set for other than
+	// text properties.
+	TBool parameterFound( EFalse );
+	TInt err = ImportNum( parameterFound, aParser );
+	if ( err == KErrNone )
+		{
+		// Index boolean not supported for other property types than text.
+		User::Leave( KErrNotSupported );
+		}
+	}
+
+// ------------------------------------------------
+// ImportSchemaRelationDefL
+// ------------------------------------------------
+//
+void CMdsImportExport::ImportSchemaRelationDefL( TLex8& aParser )
+    {
+    // relationdef <ns> <name>
+    TBuf16<KMdsMaxUriLenght> name;
+    // read namespace
+    User::LeaveIfError( ImportText( name, aParser ) );
+
+	CMdsNamespaceDef* actualNamespace = iSchema->GetNamespace( name );
+	if ( !actualNamespace )
+		{
+		_LIT( KMdsNamespaceNotFound, "Namespace not found !!!" );
+		LogError( KMdsNamespaceNotFound );
+    	User::Leave( KErrAccessDenied );
+		}
+
+    if( actualNamespace->GetReadOnly() && !actualNamespace->GetFirstRead() )
+    	{
+    	_LIT( KError, "Namespace not allowed" );
+    	LogError( KError );
+    	User::Leave( KErrAccessDenied );
+    	}
+
+    // read name
+    User::LeaveIfError( ImportText( name, aParser ) );
+
+	actualNamespace->AddRelationDefL( name );
+    }
+
+// ------------------------------------------------
+// ImportSchemaEventDefL
+// ------------------------------------------------
+//
+void CMdsImportExport::ImportSchemaEventDefL( TLex8& aParser )
+    {
+    // eventdef <ns> <name> <priority>
+    TBuf16<KMdsMaxUriLenght> name;
+    User::LeaveIfError( ImportText( name, aParser ) );
+
+	CMdsNamespaceDef* actualNamespace = iSchema->GetNamespace( name );
+	if ( !actualNamespace )
+		{
+		_LIT( KMdsNamespaceNotFound, "Namespace not found !!!" );
+		LogError( KMdsNamespaceNotFound );
+    	User::Leave( KErrAccessDenied );
+		}
+
+    if ( actualNamespace->GetReadOnly() && !actualNamespace->GetFirstRead() )
+    	{
+    	_LIT( KError, "Namespace not allowed" );
+    	LogError( KError );
+    	User::Leave( KErrAccessDenied );
+    	}
+
+    User::LeaveIfError( ImportText( name, aParser ) );
+    
+    TInt32 priority=0;
+    User::LeaveIfError( ImportNum( priority, aParser ) );
+
+	actualNamespace->AddEventDefL( name, priority );
+    }
+
+void CMdsImportExport::ImportSchemaVersionL( TLex8& aParser )
+	{
+	if ( iVersionFlags & EVersionAlreadyRead )
+		{
+		_LIT( KError, "Schema version redefined" );
+		LogError( KError );
+		User::Leave( KErrCorrupt );
+		}
+    TBuf16<KMdsMaxUriLenght> version;
+    User::LeaveIfError( ImportText( version, aParser ) );
+
+	// convert version to two numbers
+	TInt32 majorVersion, minorVersion;
+	TLex16 parser( version );
+	User::LeaveIfError( parser.BoundedVal( majorVersion, KMaxTInt ) );
+	parser.Get();
+	User::LeaveIfError( parser.BoundedVal( minorVersion, KMaxTInt ) );
+
+	if ( KSchemaFileMajorVersion != majorVersion )
+		{
+		_LIT( KError, "Schema version mismatch" );
+		LogError( KError );
+		User::Leave( KErrCorrupt );
+		}
+
+    MMdsPreferences::InsertL( KMdsSchemaVersionName, MMdsPreferences::EPreferenceBothSet,
+    		majorVersion, minorVersion );
+
+	iVersionFlags |= EVersionAlreadyRead;
+	}
+
+void CMdsImportExport::ImportNamespaceFromDBL()
+	{
+	_LIT( MdsQueryGetNamespaceDefs, "SELECT NamespaceDefID,ReadOnly,VendorId,Name FROM NamespaceDef;" );
+	TDefId namespaceDefId = KNoDefId;
+	TInt32 vendorId = 0;
+	TInt32 namespaceReadOnly = 0;
+	TPtrC namespaceName;
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	// importing namespaces
+	RRowData emptyData;
+	CleanupClosePushL( emptyData );
+	RRowData getData;
+	CleanupClosePushL( getData );
+	getData.AppendL( TColumn( namespaceDefId ) );
+	getData.AppendL( TColumn( namespaceReadOnly ) );
+	getData.AppendL( TColumn( vendorId ) );
+	getData.AppendL( TColumn( EColumnHBuf16 ) );
+	RMdsStatement query;
+	CleanupClosePushL( query );
+	connection.ExecuteQueryL( MdsQueryGetNamespaceDefs, query, emptyData );
+	
+	// read query results and add namespaces to the schema
+	while( connection.NextRowL( query, getData ) )
+		{
+		getData.Column( 0 ).Get( namespaceDefId );
+		getData.Column( 1 ).Get( namespaceReadOnly );
+		getData.Column( 2 ).Get( vendorId );
+		getData.Column( 3 ).Get( namespaceName );
+		CMdsNamespaceDef* nmsp = iSchema->NamespaceAddL( namespaceName,
+				namespaceReadOnly ? ETrue : EFalse, vendorId, namespaceDefId );
+		if ( !nmsp )
+			{
+			User::Leave( KErrGeneral );
+			}
+		nmsp->UnsetFirstRead();
+		getData.Column( 3 ).Free();
+		}
+	CleanupStack::PopAndDestroy( 3, &emptyData ); // query, getData, emptyData
+	}
+
+TBool CMdsImportExport::ImportCheckVersionInfoL()
+	{
+	TInt32 majorVersion = 0;
+	TInt64 minorVersion = 0;
+
+	// DB version
+    MMdsPreferences::GetL( KMdsDBVersionName, MMdsPreferences::EPreferenceBothGet,
+    						  majorVersion, &minorVersion );
+	if ( majorVersion != KMdSServMajorVersionNumber && (TInt)minorVersion != KMdSServMinorVersionNumber )
+		{
+		return EFalse;
+		}
+
+	// schema version
+    MMdsPreferences::GetL( KMdsSchemaVersionName, MMdsPreferences::EPreferenceBothGet,
+    						  majorVersion, &minorVersion );
+	if ( majorVersion == KSchemaFileMajorVersion )
+		{
+		return ETrue;
+		}
+
+	return EFalse;
+	}
+
+void CMdsImportExport::ImportSchemaFromDBL( CMdsSchema& aSchema )
+	{
+	// clear iSchema (we read everything from DB)
+	if ( !aSchema.iBaseObject )
+		{
+		iSchema->AddDefaultObjectL();
+		iSchema->iBaseObject->SetStoredEveryInDB();
+		aSchema.iBaseObject = iSchema->iBaseObject;
+		}
+    else
+    	{
+    	iSchema->iBaseObject = aSchema.iBaseObject;
+    	}
+	iSchema->Reset();
+
+	if ( !ImportCheckVersionInfoL() )
+		{
+	    iSchema->iBaseObject = NULL;
+    	User::Leave( KErrCorrupt );
+		}
+
+	TRAPD( err, ImportNamespaceFromDBL() );
+	if ( err != KErrNone )
+		{
+	    iSchema->iBaseObject = NULL;
+    	User::Leave( err );
+		}
+
+	const TInt count = iSchema->iNamespaceDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		CMdsNamespaceDef* namespaceDef = iSchema->iNamespaceDefs[i];
+		TRAP( err, namespaceDef->ImportFromDBL() );
+		if ( err != KErrNone )
+			{
+	    	iSchema->iBaseObject = NULL;
+	    	User::Leave( err );
+			}
+		}
+
+    TRAP( err, aSchema.MergeNamespacesL( *iSchema ) );
+   	iSchema->iBaseObject = NULL;
+    if ( err != KErrNone )
+    	{
+    	User::Leave( err );
+    	}
+	}
+
+
+TBool CMdsImportExport::ReadMetadataFileLineL()
+	{
+	if ( iLastLineProcessed )
+		{
+		TRAPD( e, iReadStream.ReadL( iLine, KMdsLineFeed ) );
+		if ( e == KErrEof )
+            {
+			return EFalse; // succesful exit
+            }
+		else if ( e != KErrNone )
+		    {
+		    iDefaultSchema = NULL;
+		    User::Leave( e );
+		    }
+	    iLastLineProcessed = EFalse;
+		}
+    ++iLineNumber;
+	return ETrue;
+	}
+
+TInt CMdsImportExport::ImportMetadataL( CMdSSqlObjectManipulate& aManipulate,
+    CMdsSchema& aSchemaNew, const TDesC16& aFileName )
+	{
+	iReadStream.PushL();
+    User::LeaveIfError( iReadStream.Open( iFs, aFileName, EFileStreamText ) );
+    iFileName.Copy( aFileName );
+
+	if ( !iBuffer )
+        {
+		iBuffer = CMdCSerializationBuffer::NewL( 8192 ); // 8kB - should be enough
+        }
+
+	iDefaultSchema = &aSchemaNew;
+    iLineNumber = 0;
+    iFailed = 0;
+    while( ReadMetadataFileLineL() )
+        {
+        if ( iLine.Length() > 0 )
+            {
+            // parse the line
+            TLex8 parser( iLine );
+            TRAPD( e, ImportMetadataItemL( parser, aManipulate ) );
+            if ( e != KErrNone )
+            	{
+			    ++iFailed;
+            	}
+            }
+		else
+        	iLastLineProcessed = ETrue;
+        }
+
+	iDefaultSchema = NULL;
+    CleanupStack::PopAndDestroy( &iReadStream ); // Closes stream.
+    return iFailed;
+	}
+
+void CMdsImportExport::ImportMetadataItemL( TLex8& aParser, CMdSSqlObjectManipulate& aManipulate )
+	{
+    TPtrC8 token = aParser.NextToken();
+
+    // valid keywords in beginning of line
+    if ( token.Length() == 0 || token.Left(2) == KMdsKeywordComment )
+        {
+        // ignore
+        iLastLineProcessed = ETrue;
+        return;
+        }
+    else if ( token == KMdsKeywordObject )
+        {
+        TRAPD( err, ImportMetadataFileObjectL( aParser, aManipulate ) );
+        if (err != KErrNone)
+        	{
+        	_LIT( KError, "Object error" );
+     		LogError( KError );
+			User::Leave( err );
+        	}
+        }
+    else if ( token == KMdsKeywordRelation )
+        {
+        TRAPD( err, ImportMetadataFileRelationL( aParser, aManipulate ) );
+        if (err != KErrNone)
+        	{
+        	_LIT( KError, "Relation error" );
+     		LogError( KError );
+			User::Leave( err );
+        	}
+        }
+    else if ( token == KMdsKeywordEvent )
+        {
+		TRAPD( err, ImportMetadataFileEventL( aParser, aManipulate ) );
+        if (err != KErrNone)
+        	{
+        	_LIT( KError, "Relation error" );
+     		LogError( KError );
+			User::Leave( err );
+        	}
+        }
+    else
+        {
+        iLastLineProcessed = ETrue;
+        _LIT( KError, "Keyword not recognized" );
+        LogError( KError );
+        User::Leave( KErrCorrupt );
+        }
+    TPtrC8 tokenLast = aParser.NextToken();
+    if ( tokenLast.Length() != 0 && tokenLast.Left(2) != KMdsKeywordComment )
+    	{
+    	_LIT( KMdsUnknownToken, "Undefined metadata file item" );
+    	LogError( KMdsUnknownToken );
+    	User::Leave( KErrCorrupt );
+    	}
+	}
+
+void CMdsImportExport::AddObjectToDBL( CMdSSqlObjectManipulate& aManipulate, CMdsNamespaceDef* aNamespaceDef )
+	{
+	iLastObjectDef = NULL;
+	iBuffer->PositionL( KNoOffset );
+	TItemId id = KNoId;
+	aManipulate.SetNamespace( aNamespaceDef );
+	RMdsStatement baseObjStmt;
+    CleanupClosePushL(baseObjStmt);
+	RMdsStatement objStmt;
+	CleanupClosePushL(objStmt);
+	
+	TRAPD( err, id = aManipulate.AddObjectL( MMdSDbConnectionPool::GetDefaultDBL(), *iBuffer, baseObjStmt, objStmt ) );
+	
+	CleanupStack::PopAndDestroy(&objStmt);
+	CleanupStack::PopAndDestroy(&baseObjStmt);
+	
+	aManipulate.SetNamespace( NULL );
+	if ( err != KErrNone || id == 0 )
+		{
+		User::Leave( err );
+		}
+	}
+
+void CMdsImportExport::ImportMetadataFileObjectL( TLex8& aParser, CMdSSqlObjectManipulate& aManipulate )
+	{
+	TInt error = KErrNone;
+
+    if ( iLastObjectDef )
+    	{
+   		User::Leave( KErrCorrupt );
+    	}
+	iLastLineProcessed = ETrue;
+
+	TMdCObject object;
+	object.iId = KNoId;
+	object.iFlags = EMdEObjectFlagModOpen;
+	object.iUsageCount = 0;
+	object.iGuidHigh = 0;
+	object.iGuidLow = 0;
+	object.iFreeTexts.iPtr.iCount = 0;
+	object.iFreeTexts.iPtr.iOffset = KNoOffset;
+
+	TMdCOffset freespaceOffset = sizeof(TMdCObject);
+	
+	TBuf16<KMdsMaxUriLenght> textValue;
+
+    // namespace
+    User::LeaveIfError( ImportText( textValue, aParser ) );
+
+    CMdsNamespaceDef* namespaceDef = iDefaultSchema->GetNamespace( textValue );
+	if ( !namespaceDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+    // read object variables
+    // objectDef name
+    User::LeaveIfError( ImportText( textValue, aParser ) );
+    
+    iLastObjectDef = namespaceDef->GetObjectDef( textValue );
+    if ( !iLastObjectDef )
+    	{
+    	User::Leave( KErrNotFound );
+    	}
+    object.iDefId = iLastObjectDef->GetId();
+    
+	// object uri
+	User::LeaveIfError( ImportText( textValue, aParser ) );
+	object.iUri.iPtr.iCount = textValue.Length();
+	object.iUri.iPtr.iOffset = freespaceOffset;
+	iBuffer->PositionL( freespaceOffset );
+	freespaceOffset = iBuffer->InsertL( textValue );
+
+	// Object must not be context object and 
+	// the length of the URI must be atleast 3 (X:\) 
+	if ( !(iLastObjectDef->GetFlags() & CMdsObjectDef::EObjectDefFlagsContext) && 
+			textValue.Length() >= 3 )
+	    {
+	    // possible drive letter
+	    TChar driveLetter( textValue[0] );
+	    driveLetter.UpperCase();
+	    
+	    // possible colon and backslash
+	    _LIT( KColonBackslashMatch, ":\\" );
+	    TPtrC beginUri = textValue.Mid( 1, KColonBackslashMatch.iTypeLength );
+	    TBool validUri( ETrue );
+	    
+	    // URI must begin with "X:\"
+	    if( 'A' <= driveLetter && driveLetter <= 'Z' && 
+	    		beginUri.Compare( KColonBackslashMatch ) == 0 )
+	    	{
+			// check if uri exists
+	        RFileReadStream tmpFile;
+			TInt err = KErrNone;
+			err = tmpFile.Open( iFs, textValue, EFileRead | EFileShareAny );
+			tmpFile.Close();
+			if ( err != KErrNone )
+				{
+				_LIT( KError, "uri is not real" );
+				validUri = EFalse;
+				LogError( KError );
+				error = err;
+				}
+	    	}
+	    else
+	        {
+	        validUri = EFalse;
+	        }
+	    
+	    if( validUri )
+	        {
+	        User::LeaveIfError( ImportMediaId( object.iMediaId, aParser, driveLetter ) );
+	        }
+	    else
+	        {
+	        User::LeaveIfError( ImportUInt32( object.iMediaId, aParser ) );
+	        }
+	    }
+	else
+	    {
+	    User::LeaveIfError( ImportUInt32( object.iMediaId, aParser ) );
+	    }
+
+    const TUint32 allPropCount = iLastObjectDef->GetAllPropertiesCount();
+    object.iProperties.iPtr.iCount = allPropCount;
+    object.iProperties.iPtr.iOffset = freespaceOffset;
+
+    freespaceOffset += allPropCount * sizeof(TMdCProperty);
+   
+    // set property offset
+	CDesC16ArrayFlat* freeTextBuffer = new(ELeave) CDesC16ArrayFlat(8);
+	CleanupStack::PushL( freeTextBuffer );
+
+	TUint32 propertyCount = 0;
+	while ( ReadMetadataFileLineL() )
+		{
+		TLex8 parser( iLine );
+		TPtrC8 token = parser.NextToken();
+
+	    if ( iLine.Length() == 0 || token.Length() == 0 || token.Left(2) == KMdsKeywordComment )
+	        {
+	        // ignore line
+	        iLastLineProcessed = ETrue;
+	        }
+		// now if exists there should be one or more properties		
+		else if(token == KMdsKeywordProperty )
+			{
+			if ( object.iFreeTexts.iPtr.iOffset != KNoOffset || propertyCount >= allPropCount )
+				{
+				_LIT( KError, "Property after freetext" );
+				LogError( KError );
+				error = KErrCorrupt;
+				}
+			if (error != KErrNone)
+				{
+				// just fetch rest of object lines
+				iLastLineProcessed = ETrue;
+				}
+			else
+				{
+				iBuffer->PositionL( object.iProperties.iPtr.iOffset
+						+ propertyCount * sizeof(TMdCProperty) );
+				TRAP( error, freespaceOffset = ImportMetadataFilePropertyL(
+						parser, freespaceOffset ) );
+				if (error != KErrNone)
+					{
+					_LIT( KError, "Property error" );
+			        LogError( KError );
+					}
+				++propertyCount;
+				}
+			}
+		// and after those there should be freetext
+		else if ( token == KMdsKeywordFreeText )
+		    {
+			if (error != KErrNone)
+				{
+				// just fetch rest of object lines
+				iLastLineProcessed = ETrue;
+				}
+			else
+				{
+			    if ( object.iFreeTexts.iPtr.iOffset == KNoOffset)
+			    	{
+			    	object.iFreeTexts.iPtr.iOffset = freespaceOffset;
+			    	}
+				else
+					{
+			    	TRAP( error, ImportMetadataFileFreeTextL( parser, *freeTextBuffer ) );
+					if (error != KErrNone)
+						{
+						_LIT( KError, "Freetext error" );
+				        LogError( KError );
+						}
+					}
+				}
+		    }
+		else
+			{
+			if ( token == KMdsKeywordObject || token == KMdsKeywordRelation || token == KMdsKeywordEvent )
+				{
+				break;
+				}
+			iLastLineProcessed = ETrue;
+			}
+		}
+
+	if ( error != KErrNone )
+		{
+		iLastObjectDef = NULL;
+		User::Leave( error );
+		}
+
+	object.iProperties.iPtr.iCount = propertyCount;
+	
+	// add freetext
+	object.iFreeTexts.iPtr.iCount = freeTextBuffer->Count();
+	if ( object.iFreeTexts.iPtr.iCount > 0 )
+		{
+		// set flags
+		object.iFlags |= EMdEObjectFlagFreetexts | EMdEObjectFlagModFreeText;
+
+		iBuffer->PositionL( object.iFreeTexts.iPtr.iOffset );
+		for ( TInt32 i = 0; i < object.iFreeTexts.iPtr.iCount; ++i )
+			{
+			TPtrC16 word = (*freeTextBuffer)[i];
+			iBuffer->InsertL( word );
+			}
+		}
+	else
+		{
+		object.iFreeTexts.iPtr.iOffset = KNoOffset;
+		}
+
+	iBuffer->PositionL( KNoOffset );
+	object.SerializeL( *iBuffer );
+	
+	// add object to DB
+	AddObjectToDBL(aManipulate, namespaceDef);
+
+	CleanupStack::PopAndDestroy( freeTextBuffer );
+	}
+
+TMdCOffset CMdsImportExport::ImportMetadataFilePropertyL( TLex8& aParser, TMdCOffset aFreespaceOffset )
+	{
+    if ( !iLastObjectDef )
+    	{
+    	User::Leave( KErrCorrupt );
+    	}
+	iLastLineProcessed = ETrue;
+	TBuf16<KMdsMaxUriLenght> textValue;
+
+	// property name
+    User::LeaveIfError( ImportText( textValue, aParser ) );
+    
+    _LIT( KGuidHigh, "GuidHigh" );
+    _LIT( KGuidLow, "GuidLow" );
+    
+    if( textValue == KGuidHigh || textValue == KGuidLow )
+    	{
+    	User::Leave( KErrCorrupt );
+    	}
+
+    CMdsPropertyDef* propertyDef = iLastObjectDef->GetProperty( textValue );
+    if ( !propertyDef )
+    	{
+    	User::Leave( KErrCorrupt );
+    	}
+
+    TMdCProperty property;
+    property.iModFlags = EMdEPropertyModChange;
+    property.iPropertyDefId = propertyDef->GetId();
+
+    // find proper place to put property
+    const TMdCOffset propertyOffset = iBuffer->Position();
+
+	switch( propertyDef->GetType() )
+		{
+    	case EPropertyBool:
+    		{
+    		TInt32 intValue;
+		    User::LeaveIfError( ImportNum( intValue, aParser ) );
+    		TBool value = intValue ? ETrue : EFalse;
+    		property.iValue.iInt32 = value;
+    		break;
+    		}
+    	case EPropertyInt8:
+    		{
+    		TInt32 intValue;
+		    User::LeaveIfError( ImportNum( intValue, aParser ) );
+    		property.iValue.iInt32 = intValue;
+    		break;
+    		}
+    	case EPropertyUint8:
+    		{
+    		TInt32 intValue;
+		    User::LeaveIfError( ImportNum( intValue, aParser ) );
+    		property.iValue.iUint32 = intValue;
+    		break;
+    		}
+    	case EPropertyInt16:
+    		{
+    		TInt32 intValue;
+		    User::LeaveIfError( ImportNum( intValue, aParser ) );
+    		property.iValue.iInt32 = intValue;
+    		break;
+    		}
+    	case EPropertyUint16:
+    		{
+    		TInt32 intValue;
+		    User::LeaveIfError( ImportNum( intValue, aParser ) );
+    		property.iValue.iUint32 = intValue;
+    		break;
+    		}
+    	case EPropertyInt32:
+    		{
+    		TInt32 value;
+		    User::LeaveIfError( ImportNum( value, aParser ) );
+    		property.iValue.iInt32 = value;
+    		break;
+    		}
+    	case EPropertyUint32:
+    		{
+    		TUint32 value;
+		    User::LeaveIfError( ImportUInt32( value, aParser ) );
+    		property.iValue.iUint32 = value;
+    		break;
+    		}
+    	case EPropertyInt64:
+    		{
+    		TInt64 value;
+		    User::LeaveIfError( ImportInt64( value, aParser ) );
+    		property.iValue.iInt64 = value;
+    		break;
+    		}
+    	case EPropertyTime:
+    		{
+    		TTime value;
+		    User::LeaveIfError( ImportTime( value, aParser ) );
+    		property.iValue.iInt64 = value.Int64();
+    		break;
+    		}
+    	case EPropertyReal32:
+    		{
+    		TReal32 value;
+		    User::LeaveIfError( ImportNum( value, aParser ) );
+    		property.iValue.iReal = value;
+    		break;
+    		}
+    	case EPropertyReal64:
+    		{
+    		TReal64 value;
+		    User::LeaveIfError( ImportNum( value, aParser ) );
+    		property.iValue.iReal = value;
+    		break;
+    		}
+    	case EPropertyText:
+    		{
+			TBuf16<256> value;
+    		User::LeaveIfError( ImportText( value, aParser ) );
+    		property.iValue.iPtr.iCount = value.Length();
+    		if (property.iValue.iPtr.iCount > 0)
+    			{
+    			property.iValue.iPtr.iOffset = aFreespaceOffset;
+    			iBuffer->PositionL( aFreespaceOffset );
+    			aFreespaceOffset = iBuffer->InsertL( value );
+    			}
+    		else
+    			{
+    			User::Leave( KErrCorrupt );
+    			}
+    		break;
+    		}
+    	default:
+    		User::Leave( KErrNotFound );
+		}
+
+	iBuffer->PositionL( propertyOffset );
+	property.SerializeL( *iBuffer );
+	
+	return aFreespaceOffset;
+	}
+
+void CMdsImportExport::ImportMetadataFileFreeTextL( TLex8& aParser, CDesC16ArrayFlat& aFreeTextArray )
+	{
+    if ( !iLastObjectDef )
+    	{
+    	User::Leave( KErrCorrupt );
+    	}
+	iLastLineProcessed = ETrue;
+
+	TBuf16<256> freeText;
+	while( ImportText( freeText, aParser ) == KErrNone )
+		{
+		aFreeTextArray.AppendL( freeText );
+		}
+	}
+
+void CMdsImportExport::ImportMetadataFileRelationL( TLex8& aParser, CMdSSqlObjectManipulate& aManipulate )
+	{
+	_LIT( KImportRelationGetObjectId, "SELECT ObjectId FROM Object%u WHERE URI=? LIMIT 1;" );
+    if(iLastObjectDef)
+    	{
+   		User::Leave( KErrCorrupt );
+    	}
+	iLastLineProcessed = ETrue;
+
+	CMdsClauseBuffer* clauseBuffer = CMdsClauseBuffer::NewLC( KImportRelationGetObjectId.iTypeLength + 10 ); // one uint
+
+	TBuf16<KMdsMaxUriLenght> textValue;
+
+	// namespace
+    User::LeaveIfError( ImportText( textValue, aParser ) );
+
+    CMdsNamespaceDef* namespaceDef = iDefaultSchema->GetNamespace( textValue );
+	if ( !namespaceDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	clauseBuffer->BufferL().Format( KImportRelationGetObjectId, namespaceDef->GetId() );
+
+	TMdCRelation relation;
+	relation.iId = KNoId;
+	relation.iGuidHigh = 0;
+	relation.iGuidLow = 0;
+	relation.iLastModifiedDate.UniversalTime();
+
+    // read relation variables
+    // relationDef name
+    User::LeaveIfError( ImportText( textValue, aParser ) );
+    CMdsRelationDef* relationDef = namespaceDef->GetRelationDef( textValue );
+    if ( !relationDef )
+    	{
+    	User::Leave( KErrNotFound );
+    	}
+    relation.iDefId = relationDef->GetId();
+
+	RRowData dataRow;
+	CleanupClosePushL( dataRow );
+	RMdsStatement query;
+	CleanupClosePushL( query );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	// left object name
+	User::LeaveIfError( ImportText( textValue, aParser ) );
+	relation.iLeftObjectId = KNoId;
+
+	dataRow.AppendL( TColumn( textValue ) );
+	connection.ExecuteQueryL( clauseBuffer->ConstBufferL(), query, dataRow );
+	dataRow.Free();
+	dataRow.Column( 0 ).Set( relation.iLeftObjectId );
+	if( connection.NextRowL( query, dataRow ) )
+		{
+		dataRow.Column( 0 ).Get( relation.iLeftObjectId );
+		}
+	if (relation.iLeftObjectId == KNoId)
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	// right object name
+	User::LeaveIfError( ImportText( textValue, aParser ) );
+	relation.iRightObjectId = KNoId;
+	dataRow.Column( 0 ).Set( textValue );
+
+	connection.ExecuteQueryL( clauseBuffer->ConstBufferL(), query, dataRow );
+	dataRow.Free();
+	dataRow.Column( 0 ).Set( relation.iLeftObjectId );
+	if( connection.NextRowL( query, dataRow ) )
+		{
+		dataRow.Column( 0 ).Get( relation.iRightObjectId );
+		}
+	if (relation.iRightObjectId == KNoId)
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	CleanupStack::PopAndDestroy( 2, &dataRow ); // query, dataRow
+
+	relation.iParameter = 0;
+	User::LeaveIfError( ImportNum( relation.iParameter, aParser ) );
+
+	iBuffer->PositionL( KNoOffset );
+	relation.SerializeL( *iBuffer );
+
+	TItemId id = KNoId;
+	iBuffer->PositionL( KNoOffset );
+	aManipulate.SetNamespace( namespaceDef );
+	TRAPD( err, id = aManipulate.AddRelationL( connection, *iBuffer ) );
+	aManipulate.SetNamespace( NULL );
+	if (err != KErrNone || id == KNoId)
+		{
+		User::Leave( err );
+		}
+	CleanupStack::PopAndDestroy( clauseBuffer ); // clauseBuffer
+	}
+
+void CMdsImportExport::ImportMetadataFileEventL( TLex8& aParser, CMdSSqlObjectManipulate& aManipulate )
+	{
+	_LIT( KImportEventGetObjectId, "SELECT ObjectId FROM Object%u WHERE URI=? LIMIT 1;" );
+    if ( iLastObjectDef )
+    	{
+   		User::Leave( KErrCorrupt );
+    	}
+	iLastLineProcessed = ETrue;
+
+	CMdsClauseBuffer* clauseBuffer = CMdsClauseBuffer::NewLC( KImportEventGetObjectId.iTypeLength + 10 ); // one uint
+
+	TBuf16<KMdsMaxUriLenght> textValue;
+
+	// namespace
+    User::LeaveIfError( ImportText( textValue, aParser ) );
+
+    CMdsNamespaceDef* namespaceDef = iDefaultSchema->GetNamespace( textValue );
+	if ( !namespaceDef )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	clauseBuffer->BufferL().Format( KImportEventGetObjectId, namespaceDef->GetId() );
+
+	TMdCEvent event;
+	event.iId = KNoId;
+
+    // read event variables
+    // eventDef name
+    User::LeaveIfError( ImportText( textValue, aParser ) );
+    CMdsEventDef* eventDef = namespaceDef->GetEventDef( textValue );
+    if ( !eventDef )
+    	{
+    	User::Leave( KErrNotFound );
+    	}
+    event.iDefId = eventDef->GetId();
+
+	RRowData dataRow;
+	CleanupClosePushL( dataRow );
+	RMdsStatement query;
+	CleanupClosePushL( query );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	// object name
+	User::LeaveIfError( ImportText( textValue, aParser ) );
+	event.iObjectId = KNoId;
+
+	dataRow.AppendL( TColumn( textValue ) );
+	connection.ExecuteQueryL( clauseBuffer->ConstBufferL(), query, dataRow );
+	dataRow.Free();
+	dataRow.Column( 0 ).Set( event.iObjectId );
+	if ( connection.NextRowL( query, dataRow ) )
+		{
+		dataRow.Column( 0 ).Get( event.iObjectId );
+		}
+	if ( event.iObjectId == KNoId )
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	CleanupStack::PopAndDestroy( 2, &dataRow ); // query, dataRow
+
+	TMdCOffset freespaceOffset = sizeof(TMdCEvent);
+	// source
+	User::LeaveIfError( ImportText( textValue, aParser ) );
+	event.iSourceText.iPtr.iCount = textValue.Length();
+	if (event.iSourceText.iPtr.iCount > 0)
+		{
+		event.iSourceText.iPtr.iOffset = freespaceOffset;
+		iBuffer->PositionL( freespaceOffset );
+		freespaceOffset = iBuffer->InsertL( textValue );
+		}
+	else
+		{
+		event.iSourceText.iPtr.iOffset = KNoOffset;
+		}
+
+	// participant
+	User::LeaveIfError( ImportText( textValue, aParser ) );
+	event.iParticipantText.iPtr.iCount = textValue.Length();
+	if (event.iParticipantText.iPtr.iCount > 0)
+		{
+		event.iParticipantText.iPtr.iOffset = freespaceOffset;
+		iBuffer->PositionL( freespaceOffset );
+		freespaceOffset = iBuffer->InsertL( textValue );
+		}
+	else
+		{
+		event.iParticipantText.iPtr.iOffset = KNoOffset;
+		}
+
+	// time
+	User::LeaveIfError( ImportTime( event.iTime, aParser ) );
+
+	iBuffer->PositionL( KNoOffset );
+	event.SerializeL( *iBuffer );
+
+	TItemId id = KNoId;
+	iBuffer->PositionL( KNoOffset );
+	aManipulate.SetNamespace( namespaceDef );
+	TRAPD( err, id = aManipulate.AddEventL( connection, *iBuffer ) );
+	aManipulate.SetNamespace( NULL );
+	if (err != KErrNone || id == KNoId)
+		{
+		User::Leave( err );
+		}
+
+	CleanupStack::PopAndDestroy( clauseBuffer ); // clauseBuffer
+	}
+
+void CMdsImportExport::ExportMetadataL( CMdsSchema& aSchemaNew, const TDesC16& aFileName,
+										CMdCSerializationBuffer& aItems )
+	{
+	iFs.PrivatePath( iFileName );
+	if ( aFileName.Find(iFileName) != KErrNotFound )
+		{
+		User::Leave( KErrAccessDenied );
+		}
+
+	CleanupClosePushL( iWriteStream );
+    User::LeaveIfError( iWriteStream.Replace( iFs, aFileName, EFileShareExclusive | EFileStreamText | EFileWrite ) );
+
+	// reading import "filters"
+	aItems.PositionL( KNoOffset ); // start from the beginning of buffer
+	const TMdCItemIds& itemIds = TMdCItemIds::GetFromBufferL( aItems ); // read item ids from buffer
+	const CMdsNamespaceDef* namespaceDefRestrict = NULL;
+	if ( itemIds.iNamespaceDefId != KNoDefId )
+		{
+		namespaceDefRestrict = aSchemaNew.GetNamespaceByIdL( itemIds.iNamespaceDefId );
+		}
+
+	RPointerArray<CMdsObjectDef>   objectDefToExport;
+	CleanupClosePushL( objectDefToExport );
+	RPointerArray<CMdsEventDef>    eventDefToExport;
+	CleanupClosePushL( eventDefToExport );
+	RPointerArray<CMdsRelationDef> relationDefToExport;
+	CleanupClosePushL( relationDefToExport );
+
+	// Get all object definitions from buffer.
+	if ( itemIds.iObjectIds.iPtr.iCount > 0 )
+		{
+		if ( !namespaceDefRestrict )
+			{
+			User::Leave( KErrCorrupt );
+			}
+		objectDefToExport.ReserveL( itemIds.iObjectIds.iPtr.iCount );
+		aItems.PositionL( itemIds.iObjectIds.iPtr.iOffset );
+		TDefId objectDefId;
+		for ( TInt i = 0; i < itemIds.iObjectIds.iPtr.iCount; ++i )
+			{
+			aItems.ReceiveL( objectDefId );
+			const CMdsObjectDef* objectDef = namespaceDefRestrict->GetObjectByIdL( objectDefId );
+			if (objectDef)
+				{
+				objectDefToExport.Append( objectDef );
+				}
+			}
+		}
+
+	// Get all event definitions from buffer.
+	if ( itemIds.iEventIds.iPtr.iCount > 0 )
+		{
+		if (!namespaceDefRestrict)
+			{
+			User::Leave( KErrCorrupt );
+			}
+		eventDefToExport.ReserveL( itemIds.iEventIds.iPtr.iCount );
+		aItems.PositionL( itemIds.iEventIds.iPtr.iOffset );
+		TDefId eventDefId;
+		for ( TInt i = 0; i < itemIds.iEventIds.iPtr.iCount; ++i )
+			{
+			aItems.ReceiveL( eventDefId );
+			const CMdsEventDef* eventDef = namespaceDefRestrict->GetEventByIdL( eventDefId );
+			if (eventDef)
+				{
+				eventDefToExport.Append( eventDef );
+				}
+			}
+		}
+
+	// Get all relation definitions from buffer.
+	if ( itemIds.iRelationIds.iPtr.iCount > 0 )
+		{
+		if ( !namespaceDefRestrict )
+			{
+			User::Leave( KErrCorrupt );
+			}
+		relationDefToExport.ReserveL( itemIds.iRelationIds.iPtr.iCount );
+		aItems.PositionL( itemIds.iRelationIds.iPtr.iOffset );
+		TDefId relationDefId;
+		for ( TInt i = 0; i < itemIds.iRelationIds.iPtr.iCount; ++i )
+			{
+			aItems.ReceiveL( relationDefId );
+			const CMdsRelationDef* relationDef = namespaceDefRestrict->GetRelationByIdL( relationDefId );
+			if ( relationDef )
+				{
+				relationDefToExport.Append( relationDef );
+				}
+			}
+		}
+
+	CMdsClauseBuffer* clause = CMdsClauseBuffer::NewLC( 2048 );
+	CMdsClauseBuffer* freeTextClause = CMdsClauseBuffer::NewLC( 512 );
+
+	RRowData dataRow;
+	CleanupClosePushL( dataRow );
+	RRowData freeTextRow;
+	CleanupClosePushL( freeTextRow );
+
+	TInt j;
+	
+	const TInt namespaceCount = aSchemaNew.iNamespaceDefs.Count();
+	
+	for ( TInt i = 0; i < namespaceCount; ++i )
+		{
+		CMdsNamespaceDef* namespaceDef = aSchemaNew.iNamespaceDefs[i];
+		if ( namespaceDefRestrict && namespaceDefRestrict != namespaceDef )
+			{
+			continue;
+			}
+
+		ExportMetadataMakeFreeTextSqlClauseL( *namespaceDef, *freeTextClause, freeTextRow );
+		// writing object information
+		
+		const TInt objectDefCount = namespaceDef->iObjectDefs.Count();
+		
+		for ( j = 0; j < objectDefCount; ++j )
+			{
+			CMdsObjectDef* objectDef = namespaceDef->iObjectDefs[j];
+			if ( !namespaceDefRestrict || objectDefToExport.Count() == 0 || objectDefToExport.Find( objectDef ) != KErrNotFound )
+				{
+				ExportMetadataMakeSqlObjectClauseL( *namespaceDef, *objectDef, *clause, dataRow );
+				ExportMetadataWriteObjectInfoL( *namespaceDef, *objectDef, *clause, dataRow, *freeTextClause, freeTextRow );
+				}
+			}
+
+		// writing relation information
+		ExportMetadataMakeSqlRelationClauseL( *namespaceDef, *clause, dataRow );
+		
+		const TInt relationDefCount = namespaceDef->iRelationDefs.Count();
+		
+		for ( j = 0; j < relationDefCount; ++j )
+			{
+			CMdsRelationDef* relationDef = namespaceDef->iRelationDefs[j];
+			if ( !namespaceDefRestrict || relationDefToExport.Count() == 0 || relationDefToExport.Find( relationDef ) != KErrNotFound )
+				{
+				ExportMetadataWriteRelationInfoL( *namespaceDef, *relationDef, *clause, dataRow );
+				}
+			if ( j == namespaceDef->iRelationDefs.Count() - 1 )
+				{
+				iWriteStream.WriteL( KExportMetadataNewLine );
+				}
+			}
+
+		// writing event information
+		ExportMetadataMakeSqlEventClauseL( *namespaceDef, *clause, dataRow );
+		
+		const TInt eventDefCount = namespaceDef->iEventDefs.Count();
+		
+		for ( j = 0; j < eventDefCount; ++j )
+			{
+			CMdsEventDef* eventDef = namespaceDef->iEventDefs[j];
+			if ( !namespaceDefRestrict || eventDefToExport.Count() == 0 || eventDefToExport.Find( eventDef ) != KErrNotFound )
+				{
+				ExportMetadataWriteEventInfoL( *namespaceDef, *eventDef, *clause, dataRow );
+				}
+			}
+		}
+
+    CleanupStack::PopAndDestroy( 8, &iWriteStream ); // freeTextRow, dataRow, freeTextClause, clause, relationDefToExport, eventDefToExport, objectDefToExport, iWriteStream
+	}
+
+void CMdsImportExport::ExportMetadataMakeSqlObjectClauseL( const CMdsNamespaceDef& aNamespaceDef, const CMdsObjectDef& aObjectDef,
+														  CMdsClauseBuffer& aClause, RRowData& aDataRow )
+	{
+	_LIT( KExportMetadataNotConfidential, " NOT (Flags&? OR Flags&? OR Flags&?);" );
+	aClause.BufferL().Zero(); // reset clause
+	aDataRow.Free(); // free and reset dataRow
+	aDataRow.Reset();
+	
+	aClause.AppendL( KSelectPropertyFilterBegin );
+	aDataRow.AppendL( TColumn( TItemId(0) ) ); // objectId
+	aDataRow.AppendL( TColumn( TDefId(0) ) ); // objectDefId
+	aDataRow.AppendL( TColumn( TUint32(0) ) ); // objectFlags
+	aDataRow.AppendL( TColumn( TUint32(0) ) ); // objectMediaId
+	aDataRow.AppendL( TColumn( TUint32(0) ) ); // usageCount
+	aDataRow.AppendL( TColumn( TInt64(0) ) ); // objectGuidHigh
+	aDataRow.AppendL( TColumn( TInt64(0) ) ); // objectGuidLow
+	aDataRow.AppendL( TColumn( EColumnDes16 ) ); // objectURI
+
+	const TInt allPropertiesCount = aObjectDef.GetAllPropertiesCount();
+	for ( TInt i = 0; i < allPropertiesCount; ++i )
+		{
+		const CMdsObjectDef::TMdsColumnOrder& column = aObjectDef.GetPropertyColumnL( i );
+		const CMdsPropertyDef& property = column.iPropertyDef;
+
+		aClause.AppendL( KComma );
+		aClause.AppendL( property.GetName() );
+
+		aDataRow.AppendL( TColumn( property.GetSqlType() ) );
+		}
+	aClause.AppendL( KSpace );
+
+	aClause.AppendL( KFromBaseObject, KMaxUintValueLength ); // + namespace id
+	aClause.BufferL().AppendNum( aNamespaceDef.GetId() );
+	aClause.AppendL( KAsBaseObject );
+
+	aClause.AppendL( KComma );
+	aClause.AppendL( aObjectDef.GetName(), KMaxUintValueLength ); // + namespace id
+	aClause.BufferL().AppendNum( aNamespaceDef.GetId() );
+
+	aClause.AppendL( KAsObjectOnEqual );
+
+	aClause.AppendL( KWhere );
+	aClause.AppendL( KSpace );
+	aClause.AppendL( KExportMetadataNotConfidential );
+	}
+
+void CMdsImportExport::ExportMetadataMakeFreeTextSqlClauseL( const CMdsNamespaceDef& aNamespaceDef,
+															CMdsClauseBuffer& aFreeTextClause, RRowData& aFreeTextRow )
+	{
+	_LIT( KExportMetadataFreeTextSearch,
+		  "SELECT Word FROM TextSearchDictionary%u WHERE WordId IN (SELECT WordId FROM TextSearch%u WHERE ObjectId = ?);" );
+
+	aFreeTextClause.BufferL().Zero();
+	aFreeTextClause.ReserveSpaceL( KExportMetadataFreeTextSearch.iTypeLength + 2*KMaxUintValueLength );
+
+	aFreeTextClause.BufferL().Format( KExportMetadataFreeTextSearch, aNamespaceDef.GetId(), aNamespaceDef.GetId() );
+
+	aFreeTextRow.Free();
+	aFreeTextRow.Reset();
+	aFreeTextRow.AppendL( TItemId(0) );
+	}
+
+void CMdsImportExport::ExportMetadataWriteObjectInfoL( const CMdsNamespaceDef& aNamespaceDef, const CMdsObjectDef& aObjectDef,
+													   CMdsClauseBuffer& aClause, RRowData& aDataRow,
+													   CMdsClauseBuffer& aFreeTextClause, RRowData& aFreeTextRow )
+	{
+	TItemId objectId;
+	TDefId objectDefId;
+	TUint32 objectFlags, objectMediaId, usageCount;
+	TInt64 objectGuidHigh, objectGuidLow;
+	TPtrC16 objectURI;
+
+	RRowData confidentialFlagRow;
+	CleanupClosePushL( confidentialFlagRow );
+	confidentialFlagRow.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+	confidentialFlagRow.AppendL( TColumn( EMdEObjectFlagNotPresent ) );
+	confidentialFlagRow.AppendL( TColumn( EMdEObjectFlagConfidential ) );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	RMdsStatement query;
+	CleanupClosePushL( query );
+
+	RMdsStatement freeTextQuery;
+	CleanupClosePushL( freeTextQuery );
+	RRowData textRow;
+	CleanupClosePushL( textRow );
+	textRow.AppendL( TColumn( EColumnDes16 ) );
+
+	RRowData queryResult;
+	CleanupClosePushL( queryResult );
+	queryResult.AppendColumnTypesL( aDataRow );
+	connection.ExecuteQueryL( aClause.ConstBufferL(), query, confidentialFlagRow );
+	while( connection.NextRowL( query, queryResult ) )
+		{
+		// get result from query
+		queryResult.Column( 0 ).Get( objectId ); // objectId
+		queryResult.Column( 1 ).Get( objectDefId ); // objectDefId
+		__ASSERT_DEBUG( objectDefId == aObjectDef.GetId(), User::Panic( _L( "CMdsImportExport::ExportMetadataWriteObjectInfo" ), KErrGeneral ) );
+		queryResult.Column( 2 ).Get( objectFlags ); // objectFlags
+		queryResult.Column( 3 ).Get( objectMediaId ); // objectMediaId
+		queryResult.Column( 4 ).Get( usageCount ); // usageCount
+		queryResult.Column( 5 ).Get( objectGuidHigh ); // objectGuidHigh
+		queryResult.Column( 6 ).Get( objectGuidLow ); // objectGuidLow
+		queryResult.Column( 7 ).Get( objectURI ); // objectURI
+
+		// writing basic object information
+		iWriteStream.WriteL( KMdsKeywordObject );
+		iWriteStream.WriteL( KExportMetadataSpace );
+		Conv16To8( aNamespaceDef.GetName(), iLine );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataSpace );
+		Conv16To8( aObjectDef.GetName(), iLine );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataSpace );
+		Conv16To8( objectURI, iLine );
+		iLine.Insert( 0, KExportMetadataQuotationMark );
+		iLine.Append( KExportMetadataQuotationMark );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataSpace );
+		iLine.Num( objectMediaId );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataNewLine );
+
+		const TInt count = aObjectDef.GetAllPropertiesCount();
+		
+		// writing property information
+		for ( TInt i = 0; i < count; ++i )
+			{
+			if ( queryResult.Column( i + KBaseObjectBasicValueColumnOffset ).IsNull() )
+				{
+				continue;
+				}
+
+			const CMdsObjectDef::TMdsColumnOrder& column = aObjectDef.GetPropertyColumnL( i );
+			const CMdsPropertyDef& property = column.iPropertyDef;
+
+			iWriteStream.WriteL( KMdsKeywordProperty );
+			iWriteStream.WriteL( KExportMetadataSpace );
+			Conv16To8( property.GetName(), iLine );
+			iWriteStream.WriteL( iLine );
+			iWriteStream.WriteL( KExportMetadataSpace );
+
+			switch( property.GetSqlType() )
+				{
+				case EColumnBool:
+					{
+					TBool value;
+					queryResult.Column( i + KBaseObjectBasicValueColumnOffset ).Get( value );
+					iLine.Num( value );
+					break;
+					}
+				case EColumnInt32:
+					{
+					TInt32 value;
+					queryResult.Column( i + KBaseObjectBasicValueColumnOffset ).Get( value );
+					iLine.Num( value );
+					break;
+					}
+				case EColumnUint32:
+					{
+					TUint32 value;
+					queryResult.Column( i + KBaseObjectBasicValueColumnOffset ).Get( value );
+					iLine.Num( value );
+					break;
+					}
+				case EColumnInt64:
+					{
+					TInt64 value;
+					queryResult.Column( i + KBaseObjectBasicValueColumnOffset ).Get( value );
+					iLine.Num( value );
+					break;
+					}
+				case EColumnTime:
+					{
+					TTime value;
+					queryResult.Column( i + KBaseObjectBasicValueColumnOffset ).Get( value );
+					TDateTime time = value.DateTime();
+					iLine.Format( KExportMetadataTimeFormat, time.Year(), time.Month()+1, time.Day()+1, time.Hour(), time.Minute(), time.Second() );
+					break;
+					}
+				case EColumnReal32:
+					{
+					TReal32 value;
+					queryResult.Column( i + KBaseObjectBasicValueColumnOffset ).Get( value );
+					TRealFormat realFormat;
+                	realFormat.iType |= KAllowThreeDigitExp | KDoNotUseTriads;
+                	realFormat.iPoint = TChar('.');
+					iLine.Num( value, realFormat );
+					break;
+					}
+				case EColumnReal64:
+					{
+					TReal64 value;
+					queryResult.Column( i + KBaseObjectBasicValueColumnOffset ).Get( value );
+					TRealFormat realFormat;
+                	realFormat.iType |= KAllowThreeDigitExp | KDoNotUseTriads;
+                	realFormat.iPoint = TChar('.');
+					iLine.Num( value, realFormat );
+					break;
+					}
+				case EColumnDes16:
+					{
+					TPtrC16 value;
+					queryResult.Column( i + KBaseObjectBasicValueColumnOffset ).Get( value );
+					Conv16To8( value, iLine );
+					iLine.Insert( 0, KExportMetadataQuotationMark );
+					iLine.Append( KExportMetadataQuotationMark );
+					break;
+					}
+				default:
+					{
+					User::Leave( KErrCorrupt );
+					}
+				}
+			iWriteStream.WriteL( iLine );
+
+			iWriteStream.WriteL( KExportMetadataNewLine );
+			}
+
+		// restore query
+		queryResult.AppendColumnTypesL( aDataRow );
+
+		// writing freetext
+		// get freetext
+		aFreeTextRow.Column( 0 ).Set( objectId );
+		connection.ExecuteQueryL( aFreeTextClause.ConstBufferL(), freeTextQuery, aFreeTextRow );
+		TBool freeTextPreamble = EFalse;
+		TInt lineSize = KMdsKeywordFreeText().Size() + 3; // space + line ending
+		while( connection.NextRowL( freeTextQuery, textRow ) )
+			{
+			// get result from query
+			if ( !freeTextPreamble )
+				{
+				iWriteStream.WriteL( KMdsKeywordFreeText );
+				iWriteStream.WriteL( KExportMetadataSpace );
+				freeTextPreamble = ETrue;
+				}
+			TPtrC16 word;
+			textRow.Column( 0 ).Get( word );
+			Conv16To8( word, iLine );
+			iLine.Insert( 0, KExportMetadataQuotationMark );
+			iLine.Append( KExportMetadataQuotationMark );
+			lineSize += iLine.Length() + 2;
+			if ( lineSize >= KMdsMaxLineLenght )
+				{
+				iWriteStream.WriteL( KExportMetadataNewLine );
+				iWriteStream.WriteL( KMdsKeywordFreeText );
+				iWriteStream.WriteL( KExportMetadataSpace );
+				lineSize = KMdsKeywordFreeText().Size() + 3; // space + line ending
+				}
+			iWriteStream.WriteL( iLine );
+			iWriteStream.WriteL( KExportMetadataSpace );
+			textRow.Free();
+			}
+		if ( freeTextPreamble )
+			{
+			iWriteStream.WriteL( KExportMetadataNewLine );
+			}
+
+		iWriteStream.WriteL( KExportMetadataNewLine );
+		}
+
+    CleanupStack::PopAndDestroy( 5, &confidentialFlagRow ); // queryResult, textRow, freeTextQuery, query, confidentialFlagRow
+	}
+
+
+void CMdsImportExport::ExportMetadataMakeSqlRelationClauseL( const CMdsNamespaceDef& aNamespaceDef,
+									  		  				CMdsClauseBuffer& aClause, RRowData& aDataRow )
+	{
+	_LIT( KExportMetadataRelationQuery, "SELECT LO.URI,RO.URI,Parameter FROM Relations%u AS R,Object%u AS LO ON LeftObjectId=LO.ObjectId JOIN Object%u AS RO ON RightObjectId=RO.ObjectId WHERE RelationDefId=? AND NOT R.Flags&? AND NOT R.Flags&?;" );
+
+	aClause.BufferL().Zero(); // reset clause
+	aClause.ReserveSpaceL( KExportMetadataRelationQuery.iTypeLength + 30 );
+	aClause.BufferL().Format( KExportMetadataRelationQuery, aNamespaceDef.GetId(), aNamespaceDef.GetId(), aNamespaceDef.GetId() );
+
+	aDataRow.Free(); // free and reset dataRow
+	aDataRow.Reset();
+	aDataRow.AppendL( TColumn( TDefId(0) ) ); // relationDefId
+	aDataRow.AppendL( TColumn( EMdERelationFlagDeleted ) );
+	aDataRow.AppendL( TColumn( EMdERelationFlagNotPresent ) );
+	}
+
+void CMdsImportExport::ExportMetadataWriteRelationInfoL( const CMdsNamespaceDef& aNamespaceDef, const CMdsRelationDef& aRelationDef,
+										  				CMdsClauseBuffer& aClause, RRowData& aDataRow )
+	{
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	RRowData resultRow;
+	CleanupClosePushL( resultRow );
+	resultRow.AppendL( TColumn( EColumnDes16 ) ); // LeftObjectIds URI
+	resultRow.AppendL( TColumn( EColumnDes16 ) ); // RightObjectIds URI
+	resultRow.AppendL( TColumn( TInt32(0) ) );  // RelationParameter
+
+	RMdsStatement query;
+	CleanupClosePushL( query );
+	RRowData resultRowGet;
+	CleanupClosePushL( resultRowGet );
+	resultRowGet.AppendColumnTypesL( resultRow );
+
+	aDataRow.Column( 0 ).Set( aRelationDef.GetId() );
+	connection.ExecuteQueryL( aClause.ConstBufferL(), query, aDataRow );
+	while( connection.NextRowL( query, resultRowGet ) )
+		{
+		iWriteStream.WriteL( KMdsKeywordRelation );
+		iWriteStream.WriteL( KExportMetadataSpace );
+		Conv16To8( aNamespaceDef.GetName(), iLine );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataSpace );
+		Conv16To8( aRelationDef.GetName(), iLine );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataSpace );
+
+		TPtrC16 uri;
+		resultRowGet.Column( 0 ).Get( uri );
+		Conv16To8( uri, iLine );
+		iLine.Insert( 0, KExportMetadataQuotationMark );
+		iLine.Append( KExportMetadataQuotationMark );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataSpace );
+
+		resultRowGet.Column( 1 ).Get( uri );
+		Conv16To8( uri, iLine );
+		iLine.Insert( 0, KExportMetadataQuotationMark );
+		iLine.Append( KExportMetadataQuotationMark );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataSpace );
+
+		TInt32 relationParameter;
+		resultRowGet.Column( 2 ).Get( relationParameter );
+		iLine.Num( relationParameter );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataNewLine );
+		
+		resultRowGet.AppendColumnTypesL( resultRow );
+		}
+
+	CleanupStack::PopAndDestroy( 3, &resultRow ); // query, resultRowGet, resultRow
+	}
+
+
+void CMdsImportExport::ExportMetadataMakeSqlEventClauseL( const CMdsNamespaceDef& aNamespaceDef,
+									  	   				 CMdsClauseBuffer& aClause, RRowData& aDataRow )
+	{
+	_LIT( KExportMetadataEventQuery, "SELECT URI,Source,Participant,Timestamp FROM Event%u AS EL,Object%u AS O ON EL.ObjectId=O.ObjectId WHERE EventDefId=?;" );
+
+	aClause.BufferL().Zero(); // reset clause
+	aClause.ReserveSpaceL( KExportMetadataEventQuery.iTypeLength + 20 );
+	aClause.BufferL().Format( KExportMetadataEventQuery, aNamespaceDef.GetId(), aNamespaceDef.GetId() );
+
+	aDataRow.Free(); // free and reset dataRow
+	aDataRow.Reset();
+	aDataRow.AppendL( TColumn( TDefId(0) ) ); // eventDefId
+	}
+
+void CMdsImportExport::ExportMetadataWriteEventInfoL( const CMdsNamespaceDef& aNamespaceDef, const CMdsEventDef& aEventDef,
+													  CMdsClauseBuffer& aClause, RRowData& aDataRow )
+	{
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	RRowData resultRow;
+	CleanupClosePushL( resultRow );
+	resultRow.AppendL( TColumn( EColumnDes16 ) ); // target
+	resultRow.AppendL( TColumn( EColumnDes16 ) ); // source
+	resultRow.AppendL( TColumn( EColumnDes16 ) ); // participant
+	resultRow.AppendL( TColumn( TTime(0) ) );     // time
+
+	RMdsStatement query;
+	CleanupClosePushL( query );
+
+	RRowData resultRowGet;
+	CleanupClosePushL( resultRowGet );
+	resultRowGet.AppendColumnTypesL( resultRow );
+
+	aDataRow.Column( 0 ).Set( aEventDef.GetId() );
+	connection.ExecuteQueryL( aClause.ConstBufferL(), query, aDataRow );
+	while( connection.NextRowL( query, resultRowGet ) )
+		{
+		iWriteStream.WriteL( KMdsKeywordEvent );
+		iWriteStream.WriteL( KExportMetadataSpace );
+		Conv16To8( aNamespaceDef.GetName(), iLine );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataSpace );
+		Conv16To8( aEventDef.GetName(), iLine );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataSpace );
+
+		TPtrC16 word;
+		// target
+		resultRowGet.Column( 0 ).Get( word );
+		Conv16To8( word, iLine );
+		iLine.Insert( 0, KExportMetadataQuotationMark );
+		iLine.Append( KExportMetadataQuotationMark );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataSpace );
+
+		// source
+		resultRowGet.Column( 1 ).Get( word );
+		Conv16To8( word, iLine );
+		iLine.Insert( 0, KExportMetadataQuotationMark );
+		iLine.Append( KExportMetadataQuotationMark );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataSpace );
+
+		// participant
+		resultRowGet.Column( 2 ).Get( word );
+		Conv16To8( word, iLine );
+		iLine.Insert( 0, KExportMetadataQuotationMark );
+		iLine.Append( KExportMetadataQuotationMark );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataSpace );
+
+		TTime value;
+		resultRowGet.Column( 3 ).Get( value );
+		TDateTime time = value.DateTime();
+		iLine.Format( KExportMetadataTimeFormat, time.Year(), time.Month()+1, time.Day()+1, time.Hour(), time.Minute(), time.Second() );
+		iWriteStream.WriteL( iLine );
+		iWriteStream.WriteL( KExportMetadataNewLine );
+		
+		resultRowGet.AppendColumnTypesL( resultRow );
+		}
+
+	CleanupStack::PopAndDestroy( 3, &resultRow ); // query, resultRowGet, resultRow
+	}
+
+
+// ---------------------------------------------------------------------------
+// ---------------------------------------------------------------------------
+//                         IMPORT HELPER FUNCTIONS
+// ---------------------------------------------------------------------------
+// ---------------------------------------------------------------------------
+
+
+// ---------------------------------------------------------------------------
+// ImportText imports text which may be quoted and escaped
+// ------------------------------------------------
+//
+TInt CMdsImportExport::ImportText( TDes16& aBuffer, TLex8& aParser )
+    {
+    TPtrC8 token;
+    token.Set( aParser.NextToken() );
+
+	if ( token.Length() == 0 || token.Length() >= aBuffer.MaxLength() )
+        {
+        return KErrCorrupt;
+        }
+
+    /**
+    *	The string may be enclosed in quotes. Unfortunately the parser always stops at 
+    *	whitespace, so we must loop with the NextToken() until we find a token that ends with
+    * 	an unescaped quotation mark. The bit below will then mark everything inside the quotes 
+    *	as a single uninterrupted token.
+    */
+    if ( token[0] == '\"' )
+    	{
+    	TInt currentTokenLength(token.Length());
+    	TInt start = aParser.Offset() - currentTokenLength;
+    	TInt end = aParser.Offset();
+    	TBool forceContinue( EFalse );
+    	while( ETrue )
+    		{
+			// if there is a closing quote in the token see if is escaped
+			if ( currentTokenLength > 1 )
+				{
+				// First skip any escaped dollar signs in the string
+				// to avoid a false match in case the string is something
+				// like "foo$$"
+				TInt loc = token.Find(_L8("$$"));
+				while( loc != KErrNotFound )
+					{
+					token.Set(token.Mid(loc+2));
+					loc = token.Find(_L8("$$"));
+					}
+				// Now the token contains only non-escaped dollars
+				currentTokenLength = token.Length();
+				if ( currentTokenLength > 2 && token.Right(2) == _L8("$\"") )
+					{
+					forceContinue = ETrue;
+					}
+				}
+				
+			if(token[currentTokenLength - 1] == '\"' && !forceContinue)
+				{
+				// The token contains a closing quote which is not escaped, 
+				// leave loop because the string is finished
+				break;
+				}
+    		forceContinue = EFalse;
+    		token.Set(aParser.NextToken());
+    		currentTokenLength = token.Length();
+    		end = aParser.Offset();
+    		if ( currentTokenLength == 0 || currentTokenLength >= aBuffer.MaxLength() - (end-start) )
+			    {
+			    return KErrCorrupt;
+			    }
+	  		}
+	  	// We have the complete token length now, set the TPtrC accordingly
+    	token.Set(iLine.Mid(start + 1, (end-start) - 2)); // skip the quotes
+    	TBuf8<256> fp(token);
+    	}
+    // The token now contains the full string
+   	Conv8To16( token, aBuffer );
+
+   	return KErrNone;
+    }
+    
+// ------------------------------------------------
+// ImportUInt32
+// ------------------------------------------------
+//
+TInt CMdsImportExport::ImportUInt32( TUint32& aValue, TLex8& aParser )
+    {
+    TLex8 tokenParser( aParser.NextToken() );
+    aParser.SkipSpace();
+    if ( tokenParser.Val( aValue, EDecimal ) != KErrNone )
+        {
+        _LIT( KError, "Expecting a numeric value" );
+        LogError( KError );
+        return KErrCorrupt;
+        }
+    return KErrNone;
+    }
+
+// ------------------------------------------------
+// ImportMediaId
+// ------------------------------------------------
+//
+TInt CMdsImportExport::ImportMediaId( TUint32& aValue, TLex8& aParser, TChar& aDriveLetter )
+    {
+    TLex8 tokenParser( aParser.NextToken() );
+    aParser.SkipSpace();
+    if ( tokenParser.Val( aValue, EDecimal ) != KErrNone )
+        {
+        _LIT( KError, "Expecting a numeric value" );
+        LogError( KError );
+        return KErrCorrupt;
+        }
+
+    TInt error( KErrNone );
+    TInt driveNumber( -1 );
+    error = iFs.CharToDrive( aDriveLetter, driveNumber );
+
+    if ( error != KErrNone )
+        {
+        return error;
+        }
+        
+    if( driveNumber != iLastDriveNumber )
+        {
+        error = iFs.Volume( iLastVolumeInfo, driveNumber );
+            
+        if ( error != KErrNone )
+            {
+            return error;
+            }     
+            
+       iLastDriveNumber = driveNumber;
+       }
+        
+    aValue = iLastVolumeInfo.iUniqueID;
+        
+    return KErrNone;
+    }
+
+// ------------------------------------------------
+// ImportInt64
+// ------------------------------------------------
+//
+TInt CMdsImportExport::ImportInt64( Int64& aValue, TLex8& aParser )
+    {
+    // due to symbian int64 parser error
+    // for now we will use ImportNum version
+    ImportNum( aValue, aParser );
+
+    return KErrNone;
+    }
+
+// ------------------------------------------------
+// ImportTime
+// ------------------------------------------------
+//
+TInt CMdsImportExport::ImportTime( TTime& aValue, TLex8& aParser )
+    {
+    // format: YYYYMMDDhhmmss
+    TPtrC8 token( aParser.NextToken() );
+    if ( token.Length() != 14 )
+    	{
+    	_LIT( KError, "Expecting a time value" );
+        LogError( KError );
+    	return KErrCorrupt;
+    	}
+    	
+    TLex8 year_p( token.Mid( 0, 4 ) );
+    TLex8 month_p( token.Mid( 4, 2 ) );
+    TLex8 day_p( token.Mid( 6, 2 ) );
+    TLex8 hour_p( token.Mid( 8, 2 ) );
+    TLex8 minute_p( token.Mid( 10, 2 ) );
+    TLex8 second_p( token.Mid( 12, 2 ) );
+    TInt year;
+    TInt month;
+    TInt day;
+    TInt hour;
+    TInt minute;
+    TInt second;
+
+    year_p.Val( year );
+    month_p.Val( month );
+    day_p.Val( day );
+    hour_p.Val( hour );
+    minute_p.Val( minute );
+    second_p.Val( second );
+
+    TDateTime datetime;
+    const TInt error = datetime.Set( year, (TMonth)(month-1), day-1, hour,
+    							minute, second, 0 );
+    if ( error != KErrNone )
+    	{
+    	return error;
+    	}
+
+    aValue = datetime;
+    return KErrNone;
+    }
+
+// ------------------------------------------------
+// Conv8To16
+// ------------------------------------------------
+//
+TDesC16& CMdsImportExport::Conv8To16( const TDesC8& aUtf8, TDes16& aBuffer )
+    {
+    TInt conversionState = CCnvCharacterSetConverter::KStateDefault;
+    iConverter->ConvertToUnicode( aBuffer, aUtf8, conversionState );
+    return aBuffer;
+    }
+
+// ------------------------------------------------
+// Conv16To8
+// ------------------------------------------------
+//
+TDesC8& CMdsImportExport::Conv16To8( const TDesC16& aUnicode, TDes8& aBuffer )
+    {
+    iConverter->ConvertFromUnicode( aBuffer, aUnicode );
+    return aBuffer;
+    }
+
+// ------------------------------------------------
+// LogError
+// ------------------------------------------------
+//
+void CMdsImportExport::LogError( const TDesC& aMessage )
+    {
+    _LIT( KParseError, "Parse error: %S" );
+    _LIT( KCurrentFile, "Current file: %S" );
+    _LIT( KCurrentLineNum, "Current line number: %d" );
+    _LIT( KCurrentLine, "Current line: %S" );
+    iLog.WriteFormat( KParseError, &aMessage );
+    iLog.WriteFormat( KCurrentFile, &iFileName );
+    iLog.WriteFormat( KCurrentLineNum, iLineNumber );
+    TBuf16<KMdsMaxLogLineLenght> line16;
+    Conv8To16( iLine, line16 );
+    iLog.WriteFormat( KCurrentLine, &line16 );
+    }
+
+
+// ------------------------------------------------
+// CheckForConstant
+// ------------------------------------------------
+//
+TInt CMdsImportExport::CheckForConstant( TLex8& aParser )
+	{
+	TInt ret = KErrNone;
+	TBuf<32> buf;
+	aParser.Mark();
+	ret = ImportText( buf, aParser );
+	if ( ret < KErrNone )
+		{
+		aParser.UnGetToMark();
+		return ret;
+		}
+	if ( buf.CompareF(KMdsKeywordMinValue) == 0 )
+		{
+		return KPropertyMinValue;
+		}
+	else if ( buf.CompareF(KMdsKeywordMaxValue) == 0 )
+		{
+		return KPropertyMaxValue;
+		}
+	else if ( buf.CompareF(KMdsKeywordDefValue) == 0 )
+		{
+		return KPropertyDefValue;
+		}
+	aParser.UnGetToMark();
+	return KErrNotFound;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsindexer.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,134 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is Metadata engine server file*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include "mdsindexer.h"  
+#include "mdsdbconnectionpool.h"
+#include "mdssqliteconnection.h"
+
+// ========================= MEMBER FUNCTIONS ==================================
+
+
+TItemId MMdSIndexer::StartIndexL()
+	{
+	GetLastItemIdL();
+	return iId;
+	}
+
+TItemId MMdSIndexer::GetIndex( )
+	{
+	return ++iId;
+	}
+
+void MMdSIndexer::RevertIndex( )
+	{
+	--iId;
+	}
+
+void MMdSIndexer::GetLastItemIdL()
+	{
+	_LIT( KGetLastMaxId, "SELECT max(seq) FROM SQLITE_SEQUENCE WHERE name!='symbian_security';" );
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	RRowData getData;
+	CleanupClosePushL(getData);
+
+	RMdsStatement selectObject;
+	CleanupClosePushL(selectObject);
+
+	//Get one row and set first column to id
+	connection.ExecuteQueryL( KGetLastMaxId, selectObject, getData );
+
+	getData.AppendL( TColumn( iId ) );
+	if (connection.NextRowL(selectObject, getData))
+		{
+		getData.Column(0).Get( iId );
+		}
+
+	CleanupStack::PopAndDestroy(2, &getData);
+	}
+
+TItemId MMdSIndexer::GetIndexL()
+	{
+	_LIT( KIndexerQuery, "SELECT last_insert_rowid();" );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	RRowData getData;
+	CleanupClosePushL(getData);
+
+	RMdsStatement selectObject;
+	CleanupClosePushL(selectObject);
+
+	TItemId id = KNoId;
+	//Get one row and set first column to id
+	connection.ExecuteQueryL(KIndexerQuery,selectObject,getData);
+	getData.AppendL(TColumn(id));
+	if (connection.NextRowL(selectObject, getData))
+		{
+		getData.Column(0).Get(id);
+		}
+
+	CleanupStack::PopAndDestroy(2, &getData);
+	return id;
+	}
+
+TItemId MMdSIndexer::ExecuteAndGetIndexL( const TDesC &aSqlClause,
+	    								 const RRowData& aRowData )
+    {
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+    const TInt queryResult = connection.ExecuteL( aSqlClause, aRowData );
+
+    if (queryResult == 0)
+    	{
+    	return KNoId;
+    	}
+
+   	return MMdSIndexer::GetIndexL();
+    }
+
+
+RSQLIndex::RSQLIndex()
+	: iId(MMdSIndexer::GetIndex()), iCommit(EFalse)
+	{
+	}
+
+const TItemId& RSQLIndex::GetId() const
+	{
+	return iId;
+	}
+
+void RSQLIndex::Commit()
+	{
+	iCommit = ETrue;
+	}
+
+void RSQLIndex::Close()
+	{
+	if (!iCommit)
+		{
+		MMdSIndexer::RevertIndex();
+		}
+	}
+
+
+// ---------------------------------------------------------------
+// -----------------INITIALIZE STATIC DATA------------------------
+// ---------------------------------------------------------------
+
+TItemId MMdSIndexer::iId = KNoId;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsitemdef.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,129 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one item definition
+*
+*/
+
+#include "mdsitemdef.h"
+#include "mdcserializationbuffer.h"
+
+// reserved words for schema definitions
+#define MDS_SCHEMA_DEFINITION_RESERVED_WORD(ReservedWord) \
+    _LIT( K##ReservedWord##Name, " #ReservedWord " );
+
+MDS_SCHEMA_DEFINITION_RESERVED_WORD(NamespaceDef)
+MDS_SCHEMA_DEFINITION_RESERVED_WORD(ObjectDef)
+MDS_SCHEMA_DEFINITION_RESERVED_WORD(PropertyDef) 
+MDS_SCHEMA_DEFINITION_RESERVED_WORD(RelationDef) 
+MDS_SCHEMA_DEFINITION_RESERVED_WORD(EventDef)
+MDS_SCHEMA_DEFINITION_RESERVED_WORD(Relations) 
+MDS_SCHEMA_DEFINITION_RESERVED_WORD(Event)
+MDS_SCHEMA_DEFINITION_RESERVED_WORD(TextSearch)
+MDS_SCHEMA_DEFINITION_RESERVED_WORD(TextSearchDictionary)
+
+#undef MDS_SCHEMA_DEFINITION_RESERVED_WORD
+
+/**
+ * ConstructL
+ */
+void CMdsItemDef::ConstructL( const TDesC& aName )
+	{
+	// check name of schema definition against reserved words
+	CheckReservedWordsL( aName );
+	
+	iName = aName.AllocL();
+	iStoredFlags = EStoredFlagsNone;
+	}
+
+/**
+ * Destructor
+ */
+CMdsItemDef::~CMdsItemDef()
+	{
+	delete iName;
+	}
+
+TUint32 CMdsItemDef::RequiredBufferSize()
+	{
+	// itemDefId, name
+	return CMdCSerializationBuffer::RequiredSize( *iName );
+	}
+
+TMdCOffset CMdsItemDef::SerializeL(CMdCSerializationBuffer& aBuffer)
+	{		
+	return aBuffer.InsertL( *iName );
+	}
+
+void CMdsItemDef::CheckAllowerCharatersL( const TDesC& aName, TBool aAllowNumbers )
+	{
+	const TInt count = aName.Length();
+
+	// name can't be empty
+	if( count <= 0 )
+		{
+		User::Leave( KErrBadDescriptor );
+		}
+
+	if( aAllowNumbers )
+		{
+		// first character can't be number
+		TUint16 c = aName[0];
+		CheckAlphabetL( c );
+
+		for( TInt i = 1; i < count; i++ )
+			{
+			c = aName[i];
+			CheckAlphabetOrNumberL( c );
+			}
+		}
+	else
+		{
+		for( TInt i = 0; i < count; i++ )
+			{
+			TUint16 c = aName[i];
+			CheckAlphabetL( c );
+			}
+		}
+	}
+
+void CMdsItemDef::CheckReservedWordsL( const TDesC& aName )
+	{
+#define MDS_DEFINE_RESERVED_WORD(ReservedWord) \
+    &K##ReservedWord##Name,
+
+	const TDesC* reservedWords[] =
+		{
+		MDS_DEFINE_RESERVED_WORD(NamespaceDef)
+		MDS_DEFINE_RESERVED_WORD(ObjectDef)
+		MDS_DEFINE_RESERVED_WORD(PropertyDef)
+		MDS_DEFINE_RESERVED_WORD(RelationDef)
+		MDS_DEFINE_RESERVED_WORD(EventDef)
+		MDS_DEFINE_RESERVED_WORD(Relations)
+		MDS_DEFINE_RESERVED_WORD(Event)
+		MDS_DEFINE_RESERVED_WORD(TextSearch)
+		MDS_DEFINE_RESERVED_WORD(TextSearchDictionary)
+		};
+
+#undef MDS_SCHEMA_DEFINITION_RESERVED_WORD
+
+	const TInt count = sizeof ( reservedWords ) / sizeof( TDesC* );
+
+	for ( TInt i = 0; i < count; ++i )
+		{
+		if ( *reservedWords[ i ] == aName )
+			{
+			User::Leave( KErrGeneral );
+			}
+		}
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdslogger.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,334 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Metadata server logger class*
+*/
+
+#include "mdslogger.h"
+#include "mdsclausebuffer.h"
+#include "mdssqliteconnection.h"
+
+
+#ifdef LOG_MASTER_FLAG
+
+// ========================= MEMBER FUNCTIONS ==================================
+
+// ------------------------------------------------
+// NewInstanceL
+// ------------------------------------------------
+//
+CMdSLogger* CMdSLogger::NewInstanceL()
+    {
+    static CMdSLogger* singleton;
+    if ( singleton == NULL )
+        {
+        singleton = new (ELeave) CMdSLogger();      
+        CleanupStack::PushL(singleton);
+        singleton->ConstructL();
+        CleanupStack::Pop(singleton);
+        }
+    return singleton;
+    }
+
+// ------------------------------------------------
+// Default constructor
+// ------------------------------------------------
+//
+CMdSLogger::CMdSLogger()
+	: iAltFileFlag(EFalse), iValid(EFalse)
+    {
+    }
+
+// ------------------------------------------------
+// Destructor
+// ------------------------------------------------
+//
+CMdSLogger::~CMdSLogger()
+    {
+    iLog.CloseLog(); 
+    iLog.Close();
+    }
+
+// ------------------------------------------------
+// ConstructL
+// ------------------------------------------------
+//
+void CMdSLogger::ConstructL()
+    {
+    User::LeaveIfError( iLog.Connect() );
+    iLog.CreateLog(KDirectory, KFilename, EFileLoggingModeOverwrite);
+    iLog.SetDateAndTime(EFalse, ETrue);
+    
+    iValid = iLog.LogValid();
+
+    // set up logging categories
+    Activate( ELogAlways );
+#ifdef LOG_QUERY
+    Activate( ELogQuery );
+#endif
+#ifdef LOG_DB
+    Activate( ELogDb );
+#endif
+#ifdef LOG_MUTEX
+    Activate( ELogMutex );
+#endif
+#ifdef LOG_SERVER
+    Activate( ELogServer );
+#endif
+    }
+
+// ------------------------------------------------
+// LogLit
+// ------------------------------------------------
+//
+void CMdSLogger::LogLit( const TDesC8& aText )
+    {
+    if (!iValid)
+    	{
+    	return;
+    	}
+
+    TInt offset = 0;
+    TInt linecount = 0;
+    TInt length = aText.Length();
+    while( offset < length )
+        {
+        TInt partLength = Min( length-offset, KLineLength );
+#ifdef MDE_FILE_LOGGING
+        iLog.Write( aText.Mid( offset, partLength ) );
+#else
+        TBuf<KLineLength> buffer;
+        buffer.Copy( aText.Mid( offset, partLength ) );
+        RDebug::Print( buffer );
+#endif
+        ++linecount;
+        offset += partLength;
+        }
+    CheckSize( linecount );
+    }
+
+// ------------------------------------------------
+// LogLit
+// ------------------------------------------------
+//
+void CMdSLogger::LogLit( const TDesC16& aText )
+    {
+    if (!iValid)
+    	{
+    	return;
+    	}
+
+    TInt offset = 0;
+    TInt linecount = 0;
+    TInt length = aText.Length();
+    while( offset < length )
+        {
+        TInt partLength = Min( length-offset, KLineLength );
+#ifdef MDE_FILE_LOGGING
+        iLog.Write( aText.Mid( offset, partLength ) );
+#else
+        RDebug::Print( aText.Mid( offset, partLength ) );
+#endif
+        ++linecount;
+        offset += partLength;
+        }
+    CheckSize( linecount );
+    }
+
+// ------------------------------------------------
+// CheckSize
+// ------------------------------------------------
+//
+void CMdSLogger::CheckSize( TInt aLines )
+    {
+#ifdef MDE_FILE_LOGGING
+    iLineCounter += aLines;
+    if ( iLineCounter < KLogfileMaxLength ) return; // no worries
+
+    iLineCounter = 0;
+
+    iLog.CloseLog();
+    
+    if ( !iAltFileFlag )
+        {
+        iLog.CreateLog(KDirectory, KAltFilename, EFileLoggingModeOverwrite);
+        iAltFileFlag = ETrue;       
+        }
+    else
+        {
+        iLog.CreateLog(KDirectory, KFilename, EFileLoggingModeOverwrite);
+        iAltFileFlag = EFalse;        
+        }    
+    iLog.SetDateAndTime(EFalse, ETrue);
+#else
+    aLines = 0;
+#endif
+    }
+
+// ---------------------------------------------------------------------------
+// DescribeL                Returns sql clause with variables
+// ---------------------------------------------------------------------------
+//
+CMdsClauseBuffer* CMdSLogger::DescribeL( const CMdsClauseBuffer& aBuffer, const RRowData& aRowData )
+    {
+    if (!iValid)
+    	{
+    	return NULL;
+    	}
+
+    CMdsClauseBuffer* buf = CMdsClauseBuffer::NewLC( aBuffer.ConstBufferL().Length() + 1024 );
+    buf->BufferL().Copy( aBuffer.ConstBufferL() );
+    buf->AppendL( _L(" variables=") );
+    for( TInt i=0; i<aRowData.Size(); ++i )
+        {
+        if ( i>0 ) buf->AppendL( _L(", ") );
+        LogVariableL( *buf, aRowData.Column(i) );
+        }
+    CleanupStack::Pop( buf );
+    return buf;
+    }
+
+// ---------------------------------------------------------------------------
+// DescribeL                Returns sql clause with variables
+// ---------------------------------------------------------------------------
+//
+CMdsClauseBuffer* CMdSLogger::DescribeFullL( const TDesC& aBuffer, const RRowData& aRowData )
+    {
+    if (!iValid)
+    	{
+    	return NULL;
+    	}
+
+    const TChar KQuestionMark = '?';
+    TPtrC buffer( aBuffer );
+    const TInt aBufferLength = aBuffer.Length();
+    CMdsClauseBuffer* buf = CMdsClauseBuffer::NewLC( aBufferLength *2 );
+    TInt columnNumber = 0;
+    TInt qpos = buffer.Locate( KQuestionMark );
+    while( qpos >= 0 )
+    	{
+		buf->ReserveSpaceL( buf->ConstBufferL().Length() + qpos );
+		buf->BufferL().Append( buffer.Left( qpos ) );
+		LogVariableL( *buf, aRowData.Column(columnNumber++) );
+    	buffer.Set( buffer.Mid( qpos + 1 ) );
+    	qpos = buffer.Locate( KQuestionMark );
+    	}
+	buf->ReserveSpaceL( buf->ConstBufferL().Length() + buffer.Length() );
+	buf->BufferL().Append( buffer );
+
+	CleanupStack::Pop( buf );
+    return buf;
+    }
+
+// ---------------------------------------------------------------------------
+// LogVariableL         Logging method for query variables
+// ---------------------------------------------------------------------------
+//
+void CMdSLogger::LogVariableL( CMdsClauseBuffer& aBuf, const TColumn& aColumn )
+    {
+    _LIT( KApostrophe, "\'" );
+    switch( aColumn.Type() )
+        {
+        case EColumnNotUsed:
+            {
+            aBuf.ReserveSpaceL( aBuf.ConstBufferL().Length() + 8 );
+            _LIT( KMessageUnused, "<unused>" );
+            aBuf.BufferL().Append( KMessageUnused );
+            break;
+            }
+        case EColumnBool:
+            {
+            TBool val=0;
+            aColumn.Get( val );
+            aBuf.ReserveSpaceL( aBuf.ConstBufferL().Length() + 4 );
+            aBuf.BufferL().AppendNum( val );
+            }
+            break;
+        case EColumnInt32:
+            {
+            TInt32 val=0;
+            aColumn.Get( val );
+            aBuf.ReserveSpaceL( aBuf.ConstBufferL().Length() + 16 );
+            aBuf.BufferL().AppendNum( static_cast<TInt>(val) );
+            }
+            break;
+        case EColumnUint32:
+            {
+            TUint32 val=0;
+            aColumn.Get( val );
+            aBuf.ReserveSpaceL( aBuf.ConstBufferL().Length() + 16 );
+            aBuf.BufferL().AppendNum( val, EDecimal );
+            }
+            break;
+        case EColumnTime:
+            {
+            TTime val(0);
+            TBuf<128> tmp;
+            aColumn.Get( val );
+            _LIT(KTimeFormat, "%D%1.%M%2.%Y%3 %H:%T:%S");
+            val.FormatL(tmp, KTimeFormat);
+            aBuf.ReserveSpaceL( aBuf.ConstBufferL().Length() + 20 );
+            aBuf.BufferL().Append( tmp );
+            }
+            break;
+        case EColumnInt64:
+            {
+            TInt64 val=0;
+            aColumn.Get( val );
+            aBuf.ReserveSpaceL( aBuf.ConstBufferL().Length() + 32 );
+            aBuf.BufferL().AppendNum( val );
+            }
+            break;
+        case EColumnReal32:
+            {
+            TReal32 val=0;
+            aColumn.Get( val );
+            aBuf.ReserveSpaceL( aBuf.ConstBufferL().Length() + 32 );
+            aBuf.BufferL().AppendNum( val, TRealFormat() );
+            }
+            break;
+        case EColumnReal64:
+            {
+            TReal64 val=0;
+            aColumn.Get( val );
+            aBuf.ReserveSpaceL( aBuf.ConstBufferL().Length() + 32 );
+            aBuf.BufferL().AppendNum( val, TRealFormat() );
+            }
+            break;
+        case EColumnDes16:
+            {
+            TPtrC16 val= TPtr16((TUint16*)0, 0); //KNullPtr16;
+            aColumn.Get( val );
+            if( val.Ptr() )
+            	{
+            	aBuf.ReserveSpaceL( aBuf.ConstBufferL().Length() + 
+            			val.Length() + 2 * KApostrophe().Length() ); // for ''
+            	aBuf.BufferL().Append( KApostrophe );
+            	aBuf.BufferL().Append( val );
+            	aBuf.BufferL().Append( KApostrophe );
+            	}
+            else
+            	{
+            	_LIT( KNull, "NULL" );
+            	aBuf.ReserveSpaceL( aBuf.ConstBufferL().Length() + 
+            			KNull().Length() );
+            	aBuf.BufferL().Append( KNull );
+            	}
+            }
+            break;
+        default:
+            User::Leave( KErrCorrupt );
+        }
+    }
+
+#endif // LOG_MASTER_FLAG
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsmaintenanceengine.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,244 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class for database import/export and maintenance
+*
+*/
+
+// INCLUDE FILES
+#include "mdsmaintenanceengine.h"
+#include "mdslogger.h"
+#include "mdsmanipulationengine.h"
+#include "mdcserializationbuffer.h"
+#include "mdsimportexport.h"
+#include "mdssqliteconnection.h"
+#include "mdsschema.h"
+#include "mdssqldbmaintenance.h"
+#include "mdsdbconnectionpool.h"
+#include "mdsindexer.h"
+#include "mdspreferences.h"
+
+__USES_LOGGER
+
+// ------------------------------------------------
+// NewL
+// ------------------------------------------------
+//
+CMdSMaintenanceEngine* CMdSMaintenanceEngine::NewL()
+    {
+    CMdSMaintenanceEngine* self = CMdSMaintenanceEngine::NewLC();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ------------------------------------------------
+// NewLC
+// ------------------------------------------------
+//
+CMdSMaintenanceEngine* CMdSMaintenanceEngine::NewLC()
+    {
+    CMdSMaintenanceEngine* self = new ( ELeave ) CMdSMaintenanceEngine();
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    return self;
+    }
+
+// ------------------------------------------------
+// Constructor
+// ------------------------------------------------
+//
+CMdSMaintenanceEngine::CMdSMaintenanceEngine()
+    {
+    }
+
+// ------------------------------------------------
+// NewL
+// ------------------------------------------------
+//
+void CMdSMaintenanceEngine::ConstructL()
+    {
+    iMaintenance = CMdSSqlDbMaintenance::NewL();
+    }
+
+// ------------------------------------------------
+// Destructor
+// ------------------------------------------------
+//
+CMdSMaintenanceEngine::~CMdSMaintenanceEngine()
+    {
+    delete iMaintenance;
+    }
+
+// ------------------------------------------------
+// InitConnectionL
+// ------------------------------------------------
+//
+void CMdSMaintenanceEngine::InitConnectionL()
+    {
+    // open the database
+    MMdSDbConnectionPool::ConnectAllL();
+    }
+
+// ------------------------------------------------
+// CloseDatabaseL
+// ------------------------------------------------
+//
+void CMdSMaintenanceEngine::CloseDatabase()
+	{
+	MMdSDbConnectionPool::DisconnectAll();
+	}
+
+// ------------------------------------------------
+// DeleteDatabaseL
+// ------------------------------------------------
+//
+void CMdSMaintenanceEngine::DeleteDatabase()
+	{
+	CMdSMaintenanceEngine::CloseDatabase();    
+	CMdSSqLiteConnection::DeleteDb( );
+	}
+
+// ------------------------------------------------
+// InstallL
+// ------------------------------------------------
+//
+void CMdSMaintenanceEngine::InstallL( CMdSManipulationEngine& aManipulate, CMdsSchema& aSchema )
+    {
+    if ( !(iMaintenance->ValidateL( ) ) )
+        {
+        // first-time init: re-form the database completely
+    	iMaintenance->CreateDatabaseL( );
+		const TUint KMdSServerUid = 0x0320e65f; // temporal uid
+
+		// try to read schema file from C drive
+		TRAPD( err, ImportSchemaL( aSchema, KSchemaImportFile, KMdSServerUid) );
+
+		if( err != KErrNone )
+			{
+			__LOG1( ELogAlways, "Schema reading error: %d", err );
+			// if schema file is not found, try to read from rom (Z) drive
+			if ( err == KErrNotFound || err == KErrPathNotFound )
+				{
+				TRAP( err, ImportSchemaL( aSchema, KSchemaRomImportFile, KMdSServerUid) );
+				}
+			if( err != KErrNone )
+				{
+				__LOG1( ELogAlways, "Schema reading error: %d", err );
+				DeleteDatabase();
+				User::Leave( err );
+				}
+			}
+
+		if ( FailedImports() != 0 )
+  			{
+	       	User::Leave( KErrCorrupt );
+       		}
+		
+		// try to read default import file from C drive
+       	TRAP( err, ImportMetadataL( aManipulate, aSchema, KMdsDefaultImportFile ) );
+       	if ( err == KErrNotFound || err == KErrPathNotFound )
+       		{
+       		// if default import file is not found, try to read from rom (Z) drive
+       		// and ignore errors
+       		TRAP_IGNORE( ImportMetadataL( aManipulate, aSchema, KMdsDefaultRomImportFile ) );
+       		}
+       	
+       	StoreCDriveMediaIdL();
+        }
+    else
+        {
+        TRAPD( err, LoadSchemaL( aSchema ) );
+
+        if( err != KErrNone )
+        	{ 
+			DeleteDatabase();
+			User::Leave( err );
+        	}
+        }
+    }
+
+// ------------------------------------------------
+// LoadSchemaL
+// ------------------------------------------------
+//
+void CMdSMaintenanceEngine::LoadSchemaL( CMdsSchema& aSchema )
+    {
+    CMdsImportExport* impSchema = CMdsImportExport::NewLC();
+    impSchema->ImportSchemaFromDBL( aSchema );
+    CleanupStack::PopAndDestroy( impSchema );
+    aSchema.SerializeToSharedMemoryL();
+    }
+    
+// ------------------------------------------------
+// ImportSchemaL
+// ------------------------------------------------
+//
+void CMdSMaintenanceEngine::ImportSchemaL( CMdsSchema& aSchema, const TDesC16& aFileName, TUint32 aVendorId )
+    {
+    CMdsImportExport* impSchema = CMdsImportExport::NewLC();
+    impSchema->ImportSchemaFromFileL( aFileName, aSchema, aVendorId );
+    CleanupStack::PopAndDestroy( impSchema );
+
+    aSchema.StoreToDBL();
+
+	aSchema.SerializeToSharedMemoryL();
+    }
+
+// ------------------------------------------------
+// ImportMetadataL
+// ------------------------------------------------
+//
+TInt CMdSMaintenanceEngine::ImportMetadataL( CMdSManipulationEngine& aManipulate, CMdsSchema& aSchema, const TDesC16& aFileName )
+    {
+    CMdsImportExport* importMetadata = CMdsImportExport::NewLC();
+    TInt failed = KErrNone;
+    TRAPD( err, failed = importMetadata->ImportMetadataL( aManipulate.Manipulate(), aSchema, aFileName ) );
+    if (err != KErrNone)
+    	{
+    	failed = err;
+    	}
+    CleanupStack::PopAndDestroy( importMetadata );
+    
+   	iFailedImports = failed;
+    return failed;
+    }
+    
+// ------------------------------------------------
+// ExportMetadataL
+// ------------------------------------------------
+//
+void CMdSMaintenanceEngine::ExportMetadataL( CMdsSchema& aSchema, const TDesC16& aFileName, 
+                                             CMdCSerializationBuffer& aItems )
+	{
+	CMdsImportExport* exporter = CMdsImportExport::NewLC();
+	exporter->ExportMetadataL( aSchema, aFileName, aItems );
+	CleanupStack::PopAndDestroy( exporter );
+    }
+
+// ------------------------------------------------
+// StoreCDriveMediaIdL
+// ------------------------------------------------
+//
+void CMdSMaintenanceEngine::StoreCDriveMediaIdL()
+	{
+	RFs fs;
+    User::LeaveIfError( fs.Connect() );
+    CleanupClosePushL( fs );
+    TVolumeInfo volumeInfo;
+    fs.Volume( volumeInfo, EDriveC );
+    MMdsPreferences::InsertL( KCMediaIdKey, MMdsPreferences::EPreferenceValueSet,
+    		(TUint32) volumeInfo.iUniqueID );
+    
+    CleanupStack::PopAndDestroy( &fs );
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsmanipulationengine.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1064 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is Manipulation engine to manage adding,
+*                deleting and modifying metadata database entries
+*
+*/
+
+// INCLUDE FILES
+#include "mdsmanipulationengine.h"
+
+#include "mdcresult.h"
+#include "mdcitem.h"
+#include "mdsschema.h"
+#include "mdsnotifier.h"
+#include "mdsdbconnectionpool.h"
+#include "mdslogger.h"
+#include "mdssqlobjectmanipulate.h"
+#include "mdssqliteconnection.h"
+#include "mdsnamespacedef.h"
+#include "mdcserializationbuffer.h"
+#include "mdeinternalerror.h"
+#include "mdeerror.h"
+
+__USES_LOGGER
+
+// ======== LOCAL FUNCTIONS ========
+
+static void TransactionCleanupL(void* aConn)
+   {
+   CMdSSqLiteConnection* conn = (CMdSSqLiteConnection*)aConn;
+   conn->TransactionRollbackL();
+   }
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CMdSManipulationEngine* CMdSManipulationEngine::NewL( CMdsSchema& aSchema,
+    CMdSNotifier& aNotifier, CMdSObjectLockList& aLockList )
+    {
+    CMdSManipulationEngine* self = CMdSManipulationEngine::NewLC( aSchema, 
+    		aNotifier, aLockList );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+CMdSManipulationEngine* CMdSManipulationEngine::NewLC( CMdsSchema& aSchema,
+    CMdSNotifier& aNotifier, CMdSObjectLockList& aLockList )
+    {
+    CMdSManipulationEngine* self = new (ELeave) CMdSManipulationEngine(
+        aSchema, aNotifier, aLockList );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Default constructor
+// ---------------------------------------------------------------------------
+//
+CMdSManipulationEngine::CMdSManipulationEngine( CMdsSchema& aSchema,
+    CMdSNotifier& aNotifier, CMdSObjectLockList& aLockList )
+    : iManipulate( NULL ), iSchema( aSchema ), iNotifier( aNotifier ), 
+    iGarbageCollector( NULL ), iLockList( aLockList )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CMdSManipulationEngine::ConstructL()
+    {
+    iManipulate = CMdSSqlObjectManipulate::NewL( iSchema, iLockList );
+    iGarbageCollector = CMdSGarbageCollector::NewL(*this);
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CMdSManipulationEngine::~CMdSManipulationEngine()
+    {
+    delete iManipulate;
+    
+    delete iGarbageCollector;
+    }
+
+// ---------------------------------------------------------------------------
+// Manipulate
+// ---------------------------------------------------------------------------
+//
+CMdSSqlObjectManipulate& CMdSManipulationEngine::Manipulate()
+    {
+    return *iManipulate;
+    }
+
+// ---------------------------------------------------------------------------
+// GarbageCollector
+// ---------------------------------------------------------------------------
+//
+CMdSGarbageCollector& CMdSManipulationEngine::GarbageCollector()
+	{
+	return *iGarbageCollector;
+	}
+
+// ---------------------------------------------------------------------------
+// AddL adds objects from serialized buffer
+// ---------------------------------------------------------------------------
+//
+void CMdSManipulationEngine::AddL( CMdCSerializationBuffer& aBuffer, 
+		CMdCSerializationBuffer& aResultBuffer, 
+		const CMdSServerSession* aServerSession )
+	{
+	const TMdCItems& items = TMdCItems::GetFromBufferL( aBuffer );
+
+	const CMdsNamespaceDef* namespaceDef = iSchema.GetNamespaceByIdL( 
+			items.iNamespaceDefId );
+	if ( !namespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+	iManipulate->SetNamespace( namespaceDef );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	TMdCItemIds resultIds;
+	resultIds.iNamespaceDefId = items.iNamespaceDefId;
+	resultIds.iErrorCode = KErrNone;
+	aResultBuffer.PositionL( sizeof(TMdCItemIds) );
+
+	// add objects
+	const TInt KObjectCount = items.iObjects.iPtr.iCount;
+	if ( KObjectCount > 0 )
+		{
+		resultIds.iObjectIds.iPtr.iOffset = aResultBuffer.Position();
+		resultIds.iObjectIds.iPtr.iCount = items.iObjects.iPtr.iCount;
+
+        RMdsStatement baseObjStmt;
+        CleanupClosePushL(baseObjStmt);
+        RMdsStatement objStmt;
+        CleanupClosePushL(objStmt);
+		
+		if( KObjectCount > 1 )
+		    {
+	        RMdSTransaction transaction( connection );
+	        CleanupClosePushL(transaction);
+	        const TInt beginError( transaction.Error() );
+	        if( beginError != KErrNone )
+	            {
+	            CleanupStack::PopAndDestroy( &transaction );
+	            }
+	    
+		    for ( TInt i = 0; i < KObjectCount; ++i )
+			    {
+			    aBuffer.PositionL( items.iObjects.iPtr.iOffset + i * sizeof(TMdCObject) );
+			    TItemId id = KNoId;
+			    TRAPD( err, id = iManipulate->AddObjectL( connection, aBuffer, 
+			            baseObjStmt, objStmt, aServerSession ) );
+			    if (err == KErrNone)
+				    {
+				    aResultBuffer.InsertL( id );
+				    }
+			    else
+				    {
+				    aResultBuffer.InsertL( KNoId );
+				    if(resultIds.iErrorCode == KErrNone)
+					    {
+					    resultIds.iErrorCode = err;
+					    }
+				    }
+			    }
+		    if( beginError == KErrNone )
+		        {
+	            transaction.CommitL();
+	            CleanupStack::PopAndDestroy( &transaction );
+		        }
+		    }
+		else
+		    {
+            for ( TInt i = 0; i < KObjectCount; ++i )
+                {
+                aBuffer.PositionL( items.iObjects.iPtr.iOffset + i * sizeof(TMdCObject) );
+                TItemId id = KNoId;
+                TRAPD( err, id = iManipulate->AddObjectL( connection, aBuffer, 
+                        baseObjStmt, objStmt, aServerSession ) );
+                if (err == KErrNone)
+                    {
+                    aResultBuffer.InsertL( id );
+                    }
+                else
+                    {
+                    aResultBuffer.InsertL( KNoId );
+                    if(resultIds.iErrorCode == KErrNone)
+                        {
+                        resultIds.iErrorCode = err;
+                        }
+                    }
+                }
+		    }
+        CleanupStack::PopAndDestroy(&objStmt);
+        CleanupStack::PopAndDestroy(&baseObjStmt);
+		}
+	else
+		{
+		resultIds.iObjectIds.iPtr.iOffset = KNoOffset;
+		resultIds.iObjectIds.iPtr.iCount = 0;
+		}
+
+	 // add events
+    const TInt KEventCount = items.iEvents.iPtr.iCount;
+    if ( KEventCount > 0 )
+		{
+		resultIds.iEventIds.iPtr.iOffset = aResultBuffer.Position();
+		resultIds.iEventIds.iPtr.iCount = KEventCount;
+	    
+	    if( KEventCount > 1 )
+	        {
+	        //More than 1 event, transaction will be used.
+	        connection.TransactionBeginL();
+	        CleanupStack::PushL(TCleanupItem(&TransactionCleanupL, &connection));
+	        }
+
+		for ( TInt i = 0; i < KEventCount; ++i )
+			{
+			aBuffer.PositionL( items.iEvents.iPtr.iOffset + 
+					i * sizeof(TMdCEvent) );
+
+			TItemId id = KNoId;
+			TRAPD( err, id = iManipulate->AddEventL( connection, aBuffer ) );
+			if (err == KErrNone)
+				{
+				aResultBuffer.InsertL( id );
+				}
+			else
+				{
+				aResultBuffer.InsertL( KNoId );
+				if(resultIds.iErrorCode == KErrNone)
+					{
+					resultIds.iErrorCode = err;
+					}
+				}
+			}
+
+		if( KEventCount > 1 )
+		    {
+		    connection.TransactionCommitL();
+		    CleanupStack::Pop();  //TransactionCleanup()
+	        }
+		}
+	else
+		{
+		resultIds.iEventIds.iPtr.iOffset = KNoOffset;
+		resultIds.iEventIds.iPtr.iCount = 0;
+		}
+
+	// add relations
+    const TInt KRelationCount = items.iRelations.iPtr.iCount;
+    if ( KRelationCount > 0 )
+		{
+		resultIds.iRelationIds.iPtr.iOffset = aResultBuffer.Position();
+		resultIds.iRelationIds.iPtr.iCount = KRelationCount;
+	    
+	    if( KRelationCount > 1 )
+	        {
+	        //More than 1 relation, transaction will be used.
+	        connection.TransactionBeginL();
+	        CleanupStack::PushL(TCleanupItem(&TransactionCleanupL, &connection));
+	        }
+
+	    for ( TInt i = 0; i < KRelationCount; ++i )
+			{
+			aBuffer.PositionL( items.iRelations.iPtr.iOffset + 
+					i * sizeof(TMdCRelation) );
+
+			TItemId id = KNoId;
+			TRAPD( err, id = iManipulate->AddRelationL( connection, aBuffer ) );
+			if (err == KErrNone)
+				{
+				aResultBuffer.InsertL( id );
+				}
+			else
+				{
+				aResultBuffer.InsertL( KNoId );
+				if(resultIds.iErrorCode == KErrNone)
+					{
+					resultIds.iErrorCode = err;
+					}
+				}
+			}
+
+	    if( KRelationCount > 1 )
+	        {
+	        connection.TransactionCommitL();
+	        CleanupStack::Pop();   //TransactionCleanup()
+	        }
+		}
+	else
+		{
+		resultIds.iRelationIds.iPtr.iOffset = KNoOffset;
+		resultIds.iRelationIds.iPtr.iCount = 0;
+		}
+
+	// set up result header
+	aResultBuffer.PositionL( KNoOffset );
+	resultIds.SerializeL( aResultBuffer );
+
+	iManipulate->SetNamespace( NULL );
+	iNotifier.NotifyAddedL( aBuffer, aResultBuffer );
+	}
+
+// ---------------------------------------------------------------------------
+// RemoveL
+// ---------------------------------------------------------------------------
+//
+void CMdSManipulationEngine::RemoveL( CMdCSerializationBuffer& aBuffer, 
+		CMdCSerializationBuffer& aResultBuffer )
+    {
+    // Read item ids from buffer.
+    const TMdCItemIds& itemIds = TMdCItemIds::GetFromBufferL( aBuffer );
+    
+	const CMdsNamespaceDef* namespaceDef = iSchema.GetNamespaceByIdL( 
+			itemIds.iNamespaceDefId );
+	if ( !namespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+	iManipulate->SetNamespace( namespaceDef );
+
+    TMdCItemIds resultIds;
+	resultIds.iNamespaceDefId = itemIds.iNamespaceDefId;
+	resultIds.iErrorCode = KErrNone;
+	resultIds.iObjectUris.iPtr.iCount = 0;
+	resultIds.iObjectUris.iPtr.iOffset = KNoOffset;
+
+	aResultBuffer.PositionL( sizeof(TMdCItemIds) );
+
+	RArray<TItemId> idArray;
+	CleanupClosePushL( idArray );
+	RArray<TItemId> removedRelations;
+	CleanupClosePushL( removedRelations );
+	RArray<TItemId> removedEvents;
+	CleanupClosePushL( removedEvents );
+
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+    // Remove objects by id or URI.
+    if (itemIds.iObjectIds.iPtr.iCount + itemIds.iObjectUris.iPtr.iCount > 0)
+		{
+	    RMdSTransaction transaction( connection );
+	    CleanupClosePushL(transaction);
+	    User::LeaveIfError( transaction.Error() );
+
+		if (itemIds.iObjectUris.iPtr.iCount > 0)
+			{
+			aBuffer.PositionL( itemIds.iObjectUris.iPtr.iOffset );
+			iManipulate->RemoveObjectsByUriL( aBuffer, itemIds.iObjectUris.iPtr.iCount,
+					idArray, removedRelations, removedEvents );
+			}
+		else
+			{
+			aBuffer.PositionL( itemIds.iObjectIds.iPtr.iOffset );
+			iManipulate->RemoveObjectsByIdL( aBuffer, itemIds.iObjectIds.iPtr.iCount,
+					idArray, removedRelations, removedEvents );
+			}
+
+	    transaction.CommitL();
+		CleanupStack::PopAndDestroy( &transaction );
+
+        // write it to the buffer
+        const TInt count = idArray.Count();
+		resultIds.iObjectIds.iPtr.iOffset = aResultBuffer.Position();
+        resultIds.iObjectIds.iPtr.iCount = count;
+        
+        for ( TInt i = 0; i < count; ++i )
+        	{
+        	aResultBuffer.InsertL( idArray[i] );
+        	if (idArray[i] == KNoId && resultIds.iErrorCode==KErrNone)
+        		{
+        		resultIds.iErrorCode = KErrNotFound;
+        		}
+        	}
+        idArray.Reset();
+		}
+    else
+    	{
+    	resultIds.iObjectIds.iPtr.iCount = 0;
+    	resultIds.iObjectIds.iPtr.iOffset = KNoOffset;
+    	}
+
+    // Remove events by id.
+	if (itemIds.iEventIds.iPtr.iCount > 0)
+		{
+		// process events
+		aBuffer.PositionL( itemIds.iEventIds.iPtr.iOffset );
+
+	    RMdSTransaction transaction( connection );
+	    CleanupClosePushL(transaction);
+	    User::LeaveIfError( transaction.Error() );
+
+		iManipulate->RemoveEventsL( aBuffer, itemIds.iEventIds.iPtr.iCount, idArray );
+
+	    transaction.CommitL();
+		CleanupStack::PopAndDestroy( &transaction );
+
+        const TInt count = idArray.Count();
+        resultIds.iEventIds.iPtr.iOffset = aResultBuffer.Position();
+        resultIds.iEventIds.iPtr.iCount = count;
+
+        for ( TInt i = 0; i < count; ++i )
+        	{
+        	aResultBuffer.InsertL( idArray[i] );
+        	if (idArray[i] == KNoId && resultIds.iErrorCode==KErrNone)
+        		{
+        		resultIds.iErrorCode = KErrNotFound;
+        		}
+        	}
+		idArray.Reset();
+		}
+	else
+		{
+        resultIds.iEventIds.iPtr.iOffset = KNoOffset;
+        resultIds.iEventIds.iPtr.iCount = 0;
+		}
+
+	// Remove relations by id.
+	if (itemIds.iRelationIds.iPtr.iCount > 0)
+		{
+		// process relations
+		aBuffer.PositionL( itemIds.iRelationIds.iPtr.iOffset );
+
+	    RMdSTransaction transaction( connection );
+	    CleanupClosePushL(transaction);
+	    User::LeaveIfError( transaction.Error() );
+
+		iManipulate->RemoveRelationsL( aBuffer, itemIds.iRelationIds.iPtr.iCount, idArray );
+
+	    transaction.CommitL();
+		CleanupStack::PopAndDestroy( &transaction );
+
+        const TInt count = idArray.Count();
+        resultIds.iRelationIds.iPtr.iOffset = aResultBuffer.Position();
+        resultIds.iRelationIds.iPtr.iCount = count;
+
+        for ( TInt i = 0; i < count; ++i )
+        	{
+        	aResultBuffer.InsertL( idArray[i] );
+        	if (idArray[i] == KNoId && resultIds.iErrorCode==KErrNone)
+        		{
+        		resultIds.iErrorCode = KErrNotFound;
+        		}
+        	}
+		}
+	else
+		{
+        resultIds.iRelationIds.iPtr.iOffset = KNoOffset;
+        resultIds.iRelationIds.iPtr.iCount = 0;
+		}
+
+	aResultBuffer.PositionL( KNoOffset );
+	resultIds.SerializeL( aResultBuffer );
+
+	// notify about items removed
+	const TBool notify = iNotifier.CheckForNotifier(EObjectNotifyRemove|EEventNotifyRemove|ERelationNotifyRemove);
+	if (notify)
+		{
+		iNotifier.NotifyRemovedL( aResultBuffer, EFalse );
+		}
+
+	// notify about additional items removed
+	const TInt KRemovedItemsCount = removedRelations.Count() + removedEvents.Count();
+    if ( notify && KRemovedItemsCount > 0 )
+    	{
+    	const TInt32 bufferSize = sizeof(TMdCItemIds)
+							+ KRemovedItemsCount * CMdCSerializationBuffer::KRequiredSizeForTItemId;
+
+		CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( bufferSize );
+
+		buffer->PositionL( sizeof(TMdCItemIds) );
+		
+		TMdCItemIds additResultIds;
+		additResultIds.iNamespaceDefId = itemIds.iNamespaceDefId;
+		additResultIds.iErrorCode = KErrNone;
+		additResultIds.iObjectIds.iPtr.iOffset = KNoOffset;
+		additResultIds.iObjectIds.iPtr.iCount = 0;
+		additResultIds.iObjectUris.iPtr.iOffset = KNoOffset;
+		additResultIds.iObjectUris.iPtr.iCount = 0;
+
+		// Insert list of removed events to the serialization buffer.
+		const TInt KRemovedEventsCount = removedEvents.Count();
+		additResultIds.iEventIds.iPtr.iCount = KRemovedEventsCount;
+		if ( KRemovedEventsCount > 0 )
+			{
+			additResultIds.iEventIds.iPtr.iOffset = buffer->Position();
+			for ( TInt i = 0; i < KRemovedEventsCount; ++i )
+				{
+				buffer->InsertL( removedEvents[i] );
+				}
+			}
+		else
+			{
+			additResultIds.iEventIds.iPtr.iOffset = KNoOffset;
+			}
+
+		// Insert list of removed relations to the serialization buffer.
+		const TInt KRemovedRelationsCount = removedRelations.Count();
+		additResultIds.iRelationIds.iPtr.iCount = KRemovedRelationsCount;
+		if ( KRemovedRelationsCount > 0 )
+			{
+			additResultIds.iRelationIds.iPtr.iOffset = buffer->Position();
+			for ( TInt i = 0; i < KRemovedRelationsCount; ++i )
+				{
+				buffer->InsertL( removedRelations[i] );
+				}
+			}
+		else
+			{
+			additResultIds.iRelationIds.iPtr.iOffset = KNoOffset;
+			}
+
+		buffer->PositionL( KNoOffset );
+		additResultIds.SerializeL( *buffer );
+		iNotifier.NotifyRemovedL( *buffer, EFalse );
+		CleanupStack::PopAndDestroy( buffer );
+    	}
+
+    // notify about removed relation items
+	const TInt relationsCount = removedRelations.Count() + idArray.Count();
+	
+    if ( relationsCount > 0 && iNotifier.CheckForNotifier(ERelationItemNotifyRemove) )
+    	{
+		CMdCSerializationBuffer* itemsBuffer = CMdCSerializationBuffer::NewLC( 
+				sizeof( TMdCItems ) + 
+				sizeof( TMdCRelation ) * relationsCount );
+
+		iManipulate->GetRemovedRelationItemsL( *itemsBuffer, 
+				removedRelations, idArray );
+
+		iNotifier.NotifyRemovedRelationItemsL( *itemsBuffer );
+
+		CleanupStack::PopAndDestroy( itemsBuffer );
+    	}
+    
+	// start garbage collector
+	if( iGarbageCollector )
+		{
+		iGarbageCollector->Start( KGarbageCollectionDelay );
+		}
+
+	// removedEvents, removedRelations, idArray
+    CleanupStack::PopAndDestroy( 3, &idArray );
+    }
+
+void CMdSManipulationEngine::UpdateL( CMdCSerializationBuffer& aBuffer, 
+		CMdCSerializationBuffer& aResultBuffer )
+	{
+	const TMdCItems& items = TMdCItems::GetFromBufferL( aBuffer );
+
+	const CMdsNamespaceDef* namespaceDef = iSchema.GetNamespaceByIdL( 
+			items.iNamespaceDefId );
+	if ( !namespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+	iManipulate->SetNamespace( namespaceDef );
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	TMdCItemIds resultIds;
+	resultIds.iNamespaceDefId = items.iNamespaceDefId;
+	resultIds.iErrorCode = KErrNone;
+	resultIds.iObjectUris.iPtr.iOffset = KNoOffset;
+	resultIds.iObjectUris.iPtr.iCount = 0;
+	resultIds.iEventIds.iPtr.iOffset = KNoOffset;
+	resultIds.iEventIds.iPtr.iCount = 0;
+
+	aResultBuffer.PositionL( sizeof(TMdCItemIds) );
+
+	// update objects
+	if ( items.iObjects.iPtr.iCount > 0 )
+		{
+		resultIds.iObjectIds.iPtr.iOffset = aResultBuffer.Position();
+		resultIds.iObjectIds.iPtr.iCount = items.iObjects.iPtr.iCount;
+
+		for ( TInt i = 0; i < items.iObjects.iPtr.iCount; ++i )
+			{
+			aBuffer.PositionL( items.iObjects.iPtr.iOffset + i * sizeof(TMdCObject) );
+
+			TItemId id = KNoId;
+			TRAPD( err, id = iManipulate->UpdateObjectL( connection, aBuffer ) );
+			if (err == KErrNone)
+				{
+				aResultBuffer.InsertL( id );
+				}
+			else
+				{
+				aResultBuffer.InsertL( KNoId );
+				if ( resultIds.iErrorCode == KErrNone )
+					{
+					resultIds.iErrorCode = err;
+					}
+				}
+			}
+		}
+	else
+		{
+		resultIds.iObjectIds.iPtr.iOffset = KNoOffset;
+		resultIds.iObjectIds.iPtr.iCount = 0;
+		}
+
+	// update relations
+	if ( items.iRelations.iPtr.iCount > 0 )
+		{
+		resultIds.iRelationIds.iPtr.iOffset = aResultBuffer.Position();
+		resultIds.iRelationIds.iPtr.iCount = items.iRelations.iPtr.iCount;
+
+		for ( TInt i = 0; i < items.iRelations.iPtr.iCount; ++i )
+			{
+			aBuffer.PositionL( items.iRelations.iPtr.iOffset + i * sizeof(TMdCRelation) );
+
+			TItemId id = KNoId;
+			TRAPD( err, id = iManipulate->UpdateRelationsL( connection, aBuffer ) );
+			if (err == KErrNone)
+				{
+				aResultBuffer.InsertL( id );
+				}
+			else
+				{
+				aResultBuffer.InsertL( KNoId );
+				if ( resultIds.iErrorCode == KErrNone )
+					{
+					resultIds.iErrorCode = err;
+					}
+				}
+			}
+		}
+	else
+		{
+		resultIds.iRelationIds.iPtr.iOffset = KNoOffset;
+		resultIds.iRelationIds.iPtr.iCount = 0;
+		}
+
+	if ( items.iEvents.iPtr.iCount > 0 )
+		{
+		// events cannot be updated
+		// so just ignore it, but if possible return error code
+		if ( resultIds.iErrorCode == KErrNone )
+			{
+			resultIds.iErrorCode = KErrArgument;
+			}
+		}
+
+	iManipulate->SetNamespace( NULL );
+
+	// set up result header
+	aResultBuffer.PositionL( KNoOffset );
+	resultIds.SerializeL( aResultBuffer );
+
+	iNotifier.NotifyModifiedL( aBuffer, aResultBuffer );
+    }
+
+CMdCSerializationBuffer* CMdSManipulationEngine::CheckObjectL( 
+		TInt aResultBufferSize, const TDesC& aUri, TDefId aNamespaceDefId )
+	{
+    return iManipulate->CheckObjectL( 
+    		aResultBufferSize, aUri, aNamespaceDefId );
+	}
+
+CMdCSerializationBuffer* CMdSManipulationEngine::CheckObjectL( 
+		TInt aResultBufferSize, TItemId aId, TDefId aNamespaceDefId )
+	{
+    return iManipulate->CheckObjectL( 
+    		aResultBufferSize, aId, aNamespaceDefId );
+	}
+
+CMdCSerializationBuffer* CMdSManipulationEngine::CheckObjectL( 
+		TInt aResultBufferSize, CMdCSerializationBuffer& aIds, 
+		TDefId aNamespaceDefId )
+	{
+	return iManipulate->CheckObjectL( 
+			aResultBufferSize, aIds, aNamespaceDefId );
+	}
+
+// ---------------------------------------------------------------------------
+// AddMemoryCardL
+// ---------------------------------------------------------------------------
+//
+void CMdSManipulationEngine::AddMemoryCardL(TUint32 aMediaId)
+	{
+	iManipulate->AddMemoryCardL( aMediaId );
+	}
+
+// ---------------------------------------------------------------------------
+// GetMemoryCardL
+// ---------------------------------------------------------------------------
+//
+void CMdSManipulationEngine::GetMemoryCardL(TUint32& aMediaId)
+	{
+	iManipulate->GetMemoryCardL( aMediaId );
+	}
+
+// ---------------------------------------------------------------------------
+// CheckMemoryCardL
+// ---------------------------------------------------------------------------
+//
+TBool CMdSManipulationEngine::CheckMemoryCardL(TUint32 aMediaId)
+	{
+	return iManipulate->CheckMemoryCardL( aMediaId );
+	}
+
+// ---------------------------------------------------------------------------
+// SetMediaL
+// ---------------------------------------------------------------------------
+//
+void CMdSManipulationEngine::SetMediaL(TUint32 aMediaId, TChar aDrive, 
+		TBool aPresentState)
+	{
+	return iManipulate->SetMediaL( aMediaId, aDrive, aPresentState );
+	}
+	
+// ---------------------------------------------------------------------------
+// GetMediaL
+// ---------------------------------------------------------------------------
+//
+TBool CMdSManipulationEngine::GetMediaL(TUint32 aMediaId, TChar& aDrive, 
+		TBool& aPresentState)
+	{
+	return iManipulate->GetMediaL( aMediaId, aDrive, aPresentState );
+	}
+
+// ---------------------------------------------------------------------------
+// GetPresentMediasL
+// ---------------------------------------------------------------------------
+//
+TInt32 CMdSManipulationEngine::GetPresentMediasL(TDes8& aMediaInfoBuffer)
+	{
+	return iManipulate->GetPresentMediasL( aMediaInfoBuffer );
+	}
+
+// ---------------------------------------------------------------------------
+// SetFilesToPresentL
+// ---------------------------------------------------------------------------
+//
+void CMdSManipulationEngine::SetFilesToPresentL(TUint32 aMediaId, TUint32 aFileCount, 
+		CMdCSerializationBuffer& aUris, CMdCSerializationBuffer& aFileInfos,
+		CMdCSerializationBuffer& aResults)
+	{
+
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+    RMdSTransaction transaction( connection );
+	CleanupClosePushL( transaction );
+	User::LeaveIfError( transaction.Error() );
+
+    RArray<TItemId> itemIds;
+	CleanupClosePushL( itemIds );
+    itemIds.ReserveL( aFileCount );
+
+    RArray<TItemId> notifyItemIds;
+	CleanupClosePushL( notifyItemIds );
+	notifyItemIds.ReserveL( aFileCount );
+
+    for( TUint32 i = 0; i < aFileCount; i++ )
+    	{
+    	TPtrC16 uri = aUris.ReceivePtr16L();
+    	TPtr16 uriLC( CONST_CAST( TUint16*, uri.Ptr() ), uri.Length(), uri.Length() );
+    	uriLC.LowerCase();
+
+    	TMdSFileInfo fileInfo;
+    	aFileInfos.ReceiveL(fileInfo.iModifiedTime);
+    	aFileInfos.ReceiveL(fileInfo.iSize);
+
+#ifdef _DEBUG    	
+    	const TInt64 time = fileInfo.iModifiedTime;
+        RDebug::Print( _L("CMdSManipulationEngine::SetFilesToPresentL: (%d) iSize %u, iModified %Ld, uri %S"),
+        		i,
+        		fileInfo.iSize,
+        		time,
+        		&uri);
+#endif
+
+    	TFilePresentStates placeHolder;
+    	TBool notPresentState( EFalse );
+    	const TItemId objectId = iManipulate->SearchNotPresentFileL( /*reservation(), */
+    			aMediaId, uri, fileInfo, placeHolder, notPresentState );
+    	if ( placeHolder != EMdsNotFound )
+    		{
+    		itemIds.Append( objectId );
+
+    		if( notPresentState )
+    			{
+    			notifyItemIds.Append( objectId );
+    			}
+    		}
+
+    	aResults.InsertL( (TUint8)placeHolder );
+    	}
+
+	iManipulate->SetFilesToPresentL( itemIds );
+
+	// only notify about objects in not present state and
+	// modify and notify relations related to those
+	if( notifyItemIds.Count() > 0 )
+		{
+		iNotifier.NotifyObjectPresent( ETrue, notifyItemIds );
+
+		RArray<TItemId> relationIds;
+		CleanupClosePushL( relationIds );
+
+	    const TInt itemIdCount = notifyItemIds.Count();
+		for( TUint32 i = 0; i < itemIdCount; i++ )
+			{
+			iManipulate->SetRelationsToPresentL( notifyItemIds[i], relationIds );
+			}
+
+		iNotifier.NotifyRelationPresent( ETrue, relationIds );
+
+		CleanupStack::PopAndDestroy( &relationIds );
+		}
+
+	transaction.CommitL();
+
+	CleanupStack::PopAndDestroy( &notifyItemIds );
+	CleanupStack::PopAndDestroy( &itemIds );
+
+	CleanupStack::PopAndDestroy( &transaction );
+	}
+
+// ---------------------------------------------------------------------------
+// SetFilesToNotPresentL
+// ---------------------------------------------------------------------------
+//
+void CMdSManipulationEngine::SetFilesToNotPresentL(TUint32 aMediaId, TBool aStartUp)
+	{
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+    RMdSTransaction transaction( connection );
+	CleanupClosePushL( transaction );
+	User::LeaveIfError( transaction.Error() );
+	
+	RArray<TItemId> objectIds;
+	CleanupClosePushL( objectIds );
+
+	iManipulate->SetFilesToNotPresentL( aMediaId, aStartUp, objectIds );
+	
+	// if start up no need for object notifications, 
+	// setting relations to not present and relation notifications
+	if( !aStartUp )
+		{
+		iNotifier.NotifyObjectPresent( EFalse, objectIds );
+		
+		RArray<TItemId> relationIds;
+		CleanupClosePushL( relationIds );
+	
+        iManipulate->SetRelationsToNotPresentL( aMediaId, relationIds );
+		iNotifier.NotifyRelationPresent( EFalse, relationIds );
+		
+		CleanupStack::PopAndDestroy( &relationIds );
+		}
+    
+    transaction.CommitL();
+
+    CleanupStack::PopAndDestroy( &objectIds );
+    CleanupStack::PopAndDestroy( &transaction );
+	}
+
+// ---------------------------------------------------------------------------
+// RemoveFilesNotPresentL
+// ---------------------------------------------------------------------------
+//
+void CMdSManipulationEngine::RemoveFilesNotPresentL(TUint32 aMediaId, TBool aStartUp)
+	{
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+    RMdSTransaction transaction( connection );
+	CleanupClosePushL( transaction );
+	User::LeaveIfError( transaction.Error() );
+	
+	if( aStartUp )
+		{
+		RArray<TItemId> objectIds;
+		CleanupClosePushL( objectIds );
+
+		iManipulate->RemoveFilesNotPresentL( aMediaId, &objectIds );
+		
+		if( objectIds.Count() > 0 )
+			{
+			iNotifier.NotifyRemovedL( objectIds );
+			}
+		
+		CleanupStack::PopAndDestroy( &objectIds );
+		}
+	else
+		{
+		iManipulate->RemoveFilesNotPresentL( aMediaId, NULL );
+		}
+
+    transaction.CommitL();
+    CleanupStack::PopAndDestroy( &transaction );
+
+	// start garbage collector
+	if( iGarbageCollector )
+		{
+		iGarbageCollector->Start( KGarbageCollectionDelay );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// StartGarbageCollection
+// ---------------------------------------------------------------------------
+//
+TBool CMdSManipulationEngine::StartGarbageCollectionL()
+	{
+#ifdef _DEBUG
+	RDebug::Print( _L("CMdSManipulationEngine::StartGarbageCollection()") );
+#endif
+
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+    RMdSTransaction transaction( connection );
+	CleanupClosePushL( transaction );
+	User::LeaveIfError( transaction.Error() );
+	
+    TBool again = EFalse;
+#ifdef _DEBUG
+    TRAPD( err, again = iManipulate->GarbageCollectionL() );
+#else
+    TRAP_IGNORE( again = iManipulate->GarbageCollectionL() );
+#endif
+
+    transaction.CommitL();
+    CleanupStack::PopAndDestroy( &transaction ); 
+    
+	#ifdef _DEBUG
+	if( err != KErrNone )
+		{
+		_LIT( KErrLog, "CMdSManipulationEngine::StartGarbageCollection error: %d" );
+		RDebug::Print( KErrLog, err );		
+		}
+	#endif
+	
+	return again;
+	}
+
+// ---------------------------------------------------------------------------
+// GetSchemaVersionL
+// ---------------------------------------------------------------------------
+//
+void CMdSManipulationEngine::GetSchemaVersionL(
+		TInt& aMajorVersion, TInt& aMinorVersion)
+	{
+	iManipulate->GetSchemaVersionL( aMajorVersion, aMinorVersion );
+	}
+
+void CMdSManipulationEngine::SetObjectToPresentByGuidL( 
+		const TInt64& aGuidHigh, const TInt64& aGuidLow )
+	{
+	iManipulate->SetObjectToPresentByGuidL( aGuidHigh, aGuidLow );
+	}
+
+void CMdSManipulationEngine::ChangePathL(const TDesC& aOldPath, const TDesC& aNewPath)
+	{
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+    RMdSTransaction transaction( connection );
+	CleanupClosePushL( transaction );
+	User::LeaveIfError( transaction.Error() );
+	
+	RArray<TItemId> objectIds;
+	CleanupClosePushL( objectIds );
+
+	iManipulate->ChangePathL( aOldPath, aNewPath, objectIds );
+
+	iNotifier.NotifyModifiedL( objectIds );
+	
+	CleanupStack::PopAndDestroy( &objectIds );
+	
+	transaction.CommitL();
+    CleanupStack::PopAndDestroy( &transaction );
+	}
+
+void CMdSManipulationEngine::ChangeMediaIdL()
+	{
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+    RMdSTransaction transaction( connection );
+	CleanupClosePushL( transaction );
+	User::LeaveIfError( transaction.Error() );
+	
+	iManipulate->ChangeMediaIdL();
+	
+	transaction.CommitL();
+
+	CleanupStack::PopAndDestroy( &transaction );
+	}
+
+void CMdSManipulationEngine::AddRelationDefL( TDefId aNamespaceId, const TDesC& aRelationDefName )
+	{
+	CMdsNamespaceDef* namespaceDef = CONST_CAST( CMdsNamespaceDef*, iSchema.GetNamespaceByIdL( aNamespaceId ) );
+	if ( !namespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+	if ( namespaceDef->GetReadOnly() )
+		{
+		User::Leave( KErrLocked );
+		}
+
+	namespaceDef->AddRelationDefL( aRelationDefName );
+	iSchema.StoreToDBL();
+	}
+
+void CMdSManipulationEngine::AddEventDefL( TDefId aNamespaceId, const TDesC& aEventDefName )
+	{
+	CMdsNamespaceDef* namespaceDef = CONST_CAST( CMdsNamespaceDef*, iSchema.GetNamespaceByIdL( aNamespaceId ) );
+	if ( !namespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+	if ( namespaceDef->GetReadOnly() )
+		{
+		User::Leave( KErrLocked );
+		}
+
+	namespaceDef->AddEventDefL( aEventDefName, 1 );
+	iSchema.StoreToDBL();
+	}
+
+void CMdSManipulationEngine::SetPendingL(const RArray<TItemId>& aObjectIds)
+	{
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	RMdSTransaction transaction( connection );
+	CleanupClosePushL( transaction );
+	User::LeaveIfError( transaction.Error() );
+
+	iManipulate->SetPendingL( aObjectIds, EFalse );
+
+	transaction.CommitL();
+    CleanupStack::PopAndDestroy( &transaction );
+	}
+
+void CMdSManipulationEngine::ResetPendingL(const RArray<TItemId>& aObjectIds)
+	{
+	iManipulate->SetPendingL( aObjectIds, ETrue );
+	}
+
+TInt CMdSManipulationEngine::GetPendingCountL( TDefId aObjectDefId )
+	{
+	return iManipulate->GetPendingCountL( aObjectDefId );
+	}
+
+TInt CMdSManipulationEngine::GetPendingL( TDefId aObjectDefId, 
+		TInt aBufferSize, RArray<TItemId>& aObjectIds )
+	{
+	return iManipulate->GetPendingL( aObjectDefId, aBufferSize, aObjectIds );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsnamespacedef.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,619 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one namespace and every object
+*                it holds.
+*
+*/
+
+#include "mdsnamespacedef.h"
+
+#include "mdcdef.h"
+#include "mdsobjectdef.h"
+#include "mdsrelationdef.h"
+#include "mdseventdef.h"
+#include "mdssqliteconnection.h"
+#include "mdsdbconnectionpool.h"
+#include "mdcserializationbuffer.h"
+#include "mdsschema.h"
+#include "mdsindexer.h"
+#include "mdeinternalerror.h"
+
+#include <uriutils.h>
+
+/**
+ * NewLC
+ */
+CMdsNamespaceDef* CMdsNamespaceDef::NewLC( TDefId aId,
+    const TDesC& aName, TBool aReadOnly, TUint32 aVendorId )
+	{
+	CMdsNamespaceDef* ret = new( ELeave ) CMdsNamespaceDef( aId, aReadOnly, aVendorId );
+	CleanupStack::PushL( ret );
+	ret->ConstructL( aName );
+	return ret;
+	}
+	
+/**
+ * NewL
+ */
+CMdsNamespaceDef* CMdsNamespaceDef::NewL( TDefId aId, const TDesC& aName,
+    TBool aReadOnly, TUint32 aVendorId )
+	{
+	CMdsNamespaceDef* ret = CMdsNamespaceDef::NewLC( aId, aName, aReadOnly, aVendorId );
+	CleanupStack::Pop( ret );
+	return ret;
+	}
+
+/**
+ * ConstructL
+ */
+void CMdsNamespaceDef::ConstructL( const TDesC& aName )
+	{
+	// validate the URI of namespace
+	TBool invalidChars = UriUtils::HasInvalidChars( aName );
+	if( invalidChars )
+		{
+		User::Leave( KErrGeneral );
+		}
+
+	CMdsItemDef::ConstructL( aName );
+	}
+
+/**
+ * Destructor
+ */
+CMdsNamespaceDef::~CMdsNamespaceDef()
+	{
+	// deleting objects
+	iObjectDefs.ResetAndDestroy();
+	iObjectDefs.Close();
+
+	// deleting relations...
+	iRelationDefs.ResetAndDestroy();
+   	iRelationDefs.Close();
+
+   	// deleting events...
+    iEventDefs.ResetAndDestroy();
+   	iEventDefs.Close();
+	}
+	
+/**
+ * AddObjectDefL
+ */
+CMdsObjectDef* CMdsNamespaceDef::AddObjectDefL( const TDesC& aObjectName, const TDesC& aParentName,
+                                                CMdsSchema* aDefaultSchema )
+	{
+	if ( GetObjectDef( aObjectName ) )
+		{
+		// duplicate object
+		User::Leave( KErrAlreadyExists );
+		}
+	CMdsObjectDef* parent = GetObjectDef( aParentName );
+	if ( !parent )
+		{
+		/* testing */
+		// found namespace in default schema
+		if ( aDefaultSchema )
+			{
+			CMdsNamespaceDef* namespaceDef = aDefaultSchema->GetNamespace( GetName() );
+			if ( !namespaceDef )
+				{
+				User::Leave( KErrMdEUnknownNamespaceDef );
+				}
+			parent = namespaceDef->GetObjectDef( aParentName );
+			}
+		if( !parent )
+			{
+			User::Leave( KErrNotFound );
+			}
+		}
+	CMdsObjectDef* object = CMdsObjectDef::NewLC( aObjectName, parent );
+	iObjectDefs.AppendL( object );
+	CleanupStack::Pop( object );
+	return object;
+	}
+
+/**
+ * AddObjectDefL (private - add from DB)
+ */
+void CMdsNamespaceDef::AddObjectDefL( TDefId aId, TDefId aParentId, TInt aFlags, const TDesC& aName )
+	{
+	const CMdsObjectDef* parent = GetObjectByIdL( aParentId );
+	if ( !parent )
+		{
+		User::Leave( KErrNotFound );
+		}
+	CMdsObjectDef* object = CMdsObjectDef::NewLC( aName, parent );
+	object->SetFlags( (CMdsObjectDef::TObjectDefFlags)aFlags );
+	iObjectDefs.AppendL( object );
+	object->SetId(aId);
+	object->SetStoredInDB();
+	CleanupStack::Pop( object );
+	}
+
+/**
+ * FindObjectDefParent
+ */
+CMdsObjectDef* CMdsNamespaceDef::GetObjectDef( const TDesC& aObjectName ) const
+	{
+	if ( iBaseObject->GetName().Compare( aObjectName ) == 0 )
+		{
+		return iBaseObject;
+		}
+
+	const TInt count = iObjectDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		if( iObjectDefs[i]->GetName().Compare( aObjectName ) == 0 )
+			{
+			return iObjectDefs[i];
+			}
+		}
+	return NULL;
+	}
+
+void CMdsNamespaceDef::AddRelationDefL( const TDesC& aRelationName )
+	{
+	if ( GetRelationDef( aRelationName ) )
+		{
+		User::Leave( KErrAlreadyExists );
+		}
+	CMdsRelationDef* relation = CMdsRelationDef::NewLC( aRelationName );
+	iRelationDefs.AppendL( relation );
+	CleanupStack::Pop( relation );
+	}
+
+
+void CMdsNamespaceDef::AddRelationDefL( TDefId aId, const TDesC& aRelationName )
+	{
+	CMdsRelationDef* relation = CMdsRelationDef::NewLC( aRelationName );
+	relation->SetId(aId);
+	iRelationDefs.AppendL( relation );
+	relation->SetStoredInDB();
+	CleanupStack::Pop( relation );
+	}
+
+
+CMdsRelationDef* CMdsNamespaceDef::GetRelationDef( const TDesC& aRelationName ) const
+	{
+	const TInt count = iRelationDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		if ( iRelationDefs[i]->GetName().Compare( aRelationName ) == 0 )
+			{
+			return iRelationDefs[i];
+			}
+		}
+	return NULL;
+	}
+
+void CMdsNamespaceDef::AddEventDefL( const TDesC& aEventName, TInt32 aPriority )
+	{
+	if ( GetEventDef( aEventName ) )
+		{
+		User::Leave( KErrAlreadyExists );
+		}
+	CMdsEventDef* event = CMdsEventDef::NewLC( aEventName, aPriority );
+	iEventDefs.AppendL( event );
+	CleanupStack::Pop( event );
+	}
+
+void CMdsNamespaceDef::AddEventDefL( TDefId aId, const TDesC& aEventName, TInt32 aPriority )
+	{
+	CMdsEventDef* event = CMdsEventDef::NewLC( aEventName, aPriority );
+	event->SetId(aId);
+	iEventDefs.AppendL( event );
+	event->SetStoredInDB();
+	CleanupStack::Pop( event );
+	}
+
+CMdsEventDef* CMdsNamespaceDef::GetEventDef( const TDesC& aEventName ) const
+	{
+	const TInt count = iEventDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		if ( iEventDefs[i]->GetName().Compare( aEventName ) == 0 )
+			{
+			return iEventDefs[i];
+			}
+		}
+	return NULL;
+	}
+
+const CMdsObjectDef* CMdsNamespaceDef::GetObjectByIdL( TDefId aId ) const
+	{
+	if ( aId == KBaseObjectDefId ) // BaseObject (hardcoded)
+		{
+		return iBaseObject;
+		}
+	
+	const TInt count = iObjectDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		if( iObjectDefs[i]->GetId() == aId )
+			{
+			return iObjectDefs[i];
+			}
+		}
+	return NULL;
+	}
+
+const CMdsEventDef* CMdsNamespaceDef::GetEventByIdL( TDefId aId ) const
+	{
+	const TInt count = iEventDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		if( iEventDefs[i]->GetId() == aId )
+			{
+			return iEventDefs[i];
+			}
+		}
+	return NULL;
+	}
+
+const CMdsRelationDef* CMdsNamespaceDef::GetRelationByIdL( TDefId aId ) const
+	{
+	const TInt count = iRelationDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		if( iRelationDefs[i]->GetId() == aId )
+			{
+			return iRelationDefs[i];
+			}
+		}
+	return NULL;
+	}
+
+void CMdsNamespaceDef::StoreToDBL( TBool aStoreOnlyNamespace )
+	{
+	_LIT( KMdsSqlClauseAddNamespaceDef, "INSERT INTO NamespaceDef(ReadOnly,VendorId,Name) Values(?,?,?);" );
+    RRowData rowData;
+    CleanupClosePushL( rowData );
+
+	if ( !GetStoredInDB() )
+		{
+		rowData.AppendL( TColumn( GetReadOnly() ) );
+		rowData.AppendL( TColumn( iVendorId ) );
+		rowData.AppendL( TColumn( GetName().AllocL() ) );
+
+		TDefId id = KNoDefId;
+		id = MMdSIndexer::ExecuteAndGetIndexL(KMdsSqlClauseAddNamespaceDef,rowData);
+		SetId( id );
+
+		SetStoredInDB();
+		}
+	
+	if (aStoreOnlyNamespace)
+		{
+		CleanupStack::PopAndDestroy( &rowData );
+		return;
+		}
+	
+	const TInt objectDefCount = iObjectDefs.Count();
+	
+	// add objectDef to DB
+	for( TInt i = 0; i < objectDefCount; ++i )
+		{
+		iObjectDefs[i]->StoreToDBL( GetId() );
+		}
+	
+	const TInt eventDefCount = iEventDefs.Count();
+	
+	// add relationDef to DB
+	for( TInt i = 0; i < eventDefCount; ++i )
+		{
+		iEventDefs[i]->StoreToDBL( GetId() );
+		}
+	
+	const TInt relationDefCount = iRelationDefs.Count();
+	
+	// add eventDef to DB
+	for( TInt i = 0; i < relationDefCount; ++i )
+		{
+		iRelationDefs[i]->StoreToDBL( GetId() );
+		}
+
+	CleanupStack::PopAndDestroy( &rowData );
+	}
+	
+
+void CMdsNamespaceDef::MergeObjectsL( CMdsNamespaceDef* aNamespace, const TBool& aDryRun )
+	{
+	const TInt count = aNamespace->iObjectDefs.Count();	
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		CMdsObjectDef* lObjectDef = GetObjectDef( aNamespace->iObjectDefs[i]->GetName() );
+		if( lObjectDef )
+			{
+			lObjectDef->MergeL( aNamespace->iObjectDefs[i], aDryRun );
+			}
+		else if ( !aDryRun )
+			{
+			iObjectDefs.AppendL( aNamespace->iObjectDefs[i] );
+			aNamespace->iObjectDefs[i]->SetAllNotStoredInDB();
+			aNamespace->iObjectDefs[i] = NULL;
+			}
+		}
+	}
+	
+void CMdsNamespaceDef::MergeRelationsL( CMdsNamespaceDef* aNamespace, const TBool& aDryRun )
+	{
+	const TInt count = aNamespace->iRelationDefs.Count();	
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		CMdsRelationDef* relation = GetRelationDef( aNamespace->iRelationDefs[i]->GetName() );
+		if ( relation )
+			{
+			if ( *aNamespace->iRelationDefs[i] != *relation )
+				{
+				User::Leave( KErrAlreadyExists );
+				}
+			}
+		else if ( !aDryRun )
+			{
+			iRelationDefs.AppendL( aNamespace->iRelationDefs[i] );
+			aNamespace->iRelationDefs[i]->SetAllNotStoredInDB();
+			aNamespace->iRelationDefs[i] = NULL;
+			}
+		}
+	}
+	
+void CMdsNamespaceDef::MergeEventsL( CMdsNamespaceDef* aNamespace, const TBool& aDryRun )
+	{
+	const TInt count = aNamespace->iEventDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		CMdsEventDef* event = GetEventDef( aNamespace->iEventDefs[i]->GetName() );
+		if ( event )
+			{
+			if ( *aNamespace->iEventDefs[i] != *event )
+				{
+				User::Leave( KErrAlreadyExists );
+				}
+			}
+		else if ( !aDryRun )
+			{
+			iEventDefs.AppendL( aNamespace->iEventDefs[i] );
+			aNamespace->iEventDefs[i]->SetAllNotStoredInDB();
+			aNamespace->iEventDefs[i] = NULL;
+			}
+		}
+	}
+
+void CMdsNamespaceDef::ImportFromDBL()
+	{
+	_LIT( KMdsQueryGetObjectDefs, "SELECT ObjectDefId,ParentDefId,Flags,Name FROM ObjectDef WHERE NamespaceDefId=?;" );
+	_LIT( KMdsQueryGetRelationDefs, "SELECT RelationDefId,Name FROM RelationDef WHERE NamespaceDefId=?;" );
+	_LIT( KMdsQueryGetEventDefs, "SELECT EventDefId,Priority,Name FROM EventDef WHERE NamespaceDefId=?;" );
+	TDefId eId = KNoDefId;
+	TInt32 objectParent = 0;
+	TInt32 flags = 0;
+	TPtrC name;
+
+	// importing namespaces
+	RRowData namespaceNumber;
+	CleanupClosePushL( namespaceNumber );
+	namespaceNumber.AppendL( TColumn( GetId() ) );
+	RRowData getData;
+	CleanupClosePushL( getData );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	// OBJECTS
+	RMdsStatement queryObject;
+	CleanupClosePushL( queryObject );
+	getData.AppendL( TColumn( eId ) );
+	getData.AppendL( TColumn( objectParent ) );
+	getData.AppendL( TColumn( flags ) );
+	getData.AppendL( TColumn( EColumnHBuf16 ) );
+	connection.ExecuteQueryL( KMdsQueryGetObjectDefs, queryObject, namespaceNumber );
+	while( connection.NextRowL( queryObject, getData ) )
+		{
+		getData.Column( 0 ).Get( eId );
+		getData.Column( 1 ).Get( objectParent );
+		getData.Column( 2 ).Get( flags );
+		getData.Column( 3 ).Get( name );
+		AddObjectDefL( eId, objectParent, flags, name );
+		getData.Column( 3 ).Free( );
+		}
+	CleanupStack::PopAndDestroy( &queryObject );
+	getData.Reset();
+	
+	// RELATIONS
+	RMdsStatement queryRelation;
+	CleanupClosePushL( queryRelation );
+	getData.AppendL( TColumn( eId ) );
+	getData.AppendL( TColumn( EColumnHBuf16 ) );
+	connection.ExecuteQueryL( KMdsQueryGetRelationDefs, queryRelation, namespaceNumber );
+	while( connection.NextRowL( queryRelation, getData ) )
+		{
+		getData.Column( 0 ).Get( eId );
+		getData.Column( 1 ).Get( name );
+		AddRelationDefL( eId, name );
+		getData.Column( 1 ).Free( );
+		}
+	CleanupStack::PopAndDestroy( &queryRelation );
+	getData.Reset();
+	
+	// EVENTS
+	TInt32 priority = 0;
+	RMdsStatement queryEvent;
+	CleanupClosePushL( queryEvent );
+	getData.AppendL( TColumn( eId ) );
+	getData.AppendL( TColumn( priority ) );
+	getData.AppendL( TColumn( EColumnHBuf16 ) );
+	connection.ExecuteQueryL( KMdsQueryGetEventDefs, queryEvent, namespaceNumber );
+	while( connection.NextRowL( queryEvent, getData ) )
+		{
+		getData.Column( 0 ).Get( eId );
+		getData.Column( 1 ).Get( priority );
+		getData.Column( 2 ).Get( name );
+		AddEventDefL( eId, name, priority );
+		getData.Column( 2 ).Free( );
+		}
+	CleanupStack::PopAndDestroy( &queryEvent );
+
+	CleanupStack::PopAndDestroy( 2, &namespaceNumber ); // getData, namespaceNumber
+	
+	const TInt count = iObjectDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		iObjectDefs[i]->ImportFromDBL();
+		}
+
+	// everything is ok, so set the flags
+	SetStoredInDB();
+	SetTableStoredInDB();
+	}
+	
+TUint32 CMdsNamespaceDef::RequiredBufferSize()
+	{
+	TUint32 bufferSize = sizeof(TMdCNamespaceDef) + CMdsItemDef::RequiredBufferSize();
+
+	const TInt objectDefsCount = iObjectDefs.Count();
+	bufferSize += (objectDefsCount + 1) * sizeof( TMdCObjectDef);
+	// base object def
+	bufferSize += iBaseObject->RequiredBufferSize();
+
+	// objectdefs
+	for ( TInt i = 0; i < objectDefsCount; ++i )
+		{
+		bufferSize += iObjectDefs[i]->RequiredBufferSize();
+		}
+
+	// eventdefs
+	const TInt eventDefsCount = iEventDefs.Count();
+	bufferSize += eventDefsCount * sizeof( TMdCEventDef );
+	for ( TInt i = 0; i < iEventDefs.Count(); ++i )
+		{
+		bufferSize += iEventDefs[i]->RequiredBufferSize();
+		}
+
+	// relationdefs
+	const TInt relationDefsCount = iRelationDefs.Count();
+	bufferSize += relationDefsCount * sizeof( TMdCRelationDef);
+	for ( TInt i = 0; i < iRelationDefs.Count(); ++i )
+		{
+		bufferSize += iRelationDefs[i]->RequiredBufferSize();
+		}
+
+	return bufferSize;
+	}
+
+TMdCOffset CMdsNamespaceDef::SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreeSpace)
+	{
+	const TMdCOffset namespaceDefOffset = aBuffer.Position();
+	TMdCNamespaceDef namespaceDef;
+	// get const data and store Name
+	namespaceDef.iDefId = GetId();
+	namespaceDef.iReadOnly = GetReadOnly();
+	namespaceDef.iName.iPtr.iCount = GetName().Length();
+	namespaceDef.iName.iPtr.iOffset = aFreeSpace;
+	aBuffer.PositionL( aFreeSpace );
+	aFreeSpace = CMdsItemDef::SerializeL( aBuffer );
+
+	// calculate necessary stuff for objectDefs
+	const TInt objectDefsCount = iObjectDefs.Count(); 
+	namespaceDef.iObjectDefs.iPtr.iCount = objectDefsCount + 1; // one extra for base object def
+	namespaceDef.iObjectDefs.iPtr.iOffset = aFreeSpace;
+
+	// create space for objectDefs
+	aFreeSpace += (objectDefsCount + 1) * sizeof(TMdCObjectDef);
+	
+	aBuffer.PositionL( namespaceDef.iObjectDefs.iPtr.iOffset ); // one extra for base object def
+	aFreeSpace = iBaseObject->SerializeL( aBuffer, aFreeSpace );
+
+	for ( TInt i = 0; i < objectDefsCount; ++i )
+		{
+		aBuffer.PositionL( namespaceDef.iObjectDefs.iPtr.iOffset
+				+ (i+1) * sizeof(TMdCObjectDef) ); // one extra for base object def
+		// write object
+		aFreeSpace = iObjectDefs[i]->SerializeL( aBuffer, aFreeSpace );
+		}
+
+	// calculate necessary stuff for eventDefs
+	const TInt eventDefsCount = iEventDefs.Count();
+	namespaceDef.iEventDefs.iPtr.iCount = eventDefsCount;
+	namespaceDef.iEventDefs.iPtr.iOffset = aFreeSpace;
+
+	// create space for eventDefs
+	aFreeSpace += eventDefsCount * sizeof(TMdCEventDef);
+
+	for ( TInt i = 0; i < eventDefsCount; ++i )
+		{
+		aBuffer.PositionL( namespaceDef.iEventDefs.iPtr.iOffset + i * sizeof(TMdCEventDef) );
+		// write event
+		aFreeSpace = iEventDefs[i]->SerializeL( aBuffer, aFreeSpace );
+		}
+
+	// calculate necessary stuff for relationDefs
+	const TInt relationDefsCount = iRelationDefs.Count();
+	namespaceDef.iRelationDefs.iPtr.iCount = relationDefsCount;
+	namespaceDef.iRelationDefs.iPtr.iOffset = aFreeSpace;
+
+	// create space for eventDefs
+	aFreeSpace += relationDefsCount * sizeof(TMdCRelationDef);
+
+	for ( TInt i = 0; i < relationDefsCount; ++i )
+		{
+		aBuffer.PositionL( namespaceDef.iRelationDefs.iPtr.iOffset + i * sizeof(TMdCRelationDef) );
+		// write relation
+		aFreeSpace = iRelationDefs[i]->SerializeL( aBuffer, aFreeSpace );
+		}
+	
+	// store namespaceDef itself
+	aBuffer.PositionL( namespaceDefOffset );
+	namespaceDef.SerializeL( aBuffer );
+
+	return aFreeSpace;
+	}
+	
+
+const CMdsPropertyDef* CMdsNamespaceDef::GetPropertyL( TDefId aId ) const
+	{
+	const CMdsPropertyDef* propertyDef = iBaseObject->GetPropertyByIdL( aId );
+
+	if ( propertyDef )
+		{
+		return propertyDef;
+		}
+
+	const TInt count = iObjectDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		const CMdsPropertyDef* objectPropertyDef = iObjectDefs[i]->GetPropertyByIdL( aId );
+		if ( objectPropertyDef )
+			{
+			return objectPropertyDef;
+			}
+		}
+
+	return NULL;
+	}
+
+/**
+ * Initialize static variables
+ */
+
+CMdsObjectDef* CMdsNamespaceDef::iBaseObject = NULL;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsnotifier.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1021 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Notifier engine / server side*
+*/
+
+#include "mdsnotifier.h"
+
+#include "mdcresult.h"
+#include "mdcitem.h"
+#include "mdsserversession.h"
+#include "mdsnotifycomparator.h"
+#include "mdslogger.h"
+#include "mdcserializationbuffer.h"
+#include "mdccommon.pan"
+
+__USES_LOGGER
+
+// ------------------------------------------------
+// NewL
+// ------------------------------------------------
+//
+CMdSNotifier* CMdSNotifier::NewL()
+    {
+    CMdSNotifier* that = CMdSNotifier::NewLC();
+    CleanupStack::Pop( that );
+    return that;
+    }
+
+
+// ------------------------------------------------
+// NewLC
+// ------------------------------------------------
+//
+CMdSNotifier* CMdSNotifier::NewLC()
+    {
+    CMdSNotifier* that = new(ELeave) CMdSNotifier();
+    CleanupStack::PushL( that );
+    that->ConstructL();
+    return that;
+    }
+
+
+// ------------------------------------------------
+// Constructor
+// ------------------------------------------------
+//
+CMdSNotifier::CMdSNotifier()
+    {
+    
+    }
+
+// ------------------------------------------------
+// ConstructL
+// ------------------------------------------------
+//
+void CMdSNotifier::ConstructL()
+    {
+    iComparator = CMdSNotifyComparator::NewL();
+    }
+
+// ------------------------------------------------
+// Destructor
+// ------------------------------------------------
+//
+CMdSNotifier::~CMdSNotifier()
+    {
+    delete iComparator;
+    iEntries.Close();
+    }
+
+// ------------------------------------------------
+// Constructor
+// ------------------------------------------------
+//
+CMdSNotifier::TEntry::TEntry( TInt aId,
+    TConditionType aType,
+    CMdCSerializationBuffer* aSerializedBuffer,
+    TDefId aNamespaceDefId, 
+    CMdSServerSession& aSession, 
+    TBool aConfidential)
+    : iId( aId )
+    , iType( aType )
+    , iNamespaceDefId(aNamespaceDefId)
+    , iSerializedCondition( aSerializedBuffer )
+    , iSession( aSession )
+    , iConfidential(aConfidential)    
+    {
+    iDataBuffer = NULL;
+    iRemoteSizeMsgSlot = KErrNotFound;
+    }
+
+// ------------------------------------------------
+// TriggerL completes the client message and sends the data size
+// ------------------------------------------------
+//
+void CMdSNotifier::TEntry::TriggerL(
+	TUint32 aCompleteCode,
+    const RArray<TItemId>& aIdArray )
+    {
+    TInt remoteSizeMsgSlot = iRemoteSizeMsgSlot;
+    iRemoteSizeMsgSlot = KErrNotFound;
+
+    __ASSERT_DEBUG( !iDataBuffer, MMdCCommon::Panic( KErrCorrupt ) );
+
+    if(aIdArray.Count())
+		{
+		iDataBuffer = CopyToBufferL( aIdArray );
+	    iSession.SizeToRemoteL( iMessage, remoteSizeMsgSlot, iDataBuffer->Size());
+		}
+	else
+		{
+	    iSession.SizeToRemoteL( iMessage, remoteSizeMsgSlot, 0);
+		}
+
+    __LOG2( ELogServer, "<- Notify trigger %d (%d)", iId, aCompleteCode );
+    iMessage.Complete( aCompleteCode );
+    }
+
+// ------------------------------------------------
+// TriggerRelationItemsL completes the client
+//                  message and sends the data size
+// ------------------------------------------------
+//
+void CMdSNotifier::TEntry::TriggerRelationItemsL(
+	TUint32 aCompleteCode,
+	CMdCSerializationBuffer& aBuffer,
+	const RArray<TItemId>& aRelationIdArray)
+    {
+    TInt remoteSizeMsgSlot = iRemoteSizeMsgSlot;
+    iRemoteSizeMsgSlot = KErrNotFound;
+
+    __ASSERT_DEBUG( !iDataBuffer, MMdCCommon::Panic( KErrCorrupt ) );
+
+    if(aRelationIdArray.Count())
+		{
+		iDataBuffer = CopyItemsToBufferL( aBuffer, aRelationIdArray );
+	    iSession.SizeToRemoteL( iMessage, remoteSizeMsgSlot, iDataBuffer->Size());
+		}
+	else
+		{
+	    iSession.SizeToRemoteL( iMessage, remoteSizeMsgSlot, 0);
+		}
+
+    __LOG2( ELogServer, "<- Notify trigger %d (%d)", iId, aCompleteCode );
+    iMessage.Complete( aCompleteCode );
+    }
+
+// ------------------------------------------------
+// TriggerSchemaL sends a schema notification
+// ------------------------------------------------
+//
+void CMdSNotifier::TEntry::TriggerSchema()
+    {
+    iRemoteSizeMsgSlot = KErrNotFound;
+    iMessage.Complete( ESchemaModify );
+    }
+
+// ------------------------------------------------
+// TriggerError send a error message to the client
+// ------------------------------------------------
+//
+void CMdSNotifier::TEntry::TriggerError( TInt aErrorCode )
+    {
+    iRemoteSizeMsgSlot = KErrNotFound;
+	delete iDataBuffer;
+    iDataBuffer = NULL;
+    __LOG2( ELogServer, "<- Notify trigger %d (%d)", iId, aErrorCode );
+
+    if( !iMessage.IsNull() )
+    	{
+    	iMessage.Complete( aErrorCode );
+    	}
+    }
+
+// ------------------------------------------------
+// CopyToBufferL copies id to buffer
+// ------------------------------------------------
+//
+CMdCSerializationBuffer* CMdSNotifier::TEntry::CopyToBufferL(const RArray<TItemId>& aIdArray)
+	{
+	// IDs are always stored in object ID, 
+	// even if those are actually relation or event IDs
+
+	const TUint32 count = aIdArray.Count();
+
+	CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC(
+			sizeof( TMdCItemIds )
+			+ count * CMdCSerializationBuffer::KRequiredSizeForTItemId );
+
+	TMdCItemIds itemIds;
+	itemIds.iNamespaceDefId = NamespaceDefId();
+	itemIds.iObjectIds.iPtr.iCount = count;
+	itemIds.iObjectIds.iPtr.iOffset = sizeof(TMdCItemIds);
+	itemIds.SerializeL( *buffer );
+
+	for( TInt i = 0; i < count; ++i )
+		{
+		buffer->InsertL( aIdArray[i] );
+		}
+
+	CleanupStack::Pop( buffer );
+	return buffer;	
+	}
+
+// ------------------------------------------------
+// CopyItemsToBufferL copies relation items to buffer
+// ------------------------------------------------
+//
+CMdCSerializationBuffer* CMdSNotifier::TEntry::CopyItemsToBufferL(
+		CMdCSerializationBuffer& aRelationItemsBuffer, 
+		const RArray<TItemId>& aIdArray)
+	{
+	const TUint32 count = aIdArray.Count();
+	aRelationItemsBuffer.PositionL( KNoOffset );
+	const TMdCItems& items = TMdCItems::GetFromBufferL( aRelationItemsBuffer );
+
+	CMdCSerializationBuffer* buffer = NULL;
+	if ( items.iRelations.iPtr.iCount == count )
+		{
+		buffer = CMdCSerializationBuffer::NewLC( aRelationItemsBuffer );
+		}
+	else
+		{
+		buffer = CMdCSerializationBuffer::NewLC( sizeof(TMdCItems)
+				+ count * sizeof(TMdCRelation) );
+
+		TMdCItems returnItems;
+		returnItems.iNamespaceDefId = items.iNamespaceDefId;
+		returnItems.iRelations.iPtr.iCount = count;
+		returnItems.iRelations.iPtr.iOffset = sizeof(TMdCItems);
+		buffer->PositionL( sizeof(TMdCItems) );
+
+		for( TInt i = 0; i < items.iRelations.iPtr.iCount; ++i )
+			{
+			TMdCRelation relation;
+			relation.DeserializeL( aRelationItemsBuffer );
+
+			if ( aIdArray.Find( relation.iId ) >= 0 )
+				{
+				relation.SerializeL( *buffer );
+				}
+			}
+		buffer->PositionL( KNoOffset );
+		returnItems.SerializeL( *buffer );
+		}
+	
+	CleanupStack::Pop( buffer );
+	return buffer;
+	}
+
+// ------------------------------------------------
+// CacheL caches the notification
+// ------------------------------------------------
+//
+void CMdSNotifier::TEntry::CacheL(TUint32 aCompleteCode, const RArray<TItemId>& aIdArray )
+    {
+    if ( aIdArray.Count() <= 0 )
+    	{
+    	return;
+    	}
+
+    CMdCSerializationBuffer* data = CopyToBufferL( aIdArray );
+    iSession.CacheNotificationL( iId, aCompleteCode, data );
+    }
+
+// ------------------------------------------------
+// CacheRelationItemsL caches the notification
+// ------------------------------------------------
+//
+void CMdSNotifier::TEntry::CacheRelationItemsL(TUint32 aCompleteCode,
+		CMdCSerializationBuffer& aBuffer, 
+		const RArray<TItemId>& aRelationIdArray )
+    {
+    CMdCSerializationBuffer* data = CopyItemsToBufferL( aBuffer, 
+    		aRelationIdArray );
+    iSession.CacheNotificationL(iId, aCompleteCode, data);
+    }
+
+// ------------------------------------------------
+// CacheL for schema mods
+// ------------------------------------------------
+//
+void CMdSNotifier::TEntry::CacheL(TUint32 aCompleteCode)
+    {
+    iSession.CacheNotificationL(iId, aCompleteCode, NULL);
+    }
+    
+// ------------------------------------------------
+// TriggerCachedL triggers a previously cached notification
+// ------------------------------------------------
+//
+void CMdSNotifier::TEntry::TriggerCachedL(TUint32 aCompleteCode, 
+		CMdCSerializationBuffer* aData)
+    {
+    TInt remoteSizeMsgSlot = iRemoteSizeMsgSlot;
+    iRemoteSizeMsgSlot = KErrNotFound;
+
+    __ASSERT_DEBUG( !iDataBuffer, MMdCCommon::Panic( KErrCorrupt ) );
+
+    if( aData )
+    	{
+    	iSession.SizeToRemoteL( iMessage, remoteSizeMsgSlot, aData->Size());
+    	}
+
+	iDataBuffer = aData;
+
+    __LOG2( ELogServer, "<- Notify trigger %d (%d)", iId, aCompleteCode );
+    iMessage.Complete( aCompleteCode );
+    }
+
+// ------------------------------------------------
+// SetupForCallback
+// ------------------------------------------------
+//
+void CMdSNotifier::TEntry::SetupForCallback(
+    RMessage2 aMessage, TInt aRemoteSizeMsgSlot )
+    {
+    __ASSERT_DEBUG( !IsPending(), MMdCCommon::Panic( KErrCorrupt ) );
+    iMessage = aMessage;
+    iRemoteSizeMsgSlot = aRemoteSizeMsgSlot;
+    }
+
+// ------------------------------------------------
+// GetDataBuffer
+// ------------------------------------------------
+//
+CMdCSerializationBuffer* CMdSNotifier::TEntry::GetDataBuffer()
+    {
+    CMdCSerializationBuffer* data = iDataBuffer;
+    iDataBuffer = NULL;
+    return data;
+    }
+
+// ------------------------------------------------
+// CreateEntry creates a new notifier entry
+// ------------------------------------------------
+//
+CMdSNotifier::TEntry& CMdSNotifier::CreateEntryL( TInt aId,
+    TConditionType aType, CMdCSerializationBuffer* aSerializedBuffer,
+    TDefId aNamespaceDefId, CMdSServerSession& aSession, TBool aConfidential )
+    {
+
+    User::LeaveIfError( iEntries.Append(
+        TEntry( aId, aType, aSerializedBuffer, aNamespaceDefId, aSession, aConfidential ) ) );
+    return iEntries[ iEntries.Count() - 1 ];
+    }
+
+// ------------------------------------------------
+// FindEntry
+// ------------------------------------------------
+//
+CMdSNotifier::TEntry& CMdSNotifier::FindEntryL( TInt aId )
+    {
+    CMdSNotifier::TEntry* entry = NULL;
+    
+    const TInt count = iEntries.Count();
+    
+    for ( TInt i = 0; i < count; ++i )
+        {
+        if ( iEntries[i].iId == aId )
+            {
+            entry = &iEntries[i];
+            break;
+            }
+        }
+
+    if( !entry )
+    	{
+    	User::Leave( KErrNotFound );
+    	}
+    
+    return *entry;
+    }
+
+// ------------------------------------------------
+// RemoveEntryL
+// ------------------------------------------------
+//
+void CMdSNotifier::RemoveEntryL( TInt aId )
+    {
+    const TInt count = iEntries.Count();
+    
+    for ( TInt i = 0; i < count; ++i )
+        {
+        TEntry& e = iEntries[i];
+        if ( e.iId == aId )
+            {
+            if ( e.IsPending() )
+                {
+                e.TriggerError( KErrCancel );
+                }
+            
+            if ( e.iSerializedCondition )
+            	{
+            	delete e.iSerializedCondition;
+            	e.iSerializedCondition = NULL;
+            	}
+            if ( e.iDataBuffer )
+            	{
+            	delete e.iDataBuffer;
+            	e.iDataBuffer = NULL;
+            	}
+            iEntries.Remove( i );
+            return;
+            }
+        }
+    User::Leave( KErrNotFound );
+    }
+
+// ------------------------------------------------
+// RemoveEntriesBySession
+// ------------------------------------------------
+//
+void CMdSNotifier::RemoveEntriesBySession(
+    const CMdSServerSession& aSession )
+    {
+    const TInt count = iEntries.Count();
+    
+    for ( TInt i = count; --i >= 0; )
+        {
+        TEntry& e = iEntries[i];
+        if ( &e.iSession == &aSession ) // pointer comparision
+            {
+            if ( e.IsPending() )
+                {
+                e.TriggerError( KErrCancel );
+                }
+            
+            delete e.iSerializedCondition;
+            delete e.iDataBuffer;
+            iEntries.Remove( i );
+            }
+        }
+    }
+
+// ------------------------------------------------
+// NotifyAdded
+// ------------------------------------------------
+//
+void CMdSNotifier::NotifyAddedL(CMdCSerializationBuffer& aSerializedItems, 
+							    CMdCSerializationBuffer& aSerializedItemIds)
+    {
+    const TInt count = iEntries.Count();
+    
+    for( TInt i = 0; i < count; ++i )
+        {
+        TEntry& e = iEntries[i];
+
+        if ( ! (e.iType & ( EObjectNotifyAdd | ERelationNotifyAdd | EEventNotifyAdd ) ) )
+        	{
+        	continue;
+        	}
+        
+        RArray<TItemId> matchingItemIdArray;
+   		CleanupClosePushL( matchingItemIdArray );
+
+		aSerializedItems.PositionL( KNoOffset );
+		aSerializedItemIds.PositionL( KNoOffset );
+
+		TBool someMatches = iComparator->MatchL( e.NamespaceDefId(), e.iType, e.Condition(), 
+												 aSerializedItems, aSerializedItemIds, 
+												 matchingItemIdArray,
+												 e.AllowConfidential() );
+
+        if( someMatches ) // check if there is some matches
+            {
+            if( e.IsPending() )
+            	{
+            	// match found. trigger notifier entry !
+	            TRAPD( err, e.TriggerL( EObjectNotifyAdd | ERelationNotifyAdd | EEventNotifyAdd,
+	            		matchingItemIdArray ) );
+	            if( err != KErrNone )
+	            	{
+	            	e.TriggerError( err );
+	            	}
+            	}
+            else
+            	{
+            	TRAP_IGNORE( e.CacheL( EObjectNotifyAdd | ERelationNotifyAdd | EEventNotifyAdd,
+            			matchingItemIdArray ) );
+            	}
+            }
+
+   		CleanupStack::PopAndDestroy( &matchingItemIdArray );
+        }
+    }
+
+// ------------------------------------------------
+// NotifyRemoved
+// ------------------------------------------------
+//
+void CMdSNotifier::NotifyRemovedL(CMdCSerializationBuffer& aSerializedItemIds, 
+								  TBool aItemIsConfidential)
+    {
+	aSerializedItemIds.PositionL( KNoOffset );
+
+	const TMdCItemIds& itemIds = TMdCItemIds::GetFromBufferL( aSerializedItemIds );
+
+    RArray<TItemId> objectIdArray;
+	CleanupClosePushL( objectIdArray );
+    RArray<TItemId> eventIdArray;
+	CleanupClosePushL( eventIdArray );
+    RArray<TItemId> relationIdArray;
+	CleanupClosePushL( relationIdArray );
+
+    //get removed item IDs
+	if( itemIds.iObjectIds.iPtr.iCount > 0 )
+		{
+		aSerializedItemIds.PositionL( itemIds.iObjectIds.iPtr.iOffset );
+
+    	objectIdArray.ReserveL( itemIds.iObjectIds.iPtr.iCount );
+    	for( TUint32 i = 0; i < itemIds.iObjectIds.iPtr.iCount; i++ )
+    		{
+    		TItemId objectId;
+    		aSerializedItemIds.ReceiveL( objectId );
+    		if ( objectId != KNoId )
+    			{
+    			objectIdArray.Append( objectId );
+    			}
+    		}
+		}
+	if( itemIds.iEventIds.iPtr.iCount > 0 )
+		{
+		aSerializedItemIds.PositionL( itemIds.iEventIds.iPtr.iOffset );
+
+    	eventIdArray.ReserveL( itemIds.iEventIds.iPtr.iCount );
+    	for( TUint32 i = 0; i < itemIds.iEventIds.iPtr.iCount; i++ )
+    		{
+    		TItemId eventId;
+    		aSerializedItemIds.ReceiveL( eventId );
+    		if ( eventId != KNoId )
+    			{
+    			eventIdArray.Append( eventId );
+    			}
+    		}
+		}
+	if( itemIds.iRelationIds.iPtr.iCount > 0 )
+		{
+		aSerializedItemIds.PositionL( itemIds.iRelationIds.iPtr.iOffset );
+
+    	relationIdArray.ReserveL( itemIds.iRelationIds.iPtr.iCount );
+    	for( TUint32 i = 0; i < itemIds.iRelationIds.iPtr.iCount; i++ )
+    		{
+    		TItemId relationId;
+    		aSerializedItemIds.ReceiveL( relationId );
+    		if ( relationId != KNoId )
+    			{
+    			relationIdArray.Append( relationId );
+    			}
+    		}
+		}
+
+	if( objectIdArray.Count() != 0 
+			|| eventIdArray.Count() != 0 
+			|| relationIdArray.Count() != 0 )
+		{
+		const TInt entriesCount = iEntries.Count();
+	    for( TInt i=0; i < entriesCount; ++i )
+	        {
+	        TEntry& e = iEntries[i];
+	        
+	        // if namespace definition IDs don't match skip listener entry
+	        if( e.NamespaceDefId() != itemIds.iNamespaceDefId )
+	        	{
+	        	continue;
+	        	}
+
+	        if(aItemIsConfidential && !e.AllowConfidential())
+	        	{
+	        	continue;	
+	        	}
+
+	        if( e.iType & EObjectNotifyRemove && objectIdArray.Count() > 0 )
+	            {
+	            // collect matching object IDs
+	            RArray<TItemId> matchingObjectIdArray;
+				CleanupClosePushL( matchingObjectIdArray );
+	
+	            TBool allMatches = iComparator->MatchObjectIdsL( e.Condition(),
+	            		objectIdArray, matchingObjectIdArray );
+	
+				// check is there any matches
+				if( allMatches || matchingObjectIdArray.Count() > 0 )
+	            	{
+	            	if(e.IsPending())
+	            		{
+		            	// Match found. Trigger notifier entry.
+		            	TInt err;
+		            	
+		            	if( allMatches )
+		            		{
+		            		// all matches so send whole object ID array
+		            		TRAP( err, e.TriggerL( EObjectNotifyRemove, 
+		            				objectIdArray ) );
+		            		}
+		            	else
+		            		{
+		            		TRAP( err, e.TriggerL( EObjectNotifyRemove, 
+		            				matchingObjectIdArray ) );
+		            		}
+	
+		            	if( err != KErrNone )
+			            	{
+			            	e.TriggerError( err );
+		    	        	}
+	            		}
+	            	else
+	            		{
+						if( allMatches )
+		            		{
+		            		// all matches so send whole object ID array
+	            			TRAP_IGNORE( e.CacheL( EObjectNotifyRemove, 
+	            					objectIdArray ) );
+		            		}
+		            	else
+		            		{
+		            		TRAP_IGNORE( e.CacheL( EObjectNotifyRemove, 
+		            				matchingObjectIdArray ) );
+		            		}
+	            		}
+	            	}
+	
+				CleanupStack::PopAndDestroy( &matchingObjectIdArray );
+				}
+	        else if( ( e.iType & EEventNotifyRemove ) 
+	        		&& eventIdArray.Count() > 0 )
+            	{
+				// event condition can't contain ID conditions, 
+            	// so get all IDs
+	        	if(e.IsPending())
+	        		{
+	            	// Match found. Trigger notifier entry.
+	            	TRAPD( err, e.TriggerL( EEventNotifyRemove, 
+	            			eventIdArray ) );
+	            	if( err != KErrNone )
+		            	{
+		            	e.TriggerError( err );
+	    	        	}
+	        		}
+	        	else
+	        		{
+	        		TRAP_IGNORE( e.CacheL( EEventNotifyRemove, 
+	        				eventIdArray ) );
+	        		}
+            	}
+	        else if( ( e.iType & ERelationNotifyRemove ) 
+	        		&& relationIdArray.Count() > 0 )
+            	{
+	            // relation condition can't contain ID conditions, 
+            	// so get all IDs
+	        	if(e.IsPending())
+	        		{
+	            	// Match found. Trigger notifier entry.
+	            	TRAPD( err, e.TriggerL( ERelationNotifyRemove, 
+	            			relationIdArray ) );
+	            	if( err != KErrNone )
+		            	{
+		            	e.TriggerError( err );
+	    	        	}
+	        		}
+	        	else
+	        		{
+	        		TRAP_IGNORE( e.CacheL( ERelationNotifyRemove, 
+	        				relationIdArray ) );
+	        		}
+            	}
+	        }
+		}
+
+	CleanupStack::PopAndDestroy( 3, &objectIdArray ); // relationIdArray, eventIdArray, objectIdArray
+    }
+
+// ------------------------------------------------
+// NotifyModified
+// ------------------------------------------------
+//
+void CMdSNotifier::NotifyModifiedL(CMdCSerializationBuffer& aSerializedItems, 
+							       CMdCSerializationBuffer& aSerializedItemIds)
+    {
+    const TInt count = iEntries.Count();
+    
+    for( TInt i = 0; i < count; ++i )
+        {
+        TEntry& e = iEntries[i];
+
+        if ( ! (e.iType & ( EObjectNotifyModify | ERelationNotifyModify /*| ERelationItemNotifyModify*/ ) ) )
+        	{
+        	continue;
+        	}
+  
+        RArray<TItemId> matchingObjectIdArray;
+		CleanupClosePushL( matchingObjectIdArray );
+
+		aSerializedItems.PositionL( KNoOffset );
+		aSerializedItemIds.PositionL( KNoOffset );
+
+		TBool someMatches = iComparator->MatchL( e.NamespaceDefId(), 
+				e.iType, e.Condition(), aSerializedItems, aSerializedItemIds, 
+				matchingObjectIdArray, e.AllowConfidential() );
+
+        if( someMatches ) // check if there is some matches
+            {
+            if( e.IsPending() )
+            	{
+            	// match found. trigger notifier entry !
+	            TRAPD( err, e.TriggerL( EObjectNotifyModify | ERelationNotifyModify /*| ERelationItemNotifyModify*/,
+	            		matchingObjectIdArray ) );
+	            if( err != KErrNone )
+	            	{
+	            	e.TriggerError( err );
+	            	}
+            	}
+            else
+            	{
+            	TRAP_IGNORE( e.CacheL( EObjectNotifyModify | ERelationNotifyModify /*| ERelationItemNotifyModify*/,
+            			matchingObjectIdArray ) );
+            	}
+            }
+
+		CleanupStack::PopAndDestroy( &matchingObjectIdArray );
+        }
+    }
+
+// ------------------------------------------------
+// NotifyModified
+// ------------------------------------------------
+//
+void CMdSNotifier::NotifyModifiedL(const RArray<TItemId>& aObjectIds)
+	{
+	if (aObjectIds.Count() == 0)
+    	{
+    	return;
+    	}
+
+    const TInt count = iEntries.Count();
+
+    for( TInt i = 0; i < count; ++i )
+        {
+        TEntry& e = iEntries[i];
+
+        if( e.iType & EObjectNotifyModify )
+            {
+            // collect matching object IDs
+            RArray<TItemId> matchingObjectIdArray;
+			CleanupClosePushL( matchingObjectIdArray );
+
+            TBool allMatches = iComparator->MatchObjectIdsL( e.Condition(), 
+            		aObjectIds, matchingObjectIdArray );
+
+			// check is there any matches
+			if( allMatches || matchingObjectIdArray.Count() > 0 )
+            	{
+            	if(e.IsPending())
+            		{
+	            	// Match found. Trigger notifier entry.
+	            	TInt err;
+
+	            	if( allMatches )
+	            		{
+	            		// all matches so send whole object ID array
+	            		TRAP( err, e.TriggerL( EObjectNotifyModify, 
+	            				aObjectIds ) );
+	            		}
+	            	else
+	            		{
+	            		TRAP( err, e.TriggerL( EObjectNotifyModify, 
+	            				matchingObjectIdArray ) );
+	            		}
+
+	            	if( err != KErrNone )
+		            	{
+		            	e.TriggerError( err );
+	    	        	}
+            		}
+            	else
+            		{
+					if( allMatches )
+	            		{
+	            		// all matches so send whole object ID array
+            			TRAP_IGNORE( e.CacheL( EObjectNotifyModify, 
+            					aObjectIds ) );
+	            		}
+	            	else
+	            		{
+	            		TRAP_IGNORE( e.CacheL( EObjectNotifyModify, 
+	            				matchingObjectIdArray ) );
+	            		}
+            		}
+            	}
+
+			CleanupStack::PopAndDestroy( &matchingObjectIdArray );
+            }
+        }
+	}
+
+// ------------------------------------------------
+// NotifyRemoved
+// ------------------------------------------------
+//
+void CMdSNotifier::NotifyRemovedL(const RArray<TItemId>& aItemIdArray)
+	{
+    for( TInt i=0; i<iEntries.Count(); ++i )
+        {
+        TEntry& e = iEntries[i];
+
+        if( e.iType & EObjectNotifyRemove )
+        	{
+            if( e.IsPending() )
+            	{
+	            TRAPD( err, e.TriggerL( EObjectNotifyRemove, aItemIdArray ) );
+	            if( err != KErrNone )
+	            	{
+	            	e.TriggerError( err );
+	            	}
+            	}
+            else
+            	{
+            	TRAP_IGNORE( e.CacheL( EObjectNotifyRemove, aItemIdArray ) );
+            	}
+        	}
+        }
+	}
+
+// ------------------------------------------------
+// NotifyObjectPresent
+// ------------------------------------------------
+//
+void CMdSNotifier::NotifyObjectPresent(TBool aPresent, const RArray<TItemId>& aObjectIds)
+    {
+    if (aObjectIds.Count() == 0)
+    	{
+    	return;
+    	}
+
+    const TInt count = iEntries.Count();
+    
+    for( TInt i = 0; i < count; ++i )
+        {
+        TEntry& e = iEntries[i];
+
+        // No condition matching, object present changes
+        // are always notified to object present observers
+        if( e.iType & ( EObjectNotifyPresent | EObjectNotifyNotPresent )  )
+            {
+            const TMdSObserverNotificationType objectState = 
+            	aPresent ? EObjectNotifyPresent : EObjectNotifyNotPresent;
+
+            if( e.IsPending() )
+            	{
+            	// match found. trigger notifier entry !
+	            TRAPD( err, e.TriggerL( objectState, aObjectIds ) );
+	            if( err != KErrNone )
+	            	{
+	            	e.TriggerError( err );
+	            	}
+            	}
+            else
+            	{
+            	TRAP_IGNORE( e.CacheL( objectState, aObjectIds ) );
+            	}
+            }
+        }
+    }
+
+// ------------------------------------------------
+// NotifyRelationPresent
+// ------------------------------------------------
+//
+void CMdSNotifier::NotifyRelationPresent(TBool aPresent, const RArray<TItemId>& aRelationIds)
+    {
+    if (aRelationIds.Count() == 0)
+    	{
+    	return;
+    	}
+
+    const TInt count = iEntries.Count();
+    
+    for( TInt i = 0; i < count; ++i )
+        {
+        TEntry& e = iEntries[i];
+
+        // No condition matching, relation present changes
+        // are always notified to relation present observers
+        if( e.iType & ( ERelationNotifyPresent | ERelationNotifyNotPresent ) )
+            {
+            const TMdSObserverNotificationType relationState = 
+            	aPresent ? ERelationNotifyPresent : ERelationNotifyNotPresent;
+
+            if( e.IsPending() )
+            	{
+            	// match found. trigger notifier entry !
+	            TRAPD( err, e.TriggerL( relationState, aRelationIds ) );
+	            if( err != KErrNone )
+	            	{
+	            	e.TriggerError( err );
+	            	}
+            	}
+            else
+            	{
+            	TRAP_IGNORE( e.CacheL( relationState, aRelationIds ) );
+            	}
+            }
+        }
+    }
+
+
+// ------------------------------------------------
+// NotifySchemaAdded
+// ------------------------------------------------
+//
+void CMdSNotifier::NotifySchemaAddedL()
+    {
+    const TInt count = iEntries.Count();
+    
+    for( TInt i = 0; i < count; ++i )
+        {
+        TEntry& e = iEntries[i];
+
+        // No condition matching, schema additions 
+        // are always notified to schema observers
+        if( e.iType == ESchemaModify )
+            {
+            if( e.IsPending() )
+            	{
+	            // match found. trigger notifier entry
+	            e.TriggerSchema();
+            	}
+            else
+            	{
+            	TRAP_IGNORE( e.CacheL( ESchemaModify ) );
+            	}
+            }
+        }
+    }
+
+
+// ------------------------------------------------
+// CheckForNotifier
+// ------------------------------------------------
+//
+TBool CMdSNotifier::CheckForNotifier( TUint32 aNotifyTypes )
+    {
+    const TInt count = iEntries.Count();
+    
+    for( TInt i = 0; i < count; ++i )
+        {
+        if ( iEntries[i].iType & aNotifyTypes )
+        	{
+        	return ETrue;
+        	}
+        }
+    return EFalse;
+    }
+
+void CMdSNotifier::NotifyRemovedRelationItemsL( 
+		CMdCSerializationBuffer& aBuffer )
+	{
+	aBuffer.PositionL( KNoOffset );
+
+	const TMdCItems& items = TMdCItems::GetFromBufferL( aBuffer );
+
+	if( items.iRelations.iPtr.iCount )
+		{
+		const TInt entriesCount = iEntries.Count();
+	    for( TInt i = 0; i < entriesCount; ++i )
+	        {
+	        TEntry& e = iEntries[i];
+	        
+	        // if namespace definition IDs don't match skip listener entry
+	        if( e.NamespaceDefId() != items.iNamespaceDefId )
+	        	{
+	        	continue;
+	        	}
+	        
+	        if( e.iType & ERelationItemNotifyRemove )
+            	{
+            	aBuffer.PositionL( items.iRelations.iPtr.iOffset );
+	            // check relations condition
+            	RArray<TItemId> matchedRelations;
+            	CleanupClosePushL( matchedRelations );
+            	TBool matches = iComparator->MatchRelationItemsL( 
+            			e.Condition(), aBuffer, matchedRelations );
+
+            	if ( matches )
+	        		{
+	        		if(e.IsPending())
+	        			{
+		            	// Match found. Trigger notifier entry.
+		            	TRAPD( err, e.TriggerRelationItemsL( 
+		            			ERelationItemNotifyRemove, aBuffer, 
+		            			matchedRelations ) );
+		            	if( err != KErrNone )
+			            	{
+			            	e.TriggerError( err );
+		    	        	}
+		        		}
+		        	else
+		        		{
+		        		TRAP_IGNORE( e.CacheRelationItemsL( 
+		        				ERelationItemNotifyRemove, aBuffer, 
+		        				matchedRelations ) );
+		        		}
+	        		}
+            	CleanupStack::PopAndDestroy( &matchedRelations );
+            	}
+	        }
+		}
+
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsnotifycomparator.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1277 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Comparator algorithms for notifier*
+*/
+
+#include "mdsnotifycomparator.h"
+
+#include "mdcresult.h"
+#include "mdcitem.h"
+#include "mdccommon.pan"
+#include "mdcserializationbuffer.h"
+#include "mderange.h"
+#include "mdscommoninternal.h"
+#include "mdcquery.h"
+#include "mdccommon.h"
+#include "mdeinternalerror.h"
+
+CMdSNotifyComparator* CMdSNotifyComparator::NewL()
+    {
+    CMdSNotifyComparator* that = CMdSNotifyComparator::NewLC();
+    CleanupStack::Pop( that );
+    return that;
+    }
+
+CMdSNotifyComparator* CMdSNotifyComparator::NewLC()
+	{
+	CMdSNotifyComparator* that = new(ELeave) CMdSNotifyComparator();
+	CleanupStack::PushL( that );
+	that->ConstructL();
+	return that;
+	}
+
+
+CMdSNotifyComparator::~CMdSNotifyComparator()
+    {
+    
+    }
+
+CMdSNotifyComparator::CMdSNotifyComparator()
+    {
+    
+    }
+
+void CMdSNotifyComparator::ConstructL()
+    {
+    }
+
+TBool CMdSNotifyComparator::MatchL(
+	TDefId aNamespaceDefId, TUint32 aType,
+    CMdCSerializationBuffer& aSerializedCondition,
+    CMdCSerializationBuffer& aSerializedItems,
+    CMdCSerializationBuffer& aSerializedItemIds,
+    RArray<TItemId>& aMatchingItemIdArray,
+    TBool aAllowConfidential)
+    {
+    const TMdCItems& items = TMdCItems::GetFromBufferL( aSerializedItems );
+
+    const TMdCItemIds& itemIds = TMdCItemIds::GetFromBufferL( aSerializedItemIds );
+
+	// check if some namespace definitions are not the same
+    if( itemIds.iNamespaceDefId != aNamespaceDefId )
+    	{
+    	return EFalse;
+    	}
+
+    if( ( items.iObjects.iPtr.iCount > 0 ) && 
+    	( itemIds.iObjectIds.iPtr.iCount > 0 ) && 
+    	( aType & ( EObjectNotifyAdd | EObjectNotifyModify ) ) )
+    	{
+    	// object ID count and object item count should match
+		__ASSERT_DEBUG( items.iObjects.iPtr.iCount == itemIds.iObjectIds.iPtr.iCount, MMdCCommon::Panic( KErrCorrupt ) );
+
+    	aSerializedItemIds.PositionL( itemIds.iObjectIds.iPtr.iOffset );
+    	for( TUint32 i = 0; i < itemIds.iObjectIds.iPtr.iCount; i++ )
+    		{
+    		TItemId objectId;
+    		aSerializedItemIds.ReceiveL( objectId );
+
+    		if( aSerializedCondition.Size() > 0 )
+    			{
+	            TBool results( EFalse );
+	            TBool succeed( EFalse );
+    			
+	            // move condition buffer's position beginnig of the buffer
+	            aSerializedCondition.PositionL( KNoOffset  );
+	            
+	            const TMdCLogicCondition& logicCondition = 
+	            		TMdCLogicCondition::GetFromBufferL( aSerializedCondition );
+
+	            for ( TUint32 j = 0; j < logicCondition.iChildConditions.iPtr.iCount; j++ )
+	                {
+		    		// set correct position to item buffer
+	    	    	aSerializedItems.PositionL( items.iObjects.iPtr.iOffset + 
+	    	    			i * sizeof(TMdCObject) );
+
+	    	    	// set correct positin to condition buffer
+	    	    	aSerializedCondition.PositionL( 
+	    	    			logicCondition.iChildConditions.iPtr.iOffset + 
+	    	    			j * CMdCSerializationBuffer::KRequiredSizeForTUint32 );
+	    	    	TUint32 conditionOffset;
+	    	    	aSerializedCondition.ReceiveL( conditionOffset );
+	    	    	aSerializedCondition.PositionL( conditionOffset );
+
+	                results = MatchObjectL( aSerializedCondition, 
+	                		aSerializedItems, objectId, aAllowConfidential );
+
+	                succeed = results;
+	                if ( logicCondition.iOperator == ELogicConditionOperatorAnd )
+	                    {
+	                    if( !results )
+	                        {
+	                        break;
+	                        }
+	                    }
+
+	                if ( logicCondition.iOperator == ELogicConditionOperatorOr )
+	                    {
+	                    if( results )
+	                        {
+	                        break;
+	                        }
+	                    }
+	                }
+    		
+	            if ( logicCondition.iNegated )    
+	                {
+	                succeed = !( succeed );
+	                }
+
+	    	    if ( succeed )    
+	                {
+	                aMatchingItemIdArray.AppendL( objectId );
+	                }
+    			}
+    		else
+    			{
+    			aMatchingItemIdArray.AppendL( objectId );
+    			}
+    		}
+    	}
+    else if( ( items.iEvents.iPtr.iCount > 0 ) && 
+    		 ( itemIds.iEventIds.iPtr.iCount > 0 ) && 
+    		 ( aType & ( EEventNotifyAdd /*| EEventNotifyRemove*/ ) ) )
+    	{
+    	// event ID count and event item count should match
+		__ASSERT_DEBUG( items.iEvents.iPtr.iCount == itemIds.iEventIds.iPtr.iCount, MMdCCommon::Panic( KErrCorrupt ) );
+
+		aSerializedItemIds.PositionL( itemIds.iEventIds.iPtr.iOffset );
+    	for( TUint32 i = 0; i < itemIds.iEventIds.iPtr.iCount; i++ )
+    		{
+    		TItemId eventId;
+    		aSerializedItemIds.ReceiveL( eventId );
+    		
+    		if( aSerializedCondition.Size() > 0 )
+    			{
+	    		// set correct position to item buffer
+	    		aSerializedItems.PositionL( items.iEvents.iPtr.iOffset + i * sizeof(TMdCEvent) );
+
+	    		// move condition buffer's position to the begin of the buffer
+	    		aSerializedCondition.PositionL( KNoOffset );
+
+	    		if( MatchEventL( aSerializedCondition, aSerializedItems, eventId ) )
+	    			{
+	    			aMatchingItemIdArray.AppendL( eventId );
+	    			}
+    			}
+    		else
+    			{
+    			aMatchingItemIdArray.AppendL( eventId );
+    			}
+    		}
+    	}
+    else if( ( items.iRelations.iPtr.iCount > 0 ) && 
+    		 ( itemIds.iRelationIds.iPtr.iCount > 0 ) && 
+    		 ( aType & ( ERelationNotifyAdd | ERelationNotifyModify /*| ERelationNotifyRemove*/ ) ) )
+    	{
+    	// relation ID count and relation item count should match
+		__ASSERT_DEBUG( items.iRelations.iPtr.iCount == itemIds.iRelationIds.iPtr.iCount, MMdCCommon::Panic( KErrCorrupt ) );
+
+    	aSerializedItemIds.PositionL( itemIds.iRelationIds.iPtr.iOffset );
+    	for( TUint32 i = 0; i < itemIds.iRelationIds.iPtr.iCount; i++ )
+    		{
+    		TItemId relationId;
+    		aSerializedItemIds.ReceiveL( relationId );
+
+			if( aSerializedCondition.Size() > 0 )
+				{
+	    		// set correct position to item buffer
+	    		aSerializedItems.PositionL( items.iRelations.iPtr.iOffset
+	    				+ i * sizeof(TMdCRelation) );
+
+	    		// move condition buffer's position to the begin of the buffer
+	    		aSerializedCondition.PositionL( KNoOffset );
+
+	    		if( MatchRelationL( aSerializedCondition, aSerializedItems, relationId ) )
+	    			{
+	    			aMatchingItemIdArray.AppendL( relationId );
+	    			}
+				}
+			else
+				{
+				aMatchingItemIdArray.AppendL( relationId );
+				}
+    		}
+    	}
+
+    if( aMatchingItemIdArray.Count() > 0 )
+    	{
+    	return ETrue;
+    	}
+    else
+    	{
+    	return EFalse;
+    	}
+    }
+
+TBool CMdSNotifyComparator::MatchObjectL(
+		CMdCSerializationBuffer& aSerializedCondition,
+		CMdCSerializationBuffer& aSerializedItem, TItemId aObjectId, 
+		TBool aAllowConfidential )
+	{
+ 	// check if object is failed
+	if( aObjectId == KNoId )
+		{
+		return EFalse;
+		}
+
+	// Check type
+	const TMdCCondition& condition = 
+			TMdCCondition::GetFromBufferL( aSerializedCondition );
+
+	switch( condition.iConditionType )
+		{
+	    case EConditionTypeObject:
+	        {
+	    	return ( CheckObjectL( aSerializedCondition, aSerializedItem, 
+	    			aAllowConfidential ) );
+	    	}
+		case EConditionTypeProperty:
+		case EConditionTypePropertyIntRange:
+		case EConditionTypePropertyInt64Range:
+		case EConditionTypePropertyUintRange:
+		case EConditionTypePropertyRealRange:
+		case EConditionTypePropertyTimeRange:
+	    case EConditionTypePropertyText:
+    	case EConditionTypePropertyBool:
+	        {
+   			return ( CheckPropertyL( aSerializedCondition, aSerializedItem ) );
+	    	}
+    	default:
+#ifdef _DEBUG
+    		User::Panic( _L("MdSNCMaO") , KErrMdEUnknownConditionType );
+#endif    		
+    	    break;
+		}
+
+	return EFalse;
+	}
+
+TBool CMdSNotifyComparator::CheckPropertyL( 
+		CMdCSerializationBuffer& aSerializedCondition,
+    	CMdCSerializationBuffer& aSerializedItem )
+    {
+    const TMdCObject& object = TMdCObject::GetFromBufferL( aSerializedItem );
+    
+    const TMdCPropertyCondition& propertyCondition = 
+    		TMdCPropertyCondition::GetFromBufferL( aSerializedCondition );
+
+    for( TUint32 i=0; i < object.iProperties.iPtr.iCount; i++ )
+        {
+        aSerializedItem.PositionL( object.iProperties.iPtr.iOffset
+        		+ i * sizeof(TMdCProperty) );
+        const TMdCProperty& property = TMdCProperty::GetFromBufferL( aSerializedItem );
+
+        // check propertyDefId doesn't match -> skip it
+        if( property.iPropertyDefId == propertyCondition.iPropertyDefId )
+            {
+            // move condition buffer to begin of the condition
+            aSerializedCondition.PositionL( propertyCondition.iCondition );
+
+            switch( propertyCondition.iConditionType )
+	            {
+	            case EConditionTypeProperty:
+	            	{
+		            // check only if existing condition is negated
+	            	if( propertyCondition.iNegated )
+	            		{
+	            		return EFalse;
+	            		}
+	            	else
+	            		{
+	            		return ETrue;
+	            		}
+	            	}
+	            
+   	            case EConditionTypePropertyIntRange:
+	                {
+		            TInt32 rangeType32( 0 );
+		            aSerializedCondition.ReceiveL( rangeType32 );
+		            const TMdERangeType rangeType = ( TMdERangeType )rangeType32;
+
+		            TMdCValueUnion minValue;
+                    aSerializedCondition.ReceiveL( minValue );
+                    TMdCValueUnion maxValue;
+                    aSerializedCondition.ReceiveL( maxValue );
+
+		            // init range for next test
+                    TMdEIntRange range( minValue.iInt32, maxValue.iInt32, 
+                    		rangeType );
+		            
+   	                if( range.InRange( property.iValue.iInt32 ) == propertyCondition.iNegated )
+                        {
+                        return EFalse;
+                        }   
+	                break;
+	                }
+	            case EConditionTypePropertyInt64Range:
+	                {
+		            TInt32 rangeType32( 0 );
+		            aSerializedCondition.ReceiveL( rangeType32 );
+		            const TMdERangeType rangeType = ( TMdERangeType )rangeType32;
+
+		            TMdCValueUnion minValue;
+                    aSerializedCondition.ReceiveL( minValue );
+                    TMdCValueUnion maxValue;
+                    aSerializedCondition.ReceiveL( maxValue );
+
+                    // init range for next test
+                    TMdEInt64Range range( minValue.iInt64, maxValue.iInt64, 
+                    		rangeType );
+                    
+                    // test if valueType is in the range
+                    if( range.InRange( property.iValue.iInt64 ) == propertyCondition.iNegated )
+                        {
+                        return EFalse;
+                        }	                
+	                break;
+	                }
+	            case EConditionTypePropertyUintRange:
+	                {
+		            TInt32 rangeType32( 0 );
+		            aSerializedCondition.ReceiveL( rangeType32 );
+		            const TMdERangeType rangeType = ( TMdERangeType )rangeType32;
+
+		            TMdCValueUnion minValue;
+                    aSerializedCondition.ReceiveL( minValue );
+                    TMdCValueUnion maxValue;
+                    aSerializedCondition.ReceiveL( maxValue );
+
+                    // init range for next test
+                    TMdEUintRange range( minValue.iUint32, maxValue.iUint32, 
+                    		rangeType );
+	               
+   	                if( range.InRange( property.iValue.iUint32 ) == propertyCondition.iNegated )
+                        {
+                        return EFalse;
+                        }   
+	                break;
+	                }
+	            case EConditionTypePropertyRealRange:
+	                {
+		            TInt32 rangeType32( 0 );
+		            aSerializedCondition.ReceiveL( rangeType32 );
+		            const TMdERangeType rangeType = ( TMdERangeType )rangeType32;
+
+		            TMdCValueUnion minValue;
+                    aSerializedCondition.ReceiveL( minValue );
+                    TMdCValueUnion maxValue;
+                    aSerializedCondition.ReceiveL( maxValue );
+                    
+                    // init range for next test
+                    TMdERealRange range( minValue.iReal, maxValue.iReal, rangeType );
+
+                    // test if valueType is in the range
+                    if( range.InRange( property.iValue.iReal ) == propertyCondition.iNegated )
+                        {
+                        return EFalse;
+                        }	                
+	                break;
+	                }
+	            case EConditionTypePropertyTimeRange:
+                    {
+		            TInt32 rangeType32( 0 );
+		            aSerializedCondition.ReceiveL( rangeType32 );
+		            TMdERangeType rangeType = ( TMdERangeType )rangeType32;
+
+		            TMdCValueUnion minValue;
+                    aSerializedCondition.ReceiveL( minValue );
+                    TMdCValueUnion maxValue;
+                    aSerializedCondition.ReceiveL( maxValue );
+
+                    // init range for next test
+                    TMdETimeRange range( minValue.iInt64, maxValue.iInt64, 
+                    		rangeType );
+
+	                TTime value( property.iValue.iInt64 );
+                    // test if valueType is in the range
+                    if( range.InRange( property.iValue.iInt64 ) == propertyCondition.iNegated )
+                        {
+                        return EFalse;
+                        }	                
+                    break;
+                    }
+                case EConditionTypePropertyText:
+	                {
+	                // SerializedItem
+	                aSerializedItem.PositionL( property.iValue.iPtr.iOffset );
+	                TPtrC16 value = aSerializedItem.ReceivePtr16L();
+
+	                // ConditionItem
+	                TUint32 condCompareMethod( 0 );
+	                aSerializedCondition.ReceiveL( condCompareMethod );
+	                TPtrC16 condValue = aSerializedCondition.ReceivePtr16L();
+
+                    //Check, that compare method is in range
+#ifdef _DEBUG
+	                if( condCompareMethod <= ETextPropertyConditionCompareFirst || condCompareMethod >= ETextPropertyConditionCompareLast )
+	                	{
+						User::Panic( _L("MdSNCCP1") , KErrMdEUnknownConditionCompareMethod );
+	                	}
+#endif
+	                TBool compareResult( EFalse );
+
+	                switch( condCompareMethod )
+		                {
+	                    case ETextPropertyConditionCompareEquals:
+	   		                {
+	   		                if( (value == condValue ) )
+	   		                    {
+	   		                    compareResult = EFalse;
+	   		                    }
+	   		                break;
+	   		                }
+	                    case ETextPropertyConditionCompareContains:
+	   		                {
+	   		                compareResult = FindDes( value, condValue ); 
+	   		                break;
+	   		                }
+	                    case ETextPropertyConditionCompareBeginsWith:
+	   		                {
+	   		                compareResult = CompareDesBeginsWith( value, condValue ); 
+                            break;	   		               
+	   		                }
+	                    case ETextPropertyConditionCompareEndsWith:
+	                        {
+	   		                compareResult = CompareDesEndsWith( value, condValue );
+                            break;	   		               
+	   		                }
+                        default: 
+                            {
+#ifdef _DEBUG
+                            User::Panic( _L("MdSNCCP2") , KErrMdEUnknownConditionCompareMethod );
+#endif
+   		                    }
+		                }          
+	                
+	                if( compareResult == propertyCondition.iNegated )
+	                    {
+	                    return EFalse;
+	                    }
+	                break;
+	                }
+	            case EConditionTypePropertyBool:
+    		        {
+			        const TBool value( property.iValue.iInt32 );
+
+			        TBool condValue( EFalse );
+			        aSerializedCondition.ReceiveL( condValue );
+
+			        if( ( value == condValue ) == propertyCondition.iNegated )
+				        {
+				        return EFalse;
+				        }
+			        break;
+    		        }
+	            default:
+	            	{
+#ifdef _DEBUG
+                    User::Panic( _L("MdSNCCP3") , KErrMdEUnknownConditionType );
+#endif
+	            	User::Leave( KErrMdEUnknownConditionType );
+	            	}
+	            } // switch
+
+            return ETrue;
+
+            } // if
+
+        } // for
+
+    return EFalse;
+    }
+
+TBool CMdSNotifyComparator::CheckObjectL( CMdCSerializationBuffer& aSerializedCondition,
+    			   						  CMdCSerializationBuffer& aSerializedItem,
+    			   						  TBool aAllowConfidential )
+    {
+    const TMdCObject& object = TMdCObject::GetFromBufferL( aSerializedItem );
+
+	const TBool confidential = object.iFlags & EMdEObjectFlagConfidential;
+
+	// check if object is confidential and confidentials are not allowed
+	if( confidential && ( aAllowConfidential == EFalse ) )
+		{
+		return EFalse;
+		}
+
+	// check if no condition defined
+	if( aSerializedCondition.Size() <= 0 )
+		{
+		// pass all successful objects
+		return ETrue;
+		}
+
+	const TMdCObjectCondition& condition = 
+			TMdCObjectCondition::GetFromBufferL( aSerializedCondition );
+
+	switch( condition.iConfidentialityLevel )
+		{
+	    case EObjectConditionLevelNormal:
+	    	if( confidential )
+	    		{
+	    		return EFalse;
+	    		}
+			break;
+		case EObjectConditionLevelConfidential:
+	    	if( confidential == EFalse )
+	    		{
+	    		return EFalse;
+	    		}
+			break;
+
+	    default:
+	    	{
+#ifdef _DEBUG
+            User::Panic( _L("MdSNCCO1") , KErrMdEUnknownConfidentialityLevel );
+#endif	    	
+	    	User::Leave( KErrMdEUnknownConfidentialityLevel );
+	    	}
+		}
+
+	if( ( condition.iFlags & EMdEObjectFlagPlaceholder ) && 
+			( object.iFlags & EMdEObjectFlagPlaceholder ) )
+		{
+		return EFalse;
+		}
+
+	// move position to begin of sub condition
+	aSerializedCondition.PositionL( condition.iCondition );
+	
+	switch( condition.iCompareMethod )
+		{
+		case EObjectConditionCompareNone:
+			break;
+
+		case EObjectConditionCompareId:
+			{
+			TItemId conditionObjectId;
+			aSerializedCondition.ReceiveL( conditionObjectId );
+
+			if( ( conditionObjectId == object.iId ) == condition.iNegated )
+				{
+				return EFalse;
+				}
+			}
+			break;
+
+        case EObjectConditionCompareUsageCount:
+			{
+			TInt32 rangeType32;
+			aSerializedCondition.ReceiveL( rangeType32 );
+			const TMdERangeType rangeType = (TMdERangeType)rangeType32;
+
+			TMdCValueUnion minValue;
+			aSerializedCondition.ReceiveL( minValue );
+			TMdCValueUnion maxValue;
+			aSerializedCondition.ReceiveL( maxValue );
+
+			// init range for next test
+			TMdEUintRange range( minValue.iUint32, maxValue.iUint32, 
+					rangeType );
+
+			// test if event's creation time is in the range
+			if( BoolEqual( range.InRange( object.iUsageCount ), condition.iNegated ) )
+				{
+				return EFalse;
+				}
+			}
+			break;
+
+		case EObjectConditionCompareGuid:
+			{
+			TInt64 conditionGuidHigh;
+			aSerializedCondition.ReceiveL( conditionGuidHigh );
+			TInt64 conditionGuidLow;
+			aSerializedCondition.ReceiveL( conditionGuidLow );
+
+			if( ( ( conditionGuidHigh == object.iGuidHigh ) && 
+				( conditionGuidLow == object.iGuidLow ) ) == 
+				condition.iNegated )
+				{
+				return EFalse;
+				}
+			}
+			break;
+
+        case EObjectConditionCompareObjectDef:
+			{
+			TDefId conditionObjectDefId;
+			aSerializedCondition.ReceiveL( conditionObjectDefId );
+
+			if( ( conditionObjectDefId == object.iDefId ) == condition.iNegated )
+				{
+				return EFalse;
+				}
+			}
+			break;
+
+        case EObjectConditionCompareUri:
+			{
+			aSerializedItem.PositionL( object.iUri.iPtr.iOffset );
+			TPtrC16 uri = aSerializedItem.ReceivePtr16L();
+
+			TPtrC16 conditionUri = aSerializedCondition.ReceivePtr16L();
+
+			if( ( conditionUri.Compare( uri ) == 0 ) == condition.iNegated )
+				{
+				return EFalse;
+				}
+			}
+			break;
+
+        case EObjectConditionCompareUriBeginsWith:
+			{
+			aSerializedItem.PositionL( object.iUri.iPtr.iOffset );
+			TPtrC16 uri = aSerializedItem.ReceivePtr16L();
+
+			TPtrC16 conditionUri = aSerializedCondition.ReceivePtr16L();
+
+			if( CompareDesBeginsWith( uri, conditionUri ) == condition.iNegated )
+				{
+				return EFalse;
+				}
+			}
+			break;
+
+	    default:
+	    	{
+#ifdef _DEBUG
+            User::Panic( _L("MdSNCCO2") , KErrMdEUnknownConditionCompareMethod );
+#endif	    	
+	    	User::Leave( KErrMdEUnknownConditionCompareMethod );
+	    	}
+		}
+
+	return ETrue;
+    }
+
+
+TBool CMdSNotifyComparator::MatchEventL(CMdCSerializationBuffer& aSerializedCondition,
+					    			    CMdCSerializationBuffer& aSerializedItem,
+					    			    TItemId aEventId)
+	{
+	const TMdCEvent& event = TMdCEvent::GetFromBufferL( aSerializedItem );
+
+	// check if event is failed
+	if( aEventId == 0 )
+		{
+		return EFalse;
+		}
+
+	// check if no condition defined
+	if( aSerializedCondition.Size() <= 0 )
+		{
+		// pass all successful events
+		return ETrue;
+		}
+
+	const TMdCEventCondition& eventCondition = 
+			TMdCEventCondition::GetFromBufferL( aSerializedCondition );
+
+	// check if event condition contains event ID comparsion
+	if( eventCondition.iEventId != KNoId )
+		{
+		if( ( eventCondition.iEventId == event.iId ) == eventCondition.iNegated )
+			{
+			return EFalse;
+			}
+		}
+
+	// check if event condition contains event def ID comparsion
+	if( eventCondition.iEventDefId != KNoDefId )
+		{
+		if( ( eventCondition.iEventDefId == event.iDefId ) == eventCondition.iNegated )
+			{
+			return EFalse;
+			}
+		}
+
+	// check event condition contains event creation time range comparision
+	if( eventCondition.iCreationTimeRange != KNoOffset )
+		{
+		aSerializedCondition.PositionL( eventCondition.iCreationTimeRange );
+
+		TInt32 rangeType32;
+		aSerializedCondition.ReceiveL( rangeType32 );
+		const TMdERangeType rangeType = (TMdERangeType)rangeType32;
+
+		TMdCValueUnion minValue;
+		aSerializedCondition.ReceiveL( minValue );
+		TMdCValueUnion maxValue;
+		aSerializedCondition.ReceiveL( maxValue );
+
+		// init range for next test
+		TMdEInt64Range range( minValue.iInt64, maxValue.iInt64, rangeType );
+
+		// test if event's creation time is in the range
+		if( range.InRange( event.iTime.Int64() ) == eventCondition.iNegated )
+			{
+			return EFalse;
+			}
+		}
+
+	// check object condition 
+	// (only accept OR-logic condition which contains object ID condition(s))
+	if( eventCondition.iObjectCondition != KNoOffset )
+		{
+		aSerializedCondition.PositionL( eventCondition.iObjectCondition );
+
+		if( MatchObjectIdToObjectIdConditionsL( aSerializedCondition, 
+				event.iObjectId ) == eventCondition.iNegated )
+			{
+			return EFalse;
+			}
+		}
+
+	// check event condition contains source or participant comparsion
+	if( ( EEventConditionCompareSourceURI == eventCondition.iCompareMethod ) || 
+		( EEventConditionCompareParticipantURI == eventCondition.iCompareMethod ) )
+		{
+		aSerializedCondition.PositionL( eventCondition.iUriCondition );
+
+		TPtrC16 eventConditionUri = aSerializedCondition.ReceivePtr16L();
+
+		// source comparsion
+		if( EEventConditionCompareSourceURI == eventCondition.iCompareMethod )
+			{
+			TPtrC16 eventSource( KNullDesC );
+			if ( event.iSourceText.iPtr.iCount > 0 )
+				{
+				aSerializedItem.PositionL( event.iSourceText.iPtr.iOffset );
+				eventSource.Set( aSerializedItem.ReceivePtr16L() );
+				}
+
+			if( ( eventConditionUri.Compare( eventSource ) == 0 ) == eventCondition.iNegated )
+				{
+				return EFalse;
+				}
+			}
+		// participant comparsion
+		else
+			{
+			TPtrC16 eventParticipant( KNullDesC );
+			if (event.iParticipantText.iPtr.iCount > 0)
+				{
+				aSerializedItem.PositionL( event.iParticipantText.iPtr.iOffset );
+				eventParticipant.Set( aSerializedItem.ReceivePtr16L() );
+				}
+
+			if( ( eventConditionUri.Compare( eventParticipant ) == 0 ) == eventCondition.iNegated )
+				{
+				return EFalse;
+				}
+			}
+		}
+
+	return ETrue;
+	}
+
+TBool CMdSNotifyComparator::MatchRelationL(CMdCSerializationBuffer& aSerializedCondition,
+    				 					   CMdCSerializationBuffer& aSerializedItem,
+    				 					   TItemId aRelationId)
+	{
+    const TMdCRelation& relation = 
+    		TMdCRelation::GetFromBufferL( aSerializedItem );
+
+	// check if event is failed
+	if( aRelationId == 0 )
+		{
+		return EFalse;
+		}
+
+	// check if no condition defined
+	if( aSerializedCondition.Size() <= 0 )
+		{
+		// pass all successful events
+		return ETrue;
+		}
+
+	const TMdCRelationCondition& relationCondition = 
+			TMdCRelationCondition::GetFromBufferL( aSerializedCondition );
+
+	// check if relation condition contains relation def ID comparsion
+	if( relationCondition.iRelationDefId != KNoDefId &&
+		BoolEqual( relationCondition.iRelationDefId == relation.iDefId, 
+				relationCondition.iNegated ) )
+		{
+		return EFalse;
+		}
+
+	if ( relationCondition.iRelationId != KNoId &&
+		 	 BoolEqual( relationCondition.iRelationId == aRelationId, 
+		 			 relationCondition.iNegated ) )
+		{
+		return EFalse;
+		}
+	
+	if ( relationCondition.iRelationIds.iPtr.iOffset != KNoOffset &&
+			BoolEqual( MatchRelationIdsL( relationCondition, 
+					aSerializedCondition, aRelationId ), 
+					relationCondition.iNegated ) )
+		{
+		return EFalse;
+		}
+
+	if( relationCondition.iGuid != KNoOffset )
+		{
+		TInt64 conditionGuidHigh;
+		aSerializedCondition.ReceiveL( conditionGuidHigh );
+		TInt64 conditionGuidLow;
+		aSerializedCondition.ReceiveL( conditionGuidLow );
+
+		if ( conditionGuidHigh != 0 && conditionGuidLow != 0 &&
+			 ( BoolEqual( conditionGuidHigh == relation.iGuidHigh, 
+					 relationCondition.iNegated ) ||
+			   BoolEqual( conditionGuidHigh == relation.iGuidLow, 
+					   relationCondition.iNegated ) ) )
+			{
+			return EFalse;
+			}
+		}
+
+	// check relation condition contains relation parameter range comparision
+	if( relation.iParameter != KNoOffset )
+		{
+		aSerializedCondition.PositionL( relation.iParameter );
+		
+		TInt32 rangeType32;
+		aSerializedCondition.ReceiveL( rangeType32 );
+		const TMdERangeType rangeType = (TMdERangeType)rangeType32;
+
+		TMdCValueUnion minValue;
+		aSerializedCondition.ReceiveL( minValue );
+		TMdCValueUnion maxValue;
+		aSerializedCondition.ReceiveL( maxValue );
+
+		// init range for next test
+		TMdEIntRange range( minValue.iInt32, maxValue.iInt32, rangeType );
+
+		// test if event's creation time is in the range
+		if( BoolEqual( range.InRange( relation.iParameter ), 
+				relationCondition.iNegated ) )
+			{
+			return EFalse;
+			}
+		}
+
+	if( relationCondition.iLeftObjectCondition != KNoOffset && 
+			ERelationConditionSideLeft == relationCondition.iObjectSide )
+		{
+		aSerializedCondition.PositionL( relationCondition.iLeftObjectCondition );
+
+		if( BoolEqual( MatchObjectIdToObjectIdConditionsL(
+				aSerializedCondition, relation.iLeftObjectId ), 
+				relationCondition.iNegated ) )
+			{
+			return EFalse;
+			}
+		}
+
+	if( relationCondition.iRightObjectCondition != KNoOffset && 
+			ERelationConditionSideRight  == relationCondition.iObjectSide )
+		{
+		aSerializedCondition.PositionL( 
+				relationCondition.iRightObjectCondition );
+
+		if( BoolEqual( MatchObjectIdToObjectIdConditionsL(
+				aSerializedCondition, relation.iRightObjectId ), 
+				relationCondition.iNegated ) )
+			{
+			return EFalse;
+			}
+		}
+
+	if ( ( relationCondition.iLeftObjectCondition != KNoOffset || 
+			relationCondition.iRightObjectCondition != KNoOffset ) && 
+			ERelationConditionSideEither == relationCondition.iObjectSide )
+		{
+		TBool eitherMatches = EFalse;
+		
+		if ( relationCondition.iLeftObjectCondition != KNoOffset )
+			{
+			aSerializedCondition.PositionL( 
+					relationCondition.iLeftObjectCondition );
+	
+			if( !BoolEqual( MatchObjectIdToObjectIdConditionsL(
+					aSerializedCondition, relation.iLeftObjectId ), 
+					relationCondition.iNegated ) )
+				{
+				eitherMatches = ETrue;
+				}
+			}
+		
+		if ( relationCondition.iRightObjectCondition != KNoOffset )
+			{
+			aSerializedCondition.PositionL( 
+					relationCondition.iRightObjectCondition );
+
+			if( !BoolEqual( MatchObjectIdToObjectIdConditionsL(
+					aSerializedCondition, relation.iRightObjectId ), 
+					relationCondition.iNegated ) )
+				{
+				eitherMatches = ETrue;
+				}
+			}
+
+		// left and right condition didn't match
+		if( !eitherMatches )
+			{
+			return EFalse;
+			}
+		}
+
+	if ( relationCondition.iLastModifiedDateRange != KNoOffset )
+		{
+		aSerializedCondition.PositionL( 
+				relationCondition.iLastModifiedDateRange );
+
+		TInt32 rangeRule;
+		aSerializedCondition.ReceiveL( rangeRule );
+		const TMdERangeType rangeType = (TMdERangeType)rangeRule;
+
+		TMdCValueUnion minValue;
+		aSerializedCondition.ReceiveL( minValue );
+		TMdCValueUnion maxValue;
+		aSerializedCondition.ReceiveL( maxValue );
+
+		// init range for next test
+		TMdEInt64Range range( minValue.iInt64, maxValue.iInt64, rangeType );
+
+		// test if event's creation time is in the range
+		if( BoolEqual( range.InRange( relation.iLastModifiedDate.Int64() ), 
+				relationCondition.iNegated ) )
+			{
+			return EFalse;
+			}
+		}
+
+	return ETrue;
+	}
+
+TBool CMdSNotifyComparator::MatchObjectIdsL(
+						    CMdCSerializationBuffer& aSerializedCondition,
+						    const RArray<TItemId>& aItemIdArray,
+						    RArray<TItemId>& aMatchingItemIdArray
+						    )
+	{
+	// check if condition buffer contains condition
+	if( aSerializedCondition.Size() > 0 )
+		{
+		aSerializedCondition.PositionL( KNoOffset );
+
+		const TMdCLogicCondition& logicCondition = 
+				TMdCLogicCondition::GetFromBufferL( aSerializedCondition );
+
+		for( TUint32 i = 0; i < logicCondition.iChildConditions.iPtr.iCount; i++ )
+		    {
+	       	aSerializedCondition.PositionL( 
+	       			logicCondition.iChildConditions.iPtr.iOffset + 
+	       			i * CMdCSerializationBuffer::KRequiredSizeForTUint32 );
+
+	 		TUint32 childOffset;
+		    aSerializedCondition.ReceiveL( childOffset );
+		    aSerializedCondition.PositionL( childOffset );
+
+		    const TMdCCondition& condition = TMdCCondition::GetFromBufferL( 
+					aSerializedCondition );
+			
+			if( EConditionTypeObject == condition.iConditionType )
+				{
+				const TMdCObjectCondition& objectCondition = 
+						TMdCObjectCondition::GetFromBufferL( aSerializedCondition );
+
+			    if ( EObjectConditionCompareNone == objectCondition.iCompareMethod )
+			    	{
+                    // all matches
+                    return ETrue;
+			    	}
+			    
+	    		// only ID conditions are checked
+	    		if( EObjectConditionCompareId == objectCondition.iCompareMethod )
+	    			{
+	    			aSerializedCondition.PositionL( objectCondition.iCondition );
+	    			
+	    			// get object condition's object ID
+	    			TItemId conditionObjectId;
+	    			aSerializedCondition.ReceiveL( conditionObjectId );
+
+	    			const TInt objectIdCount = aItemIdArray.Count();
+	    			for( TInt i = 0; i < objectIdCount; i++ )
+	    				{
+	    				const TItemId objectId = aItemIdArray[i];
+	
+	    				if( ( objectId == conditionObjectId ) != objectCondition.iNegated )
+	    					{
+	    					aMatchingItemIdArray.AppendL( objectId );
+	    					}
+	    				}
+	
+	    			if( aMatchingItemIdArray.Count() < aItemIdArray.Count() )
+	    				{
+	    				// none or some matches
+	    				return EFalse;
+	    				}	
+	    			else
+	    				{
+	    				// all matches
+	    				return ETrue;
+	    				}
+	    			}
+	    		else
+	    			{
+                    // if condition is something else than ID, return true so that client receives
+                    // needed notification even though also extra notifications will  be received
+                    return ETrue;
+	    			}
+				}
+    		}
+		}
+   return ETrue;
+   }
+
+TBool CMdSNotifyComparator::FindDes( TDesC16& aDes, TDesC16& aFindDes )
+	{
+	if( aDes.Find( aFindDes ) != KErrNotFound  )
+	    {
+	    return ETrue;
+	    }
+	return EFalse;
+	}
+
+TBool CMdSNotifyComparator::CompareDesEndsWith( TDesC16& aDes, TDesC16& aCompareDes )
+	{
+	if( aDes.Length() < aCompareDes.Length() )
+		{
+		return EFalse;
+		}
+
+	return ( aDes.Right( aCompareDes.Length() ).Compare( aCompareDes ) == 0 );
+	}
+
+TBool CMdSNotifyComparator::CompareDesBeginsWith( TDesC16& aDes, TDesC16& aCompareDes )
+	{
+	if( aDes.Length() < aCompareDes.Length() )
+		{
+		return EFalse;
+		}
+
+	return ( aDes.Left( aCompareDes.Length() ).Compare( aCompareDes ) == 0 );
+	}
+
+TBool CMdSNotifyComparator::MatchObjectIdToObjectIdConditionsL(
+	CMdCSerializationBuffer& aSerializedCondition, TItemId aObjectId)
+	{
+	const TMdCLogicCondition& logicCondition = 
+			TMdCLogicCondition::GetFromBufferL( aSerializedCondition );
+	
+	TBool matchingId = EFalse;
+
+	for( TUint32 i = 0; i < logicCondition.iChildConditions.iPtr.iCount; i++ )
+		{
+		aSerializedCondition.PositionL( 
+				logicCondition.iChildConditions.iPtr.iOffset + 
+				i * CMdCSerializationBuffer::KRequiredSizeForTUint32 );
+
+		TUint32 childOffset;
+		aSerializedCondition.ReceiveL( childOffset );
+		aSerializedCondition.PositionL( childOffset );
+
+		const TMdCCondition& condition = TMdCCondition::GetFromBufferL( 
+				aSerializedCondition );
+		
+		if( EConditionTypeObject == condition.iConditionType )
+			{
+			const TMdCObjectCondition& objectCondition = 
+					TMdCObjectCondition::GetFromBufferL( aSerializedCondition );
+			
+			if( EObjectConditionCompareId == objectCondition.iCompareMethod )
+				{
+				aSerializedCondition.PositionL( objectCondition.iCondition );
+
+				TItemId conditionObjectId;
+				aSerializedCondition.ReceiveL( conditionObjectId );
+				
+				TBool currentMatch = ( conditionObjectId == aObjectId ) != objectCondition.iNegated;
+	
+				if( currentMatch )
+					{
+					matchingId = ETrue;
+					break;
+					}
+				}
+			}
+		}
+		
+	return matchingId != logicCondition.iNegated;
+	}
+
+TBool CMdSNotifyComparator::MatchRelationIdsL(
+		const TMdCRelationCondition& aRelationCondition, 
+		CMdCSerializationBuffer& aSerializedCondition, TItemId aRelationId)
+	{
+	if( aRelationCondition.iRelationIds.iPtr.iCount > 0 &&
+			aRelationCondition.iRelationIds.iPtr.iOffset != KNoOffset )
+		{
+		aSerializedCondition.PositionL( aRelationCondition.iRelationIds.iPtr.iOffset );
+
+		for (TInt i = 0; i < aRelationCondition.iRelationIds.iPtr.iCount; ++i)
+			{
+			TItemId relationId;
+			aSerializedCondition.ReceiveL( relationId );
+			if ( relationId == aRelationId )
+				{
+				return ETrue;
+				}
+			}
+		}
+
+	return EFalse;
+	}
+
+TBool CMdSNotifyComparator::MatchRelationItemsL(
+		    CMdCSerializationBuffer& aSerializedCondition,
+		    CMdCSerializationBuffer& aSerializedItems,
+		    RArray<TItemId>& aMatchingItemIdArray)
+    {
+    aSerializedItems.PositionL( KNoOffset );
+    
+    const TMdCItems& items = TMdCItems::GetFromBufferL( aSerializedItems );
+
+    if( items.iRelations.iPtr.iCount == 0 )
+    	{
+    	return EFalse;
+    	}
+
+	for( TUint32 i = 0; i < items.iRelations.iPtr.iCount; i++ )
+		{
+		aSerializedItems.PositionL( items.iRelations.iPtr.iOffset + 
+				+ i * sizeof(TMdCRelation) );
+	    const TMdCRelation& relation = TMdCRelation::GetFromBufferL( aSerializedItems );
+
+		if( aSerializedCondition.Size() > 0 )
+			{
+    		// move condition buffer's position to the begin of the buffer
+    		aSerializedCondition.PositionL( KNoOffset );
+
+    		if( MatchRelationItemL( aSerializedCondition, relation ) )
+    			{
+    			aMatchingItemIdArray.AppendL( relation.iId );
+    			}
+			}
+		else
+			{
+			aMatchingItemIdArray.AppendL( relation.iId );
+			}
+		}
+
+	if( aMatchingItemIdArray.Count() > 0 )
+    	{
+    	return ETrue;
+    	}
+    else
+    	{
+    	return EFalse;
+    	}
+    }
+
+TBool CMdSNotifyComparator::MatchRelationItemL(CMdCSerializationBuffer& aSerializedCondition,
+		   const TMdCRelation& aRelation)
+	{
+	// check if event is failed
+	if( aRelation.iId == 0 )
+		{
+		return EFalse;
+		}
+	
+	const TMdCRelationCondition& relationCondition = 
+			TMdCRelationCondition::GetFromBufferL( aSerializedCondition );
+
+	// check if relation condition contains relation def ID comparsion
+	if( relationCondition.iRelationDefId != KNoDefId &&
+		BoolEqual( relationCondition.iRelationDefId == aRelation.iDefId, 
+				relationCondition.iNegated ) )
+		{
+		return EFalse;
+		}
+	
+	// check if relation condition contains relation ID comparsion
+	if ( relationCondition.iRelationId != KNoId &&
+	 	 BoolEqual( relationCondition.iRelationId == aRelation.iId, 
+	 			relationCondition.iNegated ) )
+		{
+		return EFalse;
+		}
+
+	// check if relation condition contains relation IDs comparsion
+	if ( relationCondition.iRelationIds.iPtr.iOffset != KNoOffset &&
+			BoolEqual( MatchRelationIdsL( relationCondition, 
+					aSerializedCondition, aRelation.iId ), 
+					relationCondition.iNegated ) )
+		{
+		return EFalse;
+		}
+
+	// check relation condition contains left and/or right object condition comparisions
+	if ( ( relationCondition.iLeftObjectCondition != KNoOffset || 
+			relationCondition.iRightObjectCondition != KNoOffset ) && 
+			ERelationConditionSideEither == relationCondition.iObjectSide )
+		{
+		TBool eitherMatches = EFalse;
+		
+		if ( relationCondition.iLeftObjectCondition != KNoOffset )
+			{
+			aSerializedCondition.PositionL( 
+					relationCondition.iLeftObjectCondition );
+	
+			if( !BoolEqual( MatchObjectIdToObjectIdConditionsL(
+					aSerializedCondition, aRelation.iLeftObjectId ), 
+					relationCondition.iNegated ) )
+				{
+				eitherMatches = ETrue;
+				}
+			}
+		
+		if ( relationCondition.iRightObjectCondition != KNoOffset )
+			{
+			aSerializedCondition.PositionL( 
+					relationCondition.iRightObjectCondition );
+
+			if( !BoolEqual( MatchObjectIdToObjectIdConditionsL(
+					aSerializedCondition, aRelation.iRightObjectId ), 
+					relationCondition.iNegated ) )
+				{
+				eitherMatches = ETrue;
+				}
+			}
+
+		// left and right condition didn't match
+		if( !eitherMatches )
+			{
+			return EFalse;
+			}
+		}
+
+	return ETrue;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsobjectdef.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,543 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one object and it's properties
+*
+*/
+
+#include "mdsobjectdef.h"
+
+#include "mdcdef.h"
+#include "mdspropertydef.h"
+#include "mdsdbconnectionpool.h"
+#include "mdcserializationbuffer.h"
+#include "mdsindexer.h"
+#include "mdeinternalerror.h"
+
+/**
+ * NewLC
+ */
+CMdsObjectDef* CMdsObjectDef::NewLC(const TDesC& aName, const CMdsObjectDef* aParent )
+	{
+	CMdsObjectDef* ret = new( ELeave ) CMdsObjectDef( aParent );
+	CleanupStack::PushL( ret );
+	ret->ConstructL( aName );
+	return ret;
+	}
+	
+/**
+ * NewL
+ */
+CMdsObjectDef* CMdsObjectDef::NewL( const TDesC& aName, const CMdsObjectDef* aParent )
+	{
+	CMdsObjectDef* ret = CMdsObjectDef::NewLC( aName, aParent );
+	CleanupStack::Pop( ret );
+	return ret;
+	}
+
+/**
+ * default constructor
+ */
+inline CMdsObjectDef::CMdsObjectDef( const CMdsObjectDef* aParent )
+	: iParent ( aParent ), iFlags( EObjectDefFlagsNone ), iMandatoryPropertyCount( 0 )
+	{}
+
+/**
+ * ConstructL
+ */
+void CMdsObjectDef::ConstructL( const TDesC& aName )
+	{
+	// check that only allowed characters (A-Z, a-z) are used
+	CheckAllowerCharatersL( aName, EFalse );
+
+	CMdsItemDef::ConstructL( aName );
+	}
+
+/**
+ * Destructor
+ */
+CMdsObjectDef::~CMdsObjectDef()
+	{
+	// deleting properties
+	iPropertyDefs.ResetAndDestroy();
+	iPropertyDefs.Close();
+
+	iCol2Prop.Close();
+	}
+
+void CMdsObjectDef::AddPropertyL( const TDesC& aName, TPropertyType aType,
+								  const TMdCValueUnion& aMinAdd, const TMdCValueUnion& aMaxAdd,
+								  TBool aReadOnly, TBool aMandatory, TBool aIndexed )
+	{
+	CMdsPropertyDef* newProp = CommonAddPropertyL( aName, aType, aReadOnly, aMandatory, aIndexed );
+	if (!newProp)
+		{
+		User::Leave( KErrMdEUnknownPropertyDef );
+		}
+	switch (aType)
+		{									
+		case EPropertyUint32:
+		case EPropertyText:
+		case EPropertyBool:		
+			{									
+			newProp->AddMinMaxValueL(aMinAdd.iUint32,aMaxAdd.iUint32);
+			break;
+			}
+		case EPropertyInt32:
+			{	
+			newProp->AddMinMaxValueL(aMinAdd.iInt32,aMaxAdd.iInt32);
+			break;
+			}
+		case EPropertyInt64:
+		case EPropertyTime:
+			{	
+			newProp->AddMinMaxValueL(aMinAdd.iInt64,aMaxAdd.iInt64);
+			break;
+			}
+		case EPropertyReal64:
+			{									
+			newProp->AddMinMaxValueL(aMinAdd.iReal,aMaxAdd.iReal);
+			break;
+			}
+
+	    default:
+	    	{
+#ifdef _DEBUG
+            User::Panic( _L("MdSODAdd") , KErrMdEUnknownPropertyType );
+#endif		    	
+	    	User::Leave( KErrMdEUnknownPropertyType );
+	    	}
+		}
+	}
+	
+/**
+ * AddPropertyL
+ */
+void CMdsObjectDef::AddPropertyL( const TDesC& aName, TPropertyType aType,
+	                              TInt32 aMinAdd, TInt32 aMaxAdd,
+	                              TBool aReadOnly, TBool aMandatory, TBool aIndexed )
+	{
+	CMdsPropertyDef* newProp = CommonAddPropertyL( aName, aType, aReadOnly, aMandatory, aIndexed );
+	newProp->AddMinMaxValueL( aMinAdd, aMaxAdd );
+	}
+
+/**
+ * AddPropertyL
+ */
+void CMdsObjectDef::AddPropertyL( const TDesC& aName, TPropertyType aType,
+	                              TUint32 aMinAdd, TUint32 aMaxAdd,
+	                              TBool aReadOnly, TBool aMandatory, TBool aIndexed )
+	{
+	CMdsPropertyDef* newProp = CommonAddPropertyL( aName, aType, aReadOnly, aMandatory, aIndexed );
+	newProp->AddMinMaxValueL( aMinAdd, aMaxAdd );
+	}
+
+/**
+ * AddPropertyL
+ */
+void CMdsObjectDef::AddPropertyL( const TDesC& aName, TPropertyType aType,
+	                              const TInt64& aMinAdd, const TInt64& aMaxAdd,
+	                              TBool aReadOnly, TBool aMandatory, TBool aIndexed )
+	{
+	CMdsPropertyDef* newProp = CommonAddPropertyL( aName, aType, aReadOnly, aMandatory, aIndexed );
+	newProp->AddMinMaxValueL( aMinAdd, aMaxAdd );
+	}
+
+/**
+ * AddPropertyL
+ */
+void CMdsObjectDef::AddPropertyL( const TDesC& aName, TPropertyType aType,
+	                              const TReal& aMinAdd, const TReal& aMaxAdd,
+	                              TBool aReadOnly, TBool aMandatory, TBool aIndexed )
+	{
+	CMdsPropertyDef* newProp = CommonAddPropertyL( aName, aType, aReadOnly, aMandatory, aIndexed );
+	newProp->AddMinMaxValueL( aMinAdd, aMaxAdd );
+	}
+
+/**
+ * CommonAddPropertyL
+ */
+CMdsPropertyDef* CMdsObjectDef::CommonAddPropertyL( const TDesC& aName, TPropertyType aType,
+		TBool aReadOnly, TBool aMandatory, TBool aIndexed )
+	{
+	CMdsPropertyDef* propertyDef = CMdsPropertyDef::NewLC( aName, aType, aReadOnly, aMandatory,
+			aIndexed );
+	iPropertyDefs.AppendL( propertyDef );
+	CleanupStack::Pop( propertyDef );
+	return propertyDef;
+	}
+
+CMdsPropertyDef* CMdsObjectDef::CommonAddPropertyL( const TDesC& aName, TPropertyType aType,
+		TUint32 aFlags, TDefId aId )
+	{
+	CMdsPropertyDef* propertyDef = CMdsPropertyDef::NewLC( aName, aType, aFlags );
+	propertyDef->SetId(aId);
+	iPropertyDefs.AppendL( propertyDef );
+	CleanupStack::Pop( propertyDef );
+	return propertyDef;
+	}
+
+CMdsPropertyDef* CMdsObjectDef::GetProperty( TUint32 aIndex ) const
+	{
+	return iPropertyDefs[aIndex];
+	}
+
+CMdsPropertyDef* CMdsObjectDef::GetProperty( const TDesC& aName ) const
+	{
+	const TInt count = iPropertyDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		if( iPropertyDefs[i]->GetName().Compare( aName ) == 0 )
+			{
+			return iPropertyDefs[i];
+			}
+		}
+	if ( iParent )
+		{
+		return iParent->GetProperty( aName );
+		}
+	return NULL;
+	}
+
+
+const CMdsPropertyDef* CMdsObjectDef::GetPropertyByIdL( TDefId aId ) const
+	{
+	const TInt propertyDefCount = iPropertyDefs.Count();
+	for ( TInt i = 0; i < propertyDefCount; ++i )
+		{
+		const CMdsPropertyDef* propDef = iPropertyDefs[i];
+		if( propDef->GetId() == aId )
+			{
+			return propDef;
+			}
+		}
+	if ( iParent )
+		{
+		return iParent->GetPropertyByIdL( aId );
+		}
+	return NULL;
+	}
+
+
+void CMdsObjectDef::StoreToDBL( TDefId aNamespaceDefId )
+	{
+	_LIT( KMdsSqlClauseTriggerObjectDef, "CREATE TRIGGER Delete%S%u DELETE ON Object%u BEGIN DELETE FROM %S%u WHERE ObjectId=OLD.ObjectId; END;" );
+	_LIT( KMdsSqlClauseAddObjectDef, "INSERT INTO ObjectDef(NamespaceDefId, ParentDefId, Flags, Name) Values(?,?,?,?);" );
+
+	RRowData rowData;
+    CleanupClosePushL( rowData );
+
+	if ( !GetStoredInDB() )
+		{
+		rowData.AppendL( TColumn( aNamespaceDefId ) );
+		rowData.AppendL( TColumn( iParent ? iParent->GetId() : KNoDefId ) );
+		rowData.AppendL( TColumn( (TInt32)iFlags ) );
+		rowData.AppendL( TColumn( GetName().AllocL() ) );
+
+		TDefId id = MMdSIndexer::ExecuteAndGetIndexL( KMdsSqlClauseAddObjectDef,rowData );
+
+	    SetId( id );
+       	SetStoredInDB();
+
+    	if ( GetId() != KBaseObjectDefId )
+    		{
+	    	// Create trigger
+	        HBufC* sqlQueryCreateTrigger = HBufC::NewLC( KMdsSqlClauseTriggerObjectDef().Size() + ( KMaxUintValueLength * 3 )  + ( GetName().Length() * 2 ) );
+            TPtr sqlPtr = sqlQueryCreateTrigger->Des();
+            sqlPtr.Format( KMdsSqlClauseTriggerObjectDef, &GetName(), aNamespaceDefId, aNamespaceDefId, &GetName(), aNamespaceDefId );
+            RRowData rowDataDummy;
+		    CleanupClosePushL( rowDataDummy );
+		    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+            connection.ExecuteL( *sqlQueryCreateTrigger, rowDataDummy );
+            CleanupStack::PopAndDestroy( 2, sqlQueryCreateTrigger ); // rowDataDummy, sqlQueryCreateTrigger
+    		}
+		}
+
+	// add propertyDef to DB
+	for( TInt counter = 0; counter < iPropertyDefs.Count(); ++counter )
+		{
+		iPropertyDefs[counter]->StoreToDBL( GetId() );
+		}
+	
+	CleanupStack::PopAndDestroy( &rowData );
+	}
+
+CMdsPropertyDef* CMdsObjectDef::FindProperty( const TDesC& aName ) const
+	{
+	const TInt count = iPropertyDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		if ( iPropertyDefs[i]->GetName().Compare( aName ) == 0 )
+			{
+			return iPropertyDefs[i];
+			}
+		}
+	return NULL;
+	}
+
+void CMdsObjectDef::MergeL( CMdsObjectDef* aObjectDef, const TBool& /*aDryRun*/ )
+	{
+	const TInt count = aObjectDef->iPropertyDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		CMdsPropertyDef* lPropertyDef = FindProperty( aObjectDef->iPropertyDefs[i]->GetName() );
+		if ( lPropertyDef )
+			{
+			if ( *lPropertyDef != *(aObjectDef->iPropertyDefs[i]) )
+				{
+				User::Leave( KErrAlreadyExists );
+				}
+			}
+		else
+			{
+			User::Leave( KErrAccessDenied );
+			}
+		}
+	}
+
+void CMdsObjectDef::AddPropertyL( const TDefId aId, TPropertyType aType, TUint32 aFlags,
+	                              const TDesC& aMinAdd, const TDesC& aMaxAdd, const TDesC& aName )
+	{
+	CMdsPropertyDef* prop = CommonAddPropertyL( aName, aType, aFlags, aId );
+	prop->SetStoredInDB();
+	switch( aType )
+		{
+		case EPropertyBool: case EPropertyInt8: case EPropertyUint8: case EPropertyInt16:
+        case EPropertyUint16: case EPropertyInt32: case EPropertyText:
+        	{
+        	TInt32 minValue = 0;
+            TInt32 maxValue = 0;
+        	TLex lex( aMinAdd );
+        	lex.Val( minValue );
+        	lex.Assign( aMaxAdd );
+        	lex.Val( maxValue );
+        	prop->AddMinMaxValueL( minValue, maxValue );
+        	break;
+        	}
+        case EPropertyUint32:
+        	{
+        	TUint32 minValue = 0;
+        	TUint32 maxValue = 0;
+        	TLex lex( aMinAdd );
+        	lex.Val( (TInt64&)minValue );
+        	lex.Assign( aMaxAdd );
+        	lex.Val( (TInt64&)maxValue );
+        	prop->AddMinMaxValueL( minValue, maxValue );
+        	break;
+        	}
+        case EPropertyInt64:
+        case EPropertyTime:
+        	{
+        	TInt64 minValue, maxValue;
+        	TLex lex( aMinAdd );
+        	lex.Val( minValue );
+        	lex.Assign( aMaxAdd );
+        	lex.Val( maxValue );
+        	prop->AddMinMaxValueL( minValue, maxValue );
+        	break;
+        	}
+        case EPropertyReal32:
+        case EPropertyReal64:
+        	{
+        	TReal minValue, maxValue;
+        	TLex lex( aMinAdd );
+        	lex.Val( minValue );
+        	lex.Assign( aMaxAdd );
+        	lex.Val( maxValue );
+        	prop->AddMinMaxValueL( minValue, maxValue );
+        	break;
+        	}
+        default:
+        	{
+#ifdef _DEBUG
+            User::Panic( _L("MdSODAd2") , KErrMdEUnknownPropertyType );
+#endif		    	
+        	
+        	User::Leave( KErrMdEUnknownPropertyType );
+        	}
+		}
+	}
+
+
+void CMdsObjectDef::ImportFromDBL()
+	{
+	_LIT( KMdsQueryGetPropertyDefs, "SELECT PropertyDefId,Flags,Type,MinValue,MaxValue,Name FROM PropertyDef WHERE ObjectDefId=?;" );
+	_LIT( KMdsQueryGetCol2Prop,     "SELECT PropertyDefId,ColumnId FROM Col2Prop WHERE ObjectDefId=?;" );
+
+	RMdsStatement query;
+	CleanupClosePushL( query );
+
+	// importing properties
+	RRowData objectNumber;
+	CleanupClosePushL( objectNumber );
+	objectNumber.AppendL( TColumn( GetId() ) );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	TDefId propertyDefId = 0;
+	TPropertyType type;
+	TInt32 typeValue = 0;
+	TUint32 propertyFlags = 0;
+	TPtrC16 name;
+    TPtrC16 minValue;
+    TPtrC16 maxValue;
+	RRowData getData;
+	CleanupClosePushL( getData );
+	getData.AppendL( TColumn( propertyDefId ) );
+	getData.AppendL( TColumn( propertyFlags ) );
+	getData.AppendL( TColumn( typeValue ) );
+	getData.AppendL( TColumn( EColumnHBuf16 ) );
+	getData.AppendL( TColumn( EColumnHBuf16 ) );
+	getData.AppendL( TColumn( EColumnHBuf16 ) );
+	connection.ExecuteQueryL( KMdsQueryGetPropertyDefs, query, objectNumber );
+	while( connection.NextRowL( query, getData ) )
+		{
+		getData.Column( 0 ).Get( propertyDefId );
+		getData.Column( 1 ).Get( propertyFlags );
+		getData.Column( 2 ).Get( typeValue );
+		type = (TPropertyType)typeValue;
+		getData.Column( 3 ).Get( minValue );
+		getData.Column( 4 ).Get( maxValue );
+		getData.Column( 5 ).Get( name );
+		AddPropertyL( propertyDefId, type, propertyFlags, minValue, maxValue, name );
+		getData.Column( 5 ).Free( );
+		getData.Column( 4 ).Free( );
+		getData.Column( 3 ).Free( );
+		}
+
+	iCol2Prop.Reset();
+	RMdsStatement queryCol;
+	CleanupClosePushL( queryCol );
+	RRowData getColData;
+	CleanupClosePushL( getColData );
+	TUint32 columnId = 0;
+	getColData.AppendL( TColumn( propertyDefId ) );
+	getColData.AppendL( TColumn( columnId ) );
+	connection.ExecuteQueryL( KMdsQueryGetCol2Prop, queryCol, objectNumber );
+	while( connection.NextRowL( queryCol, getColData ) )
+		{
+		getColData.Column( 0 ).Get( propertyDefId );
+		getColData.Column( 1 ).Get( columnId );
+		const CMdsPropertyDef* propertyDef = GetPropertyByIdL( propertyDefId );
+		
+		if( !propertyDef )
+			{
+			User::Leave( KErrMdEUnknownPropertyDef );
+			}
+
+		CMdsObjectDef::TMdsColumnOrder col = { columnId, *propertyDef };
+		iCol2Prop.AppendL( col );
+		
+		if( propertyDef->GetMandatory() )
+			{
+			++iMandatoryPropertyCount;
+			}
+		}
+
+	// everything is ok, so set the flags
+	SetStoredInDB();
+	SetTableStoredInDB();
+	SetC2PStoredInDB();
+
+	CleanupStack::PopAndDestroy( 5, &query ); // getColData, queryCol, getData, objectNumber, query
+	}
+	
+TUint32 CMdsObjectDef::RequiredBufferSize()
+	{
+	TUint32 bufferSize = sizeof(TMdCObjectDef) + CMdsItemDef::RequiredBufferSize();
+
+	// propertydefs
+	const TInt propertyDefsCount = iPropertyDefs.Count();
+	bufferSize += propertyDefsCount * sizeof(TMdCPropertyDef);
+	for ( TInt i = 0; i < propertyDefsCount; ++i )
+		{
+		bufferSize += iPropertyDefs[i]->RequiredBufferSize();
+		}
+
+	return bufferSize;
+	}
+
+TMdCOffset CMdsObjectDef::SerializeL( CMdCSerializationBuffer& aBuffer, TMdCOffset aFreeSpace )
+	{
+	const TMdCOffset objectDefOffset = aBuffer.Position();
+	TMdCObjectDef objectDef;
+	// get const data and store Name
+	objectDef.iDefId = GetId();
+	objectDef.iParentId = iParent ? iParent->GetId() : KNoDefId;
+	objectDef.iName.iPtr.iCount = GetName().Length();
+	objectDef.iName.iPtr.iOffset = aFreeSpace;
+	aBuffer.PositionL( aFreeSpace );
+	aFreeSpace = CMdsItemDef::SerializeL( aBuffer );
+
+	// calculate necessary stuff for propertyDefs
+	const TInt propertyDefsCount = iPropertyDefs.Count();
+	objectDef.iPropertyDefs.iPtr.iCount = propertyDefsCount;
+	objectDef.iPropertyDefs.iPtr.iOffset = aFreeSpace;
+
+	// create space for propertyDefs
+	aFreeSpace += propertyDefsCount * sizeof(TMdCPropertyDef);
+
+	for ( TInt i = 0; i < propertyDefsCount; ++i )
+		{
+		aBuffer.PositionL( objectDef.iPropertyDefs.iPtr.iOffset + i * sizeof(TMdCPropertyDef) );
+		// write object
+		aFreeSpace = iPropertyDefs[i]->SerializeL( aBuffer, aFreeSpace );
+		}
+
+	// store objectDef itself
+	aBuffer.PositionL( objectDefOffset );
+	objectDef.SerializeL( aBuffer );
+
+	return aFreeSpace;
+	}
+
+TInt CMdsObjectDef::GetAllPropertiesCount() const
+	{
+#ifdef _DEBUG
+	_LIT( KCountPanicError, "CMdsObjectDef::GetAllPropertiesCount()" );
+	TInt temp = iPropertyDefs.Count() + ( iParent ? iParent->GetAllPropertiesCount() : 0 );
+	__ASSERT_DEBUG( temp == iCol2Prop.Count(), User::Panic( KCountPanicError, KErrCorrupt ) );
+#endif
+	return iCol2Prop.Count();
+	}
+
+TInt CMdsObjectDef::GetMandatoryPropertyCount() const
+	{
+	return iMandatoryPropertyCount;
+	}
+
+void CMdsObjectDef::SetStoredEveryInDB()
+	{
+	SetStoredInDB();
+	
+	const TInt count = iPropertyDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		iPropertyDefs[i]->SetStoredInDB();
+		}
+	}
+
+void CMdsObjectDef::SetNotStoredEveryInDB()
+	{
+	SetAllNotStoredInDB();
+	
+	const TInt count = iPropertyDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		iPropertyDefs[i]->SetAllNotStoredInDB();
+		}
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsobjectlocklist.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,117 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Object locking features
+*
+*/
+
+#include "mdsobjectlocklist.h"
+#include "mdsnamespacedef.h"
+
+CMdSObjectLockList* CMdSObjectLockList::NewL()
+    {
+    CMdSObjectLockList* self = CMdSObjectLockList::NewLC();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+CMdSObjectLockList* CMdSObjectLockList::NewLC()
+    {
+    CMdSObjectLockList* self = new ( ELeave ) CMdSObjectLockList();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;  
+    }
+
+void CMdSObjectLockList::ConstructL()
+    {
+    iLockListArray.Reset();
+    }
+
+CMdSObjectLockList::~CMdSObjectLockList()
+    {
+    iLockListArray.Close();
+    }
+
+void CMdSObjectLockList::LockObjectL( const CMdSServerSession& aSession, 
+		const CMdsNamespaceDef& aNamespace, const TItemId aObjectId )
+    {
+    User::LeaveIfError( iLockListArray.InsertInOrder( 
+    		TMdSLockEntry( &aSession, aNamespace, aObjectId ), 
+    		TLinearOrder<TMdSLockEntry>(TMdSLockEntry::Compare) ) );
+    }
+
+void CMdSObjectLockList::UnlockBySession( const CMdSServerSession& aSession )
+    {
+    for (TInt i = iLockListArray.Count() - 1; i >= 0; --i)
+        {
+        if ( iLockListArray[i].iSession == &aSession ) // pointer comparision
+            {
+            iLockListArray.Remove(i);
+            }
+        }
+    }
+
+void CMdSObjectLockList::UnlockById( const CMdsNamespaceDef& aNamespace, 
+		const TItemId aObjectId )
+    {
+    TInt position = Find( aNamespace, aObjectId );
+    if (position >= 0)
+    	{
+    	iLockListArray.Remove(position);
+    	}
+
+    }
+
+TBool CMdSObjectLockList::IsLocked( const CMdsNamespaceDef& aNamespace, 
+		const TItemId aObjectId ) const
+    {
+    const TInt position = Find( aNamespace, aObjectId );
+    if (position >= 0)
+    	{
+    	return ETrue;
+    	}
+    return EFalse;
+    }
+
+TInt CMdSObjectLockList::Find( const CMdsNamespaceDef& aNamespace, 
+		const TItemId aObjectId ) const
+	{
+	TInt position;
+	TInt err = iLockListArray.FindInOrder( TMdSLockEntry( 
+			(const CMdSServerSession*)NULL, aNamespace, aObjectId ),
+			position, TLinearOrder<TMdSLockEntry>(TMdSLockEntry::Compare) );
+
+	if (err != KErrNone)
+		{
+		position = -1;
+		}
+	return position;
+	}
+
+void CMdSObjectLockList::Reset()
+    {
+    iLockListArray.Reset();
+    }
+
+TInt TMdSLockEntry::Compare( const TMdSLockEntry& aFirst, const 
+		TMdSLockEntry& aSecond )
+	{
+	TInt result = aFirst.iNamespace.GetId() - aSecond.iNamespace.GetId();
+	if ( result )
+		{
+		return result;
+		}
+	return aFirst.iId - aSecond.iId;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdspreferences.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,22 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Stores and load preference values to and from DB
+*
+*/
+
+#include "mdspreferences.h"
+
+// (11.12.08) This file will be removed very soon. There used to be code here but it was commented
+// out. mdspreferences.h includes code which will be moved to some other file.
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdspropertydef.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,357 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one property
+*
+*/
+
+#include "mdspropertydef.h"
+
+#include "mdcdef.h"
+#include "mdssqliteconnection.h"
+#include "mdsindexer.h"
+#include "mdcserializationbuffer.h"
+#include "mdeinternalerror.h"
+
+/**
+ * NewLC
+ */
+CMdsPropertyDef* CMdsPropertyDef::NewLC( const TDesC& aName, TPropertyType aType,
+		TBool aReadOnly, TBool aMandatory, TBool aIndexed )
+	{
+	CMdsPropertyDef* ret = new( ELeave ) CMdsPropertyDef( aType );
+	CleanupStack::PushL( ret );
+	ret->ConstructL( aName, aReadOnly, aMandatory, aIndexed );
+	return ret;
+	}
+	
+/**
+ * NewL
+ */
+CMdsPropertyDef* CMdsPropertyDef::NewL( const TDesC& aName, TPropertyType aType,
+		TBool aReadOnly, TBool aMandatory, TBool aIndexed )
+	{
+	CMdsPropertyDef* ret = CMdsPropertyDef::NewLC( aName, aType, aReadOnly, aMandatory, aIndexed );
+	CleanupStack::Pop( ret );
+	return ret;
+	}
+
+CMdsPropertyDef* CMdsPropertyDef::NewL( const TDesC& aName, TPropertyType aType, TUint32 aFlags )
+	{
+	return CMdsPropertyDef::NewL( aName, aType, aFlags & EPropertyReadOnly, aFlags & EPropertyMandatory, EFalse );
+	}
+
+CMdsPropertyDef* CMdsPropertyDef::NewLC( const TDesC& aName, TPropertyType aType, TUint32 aFlags )
+	{
+	return CMdsPropertyDef::NewLC( aName, aType, aFlags & EPropertyReadOnly, aFlags & EPropertyMandatory, EFalse );
+	}
+
+/**
+ * default constructor
+ */
+inline CMdsPropertyDef::CMdsPropertyDef( TPropertyType aType )
+	: iType( aType )
+	{}
+
+/**
+ * ConstructL
+ */
+void CMdsPropertyDef::ConstructL( const TDesC& aName, TBool aReadOnly, TBool aMandatory, 
+		TBool aIndexed )
+	{
+	// check that only allowed characters (A-Z, a-z, 0-9) are used
+	CheckAllowerCharatersL( aName, ETrue );
+	
+	CMdsItemDef::ConstructL( aName );
+
+	if ( aMandatory )
+		{
+		iPropertyFlags |= EPropertyMandatory;
+		}
+
+	if ( aReadOnly )
+		{
+		iPropertyFlags |= EPropertyReadOnly;
+		}
+	
+	iIndexed = aIndexed;
+	}
+
+/**
+ * Destructor
+ */
+CMdsPropertyDef::~CMdsPropertyDef()
+	{
+	}
+	
+/**
+ * AddMinMaxValueL
+ */
+void CMdsPropertyDef::AddMinMaxValueL( const TInt32& aMinValue, const TInt32& aMaxValue )
+	{
+	if( iType == EPropertyBool || iType == EPropertyInt8 || iType ==  EPropertyUint8 ||
+    	iType == EPropertyInt16 || iType == EPropertyUint16 || iType == EPropertyInt32 ||
+    	iType == EPropertyText )
+		{
+		iMinValue.iInt32 = aMinValue;
+		iMaxValue.iInt32 = aMaxValue;
+		}
+	else
+		{
+#ifdef _DEBUG
+		User::Panic( _L("MdSPDAd1") , KErrMdEUnknownPropertyType );
+#endif
+		User::Leave( KErrMdEUnknownPropertyType );
+		}
+	}
+
+/**
+ * AddMinMaxValueL
+ */
+void CMdsPropertyDef::AddMinMaxValueL( const TUint32& aMinValue, const TUint32& aMaxValue )
+	{
+	if( iType == EPropertyUint32 )
+		{
+		iMinValue.iUint32 = aMinValue;
+		iMaxValue.iUint32 = aMaxValue;
+		}
+	else
+		{
+#ifdef _DEBUG
+		User::Panic( _L("MdSPDAd2") , KErrMdEUnknownPropertyType );
+#endif
+		User::Leave( KErrMdEUnknownPropertyType );
+		}
+	}
+
+/**
+ * AddMinMaxValueL
+ */
+void CMdsPropertyDef::AddMinMaxValueL( const TInt64& aMinValue, const TInt64& aMaxValue )
+	{
+	if( iType == EPropertyInt64 || iType == EPropertyTime )
+		{
+		iMinValue.iInt64 = aMinValue;
+		iMaxValue.iInt64 = aMaxValue;
+		}
+	else
+		{
+#ifdef _DEBUG
+		User::Panic( _L("MdSPDAd3") , KErrMdEUnknownPropertyType );
+#endif
+		User::Leave( KErrMdEUnknownPropertyType );
+		}
+	}
+
+/**
+ * AddMinMaxValueL
+ */
+void CMdsPropertyDef::AddMinMaxValueL( const TReal& aMinValue, const TReal& aMaxValue )
+	{
+	if( iType == EPropertyReal32 || iType == EPropertyReal64 )
+		{
+		iMinValue.iReal = aMinValue;
+		iMaxValue.iReal = aMaxValue;
+		}
+	else
+		{
+#ifdef _DEBUG
+		User::Panic( _L("MdSPDAd4") , KErrMdEUnknownPropertyType );
+#endif
+		User::Leave( KErrMdEUnknownPropertyType );
+		}
+	}
+
+
+/**
+ * Get SQLite type name
+ * @return type name
+ */
+const TDesC& CMdsPropertyDef::GetSqlTypeName() const
+	{
+	_LIT( KMdsSqlTypeInt,    "INTEGER" );
+	_LIT( KMdsSqlTypeBigInt, "LARGEINT" );
+	_LIT( KMdsSqlTypeReal,   "REAL" );
+	_LIT( KMdsSqlTypeText,   "TEXT" );
+	
+	switch( iType )
+		{
+		case EPropertyBool: case EPropertyInt8: case EPropertyUint8: case EPropertyInt16:
+        case EPropertyUint16: case EPropertyInt32:
+        	{
+        	return KMdsSqlTypeInt;
+        	}
+        case EPropertyUint32: case EPropertyInt64: case EPropertyTime:
+        	{
+        	return KMdsSqlTypeBigInt;
+        	}
+        case EPropertyReal32:
+        case EPropertyReal64:
+        	{
+        	return KMdsSqlTypeReal;
+        	}
+        case EPropertyText:
+        	{
+        	return KMdsSqlTypeText;
+        	}
+        default:
+        	return KMdsSqlTypeText;	
+		}
+	}
+
+TColumnDataType CMdsPropertyDef::GetSqlType() const
+	{	
+	switch( iType )
+		{
+		case EPropertyBool:
+			return EColumnBool;
+		case EPropertyInt8:
+		case EPropertyInt16:
+        case EPropertyInt32:
+			return EColumnInt32;
+		case EPropertyUint8:
+        case EPropertyUint16:
+        case EPropertyUint32: 
+        	return EColumnUint32;
+        case EPropertyInt64:
+        	return EColumnInt64;
+        case EPropertyTime:
+        	return EColumnTime;
+        case EPropertyReal32:
+        	return EColumnReal32;
+        case EPropertyReal64:
+        	return EColumnReal64;
+        case EPropertyText:
+        	return EColumnDes16;
+        default:
+        	return EColumnDes16;
+		}
+	}
+	
+void CMdsPropertyDef::StoreToDBL( TDefId aObjectDefId )
+	{
+	_LIT( KMdsSqlClauseAddPropertyDef, "INSERT INTO PropertyDef(ObjectDefId,Flags,Type,MinValue,MaxValue,Name) Values(?,?,?,?,?,?);" );
+
+	if ( GetStoredInDB() )
+		{
+		return;
+		}
+
+    RRowData rowData;
+    CleanupClosePushL( rowData );
+	rowData.AppendL( TColumn( aObjectDefId ) );
+	rowData.AppendL( TColumn( iPropertyFlags ) );
+	rowData.AppendL( TColumn( iType ) );
+	switch( iType )
+		{
+    	case EPropertyBool: case EPropertyInt8: case EPropertyUint8: case EPropertyInt16:
+    	case EPropertyUint16: case EPropertyInt32: case EPropertyText:
+    		{
+    		rowData.AppendL( TColumn( iMinValue.iInt32 ) );
+    		rowData.AppendL( TColumn( iMaxValue.iInt32 ) );
+    		break;
+    		}
+    	case EPropertyUint32:
+    		{
+    		rowData.AppendL( TColumn( (TInt64)iMinValue.iUint32 ) );
+    		rowData.AppendL( TColumn( (TInt64)iMaxValue.iUint32 ) );
+    		break;
+    		}
+    	case EPropertyInt64: case EPropertyTime:
+    		{
+    		rowData.AppendL( TColumn( iMinValue.iInt64 ) );
+    		rowData.AppendL( TColumn( iMaxValue.iInt64 ) );
+    		break;
+    		}
+    	case EPropertyReal32: case EPropertyReal64:
+    		{
+    		rowData.AppendL( TColumn( iMinValue.iReal ) );
+    		rowData.AppendL( TColumn( iMaxValue.iReal ) );
+    		break;
+    		}
+    	default:
+#ifdef _DEBUG
+    		User::Panic( _L("MdSPDSto") , KErrMdEUnknownPropertyType );
+#endif
+    		User::Leave( KErrMdEUnknownPropertyType );
+		}
+	rowData.AppendL( TColumn( GetName().AllocL() ) );
+
+	TDefId id;
+	id =  MMdSIndexer::ExecuteAndGetIndexL( KMdsSqlClauseAddPropertyDef, rowData );
+	SetId( id );
+
+	SetStoredInDB();
+	CleanupStack::PopAndDestroy( &rowData );
+	}
+
+TBool CMdsPropertyDef::operator==( const CMdsPropertyDef& aPropertyDef ) const
+	{
+	if ( iType != aPropertyDef.iType || iPropertyFlags != aPropertyDef.iPropertyFlags ||
+	     GetName() != aPropertyDef.GetName() )
+		{
+		return EFalse;
+		}
+	switch( iType )
+		{
+		case EPropertyBool: case EPropertyInt8: case EPropertyUint8: case EPropertyInt16:
+        case EPropertyUint16: case EPropertyInt32: case EPropertyText:
+        	{
+        	return ( iMinValue.iInt32 == aPropertyDef.iMinValue.iInt32 &&
+        	         iMaxValue.iInt32 == aPropertyDef.iMaxValue.iInt32 ) ;
+        	}
+        case EPropertyUint32:
+        	{
+        	return ( iMinValue.iUint32 == aPropertyDef.iMinValue.iUint32 &&
+        	         iMaxValue.iUint32 == aPropertyDef.iMaxValue.iUint32 ) ;
+        	}
+        case EPropertyReal32:
+        case EPropertyReal64:
+        	{
+        	return ( iMinValue.iReal == aPropertyDef.iMinValue.iReal &&
+        	         iMaxValue.iReal == aPropertyDef.iMaxValue.iReal ) ;
+        	}
+        case EPropertyInt64:
+        case EPropertyTime:
+        	{
+        	return ( iMinValue.iInt64 == aPropertyDef.iMinValue.iInt64 &&
+        	         iMaxValue.iInt64 == aPropertyDef.iMaxValue.iInt64 ) ;
+        	}
+        default:
+            return EFalse;
+		}
+	
+	}
+
+TUint32 CMdsPropertyDef::RequiredBufferSize()
+	{
+	return sizeof(TMdCPropertyDef) + CMdsItemDef::RequiredBufferSize();
+	}
+
+TMdCOffset CMdsPropertyDef::SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreeSpace)
+	{
+	TMdCPropertyDef propertyDef;
+	propertyDef.iDefId = GetId();
+	propertyDef.iFlags = iPropertyFlags;
+	propertyDef.iValueType = iType;
+	propertyDef.iMinValue = iMinValue;
+	propertyDef.iMaxValue = iMaxValue;
+	
+	// store name
+	propertyDef.iName.iPtr.iCount = GetName().Length();
+	propertyDef.iName.iPtr.iOffset = aFreeSpace;
+	propertyDef.SerializeL( aBuffer );
+	
+	aBuffer.PositionL( aFreeSpace );
+	return CMdsItemDef::SerializeL( aBuffer );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsquerycriteriadeserialization.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,178 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to deserialize client query cliteria
+*
+*/
+
+#include "mdsquerycriteriadeserialization.h"
+
+
+CMdSQueryCriteriaDeserialization* CMdSQueryCriteriaDeserialization::NewL(CMdCSerializationBuffer& aSerializationBuffer)
+	{
+    CMdSQueryCriteriaDeserialization* serialization = 
+    	CMdSQueryCriteriaDeserialization::NewLC( aSerializationBuffer );
+    CleanupStack::Pop( serialization );
+    return serialization;
+	}
+
+CMdSQueryCriteriaDeserialization* CMdSQueryCriteriaDeserialization::NewLC(CMdCSerializationBuffer& aSerializationBuffer)
+	{
+    CMdSQueryCriteriaDeserialization* serialization = 
+    	new( ELeave ) CMdSQueryCriteriaDeserialization( aSerializationBuffer );
+    CleanupStack::PushL( serialization );
+    return serialization;
+	}
+
+CMdSQueryCriteriaDeserialization::~CMdSQueryCriteriaDeserialization()
+	{
+	// Doesn't own serialized buffer
+	}
+
+TPtr8 CMdSQueryCriteriaDeserialization::Buffer() const
+	{
+	return iSerializedBuffer.Buffer();
+	}
+
+const TPtr8* CMdSQueryCriteriaDeserialization::BufferPtr() const
+	{
+	return iSerializedBuffer.BufferPtr();
+	}
+
+CMdCSerializationBuffer& CMdSQueryCriteriaDeserialization::SerializationBuffer()
+	{
+	return iSerializedBuffer;
+	}
+
+TQueryResultMode CMdSQueryCriteriaDeserialization::ResultModeL()
+	{
+	iSerializedBuffer.PositionL( KOffsetResultMode );
+	
+	TInt32 resultMode;
+	iSerializedBuffer.ReceiveL( resultMode );
+	
+	return (TQueryResultMode)resultMode;
+	}
+
+TQueryType CMdSQueryCriteriaDeserialization::QueryTypeL()
+	{
+	iSerializedBuffer.PositionL( KOffsetQueryType );
+	
+	TInt32 queryType;
+	iSerializedBuffer.ReceiveL( queryType );
+	
+	return (TQueryType)queryType;
+	}
+
+TDefId CMdSQueryCriteriaDeserialization::NamespaceDefIdL()
+	{
+	iSerializedBuffer.PositionL( KOffsetNamespaceDefId );
+	
+	TDefId namespaceDefId;
+	iSerializedBuffer.ReceiveL( namespaceDefId );
+
+	return namespaceDefId;
+	}
+
+TDefId CMdSQueryCriteriaDeserialization::ObjectDefIdL()
+	{
+	iSerializedBuffer.PositionL( KOffsetObjectDefId );
+	
+	TDefId objectDefId;
+	iSerializedBuffer.ReceiveL( objectDefId );
+
+	return objectDefId;
+	}
+
+TBool CMdSQueryCriteriaDeserialization::ObjectDefsIdsL()
+	{
+	iSerializedBuffer.PositionL( KOffsetObjectDefsIds );
+
+	TUint32 offset;
+	iSerializedBuffer.ReceiveL( offset );
+
+	if( KNoOffset == offset )
+		{
+		return EFalse;
+		}
+	else
+		{
+		iSerializedBuffer.PositionL( offset );
+		return ETrue;
+		}
+	}
+
+TUint32 CMdSQueryCriteriaDeserialization::LimitL()
+	{
+	iSerializedBuffer.PositionL( KOffsetLimit );
+	
+	TUint32 limit;
+	iSerializedBuffer.ReceiveL( limit );
+
+	return limit;
+	}
+
+TUint32 CMdSQueryCriteriaDeserialization::OffsetL()
+	{
+	iSerializedBuffer.PositionL( KOffsetOffset );
+
+	TUint32 offset;
+	iSerializedBuffer.ReceiveL( offset );
+
+	return offset;
+	}
+
+TUint32 CMdSQueryCriteriaDeserialization::OptimizationFlagsL()
+	{
+	iSerializedBuffer.PositionL( KOffsetOptimizationFlags );
+
+	TUint32 optimizationFlags;
+	iSerializedBuffer.ReceiveL( optimizationFlags );
+
+	return optimizationFlags;
+	}
+
+void CMdSQueryCriteriaDeserialization::RootConditionL()
+	{
+	iSerializedBuffer.PositionL( KOffsetRootCondition );
+	
+	TUint32 offset;
+	iSerializedBuffer.ReceiveL( offset );
+	
+	iSerializedBuffer.PositionL( offset );
+	}
+
+void CMdSQueryCriteriaDeserialization::OrderRulesL()
+	{
+	iSerializedBuffer.PositionL( KOffsetOrderRules );
+
+	TUint32 offset;
+	iSerializedBuffer.ReceiveL( offset );
+	
+	iSerializedBuffer.PositionL( offset );
+	}
+
+void CMdSQueryCriteriaDeserialization::PropertyFiltersL()
+	{
+	iSerializedBuffer.PositionL( KOffsetPropertyFilters );
+
+	TUint32 offset;
+	iSerializedBuffer.ReceiveL( offset );
+	
+	iSerializedBuffer.PositionL( offset );
+	}
+
+CMdSQueryCriteriaDeserialization::CMdSQueryCriteriaDeserialization(CMdCSerializationBuffer& aSerializationBuffer)
+	: iSerializedBuffer( aSerializationBuffer )
+	{}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsrelationdef.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,110 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about one relation
+*
+*/
+
+#include "mdsrelationdef.h"
+
+#include "mdcdef.h"
+#include "mdssqliteconnection.h"
+#include "mdcserializationbuffer.h"
+#include "mdsindexer.h"
+
+
+/**
+ * NewLC
+ */
+CMdsRelationDef* CMdsRelationDef::NewLC(const TDesC& aName )
+	{
+	CMdsRelationDef* ret = new( ELeave ) CMdsRelationDef();
+	CleanupStack::PushL( ret );
+	ret->ConstructL( aName );
+	return ret;
+	}
+	
+/**
+ * NewL
+ */
+CMdsRelationDef* CMdsRelationDef::NewL(const TDesC& aName )
+	{
+	CMdsRelationDef* ret = CMdsRelationDef::NewLC( aName );
+	CleanupStack::Pop( ret );
+	return ret;
+	}
+
+/**
+ * ConstructL
+ */
+void CMdsRelationDef::ConstructL( const TDesC& aName )
+	{
+	// check that only allowed characters (A-Z, a-z) are used
+	CheckAllowerCharatersL( aName, EFalse );
+	
+	CMdsItemDef::ConstructL( aName );
+	}
+
+/**
+ * Destructor
+ */
+CMdsRelationDef::~CMdsRelationDef()
+	{
+	}
+	
+void CMdsRelationDef::StoreToDBL( const TDefId aNamespaceDefId )
+	{
+	_LIT( KMdsSqlClauseAddRelationDef, "INSERT INTO RelationDef (NamespaceDefId,Name) Values(?,?);" );
+
+	if ( GetStoredInDB() )
+		{
+		return;
+		}
+
+    RRowData rowData;
+    CleanupClosePushL( rowData );
+
+	rowData.AppendL( TColumn( aNamespaceDefId ) );
+	rowData.AppendL( TColumn( GetName().AllocL() ) );
+	TDefId id =  MMdSIndexer::ExecuteAndGetIndexL( KMdsSqlClauseAddRelationDef, rowData );
+	if ( id != KNoDefId )
+		{
+		SetId( id );
+		}
+	SetStoredInDB();
+	CleanupStack::PopAndDestroy( &rowData );
+	}
+
+TBool CMdsRelationDef::operator==( const CMdsRelationDef& aRelationDef ) const
+	{
+	return GetName() == aRelationDef.GetName();
+	}
+
+TUint32 CMdsRelationDef::RequiredBufferSize()
+	{
+	return sizeof(TMdCRelationDef) + CMdsItemDef::RequiredBufferSize();
+	}
+
+TMdCOffset CMdsRelationDef::SerializeL(CMdCSerializationBuffer& aBuffer, TMdCOffset aFreeSpace)
+	{
+	TMdCRelationDef relationDef;
+	relationDef.iDefId = GetId();
+	
+	// store name
+	relationDef.iName.iPtr.iCount = GetName().Length();
+	relationDef.iName.iPtr.iOffset = aFreeSpace;
+	relationDef.SerializeL( aBuffer );
+	
+	aBuffer.PositionL( aFreeSpace );
+	return CMdsItemDef::SerializeL( aBuffer );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsschema.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,733 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to hold description about schema
+*
+*/
+
+#include <badesca.h>
+#include "mdsschema.h"
+
+#include "mdcdef.h"
+#include "mdsnamespacedef.h"
+#include "mdsobjectdef.h"
+#include "mdsclausebuffer.h"
+#include "mdsfindsqlclausedef.h"
+#include "mdspropertydef.h"
+#include "mdsdbconnectionpool.h"
+#include "mdssqliteconnection.h"
+#include "mdcserializationbuffer.h"
+#include <mdeconstants.h>
+
+
+/**
+ * NewLC
+ */
+CMdsSchema* CMdsSchema::NewLC( )
+	{
+	CMdsSchema* ret = new( ELeave ) CMdsSchema( );
+	CleanupStack::PushL( ret );
+	ret->ConstructL( );
+	return ret;
+	}
+	
+/**
+ * NewL
+ */
+CMdsSchema* CMdsSchema::NewL( )
+	{
+	CMdsSchema* ret = CMdsSchema::NewLC( );
+	CleanupStack::Pop( ret );
+	return ret;
+	}
+
+/**
+ * ConstructL
+ */
+void CMdsSchema::ConstructL( )
+	{
+	}
+
+/**
+ * Constructor
+ */
+CMdsSchema::CMdsSchema() : iBaseObject( NULL ),
+        iSerialized( EFalse ), iSchemaHandle( 0 )
+	{
+	}
+
+/**
+ * Destructor
+ */
+CMdsSchema::~CMdsSchema()
+	{
+	iNamespaceDefs.ResetAndDestroy();
+	iNamespaceDefs.Close();
+
+	iSerializedSchema.Close();
+	iProperties.Close();
+
+	delete iBaseObject;
+	}
+
+void CMdsSchema::Reset()
+	{
+	// deleting namespaces
+	iNamespaceDefs.ResetAndDestroy();
+	}
+
+void CMdsSchema::AddDefaultObjectL()
+	{
+	
+	iBaseObject = CMdsObjectDef::NewL( MdeConstants::Object::KBaseObject, NULL );
+	iBaseObject->SetId(KBaseObjectDefId);
+	
+	// name, type, min, max, read-only, mandatory, indexed
+	iBaseObject->AddPropertyL( MdeConstants::Object::KOriginProperty, EPropertyUint8, TInt32(0), TInt32(KMaxTUint8), EFalse, EFalse, EFalse );
+	iBaseObject->AddPropertyL( MdeConstants::Object::KSizeProperty, EPropertyUint32, TUint32(0), KMaxTUint32, EFalse, EFalse, EFalse );
+	iBaseObject->AddPropertyL( MdeConstants::Object::KTimeOffsetProperty, EPropertyInt16, TInt32(KMinTInt16), TInt32(KMaxTInt16), ETrue, EFalse, EFalse );
+	iBaseObject->AddPropertyL( MdeConstants::Object::KCreationDateProperty, EPropertyTime, KMinTInt64, KMaxTInt64, EFalse, ETrue, EFalse );
+	iBaseObject->AddPropertyL( MdeConstants::Object::KLastModifiedDateProperty, EPropertyTime, KMinTInt64, KMaxTInt64, EFalse, ETrue, EFalse );
+	iBaseObject->AddPropertyL( MdeConstants::Object::KItemTypeProperty, EPropertyText, TInt32(0), TInt32(255), EFalse, EFalse, EFalse );
+	iBaseObject->AddPropertyL( MdeConstants::Object::KTitleProperty, EPropertyText, TInt32(0), TInt32(255), EFalse, EFalse, EFalse );
+	
+	TInt propcount = iBaseObject->GetPropertiesCount();
+	iBaseObject->iCol2Prop.Reset();
+	
+	for (TInt i = 0 ; i < propcount; i++)
+		{
+		CMdsPropertyDef* propertyDef = iBaseObject->GetProperty(i);
+		propertyDef->SetId(i+1);
+		CMdsObjectDef::TMdsColumnOrder col = 
+			{ i + KBaseObjectBasicValueColumnOffset, *propertyDef };
+		iBaseObject->iCol2Prop.AppendL( col );
+		if( propertyDef->GetMandatory() )
+			{
+			++iBaseObject->iMandatoryPropertyCount;
+			}
+		}
+	}
+
+void CMdsSchema::AddDefaultNamespaceL()
+	{
+	NamespaceAddL( KMdEDefaultNameSpace, EFalse, KNokiaVendorId, KDefaultNamespaceDefId );
+	}
+
+CMdsNamespaceDef* CMdsSchema::NamespaceAddL( const TDesC& aName, const TBool aReadOnly, TInt32 aVendorId, TDefId aNamespaceDefId )
+	{
+	CMdsNamespaceDef* newNamespace = CMdsNamespaceDef::NewLC( aNamespaceDefId, aName, aReadOnly, aVendorId );
+	newNamespace->SetBaseObject( iBaseObject );
+	iNamespaceDefs.AppendL( newNamespace );
+	CleanupStack::Pop( newNamespace );
+	return newNamespace;
+	}
+
+CMdsNamespaceDef* CMdsSchema::GetNamespace( const TDesC& aName )
+	{
+	const TInt count = iNamespaceDefs.Count();
+	
+	for( TInt i = 0; i < count; ++i )
+		{
+		if ( iNamespaceDefs[i]->GetName().Compare( aName ) == 0 )
+			{
+			return iNamespaceDefs[i];
+			}
+		}
+	return NULL;
+	}
+
+const CMdsNamespaceDef* CMdsSchema::GetNamespaceByIdL( TDefId aId )
+	{
+	const TInt namespaceCount = iNamespaceDefs.Count();
+	for ( TInt i = 0; i < namespaceCount; ++i )
+		{
+		if( iNamespaceDefs[i]->GetId() == aId )
+			{
+			return iNamespaceDefs[i];
+			}
+		}
+	return NULL;
+	}
+
+TInt CMdsSchema::NamespaceDefsCount() const
+	{
+	return iNamespaceDefs.Count();
+	}
+
+const RPointerArray<CMdsNamespaceDef>& CMdsSchema::NamespaceDefs() const
+	{
+	return iNamespaceDefs;
+	}
+
+void CMdsSchema::AddObjectToSqlClauseL( CMdsObjectDef* aObject, CMdsClauseBuffer* aClause,
+                                        const TBool& aAddText )
+	{
+	if ( !aObject->iParent )
+		{
+		return;
+		}
+	AddObjectToSqlClauseL( (CMdsObjectDef*)aObject->iParent, aClause, aAddText);
+
+	const TInt objectPropertyCount = aObject->iPropertyDefs.Count();
+	for ( TInt i = 0; i < objectPropertyCount; ++i )
+		{
+		CMdsPropertyDef* propertyDef = aObject->iPropertyDefs[i];
+		// to set up text columns as a last one
+		if ( propertyDef->GetType() == EPropertyText && aAddText == EFalse )
+			{
+			continue;
+			}
+		if ( propertyDef->GetType() != EPropertyText && aAddText )
+			{
+			continue;
+			}
+		// end
+
+		// make object table definition
+		aClause->AppendL( propertyDef->GetName() );
+		aClause->AppendL( KSpace );
+		aClause->AppendL( propertyDef->GetSqlTypeName() );
+		aClause->AppendL( KComma );
+		}
+	}
+
+void CMdsSchema::CreateObjectTablesL()
+	{
+	_LIT( KBaseObjectDefinition,  "CREATE TABLE IF NOT EXISTS %S%u(ObjectId INTEGER PRIMARY KEY AUTOINCREMENT,ObjectDefId INTEGER NOT NULL,Flags INTEGER,MediaId LARGEINT,UsageCount LARGEINT DEFAULT 0,GuidHigh LARGEINT,GuidLow LARGEINT,URI TEXT NOT NULL COLLATE NOCASE,Origin INTEGER,Size LARGEINT,TimeOffset INTEGER,CreationDate LARGEINT,LastModifiedDate LARGEINT,ItemType TEXT,Title TEXT,UNIQUE(GuidHigh,GuidLow),UNIQUE(MediaId,URI));" );	
+	_LIT( KCreateRelationsTable,  "CREATE TABLE IF NOT EXISTS Relations%u(RelationId INTEGER PRIMARY KEY AUTOINCREMENT,Flags INTEGER,RelationDefId INTEGER NOT NULL,LeftObjectId INTEGER NOT NULL,RightObjectId INTEGER NOT NULL,Parameter INTEGER,GuidHigh LARGEINT,GuidLow LARGEINT,LastModifiedDate LARGEINT);" );
+	_LIT( KCreateEventsTable,     "CREATE TABLE IF NOT EXISTS Event%u(EventId INTEGER PRIMARY KEY AUTOINCREMENT,ObjectId INTEGER NOT NULL, EventDefId INTEGER NOT NULL, Timestamp INTEGER NOT NULL, Source TEXT, Participant TEXT);" );
+	_LIT( KCreateTxtSrchTable,    "CREATE TABLE IF NOT EXISTS TextSearch%u(WordId INTEGER NOT NULL,ObjectId INTEGER NOT NULL,Position INTEGER);" );
+	_LIT( KCreateTxtSrchDicTable, "CREATE TABLE IF NOT EXISTS TextSearchDictionary%u(WordId INTEGER PRIMARY KEY,Word TEXT NOT NULL);" );
+
+	_LIT( KMdsSqlClauseObjTableBeg, "CREATE TABLE IF NOT EXISTS %S%u(ObjectId INTEGER NOT NULL," );
+	_LIT( KMdsSqlClauseObjTableEnd, " UNIQUE(ObjectId));" );
+
+    // Triggers
+	_LIT( KMdsTriggerEvent,      "CREATE TRIGGER DeleteEvent%u BEFORE DELETE ON Object%u BEGIN DELETE FROM Event%u WHERE ObjectId=OLD.ObjectId; END;" );
+	_LIT( KMdsTriggerRelation,   "CREATE TRIGGER DeleteRelations%u BEFORE DELETE ON Object%u BEGIN DELETE FROM Relations%u WHERE LeftObjectId=OLD.ObjectId OR RightObjectId=OLD.ObjectId; END;" );
+    _LIT( KMdsTriggerTextSearch, "CREATE TRIGGER DeleteTextSearch%u BEFORE DELETE ON Object%u BEGIN DELETE FROM TextSearch%u WHERE ObjectId=OLD.ObjectId; END;" );	
+
+	// UsageCount relation triggers
+	_LIT( KMdsTriggerInsertRelation, "CREATE TRIGGER InsertRelations%u INSERT ON Relations%u BEGIN UPDATE Object%u SET UsageCount = UsageCount + 1 WHERE ObjectId=NEW.LeftObjectId OR ObjectId=NEW.RightObjectId; END;" );
+	_LIT( KMdsTriggerUpdateRelation, "CREATE TRIGGER UpdateRelations%u UPDATE OF LeftObjectId, RightObjectId ON Relations%u WHEN OLD.Flags=NEW.Flags BEGIN UPDATE Object%u SET UsageCount = UsageCount - 1 WHERE ObjectId=OLD.LeftObjectId OR ObjectId=OLD.RightObjectId; UPDATE Object1 SET UsageCount = UsageCount + 1 WHERE ObjectId=NEW.LeftObjectId OR ObjectId=NEW.RightObjectId; END;" );
+	_LIT( KMdsTriggerUpdateNotRemovedRelation, "CREATE TRIGGER UpdateNotRemovedRelations%u UPDATE OF Flags ON Relations%u WHEN OLD.Flags!=NEW.Flags AND NOT NEW.Flags&%u BEGIN UPDATE Object%u SET UsageCount = UsageCount + 1 WHERE ObjectId=NEW.LeftObjectId OR ObjectId=NEW.RightObjectId; END;" );
+	_LIT( KMdsTriggerUpdateRemovedRelation,    "CREATE TRIGGER UpdateRemovedRelations%u UPDATE OF Flags ON Relations%u WHEN OLD.Flags!=NEW.Flags AND NEW.Flags&%u AND NOT OLD.Flags&%u BEGIN UPDATE Object%u SET UsageCount = UsageCount - 1 WHERE ObjectId=OLD.LeftObjectId OR ObjectId=OLD.RightObjectId; END;" );
+
+	// Relation indexes
+	_LIT( KMdsIndexRelationLeftObjectId,  "CREATE INDEX RelationsLeftObjectIdIndex%u ON Relations%u(LeftObjectId);" );
+	_LIT( KMdsIndexRelationRightObjectId, "CREATE INDEX RelationsRightObjectIdIndex%u ON Relations%u(RightObjectId);" );
+
+	// freetext indexes
+	_LIT( KMdsIndexFreetextWordId,   "CREATE INDEX FreetextWordIdIndex%u ON TextSearch%u(WordId);" );
+	_LIT( KMdsIndexFreetextObjectId, "CREATE INDEX FreetextObjectIdIndex%u ON TextSearch%u(ObjectId);" );
+	
+	// ObjectTypeDefinition index
+	_LIT( KMdsIndexObjectDefId, "CREATE INDEX ObjectDefIndex%u ON Object%u(ObjectDefId);" );
+
+	// create tables
+	CMdsClauseBuffer* clause = CMdsClauseBuffer::NewLC( 1024 );
+	clause->ReserveSpaceL( KBaseObjectDefinition.iTypeLength + 30 ); // maxIntNumberDecimal.Length = 10
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+    RRowData emptyRowData;
+    CleanupClosePushL( emptyRowData );
+
+	// for triggers
+	CMdsClauseBuffer* clauseTrigger = CMdsClauseBuffer::NewLC( 1024 );
+	
+	const TInt namespaceDefCount = iNamespaceDefs.Count();
+	
+	// add objectdef[number] to DB
+	for( TInt i = 0; i < namespaceDefCount; ++i )
+		{
+		CMdsNamespaceDef* namespaceDef = iNamespaceDefs[i];
+		const TDefId namespaceDefId = namespaceDef->GetId();
+
+		if (!namespaceDef->GetTableStoredInDB())
+			{
+			// add base objectdef[number]
+			clause->BufferL().Format( KBaseObjectDefinition, &MdeConstants::Object::KBaseObject, namespaceDefId );
+			TRAP_IGNORE( connection.ExecuteL( clause->ConstBufferL(), emptyRowData ) );			
+
+			// add relations[number]
+			clause->BufferL().Format( KCreateRelationsTable, namespaceDefId );
+			TRAPD( errRel, connection.ExecuteL( clause->ConstBufferL(), emptyRowData ) );
+	        if( errRel == KErrNone )
+	            {
+	            clauseTrigger->ReserveSpaceL( KMdsTriggerRelation().Size() + ( KMaxUintValueLength * 3 ) );  
+	            clauseTrigger->BufferL().Format( KMdsTriggerRelation, namespaceDefId, namespaceDefId, namespaceDefId );
+	            connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
+	            }
+
+			// add event[number]
+			clause->BufferL().Format( KCreateEventsTable, namespaceDefId );
+			TRAPD( errEve, connection.ExecuteL( clause->ConstBufferL(), emptyRowData ) );
+	        if( errEve == KErrNone )
+	            {
+	            clauseTrigger->ReserveSpaceL( KMdsTriggerEvent().Size() + ( KMaxUintValueLength * 3 ) );  
+	            clauseTrigger->BufferL().Format( KMdsTriggerEvent, namespaceDefId, namespaceDefId, namespaceDefId );
+	            connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
+	            }
+
+			// add textsearch[number]
+			clause->BufferL().Format( KCreateTxtSrchTable, namespaceDefId );
+			TRAPD( errTS, connection.ExecuteL( clause->ConstBufferL(), emptyRowData ) );
+	        if( errTS == KErrNone )
+	            {
+	            clauseTrigger->ReserveSpaceL( KMdsTriggerTextSearch().Size() + ( KMaxUintValueLength * 3 ) );  
+	            clauseTrigger->BufferL().Format( KMdsTriggerTextSearch, namespaceDefId, namespaceDefId, namespaceDefId );
+	            connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
+
+				// add KMdsIndexFreetextWordId[number]
+	            clauseTrigger->ReserveSpaceL( KMdsIndexFreetextWordId().Size() + ( KMaxUintValueLength * 2 ) );  
+	            clauseTrigger->BufferL().Format( KMdsIndexFreetextWordId, namespaceDefId, namespaceDefId );
+	            connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
+				
+				// add KMdsIndexFreetextObjectId[number]
+	            clauseTrigger->ReserveSpaceL( KMdsIndexFreetextObjectId().Size() + ( KMaxUintValueLength * 2 ) );  
+	            clauseTrigger->BufferL().Format( KMdsIndexFreetextObjectId, namespaceDefId, namespaceDefId );
+	            connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
+	            }
+
+			// add textsearchdictionary[number]
+			clause->BufferL().Format( KCreateTxtSrchDicTable, namespaceDefId );
+			TRAP_IGNORE( connection.ExecuteL( clause->ConstBufferL(), emptyRowData ) );
+			
+			// add insertrelations[number]
+            clauseTrigger->ReserveSpaceL( KMdsTriggerInsertRelation().Size() + ( KMaxUintValueLength * 3 ) );  
+            clauseTrigger->BufferL().Format( KMdsTriggerInsertRelation, namespaceDefId, namespaceDefId, namespaceDefId );
+            connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
+
+			// add updaterelations[number]
+            clauseTrigger->ReserveSpaceL( KMdsTriggerUpdateRelation().Size() + ( KMaxUintValueLength * 3 ) );  
+            clauseTrigger->BufferL().Format( KMdsTriggerUpdateRelation, namespaceDefId, namespaceDefId, namespaceDefId );
+            connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
+
+			// add updatenotremovedrelations[number]
+            clauseTrigger->ReserveSpaceL( KMdsTriggerUpdateNotRemovedRelation().Size() + ( KMaxUintValueLength * 4 ) );  
+            clauseTrigger->BufferL().Format( KMdsTriggerUpdateNotRemovedRelation, namespaceDefId, namespaceDefId, 
+                    EMdERelationFlagNotPresent | EMdERelationFlagDeleted, namespaceDefId );
+            connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
+
+			// add updateremovedrelations[number]
+            clauseTrigger->ReserveSpaceL( KMdsTriggerUpdateRemovedRelation().Size() + ( KMaxUintValueLength * 5 ) );  
+            clauseTrigger->BufferL().Format( KMdsTriggerUpdateRemovedRelation, namespaceDefId, namespaceDefId, EMdERelationFlagNotPresent | EMdERelationFlagDeleted, EMdERelationFlagNotPresent | EMdERelationFlagDeleted, namespaceDefId );
+            connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
+
+			// add relationleftobjectidindex[number]
+            clauseTrigger->ReserveSpaceL( KMdsIndexRelationLeftObjectId().Size() + ( KMaxUintValueLength * 2 ) );  
+            clauseTrigger->BufferL().Format( KMdsIndexRelationLeftObjectId, namespaceDefId, namespaceDefId );
+            connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
+
+			// add relationrightobjectidindex[number]
+            clauseTrigger->ReserveSpaceL( KMdsIndexRelationRightObjectId().Size() + ( KMaxUintValueLength * 2 ) );  
+            clauseTrigger->BufferL().Format( KMdsIndexRelationRightObjectId, namespaceDefId, namespaceDefId );
+            connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
+
+            // add objectdefidindex[number]
+            clauseTrigger->ReserveSpaceL( KMdsIndexObjectDefId().Size() + ( KMaxUintValueLength * 2 ) );  
+            clauseTrigger->BufferL().Format( KMdsIndexObjectDefId, namespaceDefId, namespaceDefId );
+            connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
+            
+			namespaceDef->SetTableStoredInDB();
+			}
+
+		const TInt objectDefCount = namespaceDef->iObjectDefs.Count();
+		
+		for ( TInt j = 0; j < objectDefCount; ++j )
+			{
+			CMdsObjectDef* objectDef = namespaceDef->iObjectDefs[j];
+
+			if (!objectDef->GetTableStoredInDB())
+				{
+				clause->BufferL().Format( KMdsSqlClauseObjTableBeg, &objectDef->GetName(), namespaceDef->GetId() );
+
+				// add no text properties
+				AddObjectToSqlClauseL( objectDef, clause, EFalse );
+				// add text properties at end
+				AddObjectToSqlClauseL( objectDef, clause, ETrue );
+
+				clause->AppendL( KMdsSqlClauseObjTableEnd );
+				TRAP_IGNORE( connection.ExecuteL( clause->ConstBufferL(), emptyRowData ) );
+
+				objectDef->SetTableStoredInDB();
+				}
+
+			const TInt objectPropertyCount = objectDef->iPropertyDefs.Count();
+			for ( TInt k = 0; k < objectPropertyCount; ++k )
+				{
+				CMdsPropertyDef* propertyDef = objectDef->iPropertyDefs[k];
+				
+				if ( propertyDef->GetIndexed() )
+					{
+					iProperties.AppendL( TPropertyInfo( objectDef->GetName(), 
+							propertyDef->GetName(), namespaceDef->GetId() ) );
+					}
+				}
+			}
+        iProperties.AppendL( TPropertyInfo( MdeConstants::Object::KBaseObject, MdeConstants::Object::KItemTypeProperty, namespaceDef->GetId() ) );
+		}
+
+	CleanupStack::PopAndDestroy( 3, clause ); // clauseTrigger, emptyRowData, clause
+	}
+
+void CMdsSchema::CreatePropertyIndexL( const TDesC& aPropertyName, const TDesC& aTableName, 
+		TDefId aNamespaceId )
+	{
+	_LIT( KMdsPropertyIndexCreate, "CREATE INDEX %S%SIndex%u ON %S%u(%S);" );
+	
+	const TUint clauseLength = KMdsPropertyIndexCreate.iTypeLength + aTableName.Length() * 2 +
+		+ aPropertyName.Length() * 2 + KMaxUintValueLength * 2;
+	CMdsClauseBuffer* clause = CMdsClauseBuffer::NewLC( clauseLength );
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+    RRowData emptyRowData;
+    CleanupClosePushL( emptyRowData );
+    clause->BufferL().Format( KMdsPropertyIndexCreate, &aTableName, &aPropertyName, aNamespaceId,
+    		&aTableName, aNamespaceId, &aPropertyName );
+	TRAP_IGNORE( connection.ExecuteL( clause->ConstBufferL(), emptyRowData ) );
+	CleanupStack::PopAndDestroy( 2, clause ); // emptyRowData, clause
+	}
+
+void CMdsSchema::StoreToDBL()
+	{
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+    RMdSTransaction transaction( connection );
+    CleanupClosePushL( transaction );
+    User::LeaveIfError( transaction.Error() );
+
+	StoreNamespacesAndBaseObjectL();
+    CreateObjectTablesL();
+	StoreSchemaToDBL();
+	CreateCol2PropTableL();
+
+    transaction.CommitL();
+    CleanupStack::PopAndDestroy( &transaction );
+    
+    TUint propertyCount = iProperties.Count();
+    for ( TUint i = 0; i < propertyCount; ++i )
+    	{
+    	TPropertyInfo& propertyInfo = iProperties[i];
+    	CreatePropertyIndexL( propertyInfo.iPropertyName, propertyInfo.iTableName,
+    			propertyInfo.iNamespaceId );
+    	}
+    iProperties.Reset();
+	}
+
+void CMdsSchema::AddCol2PropObjectL( CMdsObjectDef* aObject, CMdsObjectDef* aChildObject,
+									 TUint32& aPropertyColumnCounter, TBool aText )
+	{
+	_LIT( KMdsSqlClauseAddCol2Prop, "INSERT INTO Col2Prop(ObjectDefId,PropertyDefId,ColumnId) Values(?,?,?);" );
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	if ( !aChildObject->iParent )
+		{
+		if (aText)
+			{
+			return;
+			}
+		RRowData rowData;
+		CleanupClosePushL( rowData );
+		const TInt childObjectPropertyCount = aChildObject->iPropertyDefs.Count();
+		for ( TInt i = 0; i < childObjectPropertyCount; ++i )
+			{
+			CMdsPropertyDef* propertyDef = aChildObject->iPropertyDefs[i];
+			CMdsObjectDef::TMdsColumnOrder col = { aChildObject->iCol2Prop[i].iColumnId, *propertyDef };
+			aObject->iCol2Prop.AppendL( col );
+			
+			if( propertyDef->GetMandatory() )
+				{
+				++aObject->iMandatoryPropertyCount;
+				}
+			
+			++aPropertyColumnCounter;
+			rowData.Reset();
+			rowData.AppendL( TColumn( aObject->GetId() ) );
+			rowData.AppendL( TColumn( propertyDef->GetId() ) );
+			rowData.AppendL( TColumn( col.iColumnId ) );
+			connection.ExecuteL( KMdsSqlClauseAddCol2Prop, rowData );
+			}
+		CleanupStack::PopAndDestroy( &rowData );
+		return;
+		}
+
+	AddCol2PropObjectL( aObject, (CMdsObjectDef*)aChildObject->iParent, aPropertyColumnCounter, aText );
+
+	// if parent is baseobject
+	if ( !aText && !aChildObject->iParent->iParent )
+		{
+		++aPropertyColumnCounter;
+		}
+
+	RRowData rowData;
+	CleanupClosePushL( rowData );
+
+	const TInt childObjectPropertyCount = aChildObject->iPropertyDefs.Count();
+	for ( TInt i = 0; i < childObjectPropertyCount; ++i )
+		{
+		CMdsPropertyDef* propertyDef = aChildObject->iPropertyDefs[i];
+		CMdsObjectDef::TMdsColumnOrder col = { 0, *propertyDef };
+		if (  aText && propertyDef->GetType() != EPropertyText ||
+			 !aText && propertyDef->GetType() == EPropertyText )
+			{
+			continue;
+			}
+
+		col.iColumnId = aPropertyColumnCounter++;
+
+		aObject->iCol2Prop.AppendL( col );
+
+		if( propertyDef->GetMandatory() )
+			{
+			++aObject->iMandatoryPropertyCount;
+			}
+
+		rowData.Reset();
+		rowData.AppendL( TColumn( aObject->GetId() ) );
+		rowData.AppendL( TColumn( propertyDef->GetId() ) );
+		rowData.AppendL( TColumn( col.iColumnId ) );
+		connection.ExecuteL( KMdsSqlClauseAddCol2Prop, rowData );
+		}
+
+	CleanupStack::PopAndDestroy( &rowData );
+	}
+
+void CMdsSchema::CreateCol2PropTableL()
+	{
+	_LIT( KMdsSqlClauseCol2Prop,       "CREATE TABLE IF NOT EXISTS Col2Prop(ObjectDefId INTEGER NOT NULL,PropertyDefId INTEGER NOT NULL,ColumnId INTEGER NOT NULL);" );
+
+    RRowData emptyRowData;
+    CleanupClosePushL( emptyRowData );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	// create binding column <--> property table
+	connection.ExecuteL( KMdsSqlClauseCol2Prop, emptyRowData );
+	TUint32 propertyColumnCounter;
+
+	const TInt count = iNamespaceDefs.Count();
+	
+	for( TInt i = 0; i < count; ++i )
+		{
+		CMdsNamespaceDef* namespaceDef = iNamespaceDefs[i];
+		const TInt namespaceObjectCount = namespaceDef->iObjectDefs.Count();
+		for ( TInt j = 0; j < namespaceObjectCount; ++j )
+			{
+			CMdsObjectDef* objectDef = namespaceDef->iObjectDefs[j];
+			if (!objectDef->GetC2PStoredInDB())
+				{
+				propertyColumnCounter = KBaseObjectBasicValueColumnOffset;
+
+				objectDef->iCol2Prop.Reset();
+				objectDef->iMandatoryPropertyCount = 0;
+
+				AddCol2PropObjectL( objectDef, objectDef, propertyColumnCounter, EFalse );
+				AddCol2PropObjectL( objectDef, objectDef, propertyColumnCounter, ETrue );
+				objectDef->SetC2PStoredInDB();
+				}
+			}
+		}
+	CleanupStack::PopAndDestroy( &emptyRowData );
+	}
+
+void CMdsSchema::StoreNamespacesAndBaseObjectL()
+	{
+	_LIT( KMdsSqlClauseNamespaceDef, "CREATE TABLE IF NOT EXISTS NamespaceDef(NamespaceDefId INTEGER PRIMARY KEY,ReadOnly INTEGER,VendorId INTEGER,Name TEXT);" );
+	_LIT( KMdsSqlClauseObjectDef,    "CREATE TABLE IF NOT EXISTS ObjectDef(ObjectDefId INTEGER PRIMARY KEY,NamespaceDefId INTEGER NOT NULL,ParentDefId INTEGER NOT NULL,Flags INTEGER,Name TEXT);" );
+	_LIT( KMdsSqlClausePropertyDef,  "CREATE TABLE IF NOT EXISTS PropertyDef(PropertyDefId INTEGER PRIMARY KEY,ObjectDefId INTEGER NOT NULL,Flags INTEGER,Type INTEGER,MinValue NUMERIC,MaxValue NUMERIC,Name TEXT);" );
+	_LIT( KMdsSqlClauseRelationDef,  "CREATE TABLE IF NOT EXISTS RelationDef(RelationDefId INTEGER PRIMARY KEY,NamespaceDefId INTEGER NOT NULL,Name TEXT);" );
+	_LIT( KMdsSqlClauseEventDef,     "CREATE TABLE IF NOT EXISTS EventDef(EventDefId INTEGER PRIMARY KEY,NamespaceDefId INTEGER NOT NULL,Priority INTEGER,Name TEXT);" );
+
+    RRowData emptyRowData;
+    CleanupClosePushL( emptyRowData );
+
+	// create tables
+	const TUint KNumClauses = 5;
+
+	CDesCArrayFlat* descarray = new (ELeave) CDesCArrayFlat(KNumClauses);
+	CleanupStack::PushL(descarray);
+	descarray->AppendL(KMdsSqlClauseNamespaceDef);
+	descarray->AppendL(KMdsSqlClauseObjectDef);
+	descarray->AppendL(KMdsSqlClausePropertyDef);
+	descarray->AppendL(KMdsSqlClauseRelationDef);
+	descarray->AppendL(KMdsSqlClauseEventDef);
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	TInt error;
+	for (TUint i = 0; i < KNumClauses; i++)
+		{
+		TRAP( error,connection.ExecuteL( (*descarray)[i], emptyRowData ) );
+		if ( error != KErrNone && error != KSqlErrGeneral )
+			{
+			User::Leave( error );
+			}
+		}
+	descarray->Reset();
+	CleanupStack::PopAndDestroy( descarray );
+
+	const TInt count = iNamespaceDefs.Count();
+	
+	// add only namespaceDef to DB
+	for( TInt i = 0; i < count; ++i )
+		{
+		iNamespaceDefs[i]->StoreToDBL( ETrue );
+		}
+
+	CleanupStack::PopAndDestroy( &emptyRowData );
+	}
+
+void CMdsSchema::StoreSchemaToDBL()
+	{
+	_LIT( KMdsSqlClauseDeleteBoFromOd,  "DELETE FROM ObjectDef WHERE ObjectDefId=?;" );
+	_LIT( KMdsSqlClauseDeleteBoFromPd,  "DELETE FROM PropertyDef WHERE ObjectDefId=?;" );
+
+	iBaseObject->StoreToDBL( KNoDefId );
+	
+	const TInt count = iNamespaceDefs.Count();
+	
+	// add namespaceDef to DB
+	for( TInt i = 0; i < count; ++i )
+		{
+		iNamespaceDefs[i]->StoreToDBL();
+		}
+
+	RRowData removeBo;
+	CleanupClosePushL( removeBo );
+	removeBo.AppendL( TColumn( KBaseObjectDefId ) );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	TRAPD( err, connection.ExecuteL( KMdsSqlClauseDeleteBoFromOd,  removeBo ) );
+	TRAP ( err, connection.ExecuteL( KMdsSqlClauseDeleteBoFromPd,  removeBo ) );
+	
+	CleanupStack::PopAndDestroy( &removeBo );	
+	}
+
+void CMdsSchema::MergeElementsL( CMdsSchema& aSchema, const TBool& aDryRun )
+	{
+	const TInt count = aSchema.iNamespaceDefs.Count();
+	
+	for ( TInt i = 0; i < count; ++i )
+		{
+		CMdsNamespaceDef* lNamespace = NULL;
+		CMdsNamespaceDef* rNamespace = aSchema.iNamespaceDefs[i];
+		// reseting after namespace read from file
+		rNamespace->UnsetFirstRead();
+		// search for namespace
+        lNamespace = GetNamespace( rNamespace->GetName() );
+		if ( !lNamespace )
+			{
+			if ( !aDryRun )
+				{
+				// just add pointer to new schema and remove it from old one
+				iNamespaceDefs.AppendL( rNamespace );
+				aSchema.iNamespaceDefs[i] = NULL;
+				rNamespace->SetAllNotStoredInDB();
+				}
+			}
+		else
+			{
+			// copy appropriate elements
+			if ( lNamespace->GetVendorId() == rNamespace->GetVendorId() && !lNamespace->GetReadOnly() )
+				{
+				lNamespace->MergeObjectsL( rNamespace, aDryRun );
+				lNamespace->MergeEventsL( rNamespace, aDryRun );
+				lNamespace->MergeRelationsL( rNamespace, aDryRun );
+				}
+			else
+				{
+				User::Leave( KErrAccessDenied );
+				}
+			}
+		}
+	}
+
+void CMdsSchema::MergeNamespacesL( CMdsSchema& aSchema )
+	{
+	if ( iNamespaceDefs.Count() == 0 )
+		{// speed optimization
+		Reset();
+		
+		const TInt count = aSchema.iNamespaceDefs.Count();
+		
+		for ( TInt i = 0; i < count; ++i )
+			{
+			// reseting after namespace read from file
+			aSchema.iNamespaceDefs[i]->UnsetFirstRead();
+			iNamespaceDefs.AppendL( aSchema.iNamespaceDefs[i] );
+			aSchema.iNamespaceDefs[i] = NULL;
+			}
+		aSchema.Reset();
+		}
+	else
+		{
+		MergeElementsL( aSchema, ETrue );
+		MergeElementsL( aSchema, EFalse );
+		}
+	}
+
+void CMdsSchema::SerializeToSharedMemoryL()
+	{
+	const TInt namespaceCount = iNamespaceDefs.Count();
+
+	// namespace count, namespace offsets
+	TUint32 bufferSize = sizeof(TMdCSchema) + namespaceCount * sizeof(TMdCNamespaceDef);
+
+	for ( TInt i = 0; i < namespaceCount; ++i )
+		{
+		bufferSize += iNamespaceDefs[i]->RequiredBufferSize();
+		}
+
+	// create shared memory chunk
+	iSerialized = EFalse;
+	iSerializedSchema.Close();
+	++iSchemaHandle;
+	HBufC* name = HBufC::NewLC( KSchemaChunkName.iTypeLength + KMaxUintValueLength );
+	*name = KSchemaChunkName;
+	name->Des().AppendNum( iSchemaHandle );
+
+	TInt error = KErrNone;
+	while( (error = iSerializedSchema.CreateGlobal( *name, bufferSize, bufferSize )) == KErrAlreadyExists )
+		{
+		++iSchemaHandle;
+		*name = KSchemaChunkName;
+		name->Des().AppendNum( iSchemaHandle );
+		}
+	User::LeaveIfError( error );
+
+	CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( iSerializedSchema.Base(), bufferSize );
+
+	TMdCSchema schema;
+	schema.iNamespaceDefs.iPtr.iCount = namespaceCount;
+	schema.iNamespaceDefs.iPtr.iOffset = sizeof(schema);
+	schema.SerializeL( *buffer );
+
+	TMdCOffset freeSpace = schema.iNamespaceDefs.iPtr.iOffset + namespaceCount * sizeof(TMdCNamespaceDef);
+	for ( TInt i = 0; i < namespaceCount; ++i )
+		{
+		buffer->PositionL( schema.iNamespaceDefs.iPtr.iOffset + i * sizeof(TMdCNamespaceDef) );
+
+		// write namespace
+		freeSpace = iNamespaceDefs[i]->SerializeL( *buffer, freeSpace );
+		}
+
+	CleanupStack::PopAndDestroy( buffer );
+	CleanupStack::PopAndDestroy( name );
+	iSerialized = ETrue;
+	}
+	
+TInt CMdsSchema::SharedMemoryHandleL()
+	{
+	if ( !iSerialized )
+		{
+		User::Leave( KErrNotReady );
+		}
+	return iSchemaHandle;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsserver.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,962 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Metadata main server class*
+*/
+
+// INCLUDE FILES
+#include "mdsserver.h"
+#include "mdscommoninternal.h"
+#include "mdsserversession.h"
+#include "mdsdbconnectionpool.h"
+#include "mdssqldbmaintenance.h"
+#include "mdssqliteconnection.h"
+#include "mdsnotifier.h"
+#include "mdsobjectlocklist.h"
+#include "mdslogger.h"
+#include "mdsmaintenanceengine.h"
+#include "mdsmanipulationengine.h"
+#include "mdsclausebuffer.h"
+#include "mdebackuprestorewatcher.h"
+#include "mdsschema.h"
+#include "mdcserializationbuffer.h"
+#include <f32file.h>
+
+__DEFINE_LOGGER
+
+const TInt64 KDiskSpaceGarbageCollectorThreshold = 1024*1024; // 1 MB
+const TInt64 KDiskFullThreshold = 1024*50; // 50 kB
+
+_LIT( KSchema, "schema.mde" );
+_LIT( KDefaultImportProfile, "defaultimportfile.mde" );
+_LIT( KBackupRegistration, "backup_registration.xml" );
+_LIT( KSchemaPath, "z:\\private\\200009F3\\schema.mde" );
+_LIT( KDefaultImportProfilePath, "z:\\private\\200009F3\\defaultimportfile.mde" );
+_LIT( KBackupRegistrationPath, "z:\\private\\200009F3\\backup_registration.xml" );
+
+// ========================= MdS POLICY ==================================
+
+const TUint KMdsRangeCount = EUnknownMdEServRqst + 1;
+
+const TInt KMdsRanges[KMdsRangeCount] = 
+    {
+    EShutdown,          	// shut down the session
+    EAdd,					// add items
+    ERemove,				// remove items
+    EFind,              	// finds in sync
+    EAsyncFind,         	// finds asynchronously
+    EContinueAsyncFind, 	// continues existing asynchronous find, fetches next set
+    ECancelFind,        	// cancels asynchronous find
+    ECancelObject,      	// cancels opened object
+    ECheckObject,           // get object's "base" values
+    EUpdate,		      	// update items
+    ERegister,          	// registers an object to be notified
+    EListen,            	// listens for events for a registered profile
+    EUnregister,        	// unregisters for no more notifications
+    EGetData,           	// (transfers data server->client)
+    EImportMetadata,    	// starts metadata importing
+    EAsyncImportMetadata,	// starts asynchronous metadata importing
+    EExportMetadata,		// starts metadata exporting
+    EAsyncExportMetadata,	// starts asynchronous metadata exporting
+    EImportSchema,      	// starts schema importing
+    EAddRelationDef,		// Add relation def
+    EAddEventDef,		    // Add event def
+    EAddMemoryCard,
+    EGetMemoryCard,
+    ECheckMemoryCard,
+    ESetMedia,
+    EGetMedia,
+    EGetPresentMedias,
+    ESetFileToPresent,
+    ESetFilesToPresent,
+    ESetFilesToNotPresent,
+    ERemoveFilesNotPresent,
+    EGetSchemaVersion,
+    ESetObjectToPresentByGuid, 
+    ESetHarvestingPrioritizationChunk,
+    EAddHarvestingPrioritizationObserver,
+    ECancelHarvestingPrioritizationObserver,
+    EChangePath, 
+    ESetPending,
+    EResetPending,
+    EGetPendingCount,
+    EGetPending,
+    EResetDB,
+    EChangeMediaId,
+    EUnknownMdEServRqst     // handle for unknown requests
+    };
+
+const TUint8 KMdsElementsIndex[KMdsRangeCount] = 
+    {
+    CPolicyServer::ECustomCheck,    // EShutdown
+    CPolicyServer::ECustomCheck,    // EAdd
+    CPolicyServer::ECustomCheck,    // ERemove
+    CPolicyServer::ECustomCheck,    // EFind
+    CPolicyServer::ECustomCheck,    // EAsyncFind
+    CPolicyServer::ECustomCheck,    // EContinueAsyncFind
+    CPolicyServer::ECustomCheck,    // ECancelFind
+    CPolicyServer::ECustomCheck,    // ECancelObject
+    CPolicyServer::ECustomCheck,    // ECheckObject
+    CPolicyServer::ECustomCheck,    // EUpdate
+    CPolicyServer::ECustomCheck,    // ERegister
+    CPolicyServer::ECustomCheck,    // EListen
+    CPolicyServer::ECustomCheck,    // EUnregister
+    CPolicyServer::ECustomCheck,    // EGetData
+    CPolicyServer::ECustomCheck,    // EImportMetadata
+    CPolicyServer::ECustomCheck,    // EAsyncImportMetadata
+    CPolicyServer::ECustomCheck,    // EExportMetadata
+    CPolicyServer::ECustomCheck,    // EAsyncExportMetadata
+    CPolicyServer::ECustomCheck,    // EImportSchema
+    CPolicyServer::ECustomCheck,	// EAddRelationDef
+    CPolicyServer::ECustomCheck,	// EAddEventDef
+    CPolicyServer::ECustomCheck, 	// EAddMemoryCard
+    CPolicyServer::ECustomCheck, 	// EGetMemoryCard
+    CPolicyServer::ECustomCheck, 	// ECheckMemoryCard
+    CPolicyServer::ECustomCheck, 	// ESetMedia
+    CPolicyServer::ECustomCheck, 	// EGetMedia
+    CPolicyServer::ECustomCheck, 	// EGetPresentMedias
+    CPolicyServer::ECustomCheck, 	// ESetFileToPresent
+    CPolicyServer::ECustomCheck, 	// ESetFilesToPresent
+    CPolicyServer::ECustomCheck, 	// ESetFilesToNotPresent
+    CPolicyServer::ECustomCheck, 	// ERemoveFilesNotPresent
+    CPolicyServer::ECustomCheck, 	// EGetSchemaVersion
+    CPolicyServer::ECustomCheck, 	// ESetObjectToPresentByGuid
+    CPolicyServer::ECustomCheck, 	// ESetHarvestingPrioritizationChunk
+    CPolicyServer::ECustomCheck, 	// EAddHarvestingPrioritizationObserver
+    CPolicyServer::ECustomCheck, 	// ECancelHarvestingPrioritizationObserver
+    CPolicyServer::ECustomCheck, 	// EChangePath
+    CPolicyServer::ECustomCheck, 	// ESetPending
+    CPolicyServer::ECustomCheck, 	// EResetPending
+    CPolicyServer::ECustomCheck, 	// EGetPendingCount
+    CPolicyServer::ECustomCheck, 	// EGetPending
+    CPolicyServer::ECustomCheck, 	// EResetDB
+    CPolicyServer::ECustomCheck, 	// EChangeMediaId
+    CPolicyServer::ENotSupported	// EUnknownMdEServRqst
+    };
+
+
+const CPolicyServer::TPolicy KMdsPolicy =
+    {
+    CPolicyServer::EAlwaysPass, //specifies all connect attempts should pass
+    KMdsRangeCount,                   
+    KMdsRanges,
+    KMdsElementsIndex,
+    NULL //mdsElements
+    };
+
+
+CPolicyServer::TCustomResult CMdSServer::CustomSecurityCheckL(
+        const RMessage2& aMsg, TInt& /*aAction*/, TSecurityInfo& /*aMissing*/ )
+    {
+    CPolicyServer::TCustomResult securityCheckResult = EFail;
+    switch ( aMsg.Function() )
+        {
+        case EAdd:
+        case ERemove:
+        case ECancelObject:
+        case EUpdate:
+        case EImportMetadata:
+        case EAsyncImportMetadata:
+        case EAddRelationDef:
+        case EAddEventDef:
+        case EImportSchema:
+        case ESetObjectToPresentByGuid:
+            {
+            if( aMsg.HasCapability( ECapabilityWriteDeviceData ) )
+                {
+                securityCheckResult = EPass;
+                }
+            }
+            break;
+
+        case ERegister:
+        case EListen:
+        case EUnregister:
+        case EFind:
+        case EAsyncFind:
+        case EContinueAsyncFind:
+        case ECancelFind:    
+        case EGetData:
+        case ECheckObject:
+            {
+            securityCheckResult = EPass;
+            }
+            break;
+            
+        case EExportMetadata:
+        case EAsyncExportMetadata:
+        case EGetSchemaVersion:
+            {
+            if( aMsg.HasCapability( ECapabilityReadUserData ) || 
+            	aMsg.HasCapability( ECapabilityReadDeviceData ) )
+                {
+                securityCheckResult = EPass;
+                }
+            }
+        	break;
+        	
+        // Only for internal MdS usage
+        case EAddMemoryCard:
+    	case EGetMemoryCard:
+        case ECheckMemoryCard:
+        case ESetMedia:
+        case EGetMedia:
+        case EGetPresentMedias:
+    	case ESetFileToPresent:
+    	case ESetFilesToPresent:
+    	case ESetFilesToNotPresent:
+    	case ERemoveFilesNotPresent:
+    	case ESetHarvestingPrioritizationChunk:
+    	case EAddHarvestingPrioritizationObserver:
+    	case ECancelHarvestingPrioritizationObserver:
+    	case EChangePath:
+    	case EChangeMediaId:
+    	case ESetPending:
+    	case EResetPending:
+    	case EGetPendingCount:
+    	case EGetPending:
+    	case EResetDB:
+    		{
+            if( aMsg.HasCapability( ECapabilityDiskAdmin ) )
+                {
+                securityCheckResult = EPass;
+                }
+    		}
+        	break;
+        	
+        default:
+            {
+            securityCheckResult = EFail;
+            }
+        }
+
+    return securityCheckResult;
+    }
+
+CPolicyServer::TCustomResult CMdSServer::CustomFailureActionL(
+        const RMessage2& /*aMsg*/, TInt /*aAction*/, const TSecurityInfo& /*aMissing*/)
+    {
+    // Not used
+    return EFail;
+    }
+
+
+// ========================= MEMBER FUNCTIONS ==================================
+void CMdSServer::HandleDiskSpaceNotificationL( TDiskSpaceDirection aDiskSpaceDirection )
+	{
+	// skip db cleaning if drive's free space is over limit or
+	// backup or restore is running
+	if( MMdSDiskSpaceNotifierObserver::EMore == aDiskSpaceDirection ||
+		iBackupOrRestoreRunning )
+		{
+		return;
+		}
+
+	// delete only objects which are in "not present" state and
+	// object was not located in last (count = KMemoryCardLimit) 
+	// inserted memory cards and object doesn't have any relations
+	_LIT( KMemoryCardCleanup, "DELETE FROM Object%u WHERE ObjectId IN(SELECT ObjectId FROM Object%u WHERE((Flags&?) AND (MediaId NOT IN(SELECT DISTINCT Value FROM MdE_Preferences WHERE Key=? ORDER BY ExtraValue DESC LIMIT ?)) AND (ObjectId NOT IN(SELECT DISTINCT LeftObjectId FROM Relations%u)) AND (ObjectId NOT IN(SELECT DISTINCT RightObjectId FROM Relations%u))) ORDER BY LastModifiedDate ASC LIMIT ?);" );
+
+	const TInt KMaxLenghtForNamespaceIdsAsText = 4 * KMaxUintValueLength;
+	CMdsClauseBuffer* clause = CMdsClauseBuffer::NewLC( 
+			KMemoryCardCleanup.iTypeLength + KMaxLenghtForNamespaceIdsAsText );
+	
+	clause->BufferL().Format( KMemoryCardCleanup, 
+		KDefaultNamespaceDefId, 
+		KDefaultNamespaceDefId, 
+		KDefaultNamespaceDefId, 
+		KDefaultNamespaceDefId );
+	
+	RRowData variables;
+    CleanupClosePushL( variables );
+
+	_LIT( KMemoryCardKey, "MC" );
+	const TInt KMemoryCardLimit = 1;
+	const TInt KObjectCleanupLimit = 1024;
+	
+	variables.AppendL( TColumn( EMdEObjectFlagNotPresent ) );
+	variables.AppendL( TColumn( KMemoryCardKey ) );
+	variables.AppendL( TColumn( KMemoryCardLimit ) );
+	variables.AppendL( TColumn( KObjectCleanupLimit ) );
+	
+	TInt rowCount = iDefaultDBConnection->ExecuteL( clause->ConstBufferL(), variables );
+
+	CleanupStack::PopAndDestroy( 2, clause ); // variables, clause
+	}
+
+
+void CMdSServer::HandleDiskSpaceError(TInt /*aError*/)
+	{
+	}
+
+
+CMdSServer* CMdSServer::NewL()
+    {
+    CMdSServer* MdSServer = CMdSServer::NewLC();
+    CleanupStack::Pop( MdSServer );
+    return MdSServer;
+    }
+
+
+CMdSServer* CMdSServer::NewLC()
+    {
+    CMdSServer* MdSServer = new ( ELeave ) CMdSServer( CActive::EPriorityStandard );
+    CleanupStack::PushL( MdSServer );
+    MdSServer->ConstructL();
+    return MdSServer;
+    }
+
+
+void CMdSServer::ConstructL()
+    {
+    __INIT_LOGGER;
+    StartL( KMdSServerName );
+    __LOGLB( ELogAlways, "Server start" );
+    
+    CheckInitSriptL();
+    
+    iLockList = CMdSObjectLockList::NewL();
+    CMdSSqLiteConnection* conn = CMdSSqLiteConnection::NewLC();
+    iDefaultDBConnection = conn;
+    MMdSDbConnectionPool::SetDefaultDB( conn );
+
+    CMdSMaintenanceEngine::InitConnectionL();
+    CleanupStack::Pop( conn );
+
+    iNotifier = CMdSNotifier::NewL();
+
+    InitializeL();
+
+    iDiskSpaceGarbageCollectorNotifier = 
+    	CMdSDiskSpaceNotifierAO::NewL( *this, 
+    								   KDiskSpaceGarbageCollectorThreshold,
+    								   KMdsSqlDbDefaultName );
+    
+    iDiskFullNotifier = 
+    	CMdSDiskSpaceNotifierAO::NewL( *this, 
+    									KDiskFullThreshold,
+    									KMdsSqlDbDefaultName );
+
+    // Create a backup & restore watcher and add this server as its observer.								   
+    iBURWatcher = CMdEBackupRestoreWatcherAO::NewL(*this);
+    
+    // create shutdown observer
+    iShutdownObserver = CMDSShutdownObserver::NewL( *this );
+    iShutdown = EFalse;    
+    }
+
+void CMdSServer::InitializeL()
+    {
+    iMaintenance = CMdSMaintenanceEngine::NewL();
+
+    iSchema = CMdsSchema::NewL();
+
+    iManipulate = CMdSManipulationEngine::NewL( *iSchema, *iNotifier, 
+        *iLockList );
+
+    iMaintenance->InstallL( *iManipulate, *iSchema );
+    }
+
+void CMdSServer::DeInitializeL()
+    {
+    if ( iMaintenance )
+    	{
+    	delete iMaintenance;
+    	iMaintenance = NULL;
+    	}
+    if ( iManipulate )
+    	{
+    	delete iManipulate;
+    	iManipulate = NULL;
+    	}
+    if ( iSchema )
+    	{
+    	delete iSchema;
+    	iSchema = NULL;
+    	}
+    }
+
+TInt CMdSServer::ResetDBL()
+	{
+	DeInitializeL();
+
+	CMdSMaintenanceEngine::DeleteDatabase();
+	CMdSMaintenanceEngine::InitConnectionL();
+	
+    InitializeL();
+	return KErrNone;
+	}
+
+CMdSServer::CMdSServer( TInt aPriority ) : 
+	CPolicyServer(aPriority, KMdsPolicy), 
+	iBackupOrRestoreRunning( EFalse ),
+	iHarvestingPrioritizationSerializationBuffer( NULL )
+    {
+    iServerErrorStatus = KErrNone;
+    }
+
+
+CMdSServer::~CMdSServer()
+    {
+    
+    iShutdown = ETrue;
+    
+	delete iBURWatcher;
+	delete iDiskSpaceGarbageCollectorNotifier;
+	delete iDiskFullNotifier;
+    delete iManipulate;
+    delete iSchema;
+    delete iNotifier;
+    delete iLockList;
+    delete iMaintenance;
+    delete iDefaultDBConnection;
+
+    delete iHarvestingPrioritizationSerializationBuffer;
+	iHarvestingPrioritizationChunk.Close();
+	
+	delete iShutdownObserver;
+
+    __LOGLB( ELogAlways, "Server stop" );
+    __DESTROY_LOGGER;
+    }
+
+
+CSession2* CMdSServer::NewSessionL( const TVersion& aVersion, const RMessage2& /*aMessage*/ ) const
+    {
+    // Check we are the right version
+    if ( !User::QueryVersionSupported( TVersion( KMdSServMajorVersionNumber,
+                                                 KMdSServMinorVersionNumber,
+                                                 KMdSServBuildVersionNumber ),
+                                       aVersion ) )
+        {
+        User::Leave( KErrNotSupported );
+        }
+
+	if ( iShutdownObserver->UpdateInProgress() )
+        {
+        __LOGLB( ELogAlways, "CMdSServer::NewSessionL: iad update in progress: KErrLocked");
+        User::Leave(KErrLocked);
+        }
+
+    if ( iServerErrorStatus != KErrNone )
+        {
+        // leave with the same error code that the server has
+        User::Leave ( iServerErrorStatus );
+        }
+
+    __LOGLB( ELogAlways, "New Session" );
+    // Make new session
+    return CMdSServerSession::NewL( *const_cast<CMdSServer*> ( this ) );
+    }
+
+
+void CMdSServer::IncrementSessions()
+    {
+    iSessionCount++;
+    }
+
+
+void CMdSServer::DecrementSessions()
+    {
+    iSessionCount--;
+    if ( iSessionCount <= 0 )
+        {        
+        if (!iShutdown)
+            {
+            CActiveScheduler::Stop();
+            iShutdown = ETrue;
+            }
+        }
+    }
+
+CMdsSchema& CMdSServer::Schema()
+    {
+    return *iSchema;
+    }
+
+CMdSObjectLockList& CMdSServer::LockList()
+    {
+    return *iLockList;
+    }
+
+CMdSNotifier& CMdSServer::Notifier()
+    {
+    return *iNotifier;
+    }
+
+CMdSMaintenanceEngine& CMdSServer::Maintenance()
+    {
+    return *iMaintenance;
+    }
+
+CMdSManipulationEngine& CMdSServer::Manipulate()
+    {
+    return *iManipulate;
+    }
+
+TBool CMdSServer::DiskFull() const
+	{
+	return iDiskFullNotifier->DiskFull();
+	}
+   
+TBool CMdSServer::BackupOrRestoreRunning() const
+	{
+	return iBackupOrRestoreRunning;
+	}
+    
+// -----------------------------------------------------------------------------
+// CMdSServer::ShutdownNotification
+// -----------------------------------------------------------------------------
+//
+void CMdSServer::ShutdownNotification()
+    {
+
+    
+    if (!iShutdown)
+        {    
+        CActiveScheduler::Stop();
+        iShutdown = ETrue;
+        }
+    
+    }
+
+// -----------------------------------------------------------------------------
+// CMdSServer::ShutdownNotification
+// -----------------------------------------------------------------------------
+//
+void CMdSServer::RestartNotification()
+    {
+    }
+
+
+TInt CMdSServer::SetHarvestingPrioritizationChunkL( const RMessagePtr2 aMessage, TInt aParam )
+	{
+	// if there happens to be old chunk, close it
+	iHarvestingPrioritizationChunk.Close();
+
+	TInt error = iHarvestingPrioritizationChunk.Open( aMessage, aParam, EFalse );
+
+	if( error != KErrNone )
+		{
+		return error;
+		}
+
+	if( iHarvestingPrioritizationSerializationBuffer )
+		{
+		delete iHarvestingPrioritizationSerializationBuffer;
+		iHarvestingPrioritizationSerializationBuffer = NULL;
+		}
+
+	iHarvestingPrioritizationSerializationBuffer = 
+		CMdCSerializationBuffer::NewL( 
+			iHarvestingPrioritizationChunk.Base(), 
+			iHarvestingPrioritizationChunk.Size() );
+	
+	iHarvestingPrioritizationLocked = EFalse;
+
+	return KErrNone;
+	}
+
+TInt CMdSServer::AddHarvestingPrioritizationObserver( RMessagePtr2 aMessage )
+	{
+	if( iHarvestingPrioritizationObserver.IsNull() )
+		{
+		iHarvestingPrioritizationLocked = EFalse;
+
+		iHarvestingPrioritizationObserver = aMessage;
+
+		// reserve space for harvesting prioritization URI count
+		iHarvestingPrioritizationLimit = CMdCSerializationBuffer::KRequiredSizeForTInt32;
+		iHarvestingPrioritizationUriCount = 0;
+		
+		return KErrNone;
+		}
+	else
+	    {
+        RThread clientThread;
+        iHarvestingPrioritizationObserver.Client( clientThread );
+        TExitType exitType = clientThread.ExitType();
+        clientThread.Close();
+        if( EExitPending != exitType )
+            {
+            iHarvestingPrioritizationLocked = EFalse;
+
+            iHarvestingPrioritizationObserver = aMessage;
+
+            // reserve space for harvesting prioritization URI count
+            iHarvestingPrioritizationLimit = CMdCSerializationBuffer::KRequiredSizeForTInt32;
+            iHarvestingPrioritizationUriCount = 0;
+        
+            return KErrNone;
+            }
+	    }
+
+	return KErrAlreadyExists;
+	}
+
+TInt CMdSServer::CancelHarvestingPrioritizationObserver()
+	{	
+	iHarvestingPrioritizationLocked = EFalse;
+
+	if( iHarvestingPrioritizationObserver.IsNull() )
+		{
+		return KErrNotFound;
+		}
+	
+	NotifyHarvestingPrioritizationObserver( KErrCancel );
+	return KErrNone;
+	}
+
+TBool CMdSServer::ReserveSpaceHarvestingPrioritizationUri( const TDesC16& aUri )
+	{
+	if( !iHarvestingPrioritizationLocked && 
+		iHarvestingPrioritizationObserver.IsNull() == EFalse && 
+		iHarvestingPrioritizationSerializationBuffer )
+		{
+		// reserve space for URI offset and URI
+		const TInt reserveSpace = 
+			CMdCSerializationBuffer::KRequiredSizeForTUint32 + 
+			CMdCSerializationBuffer::RequiredSize( aUri );
+
+		const TInt maxBufferSize = 
+			iHarvestingPrioritizationSerializationBuffer->Size();
+
+		// check if buffer has enough space for the new URI
+		if( maxBufferSize >= ( iHarvestingPrioritizationLimit + reserveSpace ) )
+			{			
+			iHarvestingPrioritizationLimit += reserveSpace;
+			iHarvestingPrioritizationUriCount++;
+			return ETrue;
+			}
+		// if buffer doesn't have enough space for the new uri, 
+		// discard current URI and all following URIs
+		else
+			{
+			iHarvestingPrioritizationLimit = maxBufferSize;
+			return EFalse;
+			}
+		}
+	return EFalse;
+	}
+
+TBool CMdSServer::StartAddingHarvestingPrioritizationUrisL()
+	{
+	if( !iHarvestingPrioritizationLocked && 
+		iHarvestingPrioritizationObserver.IsNull() == EFalse && 
+		iHarvestingPrioritizationSerializationBuffer )
+		{
+		iHarvestingPrioritizationLocked = ETrue;
+
+		// add URI count to harvesting prioritization buffer
+		iHarvestingPrioritizationSerializationBuffer->PositionL( 0 );
+		iHarvestingPrioritizationSerializationBuffer->InsertL( 
+			iHarvestingPrioritizationUriCount );
+
+		iHarvestingPrioritizationBufferUriCount = 0;
+
+		// set URI offset to position of the first URI
+		iHarvestingPrioritizationBufferUriOffset = 
+			CMdCSerializationBuffer::KRequiredSizeForTInt32 + 
+			CMdCSerializationBuffer::KRequiredSizeForTUint32 * 
+			iHarvestingPrioritizationUriCount;
+
+		return ETrue;
+		}
+
+	return EFalse;
+	}
+
+TBool CMdSServer::AddHarvestingPrioritizationUriL( TDesC16& aUri )
+	{
+	if( iHarvestingPrioritizationObserver.IsNull() == EFalse && 
+		iHarvestingPrioritizationSerializationBuffer )
+		{
+		const TUint32 offset = 
+			CMdCSerializationBuffer::KRequiredSizeForTInt32 + 
+			CMdCSerializationBuffer::KRequiredSizeForTUint32 * 
+			iHarvestingPrioritizationBufferUriCount;
+
+		iHarvestingPrioritizationSerializationBuffer->PositionL( offset );
+		iHarvestingPrioritizationSerializationBuffer->InsertL( 
+			iHarvestingPrioritizationBufferUriOffset );
+
+		// move to URI offset, insert URI and get new URI offset
+		iHarvestingPrioritizationSerializationBuffer->PositionL( 
+			iHarvestingPrioritizationBufferUriOffset );
+		iHarvestingPrioritizationBufferUriOffset = 
+			iHarvestingPrioritizationSerializationBuffer->InsertL( aUri );
+
+		iHarvestingPrioritizationBufferUriCount++;
+		
+		return ETrue;
+		}
+	return EFalse;
+	}
+
+void CMdSServer::NotifyHarvestingPrioritizationObserver( TInt aStatus ) const
+	{
+	if( !iHarvestingPrioritizationObserver.IsNull() )
+		{
+	    RThread clientThread;
+	    iHarvestingPrioritizationObserver.Client( clientThread );
+	    TExitType exitType = clientThread.ExitType();
+	    if( EExitPending == exitType )
+	        {
+	        iHarvestingPrioritizationObserver.Complete( aStatus );
+	        }
+	    clientThread.Close();
+		}
+	}
+
+TInt CMdSServer::RunError( TInt aError )
+    {
+    __LOG1( ELogAlways, "Server::RunError %d", aError );
+
+    if ( aError == KErrBadDescriptor )
+        {
+        // A bad descriptor error implies a badly programmed client,
+        // so panic it; otherwise report the error to the client
+        PanicClient( Message(), KErrBadDescriptor );
+        }
+    else
+        {
+        Message().Complete( aError );
+        }
+
+    // The leave will result in an early return from CServer::RunL(), skipping
+    // the call to request another message. So do that now in order to keep the
+    // server running.
+    ReStart();
+
+    return KErrNone;    // Handled the error fully
+    }
+
+
+
+void CMdSServer::PanicClient( const RMessage2& aMessage, TInt aPanic )
+    {
+    __LOG1( ELogAlways, "Server::PanicClient %d", aPanic );
+    aMessage.Panic( KMetadataEngine, aPanic );
+    }
+
+
+void CMdSServer::PanicServer( TMetadataPanic aPanic )
+    {
+    __LOG1( ELogAlways, "Server::PanicServer %d", aPanic );
+    MMdCCommon::Panic( aPanic );
+    }
+
+void CMdSServer::ThreadFunctionL()
+    {
+    User::LeaveIfError(User::RenameThread(KMdSServerName));
+    // Construct active scheduler
+    CActiveScheduler* activeScheduler = new ( ELeave ) CActiveScheduler;
+    CleanupStack::PushL( activeScheduler );
+
+    // Install active scheduler
+    // We don't need to check whether an active scheduler is already installed
+    // as this is a new thread, so there won't be one
+    CActiveScheduler::Install( activeScheduler );
+
+    // Construct our server
+    CMdSServer::NewLC();    // Anonymous
+
+    RProcess::Rendezvous(KErrNone);
+
+    // Start handling requests
+    CActiveScheduler::Start();
+
+    CleanupStack::PopAndDestroy( 2, activeScheduler ); 
+    }
+
+
+TInt CMdSServer::ThreadFunction( TAny* /*aNone*/ )
+    {
+    CTrapCleanup* cleanupStack = CTrapCleanup::New();
+    if ( !( cleanupStack ) )
+        {
+        PanicServer( ECreateTrapCleanup );
+        }
+
+    TRAPD( err, ThreadFunctionL() );
+    if ( err != KErrNone )
+        {
+        PanicServer( ESrvCreateServer );
+        }
+
+    delete cleanupStack;
+    cleanupStack = NULL;
+
+    return KErrNone;
+    }
+    
+
+// Backup & restore methods
+void CMdSServer::HandleBackup()
+	{
+	iBackupOrRestoreRunning = ETrue;
+	
+	// Free resources for back up.
+	iManipulate->GarbageCollector().Pause();
+	
+	// disconnect all DB connections
+	CMdSMaintenanceEngine::CloseDatabase();
+	}
+
+void CMdSServer::HandleRestore()
+	{
+	iBackupOrRestoreRunning = ETrue;
+
+	// Free resources for restore.
+	iManipulate->GarbageCollector().Pause();
+
+	// disconnect all DB connections
+	CMdSMaintenanceEngine::CloseDatabase();
+	
+	// Currently trust that device will reboot after restore.
+	}
+
+void CMdSServer::ResumeOperation()
+	{
+	iBackupOrRestoreRunning = EFalse;
+
+	// Resume normal operation after back up.
+
+	// restore all DB connections
+	TRAPD( error, CMdSMaintenanceEngine::InitConnectionL() );
+
+	// if setting back DB connections fails 
+	// something very bad has happened during backup or restore
+	if( KErrNone != error )
+		{
+		MMdCCommon::Panic( EServerBackupOrRestore );
+		}
+
+	// Restore resources
+	iManipulate->GarbageCollector().Resume();
+	}
+
+void CMdSServer::CheckInitSriptL()
+    {
+    RFs fs;
+    User::LeaveIfError( fs.Connect() );
+    CleanupClosePushL( fs );
+    
+    RFileReadStream tmpFile;
+    TInt err( KErrNone );
+    TBuf<KMaxFileName> privatePath;
+    TBuf<KMaxFileName> schema;
+    TBuf<KMaxFileName> defaultImportProfile;
+    TBuf<KMaxFileName> backupRegistration;
+    
+    fs.PrivatePath( privatePath );
+    
+    schema.Copy( privatePath );
+    schema.Append( KSchema );
+    
+    defaultImportProfile.Copy( privatePath );
+    defaultImportProfile.Append( KDefaultImportProfile );
+    
+    backupRegistration.Copy( privatePath );
+    backupRegistration.Append( KBackupRegistration );
+    
+    CFileMan* fileMan = CFileMan::NewL( fs );
+    CleanupStack::PushL( fileMan);
+            
+    err = tmpFile.Open( fs, schema, EFileRead | EFileShareAny );
+    __LOG1( ELogAlways, "open schema.mde %d", err );
+    tmpFile.Close();
+    if ( err != KErrNone )
+        {
+        if ( err == KErrNotFound )
+            {
+            // Path found but not schema.mde, copy schema.m
+            const TInt error = fileMan->Copy( KSchemaPath, schema, CFileMan::EOverWrite );
+            __LOG1( ELogAlways, "copy schema.mde %d", error );
+            }
+        else if ( err == KErrPathNotFound)
+            {
+            // Create private dir
+            fs.CreatePrivatePath( EDriveC );
+            
+            // Copy schema.mde
+            const TInt error = fileMan->Copy( KSchemaPath, schema, CFileMan::EOverWrite );
+            __LOG1( ELogAlways, "copy schema.mde %d", error );
+            }    
+        }
+
+    err = tmpFile.Open( fs, defaultImportProfile, EFileRead | EFileShareAny );
+    __LOG1( ELogAlways, "open defaultimportprofile.mde %d", err );
+    tmpFile.Close();
+    if ( err != KErrNone )
+        {
+        if ( err == KErrNotFound )
+            {
+            // Path found but not schema.mde, copy schema.m
+            const TInt error1 = fileMan->Copy( KDefaultImportProfilePath, defaultImportProfile, CFileMan::EOverWrite );
+            __LOG1( ELogAlways, "copy defaultimportprofile.mde %d", error1 );
+            }
+        else if ( err == KErrPathNotFound)
+            {
+            // Create private dir
+            fs.CreatePrivatePath( EDriveC );
+             
+            // Copy schema.mde
+            const TInt error1 = fileMan->Copy( KDefaultImportProfilePath, defaultImportProfile, CFileMan::EOverWrite );
+            __LOG1( ELogAlways, "copy defaultimportprofile.mde %d", error1 );
+            }    
+        }    
+    
+    err = tmpFile.Open( fs, backupRegistration, EFileRead | EFileShareAny );
+    __LOG1( ELogAlways, "open backup_registration.xml %d", err );
+    tmpFile.Close();
+    if ( err != KErrNone )
+        {
+        if ( err == KErrNotFound )
+            {
+            // Path found but not schema.mde, copy schema.m
+            const TInt error2 = fileMan->Copy( KBackupRegistrationPath, backupRegistration, CFileMan::EOverWrite );
+            __LOG1( ELogAlways, "copy backup_registration.xml %d", error2 );
+            }
+        else if ( err == KErrPathNotFound)
+            {
+            // Create private dir
+            fs.CreatePrivatePath( EDriveC );
+            
+            // Copy schema.mde
+            const TInt error2 = fileMan->Copy( KBackupRegistrationPath, backupRegistration, CFileMan::EOverWrite );
+            __LOG1( ELogAlways, "copy backup_registration.xml %d", error2 );
+            }    
+        }   
+
+    CleanupStack::PopAndDestroy( 2 ); //fileman, fs
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+TInt E32Main()
+    {
+    __UHEAP_MARK;
+ 	CTrapCleanup* cleanup=CTrapCleanup::New();
+ 	TInt result = KErrNoMemory;
+ 	if (cleanup)
+ 		{
+ 		TRAP(result, CMdSServer::ThreadFunctionL());
+		delete cleanup;
+ 		}
+    __UHEAP_MARKEND;
+ 	return result;
+    }
+    
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsserversession.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1627 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is Metadata engine server session file
+*
+*/
+
+
+// INCLUDE FILES
+#include "mdsserversession.h"
+
+#include "mdcresult.h"
+#include "mdslogger.h"
+#include "mdcserializationbuffer.h"
+#include "mdsserver.h"
+#include "mdsmanipulationengine.h"
+#include "mdsmaintenanceengine.h"
+#include "mdsfindengine.h"
+#include "mdsobjectlocklist.h"
+#include "mdsnotifier.h"
+#include "mdsschema.h"
+#include "mdcresult.h"
+#include "mdcitem.h"
+
+#include "mdsutils.h"
+
+__USES_LOGGER
+
+
+// ========================= MEMBER FUNCTIONS ==================================
+
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CMdSServerSession* CMdSServerSession::NewL( CMdSServer& aServer )
+    {
+    CMdSServerSession* self = CMdSServerSession::NewLC( aServer );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+CMdSServerSession* CMdSServerSession::NewLC( CMdSServer& aServer )
+    {
+    CMdSServerSession* self = new ( ELeave ) CMdSServerSession( aServer );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::ConstructL()
+    {
+    iServer.IncrementSessions();
+    }
+
+// ---------------------------------------------------------------------------
+// Default constructor
+// ---------------------------------------------------------------------------
+//
+CMdSServerSession::CMdSServerSession( CMdSServer& aServer )
+	: iServer( aServer ) 
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CMdSServerSession::~CMdSServerSession()
+    {
+    iFindEngines.ResetAndDestroy();
+    iFindEngines.Close();
+
+	iServer.LockList().UnlockBySession( *this );
+	iServer.Notifier().RemoveEntriesBySession( *this );
+    iServer.DecrementSessions();
+    
+    // purge any pending notifications
+	iNotificationCache.ResetAndDestroy();
+    iNotificationCache.Close();
+    }
+
+// ---------------------------------------------------------------------------
+// Service the server message 
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::ServiceL( const RMessage2& aMessage )
+    {
+    __LOG2( ELogServer, "ServiceL message: %d uid: %.8x", 
+    		aMessage.Function(),
+    		aMessage.Identity());
+
+	if( iServer.BackupOrRestoreRunning() )
+		{
+		aMessage.Complete( KErrServerBusy );
+		return;
+		}
+
+    TRAPD( err, ServiceFunctionL( aMessage ) );
+    if( err != KErrNone )
+        {
+        aMessage.Complete( err );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// ServiceFunctionL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::ServiceFunctionL( const RMessage2& aMessage )
+    {
+    TInt complete(KErrNone);
+
+    switch ( aMessage.Function() )
+        {
+        // Add items 
+        case EAdd:
+            {
+            AddL( aMessage );
+            break;
+            }
+
+        // Add relation def
+        case EAddRelationDef:
+        	{
+        	AddRelationDefL(aMessage);
+        	iServer.Notifier().NotifySchemaAddedL();
+        	break;
+        	}
+
+        // Add event def
+        case EAddEventDef:
+        	{
+        	AddEventDefL(aMessage);
+        	iServer.Notifier().NotifySchemaAddedL();
+        	break;
+        	}        	
+
+        // Remove items
+        case ERemove:
+            {
+            RemoveL( aMessage );
+            break;
+            }
+
+        // Find items
+        case EFind:
+            {
+            TRAPD( err, FindL( aMessage ) );
+            if ( err != KErrNone )
+                {
+                if ( err != KErrNotReady )
+                    {
+                    FindCancel( aMessage, err );
+                    return;
+                    }
+	            complete = err;
+                }
+            break;
+            }
+
+        case EAsyncFind:
+            {
+            TRAPD( err, FindAsyncL( aMessage ) );
+            if ( err != KErrNone)
+            	{
+            	if(err != KErrNotReady)
+	                {
+	                FindCancel( aMessage, err );
+	                return;
+	                }
+	    		complete = err;
+            	}
+            else 
+            	{
+            	// if no error don't complete message
+            	return;
+            	}
+            break;
+            }
+
+        case EContinueAsyncFind:
+            {
+            TRAPD( err, FindContinueAsyncL( aMessage ) );
+            if ( err != KErrNone )
+                {
+                FindCancel( aMessage, err );
+                }
+            
+            // if no error don't complete message
+            return;
+            }
+
+        case ECancelFind:
+            {
+            FindCancel( aMessage, KErrNone );
+            return;
+            }
+
+        case ECheckObject:
+            {
+            CheckObjectL( aMessage );
+            break;
+            }
+            
+        case EGetData:
+            {
+            GetDataL( aMessage );
+            break;
+            }
+
+        case ECancelObject:
+            {
+            CancelObjectL( aMessage );
+            break;
+            }
+
+        case EUpdate:
+            {
+            UpdateL( aMessage );
+            break;
+            }
+
+        case ERegister:
+            {
+            RegisterL( aMessage );
+            break;
+            }
+
+        case EListen:
+            {
+            ListenL( aMessage );
+            
+            // if no error don't complete message
+            return;
+            }
+
+        case EUnregister:
+            {
+            UnregisterL( aMessage );
+            break;
+            }
+            
+        case EShutdown:
+            {
+            ShutdownL( aMessage );
+            break;
+            }
+            
+        case EImportMetadata:
+        case EAsyncImportMetadata:
+            {
+            ImportMetadataL( aMessage );
+            break;
+            }
+
+        case EExportMetadata:
+        case EAsyncExportMetadata:
+            {
+            ExportMetadataL( aMessage );
+            break;
+            }
+
+        case EImportSchema:
+            {
+            TRAPD( err, ImportSchemaL( aMessage ) );
+            if(err != KErrNone && err != KErrAccessDenied)
+            	{
+            	// Map all other errors to KErrCorrupt
+            	err = KErrCorrupt;
+            	}
+
+            if(!err)
+            	{
+            	iServer.Notifier().NotifySchemaAddedL();
+            	}
+
+			complete = err;
+            break;
+            }
+
+        case EAddMemoryCard:
+        	{
+        	AddMemoryCardL( aMessage );
+        	break;
+        	}
+
+    	case EGetMemoryCard:
+        	{
+        	GetMemoryCardL( aMessage );
+        	break;
+        	}
+
+    	case ECheckMemoryCard:
+        	{
+        	CheckMemoryCardL( aMessage );
+        	break;
+        	}
+
+    	case ESetMedia:
+    		{
+    		SetMediaL( aMessage );
+    		break;
+    		}
+        
+    	case EGetMedia:
+    		{
+    		GetMediaL( aMessage );
+    		break;
+    		}
+        	
+    	case EGetPresentMedias:
+    		{
+    		GetPresentMediasL( aMessage );
+    		break;
+    		}
+        	
+    	case ESetFileToPresent:
+        	{
+        	complete = KErrNotSupported;
+        	break;
+        	}
+
+    	case ESetFilesToPresent:
+        	{
+        	SetFilesToPresentL(aMessage);
+        	break;
+        	}        	
+        	
+    	case ESetFilesToNotPresent:
+        	{
+        	SetFilesToNotPresentL(aMessage);
+        	break;
+        	}
+
+    	case ERemoveFilesNotPresent:
+        	{
+        	RemoveFilesNotPresentL(aMessage);
+        	break;
+        	}
+
+    	case EGetSchemaVersion:
+        	{
+        	GetSchemaVersionL(aMessage);
+        	break;
+        	}
+
+    	case ESetObjectToPresentByGuid:
+    		{
+    		SetObjectToPresentByGuidL(aMessage);
+    		break;
+    		}
+        	
+        case EResetDB:
+        	{
+			#ifdef _DEBUG
+        	iServer.ResetDBL();
+			#else
+        	User::Leave( KErrNotSupported );
+			#endif
+        	break;
+        	}
+        	
+        case ESetHarvestingPrioritizationChunk:
+        	{
+        	iServer.SetHarvestingPrioritizationChunkL( aMessage, 0 );
+        	break;
+        	}
+
+        case EAddHarvestingPrioritizationObserver:
+        	{
+            User::LeaveIfError( iServer.AddHarvestingPrioritizationObserver( aMessage ) );
+            // if no error don't complete message
+        	return;
+        	}
+
+        case ECancelHarvestingPrioritizationObserver:
+        	{
+        	User::LeaveIfError( iServer.CancelHarvestingPrioritizationObserver() );
+        	break;
+        	}
+
+        case EChangePath:
+        	{
+        	ChangePathL( aMessage );
+        	break;
+        	}
+        	
+        case EChangeMediaId:
+        	{
+        	ChangeMediaIdL( aMessage );
+        	break;
+        	}	
+        	
+        case ESetPending:
+        	{
+        	SetPendingL( aMessage );
+        	}
+        	break;
+
+        case EResetPending:
+        	{
+        	ResetPendingL( aMessage );
+        	}
+        	break;
+
+        case EGetPendingCount:
+        	{
+        	complete = GetPendingCountL( aMessage );
+        	}
+        	break;
+
+        case EGetPending:
+        	{
+        	complete = GetPendingL( aMessage );
+        	}
+        	break;
+        	
+        default:
+            iServer.PanicClient( aMessage, EBadRequest );
+        }
+
+    aMessage.Complete(complete);
+    }
+
+// ---------------------------------------------------------------------------
+// QueriesCompleteL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::QueriesCompleteL()
+	{
+	// check if all queries are complete
+    for( TInt i = iFindEngines.Count() - 1; i >= 0; i--)
+    	{
+    	CMdSFindEngine* fe = iFindEngines[i];
+
+    	if( !fe->IsComplete() )
+        	{
+    	    User::Leave( KErrNotReady );
+			}
+    	}		
+	}
+
+// ---------------------------------------------------------------------------
+// AddL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::AddL( const RMessage2& aMsg )
+    {
+	if ( iServer.DiskFull() )
+		{
+		User::Leave( KErrDiskFull );
+		}
+
+	TInt resultLength = aMsg.GetDesLengthL( 1 );
+	CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( aMsg, 0 );	
+	CMdCSerializationBuffer* resultBuf = CMdCSerializationBuffer::NewLC( resultLength );
+
+    iServer.Manipulate().AddL( *buffer, *resultBuf, this );
+
+	aMsg.WriteL(1, resultBuf->Buffer() );
+	CleanupStack::PopAndDestroy( resultBuf );
+	CleanupStack::PopAndDestroy( buffer );
+    }
+
+// ---------------------------------------------------------------------------
+// AddRelationDefL
+// ---------------------------------------------------------------------------
+//	
+void CMdSServerSession::AddRelationDefL(const RMessage2 &aMsg)	
+	{
+	TDefId namespaceId = aMsg.Int0();
+
+	TInt nameLength = aMsg.GetDesLength( EAddDefArgDefName );
+	if ( nameLength < 0 )
+		{
+		User::Leave( KErrBadDescriptor );
+		}
+	HBufC* namebuf = HBufC::NewLC( nameLength );
+	TPtr bufdes = namebuf->Des();
+	aMsg.ReadL( EAddDefArgDefName, bufdes );
+
+	iServer.Manipulate().AddRelationDefL( namespaceId, *namebuf );
+
+	iServer.Schema().SerializeToSharedMemoryL();
+	
+	CleanupStack::PopAndDestroy( namebuf );
+	}
+	
+void CMdSServerSession::AddEventDefL(const RMessage2 &aMsg)	
+	{
+	TDefId namespaceId = aMsg.Int0();
+
+	TInt nameLength = aMsg.GetDesLength( EAddDefArgDefName );
+	if ( nameLength < 0 )
+		{
+		User::Leave( KErrBadDescriptor );
+		}
+	HBufC* namebuf = HBufC::NewLC( nameLength );
+	TPtr bufdes = namebuf->Des();
+	aMsg.ReadL( EAddDefArgDefName, bufdes );
+
+	iServer.Manipulate().AddEventDefL( namespaceId, *namebuf );
+	
+	iServer.Schema().SerializeToSharedMemoryL();
+	
+	CleanupStack::PopAndDestroy( namebuf );
+	}	
+
+// RemoveL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::RemoveL( const RMessage2& aMsg )
+    {
+	TInt successfulLength = aMsg.GetDesLengthL( 1 );
+
+    CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( aMsg, 0 );
+    CMdCSerializationBuffer* successfullBuffer = CMdCSerializationBuffer::NewLC( successfulLength );
+
+    iServer.Manipulate().RemoveL( *buffer, *successfullBuffer );
+    aMsg.WriteL( 1, successfullBuffer->Buffer() );
+    CleanupStack::PopAndDestroy( 2, buffer ); // successfullBuffer, buffer
+    }
+
+// ---------------------------------------------------------------------------
+// FindL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::FindL( const RMessage2& aMsg )
+    {
+    __LOGLB( ELogServer, "-> Find Sync" );
+
+	// check that all queries are complete
+	QueriesCompleteL();
+
+    TInt serializedCriteriaLength = aMsg.GetDesLength( EFindArgConditions );
+	CMdCSerializationBuffer* serializedCriteriaBuffer = CMdCSerializationBuffer::NewLC( serializedCriteriaLength );
+	TPtr8 serializedCriteriaBufferPtr(serializedCriteriaBuffer->Buffer());
+	aMsg.ReadL( EFindArgConditions, serializedCriteriaBufferPtr );
+
+    const TUint32 queryId = (TUint32)aMsg.Int0();
+
+    CMdSFindEngine* find = CMdSFindEngine::NewLC( queryId, *this,
+        iServer.LockList(), iServer.Schema() );
+    find->SetFindCriteria( serializedCriteriaBuffer );
+    find->CreateResultSet( aMsg );
+    find->SetFindParams( (TUint32)aMsg.Int3() );
+
+    CleanupStack::Pop( find );
+    CleanupStack::Pop( serializedCriteriaBuffer );
+    CleanupStack::PushL( find );
+
+    // check clients user level (whether access to confidential data or not)
+    TUserLevel userLevel = EUserLevelNone;
+    userLevel = ( aMsg.HasCapability( ECapabilityReadDeviceData ) ?
+                  EUserLevelDeviceAccess : EUserLevelNormal );
+
+    find->FindL( userLevel );
+
+    CleanupStack::Pop( find );
+    
+    iFindEngines.Append( find );
+    }
+
+// ---------------------------------------------------------------------------
+// FindAsyncL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::FindAsyncL( const RMessage2& aMsg )
+    {
+    __LOGLB( ELogServer, "-> Find Async" );
+
+    // check that all queries are complete
+    QueriesCompleteL();
+
+    TInt serializedCriteriaLength = aMsg.GetDesLength( EFindArgConditions );
+	CMdCSerializationBuffer* serializedCriteriaBuffer = CMdCSerializationBuffer::NewLC( serializedCriteriaLength );
+	TPtr8 serializedCriteriaBufferPtr(serializedCriteriaBuffer->Buffer());
+	aMsg.ReadL( EFindArgConditions, serializedCriteriaBufferPtr );
+
+    const TUint32 queryId = (TUint32)aMsg.Int0();
+
+    CMdSFindEngine* find = CMdSFindEngine::NewLC( queryId, *this,
+        iServer.LockList(), iServer.Schema() );
+    find->SetFindCriteria( serializedCriteriaBuffer );
+    find->CreateResultSet( aMsg );
+    find->SetFindParams( (TUint32)aMsg.Int3() );
+
+    CleanupStack::Pop( find );
+    CleanupStack::Pop( serializedCriteriaBuffer );    
+    CleanupStack::PushL( find );
+
+    // check clients user level (whether access to confidential data or not)
+    TUserLevel userLevel = EUserLevelNone;
+    userLevel = ( aMsg.HasCapability( ECapabilityReadDeviceData ) ?
+                  EUserLevelDeviceAccess : EUserLevelNormal );
+
+    find->FindAsyncL( userLevel );
+
+    CleanupStack::Pop( find );
+    
+    iFindEngines.Append( find );
+    }
+
+// ---------------------------------------------------------------------------
+// FindContinueAsyncL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::FindContinueAsyncL( const RMessage2& aMsg )
+    {
+    __LOGLB( ELogServer, "-> Find Continue" );
+
+    CMdSFindEngine* findEngine = NULL;
+
+    const TUint32 queryId = (TUint32)aMsg.Int0();
+
+    const TInt count = iFindEngines.Count();
+
+    TInt feIndex = 0;
+
+    for( TInt i = 0; i < count; i++ )
+    	{
+    	if( queryId == iFindEngines[i]->QueryId() )
+    		{
+        	findEngine = iFindEngines[i];
+
+    		feIndex = i;
+    		break;
+    		}
+    	}
+
+    // no correct find engine found
+    if( !findEngine )
+    	{
+    	User::Leave( KErrNotFound );
+    	}
+    // find engine is already complete
+    else if( findEngine->IsComplete() )
+    	{
+    	delete findEngine;
+
+    	iFindEngines.Remove( feIndex );
+    	
+    	User::Leave( KErrCompletion );
+    	}
+
+    findEngine->CreateResultSet( aMsg );
+
+    findEngine->ContinueAsync();
+    }
+
+// ---------------------------------------------------------------------------
+// FindCancel
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::FindCancel( const RMessage2& aMsg, TInt aError )
+    {
+    __LOGLB( ELogServer, "-> Find Cancel" );
+    
+    const TUint32 queryId = (TUint32)aMsg.Int0();
+
+    const TInt count = iFindEngines.Count();
+    
+    for( TInt i = 0; i < count; i++ )
+    	{
+    	CMdSFindEngine* findEngine = iFindEngines[i];
+
+    	if( queryId == findEngine->QueryId() )
+    		{
+    		findEngine->Cancel( aError );
+
+    		delete findEngine;
+
+    		iFindEngines.Remove( i );
+
+    		aMsg.Complete( aError );
+    		return;
+    		}
+    	}
+
+    // complete message even if correct find engine wasn't found
+    aMsg.Complete( KErrNotFound );
+    }
+
+// ---------------------------------------------------------------------------
+// CheckObjectL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::CheckObjectL( const RMessage2& aMsg )
+	{	
+	TPckgBuf<TDefId> namespaceDefIdPckg;
+	TInt nsDefIdLength = aMsg.GetDesLengthL( ECheckObjectArgNamespaceDefId );
+	if( nsDefIdLength != sizeof( TDefId ) )
+		{
+		User::Leave( KErrArgument );
+		}	
+	aMsg.Read( ECheckObjectArgNamespaceDefId, namespaceDefIdPckg );
+	const TDefId namespaceDefId = namespaceDefIdPckg();
+
+	const TInt resultBufferLength = aMsg.GetDesLengthL( ECheckObjectArgObject );
+	if( resultBufferLength <= 0 )
+		{
+		User::Leave( KErrBadDescriptor );
+		}
+
+	CMdCSerializationBuffer* buffer = NULL;
+
+	const TInt type = aMsg.Int0();
+	switch( type )
+		{
+		case ECheckObjectByUri:
+			{
+			TInt uriLength = aMsg.GetDesLengthL( ECheckObjectArgTypeValue );
+			if( uriLength <= 0 )
+				{
+				User::Leave( KErrArgument );
+				}
+		    RBuf uri;
+		    uri.Create( uriLength );
+		    CleanupClosePushL( uri );
+		    aMsg.ReadL( ECheckObjectArgTypeValue, uri );
+		    buffer = iServer.Manipulate().CheckObjectL( resultBufferLength, uri, namespaceDefId );
+			CleanupStack::PopAndDestroy( &uri );
+			CleanupStack::PushL( buffer );
+			}
+			break;
+
+		case ECheckObjectById:
+			{
+			TPckgBuf<TItemId> idPckg;
+			TInt idLength = aMsg.GetDesLengthL( ECheckObjectArgTypeValue );
+			if( idLength != sizeof( TItemId ) )
+				{
+				User::Leave( KErrArgument );
+				}
+			aMsg.Read( ECheckObjectArgTypeValue, idPckg );
+			const TItemId id = idPckg();
+			buffer = iServer.Manipulate().CheckObjectL( resultBufferLength, id, namespaceDefId );
+			CleanupStack::PushL( buffer );
+			}
+			break;
+
+		case ECheckObjectByIds:
+			{
+			TInt idLength = aMsg.GetDesLengthL( ECheckObjectArgTypeValue );
+			if( idLength < CMdCSerializationBuffer::KRequiredSizeForTUint32 )
+				{
+				User::Leave( KErrArgument );
+				}
+
+			CMdCSerializationBuffer* ids = CMdCSerializationBuffer::NewLC( idLength );
+			TPtr8 idsPtr( ids->Buffer() );
+			aMsg.ReadL( ECheckObjectArgTypeValue, idsPtr );
+			
+			buffer = iServer.Manipulate().CheckObjectL( resultBufferLength, *ids, namespaceDefId );
+			
+			CleanupStack::PopAndDestroy( ids );
+			
+			CleanupStack::PushL( buffer );
+			}
+			break;
+
+		default:
+			{
+			User::Leave( KErrNotSupported );
+			}
+		}
+
+	aMsg.WriteL( ECheckObjectArgObject, buffer->Buffer() );
+	CleanupStack::PopAndDestroy( buffer );
+	}
+
+// ---------------------------------------------------------------------------
+// GetDataL writes to the client the data from the required operation
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::GetDataL( const RMessage2& aMsg )
+    {
+    TMdEServRqst serverRequest = (TMdEServRqst)aMsg.Int2();
+
+    switch( serverRequest )
+        {
+        case ELoadSchema:
+            {
+            __LOGLB( ELogServer, "-> Get data (Schema)" );
+		    TPckgBuf<TInt> handleBuf( iServer.Schema().SharedMemoryHandleL() );
+    		aMsg.WriteL( 1, handleBuf );
+            }
+            break;
+        case EFind:
+        case EAsyncFindSetReady:
+        case EAsyncFindComplete:
+            {
+            __LOGLB( ELogServer, "-> Get data (Find)" );
+
+            const TUint32 queryId = (TUint32)aMsg.Int0();
+            
+            CMdSFindEngine* findEngine = NULL;
+
+            const TInt count = iFindEngines.Count();
+
+            TInt findEngineIndex;
+            for( findEngineIndex = 0; findEngineIndex < count; findEngineIndex++ )
+            	{
+            	if( queryId == iFindEngines[findEngineIndex]->QueryId() )
+            		{
+            		findEngine = iFindEngines[findEngineIndex];
+            		break;
+            		}
+            	}
+
+            if( !findEngine )
+            	{
+            	User::Leave( KErrNotFound );
+            	}
+
+            TMdCQueryLockType extraData = (TMdCQueryLockType)aMsg.Int3();
+            if (extraData == ELock && aMsg.HasCapability( ECapabilityWriteDeviceData ) )
+            	{
+            	findEngine->LockFindResultObjectsL( iServer.LockList() );
+            	}
+
+            // write result to client's result buffer
+            aMsg.WriteL( 1, findEngine->ResultsL().Buffer() );
+
+            if ( serverRequest != EAsyncFindSetReady )
+                {
+                delete findEngine;
+                
+                iFindEngines.Remove( findEngineIndex );
+                }
+            }
+            break;
+        case EListen:
+            {
+            __LOGLB( ELogServer, "-> Get data (Listen)" );
+            CMdSNotifier::TEntry& entry = iServer.Notifier().FindEntryL( aMsg.Int3() );
+            CMdCSerializationBuffer* buffer = entry.GetDataBuffer();
+        	CleanupStack::PushL( buffer );
+        	aMsg.WriteL( 1, buffer->Buffer() );
+        	CleanupStack::PopAndDestroy( buffer );
+            }
+            break;
+        default:
+            User::Leave( KErrNotSupported );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CancelObjectL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::CancelObjectL( const RMessage2& aMsg )
+    {
+    CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( aMsg, 0 );
+
+    const TMdCItemIds& itemIds = TMdCItemIds::GetFromBufferL( *buffer );
+    if ( itemIds.iObjectIds.iPtr.iCount != 1 )
+    	{
+    	User::Leave( KErrArgument );
+    	}
+	TItemId idValue;
+	buffer->PositionL( itemIds.iObjectIds.iPtr.iOffset );
+	buffer->ReceiveL( idValue );
+
+	CMdsSchema& schema = iServer.Schema();
+	const CMdsNamespaceDef* namespaceDef = schema.GetNamespaceByIdL( itemIds.iNamespaceDefId );
+
+	if (iServer.LockList().IsLocked( *namespaceDef, idValue ) )
+		{
+		iServer.LockList().UnlockById( *namespaceDef, idValue );
+		}
+	else
+		{
+		idValue = KNoId;
+		}
+
+	buffer->PositionL( itemIds.iObjectIds.iPtr.iOffset );
+	buffer->InsertL( idValue );
+
+    aMsg.WriteL( 0, buffer->Buffer() );
+    CleanupStack::PopAndDestroy( buffer ); // buffer
+    }
+
+// ---------------------------------------------------------------------------
+// UpdateL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::UpdateL( const RMessage2& aMsg )
+    {
+    TInt successfulLength = aMsg.GetDesLengthL( 1 );
+    
+    CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( aMsg, 0 );
+    CMdCSerializationBuffer* successfullBuffer = CMdCSerializationBuffer::NewLC( successfulLength );
+
+    iServer.Manipulate().UpdateL( *buffer, *successfullBuffer );
+    aMsg.WriteL( 1, successfullBuffer->Buffer() );
+    CleanupStack::PopAndDestroy( 2, buffer ); // successfullBuffer, buffer
+    }
+    
+// ---------------------------------------------------------------------------
+// RegisterL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::RegisterL( const RMessage2& aMsg )
+    {
+    __LOG3( ELogServer, "-> Register %u for NS: %u Type: %d",
+        (TUint32)aMsg.Int0(), (TDefId)aMsg.Int3(), aMsg.Int1() );
+
+    TInt length = aMsg.GetDesLength( 2 );
+	CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( length );
+	TPtr8 bufferPtr( buffer->Buffer() );
+	aMsg.ReadL( 2, bufferPtr );
+    
+    iServer.Notifier().CreateEntryL( aMsg.Int0(),
+        (TConditionType)aMsg.Int1(), buffer, (TDefId)aMsg.Int3(), *this, 
+        aMsg.HasCapability(ECapabilityReadDeviceData) );
+    
+    CleanupStack::Pop( buffer );                
+    }
+
+// ---------------------------------------------------------------------------
+// ListenL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::ListenL( const RMessage2& aMsg )
+    {
+    const TInt notifierId = aMsg.Int0();
+    __LOG1( ELogServer, "-> Listen %d", notifierId );
+
+    CMdSNotifier::TEntry& entry = iServer.Notifier().FindEntryL( notifierId );
+    entry.SetupForCallback( aMsg, 1 );
+    
+	const TInt count = iNotificationCache.Count();
+	for( TInt i = 0; i < count; ++i )
+		{
+		const TInt notificationCacheId = iNotificationCache[i]->iId;
+		const TInt entryId = entry.Id();
+
+		if( notificationCacheId == entryId )
+			{
+			// The cache holds a new notification for this notifier, trigger it
+			CNotificationCacheItem* item = iNotificationCache[i];
+			iNotificationCache.Remove(i);
+
+			CleanupStack::PushL( item );
+
+			entry.TriggerCachedL( item->iCode, item->iData );
+			
+			// take ownership of iData from item and delete it
+			item->iData = NULL;
+			CleanupStack::PopAndDestroy( item );
+			
+			return;
+			}
+		}
+    }
+
+// ---------------------------------------------------------------------------
+// UnregisterL 
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::UnregisterL( const RMessage2& aMsg )
+    {
+    __LOG1( ELogServer, "-> Unregister %d", aMsg.Int0() );
+    TInt id = aMsg.Int0();
+    iServer.Notifier().RemoveEntryL(id);
+	TInt count = iNotificationCache.Count();
+	for(TInt i(count - 1); i >= 0; --i)
+		{
+		if(iNotificationCache[i]->iId == id)
+			{
+			delete iNotificationCache[i]->iData;
+			iNotificationCache[i]->iData = NULL;
+			iNotificationCache.Remove(i);
+			}
+		}
+    }
+
+// ---------------------------------------------------------------------------
+// CacheNotificationL caches a notifier event
+// ---------------------------------------------------------------------------
+//
+
+CMdCSerializationBuffer* CMdSServerSession::CombineBuffersL(CMdCSerializationBuffer& aLeftBuffer,
+		CMdCSerializationBuffer& aRightBuffer )
+	{
+	// IDs are always stored in object IDs, 
+	// even if those are actually relation or event IDs	
+	
+	aLeftBuffer.PositionL( KNoOffset );
+	aRightBuffer.PositionL( KNoOffset );
+
+	const TMdCItemIds& leftItemIds = TMdCItemIds::GetFromBufferL( aLeftBuffer );
+	const TMdCItemIds& rightItemIds = TMdCItemIds::GetFromBufferL( aRightBuffer );
+
+	// check that namespaces match
+	if ( leftItemIds.iNamespaceDefId != rightItemIds.iNamespaceDefId )
+		{
+		return NULL;
+		}
+
+	// create new buffer, which will contain combined results
+	const TInt leftBufferSize = aLeftBuffer.Size();
+	const TInt rightBufferSize = aRightBuffer.Size();
+	CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( 
+			leftBufferSize + rightBufferSize );
+
+	TMdCItemIds combinedItemIds;
+	
+	// use left buffer's data as base line
+	Mem::Copy( &combinedItemIds, &leftItemIds, sizeof( TMdCItemIds ) );
+	
+	// and add right buffer's relation count
+	combinedItemIds.iObjectIds.iPtr.iCount += rightItemIds.iObjectIds.iPtr.iCount;
+
+	combinedItemIds.SerializeL( *buffer );
+
+	// move left and right buffer to begin of relations
+	aLeftBuffer.PositionL( leftItemIds.iObjectIds.iPtr.iOffset );
+	aRightBuffer.PositionL( rightItemIds.iObjectIds.iPtr.iOffset );
+
+	// copy IDs from left and right buffers to combined buffer
+	for (TInt i = 0; i < leftItemIds.iObjectIds.iPtr.iCount; ++i)
+		{
+		TItemId id;
+		aLeftBuffer.ReceiveL( id );
+		buffer->InsertL( id );		
+		}
+
+	for (TInt i = 0; i < rightItemIds.iObjectIds.iPtr.iCount; ++i)
+		{
+		TItemId id;
+		aRightBuffer.ReceiveL( id );
+		buffer->InsertL( id );		
+		}
+	
+	CleanupStack::Pop( buffer );
+	return buffer;
+	}
+
+CMdCSerializationBuffer* CMdSServerSession::CombineItemBuffersL( CMdCSerializationBuffer& aLeftBuffer,
+		CMdCSerializationBuffer& aRightBuffer )
+	{
+	// Current implementation supports only combining relations 
+	// (used in remove relation item observer case)
+
+	aLeftBuffer.PositionL( KNoOffset );
+	aRightBuffer.PositionL( KNoOffset );
+
+	const TMdCItems& leftItems = TMdCItems::GetFromBufferL( aLeftBuffer );
+	const TMdCItems& rightItems = TMdCItems::GetFromBufferL( aRightBuffer );
+
+	// check that namespaces match
+	if ( leftItems.iNamespaceDefId != rightItems.iNamespaceDefId )
+		{
+		return NULL;
+		}
+
+	// create new buffer, which will contain combined results
+	const TInt leftBufferSize = aLeftBuffer.Size();
+	const TInt rightBufferSize = aRightBuffer.Size();
+	CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC(
+			leftBufferSize + rightBufferSize );
+
+	TMdCItems combinedItems;
+
+	// use left buffer's data as base line
+	Mem::Copy( &combinedItems, &leftItems, sizeof( TMdCItems ) );
+
+	// and add right buffer's relation count
+	combinedItems.iRelations.iPtr.iCount += rightItems.iRelations.iPtr.iCount;
+
+	combinedItems.SerializeL( *buffer );
+
+	// move left and right buffer to begin of relations
+	aLeftBuffer.PositionL( leftItems.iRelations.iPtr.iOffset );
+	aRightBuffer.PositionL( rightItems.iRelations.iPtr.iOffset );
+
+	// copy relations from left and right buffers to combined buffer
+	for ( TUint32 i = 0; i < leftItems.iRelations.iPtr.iCount; ++i )
+		{
+		TMdCRelation& leftRelation = CONST_CAST( TMdCRelation&, 
+				TMdCRelation::GetFromBufferL( aLeftBuffer ) );
+		
+		leftRelation.SerializeL( *buffer );
+		}
+
+	for ( TUint32 i = 0; i < rightItems.iRelations.iPtr.iCount; ++i )
+		{
+		TMdCRelation& rightRelation = CONST_CAST( TMdCRelation&, 
+				TMdCRelation::GetFromBufferL( aRightBuffer ) );
+		
+		rightRelation.SerializeL( *buffer );
+		}
+
+	CleanupStack::Pop( buffer );
+	return buffer;
+	}
+
+
+// ---------------------------------------------------------------------------
+// CacheNotificationL caches a notifier event
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::CacheNotificationL(TInt aId, TUint32 aCompleteCode, CMdCSerializationBuffer* aData)
+	{
+	CleanupStack::PushL( aData );
+
+	const TInt notificationCount = iNotificationCache.Count();
+
+	const TInt KMaxCachedItems = 256;
+
+	if(notificationCount > KMaxCachedItems)
+		{
+		User::Leave( KErrOverflow );
+		}
+
+	if( aData )
+		{
+		// search for matching notification and combine new results to it
+		for (TInt i = 0; i < notificationCount; ++i)
+			{
+			CNotificationCacheItem& notificationItem = *iNotificationCache[i];
+			if ( notificationItem.iId == aId && notificationItem.iCode == aCompleteCode )
+				{
+				CMdCSerializationBuffer* data = NULL;
+				// combine buffers
+				if ( notificationItem.iCode != ERelationItemNotifyRemove )
+					{
+					data = CombineBuffersL( *notificationItem.iData, *aData );
+					}
+				else
+					{
+					data = CombineItemBuffersL( *notificationItem.iData, *aData );
+					}
+				// delete unecessary ones and change iData to new data
+				if (data)
+					{
+					CleanupStack::PopAndDestroy( aData );
+					
+					delete notificationItem.iData;
+					notificationItem.iData = data;
+					return;
+					}
+				}
+			}
+		}
+
+	// change ownership of aData to item
+	CNotificationCacheItem* item = 
+		new (ELeave) CNotificationCacheItem( aId, aCompleteCode, aData );
+	CleanupStack::Pop( aData );
+	CleanupStack::PushL( item );
+
+	iNotificationCache.AppendL( item );
+
+	CleanupStack::Pop( item );
+	}
+	
+CMdSServer& CMdSServerSession::GetServer() const
+	{
+	return iServer;
+	}
+
+// ---------------------------------------------------------------------------
+// ShutdownL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::ShutdownL( const RMessage2& /*aMsg*/ )
+    {
+    __LOGLB( ELogServer, "-> Shutdown session" );
+    
+    const TInt count = iFindEngines.Count();
+    
+    for( TInt i = 0; i < count; i++ )
+        {
+        CMdSFindEngine* fe = iFindEngines[i];
+        
+        fe->Cancel( KErrNone );
+        }
+    iFindEngines.ResetAndDestroy();
+    iFindEngines.Close();
+    }
+
+// ---------------------------------------------------------------------------
+// SizeToRemoteL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::SizeToRemoteL( const RMessage2& aMsg,
+    TInt aMessageSlot, TInt aSize)
+    {
+    __LOGLB( ELogServer, "-> Size to remote" );
+    TPckgBuf<TInt> sizeBuf( aSize );
+    aMsg.WriteL( aMessageSlot, sizeBuf );
+    }
+
+// ---------------------------------------------------------------------------
+// ImportSchemaL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::ImportSchemaL( const RMessage2& aMsg )
+    {
+    __LOGLB( ELogServer, "-> Import schema" );
+
+    const TInt fileNameLength = aMsg.GetDesLength( 0 );
+    if ( fileNameLength <= 0 )
+    	{
+    	User::Leave( KErrBadDescriptor );
+    	}
+
+    RBuf fileName;
+    fileName.Create( fileNameLength );
+    CleanupClosePushL( fileName );
+    aMsg.ReadL( 0, fileName );
+
+    TVendorId id = aMsg.VendorId();
+    iServer.Maintenance().ImportSchemaL( iServer.Schema(), fileName, id.iId );
+    CleanupStack::PopAndDestroy( &fileName );
+    }
+
+// ---------------------------------------------------------------------------
+// ImportMetadataL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::ImportMetadataL( const RMessage2& aMsg )
+    {
+    __LOGLB( ELogServer, "-> Import (async?) metadata" );
+    
+    const TInt fileNameLength = aMsg.GetDesLength( 0 );
+    if ( fileNameLength <= 0 )
+    	{
+    	User::Leave( KErrBadDescriptor );
+    	}
+    
+    RBuf fileName;
+    fileName.Create( fileNameLength );
+    CleanupClosePushL( fileName );
+    aMsg.ReadL( 0, fileName );
+
+    // if result is negative then result is error code
+    // else result is item import fail count
+    TInt result = iServer.Maintenance().ImportMetadataL( 
+    		iServer.Manipulate(), iServer.Schema(), fileName );
+
+    CleanupStack::PopAndDestroy( &fileName );
+
+    TPckgBuf<TInt> failBuf( result );
+    aMsg.WriteL( 1, failBuf );
+    }
+    
+// ---------------------------------------------------------------------------
+// ExportMetadataL
+// ---------------------------------------------------------------------------
+//
+void CMdSServerSession::ExportMetadataL( const RMessage2& aMsg )
+    {
+    const TInt fileNameLength = aMsg.GetDesLength( 0 );
+    if ( fileNameLength <= 0 )
+    	{
+    	User::Leave( KErrBadDescriptor );
+    	}
+
+    RBuf fileName;
+    fileName.Create( fileNameLength );
+    CleanupClosePushL( fileName );
+    aMsg.ReadL( 0, fileName );
+
+    CMdCSerializationBuffer* items = CMdCSerializationBuffer::NewLC( aMsg, 1 );
+
+    iServer.Maintenance().ExportMetadataL( iServer.Schema(), fileName, *items );
+
+    CleanupStack::PopAndDestroy( 2, &fileName ); // items, fileName
+    }
+
+void CMdSServerSession::AddMemoryCardL(const RMessage2& aMessage)
+	{
+	TUint32 mediaId;
+    TPckg<TUint32> mediaIdPckg( mediaId );
+	aMessage.ReadL( 0, mediaIdPckg );
+
+	iServer.Manipulate().AddMemoryCardL( mediaId );
+	}
+
+void CMdSServerSession::GetMemoryCardL(const RMessage2& aMessage)
+	{
+	TUint32 mediaId;
+
+	iServer.Manipulate().GetMemoryCardL( mediaId );
+
+    TPckg<TUint32> mediaIdPckg( mediaId );
+    aMessage.WriteL( 0, mediaIdPckg );
+	}
+
+void CMdSServerSession::CheckMemoryCardL(const RMessage2& aMessage)
+	{
+	TUint32 mediaId;
+    TPckg<TUint32> mediaIdPckg( mediaId );
+	aMessage.ReadL( 0, mediaIdPckg );
+
+	TBool result = iServer.Manipulate().CheckMemoryCardL( mediaId );
+
+    TPckg<TBool> resultPckg( result );
+    aMessage.WriteL( 1, resultPckg );
+	}
+
+void CMdSServerSession::SetMediaL(const RMessage2& aMessage)
+	{
+	TUint32 mediaId;
+    TPckg<TUint32> mediaIdPckg( mediaId );
+    aMessage.ReadL( 0, mediaIdPckg );
+    TChar drive;
+    TPckg<TChar> drivePckg( drive );
+    aMessage.ReadL( 1, drivePckg );
+    TBool presentState;
+    TPckg<TBool> presentStatePckg( presentState );
+    aMessage.ReadL( 2, presentStatePckg );
+
+	iServer.Manipulate().SetMediaL( mediaId, drive, presentState );
+	}
+
+void CMdSServerSession::GetMediaL(const RMessage2& aMessage)
+	{
+	TUint32 mediaId;
+    TPckg<TUint32> mediaIdPckg( mediaId );
+    aMessage.ReadL( 0, mediaIdPckg );
+
+    TChar drive;
+    TBool presentState;
+
+    const TBool exists = iServer.Manipulate().GetMediaL( mediaId, drive, 
+    		presentState );
+
+    if( exists )
+    	{
+    	TPckg<TChar> drivePckg( drive );
+    	aMessage.WriteL( 1, drivePckg );
+    	TPckg<TBool> presentStatePckg( presentState );
+    	aMessage.WriteL( 2, presentStatePckg );
+    	}
+
+    TPckg<TBool> existsPckg( exists );
+    aMessage.WriteL( 3, existsPckg );
+    }
+
+void CMdSServerSession::GetPresentMediasL(const RMessage2& aMessage)
+	{
+	// buffer size for media info for every possible drive
+	const TInt32 KMediaInfoSize = sizeof( TMdEMediaInfo ) * KMaxDrives;
+
+	RBuf8 mediaInfoBuffer;
+	mediaInfoBuffer.Create( KMediaInfoSize );
+	CleanupClosePushL( mediaInfoBuffer );
+
+	const TInt32 mediaCount = iServer.Manipulate().GetPresentMediasL( 
+			mediaInfoBuffer );
+
+	TPckgC<TInt32> mediaCountPckg( mediaCount );
+	aMessage.WriteL( 0, mediaCountPckg );
+
+	if( mediaCount > 0)
+		{
+		const TInt32 mediaInfosLength = aMessage.GetDesMaxLength( 1 );
+		if ( mediaInfosLength < KMediaInfoSize )
+			{
+			User::Leave( KErrBadDescriptor );
+			}
+		
+		aMessage.WriteL( 1, mediaInfoBuffer );
+		}
+
+	CleanupStack::PopAndDestroy(); //mediaInfoBuffer
+	}
+
+void CMdSServerSession::SetFilesToPresentL(const RMessage2& aMessage)
+	{
+	TMdSMediaIdAndCount mediaIdAndCount;
+	TPckg<TMdSMediaIdAndCount> mediaIdAndCountPckg( mediaIdAndCount );
+	aMessage.Read( 0, mediaIdAndCountPckg );
+	
+	CMdCSerializationBuffer* uris = CMdCSerializationBuffer::NewLC( aMessage, 1 );
+	CMdCSerializationBuffer* fileInfos = CMdCSerializationBuffer::NewLC( aMessage, 2 );
+
+	TInt resultsSize = aMessage.GetDesMaxLengthL( 3 );
+	if( resultsSize < ( mediaIdAndCount.iCount * CMdCSerializationBuffer::KRequiredSizeForTUint8 ) )
+		{
+		User::Leave( KErrBadDescriptor );
+		}
+	CMdCSerializationBuffer* results = CMdCSerializationBuffer::NewLC( resultsSize );
+
+	iServer.Manipulate().SetFilesToPresentL( 
+			mediaIdAndCount.iMediaId, mediaIdAndCount.iCount, *uris, *fileInfos, 
+			*results );
+
+	aMessage.WriteL( 3, results->Buffer() );
+
+	CleanupStack::PopAndDestroy( results );
+	CleanupStack::PopAndDestroy( fileInfos );
+	CleanupStack::PopAndDestroy( uris );
+	}
+
+
+void CMdSServerSession::SetFilesToNotPresentL(const RMessage2& aMessage)
+	{
+	TUint32 mediaId;
+    TPckg<TUint32> mediaIdPckg( mediaId );
+	aMessage.Read( 0, mediaIdPckg );
+	
+	TBool startUp;
+    TPckg<TBool> startUpPckg( startUp );
+	aMessage.Read( 1, startUpPckg );
+	
+	// only accept correct media IDs, other are silently ignored
+	if( mediaId != 0 )
+		{
+		iServer.Manipulate().SetFilesToNotPresentL( mediaId, startUp );		
+		}
+	}
+
+void CMdSServerSession::RemoveFilesNotPresentL(const RMessage2& aMessage)
+	{
+	TUint32 mediaId;
+    TPckg<TUint32> mediaIdPckg( mediaId );
+	aMessage.Read( 0, mediaIdPckg );
+	
+	TBool startUp;
+    TPckg<TBool> startUpPckg( startUp );
+	aMessage.Read( 1, startUpPckg );
+
+	iServer.Manipulate().RemoveFilesNotPresentL( mediaId, startUp );
+	}
+
+void CMdSServerSession::GetSchemaVersionL(const RMessage2& aMessage)
+	{
+	TInt majorVersion, minorVersion;
+
+	iServer.Manipulate().GetSchemaVersionL( majorVersion, minorVersion );
+
+	TPckg<TInt> pckgMajorVersion( majorVersion );
+	TPckg<TInt> pckgMinorVersion( minorVersion );
+	aMessage.WriteL( 0, pckgMajorVersion );
+	aMessage.WriteL( 1, pckgMinorVersion );
+	}
+
+void CMdSServerSession::SetObjectToPresentByGuidL(const RMessage2& aMessage)
+	{
+	TInt64 guidHigh;
+    TPckg<TInt64> guidHighPckg( guidHigh );
+	aMessage.ReadL( ESetObjectToPresentByGuidArgGuidHigh, guidHighPckg );
+	
+	TInt64 guidLow;
+    TPckg<TInt64> guidLowPckg( guidLow );
+	aMessage.ReadL( ESetObjectToPresentByGuidArgGuidLow, guidLowPckg );
+	
+	iServer.Manipulate().SetObjectToPresentByGuidL( guidHigh, guidLow );
+	}
+
+void CMdSServerSession::ChangePathL(const RMessage2& aMessage)
+	{
+	const TInt oldPathLength = aMessage.GetDesLength( 0 );
+	if ( oldPathLength <= 0 )
+		{
+		User::Leave( KErrBadDescriptor );
+		}
+
+	const TInt newPathLength = aMessage.GetDesLength( 1 );
+	if ( newPathLength <= 0 )
+		{
+		User::Leave( KErrBadDescriptor );
+		}
+
+	RBuf oldPath;
+	oldPath.Create( oldPathLength );
+    CleanupClosePushL( oldPath );
+    aMessage.ReadL( 0, oldPath );
+
+    RBuf newPath;
+    newPath.Create( newPathLength );
+    CleanupClosePushL( newPath );
+    aMessage.ReadL( 1, newPath );
+    
+    iServer.Manipulate().ChangePathL( oldPath, newPath );
+    
+    CleanupStack::PopAndDestroy(&newPath);
+    CleanupStack::PopAndDestroy(&oldPath);
+	}
+
+void CMdSServerSession::ChangeMediaIdL( const RMessage2& /*aMessage*/ )
+	{
+	iServer.Manipulate().ChangeMediaIdL();
+	}
+
+void CMdSServerSession::SetPendingL(const RMessage2& aMessage)
+	{
+	const TInt serializedObjectIdsLength = aMessage.GetDesLength( 0 );
+	
+	if ( serializedObjectIdsLength < 0 || serializedObjectIdsLength % sizeof( TItemId ) )
+		{
+		User::Leave( KErrBadDescriptor );
+		}
+
+	if( serializedObjectIdsLength > 0 )
+		{
+		RArray<TItemId> objectIds;
+		CleanupClosePushL( objectIds );
+	
+		HBufC8* serializedObjectIds = HBufC8::NewLC( serializedObjectIdsLength );
+	
+		TPtr8 ptr = serializedObjectIds->Des();
+		aMessage.ReadL( 0, ptr );
+	
+		DeserializeArrayL( *serializedObjectIds, objectIds );
+	
+		iServer.Manipulate().SetPendingL( objectIds );
+		
+		CleanupStack::PopAndDestroy( serializedObjectIds );
+	
+		CleanupStack::PopAndDestroy( &objectIds );
+		}
+	}
+
+void CMdSServerSession::ResetPendingL(const RMessage2& aMessage)
+	{
+	const TInt serializedObjectIdsLength = aMessage.GetDesLength( 0 );
+	
+	if ( serializedObjectIdsLength < 0 || serializedObjectIdsLength % sizeof( TItemId ) )
+		{
+		User::Leave( KErrBadDescriptor );
+		}
+	
+	if( serializedObjectIdsLength > 0 )
+		{
+		RArray<TItemId> objectIds;
+		CleanupClosePushL( objectIds );
+		
+		HBufC8* serializedObjectIds = HBufC8::NewLC( serializedObjectIdsLength );
+		
+		TPtr8 ptr = serializedObjectIds->Des();
+		aMessage.ReadL( 0, ptr );
+
+		DeserializeArrayL( *serializedObjectIds, objectIds );
+		
+		iServer.Manipulate().ResetPendingL( objectIds );
+		
+		CleanupStack::PopAndDestroy( serializedObjectIds );
+		
+		CleanupStack::PopAndDestroy( &objectIds );
+		}
+	}
+
+TInt CMdSServerSession::GetPendingCountL(const RMessage2& aMessage)
+	{
+	TDefId objectDefId;
+	TPckg<TDefId> objectDefIdPckg( objectDefId );
+	aMessage.ReadL( 0, objectDefIdPckg );
+	
+	TInt result = iServer.Manipulate().GetPendingCountL( objectDefId );
+
+	TPckg<TInt> objectIdCountPckg( result );
+	aMessage.WriteL( 1, objectIdCountPckg );
+	
+	return KErrNone;
+	}
+
+TInt CMdSServerSession::GetPendingL(const RMessage2& aMessage)
+	{
+	TDefId objectDefId;
+	TPckg<TDefId> objectDefIdPckg( objectDefId );
+	aMessage.ReadL( 0, objectDefIdPckg );
+
+	const TInt serializedObjectIdsLength = aMessage.GetDesLength( 2 );
+
+	if ( serializedObjectIdsLength < sizeof(TItemId) || 
+		 serializedObjectIdsLength % sizeof(TItemId) )
+		{
+		User::Leave( KErrBadDescriptor );
+		}
+
+	RArray<TItemId> objectIds;
+	CleanupClosePushL( objectIds );
+
+	TInt bufferSize = serializedObjectIdsLength / sizeof(TItemId);
+
+	TInt result = iServer.Manipulate().GetPendingL( objectDefId, bufferSize, objectIds );
+
+	const TInt objectIdCount = objectIds.Count();
+
+	TPckg<TInt> resultPckg( result );
+	aMessage.WriteL( 3, resultPckg );
+	
+	TPckg<TInt> objectIdCountPckg( objectIdCount );
+	aMessage.WriteL( 1, objectIdCountPckg );
+
+	if( objectIdCount > 0 )
+		{
+		HBufC8* serializedObjectIds = SerializeArrayL( objectIds );
+		CleanupStack::PushL( serializedObjectIds );
+
+		aMessage.WriteL( 2, serializedObjectIds->Des() );
+
+		CleanupStack::PopAndDestroy( serializedObjectIds );
+		}
+
+	CleanupStack::PopAndDestroy( &objectIds );
+
+	return KErrNone;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdsshutdownobserver.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,146 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#include <e32base.h>
+
+#include "mdsshutdownobserver.h"
+#include "mdscommoninternal.h"
+
+// Print macro
+#ifdef _DEBUG
+#include <e32svr.h>
+#define PRINT(x) RDebug::Print x
+#else
+#define PRINT(x)
+#endif
+
+// ---------------------------------------------------------------------------
+// CMDSShutdownObserver::NewL()
+// ---------------------------------------------------------------------------
+//
+CMDSShutdownObserver* CMDSShutdownObserver::NewL( MMDSShutdownObserver& aObserver/*, const TUid& aKeyCategory */)
+    { 
+    CMDSShutdownObserver* self = new( ELeave )CMDSShutdownObserver( aObserver/*, aKeyCategory */);
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CMDSShutdownObserver::CMDSShutdownObserver()
+// ---------------------------------------------------------------------------
+//
+CMDSShutdownObserver::CMDSShutdownObserver( MMDSShutdownObserver& aObserver/*, const TUid& aKeyCategory */)
+    : CActive( CActive::EPriorityUserInput ), iObserver( aObserver ), iValue( KErrNone )/*, iKeyCategory( aKeyCategory )*/
+    {       
+    }
+
+// ---------------------------------------------------------------------------
+// CMDSShutdownObserver::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CMDSShutdownObserver::ConstructL()
+    {
+#ifdef _DEBUG
+    PRINT(_L("CMDSShutdownObserver::ConstructL()"));
+#endif
+    
+    // attach to the property    
+    User::LeaveIfError( iProperty.Attach(KMdSPSShutdown,KShutdown,EOwnerThread) );
+    
+    CActiveScheduler::Add( this );
+    
+    // wait for the previously attached property to be updated
+    iProperty.Subscribe(iStatus);        
+    
+    SetActive();
+
+#ifdef _DEBUG
+    PRINT(_L("CMDSShutdownObserver::ConstructL() end"));
+#endif
+    }
+
+// ---------------------------------------------------------------------------
+// CMDSShutdownObserver::~CMDSShutdownObserver()
+// ---------------------------------------------------------------------------
+//
+CMDSShutdownObserver::~CMDSShutdownObserver()
+    {
+#ifdef _DEBUG
+    PRINT(_L("CMDSShutdownObserver::~CMDSShutdownObserver()"));
+#endif
+    Cancel();
+    iProperty.Close();
+#ifdef _DEBUG
+    PRINT(_L("CMDSShutdownObserver::~CMDSShutdownObserver() end"));
+#endif
+    }
+
+// ---------------------------------------------------------------------------
+// CMDSShutdownObserver::RunL()
+// ---------------------------------------------------------------------------
+//
+void CMDSShutdownObserver::RunL()
+    {
+    // resubscribe before processing new value to prevent missing updates
+    iProperty.Subscribe(iStatus);
+    SetActive();
+    
+    // retrieve the Uid of the package going to be updated
+    TInt value = 0;
+    const TInt err = iProperty.Get(value);
+    User::LeaveIfError(err);
+
+	iValue = value;
+
+    // observer callback
+    if (value)
+        {
+        iObserver.ShutdownNotification();
+        }
+    else
+        {
+        iObserver.RestartNotification();
+        }
+    }
+
+TInt CMDSShutdownObserver::RunError( TInt /*aError*/ )
+    {
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// CMDSShutdownObserver::DoCancel()
+// ---------------------------------------------------------------------------
+//
+void CMDSShutdownObserver::DoCancel()
+    {
+    iProperty.Cancel();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CMDSShutdownObserver::UpdateInProgress()
+// ---------------------------------------------------------------------------
+//
+TBool CMDSShutdownObserver::UpdateInProgress()
+    {
+    return iValue > 0 ? ETrue : EFalse;
+    }
+	
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdssqldbmaintenance.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,91 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  SQL database startup routines*
+*/
+
+// INCLUDE FILES
+#include "mdssqldbmaintenance.h"
+#include "mdccommon.h"
+#include "mdspreferences.h"
+
+// ========================= MEMBER FUNCTIONS ==================================
+
+CMdSSqlDbMaintenance* CMdSSqlDbMaintenance::NewL()
+    {
+    CMdSSqlDbMaintenance* self = CMdSSqlDbMaintenance::NewLC();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+CMdSSqlDbMaintenance* CMdSSqlDbMaintenance::NewLC()
+    {
+    CMdSSqlDbMaintenance* self = new ( ELeave ) CMdSSqlDbMaintenance();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+void CMdSSqlDbMaintenance::ConstructL( )
+    {
+    }
+
+CMdSSqlDbMaintenance::CMdSSqlDbMaintenance()
+    {
+    }
+
+CMdSSqlDbMaintenance::~CMdSSqlDbMaintenance()
+    {
+    }
+
+TBool CMdSSqlDbMaintenance::ValidateL(  )
+    {
+    _LIT( KValidateTableExistence, "SELECT COUNT(*) FROM MdE_Preferences;" );
+
+    RMdsStatement validationQuery;
+    CleanupClosePushL( validationQuery );
+    RRowData emptyRowData;
+    CleanupClosePushL( emptyRowData );
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	TRAPD( test, connection.ExecuteQueryL( KValidateTableExistence, validationQuery, emptyRowData ) );
+	CleanupStack::PopAndDestroy( 2, &validationQuery );
+    return ( test == KErrNone );
+    }
+
+
+void CMdSSqlDbMaintenance::CreateDatabaseL()
+    {
+    _LIT( KCreateTblMdE_Preferences, // Table for metadata engine use
+    	"CREATE TABLE MdE_Preferences(Key TEXT,Value NONE,ExtraValue LARGEINT,UNIQUE(Key,Value));");
+
+    _LIT( KCreateTblMdS_Medias, // Table for metadata engine use
+		"CREATE TABLE MdS_Medias(MediaId INTEGER PRIMARY KEY,Drive INTEGER,PresentState INTEGER,Time LARGEINT);");
+    
+    RRowData emptyRowData;
+    CleanupClosePushL( emptyRowData );
+
+    // Create ontology tables
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+    connection.ExecuteL( KCreateTblMdE_Preferences, emptyRowData );
+
+    connection.ExecuteL( KCreateTblMdS_Medias, emptyRowData );
+
+    TInt majorVersion = KMdSServMajorVersionNumber;
+	TInt64 minorVersion = KMdSServMinorVersionNumber;
+    MMdsPreferences::InsertL( KMdsDBVersionName, MMdsPreferences::EPreferenceBothSet,
+    						  majorVersion, minorVersion );
+
+	CleanupStack::PopAndDestroy( &emptyRowData );
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdssqlfindoperation.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,1422 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Manages object search from database using SQL,*
+*/
+
+#include "mdssqlfindoperation.h"
+
+#include "mdcresult.h"
+#include "mdcitem.h"
+#include "mdcserializationbuffer.h"
+#include "mdsfindsequence.h"
+#include "mdsobjectdef.h"
+#include "mdsnamespacedef.h"
+#include "mdspropertydef.h"
+#include "mdsfindsqlclause.h"
+#include "mdsserver.h"
+#include "mdsdbconnectionpool.h"
+#include "mdeinternalerror.h"
+
+const TInt KMaxResultSize = 1024*256; // 256 KiB
+
+CMdSSqlFindOperation* CMdSSqlFindOperation::NewL(
+    CMdSFindSequence& aFind,
+    TUint aSetSize
+    )
+    {
+    CMdSSqlFindOperation* that = CMdSSqlFindOperation::NewLC(
+        aFind, aSetSize );
+    CleanupStack::Pop( that );
+    return that;
+    }
+
+CMdSSqlFindOperation* CMdSSqlFindOperation::NewLC(    
+    CMdSFindSequence& aFind,
+    TUint aSetSize
+    )
+    {
+    CMdSSqlFindOperation* that = new (ELeave) CMdSSqlFindOperation(        
+        aFind, 
+        aSetSize
+        );
+    CleanupStack::PushL( that );
+    that->ConstructL();
+    return that;
+    }
+
+CMdSSqlFindOperation::CMdSSqlFindOperation(    
+    CMdSFindSequence& aFind,
+    TUint aSetSize
+    )
+    : iResultMode( EQueryResultModeFirst ), iResultRow(NULL),
+    iResultRows(), iResultCount( 0 ), iResults( NULL ), iFind ( aFind ),
+    iState( EStateIdle ), iSetSize( aSetSize ), iLimit( 0 ), 
+    iLimitCounter( 0 ), iMemoryLimit( 0 ), 
+    iHarvestingPrioritizationCount( 0 )
+    {
+    }
+
+void CMdSSqlFindOperation::ConstructL()
+    {    
+	iFindClause = CMdSFindSqlClause::NewL( const_cast<CMdsSchema&>(iFind.Schema()) );	
+    }
+
+
+CMdSSqlFindOperation::~CMdSSqlFindOperation()
+    {
+	ConsumeRows();
+    iResultRows.Close();
+
+    iResultIds.Close();
+
+    // doesn't own result row
+    iResultRow = NULL;
+
+    iQueryId.Close();
+
+   	delete iResults;
+   	delete iFindClause;
+    }
+
+TInt CMdSSqlFindOperation::ExecuteL()
+    {
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+    iResultRow = &iFindClause->ResultRow();
+    iQueryType = iFindClause->QueryType();
+    iResultMode = iFindClause->ResultMode();
+
+	if( EQueryResultModeFirst >= iResultMode || EQueryResultModeLast <= iResultMode )
+		{
+#ifdef _DEBUG
+		User::Panic( _L("MdSFOExe") , KErrMdEUnknownQueryResultMode );
+#endif
+
+		User::Leave( KErrMdEUnknownQueryResultMode );
+		}
+
+   	iFind.SetResultMode( iQueryType == EQueryTypeObject && iResultMode == EQueryResultModeItem );
+        
+   	connection.ExecuteQueryL( iFindClause->AsTextL(), iQueryId, iFindClause->Variables() );
+
+    iState = EStateRunning;
+
+	iSetCounter = 0;
+	iMemoryLimit = 0;
+	iHarvestingPrioritizationCount = 0;
+
+    return FetchResultsL();
+    }
+
+TInt CMdSSqlFindOperation::ContinueL()
+    {
+    // Continue query: fetch next row
+    iSetCounter = 0;
+    iState = EStateRunning;
+
+    return FetchResultsL();
+    }
+
+TInt CMdSSqlFindOperation::FetchResultsL()
+    {
+	iMemoryLimit += EstimateBaseResultSize();
+	
+	if( !iResultRow )
+		{
+#ifdef _DEBUG
+		User::Panic( _L("MdSFOFe1") , KErrCorrupt );
+#endif
+
+		User::Leave( KErrCorrupt );
+		}
+
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+    while( ETrue )
+        {
+        RRowData* resultRow = new (ELeave) RRowData();        
+        CleanupStack::PushL( resultRow );
+        CleanupClosePushL( *resultRow );
+
+        resultRow->AppendColumnTypesL( *iResultRow );
+
+        // fetch next DB row
+        if ( !connection.NextRowL( iQueryId, *resultRow ) )
+            {
+            CleanupStack::PopAndDestroy( 2, resultRow ); // close and delete resultRow separately
+            resultRow = NULL;
+
+           	TRAPD( err, AddToContainerL() );
+
+           	if( KErrNone != err )
+           		{
+           		iResults = NULL;
+           		ConsumeRows();
+           		}
+
+           	connection.Terminate( iQueryId );
+            iState = EStateDead;
+            return KErrNone;
+            }
+
+        iMemoryLimit += EstimateResultRowSizeL( *resultRow );
+
+		// Check if maximum memory limit is reached or 
+		// set/limit counter is more than maximum set/limit size. 
+		if( KMaxResultSize <= iMemoryLimit )
+			{
+			// Store all previus items to result buffer.
+
+           	TRAPD( err, AddToContainerL() );
+
+           	if( KErrNone != err )
+           		{
+           		iResults = NULL;
+           		ConsumeRows();
+           		}
+
+			// add estimated size to next result set
+	        iMemoryLimit = EstimateResultRowSizeL( *resultRow );
+
+			if( EQueryResultModeItem == iResultMode || EQueryResultModeDistinctValues == iResultMode )
+				{
+				// add result row to result rows pointer array
+	           	iResultRows.AppendL( resultRow );
+				
+				iSetCounter++;
+	           	
+				// pop result row from cleanup stack twice
+				CleanupStack::Pop( 2, resultRow );
+				}
+			else
+				{
+				if( EQueryResultModeId == iResultMode )
+					{					
+					TItemId itemId = 0;
+					resultRow->Column( 0 ).Get( itemId );
+					iResultIds.AppendL( itemId );
+
+					iSetCounter++;
+					}
+				else
+					{
+					TUint32 count;
+					resultRow->Column( 0 ).Get( count );
+					iResultCount += count;
+					}
+
+				// pop and destroy result row from cleanup stack twice
+				CleanupStack::PopAndDestroy( 2, resultRow );
+				}
+
+
+			resultRow = NULL;
+
+           	++iLimitCounter;
+                
+            iState = EStateIdle;
+            connection.EnableTransaction( EFalse, iQueryId );
+            return KFindSetReady;
+			}
+		else
+			{
+			if( EQueryResultModeItem == iResultMode || EQueryResultModeDistinctValues == iResultMode )
+				{
+				// add result row to result rows pointer array
+	           	iResultRows.AppendL( resultRow );
+
+				iSetCounter++;
+
+				// pop result row from cleanup stack twice
+				CleanupStack::Pop( 2, resultRow );
+				}
+			else 
+				{
+				if( EQueryResultModeId == iResultMode )
+					{					
+					TItemId itemId = 0;
+					resultRow->Column( 0 ).Get( itemId );
+					iResultIds.AppendL( itemId ); 
+
+					iSetCounter++;
+					}
+				else
+					{
+					TUint32 count;
+					resultRow->Column( 0 ).Get( count );
+					iResultCount += count;
+					}
+
+				// pop and destroy result row from cleanup stack twice
+				CleanupStack::PopAndDestroy( 2, resultRow );
+				}
+
+			resultRow = NULL;
+
+			++iLimitCounter;
+			}
+
+        // check for different exit conditions
+        if ( iState == EStateRunning )
+            {
+            if ( iLimitCounter >= iLimit )
+                {
+	           	TRAPD( err, AddToContainerL() );
+
+	           	if( KErrNone != err )
+	           		{
+	           		iResults = NULL;
+	           		ConsumeRows();
+	           		}
+
+	           	connection.Terminate( iQueryId );
+                iState = EStateDead;
+                return KErrNone;
+                }
+            else if( iSetCounter >= iSetSize )
+                {
+	           	TRAPD( err, AddToContainerL() );
+
+	           	if( KErrNone != err )
+	           		{
+	           		iResults = NULL;
+	           		ConsumeRows();
+	           		}
+
+                iState = EStateIdle;
+                connection.EnableTransaction( EFalse, iQueryId );
+                return KFindSetReady;
+                }
+            }
+        else if ( iState == EStateStop )
+            {
+            // stop instructed
+            connection.Terminate( iQueryId );
+            iState = EStateDead;
+            return KErrCancel;
+            }
+        else 
+            {
+#ifdef _DEBUG
+	    	User::Panic( _L("MdSFOFe2") , KErrCorrupt );
+#endif
+	    	User::Leave( KErrCorrupt );
+            }
+        }
+    }
+
+TInt CMdSSqlFindOperation::EstimateBaseResultSize()
+	{
+	switch( iResultMode )
+		{
+		case EQueryResultModeItem:
+			return sizeof(TMdCItems);
+
+		case EQueryResultModeId:
+			return sizeof(TMdCItemIds);
+
+		case EQueryResultModeCount:
+			return sizeof(TMdCItemCounts);
+
+		case EQueryResultModeDistinctValues:
+			return sizeof(TMdCItemIds);
+
+		// should never happen
+		default:
+#ifdef _DEBUG
+			User::Panic( _L( "MdSFOEBS" ), KErrMdEUnknownQueryResultMode );
+#endif
+			return 0;
+		}
+	}
+
+TInt CMdSSqlFindOperation::EstimateResultRowSizeL( RRowData& aRow )
+	{
+	if( iResultMode == EQueryResultModeId )
+		{
+		return CMdCSerializationBuffer::KRequiredSizeForTItemId;
+		}
+	else if( iResultMode == EQueryResultModeCount )
+		{
+		return 0;
+		}
+	else if( iResultMode == EQueryResultModeDistinctValues )
+		{
+		if( iFindClause->PropertyFilters().Count() != 1 )
+			{
+			User::Leave( KErrCorrupt );
+			}
+
+		const RPointerArray<CMdsPropertyDef>& propertyFilters = iFindClause->PropertyFilters();
+
+		TInt rowSize = 0;
+		if( propertyFilters[0]->GetType() == EPropertyText )
+	    	{
+	    	if ( !aRow.Column( 0 ).IsNull() )
+	    		{
+				// Required size for text property
+				TPtrC16 value = TPtr16((TUint16*)0, 0);
+				aRow.Column( 0 ).Get( value );
+				rowSize += CMdCSerializationBuffer::RequiredSize( value );
+	    		}	    		
+	    	}
+	    else
+	    	{
+#ifdef _DEBUG
+	    	User::Panic( _L("MdSFOEs1") , KErrMdEUnknownPropertyType );
+#endif
+	    	User::Leave( KErrMdEUnknownPropertyType );
+	    	}
+	    	
+	    return rowSize;
+		}
+
+	switch( iQueryType )
+		{
+		case EQueryTypeObject:
+			{
+			TInt rowSize = sizeof(TMdCObject);
+
+			const TInt KUriColumn = 7;
+
+			TPtrC16 uri = TPtr16((TUint16*)0, 0);
+			
+			// Required size for object URI
+			if (!aRow.Column( KUriColumn ).IsNull())
+				{
+				aRow.Column( KUriColumn ).Get( uri );
+				rowSize += CMdCSerializationBuffer::RequiredSize( uri );
+				}
+
+			if( iFindClause->NoObjectLocking() && iFindClause->ObjectDef() && iFindClause->ObjectDef()->GetId() != KBaseObjectDefId )
+				{
+				// check if object is placeholder and add it to count of harvester 
+				// prioritization URIs
+				const TInt KFlagsColumn = 2;
+				TUint32 flags = 0;
+				aRow.Column( KFlagsColumn ).Get( flags );
+				if( flags & EMdEObjectFlagPlaceholder )
+					{
+					if( iFind.Server().ReserveSpaceHarvestingPrioritizationUri( uri ) )
+						{
+						iHarvestingPrioritizationCount++;
+						}
+					}
+				}
+
+			// Required size for properties
+			CMdsObjectDef* objectDef = iFindClause->ObjectDef();
+
+			if( !objectDef )
+				{
+#ifdef _DEBUG
+				User::Panic( _L("MdSFOEs2") , KErrMdEUnknownObjectDef );
+#endif
+				User::Leave( KErrMdEUnknownObjectDef );
+				}
+
+			const RPointerArray<CMdsPropertyDef>& propertyFilters = iFindClause->PropertyFilters();
+
+			// no property filterss
+			if( propertyFilters.Count() <= 0 )
+				{
+				const TInt count = objectDef->GetAllPropertiesCount();
+
+				// space for every property, even if it's "null"
+				rowSize += count * sizeof(TMdCProperty);
+
+				for( TInt i = 0; i < count; i++ )
+					{
+					const CMdsObjectDef::TMdsColumnOrder& propertyColumn = 
+						objectDef->GetPropertyColumnL( i );
+
+					TColumn& column = aRow.Column( propertyColumn.iColumnId );
+
+					if( column.IsNull() )
+						{
+						continue;
+						}
+
+					if( propertyColumn.iPropertyDef.GetType() == EPropertyText )
+				    	{
+						// Required size for text in text property
+						TPtrC16 value = TPtr16((TUint16*)0, 0);
+						column.Get( value );
+						rowSize += CMdCSerializationBuffer::RequiredSize( value );
+				    	}
+					}
+				}
+			// property filters
+			else
+				{
+				const TInt count = propertyFilters.Count();
+
+				// space for every property, even if it's "null"
+				rowSize += count * sizeof(TMdCProperty);
+
+				for( TInt i = 0; i < count; i++ )
+					{
+					CMdsPropertyDef* propDef = propertyFilters[i];
+
+					if( !propDef )
+						{
+#ifdef _DEBUG
+						User::Panic( _L("MdSFOEs3") , KErrMdEUnknownPropertyDef );
+#endif						
+						User::Leave( KErrMdEUnknownPropertyDef );
+						}
+
+					TColumn& column = aRow.Column( KBaseObjectBasicValueColumnOffset + i );
+
+					if( column.IsNull() )
+						{
+						continue;
+						}
+
+					if( propDef->GetType() == EPropertyText )
+				    	{
+						// Required size for text in text property
+						TPtrC16 value = TPtr16((TUint16*)0, 0);
+						column.Get( value );
+						rowSize += CMdCSerializationBuffer::RequiredSize( value );
+				    	}
+					}
+				}
+
+			if( FindCriteria().IncludesFreetexts() )
+				{
+				// In result row the second lastest column is free text count
+				const TInt freeTextCountColumn = aRow.Size() - 2;
+
+				// Get free text count
+				TUint32 freeTextCount = 0;
+				aRow.Column( freeTextCountColumn ).Get( freeTextCount );
+
+				if( freeTextCount > 0 )
+					{
+					// In result row last column is total free text length
+					const TInt totalFreeTextsLengthColumn = aRow.Size() - 1;
+
+					// Get total free text length.
+					TUint32 totalFreeTextsLength = 0;
+					aRow.Column( totalFreeTextsLengthColumn ).Get( totalFreeTextsLength );
+
+					// Required size for free texts.
+					// For every free text length (TUint16) 
+					rowSize += freeTextCount * ( CMdCSerializationBuffer::KRequiredSizeForEmptyText );
+					// and total free text length * TUint16
+					rowSize += totalFreeTextsLength * sizeof( TUint16 );
+					}
+				}
+
+			return rowSize;
+			}
+
+		case EQueryTypeRelation:
+			return sizeof(TMdCRelation);
+
+		case EQueryTypeEvent:
+			{
+			TInt rowSize = sizeof(TMdCEvent);
+
+			// Required size for source and participant texts
+			TPtrC16 source = TPtr16((TUint16*)0, 0);
+			aRow.Column( 4 ).Get( source );
+			rowSize += CMdCSerializationBuffer::RequiredSize( source );
+
+			TPtrC16 participant = TPtr16((TUint16*)0, 0);
+			aRow.Column( 5 ).Get( participant );
+			rowSize += CMdCSerializationBuffer::RequiredSize( participant );
+
+			return rowSize;
+			}
+
+		default:
+#ifdef _DEBUG
+			User::Panic( _L( "MdSFOEs4" ), KErrMdEUnknownQueryResultMode );
+#endif
+			return 0;
+		}
+	}
+
+TInt CMdSSqlFindOperation::State()
+    {
+    return iState;
+    }
+
+void CMdSSqlFindOperation::Cancel()
+    {
+    if ( iState == EStateRunning )
+        {
+        iState = EStateStop;
+        }
+    }
+
+RPointerArray<HBufC>& CMdSSqlFindOperation::QueryFreeText()
+	{
+	return iFindClause->QueryFreeText();
+	}
+
+
+CMdSFindSqlClause& CMdSSqlFindOperation::FindCriteria()
+    {
+    return *iFindClause;
+    }
+
+CMdCSerializationBuffer* CMdSSqlFindOperation::Results()
+	{
+	CMdCSerializationBuffer* results = iResults;
+	iResults = NULL;
+	return results;
+	}
+
+void CMdSSqlFindOperation::SetLimit(TUint32 aLimit)
+	{
+	iLimit = aLimit;
+	}
+
+void CMdSSqlFindOperation::SetOffset(TUint32 aOffset)
+	{
+	iOffset = aOffset;
+	}
+
+TMdCOffset CMdSSqlFindOperation::AddItemToContainerL( RRowData &aRow, TMdCOffset aFreespaceOffset )
+    {
+    switch( iQueryType )  
+        {
+        case EQueryTypeObject:
+            {
+            aFreespaceOffset = AddObjectToContainerL( aRow, aFreespaceOffset );
+            break;
+            }
+        case EQueryTypeEvent:
+            {
+            TMdCEvent event;
+            TPtrC16 source = TPtr16( ( TUint16* )0, 0 );      //KNullPtr16;
+            TPtrC16 participant = TPtr16( ( TUint16* )0, 0 ); //KNullPtr16;
+
+            aRow.Column( 0 ).Get( event.iId );
+            aRow.Column( 1 ).Get( event.iObjectId );
+            aRow.Column( 2 ).Get( event.iDefId );
+            aRow.Column( 3 ).Get( event.iTime );
+            aRow.Column( 4 ).Get( source );
+            aRow.Column( 5 ).Get( participant );
+
+            const TMdCOffset eventOffset = iResults->Position();
+            
+            if ( source.Length() > 0 )
+            	{
+            	event.iSourceText.iPtr.iCount = source.Length();
+            	event.iSourceText.iPtr.iOffset = aFreespaceOffset;
+            	iResults->PositionL( aFreespaceOffset );
+            	aFreespaceOffset = iResults->InsertL( source );
+            	}
+            else
+            	{
+            	event.iSourceText.iPtr.iCount = 0;
+            	event.iSourceText.iPtr.iOffset = KNoOffset;
+            	}
+
+            if ( participant.Length() > 0 )
+            	{
+            	event.iParticipantText.iPtr.iCount = participant.Length();
+            	event.iParticipantText.iPtr.iOffset = aFreespaceOffset;
+            	iResults->PositionL( aFreespaceOffset );
+                aFreespaceOffset = iResults->InsertL( participant );
+            	}
+            else
+            	{
+            	event.iParticipantText.iPtr.iCount = 0;
+            	event.iParticipantText.iPtr.iOffset = KNoOffset;
+            	}
+            
+            iResults->PositionL( eventOffset );
+            event.SerializeL( *iResults );
+            break;
+            }
+        case EQueryTypeRelation:
+            {
+            TMdCRelation relation;
+            TUint32 flags           ( 0 );
+
+            aRow.Column( 0 ).Get( relation.iId );
+            aRow.Column( 1 ).Get( flags );
+            aRow.Column( 2 ).Get( relation.iDefId );
+            aRow.Column( 3 ).Get( relation.iLeftObjectId );
+            aRow.Column( 4 ).Get( relation.iRightObjectId );
+            aRow.Column( 5 ).Get( relation.iParameter );
+            aRow.Column( 6 ).Get( relation.iGuidHigh );
+            aRow.Column( 7 ).Get( relation.iGuidLow );
+            aRow.Column( 8 ).Get( relation.iLastModifiedDate );
+
+            relation.SerializeL( *iResults );
+            break;
+            }
+        // Unknown query type
+        default:
+            {
+#ifdef _DEBUG
+			User::Panic( _L("MdSFOAd1") , KErrMdEUnknownQueryType );
+#endif
+            User::Leave( KErrMdEUnknownQueryType );
+            }
+        }
+    return aFreespaceOffset;
+    }
+
+void CMdSSqlFindOperation::AddIdToContainerL( TItemId aId )
+    {
+    switch( iQueryType )  
+        {
+        case EQueryTypeObject:
+        case EQueryTypeEvent:
+        case EQueryTypeRelation:
+            {
+            iResults->InsertL( aId );
+            break;
+            }
+        default:
+            {
+#ifdef _DEBUG
+			User::Panic( _L("MdSFOAd2") , KErrMdEUnknownQueryType );
+#endif
+            User::Leave( KErrMdEUnknownQueryType );
+            }
+        }
+    }
+
+void CMdSSqlFindOperation::CreateItemL()
+    {
+    TMdCItems items;
+    items.iNamespaceDefId = iFindClause->NamespaceDef()->GetId();
+    items.iObjects.iPtr.iCount = 0;
+    items.iObjects.iPtr.iOffset = KNoOffset;
+    items.iRelations.iPtr.iCount = 0;
+    items.iRelations.iPtr.iOffset = KNoOffset;
+    items.iEvents.iPtr.iCount = 0;
+    items.iEvents.iPtr.iOffset = KNoOffset;
+
+    // move after main header
+    iResults->PositionL( sizeof(TMdCItems) );
+
+    TUint32 count = iResultRows.Count();
+    TMdCOffset freetextOffset = KNoOffset;
+    switch( iQueryType )
+        {
+        case EQueryTypeObject:
+            {
+            // add objects header
+            items.iObjects.iPtr.iCount = count;
+            items.iObjects.iPtr.iOffset = iResults->Position();
+            freetextOffset = items.iObjects.iPtr.iOffset + count * sizeof(TMdCObject);
+            
+            // initializate server's harvesting prioritization buffer
+        	if( iHarvestingPrioritizationCount > 0 )
+        		{
+        		iFind.Server().StartAddingHarvestingPrioritizationUrisL();
+        		}		
+
+            break;
+            }
+        case EQueryTypeEvent:
+            {
+            // add objects header
+            items.iEvents.iPtr.iCount = count;
+            items.iEvents.iPtr.iOffset = iResults->Position();
+            freetextOffset = items.iEvents.iPtr.iOffset + count * sizeof(TMdCEvent);
+            break;
+            }
+        case EQueryTypeRelation:
+            {
+            // add objects header
+            items.iRelations.iPtr.iCount = count;
+            items.iRelations.iPtr.iOffset = iResults->Position();
+            freetextOffset = items.iRelations.iPtr.iOffset + count * sizeof(TMdCRelation);
+            break;
+            }
+        default:
+            {
+#ifdef _DEBUG
+			User::Panic( _L("MdSFOCr1") , KErrMdEUnknownQueryType );
+#endif
+			User::Leave( KErrMdEUnknownQueryType );
+            }
+        }
+
+  	iResults->PositionL( KNoOffset );
+	items.SerializeL( *iResults );
+
+    //Set offset to objects/events/relations
+    for( TInt i = 0; i < count; i++ )
+        {
+        switch ( iQueryType )
+        	{
+			case EQueryTypeObject:
+	        	{
+	            iResults->PositionL( items.iObjects.iPtr.iOffset
+	            		+ i * sizeof(TMdCObject) );
+	            freetextOffset = AddItemToContainerL( *iResultRows[i], freetextOffset );
+	            break;
+	            }
+	        case EQueryTypeEvent:
+	        	{
+	            iResults->PositionL( items.iEvents.iPtr.iOffset
+	            		+ i * sizeof(TMdCEvent) );
+	            freetextOffset = AddItemToContainerL( *iResultRows[i], freetextOffset );
+	            break;
+	            }
+	        case EQueryTypeRelation:
+	        	{
+	            iResults->PositionL( items.iRelations.iPtr.iOffset
+	            		+ i * sizeof(TMdCRelation) );
+	            freetextOffset = AddItemToContainerL( *iResultRows[i], freetextOffset );
+			    break;
+	            }
+	        default:
+	        	{
+#ifdef _DEBUG
+	        	User::Panic( _L("MdSFOCr2") , KErrMdEUnknownQueryType );
+#endif
+	        	User::Leave( KErrMdEUnknownQueryType );
+	        	}
+        	}
+        }
+    }
+
+void CMdSSqlFindOperation::CreateCountL()
+    {
+    TMdCItemCounts itemCounts;
+    itemCounts.iNamespaceDefId = iFindClause->NamespaceDef()->GetId();
+    itemCounts.iObjects = 0;
+    itemCounts.iEvents = 0;
+    itemCounts.iRelations = 0;
+
+    switch( iQueryType )
+        {
+        case EQueryTypeObject:
+            {
+            itemCounts.iObjects = iResultCount;
+            break;
+            }
+        case EQueryTypeEvent:
+            {
+            itemCounts.iEvents = iResultCount;
+            break;
+            }
+        case EQueryTypeRelation:
+            {
+            itemCounts.iRelations = iResultCount;
+            break;
+            }
+        default:
+            {
+#ifdef _DEBUG
+			User::Panic( _L("MdSFOCr3") , KErrMdEUnknownQueryType );
+#endif
+			User::Leave( KErrMdEUnknownQueryType );
+            }
+        }
+
+    itemCounts.SerializeL( *iResults );
+    }
+
+void CMdSSqlFindOperation::CreateIdL()
+    {
+    TMdCItemIds itemIds;
+    itemIds.iNamespaceDefId = iFindClause->NamespaceDef()->GetId();
+    itemIds.iErrorCode = KErrNone;
+    itemIds.iObjectIds.iPtr.iCount = 0;
+    itemIds.iObjectIds.iPtr.iOffset = KNoOffset;
+    itemIds.iObjectUris.iPtr.iCount = 0;
+    itemIds.iObjectUris.iPtr.iOffset = KNoOffset;
+    itemIds.iEventIds.iPtr.iCount = 0;
+    itemIds.iEventIds.iPtr.iOffset = KNoOffset;
+    itemIds.iRelationIds.iPtr.iCount = 0;
+    itemIds.iRelationIds.iPtr.iOffset = KNoOffset;
+
+    iResults->PositionL( sizeof(TMdCItemIds) );
+
+    TUint32 count = iResultIds.Count();
+    switch( iQueryType )  
+        {
+        case EQueryTypeObject:
+            {
+            itemIds.iObjectIds.iPtr.iCount = count;
+            itemIds.iObjectIds.iPtr.iOffset = iResults->Position();
+            break;
+            }
+        case EQueryTypeEvent:
+            {
+            itemIds.iEventIds.iPtr.iCount = count;
+            itemIds.iEventIds.iPtr.iOffset = iResults->Position();
+            break;
+            }
+        case EQueryTypeRelation:
+            {
+            itemIds.iRelationIds.iPtr.iCount = count;
+            itemIds.iRelationIds.iPtr.iOffset = iResults->Position();
+            break;
+            }
+        default:
+            {
+#ifdef _DEBUG
+			User::Panic( _L("MdSFOCr4") , KErrMdEUnknownQueryType );
+#endif
+			User::Leave( KErrMdEUnknownQueryType );
+            }
+        }
+
+	iResults->PositionL( KNoOffset );
+	itemIds.SerializeL( *iResults );
+
+    for( TInt i = 0; i < count; i++ )
+        {
+	    AddIdToContainerL( iResultIds[i] );
+        }
+    }
+
+void CMdSSqlFindOperation::CreateDistinctL()
+	{
+    TMdCItemIds itemIds;
+    itemIds.iNamespaceDefId = iFindClause->NamespaceDef()->GetId();
+    itemIds.iErrorCode = KErrNone;
+    itemIds.iObjectIds.iPtr.iCount = 0;
+    itemIds.iObjectIds.iPtr.iOffset = KNoOffset;
+    itemIds.iEventIds.iPtr.iCount = 0;
+    itemIds.iEventIds.iPtr.iOffset = KNoOffset;
+    itemIds.iRelationIds.iPtr.iCount = 0;
+    itemIds.iRelationIds.iPtr.iOffset = KNoOffset;
+
+    itemIds.iObjectUris.iPtr.iCount = 0;
+    itemIds.iObjectUris.iPtr.iOffset = sizeof(TMdCItemIds);
+    
+    iResults->PositionL( itemIds.iObjectUris.iPtr.iOffset );
+    const TInt resultRowsCount = iResultRows.Count();
+	for ( TInt i = 0; i < resultRowsCount; ++i )
+		{		
+		if ( !iResultRows[i]->Column( 0 ).IsNull() )
+			{
+			TPtrC16 value = TPtr16((TUint16*)0, 0);
+			iResultRows[i]->Column( 0 ).Get( value );
+			iResults->InsertL( value );
+			++itemIds.iObjectUris.iPtr.iCount;
+			}
+		}
+
+    iResults->PositionL( KNoOffset );
+    itemIds.SerializeL( *iResults );
+	}
+
+void CMdSSqlFindOperation::AddToContainerL()
+    {
+    // if old result buffer exist try to use it
+    if( iResults )
+    	{
+    	// create new if the old result buffer is too short
+    	if( iResults->Size() < iMemoryLimit )
+    		{
+    		delete iResults;
+    		iResults = NULL;
+
+    		iResults = CMdCSerializationBuffer::NewL( iMemoryLimit );
+    		}
+    	// else just move to the begin of the result buffer
+    	else
+    		{
+    		iResults->PositionL( 0 );
+    		}
+    	}
+	else
+		{
+		iResults = CMdCSerializationBuffer::NewL( iMemoryLimit );
+		}
+
+    TInt err;
+    switch( iResultMode )  
+        {
+        case EQueryResultModeCount:
+            {
+            TRAP( err, CreateCountL() );
+            break;
+            }
+        case EQueryResultModeItem:
+            {
+            TRAP( err, CreateItemL() );
+            break;
+            }
+        case EQueryResultModeId:
+            {
+            TRAP( err, CreateIdL() );
+          break;
+            }
+        case EQueryResultModeDistinctValues:
+            {
+            TRAP( err, CreateDistinctL() );
+            break;
+            }
+        default:
+            {
+#ifdef _DEBUG
+			User::Panic( _L("MdSFOAd3") , KErrMdEUnknownQueryResultMode );
+#endif
+			User::Leave( KErrMdEUnknownQueryResultMode );
+            }
+        }
+ 
+	if( err != KErrNone )
+		{
+		delete iResults;
+		iResults = NULL;
+		}
+
+   	ConsumeRows();
+    }
+
+TMdCOffset CMdSSqlFindOperation::AddObjectToContainerL( RRowData& aRow, TMdCOffset aFreespaceOffset )
+    {
+    TMdCObject object;
+    const TMdCOffset objectOffset = iResults->Position();
+    object.iFlags = EMdEObjectFlagNone;
+
+	// Get base objects basic values
+    TUint32 serverSideFlags;
+    TPtrC16 uri;
+    aRow.Column( 0 ).Get( object.iId );
+    aRow.Column( 1 ).Get( object.iDefId );
+    aRow.Column( 2 ).Get( serverSideFlags );
+    aRow.Column( 3 ).Get( object.iMediaId );
+    aRow.Column( 4 ).Get( object.iUsageCount );
+    aRow.Column( 5 ).Get( object.iGuidHigh );
+    aRow.Column( 6 ).Get( object.iGuidLow );
+    if (aRow.Column( 7 ).IsNull())
+    	{
+    	object.iId = KNoId;
+    	object.iUri.iPtr.iCount = 0;
+    	object.iUri.iPtr.iOffset = KNoOffset;
+    	object.SerializeL( *iResults );
+    	return aFreespaceOffset;
+    	}
+    aRow.Column( 7 ).Get( uri );
+
+	// SETTING CLIENT SIDE FLAGS
+	// Set not present flag to client side flags 
+	// (removed objects are also flaged as not present)
+	if( ( serverSideFlags & EMdEObjectFlagNotPresent ) ||
+		( serverSideFlags & EMdEObjectFlagRemoved ) )
+		{
+		object.iFlags |= EMdEObjectFlagNotPresent;
+		}
+
+	// Set confidential flag to client side flags
+	if( serverSideFlags & EMdEObjectFlagConfidential )
+		{
+		object.iFlags |= EMdEObjectFlagConfidential;
+		}
+
+	// Set freetext flag to client side flags
+	if( serverSideFlags & EMdEObjectFlagFreetexts )
+		{
+		object.iFlags |= EMdEObjectFlagFreetexts;
+		}
+
+	// Set placeholder flag to client side flags
+	if( serverSideFlags & EMdEObjectFlagPlaceholder )
+		{
+		object.iFlags |= EMdEObjectFlagPlaceholder;
+		
+		// object is placeholder, so try add it's URI to harverting 
+		// prioritization buffer
+		if( iHarvestingPrioritizationCount > 0 )
+			{
+			iFind.Server().AddHarvestingPrioritizationUriL( uri );
+
+			iHarvestingPrioritizationCount--;
+
+			if( iHarvestingPrioritizationCount == 0 )
+				{
+				iFind.Server().NotifyHarvestingPrioritizationObserver( KErrNone );
+				}
+			}
+		}
+	
+	const CMdsObjectDef* objectDef = iFindClause->ObjectDef();
+	if( !objectDef )
+		{
+#ifdef _DEBUG
+		User::Panic( _L("MdSFOAd4") , KErrMdEUnknownObjectDef );
+#endif		
+		User::Leave( KErrMdEUnknownObjectDef );
+		}
+
+    // Add base objects basic values to result buffer
+    object.iUri.iPtr.iCount = uri.Length();
+    object.iUri.iPtr.iOffset = aFreespaceOffset;
+    iResults->PositionL( aFreespaceOffset );
+    aFreespaceOffset = iResults->InsertL( uri );
+
+	const RPointerArray<CMdsPropertyDef>& propertyFilters = iFindClause->PropertyFilters();
+
+	// No property filters
+	if( propertyFilters.Count() <= 0 )
+		{
+		const TInt allPropertyCount = objectDef->GetAllPropertiesCount();
+		object.iProperties.iPtr.iCount = 0;
+		object.iProperties.iPtr.iOffset = aFreespaceOffset;
+
+		// Position after property offsets
+		aFreespaceOffset += allPropertyCount * sizeof(TMdCProperty);
+		
+		for( TInt i = 0; i < allPropertyCount; i++ )
+			{
+			const CMdsObjectDef::TMdsColumnOrder& propertyColumn = 
+				objectDef->GetPropertyColumnL( i );
+
+			TColumn& column = aRow.Column( propertyColumn.iColumnId );
+
+			// check if property exists, else continue to with next property
+			if( column.IsNull() )
+				{
+				continue;
+				}
+
+			TMdCProperty property;
+
+			property.iPropertyDefId = propertyColumn.iPropertyDef.GetId();
+			property.iModFlags = EMdEPropertyModNone;
+
+			const TPropertyType propertyType = propertyColumn.iPropertyDef.GetType();
+			switch(propertyType)
+				{
+				case EPropertyBool:
+					{
+					TBool value;
+					column.Get( value );
+					property.iValue.iInt32 = value;
+					}
+    				break;
+    			case EPropertyInt8:
+    				{
+					TInt32 value32;
+					column.Get( value32 );
+					property.iValue.iInt32 = value32;
+    				}
+    				break;
+    			case EPropertyUint8:
+    				{
+					TUint32 value32;
+					column.Get( value32 );
+					property.iValue.iUint32 = value32;
+    				}
+    				break;
+    			case EPropertyInt16:
+    				{
+					TInt32 value32;
+					column.Get( value32 );
+					property.iValue.iInt32 = value32;
+    				}
+    				break;
+    			case EPropertyUint16:
+    				{
+					TUint32 value32;
+					column.Get( value32 );
+					property.iValue.iUint32 = value32;
+    				}
+    				break;
+    			case EPropertyInt32:
+    				{
+					TInt32 value;
+					column.Get( value );
+					property.iValue.iInt32 = value;
+    				}
+    				break;
+    			case EPropertyUint32:
+    				{
+					TUint32 value;
+					column.Get( value );
+					property.iValue.iUint32 = value;
+    				}
+    				break;
+				case EPropertyInt64:
+    				{
+					TInt64 value;
+					column.Get( value );
+					property.iValue.iInt64 = value;
+    				}
+    				break;    				
+    			case EPropertyReal32:
+    				{
+					TReal32 value;
+					column.Get( value );
+					property.iValue.iReal = value;
+    				}
+    				break;
+    			case EPropertyReal64:
+    				{
+					TReal64 value;
+					column.Get( value );
+					property.iValue.iReal = value;
+    				}
+    				break;
+    			case EPropertyTime:
+    				{
+					TTime value;
+					column.Get( value );
+					property.iValue.iInt64 = value.Int64();
+    				}
+    				break;
+    			case EPropertyText:
+    				{    				
+	    			TPtrC16 value;
+					column.Get( value );
+					if (value.Length() > 0)
+						{
+						property.iValue.iPtr.iCount = value.Length();
+						property.iValue.iPtr.iOffset = aFreespaceOffset;
+						iResults->PositionL( aFreespaceOffset );
+						aFreespaceOffset = iResults->InsertL( value );
+						}
+					else
+						{
+						property.iValue.iPtr.iCount = 0;
+						property.iValue.iPtr.iOffset = KNoOffset;
+						}
+    				}
+    				break;
+    			default:
+#ifdef _DEBUG
+					User::Panic( _L("MdSFOAd5") , KErrMdEUnknownPropertyType );
+#endif
+					User::Leave( KErrMdEUnknownPropertyType );
+				}
+
+		    // store property in buffer
+			iResults->PositionL( object.iProperties.iPtr.iOffset
+					+ object.iProperties.iPtr.iCount * sizeof(TMdCProperty) );
+			++object.iProperties.iPtr.iCount;
+		    property.SerializeL( *iResults );
+			}
+		}
+	// Property filters
+	else
+		{
+		const TUint32 propertyCount = propertyFilters.Count();
+		object.iProperties.iPtr.iCount = 0;
+		object.iProperties.iPtr.iOffset = aFreespaceOffset;
+
+		// Position after property offsets
+		aFreespaceOffset += propertyCount * sizeof(TMdCProperty);
+
+		for( TInt i = 0; i < propertyCount; i++ )
+			{
+			CMdsPropertyDef* propDef = propertyFilters[i];
+
+			if( !propDef )
+				{
+#ifdef _DEBUG
+				User::Panic( _L("MdSFOAd6") , KErrMdEUnknownPropertyDef );
+#endif
+				User::Leave( KErrMdEUnknownPropertyDef );
+				}
+
+			TColumn& column = aRow.Column( KBaseObjectBasicValueColumnOffset + i );
+
+			// check if property exists, else continue to with next property
+			if( column.IsNull() )
+				{
+				continue;
+				}
+
+			TMdCProperty property;
+
+			property.iPropertyDefId = propDef->GetId();
+			property.iModFlags = EMdEPropertyModNone;
+
+			const TPropertyType propertyType = propDef->GetType();
+			switch(propertyType)
+				{
+				case EPropertyBool:
+					{
+					TBool value;
+					column.Get( value );
+					property.iValue.iInt32 = value;
+					}
+					break;
+				case EPropertyInt8:
+					{
+					TInt32 value32;
+					column.Get( value32 );
+					property.iValue.iInt32 = value32;
+					}
+					break;
+				case EPropertyUint8:
+					{
+					TUint32 value32;
+					column.Get( value32 );
+					property.iValue.iUint32 = value32;
+					}
+					break;
+				case EPropertyInt16:
+					{
+					TInt32 value32;
+					column.Get( value32 );
+					property.iValue.iInt32 = value32;
+					}
+					break;
+				case EPropertyUint16:
+					{
+					TUint32 value32;
+					column.Get( value32 );
+					property.iValue.iUint32 = value32;
+					}
+					break;
+				case EPropertyInt32:
+					{
+					TInt32 value;
+					column.Get( value );
+					property.iValue.iInt32 = value;
+					}
+					break;
+				case EPropertyUint32:
+					{
+					TUint32 value;
+					column.Get( value );
+					property.iValue.iUint32 = value;
+					}
+					break;
+				case EPropertyInt64:
+					{
+					TInt64 value;
+					column.Get( value );
+					property.iValue.iInt64 = value;
+					}
+					break;    				
+				case EPropertyReal32:
+					{
+					TReal32 value;
+					column.Get( value );
+					property.iValue.iReal = value;
+					}
+					break;
+				case EPropertyReal64:
+					{
+					TReal64 value;
+					column.Get( value );
+					property.iValue.iReal = value;
+					}
+					break;
+				case EPropertyTime:
+					{
+					TTime value;
+					column.Get( value );
+					property.iValue.iReal = value.Int64();
+					}
+					break;
+				case EPropertyText:
+					{    				
+	    			TPtrC16 value;
+					column.Get( value );
+					if (value.Length() > 0)
+						{
+						property.iValue.iPtr.iCount = value.Length();
+						property.iValue.iPtr.iOffset = aFreespaceOffset;
+						iResults->PositionL( aFreespaceOffset );
+						aFreespaceOffset = iResults->InsertL( value );
+						}
+					else
+						{
+						property.iValue.iPtr.iCount = 0;
+						property.iValue.iPtr.iOffset = KNoOffset;
+						}
+					}
+					break;
+				default:
+#ifdef _DEBUG
+					User::Panic( _L("MdSFOAd7") , KErrMdEUnknownPropertyType );
+#endif
+					User::Leave( KErrMdEUnknownPropertyType );
+				}
+
+		    // store property in buffer
+			iResults->PositionL( object.iProperties.iPtr.iOffset
+					+ object.iProperties.iPtr.iCount * sizeof(TMdCProperty) );
+			++object.iProperties.iPtr.iCount;
+		    property.SerializeL( *iResults );
+			}
+		}
+
+	if( FindCriteria().IncludesFreetexts() )
+		{		
+		// In result row the second lastest column is free text count
+		const TInt freeTextCountColumn = aRow.Size() - 2;
+
+		// Get free text count and total free text lenght.
+		TUint32 freeTextCount = 0;
+		aRow.Column( freeTextCountColumn ).Get( freeTextCount );
+
+		if( freeTextCount > 0 )
+			{
+			object.iFreeTexts.iPtr.iCount = freeTextCount;
+			object.iFreeTexts.iPtr.iOffset = aFreespaceOffset;
+			
+			// In result row last column is total free text lenght.
+			const TInt totalFreeTextsLengthColumn = aRow.Size() - 1;
+
+			TUint32 totalFreeTextsLength = 0;
+			aRow.Column( totalFreeTextsLengthColumn ).Get( totalFreeTextsLength );
+
+			// Reserve space for free texts.
+			// For every free text possible padding (TUint8), length (TUint16)
+			TUint32 freeTextReserve = freeTextCount * CMdCSerializationBuffer::KRequiredSizeForEmptyText;
+			// and total free text length * TUint16
+			freeTextReserve += totalFreeTextsLength * sizeof( TUint16 );
+
+			aFreespaceOffset += freeTextReserve;
+			}
+		else
+			{
+			object.iFreeTexts.iPtr.iCount = 0;
+			object.iFreeTexts.iPtr.iOffset = KNoOffset;
+			}
+		}
+	else
+		{
+		object.iFreeTexts.iPtr.iCount = 0;
+		object.iFreeTexts.iPtr.iOffset = KNoOffset;
+		}
+
+	iResults->PositionL( objectOffset );
+    object.SerializeL( *iResults );
+
+	return aFreespaceOffset;
+    }
+
+void CMdSSqlFindOperation::ConsumeRows()
+    {
+	if( EQueryResultModeId != iResultMode )
+		{    
+	    const TInt KRowCount = iResultRows.Count();
+
+	    for( TInt i = 0; i < KRowCount; i++ )
+	    	{
+	    	iResultRows[i]->Close();
+	    	}
+
+	    iResultRows.ResetAndDestroy();
+		}
+	// handle result mode IDs as special case
+	else
+		{
+		iResultIds.Reset();
+		}
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdssqliteconnection.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,582 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Adaptation layer to SQLite database*
+*/
+
+// INCLUDE FILES
+#include "mdssqliteconnection.h"
+#include "mdslogger.h"
+
+__USES_LOGGER
+
+CMdSSqLiteConnection* CMdSSqLiteConnection::NewL()
+    {    
+    CMdSSqLiteConnection* self = CMdSSqLiteConnection::NewLC();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+CMdSSqLiteConnection* CMdSSqLiteConnection::NewLC()
+    {
+    CMdSSqLiteConnection* self = new ( ELeave ) CMdSSqLiteConnection( );
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    return self;  
+    }
+
+
+CMdSSqLiteConnection::CMdSSqLiteConnection()
+	: iDbFileName( NULL ), iEnableTransaction( ETrue ),iNotFinishFindQuery( NULL )
+    {
+    }
+
+
+CMdSSqLiteConnection::~CMdSSqLiteConnection()
+    {
+    CloseDb();
+
+    delete iDbFileName;
+
+    iNotFinishFindQuery = NULL;
+    }
+
+void CMdSSqLiteConnection::DeleteDb( TDesC16* aName )
+	{
+	if( aName )
+		{
+		RSqlDatabase::Delete( *aName );
+		}
+	else
+		{
+		RSqlDatabase::Delete( KMdsSqlDbDefaultName );
+		}
+	}
+
+void CMdSSqLiteConnection::CloseDb()
+	{
+	iMdeSqlDb.Close();
+	}
+
+void CMdSSqLiteConnection::ConstructL()
+    {
+    }
+
+void CMdSSqLiteConnection::OpenDbL( const TDesC& aDbFileName )
+    {
+    _LIT8( KMdsSqlDbaConfig, "cache_size=10000; page_size=4096; encoding=\"UTF-16\";");
+
+    TInt err = KErrNone;
+
+    delete iDbFileName;
+    iDbFileName = NULL; // in case AllocL leaves
+    iDbFileName = aDbFileName.AllocL();
+
+    // we need to set up policy, because we use secure database
+	TSecurityPolicy defaultPolicy(TSecurityPolicy::EAlwaysPass);
+    RSqlSecurityPolicy sqlSecurityPolicy;
+    CleanupClosePushL( sqlSecurityPolicy );
+    err = sqlSecurityPolicy.Create( defaultPolicy );
+
+    if ( err != KErrNone )
+    	{
+    	_LIT( KMdsSecurityCheckFail, "Security check fail" );
+    	TraceAndLeaveL( KMdsSecurityCheckFail, err );
+    	}
+    /**
+     * Open database:
+     *   First we try to create new db. If this fails check if db already exists and
+     *   try to open it. Otherwise we cannot open it and we leave
+     */
+    err = iMdeSqlDb.Create( *iDbFileName, sqlSecurityPolicy, &KMdsSqlDbaConfig );
+    if ( err != KErrNone )
+    	{
+    	// it could fail because database exists
+    	if ( err == KErrAlreadyExists )
+    		{
+    		err = iMdeSqlDb.Open( *iDbFileName, &KMdsSqlDbaConfig );
+    		if ( err != KErrNone )
+    			{
+    			__LOG1( ELogDb, "Cannot open database %d", err );
+    			}
+    		}
+    	else 
+    		{
+    		__LOG1( ELogDb, "Unknown error while creating %d", err );
+    		}
+
+    	User::LeaveIfError( err );
+    	}
+    CleanupStack::PopAndDestroy( &sqlSecurityPolicy );
+    }
+
+TInt CMdSSqLiteConnection::ExecuteL( const TDesC& aCommand,
+                                     const RRowData& aVariables,
+                                     RMdsStatement* aStatement )
+    {
+    TInt err = KErrNone;
+
+    if ( aVariables.Size() == 0 )
+        {
+        // no variables
+        err = iMdeSqlDb.Exec( aCommand );
+
+		if ( err < KErrNone )
+        	{
+            _LIT( KMdSExec, "Exec (no variables)" );
+            TraceAndLeaveL( KMdSExec, err );
+            }
+		}
+    else if ( aStatement )
+    	{
+        if ( aStatement->iPrepared == EFalse )
+            {
+            err = aStatement->iStatement.Prepare( iMdeSqlDb, aCommand );
+
+        	if ( err < KErrNone )
+                {
+                _LIT( KMdSPrepare, "Prepare" );
+                TraceAndLeaveL( KMdSPrepare, err );
+                }
+            aStatement->iPrepared = ETrue;
+            }
+        else
+            {
+            err = aStatement->iStatement.Reset();
+         	if ( err < KErrNone )
+                {
+                _LIT( KMdSResume, "Resume" );
+                TraceAndLeaveL( KMdSResume, err );
+                }
+            }
+           
+        DoBindL( aStatement->iStatement, aVariables );
+        err = aStatement->iStatement.Exec();
+
+        if ( err < KErrNone )
+            {
+            aStatement->iStatement.Reset();
+            aStatement->iPrepared = EFalse;
+			_LIT( KMdSExec, "Exec" );
+            TraceAndLeaveL( KMdSExec, err );
+            }
+    	}
+    else
+        {
+        RSqlStatement mdeSqlDbStmt;
+        CleanupClosePushL( mdeSqlDbStmt );
+        err = mdeSqlDbStmt.Prepare( iMdeSqlDb, aCommand );
+
+        if ( err < KErrNone )
+            {
+            _LIT( KMdsPrepare, "Prepare (no statement)" );
+            TraceAndLeaveL( KMdsPrepare, err );
+            }
+
+        DoBindL( mdeSqlDbStmt, aVariables );
+        
+        err = mdeSqlDbStmt.Exec();
+
+        if ( err < KErrNone )
+            {
+            _LIT( KMdsExec, "Exec (no statement)" );
+            TraceAndLeaveL( KMdsExec, err );
+            }
+
+        CleanupStack::PopAndDestroy( &mdeSqlDbStmt );
+        }
+    return err;
+    }
+
+void CMdSSqLiteConnection::ExecuteQueryL( const TDesC& aQuery,
+										  RMdsStatement& aStatement,
+										  const RRowData& aVariables )
+    {
+    TInt stmterr;
+    if ( aStatement.iPrepared == EFalse )
+    	{
+    	stmterr = aStatement.iStatement.Prepare( iMdeSqlDb, aQuery );
+    	if ( stmterr != KErrNone )
+        	{
+        	_LIT( KMdSQueryPrepare, "Query Prepare" );
+        	TraceAndLeaveL( KMdSQueryPrepare, stmterr );
+        	}
+    	aStatement.iPrepared = ETrue;
+    	}
+    else
+    	{
+    	stmterr = aStatement.iStatement.Reset();
+    	if ( stmterr != KErrNone )
+        	{
+        	_LIT( KMdSQueryReset, "Query Reset" );
+        	TraceAndLeaveL( KMdSQueryReset, stmterr );
+        	}
+    	}
+        
+    DoBindL( aStatement.iStatement, aVariables );
+    }
+
+void CMdSSqLiteConnection::DoBindL( RSqlStatement& aStatement, const RRowData& aVariables )
+    {
+    const TInt count( aVariables.Size() );
+    for( TInt i=0; i < count; ++i )
+        {
+        switch ( aVariables.Column( i ).Type() )
+            {
+            case EColumnInt32:
+                {
+                TInt32 val = 0;
+                aVariables.Column( i ).Get( val );
+                aStatement.BindInt( i, val );
+                break;
+                }
+            case EColumnUint32:
+                {
+                TUint32 val = 0;
+                aVariables.Column( i ).Get( val );
+                aStatement.BindInt64( i, (TInt64)val ); 
+                break;
+                }
+            case EColumnBool:
+                {
+                TBool val = 0;
+                aVariables.Column( i ).Get( val );
+                aStatement.BindInt( i, val );
+                break;
+                }
+            case EColumnInt64:
+                {
+                TInt64 val = 0;
+                aVariables.Column( i ).Get( val );
+                aStatement.BindInt64( i, val );
+                break;
+                }
+            case EColumnReal32:
+                {
+                TReal32 val = 0;
+                aVariables.Column( i ).Get( val );
+                aStatement.BindReal( i, val );
+                break;
+                }
+            case EColumnReal64:
+                {
+                TReal64 val = 0;
+                aVariables.Column( i ).Get( val );
+                aStatement.BindReal( i, val );
+                break;
+                }
+            case EColumnTime:
+                {
+                TTime val = TInt64(0);
+                aVariables.Column( i ).Get( val );
+                aStatement.BindInt64( i, val.Int64() );
+                break;
+                }
+            case EColumnDes16:
+                {
+                TPtrC16 val = TPtr16((TUint16*)0, 0); //KNullPtr16;
+                aVariables.Column( i ).Get( val );
+                aStatement.BindText( i, val );
+                break;
+                }
+            case EColumnNotUsed:
+                // skip this variable
+                break;
+            default:
+#ifdef _DEBUG
+            	User::Panic( _L( "MdSSCDoB" ), KErrCorrupt );
+#endif
+                User::Leave( KErrCorrupt );
+            }
+        }
+    }
+
+TBool CMdSSqLiteConnection::NextRowL( RMdsStatement& aQuery, RRowData& aRow )
+    {
+    const TInt qerr = aQuery.iStatement.Next();
+	if ( qerr == KSqlAtEnd )
+		{
+		return EFalse;
+		}
+	else if ( qerr != KSqlAtRow )
+		{
+		_LIT( KMdsQueryNextRow, "Query NextRow" );
+		TraceAndLeaveL( KMdsQueryNextRow, qerr );
+		}
+
+    // obtain column data into local storage and row data pointer
+    ColumnsL( aQuery.iStatement, aRow );
+
+    return ETrue;
+    }
+
+void CMdSSqLiteConnection::CurrentRowL( const RMdsStatement& aQuery, RRowData& aRow )
+    {
+    // obtain column data into local storage and row data pointer
+    if ( EFalse != aQuery.iStatement.AtRow() )
+    	{
+    	ColumnsL( aQuery.iStatement, aRow );
+    	}
+    else
+    	{
+    	_LIT( KMdsNoProcessableRow, "Wrong row to process" );
+    	TraceAndLeaveL( KMdsNoProcessableRow, KSqlErrNotFound );
+    	}
+    }
+
+void CMdSSqLiteConnection::ColumnsL( const RSqlStatement& aStatement, RRowData& aRow )
+    {
+    const TInt count( aRow.Size() );
+    for( TInt i=0; i < count; ++i )
+        {
+        // get data in column, check for type
+   		const TSqlColumnType actual = aStatement.ColumnType( i );
+   		
+   		if( actual == ESqlNull )
+   			{
+            aRow.Column( i ).Set( (const HBufC16*)NULL );
+
+            continue;
+   			}
+   		
+        const TColumnDataType coltype = aRow.Column( i ).Type();
+        switch ( coltype )
+            {
+            case EColumnBool:
+                {
+                TInt valInt = aStatement.ColumnInt( i );
+                const TBool valBool = valInt ? ETrue : EFalse;
+                aRow.Column( i ).Set( valBool );
+                break;
+                }
+            case EColumnInt32:
+                {
+                TInt32 valInt = aStatement.ColumnInt( i );
+                aRow.Column( i ).Set( valInt );
+                break;
+                }
+            case EColumnUint32:
+                {
+                TInt64 valInt64 = aStatement.ColumnInt64( i );           
+                aRow.Column( i ).Set( (TUint32)valInt64 );
+                break;
+                }
+            case EColumnInt64:
+                {
+                TInt64 valInt64 = aStatement.ColumnInt64( i );
+                aRow.Column( i ).Set( valInt64 );
+                break;
+                }
+            case EColumnReal32:
+                {
+                TReal valReal = aStatement.ColumnReal( i );
+                aRow.Column( i ).Set(  static_cast<TReal32>( valReal ) );
+                break;
+                }
+            case EColumnReal64:
+                {
+                TReal valReal = aStatement.ColumnReal( i );
+                aRow.Column( i ).Set( valReal );
+                break;
+                }
+            case EColumnTime:
+                {
+                TTime valTime = aStatement.ColumnInt64( i );
+                aRow.Column( i ).Set( valTime );
+                break;
+                }
+           	case EColumnDes16:
+           		{
+           		switch ( actual )
+           		{
+           		case ESqlText:
+                    {
+                    TPtrC16 valTPtrC16 = aStatement.ColumnTextL( i );
+                    HBufC16* valHBuf16 = HBufC16::NewL( valTPtrC16.Length() );
+                    *valHBuf16 = valTPtrC16;
+                	aRow.Column( i ).Set( valHBuf16 );
+                	break;
+                    }
+           		case ESqlInt:
+                    {
+                    HBufC16* valHBuf16int32 = HBufC16::NewL( 30 );
+                    TInt valInt = aStatement.ColumnInt( i );
+                    valHBuf16int32->Des().Num( valInt );
+                    aRow.Column( i ).Set( valHBuf16int32 );
+                    break;
+                    }
+           		case ESqlInt64:
+                    {
+                    HBufC16* valHBuf16int64 = HBufC16::NewL( 30 );
+                	TInt64 valInt64 = aStatement.ColumnInt64( i );
+                    valHBuf16int64->Des().Num( valInt64 );
+                    aRow.Column( i ).Set( valHBuf16int64 );
+                    break;
+                    }
+           		case ESqlReal:
+                    {
+                    HBufC16* valHBuf16real64 = HBufC16::NewL( 40 );
+                	TReal valReal = aStatement.ColumnReal( i );
+                	TRealFormat realFormat;
+                	realFormat.iType |= KAllowThreeDigitExp;
+                    valHBuf16real64->Des().Num( valReal, realFormat );
+                    aRow.Column( i ).Set( valHBuf16real64 );
+                    break;
+                    }
+           		case ESqlNull:
+                    {
+                    aRow.Column( i ).Set( (HBufC16*)NULL );
+                    break;
+                    }
+           		default:
+                    {
+#ifdef _DEBUG
+            		User::Panic( _L( "MdSSCCo1" ), KErrCorrupt );
+#endif
+                    User::Leave( KErrCorrupt );
+                    }
+           		}
+           		
+                break;
+                }
+            case EColumnNotUsed:
+                // skip this round
+                break;
+
+            default:
+#ifdef _DEBUG
+				User::Panic( _L( "MdSSCCo2" ), KErrCorrupt );
+#endif
+				User::Leave( KErrCorrupt );
+            }
+        }
+    }
+
+void CMdSSqLiteConnection::Terminate( RMdsStatement& aQuery )
+    {    
+    aQuery.Close();
+    EnableTransaction( ETrue, aQuery );
+    }
+
+void CMdSSqLiteConnection::TransactionBeginL()
+    {
+    if ( !iEnableTransaction || iMdeSqlDb.InTransaction() )
+        {
+        return;
+        }
+    iEnableTransaction = EFalse;
+    iTransactionOngoing = ETrue;
+    _LIT(KBeginTransaction, "BEGIN;");
+    RRowData emptyRow;
+    CleanupClosePushL( emptyRow );
+    TRAPD( err, ExecuteL(KBeginTransaction, emptyRow) );
+    if (err != KErrNone)
+    	{
+    	_LIT( KMdsTransactionBegin, "Transaction begin error" );
+    	TraceAndLeaveL( KMdsTransactionBegin, err );
+    	}
+	CleanupStack::PopAndDestroy( &emptyRow );
+    }
+
+void CMdSSqLiteConnection::TransactionCommitL()
+    {
+    if ( !iTransactionOngoing )
+        {
+        return;
+        }
+    _LIT(KCommit, "COMMIT;");
+    RRowData emptyRow;
+    CleanupClosePushL( emptyRow );
+    TRAPD( err, ExecuteL(KCommit, emptyRow) );
+    if (err != KErrNone)
+    	{
+    	_LIT( KMdsTransactionCommit, "Transaction commit error" );
+    	TraceAndLeaveL( KMdsTransactionCommit, err );
+    	}
+    if( !iNotFinishFindQuery )
+        {
+        iEnableTransaction = ETrue;
+        }
+    iTransactionOngoing = EFalse;
+	CleanupStack::PopAndDestroy( &emptyRow );
+    }
+
+void CMdSSqLiteConnection::TransactionRollbackL()
+    {
+    if ( !iTransactionOngoing )
+        {
+        return;
+        }
+    _LIT(KRollback, "ROLLBACK;");
+    RRowData emptyRow;
+    CleanupClosePushL( emptyRow );
+    TRAPD( err, ExecuteL(KRollback, emptyRow) );
+    if( !iNotFinishFindQuery )
+        {
+        iEnableTransaction = ETrue;
+        }
+    iTransactionOngoing = EFalse;
+    if (err != KErrNone)
+    	{
+    	_LIT( KMdsTransactionRollback, "Transaction rollback error" );
+    	TraceAndLeaveL( KMdsTransactionRollback, err );
+    	}
+	CleanupStack::PopAndDestroy( &emptyRow );
+    }
+
+#ifdef _DEBUG
+void CMdSSqLiteConnection::TraceAndLeaveL( const TDesC& aFailedCommand, TInt aSqliteError )
+    {
+	TPtrC errorMsg = iMdeSqlDb.LastErrorMessage();
+    if ( aFailedCommand.Length() > 0 )
+        {
+        __LOG2( ELogDb, "%S %d", &aFailedCommand, aSqliteError );
+        }
+	__LOG1( ELogDb, "SQLiteError description: %S", &errorMsg );
+    User::Leave( aSqliteError );
+    }
+#else
+void CMdSSqLiteConnection::TraceAndLeaveL( const TDesC& /*aFailedCommand*/, TInt aSqliteError )
+    {
+    User::Leave( aSqliteError );
+    }
+#endif
+
+const TDesC& CMdSSqLiteConnection::DbFileName() const
+	{
+	return *iDbFileName;
+	}
+
+void CMdSSqLiteConnection::EnableTransaction( TBool aEnable, RMdsStatement& aQuery ) 
+    {
+    if( aEnable )
+        {
+        // check whether current query is the query which disabled the transaction when enabling transaction
+        if( !iEnableTransaction && ( iNotFinishFindQuery == &aQuery ) )
+            {
+            if( !iTransactionOngoing )
+                {
+                iEnableTransaction = aEnable;
+                }
+            iNotFinishFindQuery = NULL;
+            }
+        }
+    else
+        {
+        iEnableTransaction = aEnable;
+        // save current find operation which will continue when diable transaction
+        iNotFinishFindQuery = &aQuery;
+        }
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/server/src/mdssqlobjectmanipulate.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,3283 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Add, update and remove items in DB.
+*                 Basic DB manipulation engine.
+*
+*/
+
+#include "mdssqlobjectmanipulate.h"
+
+#include "mdcitem.h"
+#include "mdsdbconnectionpool.h"
+#include "mdssqliteconnection.h"
+#include "mdsfindsqlclausedef.h"
+#include "mdsschema.h"
+#include "mdsnamespacedef.h"
+#include "mdsobjectdef.h"
+#include "mdspropertydef.h"
+#include "mdsclausebuffer.h"
+#include "mdsobjectlocklist.h"
+#include "mdsindexer.h"
+#include "mdspreferences.h"
+#include "mdslogger.h"
+#include "mdcserializationbuffer.h"
+#include "mdssqldbmaintenance.h"
+#include "mdcresult.h"
+#include "mdeinternalerror.h"
+
+#include "mdsgetimeiao.h"
+
+#include <e32math.h>
+
+/** logging instance */
+__USES_LOGGER
+
+const TInt KMaxBuffers = 3;
+
+_LIT( KMemoryCard, "MC" );
+
+
+//------------------------------------------------------------------------------------
+// CLASS      CMdSSqlObjectManipulate
+//------------------------------------------------------------------------------------
+
+CMdSIdentifierGenerator* CMdSIdentifierGenerator::NewL( )
+    {
+    CMdSIdentifierGenerator* self = CMdSIdentifierGenerator::NewLC( );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+CMdSIdentifierGenerator* CMdSIdentifierGenerator::NewLC( )
+    {
+    CMdSIdentifierGenerator* self = new ( ELeave ) CMdSIdentifierGenerator( );
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    return self;
+    }
+
+CMdSIdentifierGenerator::~CMdSIdentifierGenerator()
+    {
+    delete iDigest;
+    }
+
+void CMdSIdentifierGenerator::ConstructL( )
+    {
+    CMdsGetImeiAO * imeigetter = CMdsGetImeiAO::NewLC();
+    iImei = imeigetter->GetIMEI();
+    
+    TTime uTime;
+    uTime.UniversalTime();
+    TInt64 intTime = uTime.Int64();
+    TUint32 rand = Math::Rand( intTime );
+
+    iImei ^= (TInt64)(rand & 0xFF000000) << ( sizeof( TUint32 ) * 8 );
+    
+    CleanupStack::PopAndDestroy(imeigetter);
+    iLastTime = 0;
+    
+    iDigest = CMessageDigestFactory::NewDigestL( CMessageDigest::EMD5 );
+    }
+
+void CMdSIdentifierGenerator::GenerateGuid( TInt64& aGuidHigh, TInt64& aGuidLow )
+	{
+	if (aGuidHigh == 0 && aGuidLow == 0)
+		{
+		TTime currTime;
+		currTime.UniversalTime();
+		const TInt64 tickCount = currTime.Int64();
+		if (iLastTime < tickCount)
+			{
+			iLastTime = tickCount;
+			}
+		else
+			{
+			++iLastTime;
+			}
+
+		//MD5 hash GUID
+		const TInt64 KXorImei = I64LIT( 0x2C3E773D1A25916E );
+		const TInt64 xorImei = iImei ^ KXorImei;
+
+		const TInt KMaxQuidLength = 16;
+		TBuf8<KMaxQuidLength> message;
+		message.SetLength( KMaxQuidLength );
+		Mem::Copy( (TAny*)( message.Ptr() ), &xorImei, sizeof( TInt64 ) );
+		Mem::Copy( (TAny*)( message.Ptr() + sizeof( TInt64 ) ), &iLastTime, sizeof( TInt64 ) );
+
+		TPtrC8 hash = iDigest->Final( message );
+
+		__ASSERT_DEBUG( hash.Size() >= KMaxQuidLength, User::Panic( _L("CMdSIdentifierGenerator::GenerateGuid"), KErrGeneral ) );
+
+		Mem::Copy( &aGuidHigh, hash.Ptr(), sizeof( TInt64 ) );
+		Mem::Copy( &aGuidLow, hash.Ptr() + sizeof( TInt64 ), sizeof( TInt64 ) );
+		//MD5 hash GUID end
+		}
+	}
+
+HBufC* CMdSIdentifierGenerator::GenerateUriL( const CMdsObjectDef& aObjectDef, 
+		const TInt64& aGuidHigh, const TInt64& aGuidLow ) const
+	{
+	_LIT( KDot, "." );
+	HBufC* uri = HBufC::NewLC( aObjectDef.GetName().Length() + 2 /*two dots*/+ 
+			2*KMaxUint64ValueLength );
+
+	TPtr uriPtr( uri->Des() );
+	uriPtr.Append( aObjectDef.GetName() );
+	uriPtr.Append( KDot );
+	uriPtr.AppendNum( aGuidHigh );
+	uriPtr.Append( KDot );
+	uriPtr.AppendNum( aGuidLow );
+	CleanupStack::Pop( uri );
+	return uri;
+	}
+
+
+//-----------------------------------------------------------------------------
+// CLASS      CMdSSqlObjectManipulate
+//-----------------------------------------------------------------------------
+
+CMdSSqlObjectManipulate* CMdSSqlObjectManipulate::NewL( 
+		const CMdsSchema& aSchema, CMdSObjectLockList& aLockList )
+    {
+    CMdSSqlObjectManipulate* self = CMdSSqlObjectManipulate::NewLC( aSchema, 
+    		aLockList );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+CMdSSqlObjectManipulate* CMdSSqlObjectManipulate::NewLC( 
+		const CMdsSchema& aSchema, CMdSObjectLockList& aLockList )
+    {
+    CMdSSqlObjectManipulate* self = new ( ELeave ) CMdSSqlObjectManipulate( 
+    		aSchema, aLockList );
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    return self;
+    }
+
+CMdSSqlObjectManipulate::~CMdSSqlObjectManipulate()
+    {
+    // doesn't own namespace definition
+	iNamespaceDef = NULL;
+
+	const TInt count = iBuffers.Count();
+	
+	for (TInt i = 0; i < count; ++i)
+		{
+		delete iBuffers[i].iBuffer;
+		}
+	iBuffers.Close();
+
+	delete iGenerator;
+    }
+
+CMdSSqlObjectManipulate::CMdSSqlObjectManipulate( const CMdsSchema& aSchema, 
+		CMdSObjectLockList& aLockList )
+	: iSchema( aSchema ), iGenerator(NULL), iLockList( aLockList ) 
+    {
+    }
+
+void CMdSSqlObjectManipulate::ConstructL( )
+    {
+    
+	iGenerator = CMdSIdentifierGenerator::NewL();
+
+	iNamespaceDef = NULL;
+	
+	TLockBuffer lockBuffer;
+	lockBuffer.iLock = EFalse;
+	for (TInt i = 0; i < KMaxBuffers; ++i)
+		{
+	    CMdsClauseBuffer* buffer = CMdsClauseBuffer::NewLC( 1024 );
+		lockBuffer.iBuffer = buffer;
+		iBuffers.AppendL( lockBuffer );
+		CleanupStack::Pop(); // buffer
+		}
+
+    }
+
+TBool CMdSSqlObjectManipulate::GarbageCollectionL()
+	{
+	return DoGarbageCollectionL();
+	}
+
+void CMdSSqlObjectManipulate::SetNamespace( 
+		const CMdsNamespaceDef* aNamespaceDef )
+	{
+	iNamespaceDef = aNamespaceDef;
+	}
+
+void CMdSSqlObjectManipulate::AddMemoryCardL(TUint32 aMediaId)
+	{
+	TTime currentTime;
+	currentTime.UniversalTime();
+
+	TInt modifiedRowCount = MMdsPreferences::UpdateL( KMemoryCard, 
+			MMdsPreferences::EPreferenceExtraSet, aMediaId, 
+			currentTime.Int64() );
+
+	if( modifiedRowCount <= 0 )
+		{
+		MMdsPreferences::InsertL( KMemoryCard, 
+								  MMdsPreferences::EPreferenceBothSet, 
+								  aMediaId, currentTime.Int64() );
+		}
+	}
+
+void CMdSSqlObjectManipulate::GetMemoryCardL(TUint32& aMediaId)
+	{
+	TInt rowCount = MMdsPreferences::GetL( KMemoryCard, 
+										   MMdsPreferences::EPreferenceValueGet | MMdsPreferences::EPreferenceExtraSortDesc, 
+								  		   aMediaId );
+
+	// if no rows found leave
+	if( rowCount <= 0 )
+		{
+		User::Leave( KErrNotFound );
+		}
+	}
+
+TBool CMdSSqlObjectManipulate::CheckMemoryCardL(TUint32 aMediaId)
+	{
+	TInt rowCount = MMdsPreferences::GetL( KMemoryCard, 
+										   MMdsPreferences::EPreferenceValueGet | MMdsPreferences::EPreferenceValueSet, 
+								  		   aMediaId );
+
+	if( rowCount > 0 )
+		{
+		return ETrue;
+		}
+	return EFalse;
+	}
+
+
+void CMdSSqlObjectManipulate::SetMediaL(TUint32 aMediaId, TChar aDrive,
+		TBool aPresentState)
+	{
+	_LIT( KInsertMedia, "INSERT OR REPLACE INTO MdS_Medias VALUES(?,?,?,?);" );
+
+	RClauseBuffer commonClause( *this, KInsertMedia.iTypeLength );
+	CleanupClosePushL( commonClause );
+	CMdsClauseBuffer& clauseBuffer = commonClause.BufferL();
+	clauseBuffer.BufferL() = KInsertMedia;
+
+	TTime currentTime;
+	currentTime.UniversalTime();
+	const TInt64 currentTime64 = currentTime.Int64();
+	
+    RRowData var;
+    CleanupClosePushL( var );
+    var.ReserveL( 4 ); // reserve space for media ID, drive, present state and time
+    var.AppendL( TColumn( aMediaId ) );
+    var.AppendL( TColumn( (TInt32)aDrive ) );
+    var.AppendL( TColumn( aPresentState ) );
+    var.AppendL( TColumn( currentTime64 ) );
+
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	connection.ExecuteL( clauseBuffer.ConstBufferL(), var );
+
+	CleanupStack::PopAndDestroy( 2, &commonClause ); // var, commonClauseOne
+	}
+
+TBool CMdSSqlObjectManipulate::GetMediaL(TUint32 aMediaId, TChar& aDrive, 
+		TBool& aPresentState)
+	{
+	_LIT( KGetMedia, "SELECT Drive, PresentState FROM MdS_Medias WHERE MediaId=?;" );
+
+	RClauseBuffer commonClause( *this, KGetMedia.iTypeLength );
+	CleanupClosePushL( commonClause );
+	CMdsClauseBuffer& clauseBuffer = commonClause.BufferL();
+	clauseBuffer.BufferL() = KGetMedia;
+
+    RRowData var;
+    CleanupClosePushL( var );
+    var.AppendL( TColumn( aMediaId ) );
+
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	RMdsStatement statement;
+	CleanupClosePushL( statement );
+	connection.ExecuteQueryL( clauseBuffer.ConstBufferL(), statement, var );
+
+	var.Free();
+	var.Reset();
+
+	TInt32 drive = 0;
+	
+    var.ReserveL( 2 ); // reserve space for drive and present state
+	var.AppendL( TColumn( drive ) );
+	var.AppendL( TColumn( aPresentState ) );
+
+	TBool found = EFalse;
+
+	if( connection.NextRowL( statement, var ) )
+		{
+		var.Column( 0 ).Get( drive );
+		var.Column( 1 ).Get( aPresentState );
+		
+		aDrive = drive;
+		
+		found = ETrue;
+		}
+
+	CleanupStack::PopAndDestroy( 3, &commonClause ); // statement, var, commonClauseOne
+
+	return found;
+	}
+
+TInt32 CMdSSqlObjectManipulate::GetPresentMediasL(TDes8& aMediaInfoBuffer)
+	{
+	_LIT( KGetPresentMedias, "SELECT MediaId, Drive FROM MdS_Medias WHERE PresentState!=?;" );
+
+	RClauseBuffer commonClause( *this, KGetPresentMedias.iTypeLength );
+	CleanupClosePushL( commonClause );
+	CMdsClauseBuffer& clauseBuffer = commonClause.BufferL();
+	clauseBuffer.BufferL() = KGetPresentMedias;
+
+	const TBool notPresentState = EFalse;
+
+    RRowData var;
+    CleanupClosePushL( var );
+    var.AppendL( TColumn( notPresentState ) );
+
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	RMdsStatement statement;
+	CleanupClosePushL( statement );
+	connection.ExecuteQueryL( clauseBuffer.ConstBufferL(), statement, var );
+
+	var.Free();
+	var.Reset();
+
+	TUint32 mediaId = 0;
+	TInt32 drive = 0;
+
+    var.ReserveL( 2 ); // reserve space for drive and present state
+	var.AppendL( TColumn( mediaId ) );
+	var.AppendL( TColumn( drive ) );
+
+	TInt32 count = 0;
+
+	TInt bufferPosition = 0;
+	
+	const TInt lastBufferPosition = aMediaInfoBuffer.MaxSize() - sizeof( TMdEMediaInfo );
+
+	const TUint8* aMediaInfoBufferPtr = aMediaInfoBuffer.Ptr();
+	
+	while( connection.NextRowL( statement, var ) )
+		{
+		var.Column( 0 ).Get( mediaId );
+		var.Column( 1 ).Get( drive );
+		
+		TMdEMediaInfo mediaInfo;
+		mediaInfo.iMediaId = mediaId;
+		mediaInfo.iDrive = drive;
+
+		if( bufferPosition > lastBufferPosition )
+			{
+			User::Leave( KErrBadDescriptor );
+			}
+	
+		TUint8* ptr = (TUint8*)( aMediaInfoBufferPtr + bufferPosition );
+		
+		Mem::Copy( ptr, &mediaInfo, sizeof( TMdEMediaInfo ) );
+		
+		bufferPosition += sizeof( TMdEMediaInfo );
+		
+		++count;
+		}
+	
+	aMediaInfoBuffer.SetLength( bufferPosition );
+
+	CleanupStack::PopAndDestroy( 3, &commonClause ); // statement, var, commonClauseOne
+
+	return count;
+	}
+
+TItemId CMdSSqlObjectManipulate::SearchNotPresentFileL(TUint32 aMediaId, 
+		TDesC16& aUri, TMdSFileInfo& aFileInfo,
+		TFilePresentStates& aPlaceHolder, TBool& aNotPresentState)
+	{
+	_LIT( KSearchNotPresentFile, "SELECT ObjectId, Flags, LastModifiedDate, Size FROM Object%u WHERE NOT Flags&? AND (Flags&? OR Flags&? OR Flags&? ) AND MediaId=? AND URI=?;" );
+
+	RClauseBuffer commonClauseOne(*this, KSearchNotPresentFile.iTypeLength + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& clauseBuffer = commonClauseOne.BufferL();
+	clauseBuffer.BufferL().Format( KSearchNotPresentFile, KDefaultNamespaceDefId );
+
+	TItemId objectId = KNoId;
+	TUint32 flags = 0;
+
+    RRowData var;
+    CleanupClosePushL( var );
+    var.ReserveL( 5 );
+    var.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+    var.AppendL( TColumn( EMdEObjectFlagNotPresent ) ); // not present flag
+    var.AppendL( TColumn( EMdEObjectFlagStartUpNotPresent ) ); // start up not present flag
+    var.AppendL( TColumn( EMdeObjectFlagPending ) ); // pending for composing - needed to complete composing
+    var.AppendL( TColumn( aMediaId ) );
+    var.AppendL( TColumn( aUri ) );
+
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	RMdsStatement statement;
+	CleanupClosePushL( statement );
+    connection.ExecuteQueryL( clauseBuffer.ConstBufferL(), statement, var );
+
+    TInt64 modifiedTime(0);
+    TUint32 size(0);
+
+    RRowData result;
+    CleanupClosePushL( result );
+    result.ReserveL( 4 );
+    result.AppendL( TColumn( objectId ) );
+    result.AppendL( TColumn( flags ) );
+    result.AppendL( TColumn( modifiedTime ) );
+    result.AppendL( TColumn( size ) );
+
+    // default values (used if object doesn't exist)
+	aPlaceHolder = EMdsNotFound;
+	aNotPresentState = EFalse;
+
+	if( connection.NextRowL( statement, result ) )
+		{
+		result.Column( 0 ).Get( objectId );
+		result.Column( 1 ).Get( flags );
+
+		if ( flags & EMdEObjectFlagPlaceholder )
+			{
+			aPlaceHolder = EMdsPlaceholder;
+			}
+		else
+			{
+			result.Column( 2 ).Get( modifiedTime );
+			result.Column( 3 ).Get( size );
+
+			// check if file is modified
+    		if ( ( aFileInfo.iModifiedTime == modifiedTime ) && ( aFileInfo.iSize == size ) )
+    			{
+    			aPlaceHolder = EMdsNormal;
+    			
+    	        // If images were pending for composing, composer needs to be notified for the composing to complete 
+    	        if( (flags & EMdeObjectFlagPending) && (flags & EMdEObjectFlagStartUpNotPresent) )
+    	            {
+    	            aNotPresentState = ETrue;
+    	            }
+    			}
+    		else
+    			{
+    			aPlaceHolder = EMdsModified;
+    			}
+			}
+
+		if( flags & EMdEObjectFlagNotPresent )
+			{
+			aNotPresentState = ETrue;
+			}
+		}
+
+	CleanupStack::PopAndDestroy( &result );
+	CleanupStack::PopAndDestroy( &statement );
+	CleanupStack::PopAndDestroy( &var );
+	CleanupStack::PopAndDestroy( &commonClauseOne );
+	return objectId;
+	}
+
+void CMdSSqlObjectManipulate::SetFilesToPresentL(const RArray<TItemId>& aObjectIds)
+	{
+	const TInt objectCount = aObjectIds.Count();
+    if ( objectCount > 0 )
+    	{
+		_LIT( KSetFileToPresent, "UPDATE Object%u SET Flags=Flags&? WHERE (Flags&?)<>0 AND ObjectId IN (?" );
+		_LIT( KCommaQuestionmark, ",?");
+		_LIT( KBracketSemicolon, ");");
+		
+		RClauseBuffer commonClauseOne(*this, KSetFileToPresent.iTypeLength + KMaxUintValueLength +
+				( KCommaQuestionmark.iTypeLength * ( objectCount-1 ) ) +
+				KBracketSemicolon.iTypeLength );
+		CleanupClosePushL( commonClauseOne );
+		CMdsClauseBuffer& clauseBuffer = commonClauseOne.BufferL();
+		clauseBuffer.BufferL().Format( KSetFileToPresent, KDefaultNamespaceDefId );
+
+	    RRowData var;
+	    CleanupClosePushL( var );
+	    // reset not present and start up not present flags
+	    var.AppendL( TColumn( ~(EMdEObjectFlagNotPresent | EMdEObjectFlagStartUpNotPresent) ) );
+	    var.AppendL( TColumn( (EMdEObjectFlagNotPresent | EMdEObjectFlagStartUpNotPresent) ) );
+	    var.AppendL( TColumn( aObjectIds[0] ) );
+
+	    for ( TInt i = 1; i < objectCount; i++ )
+	    	{
+	    	clauseBuffer.AppendL( KCommaQuestionmark );
+		    var.AppendL( TColumn( aObjectIds[i] ) );
+	    	}
+	    
+	    clauseBuffer.AppendL( KBracketSemicolon );
+	    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	    connection.ExecuteL( clauseBuffer.ConstBufferL(), var );
+	
+		CleanupStack::PopAndDestroy( &var );
+		CleanupStack::PopAndDestroy( &commonClauseOne ); 
+    	}
+	}
+
+void CMdSSqlObjectManipulate::SetRelationsToPresentL(TItemId aObjectId, 
+		RArray<TItemId>& aIdArray)
+	{
+	_LIT( KSearchNotPresentRelations, "SELECT RelationId FROM Relations%u WHERE NOT Flags&? AND Flags&? AND (LeftObjectId=? OR RightObjectId=?);" );
+	_LIT( KSetRelationsToPresent, "UPDATE Relations%u SET Flags=Flags&? WHERE Flags&? AND (LeftObjectId=? OR RightObjectId=?);" );
+
+	RClauseBuffer commonClauseOne(*this, KSearchNotPresentRelations.iTypeLength + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& clauseBuffer = commonClauseOne.BufferL();
+	clauseBuffer.BufferL().Format( KSearchNotPresentRelations, KDefaultNamespaceDefId );
+
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+    RRowData var;
+    CleanupClosePushL( var );
+    
+    var.ReserveL( 4 ); // reserve space for flags and object IDs
+    var.AppendL( TColumn( EMdERelationFlagDeleted ) );
+    var.AppendL( TColumn( EMdERelationFlagNotPresent ) );
+    var.AppendL( TColumn( aObjectId ) );
+    var.AppendL( TColumn( aObjectId ) );
+
+	RMdsStatement statement;
+	CleanupClosePushL( statement );
+	connection.ExecuteQueryL( clauseBuffer.ConstBufferL(), statement, var );
+
+	var.Free();	var.Reset();
+    TItemId relationId(0);
+    var.AppendL( TColumn( relationId ) );
+	while( connection.NextRowL( statement, var ) )
+		{
+		var.Column( 0 ).Get( relationId );
+		aIdArray.AppendL( relationId );
+		}
+
+	clauseBuffer.ReserveSpaceL( KSetRelationsToPresent.iTypeLength + KMaxUintValueLength );
+	clauseBuffer.BufferL().Format( KSetRelationsToPresent, KDefaultNamespaceDefId );
+
+    var.Free(); 
+    var.Reset();
+
+    var.AppendL( TColumn( ~EMdERelationFlagNotPresent ) ); // reset not present flag
+    var.AppendL( TColumn( EMdERelationFlagNotPresent ) );
+    var.AppendL( TColumn( aObjectId ) );
+    var.AppendL( TColumn( aObjectId ) );
+
+    connection.ExecuteL( clauseBuffer.ConstBufferL(), var );
+
+	CleanupStack::PopAndDestroy( 3, &commonClauseOne ); // statement, var, clauseBuffer
+	}
+
+void CMdSSqlObjectManipulate::SetFilesToNotPresentL(TUint32 aMediaId, TBool aStartUp,
+		RArray<TItemId>& aObjectIds)
+	{
+	
+	_LIT( KSearchPresentFilesStartUpL, "SELECT ObjectId FROM Object%u WHERE NOT Flags&? AND MediaId=?;" );
+	_LIT( KSearchPresentFilesL, "SELECT ObjectId FROM Object%u WHERE NOT Flags&? AND NOT Flags&? AND MediaId=?;" );
+	
+	RClauseBuffer commonClauseOne(*this, ( aStartUp ? KSearchPresentFilesStartUpL.iTypeLength : KSearchPresentFilesL.iTypeLength )+ 
+			KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& clauseBuffer = commonClauseOne.BufferL();
+	
+	if( aStartUp )
+		{
+		clauseBuffer.BufferL().Format( KSearchPresentFilesStartUpL, KDefaultNamespaceDefId );
+		}
+	else
+		{
+		clauseBuffer.BufferL().Format( KSearchPresentFilesL, KDefaultNamespaceDefId );
+		}
+
+	TItemId objectId = 0;
+
+    RRowData var;
+    CleanupClosePushL( var );
+    
+    var.ReserveL( 3 ); // reserve space for flags and media ID
+    var.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+    if ( !aStartUp )
+    	{
+    	var.AppendL( TColumn( EMdEObjectFlagNotPresent ) ); // present flag
+    	}
+    var.AppendL( TColumn( aMediaId ) );
+
+	RMdsStatement statement;
+	CleanupClosePushL( statement );
+
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+    connection.ExecuteQueryL( clauseBuffer.ConstBufferL(), statement, var );
+
+    var.Free(); 
+    var.Reset();
+
+    var.AppendL( TColumn( objectId ) );
+	while( connection.NextRowL( statement, var ) )
+		{
+		var.Column( 0 ).Get( objectId );
+		aObjectIds.AppendL( objectId );
+		}
+
+	_LIT( KSetFilesToNotPresent, "UPDATE Object%u SET Flags=Flags|? WHERE MediaId=?;" );
+	clauseBuffer.ReserveSpaceL( 
+			KSetFilesToNotPresent.iTypeLength + 
+			KMaxUintValueLength ); // TUint32 max value's lenght is 10 numbers so %u + 8
+	clauseBuffer.BufferL().Format( KSetFilesToNotPresent, KDefaultNamespaceDefId );
+
+	var.Free(); 
+	var.Reset();
+
+	if( aStartUp )
+		{
+		var.AppendL( TColumn( EMdEObjectFlagStartUpNotPresent ) ); // set not present flag
+		}
+	else 
+		{
+		var.AppendL( TColumn( EMdEObjectFlagNotPresent ) ); // set not present flag
+		}
+	var.AppendL( TColumn( aMediaId ) );
+
+    connection.ExecuteL( clauseBuffer.ConstBufferL(), var );
+
+    // statement, var, commonClauseOne
+	CleanupStack::PopAndDestroy( 3, &commonClauseOne );
+	}
+
+void CMdSSqlObjectManipulate::SetRelationsToNotPresentL(
+		TUint32 aMediaId, RArray<TItemId>& aRelationIds)
+	{
+	_LIT( KSearchPresentRelations, "SELECT DISTINCT A.RelationId FROM Relations%u AS A LEFT JOIN object%u AS B On A.LeftObjectId = B.ObjectId OR A.RightObjectId = B.ObjectId WHERE NOT A.Flags&%u AND NOT A.Flags&%u AND B.MediaId=%u" );
+	_LIT( KSetRelationsToPresent, "UPDATE Relations%u SET Flags=Flags|? WHERE NOT Flags&? AND RelationId IN (%S);" );
+
+	// RelationIDs query sql statement
+	RClauseBuffer commonClauseOne(*this, 
+			KSearchPresentRelations.iTypeLength + 
+			KMaxUintValueLength  );
+    CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& clauseBufferOne = commonClauseOne.BufferL();
+	clauseBufferOne.BufferL().Format( KSearchPresentRelations, 
+                KDefaultNamespaceDefId,
+                KDefaultNamespaceDefId,
+                EMdERelationFlagDeleted,
+                EMdERelationFlagNotPresent,
+                aMediaId );
+	
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+    	
+    RRowData var;
+    CleanupClosePushL( var );
+    
+	RMdsStatement statement;
+	CleanupClosePushL( statement );
+
+	connection.ExecuteQueryL( clauseBufferOne.ConstBufferL(), statement, var );
+
+    // Get RelationIDs From query result
+    TItemId relationId(0);
+    var.AppendL( TColumn( relationId ) );
+	while( connection.NextRowL( statement, var ) )
+		{
+		var.Column( 0 ).Get( relationId );
+		aRelationIds.AppendL( relationId );
+		}
+	
+    // Set objects' relations not present by MediaID
+	RClauseBuffer commonClauseTwo(*this, 
+			KSetRelationsToPresent.iTypeLength + 
+			clauseBufferOne.ConstBufferL().Length() );
+	
+    CleanupClosePushL( commonClauseTwo );
+	CMdsClauseBuffer& clauseBufferTwo = commonClauseTwo.BufferL();
+	clauseBufferTwo.BufferL().Format( KSetRelationsToPresent, 
+                                   KDefaultNamespaceDefId,
+                                   &clauseBufferOne.ConstBufferL() );
+
+	var.Free();
+	var.Reset();
+    var.ReserveL( 2 ); 
+    var.AppendL( TColumn( EMdERelationFlagNotPresent ) );
+    var.AppendL( TColumn( EMdERelationFlagNotPresent ) );
+
+    connection.ExecuteL( clauseBufferTwo.ConstBufferL(), var );
+
+    // commonClauseTwo, statement, var, commonClauseOne
+	CleanupStack::PopAndDestroy( 4, &commonClauseOne );
+	}
+
+void CMdSSqlObjectManipulate::RemoveFilesNotPresentL(TUint32 aMediaId, RArray<TItemId>* aObjectIds)
+	{
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	
+	// collect object IDs from start up not present objects
+	if( aObjectIds )
+		{
+		_LIT( KSelectFilesStartUpNotPresent, "SELECT ObjectId FROM Object%u WHERE NOT Flags&? AND NOT Flags&? AND Flags&? AND MediaId=?;" );
+
+		RClauseBuffer commonClauseOne(*this, 
+				KSelectFilesStartUpNotPresent.iTypeLength + KMaxUintValueLength );
+		CleanupClosePushL( commonClauseOne );
+		CMdsClauseBuffer& clauseBuffer = commonClauseOne.BufferL();
+
+		clauseBuffer.BufferL().Format( KSelectFilesStartUpNotPresent, KDefaultNamespaceDefId );
+
+		RRowData var;
+		CleanupClosePushL( var );
+		var.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+		var.AppendL( TColumn( EMdEObjectFlagNotPresent ) );
+		var.AppendL( TColumn( EMdEObjectFlagStartUpNotPresent ) );
+		var.AppendL( TColumn( aMediaId ) );
+
+		RMdsStatement statement;
+		CleanupClosePushL( statement );
+	    connection.ExecuteQueryL( clauseBuffer.ConstBufferL(), statement, var );
+
+		RRowData result;
+	    CleanupClosePushL( result );
+	    TItemId objectId( KNoId );
+	    result.AppendL( TColumn( objectId ) );
+
+		while( connection.NextRowL( statement, result ) )
+			{
+			result.Column( 0 ).Get( objectId );
+			aObjectIds->AppendL( objectId );
+			}
+
+		CleanupStack::PopAndDestroy( &result );
+		CleanupStack::PopAndDestroy( &statement );
+		CleanupStack::PopAndDestroy( &var );
+		CleanupStack::PopAndDestroy( &commonClauseOne );
+		}
+
+	_LIT( KRemoveFilesNotPresent, "UPDATE Object%u SET Flags=Flags|? WHERE NOT Flags&? AND (Flags&? OR Flags&?) AND MediaId=?;" );
+
+	RClauseBuffer commonClauseOne(*this, 
+			KRemoveFilesNotPresent.iTypeLength + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& clauseBuffer = commonClauseOne.BufferL();
+	clauseBuffer.BufferL().Format( KRemoveFilesNotPresent, KDefaultNamespaceDefId );
+
+    RRowData var;
+    CleanupClosePushL( var );
+    var.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+    var.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+    var.AppendL( TColumn( EMdEObjectFlagNotPresent ) ); // not present flag
+    var.AppendL( TColumn( EMdEObjectFlagStartUpNotPresent ) ); // start up not present flag
+    var.AppendL( TColumn( aMediaId ) );
+
+	__LOGQUERY_16( _L("RemoveFilesNotPresentL:"), clauseBuffer.ConstBufferL(), var);
+    connection.ExecuteL( clauseBuffer.ConstBufferL(), var );
+
+	CleanupStack::PopAndDestroy( 2, &commonClauseOne ); // var, commonClauseOne
+	}
+
+void CMdSSqlObjectManipulate::GetSchemaVersionL(
+		TInt& aMajorVersion, TInt& aMinorVersion)
+	{
+	TInt64 minorVersion;
+	TInt rowCount = MMdsPreferences::GetL( KMdsSchemaVersionName, 
+			MMdsPreferences::EPreferenceBothGet, 
+			aMajorVersion, &minorVersion );
+
+	aMinorVersion = minorVersion;
+
+	// if no rows found leave
+	if( rowCount <= 0 )
+		{
+		User::Leave( KErrNotFound );
+		}
+	}
+
+void CMdSSqlObjectManipulate::SetObjectToPresentByGuidL( 
+		const TInt64& aGuidHigh, const TInt64& aGuidLow )
+	{
+	// get object ID for later queries
+	_LIT( KGetObjectIdByGuid, "SELECT ObjectId FROM Object%u WHERE Flags&? AND GuidHigh=? AND GuidLow=?;" );
+
+	RClauseBuffer commonClauseOne(*this, 
+			KGetObjectIdByGuid.iTypeLength + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& clauseBuffer = commonClauseOne.BufferL();
+	clauseBuffer.BufferL().Format( KGetObjectIdByGuid, KDefaultNamespaceDefId );
+
+    RRowData var;
+    CleanupClosePushL( var );
+    var.ReserveL( 3 ); // for flags and GUID high/low in WHERE
+
+    var.AppendL( TColumn( (TUint32)EMdEObjectFlagNotPresent ) );
+    var.AppendL( TColumn( aGuidHigh ) );
+    var.AppendL( TColumn( aGuidLow ) );
+
+	RMdsStatement statement;
+	CleanupClosePushL( statement );
+
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	__LOGQUERY_16( _L("SetObjectToPresentByGuidL q1:"), clauseBuffer.ConstBufferL(), var);
+
+    connection.ExecuteQueryL( clauseBuffer.ConstBufferL(), statement, var );
+
+	var.Free();
+	var.Reset();
+	TItemId objectId = KNoId;
+	var.AppendL( TColumn( objectId ) );
+
+	if( connection.NextRowL( statement, var ) )
+		{
+		var.Column( 0 ).Get( objectId );
+
+		// set object, which object ID is matching, to present state
+		_LIT( KSetObjectToPresentByGuid, "UPDATE Object%u SET Flags=Flags&? WHERE ObjectId=? AND (Flags&?)<>0;" );
+
+		RClauseBuffer commonClauseTwo(*this, 
+				KSetObjectToPresentByGuid.iTypeLength + KMaxUintValueLength);
+		CleanupClosePushL( commonClauseTwo );
+		CMdsClauseBuffer& clauseBuffer2 = commonClauseTwo.BufferL();
+		clauseBuffer2.BufferL().Format( KSetObjectToPresentByGuid, 
+				KDefaultNamespaceDefId );
+
+		var.Free();
+		var.Reset();
+		var.AppendL( TColumn( (TUint32)~EMdEObjectFlagNotPresent ) );
+		var.AppendL( TColumn( objectId ) );
+		
+		var.AppendL( TColumn( (TUint32)EMdEObjectFlagNotPresent ) );
+
+		__LOGQUERY_16( _L("SetObjectToPresentByGuidL q2:"), 
+				clauseBuffer2.ConstBufferL(), var);
+		
+		connection.ExecuteL( clauseBuffer2.ConstBufferL(), var );
+		
+		CleanupStack::PopAndDestroy( &commonClauseTwo );
+
+		// set relations, which left or right object ID is matching, 
+		// to present state
+		_LIT( KSetRelationToPresentByGuid, "UPDATE Relations%u SET Flags=Flags&? WHERE LeftObjectId=? OR RightObjectId=?;" );
+		
+		RClauseBuffer commonClauseThree(*this, 
+				KSetRelationToPresentByGuid.iTypeLength + KMaxUintValueLength);
+		CleanupClosePushL( commonClauseThree );
+		CMdsClauseBuffer& clauseBuffer3 = commonClauseThree.BufferL();
+		clauseBuffer3.BufferL().Format( KSetRelationToPresentByGuid, 
+				KDefaultNamespaceDefId );
+
+		var.Free();
+		var.Reset();
+		var.AppendL( TColumn( (TUint32)~EMdERelationFlagNotPresent ) );
+		var.AppendL( TColumn( objectId ) );
+		var.AppendL( TColumn( objectId ) );
+
+		__LOGQUERY_16( _L("SetObjectToPresentByGuidL q3:"), 
+				clauseBuffer3.ConstBufferL(), var);
+
+		connection.ExecuteL( clauseBuffer3.ConstBufferL(), var );
+		
+		CleanupStack::PopAndDestroy( &commonClauseThree );
+		}
+	// no any matching object
+	else
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	CleanupStack::PopAndDestroy( 3, &commonClauseOne ); // statement, var, commonClauseOne
+	}
+
+void CMdSSqlObjectManipulate::ChangePathL(
+		const TDesC& aOldPath, const TDesC& aNewPath, 
+		RArray<TItemId>& aObjectIds)
+	{
+	// collect object IDs from object which match to the old path
+	_LIT( KGetObjectIdByBeginOfUri, "SELECT ObjectId FROM Object%u WHERE NOT Flags&? AND substr(URI, 1, ?) = ?;" );
+
+	RClauseBuffer commonClauseOne(*this, 
+			KGetObjectIdByBeginOfUri.iTypeLength + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& clauseBuffer = commonClauseOne.BufferL();
+	clauseBuffer.BufferL().Format( KGetObjectIdByBeginOfUri, KDefaultNamespaceDefId );
+
+	const TUint32 flags = EMdEObjectFlagNotPresent | EMdEObjectFlagRemoved | EMdEObjectFlagGarbage;
+
+	const TInt oldPathLength = aOldPath.Length();
+
+	RRowData var;
+    CleanupClosePushL( var );
+	var.ReserveL( 3 );
+    var.AppendL( TColumn( flags ) );
+    var.AppendL( TColumn( oldPathLength ) );
+    var.AppendL( TColumn( aOldPath ) );
+
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	RMdsStatement statement;
+	CleanupClosePushL( statement );
+
+	__LOGQUERY_16( _L("ChangePathL q1:"), clauseBuffer.ConstBufferL(), var);
+
+    connection.ExecuteQueryL( clauseBuffer.ConstBufferL(), statement, var );
+
+    var.Free();
+    var.Reset();
+    TItemId objectId( 0 );
+    var.AppendL( TColumn( objectId ) );
+
+	while( connection.NextRowL( statement, var ) )
+		{
+		var.Column( 0 ).Get( objectId );
+		aObjectIds.AppendL( objectId );
+		}
+
+	// update the new path to objects which match with the old path
+	_LIT( KChangeOldPathToNewPath, "UPDATE Object%u SET URI=? || substr(URI, ?, length(URI)) WHERE NOT Flags&? AND substr(URI, 1, ?) = ?;" );
+
+	RClauseBuffer commonClauseTwo(*this, 
+			KChangeOldPathToNewPath.iTypeLength + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseTwo );
+	CMdsClauseBuffer& clauseBuffer2 = commonClauseTwo.BufferL();
+	clauseBuffer2.BufferL().Format( KChangeOldPathToNewPath, KDefaultNamespaceDefId );
+
+	var.Free();
+	var.Reset();
+
+	var.ReserveL( 5 );
+    var.AppendL( TColumn( aNewPath ) );
+    var.AppendL( TColumn( oldPathLength + 1 ) );
+    var.AppendL( TColumn( flags ) );
+    var.AppendL( TColumn( oldPathLength ) );
+    var.AppendL( TColumn( aOldPath ) );
+
+	__LOGQUERY_16( _L("ChangePathL q2:"), clauseBuffer2.ConstBufferL(), var);
+
+	connection.ExecuteL( clauseBuffer2.ConstBufferL(), var );
+
+	CleanupStack::PopAndDestroy( 4, &commonClauseOne ); // commonClauseTwo, statement, var, commonClauseOne
+	}
+
+void CMdSSqlObjectManipulate::ChangeMediaIdL()
+	{
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	
+	TVolumeInfo volumeInfo;
+	RFs fs;
+	User::LeaveIfError( fs.Connect() );
+	CleanupClosePushL( fs );
+
+	fs.Volume( volumeInfo, EDriveC );
+	CleanupStack::PopAndDestroy( &fs );
+
+	// update the new media id to objects which match with the old id
+	_LIT( KChangeOldIdToNewId, "UPDATE Object%u SET MediaId=? WHERE NOT Flags&? AND MediaId = (SELECT Value FROM MdE_Preferences WHERE Key=?);" );
+
+	RClauseBuffer clauseOne( *this, KChangeOldIdToNewId.iTypeLength + KMaxUintValueLength );
+	CleanupClosePushL( clauseOne );
+	CMdsClauseBuffer& clauseBuffer = clauseOne.BufferL();
+	clauseBuffer.BufferL().Format( KChangeOldIdToNewId, KDefaultNamespaceDefId );
+
+	const TUint32 flags = EMdEObjectFlagNotPresent | EMdEObjectFlagRemoved | EMdEObjectFlagGarbage;
+
+	RRowData var;
+	CleanupClosePushL( var );
+
+	var.ReserveL( 3 );
+	var.AppendL( TColumn( (TUint32) volumeInfo.iUniqueID ) );
+	var.AppendL( TColumn( flags ) );
+	var.AppendL( TColumn( KCMediaIdKey ) );
+
+	__LOGQUERY_16( _L("ChangeMediaIdL q2:"), clauseBuffer.ConstBufferL(), var);
+
+	connection.ExecuteL( clauseBuffer.ConstBufferL(), var );
+	
+	// update the new media id to objects which match with the old id
+	_LIT( KUpdateMediaId, "UPDATE MdE_Preferences SET Value=? WHERE Key = ?;" );
+	
+	var.Free();
+	var.Reset();
+	
+	TTime currentTime;
+	currentTime.UniversalTime();
+	const TInt64 currentTime64 = currentTime.Int64();
+
+	var.ReserveL( 2 );
+	var.AppendL( TColumn( (TUint32) volumeInfo.iUniqueID ) );
+	var.AppendL( TColumn( KCMediaIdKey ) );
+
+	connection.ExecuteL( KUpdateMediaId, var );
+
+	CleanupStack::PopAndDestroy( &var );
+	CleanupStack::PopAndDestroy( &clauseOne );
+	}
+
+const CMdsPropertyDef& CMdSSqlObjectManipulate::ReadPropertyL( 
+		CMdCSerializationBuffer& aBuffer, const CMdsObjectDef& aObjectDef,
+		CMdsClauseBuffer& aBaseObjectClause, CMdsClauseBuffer& aObjectClause,
+		RRowData& aBaseObjectDataRow, RRowData& aObjectDataRow, TUint8& aFlags)
+	{
+	const TMdCProperty& property = TMdCProperty::GetFromBufferL( aBuffer );
+	const CMdsPropertyDef* propertyDef = aObjectDef.GetPropertyByIdL( 
+			property.iPropertyDefId );
+	if ( !propertyDef )
+		{
+#ifdef _DEBUG
+		WRITELOG( "Incorrect property" );
+#endif
+		User::Leave( KErrMdEUnknownPropertyDef );
+		}
+	aFlags = property.iModFlags;
+
+	if (property.iModFlags == EMdEPropertyModNone)
+		{
+		return *propertyDef;
+		}
+
+	const TBool baseObjectProperty = 
+		iBaseObjectDef->GetPropertyByIdL(property.iPropertyDefId) != NULL;
+
+	// if property is not removed add actual value
+	if( !( property.iModFlags & EMdEPropertyModRemove ) )
+		{
+		switch(propertyDef->GetType())
+			{
+			case EPropertyBool:
+				{
+				const TBool boolValue = property.iValue.iInt32;
+				if ( baseObjectProperty )
+					{
+					aBaseObjectDataRow.AppendL( TColumn( boolValue ) );
+					}
+				else
+					{
+					aObjectDataRow.AppendL( TColumn( boolValue ) );
+					}
+				break;
+				}
+			case EPropertyInt8:
+				{
+				const TInt8 int8Value = property.iValue.iInt32;
+				if ( !propertyDef->CheckMinMaxValue( (TInt32)int8Value ) )
+					{
+#ifdef _DEBUG
+					TInt32 debugValue = int8Value;
+					WRITELOG2( "Incorrect property[%S] value: %d", 
+							&propertyDef->GetName(), debugValue );
+#endif
+					User::Leave( KErrMdEPropertyValueNotBetweenAllowedMinMax );
+					}
+				if ( baseObjectProperty )
+					{
+					aBaseObjectDataRow.AppendL( TColumn( int8Value ) );
+					}
+				else
+					{
+					aObjectDataRow.AppendL( TColumn( int8Value ) );
+					}
+				break;
+				}
+			case EPropertyUint8:
+				{
+				const TUint8 uInt8Value = property.iValue.iUint32;
+				if ( !propertyDef->CheckMinMaxValue( (TInt32)uInt8Value ) )
+					{
+#ifdef _DEBUG
+					TInt32 debugValue = uInt8Value;
+					WRITELOG2( "Incorrect property[%S] value: %d", 
+							&propertyDef->GetName(), debugValue );
+#endif
+					User::Leave( KErrMdEPropertyValueNotBetweenAllowedMinMax );
+					}
+				if ( baseObjectProperty )
+					{
+					aBaseObjectDataRow.AppendL( TColumn( uInt8Value ) );
+					}
+				else
+					{
+					aObjectDataRow.AppendL( TColumn( uInt8Value ) );
+					}
+				break;
+				}
+			case EPropertyInt16:
+				{
+				const TInt16 int16Value = property.iValue.iInt32;
+				if ( !propertyDef->CheckMinMaxValue( (TInt32)int16Value ) )
+					{
+#ifdef _DEBUG
+					TInt32 debugValue = int16Value;
+					WRITELOG2( "Incorrect property[%S] value: %d", 
+							&propertyDef->GetName(), debugValue );
+#endif
+					User::Leave( KErrMdEPropertyValueNotBetweenAllowedMinMax );
+					}
+				if ( baseObjectProperty )
+					{
+					aBaseObjectDataRow.AppendL( TColumn( int16Value ) );
+					}
+				else
+					{
+					aObjectDataRow.AppendL( TColumn( int16Value ) );
+					}
+				break;
+				}
+			case EPropertyUint16:
+				{
+				const TUint16 uInt16Value = property.iValue.iUint32;
+				if ( !propertyDef->CheckMinMaxValue( (TInt32)uInt16Value ) )
+					{
+#ifdef _DEBUG
+					TInt32 debugValue = uInt16Value;
+					WRITELOG2( "Incorrect property[%S] value: %d", 
+							&propertyDef->GetName(), debugValue );
+#endif
+					User::Leave( KErrMdEPropertyValueNotBetweenAllowedMinMax );
+					}
+				if ( baseObjectProperty )
+					{
+					aBaseObjectDataRow.AppendL( TColumn( uInt16Value ) );
+					}
+				else
+					{
+					aObjectDataRow.AppendL( TColumn( uInt16Value ) );
+					}
+				break;
+				}
+			case EPropertyInt32:
+				{
+				const TInt32 int32Value = property.iValue.iInt32;
+				if ( !propertyDef->CheckMinMaxValue( int32Value ) )
+					{
+#ifdef _DEBUG
+					WRITELOG2( "Incorrect property[%S] value: %d", 
+							&propertyDef->GetName(), int32Value );
+#endif
+					User::Leave( KErrMdEPropertyValueNotBetweenAllowedMinMax );
+					}
+				if ( baseObjectProperty )
+					{
+					aBaseObjectDataRow.AppendL( TColumn( int32Value ) );
+					}
+				else
+					{
+					aObjectDataRow.AppendL( TColumn( int32Value ) );
+					}
+				break;
+				}
+			case EPropertyUint32:
+				{
+				const TUint32 uInt32Value = property.iValue.iUint32;
+				if ( !propertyDef->CheckMinMaxValue( uInt32Value ) )
+					{
+#ifdef _DEBUG
+					WRITELOG2( "Incorrect property[%S] value: %u", 
+							&propertyDef->GetName(), uInt32Value );
+#endif
+					User::Leave( KErrMdEPropertyValueNotBetweenAllowedMinMax );
+					}
+				if ( baseObjectProperty )
+					{
+					aBaseObjectDataRow.AppendL( TColumn( uInt32Value ) );
+					}
+				else
+					{
+					aObjectDataRow.AppendL( TColumn( uInt32Value ) );
+					}
+				break;
+				}
+			case EPropertyInt64:
+				{
+				const TInt64 int64Value = property.iValue.iInt64;
+				if ( !propertyDef->CheckMinMaxValue( int64Value ) )
+					{
+#ifdef _DEBUG
+					WRITELOG2( "Incorrect property[%S] value: %Ld", 
+							&propertyDef->GetName(), int64Value );
+#endif
+					User::Leave( KErrMdEPropertyValueNotBetweenAllowedMinMax );
+					}
+				if ( baseObjectProperty )
+					{
+					aBaseObjectDataRow.AppendL( TColumn( int64Value ) );
+					}
+				else
+					{
+					aObjectDataRow.AppendL( TColumn( int64Value ) );
+					}
+				break;
+				}
+			case EPropertyTime:
+				{
+				const TInt64 int64Value = property.iValue.iInt64;
+				if ( !propertyDef->CheckMinMaxValue( int64Value ) )
+					{
+#ifdef _DEBUG					
+					WRITELOG2( "Incorrect property[%S] value: %Ld", 
+							&propertyDef->GetName(), int64Value );
+#endif
+					User::Leave( KErrMdEPropertyValueNotBetweenAllowedMinMax );
+					}
+				if ( baseObjectProperty )
+					{
+					aBaseObjectDataRow.AppendL( TColumn( int64Value ) );
+					}
+				else
+					{
+					aObjectDataRow.AppendL( TColumn( int64Value ) );
+					}
+				break;
+				}
+			case EPropertyReal32:
+				{
+				const TReal32 real32Value = property.iValue.iReal;
+				if ( !propertyDef->CheckMinMaxValue( real32Value ) )
+					{
+#ifdef _DEBUG
+					TReal64 debugValue = real32Value;
+					WRITELOG2( "Incorrect property[%S] value: %.2f", 
+							&propertyDef->GetName(), debugValue );
+#endif
+					User::Leave( KErrMdEPropertyValueNotBetweenAllowedMinMax );
+					}
+				if ( baseObjectProperty )
+					{
+					aBaseObjectDataRow.AppendL( TColumn( real32Value ) );
+					}
+				else
+					{
+					aObjectDataRow.AppendL( TColumn( real32Value ) );
+					}
+				break;
+				}
+			case EPropertyReal64:
+				{
+				const TReal64 real64Value = property.iValue.iReal;
+				if ( !propertyDef->CheckMinMaxValue( real64Value ) )
+					{
+#ifdef _DEBUG					
+					WRITELOG2( "Incorrect property[%S] value: %.2f", 
+							&propertyDef->GetName(), real64Value );
+#endif
+					User::Leave( KErrMdEPropertyValueNotBetweenAllowedMinMax );
+					}
+				if ( baseObjectProperty )
+					{
+					aBaseObjectDataRow.AppendL( TColumn( real64Value ) );
+					}
+				else
+					{
+					aObjectDataRow.AppendL( TColumn( real64Value ) );
+					}
+				break;
+				}
+			case EPropertyText:
+				{
+				aBuffer.PositionL( property.iValue.iPtr.iOffset );
+				TPtrC16 textValue( aBuffer.ReceivePtr16L() );
+				if ( !propertyDef->CheckMinMaxValue( (TInt32)textValue.Length() ) )
+					{
+#ifdef _DEBUG
+					WRITELOG3( "Incorrect property[%S] value: \"%S\", length: %d", 
+							&propertyDef->GetName(), &textValue, 
+							textValue.Length() );
+#endif
+					User::Leave( KErrMdEPropertyValueNotBetweenAllowedMinMax );
+					}
+				if ( baseObjectProperty )
+					{
+					aBaseObjectDataRow.AppendL( TColumn( textValue ) );
+					}
+				else
+					{
+					aObjectDataRow.AppendL( TColumn( textValue ) );
+					}
+				break;
+				}
+			default:
+				User::Leave( KErrMdEUnknownPropertyType );
+			}
+		}
+	// if property is removed add null value
+	else
+		{
+		TPtrC16 val = TPtr16((TUint16*)0, 0);
+		if( baseObjectProperty )
+			{
+			aBaseObjectDataRow.AppendL( TColumn( val ) );
+			}
+		else
+			{
+			aObjectDataRow.AppendL( TColumn( val ) );
+			}
+		}
+
+	if( baseObjectProperty )
+		{
+		aBaseObjectClause.AppendL( KComma );
+		aBaseObjectClause.AppendL( propertyDef->GetName() );
+		}
+	else
+		{
+		aObjectClause.AppendL( KComma );
+		aObjectClause.AppendL( propertyDef->GetName() );
+		}
+	
+	return *propertyDef;
+	}
+
+TItemId CMdSSqlObjectManipulate::AddObjectL( CMdSSqLiteConnection& aConnection, 
+       CMdCSerializationBuffer& aBuffer,
+       RMdsStatement& aMdsBaseObjStatement, RMdsStatement& aMdsObjStatement,
+       const CMdSServerSession* aServerSession )
+	{
+	_LIT( KMdsObjectAddBaseObjectBegin, "INSERT INTO Object%u(ObjectId,ObjectDefId,Flags,MediaId,GuidHigh,GuidLow,URI" );
+	_LIT( KMdsObjectAddBaseObjectMiddle, ") VALUES(?,?,?,?,?,?,?" );
+	_LIT( KMdsObjectAddObjectBegin, "INSERT INTO %S%u(ObjectId" );
+	_LIT( KMdsObjectAddObjectMiddle, ") VALUES(?" );
+	_LIT( KMdsObjectAddObjectEnd,   ");" );
+
+	if ( !iNamespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+
+	RRowData baseObjectRow;
+	CleanupClosePushL( baseObjectRow );
+	RRowData objectRow;
+	CleanupClosePushL( objectRow );
+
+	const TMdCObject& object = TMdCObject::GetFromBufferL( aBuffer );
+	// there must be at least one property (btw. base object have 7 properties)
+	if (object.iProperties.iPtr.iCount < 1)
+		{
+		User::Leave( KErrMdEMandatoryPropertyMissing );
+		}
+
+	// objectid
+	if (object.iId != KNoId)
+		{
+		User::Leave( KErrAlreadyExists );
+		}
+
+	RSQLIndex sqlIndex;
+	CleanupClosePushL( sqlIndex );
+	const TItemId objectId = sqlIndex.GetId();
+
+	baseObjectRow.AppendL( TColumn( objectId ) );
+	objectRow.AppendL( TColumn( objectId ) );
+
+	// objectdefid
+	const CMdsObjectDef* objectDef = iNamespaceDef->GetObjectByIdL( object.iDefId );
+	if ( !objectDef )
+		{
+		// objectDef doesn't exist
+		User::Leave( KErrMdEUnknownObjectDef );
+		}
+	baseObjectRow.AppendL( TColumn( object.iDefId ) );
+
+	// get BaseObjectDef
+	iBaseObjectDef = iNamespaceDef->GetObjectByIdL( KBaseObjectDefId );
+
+	RClauseBuffer commonClauseOne(*this);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& clauseBaseObject = commonClauseOne.BufferL(); 
+	RClauseBuffer commonClauseTwo(*this);
+	CleanupClosePushL( commonClauseTwo );
+	CMdsClauseBuffer& clauseObject = commonClauseTwo.BufferL(); 
+
+	const TDesC& objName = objectDef->GetName();
+	if(objName != iLastAddedObjName)
+	    {
+        iLastAddedObjName = objName;
+        aMdsBaseObjStatement.Close();
+        aMdsBaseObjStatement = RMdsStatement();
+	    aMdsObjStatement.Close();
+        aMdsObjStatement = RMdsStatement();
+        }
+ 
+    clauseObject.BufferL().Format( KMdsObjectAddObjectBegin, &objName, iNamespaceDef->GetId() );
+	clauseBaseObject.BufferL().Format( KMdsObjectAddBaseObjectBegin, iNamespaceDef->GetId() );
+
+	TUint32 objectFlags = 0;
+	if ( !( object.iFlags & ( EMdEObjectFlagModOpen | EMdEObjectFlagAutoLock ) ) )
+		{
+		User::Leave( KErrMdENotLocked );
+		}
+
+	if (object.iFlags & EMdEObjectFlagConfidential) 
+		{
+		objectFlags |= EMdEObjectFlagConfidential;
+		}
+	if (object.iFlags & EMdEObjectFlagModFreeText)
+		{
+		objectFlags |= EMdEObjectFlagFreetexts;
+		}
+	if (object.iFlags & EMdEObjectFlagPlaceholder)
+		{
+		objectFlags |= EMdEObjectFlagPlaceholder;
+		}
+	if (objectDef->GetFlags() == CMdsObjectDef::EObjectDefFlagsContext)
+		{
+		objectFlags |= EMdEObjectFlagContext;
+		}
+	baseObjectRow.AppendL( TColumn( objectFlags ) );
+
+	// mediaId
+	baseObjectRow.AppendL( TColumn( object.iMediaId ) );
+
+	TInt64 guidHigh = object.iGuidHigh;
+	TInt64 guidLow = object.iGuidLow;
+
+	if (guidLow == 0 && guidHigh == 0)
+		{
+		iGenerator->GenerateGuid( guidHigh, guidLow );
+		}
+
+	baseObjectRow.AppendL( TColumn( guidHigh ) );
+	baseObjectRow.AppendL( TColumn( guidLow ) );
+
+	// uri
+	HBufC* uriBuf = NULL;
+	if (object.iUri.iPtr.iCount == 0)
+		{
+		uriBuf = iGenerator->GenerateUriL( *objectDef, guidHigh, guidLow );
+		}
+	else
+		{
+		aBuffer.PositionL( object.iUri.iPtr.iOffset );
+		uriBuf = aBuffer.ReceiveDes16L();
+		}
+	CleanupStack::PushL( uriBuf );
+	TPtr16 uri( uriBuf->Des() );
+	uri.LowerCase();
+	baseObjectRow.AppendL( TColumn( uri ) );
+
+	const TInt baseObjectRowSizeWithoutProperties = baseObjectRow.Size();
+
+	TInt mandatoryPropertyCount = objectDef->GetMandatoryPropertyCount();
+	
+	// try to add property
+	for ( TUint32 i = 0; i < object.iProperties.iPtr.iCount; ++i )
+		{
+		aBuffer.PositionL( object.iProperties.iPtr.iOffset + i * sizeof(TMdCProperty) );
+		TUint8 modFlags;
+		const CMdsPropertyDef& propertyDef = ReadPropertyL( aBuffer, *objectDef, clauseBaseObject, clauseObject, baseObjectRow, objectRow, modFlags );
+		if ( modFlags == EMdEPropertyModNone )
+			{
+			continue;
+			}
+
+		// check if mandatory property is removed
+		if( propertyDef.GetMandatory() )
+			{
+			if( modFlags & EMdEPropertyModRemove )
+				{
+				User::Leave( KErrMdEMandatoryPropertyMissing );
+				}
+			else
+				{
+				--mandatoryPropertyCount;
+				}
+			}
+		}
+
+	if( mandatoryPropertyCount != 0 )
+		{
+		User::Leave( KErrMdEMandatoryPropertyMissing );
+		}
+
+	clauseBaseObject.AppendL( KMdsObjectAddBaseObjectMiddle );
+
+	const TInt baseObjectPropertyCount = baseObjectRow.Size() - 
+		baseObjectRowSizeWithoutProperties;
+
+	for ( TInt i = 0; i < baseObjectPropertyCount; ++i )
+		{
+		clauseBaseObject.AppendL( KComma );
+		clauseBaseObject.AppendL( KVariable );
+		}
+
+	clauseObject.AppendL( KMdsObjectAddObjectMiddle );
+
+	// object row property count (object row size without object ID)
+	const TInt objectPropertyCount = objectRow.Size() - 1;
+
+	for ( TInt i = 0; i < objectPropertyCount; ++i )
+		{
+		clauseObject.AppendL( KComma );
+		clauseObject.AppendL( KVariable );
+		}
+	
+	clauseBaseObject.AppendL( KMdsObjectAddObjectEnd );
+	clauseObject.AppendL( KMdsObjectAddObjectEnd );
+
+	// EVERYTHING IS OK - add object to DB
+
+	TInt queryResult = 0, err;
+	// add base object properties
+	__LOGQUERY_16( _L("Add BaseObject to DB:"), clauseBaseObject.ConstBufferL(), baseObjectRow);
+	TRAP( err, aConnection.ExecuteL( clauseBaseObject.ConstBufferL(), baseObjectRow, &aMdsBaseObjStatement ) );
+	if (err == KSqlErrConstraint)
+		{
+		__LOG1( ELogQuery, "Adding baseObject constraint error - err:%d", err );
+		TRAP_IGNORE( RemoveObjectForceL( uri, KNoId ) );
+		__LOGQUERY_16( _L("Add AGAIN BaseObject to DB:"), clauseBaseObject.ConstBufferL(), baseObjectRow);
+		TRAP( err, aConnection.ExecuteL( clauseBaseObject.ConstBufferL(), baseObjectRow, &aMdsBaseObjStatement ) );
+		}
+
+	if (err != KErrNone)
+		{
+		__LOG1( ELogQuery, "Adding baseObject failed - err:%d", err );
+		User::Leave( KErrGeneral );
+		}
+
+	if( !( // skip if object definition is "base object"
+		   // and object is placeholder
+			(object.iDefId == KBaseObjectDefId) &&
+			(object.iFlags & EMdEObjectFlagPlaceholder)
+		 ) 
+	  )
+		{	
+		__LOGQUERY_16( _L("Add Object to DB:"), clauseObject.ConstBufferL(), 
+				objectRow);
+		TRAP( err, queryResult = aConnection.ExecuteL( 
+		        clauseObject.ConstBufferL(), objectRow, &aMdsObjStatement ) );
+		if (err != KErrNone || queryResult != 1)
+			{
+			__LOG2( ELogQuery, "Adding object failed - err:%d, queryResult:%d", err, queryResult );
+			TRAP_IGNORE( RemoveObjectForceL( objectId ) );
+			User::Leave( err );
+			}
+		}
+
+	CleanupStack::PopAndDestroy( uriBuf );
+	CleanupStack::PopAndDestroy( 2, &commonClauseOne ); // commonClauseTwo, commonClauseOne
+
+	// add freetext to DB
+	if ( object.iFreeTexts.iPtr.iCount > 0 )
+		{
+		aBuffer.PositionL( object.iFreeTexts.iPtr.iOffset );
+		TRAP( err, AddFreeTextL( aBuffer, object.iFreeTexts.iPtr.iCount, objectId ) );
+		if (err != KErrNone)
+			{
+			__LOG1( ELogQuery, "Adding object freetext failed - err:%d", err );
+			TRAP_IGNORE( RemoveObjectForceL( objectId ) );
+			User::Leave( err );
+			}
+		}
+
+	sqlIndex.Commit();
+	CleanupStack::PopAndDestroy( &sqlIndex );
+	CleanupStack::PopAndDestroy( 2, &baseObjectRow ); // objectRow, baseObjectRow
+
+	if( ( object.iFlags & EMdEObjectFlagAutoLock ) && aServerSession )
+		{
+		iLockList.LockObjectL( *aServerSession, *iNamespaceDef, objectId );
+		}
+	
+	return objectId;
+	}
+
+TUint32 CMdSSqlObjectManipulate::AddFreeTextToDBL( TPtrC16& aWord, TItemId aObjectId,
+    TInt32 aPosition, TBool aSearch )
+	{
+	_LIT( KMdsFreeTextAdd, "INSERT INTO TextSearch%d(WordId,ObjectId,Position) VALUES(?,?,?)" );
+	_LIT( KMdsFreeTextDictAdd, "INSERT INTO TextSearchDictionary%d(Word) VALUES(?)" );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	RClauseBuffer commonClauseOne(*this);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& freeTextAdd     = commonClauseOne.BufferL(); 
+	RClauseBuffer commonClauseTwo(*this);
+	CleanupClosePushL( commonClauseTwo );
+	CMdsClauseBuffer& freeTextDictAdd = commonClauseTwo.BufferL();
+
+	freeTextAdd.BufferL().Format( KMdsFreeTextAdd, iNamespaceDef->GetId() );
+	freeTextDictAdd.BufferL().Format( KMdsFreeTextDictAdd, iNamespaceDef->GetId() );
+
+	TItemId freeTextId = KNoId;
+	RRowData freeTextRow;
+	CleanupClosePushL( freeTextRow );
+	RRowData freeTextRowDict;
+	CleanupClosePushL( freeTextRowDict );
+
+	freeTextRow.ReserveL( 3 );
+
+	freeTextRow.AppendL( TColumn(KNoId) );
+	freeTextRow.AppendL( TColumn(aObjectId) );
+	freeTextRow.AppendL( TColumn(aPosition) );
+
+    freeTextId = FindFreeTextInDbL( aWord );
+	if ( aSearch && freeTextId )
+		{
+		freeTextRow.Column(0).Set( freeTextId );
+		__LOGQUERY_16( _L("Add FreeText index to DB:"), 
+				freeTextAdd.ConstBufferL(), freeTextRow);
+		connection.ExecuteL( freeTextAdd.ConstBufferL(), freeTextRow );
+		}
+	else
+		{
+		freeTextRowDict.AppendL( TColumn( aWord ) );
+		__LOGQUERY_16( _L("Add FreeText to DB:"), 
+				freeTextDictAdd.ConstBufferL(), freeTextRowDict);
+		TRAPD( err, freeTextId = MMdSIndexer::ExecuteAndGetIndexL( 
+				freeTextDictAdd.ConstBufferL(), freeTextRowDict ) );
+		if (err != KErrNone || freeTextId == KNoId)
+			{
+			__LOG2( ELogQuery, "Adding freetextDict failed - err:%d, freeTextId:%d", 
+					err, freeTextId );
+			User::Leave( KErrGeneral );
+			}
+		
+		freeTextRow.Column(0).Set( freeTextId );
+		connection.ExecuteL( freeTextAdd.ConstBufferL(), freeTextRow );
+		}
+
+	CleanupStack::PopAndDestroy( 4, &commonClauseOne ); // freeTextRowDict, freeTextRow, commonClauseTwo, commonClauseOne
+	return freeTextId;
+	}
+
+TInt CMdSSqlObjectManipulate::AddFreeTextL( CMdCSerializationBuffer& aBuffer, TInt aFreeTextCount, TItemId aObjectId )
+	{
+	TInt freeTextAdded = 0;
+
+	for ( TUint32 i = 0; i < aFreeTextCount; ++i )
+		{
+		TPtrC16 freeText = aBuffer.ReceivePtr16L();
+		AddFreeTextToDBL( freeText, aObjectId, i );
+		++freeTextAdded;
+		}
+	return freeTextAdded;
+	}
+
+TItemId CMdSSqlObjectManipulate::FindFreeTextInDbL( TPtrC16 aFreeText )
+	{
+	_LIT( KMdsFreeTextSearch, "SELECT WordId FROM TextSearchDictionary%d WHERE Word=? LIMIT 1;" );
+	
+	RClauseBuffer commonClauseOne(*this, KMdsFreeTextSearch.iTypeLength + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& freeTextSearchClause = commonClauseOne.BufferL();
+	freeTextSearchClause.BufferL().Format( KMdsFreeTextSearch, iNamespaceDef->GetId() );
+
+	TItemId freeTextId = 0;
+	RRowData wordRow;
+	CleanupClosePushL( wordRow );
+	RRowData idRow;
+	CleanupClosePushL( idRow );
+	RMdsStatement query;
+	CleanupClosePushL( query );
+	
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	wordRow.AppendL( TColumn( aFreeText ) );
+	idRow.AppendL( TColumn( freeTextId ) );
+	connection.ExecuteQueryL( freeTextSearchClause.ConstBufferL(), query, wordRow );
+	if( connection.NextRowL( query, idRow ) )
+		{
+		idRow.Column( 0 ).Get( freeTextId );
+		}
+
+	CleanupStack::PopAndDestroy( 4, &commonClauseOne ); // query, idRow, wordRow, commonClauseOne
+	return freeTextId;
+	}
+
+void CMdSSqlObjectManipulate::RemoveObjectForceL( const TDesC16& aUri, TItemId aObjectId )
+	{
+	_LIT( KMdsRemoveObjectByUri, "DELETE FROM Object%u WHERE Flags&? AND ObjectId!=? AND URI=?;" );
+
+	if ( !iNamespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+
+	RClauseBuffer commonClauseOne(*this, KMdsRemoveObjectByUri.iTypeLength + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& removeObjectClause = commonClauseOne.BufferL();
+
+	removeObjectClause.BufferL().Format( KMdsRemoveObjectByUri, 
+			iNamespaceDef->GetId() );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+    // do remove
+    RRowData varRemove;
+    CleanupClosePushL( varRemove );
+    varRemove.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+    varRemove.AppendL( TColumn( aObjectId ) );
+    varRemove.AppendL( TColumn( aUri ) );
+
+#ifdef _DEBUG    
+#ifdef LOG_MASTER_FLAG
+	TInt queryResult = 0; // For debug
+	__LOGQUERY_16( _L("Remove FORCE object using URI:"), 
+			removeObjectClause.ConstBufferL(), varRemove);
+	TRAPD( err, queryResult = connection.ExecuteL( 
+			removeObjectClause.ConstBufferL(), varRemove ) );
+	if( err != KErrNone )
+		{
+		__LOG2( ELogQuery, "Remove FORCE object err:%d, queryResult:%d", err, queryResult );
+		}
+#else
+    TRAP_IGNORE( connection.ExecuteL( removeObjectClause.ConstBufferL(), varRemove ) );
+#endif // LOG_MASTER_FLAG
+#else
+    TRAP_IGNORE( connection.ExecuteL( removeObjectClause.ConstBufferL(), varRemove ) );    
+#endif // _DEBUG
+	
+	CleanupStack::PopAndDestroy( 2, &commonClauseOne ); // varRemove, commonClauseOne
+	}
+
+// USE WITH CAUTION !!!
+// THIS FUNCTION REMOVES OBJECT WITHOUT ANY CHECKING
+// ONLY FOR INTERNAL USE !!!
+void CMdSSqlObjectManipulate::RemoveObjectForceL( TItemId aObjectId )
+	{
+	_LIT( KMdsRemoveObjectById, "DELETE FROM Object%u WHERE ObjectId=?;" );
+
+	if ( !iNamespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+
+	RClauseBuffer commonClauseOne(*this,  KMdsRemoveObjectById.iTypeLength + KMaxUintValueLength );
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& removeObjectClause = commonClauseOne.BufferL();
+
+	removeObjectClause.BufferL().Format( KMdsRemoveObjectById, iNamespaceDef->GetId() );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+    // do remove
+    RRowData varRemove;
+    CleanupClosePushL( varRemove );
+    varRemove.AppendL( TColumn( aObjectId ) );
+
+#ifdef _DEBUG    
+#ifdef LOG_MASTER_FLAG
+	TInt queryResult = 0; // For debug
+	__LOGQUERY_16( _L("Remove object using ID:"), 
+			removeObjectClause.ConstBufferL(), varRemove);
+	TRAPD( err, queryResult = connection.ExecuteL( 
+			removeObjectClause.ConstBufferL(), varRemove ) );
+	if ( err != KErrNone )
+		{
+		__LOG2( ELogQuery, "Remove FORCE Object err:%d, queryResult:%d", err, queryResult );
+		}
+#else
+    TRAP_IGNORE( connection.ExecuteL( removeObjectClause.ConstBufferL(), varRemove ) );
+#endif // LOG_MASTER_FLAG
+#else
+    TRAP_IGNORE( connection.ExecuteL( removeObjectClause.ConstBufferL(), varRemove ) );  
+#endif // _DEBUG
+    
+	CleanupStack::PopAndDestroy( 2, &commonClauseOne ); // varRemove, commonClauseOne
+	}
+
+CMdCSerializationBuffer* CMdSSqlObjectManipulate::CheckObjectL( TInt aResultBufferSize, 
+		const TDesC& aUri, TDefId aNamespaceDefId )
+	{
+	_LIT( KMdsCheckObjectByUri, "SELECT ObjectId, ObjectDefId, Flags FROM Object%u WHERE URI=?;" );
+
+	RClauseBuffer commonClauseOne(*this, KMdsCheckObjectByUri.iTypeLength + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& checkObjectClause = commonClauseOne.BufferL();
+
+	checkObjectClause.BufferL().Format( KMdsCheckObjectByUri, aNamespaceDefId );
+
+    RRowData rowData;
+    CleanupClosePushL( rowData );
+    rowData.AppendL( TColumn( aUri ) );
+    
+    RMdsStatement query;
+	CleanupClosePushL( query );
+
+	CMdSSqLiteConnection& db = MMdSDbConnectionPool::GetDefaultDBL();
+
+	db.ExecuteQueryL( checkObjectClause.ConstBufferL(), query, rowData );
+
+	rowData.Free();	rowData.Reset();
+	rowData.ReserveL( 3 ); // space for SELECTs
+
+	TMdCObject object;
+    rowData.AppendL( TColumn( object.iId ) );
+    rowData.AppendL( TColumn( object.iDefId ) );
+    rowData.AppendL( TColumn( object.iFlags ) );
+
+    CMdCSerializationBuffer* buffer = NULL;
+	if ( db.NextRowL( query, rowData ) )
+		{
+		rowData.Column(0).Get( object.iId );
+		rowData.Column(1).Get( object.iDefId );
+		rowData.Column(2).Get( object.iFlags );
+
+		buffer = CMdCSerializationBuffer::NewLC( aResultBufferSize );
+		object.SerializeL( *buffer );
+		CleanupStack::Pop( buffer );
+		}
+	else
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	CleanupStack::PopAndDestroy( 3, &commonClauseOne ); // query, rowData, commonClauseOne
+
+	return buffer;
+	}
+
+CMdCSerializationBuffer* CMdSSqlObjectManipulate::CheckObjectL( TInt aResultBufferSize, 
+		TItemId aId, TDefId aNamespaceDefId )
+	{
+	_LIT( KMdsCheckObjectById, "SELECT ObjectDefId, Flags FROM Object%u WHERE ObjectId=?;" );
+
+	RClauseBuffer commonClauseOne(*this, KMdsCheckObjectById.iTypeLength + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& checkObjectClause = commonClauseOne.BufferL();
+
+	checkObjectClause.BufferL().Format( KMdsCheckObjectById, aNamespaceDefId );
+	
+    RRowData rowData;
+    CleanupClosePushL( rowData );
+    rowData.AppendL( TColumn( aId ) );
+
+    RMdsStatement query;
+	CleanupClosePushL( query );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	connection.ExecuteQueryL( checkObjectClause.ConstBufferL(), query, rowData );
+
+	rowData.Free();	rowData.Reset();
+	rowData.ReserveL( 2 ); // space for SELECTs
+
+	TMdCObject object;
+	object.iId = aId;
+    rowData.AppendL( TColumn( object.iDefId ) );
+    rowData.AppendL( TColumn( object.iFlags ) );
+
+    CMdCSerializationBuffer* buffer = NULL;
+	if ( connection.NextRowL( query, rowData ) )
+		{
+		rowData.Column(0).Get( object.iDefId );
+		rowData.Column(1).Get( object.iFlags );
+
+		buffer = CMdCSerializationBuffer::NewLC( aResultBufferSize );
+		object.SerializeL( *buffer );
+		CleanupStack::Pop( buffer );
+		}
+	else
+		{
+		User::Leave( KErrNotFound );
+		}
+
+	CleanupStack::PopAndDestroy( 3, &commonClauseOne ); // query, rowData, commonClauseOne
+
+	return buffer;
+	}
+
+CMdCSerializationBuffer* CMdSSqlObjectManipulate::CheckObjectL( TInt aResultBufferSize, 
+		CMdCSerializationBuffer& aIds, TDefId aNamespaceDefId )
+	{
+
+	aIds.PositionL( KNoOffset );
+	TUint32 idCount = 0;
+	aIds.ReceiveL( idCount );
+
+	// if no IDs, just return 0 objects
+	if( idCount == 0 )
+		{
+		CMdCSerializationBuffer* buffer = 
+			CMdCSerializationBuffer::NewLC( CMdCSerializationBuffer::KRequiredSizeForTUint32 );
+		buffer->InsertL( idCount );
+		return buffer;
+		}
+
+	_LIT( KMdsCheckObjectByIds, "SELECT ObjectId, ObjectDefId, Flags FROM Object%u WHERE ObjectId IN(?" );
+	_LIT( KMdsCheckObjectByIdsAppend, ",?" );
+	_LIT( KMdsCheckObjectByIdsEnd, ");" );
+
+	RClauseBuffer commonClauseOne(*this, KMdsCheckObjectByIds.iTypeLength + KMaxUintValueLength + 
+										 KMdsCheckObjectByIdsAppend.iTypeLength * (idCount - 1) + 
+										 KMdsCheckObjectByIdsEnd.iTypeLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& checkObjectClause = commonClauseOne.BufferL();
+	
+	RRowData rowData;
+	CleanupClosePushL( rowData );
+
+	checkObjectClause.BufferL().Format( KMdsCheckObjectByIds, aNamespaceDefId );
+	TItemId id;
+	aIds.ReceiveL( id );
+	rowData.AppendL( TColumn( id ) );
+	
+	for( TUint32 i = 1; i < idCount; i++ )
+		{
+		checkObjectClause.BufferL().Append( KMdsCheckObjectByIdsAppend );
+		aIds.ReceiveL( id );
+		rowData.AppendL( TColumn( id ) );
+		}
+
+	checkObjectClause.BufferL().Append( KMdsCheckObjectByIdsEnd );
+
+	RMdsStatement query;
+	CleanupClosePushL( query );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	connection.ExecuteQueryL( checkObjectClause.ConstBufferL(), query, rowData );
+
+	CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC( aResultBufferSize );
+	
+	// initialize with 0 objects (will be updated later)
+	TUint32 resultObjectCount = 0;
+	buffer->InsertL( resultObjectCount );
+
+	rowData.Free();
+	rowData.Reset();
+
+	rowData.ReserveL( 3 ); // space for SELECT's object
+	
+	TMdCObject object;
+	rowData.AppendL( TColumn( object.iId ) );
+	rowData.AppendL( TColumn( object.iDefId ) );
+	rowData.AppendL( TColumn( object.iFlags ) );
+
+	while( connection.NextRowL( query, rowData ) )
+		{
+		rowData.Column(0).Get( object.iId );
+		rowData.Column(1).Get( object.iDefId );
+		rowData.Column(2).Get( object.iFlags );
+
+		object.SerializeL( *buffer );
+		++resultObjectCount;
+		}
+
+	// update object count
+	buffer->PositionL( KNoOffset );
+	buffer->InsertL( resultObjectCount );
+
+	CleanupStack::Pop( buffer );
+	CleanupStack::PopAndDestroy( 3, &commonClauseOne ); // query, rowData, commonClauseOne
+	
+	return buffer;
+	}
+
+static TInt CompareTItemIds( const TItemId& aLeft, const TItemId& aRight )
+	{
+	return aLeft - aRight;
+	}
+
+void CMdSSqlObjectManipulate::CollectRemovedItemsL( RArray<TItemId>& aRemoveIds, RArray<TItemId>& aObjectIds,
+                                                    RArray<TItemId>& aRelationIds, RArray<TItemId>& /*aEventIds*/ )
+	{
+	_LIT( KCollectGetDeleteId,          "SELECT O.ObjectId, R.RelationId FROM Object%u AS O LEFT JOIN Relations%u AS R ON O.ObjectId=R.LeftObjectId OR O.ObjectId=R.RightObjectId WHERE NOT O.Flags&? AND ObjectId IN(?" );
+	_LIT( KCollectUpdateObjectBegin,    "UPDATE Object%u SET Flags=Flags|? WHERE ObjectId IN(?" );
+	_LIT( KCollectUpdateRelationsBegin, "UPDATE Relations%u SET Flags=Flags|? WHERE RelationId IN(?" );
+	_LIT( KCollectMiddle, ",?" );
+	_LIT( KCollectEnd,    ");" );
+
+	const TInt removeIdsCount = aRemoveIds.Count();
+	if (removeIdsCount < 1)
+		{
+		return;
+		}
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	RClauseBuffer commonClauseOne(*this,  KCollectGetDeleteId().Length() + 2 * KMaxUintValueLength +
+											(removeIdsCount-1) * KCollectMiddle().Length() +
+											KCollectEnd().Length());
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& buffer = commonClauseOne.BufferL();
+
+	// getting removed object id and relation id
+	RRowData dataRow;
+	CleanupClosePushL( dataRow );
+	dataRow.ReserveL( removeIdsCount );
+	dataRow.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+	buffer.BufferL().Format( KCollectGetDeleteId, iNamespaceDef->GetId(), iNamespaceDef->GetId() );
+	for (TInt i = 0; i < removeIdsCount; ++i)
+		{
+		if(i>0)
+			{
+			buffer.AppendL( KCollectMiddle );
+			}
+		dataRow.AppendL( TColumn( aRemoveIds[i] ) );
+		}
+	buffer.AppendL( KCollectEnd );
+
+	RMdsStatement objectQuery;
+	CleanupClosePushL( objectQuery );
+
+	__LOGQUERY_16( _L("Find objects to delete:"), buffer.ConstBufferL(), dataRow);
+	connection.ExecuteQueryL( buffer.ConstBufferL(), objectQuery, dataRow );
+
+	dataRow.Free();	dataRow.Reset();
+	TItemId objectId = KNoId;
+    TItemId prevId = objectId;
+    TItemId relationId = KNoId;
+	dataRow.AppendL( TColumn( objectId ) );
+	dataRow.AppendL( TColumn( relationId ) );
+	while ( connection.NextRowL( objectQuery, dataRow ) )
+		{
+		dataRow.Column(0).Get( objectId );
+		if (objectId != prevId)
+			{
+			aObjectIds.AppendL( objectId );
+			prevId = objectId;
+			}
+		if (!dataRow.Column(1).IsNull())
+			{
+			dataRow.Column(1).Get( relationId );
+			aRelationIds.InsertInOrder( relationId, TLinearOrder<TItemId>( CompareTItemIds ) );
+			}
+		else
+			{
+			dataRow.Column(1).Set( relationId );
+			}
+		}
+
+	// mark object's as removed
+	// remove only item that are OK to remove (not removed earlier)
+	const TInt removeObjectCount = aObjectIds.Count();
+	if ( removeObjectCount > 0 )
+		{
+		buffer.ReserveSpaceL( KCollectUpdateObjectBegin().Length() + KMaxUintValueLength +
+							   (removeObjectCount-1) * KCollectMiddle().Length() +
+							   KCollectEnd().Length() );
+
+		buffer.BufferL().Format( KCollectUpdateObjectBegin, iNamespaceDef->GetId() );
+
+		dataRow.Free();
+		dataRow.Reset();
+		dataRow.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+
+		for (TInt i = 0; i < removeObjectCount; ++i)
+			{
+			if(i>0)
+				{
+				buffer.AppendL( KCollectMiddle );
+				}
+			dataRow.AppendL( TColumn( aObjectIds[i] ) );
+			}
+		buffer.AppendL( KCollectEnd );
+
+		__LOGQUERY_16( _L("Remove objects:"), buffer.ConstBufferL(), dataRow);
+		connection.ExecuteL( buffer.ConstBufferL(), dataRow );
+		}
+
+	// mark relations as removed
+	// remove only item that are OK to remove (not removed earlier)
+	const TInt removeRelationCount = aRelationIds.Count();
+	if ( removeRelationCount > 0 )
+		{
+		buffer.ReserveSpaceL( KCollectUpdateRelationsBegin().Length() + KMaxUintValueLength +
+							   (removeRelationCount-1) * KCollectMiddle().Length() +
+							   KCollectEnd().Length() );
+
+		buffer.BufferL().Format( KCollectUpdateRelationsBegin, iNamespaceDef->GetId() );
+
+		dataRow.Free();	dataRow.Reset();
+		dataRow.ReserveL( 1 + removeRelationCount );
+		dataRow.AppendL( TColumn( EMdERelationFlagDeleted ) );
+
+		for ( TInt i = 0; i < removeRelationCount; ++i )
+			{
+			if( i > 0 )
+				{
+				buffer.AppendL( KCollectMiddle );
+				}
+			dataRow.AppendL( TColumn( aRelationIds[i] ) );
+			}
+		buffer.AppendL( KCollectEnd );
+
+		__LOGQUERY_16( _L("Remove relations:"), buffer.ConstBufferL(), dataRow);
+		connection.ExecuteL( buffer.ConstBufferL(), dataRow );
+		}
+
+
+	CleanupStack::PopAndDestroy( 3, &commonClauseOne ); // objectQuery, dataRow, commonClauseOne
+	}
+
+void CMdSSqlObjectManipulate::RemoveObjectsByIdL( 
+		CMdCSerializationBuffer& aBuffer, TInt aCount, RArray<TItemId>& aIdArray, 
+		RArray<TItemId>& aRelationIds, RArray<TItemId>& aEventIds )
+	{
+	if ( !iNamespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+
+	RArray<TItemId> objectIds;
+	CleanupClosePushL( objectIds );
+
+	TItemId objectId = KNoId;
+
+	objectIds.ReserveL( aCount );
+	for (TUint32 i = 0; i < aCount; ++i)
+		{
+		aBuffer.ReceiveL( objectId );
+		if ( objectId != KNoId )
+			{
+			if ( iLockList.IsLocked( *iNamespaceDef, objectId ) )
+				{
+				iLockList.UnlockById( *iNamespaceDef, objectId );
+				}
+
+			objectIds.AppendL( objectId );
+			}
+		}
+
+	CollectRemovedItemsL( objectIds, aIdArray, aRelationIds, aEventIds );
+
+    CleanupStack::PopAndDestroy( &objectIds );
+	}
+
+void CMdSSqlObjectManipulate::RemoveObjectsByUriL( 
+		CMdCSerializationBuffer& aBuffer, TInt aCount, RArray<TItemId>& aIdArray,
+        RArray<TItemId>& aRelationIds, RArray<TItemId>& aEventIds )
+	{
+	if ( !iNamespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+
+	RArray<TItemId> objectIds;
+	CleanupClosePushL( objectIds );
+
+	TUint32 flags;
+	TItemId objectId = KNoId;
+	objectIds.ReserveL( aCount );
+	for (TUint32 i = 0; i < aCount; ++i)
+		{
+		TPtrC16 uri = aBuffer.ReceivePtr16L();
+        objectId = SearchObjectByUriL( uri, flags );
+		if ( objectId != KNoId )
+			{
+			// unlock object, so update is no possible anymore
+			if ( iLockList.IsLocked( *iNamespaceDef, objectId ) )
+				{
+				iLockList.UnlockById( *iNamespaceDef, objectId );
+				}
+			
+			objectIds.AppendL( objectId );
+			}
+		}
+
+	CollectRemovedItemsL( objectIds, aIdArray, aRelationIds, aEventIds );
+
+    CleanupStack::PopAndDestroy( &objectIds );
+	}
+
+TItemId CMdSSqlObjectManipulate::SearchObjectByUriL( const TDesC16& aUri, 
+		TUint32& aFlags )
+	{
+	_LIT( KMdsSearchObjectbyUri, "SELECT ObjectId,Flags FROM Object%u WHERE NOT Flags&? AND NOT Flags&? AND URI=? LIMIT 1;" );
+
+	if ( !iNamespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+
+	RClauseBuffer commonClauseOne(*this, KMdsSearchObjectbyUri.iTypeLength + KMaxUintValueLength );
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& searchUriClause = commonClauseOne.BufferL();
+
+	searchUriClause.BufferL().Format( KMdsSearchObjectbyUri, iNamespaceDef->GetId() );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	TItemId objectId = KNoId;
+	aFlags = 0;
+
+    RRowData varSearch;
+    CleanupClosePushL( varSearch );
+    varSearch.AppendL( TColumn( EMdEObjectFlagNotPresent ) );
+    varSearch.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+    varSearch.AppendL( TColumn( aUri ) );
+
+	RMdsStatement getQuery;
+    CleanupClosePushL( getQuery );
+
+	__LOGQUERY_16( _L("Search object by URI:"), 
+			searchUriClause.ConstBufferL(), varSearch);
+	TRAPD( err, connection.ExecuteQueryL( 
+			searchUriClause.ConstBufferL(), getQuery, varSearch ) );
+
+	varSearch.Free();
+	varSearch.Reset();
+	varSearch.AppendL( TColumn( objectId ) );
+	varSearch.AppendL( TColumn( aFlags ) );
+	if ( err == KErrNone && connection.NextRowL( getQuery, varSearch ) )
+		{
+		varSearch.Column(0).Get( objectId );
+		varSearch.Column(1).Get( aFlags );
+		}
+
+	CleanupStack::PopAndDestroy( 2, &varSearch ); // getQuery, varSearch
+	CleanupStack::PopAndDestroy( &commonClauseOne );
+	return objectId;
+	}
+
+TItemId CMdSSqlObjectManipulate::UpdateObjectL( 
+		CMdSSqLiteConnection& aConnection, CMdCSerializationBuffer& aBuffer )
+	{
+	_LIT( KMdsObjectUpdateBaseObjectBegin,     "UPDATE Object%u SET " );
+	_LIT( KMdsObjectUpdateBaseObjectFlags,     "Flags=? " );
+	_LIT( KMdsObjectUpdateBaseObjectEnd,       ",MediaId=?,GuidHigh=?,GuidLow=?,URI=? ");
+	_LIT( KMdsObjectUpdateObjectBegin,         "UPDATE %S%u SET " );
+	_LIT( KMdsObjectUpdateEnd,                 " WHERE ObjectId=?;" );
+	_LIT( KUpdateEqual, "=?" );
+
+	if ( !iNamespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+
+	const TMdCObject& object = TMdCObject::GetFromBufferL( aBuffer );
+
+	// objectid
+	if (object.iId == KNoId)
+		{
+		User::Leave( KErrArgument );
+		}
+
+	// object must be locked
+	if (!iLockList.IsLocked(*iNamespaceDef, object.iId))
+		{
+		User::Leave( KErrMdENotLocked );
+		}
+
+	// objectdefid
+	// objectDef exists ??
+	const CMdsObjectDef* objectDef = iNamespaceDef->GetObjectByIdL( 
+			object.iDefId );
+	if ( !objectDef )
+		{
+		User::Leave( KErrMdEUnknownObjectDef );
+		}
+
+	// get BaseObjectDef
+	iBaseObjectDef = iNamespaceDef->GetObjectByIdL( KBaseObjectDefId );
+
+	TUint32 objectFlags = 0;
+	if (object.iFlags & EMdEObjectFlagConfidential)
+		{
+		objectFlags |= EMdEObjectFlagConfidential;
+		}
+	if (object.iFlags & EMdEObjectFlagModFreeText)
+		{
+		objectFlags |= EMdEObjectFlagFreetexts;
+		}
+	if (object.iFlags & EMdEObjectFlagPlaceholder)
+		{
+		objectFlags |= EMdEObjectFlagPlaceholder;
+		}
+	if (objectDef->GetFlags() == CMdsObjectDef::EObjectDefFlagsContext)
+		{
+		objectFlags |= EMdEObjectFlagContext;
+		}
+
+	if (!(object.iFlags & EMdEObjectFlagModOpen))
+		{
+		User::Leave( KErrMdENotLocked );
+		}
+
+	const TBool KUpdateModObject   = 
+		object.iFlags & EMdEObjectFlagModObject   ? ETrue : EFalse;
+	const TBool KUpdateModFreeText = 
+		object.iFlags & EMdEObjectFlagModFreeText ? ETrue : EFalse;
+	const TBool KUpdateModProperty = 
+		object.iFlags & EMdEObjectFlagModProperty ? ETrue : EFalse;
+
+	if ( !( KUpdateModObject || KUpdateModFreeText || KUpdateModProperty ) )
+		{
+		// nothing to change, so unlock object and return
+		iLockList.UnlockById( *iNamespaceDef, object.iId );
+		return object.iId;
+		}
+
+	RRowData baseObjectRow;
+	CleanupClosePushL( baseObjectRow );
+	RRowData objectRow;
+	CleanupClosePushL( objectRow );
+
+	RClauseBuffer commonClauseOne(*this);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& clauseObject = commonClauseOne.BufferL();
+	
+	if (KUpdateModProperty)
+		{
+		clauseObject.BufferL().Format( KMdsObjectUpdateObjectBegin, 
+				&objectDef->GetName(), iNamespaceDef->GetId() );
+		}
+
+	RClauseBuffer commonClauseTwo(*this);
+	CleanupClosePushL( commonClauseTwo );
+	CMdsClauseBuffer& clauseBaseObject = commonClauseTwo.BufferL();
+	if (KUpdateModObject || KUpdateModProperty)
+		{
+		clauseBaseObject.BufferL().Format( KMdsObjectUpdateBaseObjectBegin, 
+				iNamespaceDef->GetId() );
+		}
+
+	aBuffer.PositionL( object.iUri.iPtr.iOffset );
+	HBufC* uriBuf = aBuffer.ReceiveDes16L();
+	CleanupStack::PushL( uriBuf );
+	TPtr16 uri( uriBuf->Des() );
+	uri.LowerCase();
+
+	// if auto locking, skip extra checks, because only flags can be changed
+	if( !(object.iFlags & EMdEObjectFlagAutoLock) )
+		{
+		// leave if GUID high and low are 0
+		if( object.iGuidHigh == 0 && object.iGuidLow == 0 )
+			{
+			User::Leave( KErrCorrupt );
+			}
+
+		// leave if URI is "empty"
+		if( uri.Length() == 0 )
+			{
+			User::Leave( KErrCorrupt );
+			}
+		}
+
+	TBool KBaseObjectPropertyMod = EFalse;
+	TBool KObjectPropertyMod     = EFalse;
+
+	if (KUpdateModObject)
+		{
+		clauseBaseObject.AppendL( KMdsObjectUpdateBaseObjectFlags );
+		baseObjectRow.AppendL( TColumn( objectFlags ) );
+
+		if( !(object.iFlags & EMdEObjectFlagAutoLock) )
+			{
+			clauseBaseObject.AppendL( KMdsObjectUpdateBaseObjectEnd );
+			baseObjectRow.AppendL( TColumn( object.iMediaId ) );
+			baseObjectRow.AppendL( TColumn( object.iGuidHigh ) );
+			baseObjectRow.AppendL( TColumn( object.iGuidLow ) );
+			baseObjectRow.AppendL( TColumn( uri ) );
+			}
+		KBaseObjectPropertyMod = ETrue;
+		}
+
+	// read properties array
+	if ( KUpdateModProperty )
+		{
+		// try to add property and increase property count
+		for ( TUint32 i = 0; i < object.iProperties.iPtr.iCount; ++i )
+			{
+			aBuffer.PositionL( object.iProperties.iPtr.iOffset + 
+					i * sizeof(TMdCProperty) );
+			TUint8 modFlags;
+			const CMdsPropertyDef& propertyDef = ReadPropertyL( aBuffer, 
+					*objectDef, clauseBaseObject, clauseObject, baseObjectRow, 
+					objectRow, modFlags );
+			// check if property is already in array
+			if ( modFlags == EMdEPropertyModNone )
+				{
+				continue;
+				}
+
+			if( ( modFlags & EMdEPropertyModRemove ) && propertyDef.GetMandatory() )
+				{
+				User::Leave( KErrMdEMandatoryPropertyMissing );
+				}
+
+			const TDefId propertyId = propertyDef.GetId();
+
+			if ( iBaseObjectDef->GetPropertyByIdL( propertyId ) )
+				{
+				if (!KBaseObjectPropertyMod)
+					{
+					// remove comma before first property
+					clauseBaseObject.BufferL().Delete( 
+							clauseBaseObject.ConstBufferL().LocateReverse( ',' ), 1 );
+					KBaseObjectPropertyMod = ETrue;
+					}
+				clauseBaseObject.AppendL( KUpdateEqual );
+				}
+			else
+				{
+				if (!KObjectPropertyMod)
+					{
+					// remove comma before first property
+					clauseObject.BufferL().Delete( 
+							clauseObject.ConstBufferL().LocateReverse( ',' ), 1 );
+					KObjectPropertyMod = ETrue;
+					}
+				clauseObject.AppendL( KUpdateEqual );
+				}
+			}
+		}
+
+	if (KUpdateModObject || KBaseObjectPropertyMod)
+		{
+		clauseBaseObject.AppendL( KMdsObjectUpdateEnd );
+		// append confidential and deleted flags
+		baseObjectRow.AppendL( TColumn( object.iId ) );
+		}
+
+	if (KObjectPropertyMod)
+		{
+		clauseObject.AppendL( KMdsObjectUpdateEnd );
+		// append confidential and deleted flags
+		objectRow.AppendL( TColumn( object.iId ) );
+		}
+
+	TInt queryResult = 0, err;
+    RMdSTransaction transaction( aConnection );
+    CleanupClosePushL( transaction );
+    User::LeaveIfError( transaction.Error() );
+
+	if ( KUpdateModObject || KBaseObjectPropertyMod )
+		{
+		__LOGQUERY_16( _L("Update BaseObject:"), 
+				clauseBaseObject.ConstBufferL(), baseObjectRow);
+		TRAP( err, queryResult = aConnection.ExecuteL( 
+				clauseBaseObject.ConstBufferL(), baseObjectRow ) );
+
+		// Try to remove the object which caused the constraint error and try add the object again.
+		if ( err == KSqlErrConstraint )
+			{
+			__LOG2( ELogQuery, "Update baseObject constraint error - err:%d, queryResult:%d", err, queryResult );
+			// The reason of the constraint error is not checked due to performance hit.
+			TRAP_IGNORE( RemoveObjectForceL( uri, object.iId ) );
+			__LOGQUERY_16( _L("Update AGAIN BaseObject:"), 
+					clauseBaseObject.ConstBufferL(), baseObjectRow);
+			// Fails if the object was not marked as removed.
+			TRAP( err, queryResult = aConnection.ExecuteL( 
+					clauseBaseObject.ConstBufferL(), baseObjectRow ) );
+			}
+
+		if ( err != KErrNone || queryResult != 1 )
+			{
+			__LOG2( ELogQuery, "Update baseObject failed - err:%d, queryResult:%d", err, queryResult );
+			User::Leave( KErrGeneral );
+			}
+		}
+
+	if ( KObjectPropertyMod )
+		{
+		__LOGQUERY_16( _L("Update Object:"), clauseObject.ConstBufferL(), 
+				objectRow);
+		TRAP( err, queryResult = aConnection.ExecuteL( 
+				clauseObject.ConstBufferL(), objectRow ) );
+		if (err != KErrNone || queryResult != 1)
+			{
+			__LOG2( ELogQuery, "Update Object failed - err:%d, queryResult:%d", err, queryResult );
+			User::Leave( KErrGeneral );
+			}
+		}
+
+	if ( KUpdateModFreeText )
+		{
+		if ( object.iFreeTexts.iPtr.iCount > 0 )
+			{
+			aBuffer.PositionL( object.iFreeTexts.iPtr.iOffset );
+			UpdateFreeTextL( aBuffer, object.iFreeTexts.iPtr.iCount, object.iId );
+			}
+		}
+
+    transaction.CommitL();
+    CleanupStack::PopAndDestroy( &transaction );
+
+    CleanupStack::PopAndDestroy( uriBuf );
+    CleanupStack::PopAndDestroy( &commonClauseTwo );
+	CleanupStack::PopAndDestroy( &commonClauseOne );
+
+    // objectRow, baseObjectRow
+	CleanupStack::PopAndDestroy( 2, &baseObjectRow );
+
+	iLockList.UnlockById( *iNamespaceDef, object.iId );
+	return object.iId;
+	}
+
+
+void CMdSSqlObjectManipulate::UpdateFreeTextL( CMdCSerializationBuffer& aBuffer,
+		TInt aCount, TItemId aObjectId )
+	{
+	_LIT( KMdSUpdateFreeTextDelete,     "DELETE FROM TextSearch%u WHERE ObjectId=?;" );
+	_LIT( KMdSUpdateFreeTextDictDelete, "DELETE FROM TextSearchDictionary%u WHERE WordId NOT IN(SELECT WordId FROM TextSearch%u);" );
+	_LIT( KMdSUpdateFreeTextObjectFlagSet,   "UPDATE Object%u SET Flags=Flags|? WHERE ObjectId=?;" );
+	_LIT( KMdSUpdateFreeTextObjectFlagReset, "UPDATE Object%u SET Flags=Flags&? WHERE ObjectId=?;" );
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+	RClauseBuffer commonClauseOne(*this, KMdSUpdateFreeTextDictDelete.iTypeLength + 2*KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& buffer = commonClauseOne.BufferL();
+	RRowData delRow;
+	CleanupClosePushL( delRow );
+
+	delRow.AppendL( TColumn( aObjectId ) );
+	buffer.BufferL().Format( KMdSUpdateFreeTextDelete, iNamespaceDef->GetId() );
+	connection.ExecuteL( buffer.ConstBufferL(), delRow );
+
+	delRow.Free(); delRow.Reset();
+	buffer.BufferL().Format( KMdSUpdateFreeTextDictDelete, iNamespaceDef->GetId(), 
+			iNamespaceDef->GetId() );
+	connection.ExecuteL( buffer.ConstBufferL(), delRow );
+
+	// update object flags
+	delRow.Free(); delRow.Reset();
+	delRow.AppendL( TColumn( EMdEObjectFlagFreetexts ) );
+	delRow.AppendL( TColumn( aObjectId ) );
+	if ( AddFreeTextL( aBuffer, aCount, aObjectId ) > 0 )
+		{
+		buffer.BufferL().Format( KMdSUpdateFreeTextObjectFlagSet, iNamespaceDef->GetId() );
+		}
+	else
+		{
+		buffer.BufferL().Format( KMdSUpdateFreeTextObjectFlagReset, iNamespaceDef->GetId() );
+		delRow.Column(0).Set( ~EMdEObjectFlagFreetexts );
+		}
+	connection.ExecuteL( buffer.ConstBufferL(), delRow );
+
+	CleanupStack::PopAndDestroy( 2, &commonClauseOne ); // delRow, commonClauseOne
+	}
+
+TItemId CMdSSqlObjectManipulate::AddEventL( CMdSSqLiteConnection& aConnection, 
+		CMdCSerializationBuffer& aBuffer )
+	{
+	_LIT( KAddEvent, "INSERT INTO Event%u(EventId,ObjectId,EventDefId,Timestamp,Source,Participant) VALUES(?,?,?,?,?,?);" );
+
+	if ( !iNamespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+	
+	RClauseBuffer commonClauseOne(*this, KAddEvent().Length() + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& sqlBuf = commonClauseOne.BufferL();
+	sqlBuf.BufferL().Format( KAddEvent, iNamespaceDef->GetId() );
+
+   	RRowData var;
+    CleanupClosePushL( var );
+
+    const TMdCEvent& event = TMdCEvent::GetFromBufferL( aBuffer );
+
+    TItemId eventId = event.iId;
+	if ( eventId != KNoId )
+		{
+		User::Leave( KErrArgument );
+		}
+	
+	RSQLIndex sqlIndex;
+	CleanupClosePushL( sqlIndex );
+	eventId = sqlIndex.GetId();
+
+	if ( !iNamespaceDef->GetEventByIdL( event.iDefId ) )
+		{
+		User::Leave( KErrMdEUnknownEventDef );
+		}
+
+    if ( event.iObjectId == KNoId )
+    	{
+    	User::Leave( KErrCorrupt );
+    	}
+
+    var.AppendL( TColumn( eventId ) );
+    var.AppendL( TColumn( event.iObjectId ) );
+    var.AppendL( TColumn( event.iDefId ) );
+    var.AppendL( TColumn( event.iTime.Int64() ) );
+
+    TPtrC16 source;
+    if ( event.iSourceText.iPtr.iCount > 0 )
+    	{
+    	aBuffer.PositionL( event.iSourceText.iPtr.iOffset );
+        source.Set( aBuffer.ReceivePtr16L() );
+    	}
+    else
+    	{
+    	source.Set( TPtr16((TUint16*)0, 0) );
+    	}
+    var.AppendL( TColumn( source ) );
+
+	TPtrC16 participant;
+    if ( event.iParticipantText.iPtr.iCount > 0 )
+    	{
+    	aBuffer.PositionL( event.iParticipantText.iPtr.iOffset );
+    	participant.Set( aBuffer.ReceivePtr16L() );
+    	}
+    else
+    	{
+    	participant.Set( TPtr16((TUint16*)0, 0) );
+    	}
+    var.AppendL( TColumn( participant ) );
+
+    aConnection.ExecuteL( sqlBuf.ConstBufferL(), var );
+
+	sqlIndex.Commit();
+	CleanupStack::PopAndDestroy( 3, &commonClauseOne ); // sqlIndex, var, commonClauseOne
+	return eventId;
+	}
+        
+TItemId CMdSSqlObjectManipulate::AddRelationL( 
+		CMdSSqLiteConnection& aConnection, CMdCSerializationBuffer& aBuffer )
+	{
+	_LIT( KAddRelation, "INSERT INTO Relations%u(RelationId,Flags,RelationDefId,LeftObjectId,RightObjectId,Parameter,GuidHigh,GuidLow,LastModifiedDate) VALUES(?,?,?,?,?,?,?,?,?);" );
+
+	if ( !iNamespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+	
+	RClauseBuffer commonClauseOne(*this, KAddRelation().Length() + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& buffer = commonClauseOne.BufferL();
+	buffer.BufferL().Format( KAddRelation, iNamespaceDef->GetId() );
+
+    RRowData var;
+	CleanupClosePushL( var );
+
+	const TMdCRelation& relation = TMdCRelation::GetFromBufferL( aBuffer );
+	TItemId relationId = relation.iId;
+
+	if ( relationId != KNoId )
+		{
+		User::Leave( KErrArgument );
+		}
+	
+	RSQLIndex sqlIndex;
+	CleanupClosePushL( sqlIndex );
+	relationId = sqlIndex.GetId();
+
+	if ( !iNamespaceDef->GetRelationByIdL( relation.iDefId ) )
+		{
+		User::Leave( KErrMdEUnknownRelationDef );
+		}
+
+    if ( relation.iLeftObjectId == KNoId || relation.iRightObjectId == KNoId )
+    	{
+    	User::Leave( KErrCorrupt );
+    	}
+
+	TInt64 guidHigh = relation.iGuidHigh;
+	TInt64 guidLow = relation.iGuidLow;
+	if ( guidHigh == 0 && guidLow == 0 )
+		{
+		iGenerator->GenerateGuid( guidHigh, guidLow );
+		}
+
+	// if last modified date is 0, set it to current universal time
+	TInt64 lastModifiedDate = relation.iLastModifiedDate.Int64();
+	if( lastModifiedDate == 0 )
+		{
+		TTime currentTime;
+		currentTime.UniversalTime();
+		lastModifiedDate = currentTime.Int64();
+		}
+
+    var.AppendL( TColumn( relationId ) );
+    var.AppendL( TColumn( TUint32(0) ) ); // no flags
+    var.AppendL( TColumn( relation.iDefId) );
+    var.AppendL( TColumn( relation.iLeftObjectId ) );
+    var.AppendL( TColumn( relation.iRightObjectId ) );
+    var.AppendL( TColumn( relation.iParameter ) );
+    var.AppendL( TColumn( guidHigh ) );
+    var.AppendL( TColumn( guidLow ) );
+    var.AppendL( TColumn( lastModifiedDate ) );
+
+    aConnection.ExecuteL( buffer.ConstBufferL(), var );
+
+	sqlIndex.Commit();
+	CleanupStack::PopAndDestroy( 3, &commonClauseOne ); // sqlIndex, var, commonClauseOne
+	return relationId;
+	}
+
+void CMdSSqlObjectManipulate::RemoveRelationsL( CMdCSerializationBuffer& aBuffer,
+		TInt aCount, RArray<TItemId>& aIdArray )
+    {	
+	_LIT( KRemoveRelation, "UPDATE Relations%u SET Flags=Flags|? WHERE RelationId=? AND NOT Flags&?;" );
+    CMdSSqLiteConnection& db = MMdSDbConnectionPool::GetDefaultDBL();
+    
+	RClauseBuffer commonClauseOne(*this, KRemoveRelation().Length() + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& buf = commonClauseOne.BufferL();
+    buf.BufferL().Format( KRemoveRelation, iNamespaceDef->GetId() );
+
+	TInt queryResult = 0;
+	TItemId relationId = KNoId;
+
+    RRowData varRemove;
+    CleanupClosePushL( varRemove );
+    varRemove.AppendL( TColumn( 
+    		EMdERelationFlagDeleted | EMdERelationFlagGarbageDeleted ) );
+    varRemove.AppendL( TColumn( relationId ) );
+    varRemove.AppendL( TColumn( 
+    		EMdERelationFlagDeleted | EMdERelationFlagNotPresent ) );
+
+	for ( TUint32 i = 0; i < aCount; ++i )
+		{
+		aBuffer.ReceiveL( relationId );
+		varRemove.Column( 1 ).Set( relationId );
+		TRAPD( err, queryResult = db.ExecuteL( buf.ConstBufferL(), varRemove ) );
+		if ( err == KErrNone && queryResult == 1 )
+			{
+			aIdArray.AppendL( relationId );
+			}
+		else
+			{
+			aIdArray.AppendL( KNoId );
+			}
+		}
+	CleanupStack::PopAndDestroy( 2, &commonClauseOne ); // varRemove, commonClauseOne
+    }
+
+void CMdSSqlObjectManipulate::RemoveEventsL( CMdCSerializationBuffer& aBuffer, 
+		TInt aCount, RArray<TItemId>& aIdArray )
+    {
+	_LIT( KRemoveEvent, "DELETE FROM Event%u WHERE EventId=?;" );
+
+    CMdSSqLiteConnection& db = MMdSDbConnectionPool::GetDefaultDBL();
+
+	RClauseBuffer commonClauseOne(*this, KRemoveEvent().Length() + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& buf = commonClauseOne.BufferL();
+    buf.BufferL().Format( KRemoveEvent, iNamespaceDef->GetId() );
+
+	TInt queryResult = 0;
+	TItemId eventId = KNoId;
+
+    RRowData varRemove;
+    CleanupClosePushL( varRemove );
+    varRemove.AppendL( TColumn( eventId ) );
+
+	for ( TUint32 i = 0; i < aCount; ++i )
+		{
+		aBuffer.ReceiveL( eventId );
+		varRemove.Column( 0 ).Set( eventId );
+		TRAPD( err, queryResult = db.ExecuteL( buf.ConstBufferL(), varRemove ) );
+		if ( err == KErrNone && queryResult == 1 )
+			{
+			aIdArray.AppendL( eventId );
+			}
+		else
+			{
+			aIdArray.AppendL( KNoId );
+			}
+		}
+	CleanupStack::PopAndDestroy( 2, &commonClauseOne ); // varRemove, commonClauseOne
+    }
+
+TItemId CMdSSqlObjectManipulate::UpdateRelationsL(
+		CMdSSqLiteConnection& aConnection, CMdCSerializationBuffer& aBuffer )
+    {	
+	_LIT( KUpdateRelation, "UPDATE Relations%u SET RelationDefId=?,LeftObjectId=?,RightObjectId=?,Parameter=?,GuidHigh=?,GuidLow=?,LastModifiedDate=? WHERE NOT Flags&? AND NOT Flags&? AND RelationId=?;" );
+
+if ( !iNamespaceDef )
+		{
+		User::Leave( KErrMdEUnknownNamespaceDef );
+		}
+	
+	RClauseBuffer commonClauseOne(*this, KUpdateRelation().Length() + KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& sqlBuf = commonClauseOne.BufferL();
+    sqlBuf.BufferL().Format( KUpdateRelation, iNamespaceDef->GetId() );
+
+    RRowData var;
+    CleanupClosePushL( var );
+
+    const TMdCRelation& relation = TMdCRelation::GetFromBufferL( aBuffer );
+
+    if ( relation.iId == KNoId )
+    	{
+    	User::Leave( KErrArgument );
+    	}
+
+    if ( !iNamespaceDef->GetRelationByIdL( relation.iDefId ) )
+		{
+		User::Leave( KErrMdEUnknownRelationDef );
+		}
+
+	// leave if GUID high and low are 0
+	if( relation.iGuidHigh == 0 && relation.iGuidLow == 0 )
+		{
+		User::Leave( KErrCorrupt );
+		}
+
+	// if last modified date is 0, set it to current universal time
+	TInt64 lastModifiedDate = relation.iLastModifiedDate.Int64();
+	if( lastModifiedDate == 0 )
+		{
+		TTime currentTime;
+		currentTime.UniversalTime();
+		lastModifiedDate = currentTime.Int64();
+		}
+
+    var.AppendL( TColumn( relation.iDefId ) );
+    var.AppendL( TColumn( relation.iLeftObjectId ) );
+    var.AppendL( TColumn( relation.iRightObjectId ) );
+    var.AppendL( TColumn( relation.iParameter ) );
+    var.AppendL( TColumn( relation.iGuidHigh ) );
+    var.AppendL( TColumn( relation.iGuidLow ) );
+    var.AppendL( TColumn( lastModifiedDate ) );
+    var.AppendL( TColumn( EMdERelationFlagNotPresent ) );
+    var.AppendL( TColumn( EMdERelationFlagDeleted ) );
+	var.AppendL( TColumn( relation.iId ) );
+
+	aConnection.ExecuteL( sqlBuf.ConstBufferL(), var );
+
+	CleanupStack::PopAndDestroy( 2, &commonClauseOne ); // var, commonClauseOne
+
+	return relation.iId;
+    }
+
+void CMdSSqlObjectManipulate::GetRemovedRelationItemsL( CMdCSerializationBuffer& aBuffer,
+		const RArray<TItemId>& aRemovedRelations,
+		const RArray<TItemId>& aAdditionalRemovedRelations )
+	{
+	_LIT( KGetRelationItemsStart, "SELECT RelationId,RelationDefId,LeftObjectId,RightObjectId FROM Relations%u WHERE Flags&? AND RelationId IN(?" );
+	_LIT( KGetRelationItemsMiddle, ",?" );
+	_LIT( KGetRelationItemsEnd, ");" );
+
+	const TInt relationsCount = aRemovedRelations.Count() + aAdditionalRemovedRelations.Count();
+	
+	TMdCItems relationItems;
+	
+	relationItems.iNamespaceDefId = iNamespaceDef->GetId();
+	relationItems.iRelations.iPtr.iCount = 0; // will be updated later
+	relationItems.iRelations.iPtr.iOffset = sizeof( TMdCItems );
+
+	if ( relationsCount == 0 )
+		{
+		relationItems.SerializeL( aBuffer );
+
+		return;
+		}
+	
+	RClauseBuffer commonClauseOne(*this, KGetRelationItemsStart().Length() + KMaxUintValueLength
+			+ KGetRelationItemsMiddle().Length() * relationsCount 
+			+ KGetRelationItemsEnd().Length() );
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& sqlBuffer = commonClauseOne.BufferL();
+	sqlBuffer.BufferL().Format( KGetRelationItemsStart, iNamespaceDef->GetId() );
+
+    RRowData var;
+    CleanupClosePushL( var );
+    var.ReserveL( 1 + relationsCount );
+    var.AppendL( EMdERelationFlagDeleted );
+
+    const TInt removedRelationsCount = aRemovedRelations.Count();
+    for (TInt i = 0; i < removedRelationsCount-1; ++i)
+    	{
+    	sqlBuffer.AppendL( KGetRelationItemsMiddle );
+    	var.AppendL( aRemovedRelations[i] );
+    	}
+    if ( removedRelationsCount )
+    	{
+	    var.AppendL( aRemovedRelations[removedRelationsCount-1] );
+    	}
+
+    const TInt additionalRemovedRelationsCount = aAdditionalRemovedRelations.Count();
+    for (TInt i = 0; i < additionalRemovedRelationsCount-1; ++i)
+    	{
+    	sqlBuffer.AppendL( KGetRelationItemsMiddle );
+    	var.AppendL( aAdditionalRemovedRelations[i] );
+    	}
+    if ( removedRelationsCount == 0 /*&& additionalRemovedRelationsCount*/ )
+    	{
+    	// cannot be empty
+    	var.AppendL( aAdditionalRemovedRelations[additionalRemovedRelationsCount-1] );
+    	}
+    
+    sqlBuffer.AppendL( KGetRelationItemsEnd );
+    
+	RMdsStatement getQuery;
+    CleanupClosePushL( getQuery );
+
+	__LOGQUERY_16( _L("CMdSSqlObjectManipulate::GetRemovedRelationItemsL:"), 
+			sqlBuffer.ConstBufferL(), var);
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	
+    connection.ExecuteQueryL( sqlBuffer.ConstBufferL(), getQuery, var );
+
+	var.Free(); 
+	var.Reset();
+
+    var.ReserveL( 4 );
+    
+    TMdCRelation relation;
+	var.AppendL( relation.iId );
+	var.AppendL( relation.iDefId );
+	var.AppendL( relation.iLeftObjectId );
+	var.AppendL( relation.iRightObjectId );
+	
+    TUint32 resultCount = 0;
+    
+    // move position after items
+	aBuffer.PositionL( relationItems.iRelations.iPtr.iOffset );
+
+	while( connection.NextRowL( getQuery, var ) )
+		{
+		++resultCount;
+
+		var.Column( 0 ).Get( relation.iId );
+		var.Column( 1 ).Get( relation.iDefId );
+		var.Column( 2 ).Get( relation.iLeftObjectId );
+		var.Column( 3 ).Get( relation.iRightObjectId );
+
+		relation.SerializeL( aBuffer );
+		}
+
+	// update relation count
+	relationItems.iRelations.iPtr.iCount = resultCount;
+
+	// move position to begin of buffer and serialize items
+	aBuffer.PositionL( KNoOffset );
+	relationItems.SerializeL( aBuffer );
+
+	CleanupStack::PopAndDestroy( 3, &commonClauseOne ); // getQuery, var, commonClauseOne
+	}
+
+void CMdSSqlObjectManipulate::SetPendingL(const RArray<TItemId>& aObjectIds, 
+		TBool aReset)
+	{
+	_LIT( KUpdatePending,   "UPDATE Object%u SET Flags=Flags%c? WHERE ObjectId IN(?" );
+	_LIT( KUpdatePendingMiddle, ",?" );
+	_LIT( KUpdatePendingEnd, ");" );
+
+    CMdSSqLiteConnection& db = MMdSDbConnectionPool::GetDefaultDBL();
+
+    const TInt objectIdsCount = aObjectIds.Count();
+
+	RClauseBuffer commonClause(*this, KUpdatePending().Length() + KMaxUintValueLength + 
+			KUpdatePendingMiddle().Length() * (objectIdsCount - 1) + 
+			KUpdatePendingEnd().Length() );
+	CleanupClosePushL( commonClause );
+	CMdsClauseBuffer& buf = commonClause.BufferL();
+
+	const TChar KSetUpdateFlag = '|';
+	const TChar KResetUpdateFlag = '&';
+	
+	TChar flagUpdate = KSetUpdateFlag; // set flag
+	TUint32 objectFlag = EMdeObjectFlagPending;
+
+	if( aReset )
+		{
+		flagUpdate = KResetUpdateFlag; // reset flag
+		objectFlag = ~objectFlag; // not pending flag
+		}
+	
+    buf.BufferL().Format( KUpdatePending, KDefaultNamespaceDefId, (TUint)flagUpdate );
+
+    RRowData var;
+    CleanupClosePushL( var );
+
+    var.ReserveL( 1 + objectIdsCount );
+    
+    var.AppendL( TColumn( objectFlag ) );
+
+	var.AppendL( aObjectIds[0] );
+    for (TInt i = 1; i < objectIdsCount; ++i)
+    	{
+    	buf.AppendL( KUpdatePendingMiddle );
+    	var.AppendL( aObjectIds[i] );
+    	}
+    buf.AppendL( KUpdatePendingEnd );
+
+    db.ExecuteL( buf.ConstBufferL(), var );
+
+	CleanupStack::PopAndDestroy( 2, &commonClause ); // var, commonClause
+	}
+
+TInt CMdSSqlObjectManipulate::GetPendingCountL(TDefId aObjectDefId)
+	{
+	_LIT( KGetPendingCount,   "SELECT count(*) FROM Object%u WHERE Flags&? AND NOT Flags&?" );
+	_LIT( KGetPendingCountObjectDefId, " AND ObjectDefId=?" );
+	_LIT( KGetPendingCountEnd, ";" );
+
+    CMdSSqLiteConnection& db = MMdSDbConnectionPool::GetDefaultDBL();
+
+    TInt bufferSize = KGetPendingCount().Length() + KMaxUintValueLength + 
+    		KGetPendingCountEnd().Length();
+    
+	if( aObjectDefId != KNoDefId )	
+		{
+		bufferSize += KGetPendingCountObjectDefId().Length();
+		}
+    
+	RClauseBuffer commonClause( *this, bufferSize );
+	CleanupClosePushL( commonClause );
+	CMdsClauseBuffer& buf = commonClause.BufferL();
+    buf.BufferL().Format( KGetPendingCount, KDefaultNamespaceDefId );
+    
+    TInt varReservation = 2;
+    
+	if( aObjectDefId != KNoDefId )	
+		{
+		buf.AppendL( KGetPendingCountObjectDefId );
+		++varReservation;
+		}
+
+	buf.AppendL( KGetPendingCountEnd );
+	
+    RRowData var;
+    CleanupClosePushL( var );
+
+    var.ReserveL( varReservation );
+
+    var.AppendL( TColumn( EMdeObjectFlagPending ) );
+    var.AppendL( TColumn( EMdEObjectFlagNotPresent | EMdEObjectFlagRemoved | 
+    		EMdEObjectFlagPlaceholder | EMdEObjectFlagStartUpNotPresent ) );
+
+    if( aObjectDefId != KNoDefId )
+    	{
+    	var.AppendL( TColumn( aObjectDefId ) );
+    	}
+    
+	RMdsStatement getQuery;
+    CleanupClosePushL( getQuery );
+
+	db.ExecuteQueryL( buf.ConstBufferL(), getQuery, var );
+
+	var.Free();
+	var.Reset();
+
+	TUint32 count = 0;
+	
+	var.AppendL( TColumn( count ) );
+
+	if ( db.NextRowL( getQuery, var ) )
+		{
+		var.Column(0).Get( count );
+		}
+
+	CleanupStack::PopAndDestroy( 2, &var ); // getQuery, varSearch
+	CleanupStack::PopAndDestroy( &commonClause );
+	
+	return count;
+	}
+
+TInt CMdSSqlObjectManipulate::GetPendingL(TDefId aObjectDefId, 
+		TInt aBufferSize, RArray<TItemId>& aObjectIds)
+	{
+	_LIT( KGetPending,   "SELECT ObjectId FROM Object%u WHERE Flags&? AND NOT Flags&?" );
+	_LIT( KGetPendingObjectDefId, " AND ObjectDefId=?" );
+	_LIT( KGetPendingEnd, " LIMIT ?;" );
+
+    CMdSSqLiteConnection& db = MMdSDbConnectionPool::GetDefaultDBL();
+
+    TInt bufferSize = KGetPending().Length() + KMaxUintValueLength + 
+    		KGetPendingEnd().Length();
+
+	if( aObjectDefId != KNoDefId )	
+		{
+		bufferSize += KGetPendingObjectDefId().Length();
+		}
+
+	RClauseBuffer commonClause( *this, bufferSize );
+	CleanupClosePushL( commonClause );
+	CMdsClauseBuffer& buf = commonClause.BufferL();
+    buf.BufferL().Format( KGetPending, KDefaultNamespaceDefId );
+
+    TInt varReservation = 3;
+
+	if( aObjectDefId != KNoDefId )	
+		{
+		buf.AppendL( KGetPendingObjectDefId );
+		++varReservation;
+		}
+
+	buf.AppendL( KGetPendingEnd );
+
+    RRowData var;
+    CleanupClosePushL( var );
+
+    var.ReserveL( varReservation );
+
+    var.AppendL( TColumn( EMdeObjectFlagPending ) );
+    var.AppendL( TColumn( EMdEObjectFlagNotPresent | EMdEObjectFlagRemoved | 
+    		EMdEObjectFlagPlaceholder | EMdEObjectFlagStartUpNotPresent ) );
+
+    if( aObjectDefId != KNoDefId )
+    	{
+    	var.AppendL( TColumn( aObjectDefId ) );
+    	}
+
+    // get as much as possible to buffer and check if there is more than that
+    var.AppendL( TColumn( aBufferSize + 1 ) );
+
+	RMdsStatement getQuery;
+    CleanupClosePushL( getQuery );
+
+	db.ExecuteQueryL( buf.ConstBufferL(), getQuery, var );
+
+	var.Free();
+	var.Reset();
+
+	TItemId objectId = 0;
+
+	var.AppendL( TColumn( objectId ) );
+
+	TInt extraRows = 0;
+
+	while( db.NextRowL( getQuery, var ) )
+		{
+		var.Column(0).Get( objectId );
+		
+		if( aObjectIds.Count() < aBufferSize )
+			{
+			aObjectIds.Append( objectId );
+			}
+		else
+			{
+			extraRows = 1;
+			break;
+			}
+		}
+
+	CleanupStack::PopAndDestroy( 2, &var ); // getQuery, varSearch
+	CleanupStack::PopAndDestroy( &commonClause );
+
+	return extraRows;
+	}
+
+TBool CMdSSqlObjectManipulate::DoGarbageCollectionL()
+	{
+	_LIT( KDeleteObject,                 "DELETE FROM Object%u WHERE Flags&?;" );
+	_LIT( KUpdateDeleteObject,           "UPDATE Object%u SET Flags=Flags|? WHERE Flags&?;" );
+	_LIT( KDeleteRelations,              "DELETE FROM Relations%u WHERE Flags&?;" );
+	_LIT( KUpdateDeleteRelations,        "UPDATE Relations%u SET Flags=Flags|? WHERE Flags&?;" );
+	_LIT( KUpdateDeleteContextObjects,   "UPDATE Object%u SET Flags=Flags|? WHERE ObjectId IN ( SELECT ObjectId FROM Object%u AS O WHERE Flags&? AND UsageCount=0 AND ( SELECT count(*) FROM Relations%u WHERE NOT Flags&? AND ( LeftObjectId = O.ObjectId OR RightObjectId = O.ObjectId ) )= 0 );" );
+    _LIT( KDeleteWordFromTextSearchDict, "DELETE FROM TextSearchDictionary%u WHERE NOT EXISTS(SELECT WordId FROM TextSearch%u WHERE WordId = TextSearchDictionary%u.WordId);");
+
+
+	RClauseBuffer commonClauseOne(*this, KUpdateDeleteContextObjects().Length() + 3 * KMaxUintValueLength);
+	CleanupClosePushL( commonClauseOne );
+	CMdsClauseBuffer& buffer = commonClauseOne.BufferL();
+
+    RRowData rowDataDel;
+    CleanupClosePushL( rowDataDel );
+    rowDataDel.AppendL( TColumn( EMdEObjectFlagGarbage ) );
+
+    RRowData rowDataUpd;
+    CleanupClosePushL( rowDataUpd );
+    rowDataUpd.AppendL( TColumn( EMdEObjectFlagGarbage ) );
+    rowDataUpd.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+
+    RRowData rowDataDelRel;
+    CleanupClosePushL( rowDataDelRel );
+    rowDataDelRel.AppendL( TColumn( EMdERelationFlagGarbageDeleted ) );
+
+    RRowData rowDataUpdRel;
+    CleanupClosePushL( rowDataUpdRel );
+    rowDataUpdRel.AppendL( TColumn( EMdERelationFlagGarbageDeleted ) );
+    rowDataUpdRel.AppendL( TColumn( EMdERelationFlagDeleted ) );
+
+    RRowData rowDataDelContext;
+    CleanupClosePushL( rowDataDelContext );
+    rowDataDelContext.AppendL( TColumn( EMdEObjectFlagRemoved ) );
+    rowDataDelContext.AppendL( TColumn( EMdEObjectFlagContext ) );
+    rowDataDelContext.AppendL( TColumn( EMdERelationFlagDeleted ) );
+
+	RRowData emptyRow;
+	CleanupClosePushL( emptyRow );
+
+   	const RPointerArray<CMdsNamespaceDef>& namespaceDefs = 
+   		iSchema.NamespaceDefs();
+
+	CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+	TInt deleteObjectResult;
+	TInt updateResult = 0;
+	
+	const TInt count = namespaceDefs.Count();
+	
+   	for( TInt i = 0; i < count; ++i )
+   	    {
+   	    const TDefId nmspId = namespaceDefs[i]->GetId();
+
+		// deleting objects
+		buffer.BufferL().Format( KDeleteObject, nmspId );
+   	    User::LeaveIfError( deleteObjectResult = connection.ExecuteL( 
+   	    		buffer.ConstBufferL(), rowDataDel ) );
+
+        buffer.BufferL().Format( KUpdateDeleteObject, nmspId );
+   	    User::LeaveIfError( updateResult += connection.ExecuteL(
+   	    		buffer.ConstBufferL(), rowDataUpd ) );
+
+		// deleting relations
+		buffer.BufferL().Format( KDeleteRelations, nmspId );
+   	    User::LeaveIfError( connection.ExecuteL( 
+   	    		buffer.ConstBufferL(), rowDataDelRel ) );
+
+		buffer.BufferL().Format( KUpdateDeleteRelations, nmspId );
+   	    User::LeaveIfError( updateResult += connection.ExecuteL( 
+   	    		buffer.ConstBufferL(), rowDataUpdRel ) );
+
+		// deleting context objects
+		buffer.BufferL().Format( KUpdateDeleteContextObjects, nmspId, nmspId, nmspId );
+   	    User::LeaveIfError( updateResult += connection.ExecuteL( 
+   	    		buffer.ConstBufferL(), rowDataDelContext ) );
+
+		// deleting words from text search dictionary
+		if ( deleteObjectResult > 0 )
+			{
+			buffer.BufferL().Format( KDeleteWordFromTextSearchDict, nmspId, nmspId, 
+					nmspId );
+	   	    User::LeaveIfError( connection.ExecuteL( 
+	   	    		buffer.ConstBufferL(), emptyRow ) );
+			}
+   	    }
+
+   	// empryRow, rowDataDelContext, rowDataUpdRel, rowDataDelRel, rowDataUpd, 
+   	// rowDataDel, commonClauseOne
+	CleanupStack::PopAndDestroy( 7, &commonClauseOne );
+
+	return updateResult != 0;
+	}
+
+CMdSSqlObjectManipulate::RClauseBuffer::RClauseBuffer( CMdSSqlObjectManipulate& aSOM, TInt aSize )
+	: iBuffers( aSOM.iBuffers ), iBuffer( NULL ), iNr( -1 ), iSize( aSize )
+	{
+	// search for available buffer
+	// or create new one
+	for (TInt i = 0; i < iBuffers.Count(); ++i)
+		{
+		if (!iBuffers[i].iLock)
+			{
+			iBuffers[i].iLock = ETrue;
+			iBuffer = iBuffers[i].iBuffer;
+			iNr = i;
+			TRAP_IGNORE( iBuffer->ReserveSpaceL(aSize) );
+			TRAP_IGNORE( iBuffer->BufferL().Zero() );
+			return;
+			}
+		}
+	}
+
+CMdsClauseBuffer& CMdSSqlObjectManipulate::RClauseBuffer::BufferL()
+	{
+	if ( iNr < 0 && !iBuffer )
+		{
+		iBuffer = CMdsClauseBuffer::NewL( iSize );
+		}
+	return *iBuffer;
+	}
+
+void CMdSSqlObjectManipulate::RClauseBuffer::Close()
+	{
+	if ( iNr < 0 )
+		{
+		__ASSERT_DEBUG( iBuffer, _L("RClauseBuffer::Close()") );
+		if ( iBuffer )
+			{
+			delete iBuffer;
+			iBuffer = NULL;
+			}
+		}
+	else
+		{
+		iBuffers[iNr].iLock = EFalse;
+		iBuffer = NULL;
+		}
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/sis/depends.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ad:metadata xmlns="http://nokia.com/arrow/repository/ia_component"
+  xmlns:ad="http://nokia.com/arrow/application_metadata">
+  <appResources>
+     <appResource>
+        <language>1</language>
+        <iacName>MdS Metadata Engine</iacName>
+        <iacDescription>Upgrade package for MdS Metadata Engine</iacDescription>
+     </appResource>
+  </appResources>
+  <swPlatformDep>
+     <platform>S60</platform>
+     <versionFrom>
+        <major>5</major>
+        <minor>0</minor>
+        <date>
+           <year>2009</year>
+           <week>16</week>
+        </date>
+     </versionFrom>
+  </swPlatformDep>
+  <interDeps>
+  </interDeps>
+</ad:metadata>
\ No newline at end of file
Binary file metadataengine/sis/metadataengine_stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/sis/package.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Metadata Engine Patch"},(0x200009F1), 2, 0, 0, TYPE=SA, RU
+
+; Localised vendor name
+%{"Nokia"}
+
+; Unique vendor name
+:"Nokia"
+
+;Files
+"\EPOC32\RELEASE\ARMV5\UREL\mdeclient.dll" -"c:\sys\bin\mdeclient.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\mdccommon.dll" -"c:\sys\bin\mdccommon.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\mdsserver.exe" -"c:\sys\bin\mdsserver.exe"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/metadataengine/sis/stub.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+; Languages
+&EN
+
+; Header
+#{"Metadata Engine"}, (0x200009F1), 1, 0, 0, TYPE=SA
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+;Files
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/package_definition.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,111 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SystemDefinition schema="3.0.0">
+  <package id="mds" name="Metadata Services" levels="mgr eng server int">
+    <collection id="clfwrapper" name="Content Listing Framework Wrapper" level="int">
+      <component id="clfwrapper_build" filter="s60" name="CLF Wrapper Build" introduced="^2">
+        <unit bldFile="clfwrapper/group"/>
+      </component>
+    </collection>
+    <collection id="contextengine" name="Context Engine" level="eng">
+      <component id="contextengine_plugins" filter="s60" name="Context Engine Plugins" class="plugin" introduced="^2">
+        <unit bldFile="contextengine/plugins/group"/>
+      </component>
+      <component id="contextengine_build" filter="s60" name="Context Engine Build" introduced="^2">
+        <unit bldFile="contextengine/group"/>
+      </component>
+    </collection>
+    <collection id="harvester" name="Harvester" level="eng">
+      <component id="blacklistclient" filter="s60" name="Blacklist Client" introduced="^2">
+        <unit bldFile="harvester/blacklistclient/group"/>
+      </component>
+      <component id="blacklistserver" filter="s60" name="Blacklist Server" introduced="^2">
+        <unit bldFile="harvester/blacklistserver/group"/>
+      </component>
+      <component id="harvester_common" filter="s60" name="Harvester Common" introduced="^2">
+        <unit bldFile="harvester/common/group"/>
+      </component>
+      <component id="composerplugins" filter="s60" name="Composer Plugins" class="plugin" introduced="^2">
+        <unit bldFile="harvester/composerplugins/group"/>
+      </component>
+      <component id="harvesterplugins" filter="s60" name="Harvester Plugins" class="plugin" introduced="^2">
+        <!-- <unit bldFile="harvester/harvesterplugins/audioplaylistplugin/group"/> -->
+        <unit bldFile="harvester/harvesterplugins/group"/>
+      </component>
+      <component id="monitorplugins" filter="s60" name="Monitor Plugins" class="plugin" introduced="^2">
+        <unit bldFile="harvester/monitorplugins/group"/>
+      </component>
+      <component id="harvester_server" filter="s60" name="Harvester Server" introduced="^2">
+        <unit bldFile="harvester/server/group"/>
+      </component>
+      <component id="harvester_client" filter="s60" name="Harvester Client" introduced="^2">
+        <unit bldFile="harvester/client/group"/>
+      </component>
+      <component id="harvester_build" filter="s60" name="Harvester Build" introduced="^2">
+        <unit bldFile="harvester/group"/>
+      </component>
+    </collection>
+    <collection id="locationmanager" name="Location Manager" level="mgr">
+      <component id="locationtrail" filter="s60" name="Location Trail" introduced="^2">
+        <unit bldFile="locationmanager/locationtrail/group"/>
+      </component>
+      <component id="locationmanager_server" filter="s60" name="Location Manager Server" introduced="^2">
+        <unit bldFile="locationmanager/server/group"/>
+      </component>
+      <component id="locationmanager_client" filter="s60" name="Location Manager Client" introduced="^2">
+        <unit bldFile="locationmanager/client/group"/>
+      </component>
+      <component id="locationmanager_build" filter="s60" name="Location Manager Build" introduced="^2">
+      	<!--consider making this collection a single component  -->
+        <unit bldFile="locationmanager/group"/>
+      </component>
+    </collection>
+    <collection id="metadataengine" name="Metadata Engine" level="eng">
+      <component id="metadataengine_common" filter="s60" name="Metadata Engine Common" introduced="^2">
+        <unit bldFile="metadataengine/common/group"/>
+      </component>
+      <component id="metadataengine_server" filter="s60" name="Metadata Engine Server" introduced="^2">
+        <unit bldFile="metadataengine/server/group"/>
+      </component>
+      <component id="metadataengine_client" filter="s60" name="Metadata Engine Client" introduced="^2">
+        <unit bldFile="metadataengine/client/group"/>
+      </component>
+      <component id="metadataengine_build" filter="s60" name="Metadata Engine Build" introduced="^2">
+      	<!--consider making this collection a single component  -->
+        <unit bldFile="metadataengine/group"/>
+      </component>
+    </collection>
+    <collection id="watchdog" name="Watchdog" level="server">
+      <component id="mdswatchdog" filter="s60" name="Metadata Watchdog" introduced="^2">
+        <unit bldFile="watchdog/group"/>
+      </component>
+    </collection>
+    <collection id="iadstoprestart" name="IAD Stop/Restart" level="server">
+      <component id="iadstoprestart_build" filter="s60" name="IAD Stop Restart Build" introduced="^2">
+        <!-- <unit bldFile="iadstoprestart/group"/> -->
+      </component>
+    </collection>
+    <collection id="mds_info" name="Metadata Services Info" level="int">
+      <component id="mds_pub" filter="s60" name="Metadata Services Public Interfaces" class="api" introduced="^2">
+        <unit bldFile="mds_pub/group"/>
+      </component>
+      <component id="mds_plat" filter="s60" name="Metadata Services Platform Interfaces" class="api" introduced="^2">
+        <unit bldFile="mds_plat/group"/>
+        <!--  should #include the rets if they're needed -->
+        <!-- <unit bldFile="mds_plat/content_listing_framework_collection_manager_api/tsrc/group"/> -->
+        <!-- <unit bldFile="mds_plat/context_engine_plugin_api/tsrc/group"/> -->
+        <!-- <unit bldFile="mds_plat/harvester_framework_api/tsrc/composerplugintest/group"/> -->
+        <!-- <unit bldFile="mds_plat/harvester_framework_api/tsrc/group"/> -->
+        <!-- <unit bldFile="mds_plat/harvester_framework_api/tsrc/harvesterclienttest/group"/> -->
+        <!-- <unit bldFile="mds_plat/harvester_framework_api/tsrc/harvesterdatatest/group"/> -->
+        <!-- <unit bldFile="mds_plat/harvester_framework_api/tsrc/harvesterplugintest/group"/> -->
+        <!-- <unit bldFile="mds_plat/harvester_framework_api/tsrc/monitorplugintest/group"/> -->
+        <!-- <unit bldFile="mds_plat/location_manager_api/tsrc/group"/> -->
+        <!-- <unit bldFile="mds_plat/metadata_engine_api/tsrc/group"/> -->
+      </component>
+      <component id="mds_build" filter="s60" name="Metadata Services Build" introduced="^2">
+      	<!-- consider distributiing this into the rest of the components in the package -->
+        <unit bldFile="group"/>
+      </component>
+    </collection>
+  </package>
+</SystemDefinition>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rom/ContentListingFramework.iby	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IBY file for Content Listing Framework
+*
+*/
+
+#ifndef CONTENTLISTINGFRAMEWORK_IBY
+#define CONTENTLISTINGFRAMEWORK_IBY
+
+file=ABI_DIR\BUILD_DIR\ContentListingFramework.dll                     SHARED_LIB_DIR\ContentListingFramework.dll
+file=ABI_DIR\BUILD_DIR\MediaCollectionManager.dll                      SHARED_LIB_DIR\MediaCollectionManager.dll
+
+// Backup registration
+data=ZPRIVATE\101F8857\backup_registration.xml                         	private\101F8857\backup_registration.xml
+
+// Stubs
+//data=ZSYSTEM\install\ContentListingFrameworkStub.sis    System\Install\ContentListingFrameworkStub.sis
+
+#endif // CONTENTLISTINGFRAMEWORK_IBY
+
+//  End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rom/mds.iby	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,109 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*  Metadata system iby file (for ROM image creation)
+*       
+*
+*/
+
+
+#ifndef __METADATA_IBY__
+#define __METADATA_IBY__
+
+// sql is mandatory for mds
+#include <sql.iby>
+
+rem - MdE binaries
+file=ABI_DIR\BUILD_DIR\mdeclient.dll		SHARED_LIB_DIR\mdeclient.dll
+file=ABI_DIR\BUILD_DIR\mdccommon.dll		SHARED_LIB_DIR\mdccommon.dll
+file=ABI_DIR\BUILD_DIR\mdsserver.exe		PROGRAMS_DIR\mdsserver.exe
+
+rem - MdE data files
+data=EPOCROOT##epoc32\data\z\Private\200009F3\schema.mde                PRIVATE\200009F3\schema.mde
+data=EPOCROOT##epoc32\data\z\Private\200009F3\defaultimportfile.mde	    PRIVATE\200009F3\defaultimportfile.mde
+data=EPOCROOT##epoc32\data\z\Private\200009F3\backup_registration.xml   PRIVATE\200009F3\backup_registration.xml
+data=EPOCROOT##epoc32\data\z\Private\200009F5\backup_registration.xml   PRIVATE\200009F5\backup_registration.xml
+data=EPOCROOT##epoc32\data\z\Private\200009F5\mappings.db               PRIVATE\200009F5\mappings.db
+
+rem - Harvester and Context Engine binaries
+file=ABI_DIR\BUILD_DIR\HarvesterPluginInterface.dll		SHARED_LIB_DIR\HarvesterPluginInterface.dll
+file=ABI_DIR\BUILD_DIR\HarvesterClient.dll		        SHARED_LIB_DIR\HarvesterClient.dll
+file=ABI_DIR\BUILD_DIR\HarvesterServer.exe		        PROGRAMS_DIR\HarvesterServer.exe
+file=ABI_DIR\BUILD_DIR\harvestercommon.dll		    SHARED_LIB_DIR\harvestercommon.dll
+file=ABI_DIR\BUILD_DIR\harvesterdata.dll		    SHARED_LIB_DIR\harvesterdata.dll
+file=ABI_DIR\BUILD_DIR\mdsfileserverplugin.pxt			SHARED_LIB_DIR\mdsfileserverplugin.pxt
+ECOM_PLUGIN(HarvesterImagePlugin.dll,HarvesterImagePlugin.rsc)
+ECOM_PLUGIN(HarvesterVideoPlugin.dll,HarvesterVideoPlugin.rsc)
+ECOM_PLUGIN(HarvesterMessagePlugin.dll,HarvesterMessagePlugin.rsc)
+ECOM_PLUGIN(harvesteromadrmplugin.dll,harvesteromadrmplugin.rsc)
+ECOM_PLUGIN(harvesterwmvplugin.dll,harvesterwmvplugin.rsc)
+ECOM_PLUGIN(harvesterrtpplugin.dll,harvesterrtpplugin.rsc)
+ECOM_PLUGIN(harvesteraudioplugin.dll,harvesteraudioplugin.rsc)
+
+rem - Blacklist server binaries
+file=ABI_DIR\BUILD_DIR\blacklistserver.exe		        PROGRAMS_DIR\blacklistserver.exe
+file=ABI_DIR\BUILD_DIR\blacklistclient.dll		        SHARED_LIB_DIR\blacklistclient.dll
+
+file=ABI_DIR\BUILD_DIR\MonitorPluginInterface.dll		SHARED_LIB_DIR\MonitorPluginInterface.dll
+ECOM_PLUGIN(MMCMonitorPlugin.dll,MMCMonitorPlugin.rsc)
+ECOM_PLUGIN(FileMonitorPlugin.dll,FileMonitorPlugin.rsc)
+ECOM_PLUGIN(MessageMonitorPlugin.dll,MessageMonitorPlugin.rsc)
+ECOM_PLUGIN(mdsoomplugin.dll,mdsoomplugin.rsc)
+
+file=ABI_DIR\BUILD_DIR\ContextPluginInterface.dll		SHARED_LIB_DIR\ContextPluginInterface.dll
+file=ABI_DIR\BUILD_DIR\ContextEngine.dll		        SHARED_LIB_DIR\ContextEngine.dll
+ECOM_PLUGIN(locationcontextplugin.dll,locationcontextplugin.rsc)
+ECOM_PLUGIN(calendarcontextplugin.dll,calendarcontextplugin.rsc)
+
+file=ABI_DIR\BUILD_DIR\ComposerPluginInterface.dll		SHARED_LIB_DIR\ComposerPluginInterface.dll
+ECOM_PLUGIN(ComposerImagePlugin.dll,ComposerImagePlugin.rsc)
+
+// Location Manager
+REM locationmanager
+file=ABI_DIR\BUILD_DIR\locationmanager.dll		    SHARED_LIB_DIR\locationmanager.dll
+
+REM locationmanagerserver
+file=ABI_DIR\BUILD_DIR\locationmanagerserver.exe	PROGRAMS_DIR\locationmanagerserver.exe
+
+REM watchdog
+file=ABI_DIR\BUILD_DIR\mdswatchdog.exe	PROGRAMS_DIR\mdswatchdog.exe
+
+REM locationtrail
+file=ABI_DIR\BUILD_DIR\locationtrail.dll		    SHARED_LIB_DIR\locationtrail.dll
+
+REM Location Manager data files
+data=ZPRIVATE\10202BE9\200071BE.txt					"PRIVATE\10202BE9\200071BE.txt"
+
+REM Harvester Cen Repo file
+data=ZPRIVATE\10202BE9\200009FE.txt					"PRIVATE\10202BE9\200009FE.txt"
+
+REM MdS version CenRep file
+data=ZPRIVATE\10202BE9\200009F3.txt                 "PRIVATE\10202BE9\200009F3.txt"
+
+REM Harvester MMC plugin CenRep file
+data=ZPRIVATE\10202BE9\20007183.txt                 "PRIVATE\10202BE9\20007183.txt"
+
+data=ZSYSTEM\install\contentlistingframework_stub.sis       system\install\contentlistingframework_stub.sis
+data=ZSYSTEM\install\contextengine_stub.sis       system\install\contextengine_stub.sis
+data=ZSYSTEM\install\blacklistserver_stub.sis       system\install\blacklistserver_stub.sis
+data=ZSYSTEM\install\composerplugins_stub.sis       system\install\composerplugins_stub.sis
+data=ZSYSTEM\install\harvester_stub.sis	system\install\harvester_stub.sis
+data=ZSYSTEM\install\harvesterplugins_stub.sis	system\install\harvesterplugins_stub.sis
+data=ZSYSTEM\install\monitorplugins_stub.sis	system\install\monitorplugins_stub.sis
+data=ZSYSTEM\install\locationmanager_stub.sis	system\install\locationmanager_stub.sis
+data=ZSYSTEM\install\metadataengine_stub.sis	system\install\metadataengine_stub.sis
+data=ZSYSTEM\install\mds_stub.sis	system\install\mds_stub.sis
+data=ZSYSTEM\install\mdswatchdog_stub.sis	system\install\mdswatchdog_stub.sis
+
+#endif //__METADATA_IBY__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rom/mds_testers.iby	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,66 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Metadata system iby file (for ROM image creation)
+*
+*/
+
+#ifndef __METADATATESTERS_IBY__
+#define __METADATATESTERS_IBY__
+
+rem - !!! TEST APPLICATIONS !!!
+S60_APP_EXE(mdeexample)
+S60_APP_AIF_RSC(mdeexample)
+S60_APP_RESOURCE(mdeexample)
+
+//S60_APP_EXE(HarvesterPluginTester)
+//S60_APP_AIF_RSC(HarvesterPluginTester)
+//S60_APP_RESOURCE(HarvesterPluginTester)
+
+S60_APP_EXE(HarvesterClientTest)
+S60_APP_AIF_RSC(HarvesterClientTest)
+S60_APP_RESOURCE(HarvesterClientTest)
+
+//S60_APP_EXE(MonitorPluginTester)
+//S60_APP_AIF_RSC(MonitorPluginTester)
+//S60_APP_RESOURCE(MonitorPluginTester)
+
+//S60_APP_EXE(ComposerPluginTester)
+//S60_APP_AIF_RSC(ComposerPluginTester)
+//S60_APP_RESOURCE(ComposerPluginTester)
+
+//S60_APP_EXE(mdsfsplugintest)
+//S60_APP_AIF_RSC(mdsfsplugintest)
+//S60_APP_RESOURCE(mdsfsplugintest)
+
+S60_APP_EXE(locationtest)
+S60_APP_AIF_RSC(locationtest)
+S60_APP_RESOURCE(locationtest)
+
+S60_APP_EXE(HarvesterEventTest_0xE1642415)
+S60_APP_AIF_RSC(HarvesterEventTest_0xE1642415)
+S60_APP_RESOURCE(HarvesterEventTest_0xE1642415)
+
+S60_APP_EXE(HarvesterEventTest2_0xE1642416)
+S60_APP_AIF_RSC(HarvesterEventTest2_0xE1642416)
+S60_APP_RESOURCE(HarvesterEventTest2_0xE1642416)
+
+//S60_APP_EXE(LocationPluginTest)
+file=ABI_DIR\BUILD_DIR\locationplugintest.exe	PROGRAMS_DIR\locationplugintest.exe
+file=ABI_DIR\BUILD_DIR\blacklisttest.exe		PROGRAMS_DIR\blacklisttest.exe
+
+rem - Test Application data
+data=EPOCROOT##epoc32\data\z\Private\200009FD\mdeexampleimportmetadata.mde  Data\Others\mdeexampleimportmetadata.mde
+data=EPOCROOT##epoc32\data\z\Private\200009FD\test_schema.mde               Data\Others\test_schema.mde
+
+#endif //__METADATATESTERS_IBY__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sis/mds/depends.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ad:metadata xmlns="http://nokia.com/arrow/repository/ia_component"
+  xmlns:ad="http://nokia.com/arrow/application_metadata">
+  <appResources>
+     <appResource>
+        <language>1</language>
+        <iacName>Metadata System</iacName>
+        <iacDescription>Upgrade package for Metadata System</iacDescription>
+     </appResource>
+  </appResources>
+  <swPlatformDep>
+     <platform>S60</platform>
+     <versionFrom>
+        <major>5</major>
+        <minor>0</minor>
+        <date>
+           <year>2009</year>
+           <week>29</week>
+        </date>
+     </versionFrom>
+  </swPlatformDep>
+  <interDeps>
+  </interDeps>
+</ad:metadata>
\ No newline at end of file
Binary file sis/mds/mds_stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sis/mds/package.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,111 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Metadata System Upgrade"},(0x200009F5), 9, 20, 0, TYPE=SA, RU
+
+; Localised vendor name
+%{"Nokia"}
+
+; Unique vendor name
+:"Nokia"
+
+;Files
+"\epoc32\release\armv5\udeb\mdsiadstop.exe"-"c:\sys\bin\mdsiadstop.exe",FILERUN,RB,RW
+
+; CenRep
+"..\..\clfwrapper\conf\102828AC.txt"-"c:\private\10202be9\102828AC.txt"
+"..\..\harvester\common\data\200009FE.txt"-"c:\private\10202be9\200009FE.txt"
+"..\..\locationmanager\conf\200071BE.txt"-"c:\private\10202be9\200071BE.txt"
+
+; contextengine
+"\EPOC32\RELEASE\ARMV5\UREL\contextengine.dll" -"c:\sys\bin\contextengine.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\contextplugininterface.dll" -"c:\sys\bin\contextplugininterface.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\calendarcontextplugin.dll" -"c:\sys\bin\calendarcontextplugin.dll"
+"\epoc32\data\z\resource\plugins\calendarcontextplugin.rsc" -"c:\resource\plugins\calendarcontextplugin.rsc"
+"\EPOC32\RELEASE\ARMV5\UREL\locationcontextplugin.dll" -"c:\sys\bin\locationcontextplugin.dll"
+"\epoc32\data\z\resource\plugins\locationcontextplugin.rsc" -"c:\resource\plugins\locationcontextplugin.rsc"
+
+; clf wrapper
+"\EPOC32\RELEASE\ARMV5\UREL\MediaCollectionManager.dll" -"c:\sys\bin\MediaCollectionManager.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\ContentListingFramework.dll" -"c:\sys\bin\ContentListingFramework.dll"
+
+; blacklist 
+"\EPOC32\RELEASE\ARMV5\UREL\blacklistserver.exe" -"c:\sys\bin\blacklistserver.exe"
+"\EPOC32\RELEASE\ARMV5\UREL\blacklistclient.dll" -"c:\sys\bin\blacklistclient.dll"
+
+; composer plugins
+"\epoc32\RELEASE\armv5\UREL\composerplugininterface.dll"-"c:\sys\bin\composerplugininterface.dll"
+"\epoc32\RELEASE\armv5\UREL\composerimageplugin.dll"-"c:\sys\bin\composerimageplugin.dll"
+"\epoc32\data\z\resource\plugins\composerimageplugin.rsc"-"c:\resource\plugins\composerimageplugin.rsc"
+
+; harvester
+"\epoc32\RELEASE\armv5\UREL\harvesterclient.dll" -"c:\sys\bin\harvesterclient.dll"
+"\epoc32\RELEASE\armv5\UREL\harvestercommon.dll" -"c:\sys\bin\harvestercommon.dll"
+"\epoc32\RELEASE\armv5\UREL\harvesterdata.dll" -"c:\sys\bin\harvesterdata.dll"
+"\epoc32\RELEASE\armv5\UREL\harvesterplugininterface.dll" -"c:\sys\bin\harvesterplugininterface.dll"
+"\epoc32\RELEASE\armv5\UREL\harvesterserver.exe" -"c:\sys\bin\harvesterserver.exe"
+
+; harvester plugins
+"\epoc32\RELEASE\armv5\UREL\harvesteraudioplugin.dll"-"c:\sys\bin\harvesteraudioplugin.dll"
+"\epoc32\data\z\resource\plugins\harvesteraudioplugin.rsc"-"c:\resource\plugins\harvesteraudioplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\harvesterimageplugin.dll"-"c:\sys\bin\harvesterimageplugin.dll"
+"\epoc32\data\z\resource\plugins\harvesterimageplugin.rsc"-"c:\resource\plugins\harvesterimageplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\harvestermessageplugin.dll"-"c:\sys\bin\harvestermessageplugin.dll"
+"\epoc32\data\z\resource\plugins\harvestermessageplugin.rsc"-"c:\resource\plugins\harvestermessageplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\harvesteromadrmplugin.dll"-"c:\sys\bin\harvesteromadrmplugin.dll"
+"\epoc32\data\z\resource\plugins\harvesteromadrmplugin.rsc"-"c:\resource\plugins\harvesteromadrmplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\harvesterrtpplugin.dll"-"c:\sys\bin\harvesterrtpplugin.dll"
+"\epoc32\data\z\resource\plugins\harvesterrtpplugin.rsc"-"c:\resource\plugins\harvesterrtpplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\harvestervideoplugin.dll"-"c:\sys\bin\harvestervideoplugin.dll"
+"\epoc32\data\z\resource\plugins\harvestervideoplugin.rsc"-"c:\resource\plugins\harvestervideoplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\harvesterwmvplugin.dll"-"c:\sys\bin\harvesterwmvplugin.dll"
+"\epoc32\data\z\resource\plugins\harvesterwmvplugin.rsc"-"c:\resource\plugins\harvesterwmvplugin.rsc"
+
+; monitor plugins
+"\epoc32\RELEASE\armv5\UREL\monitorplugininterface.dll"-"c:\sys\bin\monitorplugininterface.dll"
+"\epoc32\RELEASE\armv5\UREL\mdsfileserverplugin.pxt"-"c:\sys\bin\mdsfileserverplugin.pxt"
+"\epoc32\RELEASE\armv5\UREL\filemonitorplugin.dll"-"c:\sys\bin\filemonitorplugin.dll"
+"\epoc32\data\z\resource\plugins\filemonitorplugin.rsc"-"c:\resource\plugins\filemonitorplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\MessageMonitorPlugin.dll"-"c:\sys\bin\MessageMonitorPlugin.dll"
+"\epoc32\data\z\resource\plugins\MessageMonitorPlugin.rsc"-"c:\resource\plugins\MessageMonitorPlugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\mmcmonitorplugin.dll"-"c:\sys\bin\mmcmonitorplugin.dll"
+"\epoc32\data\z\resource\plugins\mmcmonitorplugin.rsc"-"c:\resource\plugins\mmcmonitorplugin.rsc"
+"\epoc32\RELEASE\armv5\UREL\mdsoomplugin.dll"-"c:\sys\bin\mdsoomplugin.dll"
+"\epoc32\data\z\resource\plugins\mdsoomplugin.rsc"-"c:\resource\plugins\mdsoomplugin.rsc"
+
+; location manager
+"\EPOC32\RELEASE\ARMV5\UREL\LocationTrail.dll" -"c:\sys\bin\LocationTrail.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\locationmanager.dll" -"c:\sys\bin\locationmanager.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\locationmanagerserver.exe" -"c:\sys\bin\locationmanagerserver.exe"
+
+; metadata engine
+"\EPOC32\RELEASE\ARMV5\UREL\mdeclient.dll" -"c:\sys\bin\mdeclient.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\mdccommon.dll" -"c:\sys\bin\mdccommon.dll"
+"\EPOC32\RELEASE\ARMV5\UREL\mdsserver.exe" -"c:\sys\bin\mdsserver.exe"
+
+"\epoc32\release\armv5\udeb\mdswatchdog.exe"-"c:\sys\bin\mdswatchdog.exe"
+
+"\epoc32\data\z\Private\200009F3\schema.mde"-"c:\PRIVATE\200009F3\schema.mde"
+"\epoc32\data\z\Private\200009F3\defaultimportfile.mde"-"c:\PRIVATE\200009F3\defaultimportfile.mde"
+"\epoc32\data\z\Private\200009F3\backup_registration.xml"-"c:\PRIVATE\200009F3\backup_registration.xml"
+"\epoc32\data\z\Private\200009F5\backup_registration.xml"-"c:\PRIVATE\200009F5\backup_registration.xml"
+"\epoc32\data\z\Private\200009F5\mappings.db"-"c:\PRIVATE\200009F5\mappings.db"
+
+"\epoc32\release\armv5\udeb\mdsiadrestart.exe"-"c:\sys\bin\mdsiadrestart.exe",FILERUN,RB,RW
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sis/mds/package_separate.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,46 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;packet-header (name, uid, major, minor, build, type)
+#{"Metadata System Upgrade"},(0x200009F5), 9, 20, 0, TYPE=SA, RU
+
+; Localised vendor name
+%{"Nokia"}
+
+; Unique vendor name
+:"Nokia"
+
+;Files
+"\epoc32\release\armv5\udeb\mdsiadstop.exe"-"c:\sys\bin\mdsiadstop.exe",FILERUN,RB,RW
+
+;@"../../iadstoprestart/iadrestart.sisx", (0x2001FD52)
+
+@"../mdscenrep/mds_cenrep.sisx", (0x10202BE9)
+
+@"../../clfwrapper/sis/contentlistingframework.sisx", (0x101F8858)
+@"../../contextengine/sis/contextengine.sisx", (0x200009F6)
+@"../../harvester/sis/blacklistserver/blacklistserver.sisx", (0x2001B2EB)
+@"../../harvester/sis/composerplugins/composerplugins.sisx", (0x2000717E)
+@"../../harvester/sis/harvester/harvester.sisx", (0x200009F4)
+@"../../harvester/sis/harvesterplugins/harvesterplugins.sisx", (0x2001116A)
+@"../../harvester/sis/monitorplugins/monitorplugins.sisx", (0x20007182)
+@"../../locationmanager/sis/locationmanager.sisx", (0x200071BE)
+@"../../metadataengine/sis/metadataengine.sisx", (0x200009F1)
+
+;"\epoc32\release\armv5\udeb\mdsiadrestart.exe"-"c:\sys\bin\mdsiadrestart.exe",FILERUN,RB,RW
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sis/mds/stub.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,29 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+; Languages
+&EN
+
+; Header
+#{"Metadata System"}, (0x200009F5), 9, 20, 0, TYPE=SA
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+;Files
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sis/mdscenrep/depends.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ad:metadata xmlns="http://nokia.com/arrow/repository/ia_component"
+  xmlns:ad="http://nokia.com/arrow/application_metadata">
+  <appResources>
+     <appResource>
+        <language>1</language>
+        <iacName>MdS CenRep</iacName>
+        <iacDescription>Upgrade package for MdS Central Repository</iacDescription>
+     </appResource>
+  </appResources>
+  <swPlatformDep>
+     <platform>S60</platform>
+     <versionFrom>
+        <major>5</major>
+        <minor>0</minor>
+        <date>
+           <year>2009</year>
+           <week>16</week>
+        </date>
+     </versionFrom>
+  </swPlatformDep>
+  <interDeps>
+  </interDeps>
+</ad:metadata>
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sis/mdscenrep/package.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,31 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+; Languages
+&EN
+
+; Header
+#{"MDS CenRep"},(0x10202BE9), 2, 0, 0, TYPE=SA, RU
+
+; Localised Vendor name
+%{"Symbian Software Ltd."}
+
+; Unique Vendor name
+:"Symbian Software Ltd."
+
+;Files
+"..\..\clfwrapper\conf\102828AC.txt"-"c:\private\10202be9\102828AC.txt"
+"..\..\harvester\common\data\200009FE.txt"-"c:\private\10202be9\200009FE.txt"
+"..\..\locationmanager\conf\200071BE.txt"-"c:\private\10202be9\200071BE.txt"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sysdef_1_4_0.dtd	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,86 @@
+ <!ELEMENT SystemDefinition (systemModel?, build?)>
+ <!ATTLIST SystemDefinition
+  name CDATA #REQUIRED
+  schema CDATA #REQUIRED>
+ <!ELEMENT systemModel (layer+)>
+ <!ELEMENT layer (logicalset* | module*)*>
+ <!ATTLIST layer
+  name CDATA #REQUIRED
+  levels CDATA #IMPLIED
+  span CDATA #IMPLIED>
+ <!ELEMENT logicalset (logicalsubset* | module* | unit* | package* | prebuilt*)*>
+ <!ATTLIST logicalset name CDATA #REQUIRED>
+ <!ELEMENT logicalsubset (module* | unit* | package* | prebuilt*)*>
+ <!ATTLIST logicalsubset name CDATA #REQUIRED>
+ <!ELEMENT module (component* | unit* | package* | prebuilt*)*>
+ <!ATTLIST module
+  name CDATA #REQUIRED
+  level CDATA #IMPLIED>
+ <!ELEMENT component (unit* | package* | prebuilt*)*>
+ <!ATTLIST component name CDATA #REQUIRED>
+ <!ELEMENT unit EMPTY>
+ <!ATTLIST unit
+  unitID ID #REQUIRED
+  name CDATA #REQUIRED
+  mrp CDATA #REQUIRED
+  filter CDATA #IMPLIED
+  bldFile CDATA #REQUIRED
+  priority CDATA #IMPLIED
+  contract CDATA #IMPLIED>
+ <!ELEMENT package EMPTY>
+ <!ATTLIST package
+  name CDATA #REQUIRED
+  mrp CDATA #REQUIRED
+  filter CDATA #IMPLIED
+  contract CDATA #IMPLIED>
+ <!ELEMENT prebuilt EMPTY>
+ <!ATTLIST prebuilt
+  name CDATA #REQUIRED
+  version CDATA #REQUIRED
+  late (Y|N) #IMPLIED
+  filter CDATA #IMPLIED
+  contract CDATA #IMPLIED>
+ <!ELEMENT build (option* | target+ | targetList+ | unitList+ | configuration+)*>
+ <!ELEMENT unitList (unitRef+)>
+ <!ATTLIST unitList
+  name ID #REQUIRED
+  description CDATA #REQUIRED>
+ <!ELEMENT unitRef EMPTY>
+ <!ATTLIST unitRef unit IDREF #REQUIRED>
+ <!ELEMENT targetList EMPTY>
+ <!ATTLIST targetList
+  name ID #REQUIRED
+  description CDATA #REQUIRED
+  target IDREFS #REQUIRED>
+ <!ELEMENT target EMPTY>
+ <!ATTLIST target
+  name ID #REQUIRED
+  abldTarget CDATA #REQUIRED
+  description CDATA #REQUIRED>
+ <!ELEMENT option EMPTY>
+ <!ATTLIST option
+  name ID #REQUIRED
+  abldOption CDATA #REQUIRED
+  description CDATA #REQUIRED
+  enable (Y | N | y | n) #REQUIRED>
+ <!ELEMENT configuration (unitListRef+ | layerRef+ | task+)*>
+ <!ATTLIST configuration
+  name ID #REQUIRED
+  description CDATA #REQUIRED
+  filter CDATA #REQUIRED>
+ <!ELEMENT task ( unitListRef* , (buildLayer | specialInstructions))>
+ <!ELEMENT unitListRef EMPTY>
+ <!ATTLIST unitListRef unitList IDREF #REQUIRED>
+ <!ELEMENT layerRef EMPTY>
+ <!ATTLIST layerRef layerName CDATA #REQUIRED>
+ <!ELEMENT buildLayer EMPTY>
+ <!ATTLIST buildLayer
+  command CDATA #REQUIRED
+  targetList IDREFS #IMPLIED
+  unitParallel (Y | N | y | n) #REQUIRED
+  targetParallel (Y | N | y | n) #IMPLIED>
+ <!ELEMENT specialInstructions EMPTY>
+ <!ATTLIST specialInstructions
+  name CDATA #REQUIRED
+  cwd CDATA #REQUIRED
+  command CDATA #REQUIRED>  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/watchdog/group/bld.inf	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+../sis/mdswatchdog_stub.sis  /epoc32/data/z/system/install/mdswatchdog_stub.sis
+
+PRJ_MMPFILES
+watchdog.mmp
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/watchdog/group/watchdog.mmp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+VERSION					10.0
+TARGET                  mdswatchdog.exe
+TARGETTYPE              EXE
+UID                     0x0 0x20022E93
+
+CAPABILITY              CAP_APPLICATION PowerMgmt
+VENDORID                VID_DEFAULT
+
+SOURCEPATH              ../src
+SOURCE                  watchdog.cpp wdshutdownobserver.cpp wdselfshutdownobserver.cpp
+
+// Default system include paths for middleware layer modules.
+MW_LAYER_SYSTEMINCLUDE
+
+USERINCLUDE             ../inc
+USERINCLUDE             ../../inc
+USERINCLUDE             ../../harvester/common/inc
+
+LIBRARY                 euser.lib
+
+EPOCPROCESSPRIORITY background
+
+PAGED
+BYTEPAIRCOMPRESSTARGET
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/watchdog/inc/watchdog.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,75 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Monitoring application for servers restarting & IAD
+*
+*/
+
+#ifndef MDSWATCHDOG_H
+#define MDSWATCHDOG_H
+
+#include <e32base.h>
+
+#include "wdshutdownobserver.h"
+#include "wdselfshutdownobserver.h"
+
+class CWatchdog : public CActive, public MWDShutdownObserver, public MWDSelfShutdownObserver
+    {
+    public:
+    
+        enum TWatchdogState
+            {
+            EIdle,
+            EWaitingRendezvous,
+            ERunning,
+            EShuttingDown,
+            ERestarting
+        };
+
+        static CWatchdog* NewL();
+	    virtual ~CWatchdog();
+
+        // from base class CActive
+	    void RunL();
+        TInt RunError( TInt aError );
+	    void DoCancel();
+
+	    // From MShutdownObserver
+        void ShutdownNotification();
+        void RestartNotification();
+        
+        // From MWDSelfShutdownObserver
+        void SelfShutdownNotification();
+
+    private:
+
+        CWatchdog();
+        
+        void ConstructL();
+        
+        void Start();
+
+    private: // data
+
+        TWatchdogState iState;
+
+        CWDShutdownObserver* iShutdownObserver;        
+        
+        CWDSelfShutdownObserver* iSelfShutdownObserver;
+        
+        RProcess iProcess;
+  
+    };
+
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/watchdog/inc/wdselfshutdownobserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,105 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Shutdown observer
+*
+*/
+
+#ifndef WDSELFSHUTDOWNOBSERVER_H
+#define WDSELFHUTDOWNOBSERVER_H
+
+#include <e32base.h>
+#include <w32std.h>
+#include <e32property.h> 
+
+
+/**
+ * Observer interface for signaling the need for shutdown
+ */
+class MWDSelfShutdownObserver
+    {
+public:
+
+    virtual void SelfShutdownNotification() = 0;
+        
+    };
+
+/**
+ *  Active object for observing P&S keys
+ *
+ *  @since S60 v5.0
+ */
+class CWDSelfShutdownObserver  : public CActive
+    {
+public:
+
+    /**
+     * Two-phased constructor.
+     *
+     * @since S60 v5.0
+     * @return Instance of CTMShutdownObserver.
+     */
+    IMPORT_C static CWDSelfShutdownObserver* NewL( MWDSelfShutdownObserver& aObserver/*, const TUid& aKeyCategory*/ );
+
+    /**
+     * Destructor
+     *
+     * @since S60 v5.0
+     */
+    virtual ~CWDSelfShutdownObserver();
+    
+protected:
+
+    /**
+     * Handles an active object's request completion event.
+     *
+     * @since S60 v5.0
+     */
+    void RunL();
+
+    /**
+     * Implements cancellation of an outstanding request.
+     *
+     * @since S60 v5.0
+     */
+    void DoCancel();
+    
+    TInt RunError( TInt aError );
+
+private:
+
+    /**
+     * C++ default constructor
+     *
+     * @since S60 v5.0
+     * @return Instance of CShutdownObserver.
+     */
+    CWDSelfShutdownObserver( MWDSelfShutdownObserver& aObserver/*, const TUid& aKeyCategory*/ );
+
+    /**
+     * Symbian 2nd phase constructor can leave.
+     *
+     * @since S60 v5.0
+     */
+    void ConstructL();
+
+private:
+    
+    // not own
+    MWDSelfShutdownObserver& iObserver;
+    
+    /*const TUid& iKeyCategory;*/
+    RProperty iProperty;
+};
+
+#endif // SHUTDOWNOBSERVER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/watchdog/inc/wdshutdownobserver.h	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,107 @@
+
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Shutdown observer
+*
+*/
+
+#ifndef WDSHUTDOWNOBSERVER_H
+#define WDSHUTDOWNOBSERVER_H
+
+#include <e32base.h>
+#include <w32std.h>
+#include <e32property.h> 
+
+
+/**
+ * Observer interface for signaling the need for shutdown
+ */
+class MWDShutdownObserver
+    {
+public:
+
+    virtual void ShutdownNotification() = 0;
+    
+    virtual void RestartNotification() = 0;
+    };
+
+/**
+ *  Active object for observing P&S keys
+ *
+ *  @since S60 v5.0
+ */
+class CWDShutdownObserver  : public CActive
+    {
+public:
+
+    /**
+     * Two-phased constructor.
+     *
+     * @since S60 v5.0
+     * @return Instance of CTMShutdownObserver.
+     */
+    IMPORT_C static CWDShutdownObserver* NewL( MWDShutdownObserver& aObserver/*, const TUid& aKeyCategory*/ );
+
+    /**
+     * Destructor
+     *
+     * @since S60 v5.0
+     */
+    virtual ~CWDShutdownObserver();
+    
+protected:
+
+    /**
+     * Handles an active object's request completion event.
+     *
+     * @since S60 v5.0
+     */
+    void RunL();
+
+    /**
+     * Implements cancellation of an outstanding request.
+     *
+     * @since S60 v5.0
+     */
+    void DoCancel();
+    
+    TInt RunError( TInt aError );
+
+private:
+
+    /**
+     * C++ default constructor
+     *
+     * @since S60 v5.0
+     * @return Instance of CShutdownObserver.
+     */
+    CWDShutdownObserver( MWDShutdownObserver& aObserver/*, const TUid& aKeyCategory*/ );
+
+    /**
+     * Symbian 2nd phase constructor can leave.
+     *
+     * @since S60 v5.0
+     */
+    void ConstructL();
+
+private:
+    
+    // not own
+    MWDShutdownObserver& iObserver;
+    
+    /*const TUid& iKeyCategory;*/
+    RProperty iProperty;
+};
+
+#endif // SHUTDOWNOBSERVER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/watchdog/sis/depends.xml	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ad:metadata xmlns="http://nokia.com/arrow/repository/ia_component"
+  xmlns:ad="http://nokia.com/arrow/application_metadata">
+  <appResources>
+     <appResource>
+        <language>1</language>
+        <iacName>MdS Watchdog</iacName>
+        <iacDescription>Upgrade package for MdS Watchdog</iacDescription>
+     </appResource>
+  </appResources>
+  <swPlatformDep>
+     <platform>S60</platform>
+     <versionFrom>
+        <major>5</major>
+        <minor>0</minor>
+        <date>
+           <year>2009</year>
+           <week>16</week>
+        </date>
+     </versionFrom>
+  </swPlatformDep>
+  <interDeps>
+  </interDeps>
+</ad:metadata>
\ No newline at end of file
Binary file watchdog/sis/mdswatchdog_stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/watchdog/sis/stub.pkg	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,30 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;Languages
+&EN
+
+;Header
+# {"MdS Watchdog"}, (0x20022E93), 1, 0, 0, TYPE=SA
+
+;Localised Vendor name
+%{"Nokia"}
+
+;Unique Vendor name
+:"Nokia"
+
+;Files
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/watchdog/src/watchdog.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,283 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: Monitoring application for servers restarting & IAD
+*
+*/
+
+#include "mdscommoninternal.h"
+#include "watchdog.h"
+
+_LIT( KHarvesterServerProcess, "HarvesterServer*" );
+_LIT( KHarvesterServerExe, "harvesterserver.exe" );
+
+// Print macro
+#ifdef _DEBUG
+#include <e32svr.h>
+#define PRINT(x) RDebug::Print x
+#else
+#define PRINT(x)
+#endif
+
+
+// ======== MEMBER FUNCTIONS ========
+// ---------------------------------------------------------------------------
+// Constructor.
+// ---------------------------------------------------------------------------
+//
+CWatchdog* CWatchdog::NewL()
+    {
+    PRINT(_L("CWatchdog::NewL()"));
+    CWatchdog* self = new ( ELeave ) CWatchdog();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// C++ constructor.
+// ---------------------------------------------------------------------------
+//
+CWatchdog::CWatchdog() : 
+    CActive( CActive::EPriorityLow ), iState(EIdle)
+    {
+    // Add to active scheduler.
+    CActiveScheduler::Add( this );
+    }
+
+// ---------------------------------------------------------------------------
+// 2nd phase constructor.
+// ---------------------------------------------------------------------------
+//
+void CWatchdog::ConstructL()
+    {
+    PRINT(_L("CWatchdog::ConstructL()"));
+        
+    TFullName name;
+        
+    // find Harvester Server
+    TFindProcess findProcess( KHarvesterServerProcess );
+    if ( findProcess.Next(name) == KErrNone )
+        {                
+        PRINT(_L("CWatchdog::ConstructL() - found server, start listening"));
+        
+        User::LeaveIfError( iProcess.Open(name) );
+        iState = ERunning;
+        // logon to get termination signal
+        iProcess.Logon(iStatus);        
+        SetActive();
+        }        
+    else
+        {               
+        PRINT(_L("CWatchdog::ConstructL() - start Harvester server"));
+        // start new Harvester            
+        Start();
+        }
+    
+    PRINT(_L("CWatchdog::ConstructL() - create observer"));
+    iShutdownObserver = CWDShutdownObserver::NewL( *this );        
+    iSelfShutdownObserver = CWDSelfShutdownObserver::NewL( *this ); 
+    
+    RProcess process;
+    process.SetPriority( EPriorityBackground );
+    process.Close();
+    }
+
+void CWatchdog::Start()
+    {
+    
+    PRINT(_L("CWatchdog::Start()"));
+
+    // Create the server process
+    TInt res( KErrNone );
+    
+    // KNullDesC param causes server's E32Main() to be run
+    res = iProcess.Create( KHarvesterServerExe, KNullDesC );
+    if ( res != KErrNone )
+        {
+        PRINT(_L("CWatchdog::ConstructL() - error in server creation"));
+        return;
+        }
+    
+    // start process and wait until it is constructed                
+    iProcess.Rendezvous(iStatus);                                         
+    
+    if( iStatus != KRequestPending )
+        {
+        iProcess.Kill( 0 );   // abort startup
+        }
+    else
+        {
+        iProcess.Resume();    // logon OK - start the server   
+        iState = EWaitingRendezvous;
+        SetActive();
+        }
+    
+    PRINT(_L("CWatchdog::ConstructL() - Start end"));
+    }    
+    
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CWatchdog::~CWatchdog()
+    {
+    delete iShutdownObserver;    
+    delete iSelfShutdownObserver;
+    Cancel();
+    }
+
+// ---------------------------------------------------------------------------
+// Active object's request handling.
+// ---------------------------------------------------------------------------
+//
+void CWatchdog::RunL()
+    {
+    PRINT(_L("CWatchdog::RunL"));
+    	
+    	switch (iState)
+    	{
+          case EIdle:
+              {
+              PRINT(_L("CWatchdog::RunL() - EIdle"));
+              break;
+              }
+              
+          case EWaitingRendezvous:          
+              {
+              PRINT(_L("CWatchdog::RunL() - EWaitingRendezvous"));
+              iState = ERunning;              
+              // logon to get termination signal
+              iProcess.Logon(iStatus);        
+              SetActive();
+              break;
+              }             
+              
+          case ERunning:
+              {
+              PRINT(_L("CWatchdog::RunL() - server died"));
+              // server died unexpectedly, start it    
+              Start();
+              break;
+              }
+              
+          case EShuttingDown:
+              {
+              PRINT(_L("CWatchdog::RunL() - IAD shutdown"));
+              // Do nothing              
+              break;
+              }
+              
+          case ERestarting:
+              {
+              PRINT(_L("CWatchdog::RunL() - IAD restart"));
+              Start();
+              break;
+              }
+            
+          default:
+              break;
+              
+          
+    	}
+    
+    }
+
+// ---------------------------------------------------------------------------
+// Active object's request error handling.
+// ---------------------------------------------------------------------------
+//
+TInt CWatchdog::RunError( TInt /*aError*/ )
+    {
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// Cancel the request.
+// ---------------------------------------------------------------------------
+//
+void CWatchdog::DoCancel()
+    {
+    PRINT(_L("CWatchdog::DoCancel()"));
+    iProcess.LogonCancel(iStatus);
+    iProcess.Close();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWatchdog::ShutdownNotification
+// -----------------------------------------------------------------------------
+//
+void CWatchdog::ShutdownNotification()
+    {
+
+    iState = EShuttingDown;
+    
+    PRINT((_L("CWatchdog::ShutdownNotification() IsActive() = %d"), IsActive() ));
+    
+    
+    }
+
+// -----------------------------------------------------------------------------
+// CWatchdog::ShutdownNotification
+// -----------------------------------------------------------------------------
+//
+void CWatchdog::RestartNotification()
+    {
+    PRINT(_L("CWatchdog::RestartNotification()"));
+    
+    if (!IsActive())
+        SetActive();
+    
+    iState = ERestarting;    
+    TRequestStatus *status = &iStatus;
+    User::RequestComplete(status, KErrNone);
+        
+    }
+
+void CWatchdog::SelfShutdownNotification()
+    {
+    PRINT(_L("CWatchdog::SelfShutdownNotification()"));
+    CActiveScheduler::Stop();
+    
+    }
+
+void MainL()
+    {
+    CActiveScheduler* scheduler = new (ELeave) CActiveScheduler();
+    CActiveScheduler::Install( scheduler );
+    CleanupStack::PushL( scheduler );
+    
+    CWatchdog* w = CWatchdog::NewL();
+    CleanupStack::PushL( w );
+    CActiveScheduler::Start();
+    
+    CleanupStack::PopAndDestroy( 2, scheduler );
+    }
+
+TInt E32Main()
+    {
+    TInt err = KErrNoMemory;
+   
+    CTrapCleanup* cleanupStack = CTrapCleanup::New();
+    if ( cleanupStack )
+        {
+        TRAP( err, MainL() );
+        }
+  
+    delete cleanupStack;
+    return err;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/watchdog/src/wdselfshutdownobserver.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,128 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: Shutdown Observer
+*
+*/
+#include <e32base.h>
+
+#include "wdselfshutdownobserver.h"
+#include "mdscommoninternal.h"
+
+// Print macro
+#ifdef _DEBUG
+#include <e32svr.h>
+#define PRINT(x) RDebug::Print x
+#else
+#define PRINT(x)
+#endif
+
+// ---------------------------------------------------------------------------
+// CWDSelfShutdownObserver::NewL()
+// ---------------------------------------------------------------------------
+//
+CWDSelfShutdownObserver* CWDSelfShutdownObserver::NewL( MWDSelfShutdownObserver& aObserver/*, const TUid& aKeyCategory */)
+    { 
+    CWDSelfShutdownObserver* self = new( ELeave )CWDSelfShutdownObserver( aObserver/*, aKeyCategory */);
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CWDSelfShutdownObserver::CWDSelfShutdownObserver()
+// ---------------------------------------------------------------------------
+//
+CWDSelfShutdownObserver::CWDSelfShutdownObserver( MWDSelfShutdownObserver& aObserver/*, const TUid& aKeyCategory */)
+    : CActive( CActive::EPriorityStandard ), iObserver( aObserver )/*, iKeyCategory( aKeyCategory )*/
+    {       
+    }
+
+// ---------------------------------------------------------------------------
+// CWDSelfShutdownObserver::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CWDSelfShutdownObserver::ConstructL()
+    {
+    PRINT(_L("CWDSelfShutdownObserver::ConstructL()"));
+    
+    TInt error = RProperty::Define(KWatchdogPSShutdown, KShutdown,RProperty::EInt,KAllowAllPolicy,KPowerMgmtPolicy);
+    RProperty::Set(KWatchdogPSShutdown,KShutdown,0);
+
+    // attach to the property    
+    User::LeaveIfError( iProperty.Attach(KWatchdogPSShutdown,KShutdown,EOwnerThread) );
+    
+    CActiveScheduler::Add( this );
+    
+    // wait for the previously attached property to be updated
+    iProperty.Subscribe(iStatus);        
+    
+    SetActive();
+    
+    PRINT(_L("CWDSelfShutdownObserver::ConstructL() end"));
+    }
+
+// ---------------------------------------------------------------------------
+// CWDSelfShutdownObserver::~CWDSelfShutdownObserver()
+// ---------------------------------------------------------------------------
+//
+CWDSelfShutdownObserver::~CWDSelfShutdownObserver()
+    {
+    PRINT(_L("CWDSelfShutdownObserver::~CWDSelfShutdownObserver()"));
+    Cancel();
+    iProperty.Close();
+    PRINT(_L("CWDSelfShutdownObserver::~CWDSelfShutdownObserver() end"));
+    }
+
+// ---------------------------------------------------------------------------
+// CWDSelfShutdownObserver::RunL()
+// ---------------------------------------------------------------------------
+//
+void CWDSelfShutdownObserver::RunL()
+    {
+    
+    PRINT(_L("CWDSelfShutdownObserver::RunL()"));
+    
+    // resubscribe before processing new value to prevent missing updates
+    iProperty.Subscribe(iStatus);
+    SetActive();
+    
+    // retrieve the Uid of the package going to be updated
+    TInt value = 0;
+    const TInt err = iProperty.Get(value);
+    User::LeaveIfError(err);
+
+    // observer callback
+    if (value)
+        {
+        iObserver.SelfShutdownNotification();
+        }
+    
+    }
+
+TInt CWDSelfShutdownObserver::RunError( TInt /*aError*/ )
+    {
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// CWDSelfShutdownObserver::DoCancel()
+// ---------------------------------------------------------------------------
+//
+void CWDSelfShutdownObserver::DoCancel()
+    {
+    iProperty.Cancel();
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/watchdog/src/wdshutdownobserver.cpp	Mon Jan 18 20:34:07 2010 +0200
@@ -0,0 +1,129 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: Shutdown Observer
+*
+*/
+
+#include <e32base.h>
+
+#include "wdshutdownobserver.h"
+#include "mdscommoninternal.h"
+
+// Print macro
+#ifdef _DEBUG
+#include <e32svr.h>
+#define PRINT(x) RDebug::Print x
+#else
+#define PRINT(x)
+#endif
+
+// ---------------------------------------------------------------------------
+// CWDShutdownObserver::NewL()
+// ---------------------------------------------------------------------------
+//
+CWDShutdownObserver* CWDShutdownObserver::NewL( MWDShutdownObserver& aObserver/*, const TUid& aKeyCategory */)
+    { 
+    CWDShutdownObserver* self = new( ELeave )CWDShutdownObserver( aObserver/*, aKeyCategory */);
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CWDShutdownObserver::CWDShutdownObserver()
+// ---------------------------------------------------------------------------
+//
+CWDShutdownObserver::CWDShutdownObserver( MWDShutdownObserver& aObserver/*, const TUid& aKeyCategory */)
+    : CActive( CActive::EPriorityStandard ), iObserver( aObserver )/*, iKeyCategory( aKeyCategory )*/
+    {       
+    }
+
+// ---------------------------------------------------------------------------
+// CWDShutdownObserver::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CWDShutdownObserver::ConstructL()
+    {
+    PRINT(_L("CWDShutdownObserver::ConstructL()"));
+    
+    // attach to the property    
+    User::LeaveIfError( iProperty.Attach(KHarvesterPSShutdown,KShutdown,EOwnerThread) );
+    
+    CActiveScheduler::Add( this );
+    
+    // wait for the previously attached property to be updated
+    iProperty.Subscribe(iStatus);        
+    
+    SetActive();
+    
+    PRINT(_L("CWDShutdownObserver::ConstructL() end"));
+    }
+
+// ---------------------------------------------------------------------------
+// CWDShutdownObserver::~CWDShutdownObserver()
+// ---------------------------------------------------------------------------
+//
+CWDShutdownObserver::~CWDShutdownObserver()
+    {
+    PRINT(_L("CWDShutdownObserver::~CWDShutdownObserver()"));
+    Cancel();
+    iProperty.Close();
+    PRINT(_L("CWDShutdownObserver::~CWDShutdownObserver() end"));
+    }
+
+// ---------------------------------------------------------------------------
+// CWDShutdownObserver::RunL()
+// ---------------------------------------------------------------------------
+//
+void CWDShutdownObserver::RunL()
+    {
+    
+    PRINT(_L("CWDShutdownObserver::RunL()"));
+    
+    // resubscribe before processing new value to prevent missing updates
+    iProperty.Subscribe(iStatus);
+    SetActive();
+    
+    // retrieve the Uid of the package going to be updated
+    TInt value = 0;
+    const TInt err = iProperty.Get(value);
+    User::LeaveIfError(err);
+
+    // observer callback
+    if (value)
+        {
+        iObserver.ShutdownNotification();
+        }
+    else
+        {
+        iObserver.RestartNotification();
+        }
+    }
+
+TInt CWDShutdownObserver::RunError( TInt /*aError*/ )
+    {
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// CWDShutdownObserver::DoCancel()
+// ---------------------------------------------------------------------------
+//
+void CWDShutdownObserver::DoCancel()
+    {
+    iProperty.Cancel();
+    }
+
+// End of file