From C++ to C#

I have gone back in time this week to work on a legacy ISAPI
application.  The ISAPI application is being developed in C++ and
makes use of MSXML to read an XML configuration file.  Below is
some code in C++ to open the XML file and read two text values,
contained in element nodes:

BOOL GetConfigDetails(string &userName, string &domain)
{
BOOL result = FALSE;
if (0 != configFilename && _tcslen(configFilename) > 0)
{
try
{
// Create a DOM Document.
// CComPtr smart pointer will release our COM handle.
CComPtr pItfcDoc = 0;
HRESULT hr = pItfcDoc.CoCreateInstance(__uuidof(MSXML2::DOMDocument60));
if (SUCCEEDED(hr))
{
// Load the config file.
if (VARIANT_TRUE == pItfcDoc->load(configFilename))
{
// Look for the username and domain nodes.
CComPtr pItfcNode = 0;
pItfcNode = pItfcDoc->selectSingleNode(_bstr_t(“/ISAPIStub/username”));
userName = 0 != pItfcNode ? pItfcNode->Gettext() : _bstr_t(“”);
pItfcNode = pItfcDoc->selectSingleNode(_bstr_t(“/ISAPIStub/domain”));
domain = 0 != pItfcNode ? pItfcNode->Gettext() : _bstr_t(“”);
result = TRUE;
}
}
}
catch (_com_error)
{
result = FALSE;
}
}
return result;
}

Now, here is the code in C#:

public bool GetConfigDetails(out string userName, out string domain)
{
bool result = false;
userName = domain = String.Empty;
if (!String.IsNullOrEmpty(configFilename))
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(configFilename);
XmlNode node = doc.SelectSingleNode(“/ISAPIStub/username”);
userName = (null != node) ? node.InnerText : String.Empty;
node = doc.SelectSingleNode(“/ISAPIStub/domain”);
domain = (null != node) ? node.InnerText : String.Empty;
}
catch
{
result = false;
}
}
return result;
}

Much easier huh?  See how far we’ve come as developers. 
Whilst writing my ISAPI application I had to remember to go back and
clean up my memory allocations because there is no friendly garbage
collector doing it for me – doh.

3 thoughts on “From C++ to C#

  1. Nathan

    Definitely a bit easier to read. Although I would submit that the API is more of an issue than the language itself… Dealing with COM is never what I would call pleasant. (The code would look remarkably the same in managed C++…)

  2. Rob Garrett

    Hmmm, I would agree with your comment about the API, but have to disagree about interfacing with COM from .NET. The framework makes COM interop a breeze. Just add a reference to the COM object from inside Visual Studio and all the plumbing and marshalling code is handled by the framework. The developer is presented with a nicely typed class representing the CoClass in the COM component.

Comments are closed.