Just a tiny gem, which not often would be required but it can save you some time. It also demonstrates the power of the IXmlReader in unmanaged code. Because, as far I am aware of, the processing time a .config file measuring it with TickCount always is 0 ms (too small to measure). Microsoft has optimized the XML Reader implementation for fast forward reading, and it also does not allocate strings in memory, it just passes the pointer to the unicode strings (either key or value). In line with that, you might appreciate :) why I attach to the BSTR key to find as well.

What this class does, it reads the <appSettings>  section and puts the key value pairs in a ‘named value collection’ item.

Note 1: I am a big fan of CComBSTR when the final client still understands COM/automation. That is the reason I did not use CString in this class. In addition, the CComBSTR class has been boosted by me, to optimize reallocation of existing memory. But you can use the default MS implementation as well. So, you can change CSimpleMap to CSimpleMap<CString, CString> if you wish.

Note 2: The .config file is cached but it is parsed again if the filewritetime of the .config file was changed.

config.h header.

#include <xmllite.h>
#include <map>
#pragma once


using namespace ATL;

class ConfigurationManager
{
private:
    static const int DELAYTICKS = 1000;
    std::map<CComBSTR, CComBSTR> _map;
    time_t _ftLastCheck;
    CComPtr<IXmlReader> _xmlReader;
    CComPtr<IMalloc> _malloc;
    HRESULT CheckTimeOut();
    //ansi version!
    CComBSTR _szFilePath;
   
    void Init();

public:
    ConfigurationManager();
    ConfigurationManager(const BSTR configFile);
    std::wstring& AppSettings(const std::wstring key, PCWSTR defaultValue = NULL);
    BSTR AppSettings(const BSTR key, PCWSTR defaultValue = NULL);
    time_t GetFileTime();
    ~ConfigurationManager();
};

 

Implementation:


#include <ctime>
#include <sys/stat.h>
#include "config.h"
#pragma comment(lib, "xmllite.lib")


ConfigurationManager::ConfigurationManager(const BSTR configFile) throw()
{
    _szFilePath = configFile;
    time(&_ftLastCheck);
    Init();
}
ConfigurationManager::ConfigurationManager() throw()
{   
    time(&_ftLastCheck);
    _szFilePath.Attach(GetModulePath());   
    if (!_szFilePath.IsEmpty())
    {       
        _szFilePath.Append(L".config");
       
        Init();
    }   
}
void ConfigurationManager::Init() throw()
{
    if (!_szFilePath.IsEmpty())
    {
        HRESULT hr = CoGetMalloc(1, &_malloc);
        hr = CreateXmlReader(IID_IXmlReader, (void**)&_xmlReader, _malloc);
        if (FAILED(hr))
        {
   
        }
    }
}
time_t ConfigurationManager::GetFileTime() throw()
{   
    struct stat stResult;
    CComBSTR ansi(_szFilePath);
    ansi.Attach(ansi.ToByteString());
    ::stat((char*)ansi.m_str, &stResult);        // get the attributes of afile.txt
   
    return stResult.st_mtime;
}
BSTR ConfigurationManager::AppSettings(const BSTR key, PCWSTR defaultValue) throw()
{
   
    HRESULT hr = CheckTimeOut();
    if (FAILED(hr))
    {
      
        return NULL;
    }
    CComBSTR find;
    find.Attach(key);
   
    auto found = _map.find(find);
    find.Detach();
       if (found != _map.end())
    {
        return found->second.Copy();
    }
    else if (defaultValue != NULL)
    {
        return ::SysAllocString(defaultValue);
    }
    return NULL;
   
}
ConfigurationManager::~ConfigurationManager() throw()
{
    _map.clear();
    _xmlReader.Release();
    _malloc.Release();
    _szFilePath.Empty();
}
HRESULT ConfigurationManager::CheckTimeOut() throw()
{
   
    auto curT = GetFileTime();
   
    PCWSTR pwzValue;
    auto memResult = ::difftime(curT, _ftLastCheck);
    if (memResult != 0.0F)
    {
        DWORD start = ::GetTickCount();
   
        HRESULT hr = S_OK;
       
        CComPtr<IStream> pStream;
        CComPtr<IXmlReaderInput> _readerInput;
       
        hr = ::SHCreateStreamOnFileEx(_szFilePath, STGM_READ | STGM_SHARE_DENY_NONE, FILE_ATTRIBUTE_NORMAL, FALSE,NULL, &pStream);

        if (SUCCEEDED(hr))
        {
            hr = ::CreateXmlReaderInputWithEncodingCodePage(pStream, _malloc, CP_UTF8, TRUE, NULL, &_readerInput);           
            hr = _xmlReader->SetProperty(XmlReaderProperty_DtdProcessing, DtdProcessing_Prohibit);   
            hr = _xmlReader->SetInput(_readerInput);
        }   
        else
        {
            return hr;
        }
       
        XmlNodeType nodeType = XmlNodeType::XmlNodeType_None;
        UINT lenValue;
        PCWSTR key;
        bool startCollecting  = false;
        while (S_OK == _xmlReader->Read(&nodeType) && hr == S_OK)
        {
            switch(nodeType) {
            case XmlNodeType::XmlNodeType_EndElement:
               
                //hr = pReader->GetDepth(&dept);
                hr = _xmlReader->GetLocalName(&pwzValue, NULL);
                if (startCollecting && lstrcmpW(pwzValue, L"appSettings") == 0)
                {
                    //break loop
                    hr = S_FALSE;
                }
                break;
            case XmlNodeType::XmlNodeType_Element:
                {
                    // get element name such as option in <option value="11">
                    hr = _xmlReader->GetLocalName(&pwzValue, NULL);
           
                    if (FAILED(hr)) break;
                   
                    //iOrdinalCount++;
                    if (startCollecting == false && lstrcmpW(pwzValue, L"appSettings") == 0)
                    {
                        startCollecting = true;

                        hr = _xmlReader->MoveToAttributeByName(L"configSource", NULL);
                        if (hr == S_OK)
                        {
                            hr = _xmlReader->GetValue(&pwzValue, NULL);
                            
                                              
                            if (::PathIsRelativeW(pwzValue) == TRUE)
                            {
                                //TODO: call back to do a Server.MapPath
                                _szFilePath.Attach(FileStripFile(_szFilePath));                               
                                _szFilePath.Append(L'\\');
                                _szFilePath.Append(pwzValue);
                            }
                            else
                            {
                                _szFilePath = pwzValue;
                            }
                            _readerInput.Release();
                            pStream.Release();
                            return CheckTimeOut(); //recursion                           
                        }
                        hr = S_OK;//reset otherwise loop stops
                    }                   
                    else if (startCollecting && lstrcmpW(pwzValue, L"add") == 0)
                    {
                       
                        hr = _xmlReader->MoveToAttributeByName(L"key", NULL);
                        if (hr == S_OK)
                        {
                            hr = _xmlReader->GetValue(&pwzValue, &lenValue);
                            //key.Append( pwzValue, lenValue);
                            key = pwzValue;

                            //ATLTRACE(L"found key %s %d\r\n", pwzValue, lenValue);
                            hr = _xmlReader->MoveToAttributeByName(L"value", NULL);
                            if (hr == S_OK)
                            {
                                _xmlReader->GetValue(&pwzValue, NULL);
                                _map.insert(std::pair<CComBSTR, CComBSTR>(key, pwzValue));
                            }
                        }
                    }                   
                }
                break;
            }
        }
        if (SUCCEEDED(hr)) _ftLastCheck = curT;
        if (_xmlReader != NULL)
        {
            _xmlReader->SetInput(NULL);
        }
    
        return S_FALSE;
       
    }

    return S_OK;
   
};