Wednesday 29 February 2012

Explore networking configuration with INetCfg interface

Current configuration of network adapters in Windows OS can be explored from Network Connections (Start -> Control Panel -> Network and Sharing Center -> Change Adapter Settings). Selecting Properties from a right click context menu for chosen connection displays a dialog box which contains Networking tab. It contains the name of the network adapter used by this connection and, below it, a list of network features bound to the adapter. Those features are:

  • network clients (identified with a COM class with GUID GUID_DEVCLASS_NETCLIENT)
  • network services (GUID_DEVCLASS_NETSERVICE)
  • network protocols (transports) (GUID_DEVCLASS_NETTRANS)

(Adapters are identified with a COM class with GUID GUID_DEVCLASS_NET.)

You can install or uninstall, enable or disable these features manually from that dialog box.

In order to view or modify these networking configuration programmatically we can use a family of COM objects starting with a root one which implements INetCfg interface. When we acquire (pointer to) this object, we can query it for all other interfaces and call methods on them. Common name for these methods is INetCfg API. They are all implemented in Netcfgx.dll. This dll basically contains Network Configuration COM Objects and can be found in C:\Windows\System32.

Following code shows how to use INetCfg API in order to display all network adapters, clients, transports and services. For each client, transport and service we check which adapter it is bound to.



Output:




Enumerating GUID_DEVCLASS_NET class:

Network card (adapter) 1:
        Display name: VirtualBox Host-Only Ethernet Adapter
        Bind name: {0B904F29-FBC7-452E-B502-038521DC4212}
        Characteristics: 4
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: sun_vboxnetadp

Network card (adapter) 2:
        Display name: Microsoft ISATAP Adapter #4
        Bind name: {EAAB95CA-6285-4DE9-AF45-8643E8662958}
        Characteristics: 9
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text: Microsoft ISATAP Adapter Driver
        ID: *isatap

Network card (adapter) 3:
        Display name: Microsoft Windows Mobile Remote Adapter
        Bind name: {2C42503C-D28B-4A6F-9A3B-88C806CDDE3B}
        Characteristics: 132
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: usb\class_ef&subclass_01&prot_01

Network card (adapter) 4:
        Display name: Microsoft ISATAP Adapter #2
        Bind name: {05388434-DF29-4E65-99C1-557E0E276171}
        Characteristics: 9
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text: Microsoft ISATAP Adapter Driver
        ID: *isatap

Network card (adapter) 5:
        Display name: Microsoft ISATAP Adapter #3
        Bind name: {F41C92AB-9451-437B-B7E8-713CE75F76B4}
        Characteristics: 9
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text: Microsoft ISATAP Adapter Driver
        ID: *isatap

Network card (adapter) 6:
        Display name: WAN Miniport (IKEv2)
        Bind name: {96704964-C9AC-4D9E-B07E-CB777DBA8DD9}
        Characteristics: 41
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_agilevpnminiport

Network card (adapter) 7:
        Display name: Apollo NDIS Driver for Windows Vista/7
        Bind name: {65A8E0D2-5990-402A-8B9D-12527C3813C6}
        Characteristics: 129
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text: This protocol allows the apollo emulator to act as ;
        ID: brandapolloemulator

Network card (adapter) 8:
        Display name: Teredo Tunneling Pseudo-Interface
        Bind name: {D8CDC497-340C-4AF0-8B3F-12ECE377706D}
        Characteristics: 9
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text: Microsoft Teredo Tunneling Adapter
        ID: *teredo

Network card (adapter) 9:
        Display name: Microsoft ISATAP Adapter
        Bind name: {8A9C39F5-6704-4E11-91CE-122BFA7150E9}
        Characteristics: 9
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text: Microsoft ISATAP Adapter Driver
        ID: *isatap

Network card (adapter) 10:
        Display name: Intel(R) 82566DC Gigabit Network Connection
        Bind name: {B05DCEC3-9E0E-499C-8EA0-F86503FDA39B}
        Characteristics: 132
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: pci\ven_8086&dev_104b

Network card (adapter) 11:
        Display name: RAS Async Adapter
        Bind name: {E2F8A220-AF88-446C-9A55-453E58DD3A33}
        Characteristics: 42
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: sw\{eeab7790-c514-11d1-b42b-00805fc1270e}

Network card (adapter) 12:
        Display name: WAN Miniport (IP)
        Bind name: NdisWanIp
        Characteristics: 41
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_ndiswanip

Network card (adapter) 13:
        Display name: WAN Miniport (Network Monitor)
        Bind name: NdisWanBh
        Characteristics: 41
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_ndiswanbh

Network card (adapter) 14:
        Display name: WAN Miniport (IPv6)
        Bind name: NdisWanIpv6
        Characteristics: 41
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_ndiswanipv6

Network card (adapter) 15:
        Display name: WAN Miniport (PPPOE)
        Bind name: {DB2B4279-B5CF-4626-9DBA-32D0ECE44C87}
        Characteristics: 41
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_pppoeminiport

Network card (adapter) 16:
        Display name: WAN Miniport (PPTP)
        Bind name: {C0DE3E38-8BA7-479F-8B75-833F294C5AA8}
        Characteristics: 41
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_pptpminiport

Network card (adapter) 17:
        Display name: WAN Miniport (L2TP)
        Bind name: {483C9FF8-503D-414B-B402-E4C1F1F568CB}
        Characteristics: 41
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_l2tpminiport

Network card (adapter) 18:
        Display name: WAN Miniport (SSTP)
        Bind name: {E28D896F-9EA8-433A-9C10-66C97C19A921}
        Characteristics: 41
        Class GUID: 1295444338-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_sstpminiport



Enumerating GUID_DEVCLASS_NETCLIENT class:

Network client 1:
        Display name: Client for Microsoft Networks
        Bind name: LanmanWorkstation
        Characteristics: 128
        Class GUID: 1295444339-58149-4558-3210004
        Device Status: 0
        Help Text: Allows your computer to access resources on a Microsoft netwo
rk.
        ID: ms_msclient
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Microsoft ISATAP Adapter #4
           Bound to: Microsoft Windows Mobile Remote Adapter
           Bound to: Microsoft ISATAP Adapter #2
           Bound to: Microsoft ISATAP Adapter #3
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Teredo Tunneling Pseudo-Interface
           Bound to: Microsoft ISATAP Adapter
           Bound to: Intel(R) 82566DC Gigabit Network Connection



Enumerating GUID_DEVCLASS_NETTRANS class:

Network transport 1:
        Display name: AgileVpn based VPN
        Bind name: msagilevpn
        Characteristics: 56
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text: Allows you to securely connect to a private network using the
 Internet.
        ID: ms_agilevpn

Network transport 2:
        Display name: Microsoft TCP/IP version 6 - Tunnels
        Bind name: TCPIP6TUNNEL
        Characteristics: 40
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_tcpip6_tunnel
           Bound to: Microsoft ISATAP Adapter #2
           Bound to: Microsoft ISATAP Adapter #3
           Bound to: Teredo Tunneling Pseudo-Interface
           Bound to: Microsoft ISATAP Adapter

Network transport 3:
        Display name: Internet Protocol (TCP/IP) - Tunnels
        Bind name: TCPIPTUNNEL
        Characteristics: 40
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_tcpip_tunnel

Network transport 4:
        Display name: Microsoft NetbiosSmb
        Bind name: Smb
        Characteristics: 40
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_smb
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Microsoft ISATAP Adapter #4
           Bound to: Microsoft Windows Mobile Remote Adapter
           Bound to: Microsoft ISATAP Adapter #2
           Bound to: Microsoft ISATAP Adapter #3
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Teredo Tunneling Pseudo-Interface
           Bound to: Microsoft ISATAP Adapter
           Bound to: Intel(R) 82566DC Gigabit Network Connection

Network transport 5:
        Display name: Remote Access IP ARP Driver
        Bind name: Wanarp
        Characteristics: 40
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_wanarp
           Bound to: WAN Miniport (IP)

Network transport 6:
        Display name: Message-oriented TCP/IP Protocol (SMB session)
        Bind name: NetbiosSmb
        Characteristics: 56
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_netbt_smb

Network transport 7:
        Display name: WINS Client(TCP/IP) Protocol
        Bind name: NetBT
        Characteristics: 40
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_netbt
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Microsoft ISATAP Adapter #4
           Bound to: Microsoft Windows Mobile Remote Adapter
           Bound to: Microsoft ISATAP Adapter #2
           Bound to: Microsoft ISATAP Adapter #3
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Teredo Tunneling Pseudo-Interface
           Bound to: Microsoft ISATAP Adapter
           Bound to: Intel(R) 82566DC Gigabit Network Connection

Network transport 8:
        Display name: Internet Protocol Version 6 (TCP/IPv6)
        Bind name: Tcpip6
        Characteristics: 160
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text: TCP/IP version 6. The latest version of the internet protocol
 that provides communication across diverse interconnected networks.
        ID: ms_tcpip6
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Microsoft ISATAP Adapter #4
           Bound to: Microsoft ISATAP Adapter #2
           Bound to: Microsoft ISATAP Adapter #3
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Teredo Tunneling Pseudo-Interface
           Bound to: Microsoft ISATAP Adapter
           Bound to: Intel(R) 82566DC Gigabit Network Connection

Network transport 9:
        Display name: Internet Protocol Version 4 (TCP/IPv4)
        Bind name: Tcpip
        Characteristics: 160
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text: Transmission Control Protocol/Internet Protocol. The default
wide area network protocol that provides communication across diverse interconne
cted networks.
        ID: ms_tcpip
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Microsoft Windows Mobile Remote Adapter
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Intel(R) 82566DC Gigabit Network Connection

Network transport 10:
        Display name: Link-Layer Topology Discovery Mapper I/O Driver
        Bind name: lltdio
        Characteristics: 0
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text: Used to discover and locate other PCs, devices, and network i
nfrastructure components on the network.  Also used to determine network bandwid
th.
        ID: ms_lltdio
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Intel(R) 82566DC Gigabit Network Connection

Network transport 11:
        Display name: Link-Layer Topology Discovery Responder
        Bind name: rspndr
        Characteristics: 0
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text: Allows this PC to be discovered and located on the network.
        ID: ms_rspndr
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Intel(R) 82566DC Gigabit Network Connection

Network transport 12:
        Display name: Remote Access IPv6 ARP Driver
        Bind name: Wanarpv6
        Characteristics: 40
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_wanarpv6
           Bound to: WAN Miniport (IPv6)

Network transport 13:
        Display name: Point to Point Protocol Over Ethernet
        Bind name: RasPppoe
        Characteristics: 40
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text: Provides the abilitiy to connect a host to a Remote Access Co
ncentrator that supports RFC2516.
        ID: ms_pppoe
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Intel(R) 82566DC Gigabit Network Connection

Network transport 14:
        Display name: Point to Point Tunneling Protocol
        Bind name: mspptp
        Characteristics: 56
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text: Allows you to securely connect to a private network using the
 Internet.
        ID: ms_pptp

Network transport 15:
        Display name: Layer 2 Tunneling Protocol
        Bind name: msl2tp
        Characteristics: 56
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text: Allows you to securely connect to a private network using the
 Internet.
        ID: ms_l2tp

Network transport 16:
        Display name: Remote Access NDIS WAN Driver
        Bind name: NdisWan
        Characteristics: 40
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_ndiswan
           Bound to: WAN Miniport (IKEv2)
           Bound to: RAS Async Adapter
           Bound to: WAN Miniport (PPPOE)
           Bound to: WAN Miniport (PPTP)
           Bound to: WAN Miniport (L2TP)
           Bound to: WAN Miniport (SSTP)

Network transport 17:
        Display name: SSTP based VPN
        Bind name: mssstp
        Characteristics: 56
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text: Allows you to securely connect to a private network using the
 Internet.
        ID: ms_sstp

Network transport 18:
        Display name: NDIS Usermode I/O Protocol
        Bind name: Ndisuio
        Characteristics: 40
        Class GUID: 1295444341-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_ndisuio
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Intel(R) 82566DC Gigabit Network Connection



Enumerating GUID_DEVCLASS_NETSERVICE class:

Network service 1:
        Display name: VirtualBox Bridged Networking Driver
        Bind name: VBoxNetFlt
        Characteristics: 17424
        Class GUID: 1295444340-58149-4558-3210004
        Device Status: 0
        Help Text: VirtualBox Bridged Networking Driver
        ID: sun_vboxnetflt
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Intel(R) 82566DC Gigabit Network Connection

Network service 2:
        Display name: Apollo Lan Service
        Bind name: Sfilter
        Characteristics: 1040
        Class GUID: 1295444340-58149-4558-3210004
        Device Status: 0
        Help Text: Apollo Lan Service
        ID: bc_sfilter

Network service 3:
        Display name: Apollo VLAN Trunk Service
        Bind name: ApVlanIm
        Characteristics: 1040
        Class GUID: 1295444340-58149-4558-3210004
        Device Status: 0
        Help Text: Apollo VLAN Trunk Service
        ID: bc_apvlanim

Network service 4:
        Display name: Virtual Machine Network Services
        Bind name: VPCNetS2
        Characteristics: 17552
        Class GUID: 1295444340-58149-4558-3210004
        Device Status: 0
        Help Text: Provides networking support for Microsoft virtual machines.
        ID: cntx_vpcnets2
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Intel(R) 82566DC Gigabit Network Connection

Network service 5:
        Display name: NativeWiFi Filter
        Bind name: NativeWifiP
        Characteristics: 262184
        Class GUID: 1295444340-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_nativewifip

Network service 6:
        Display name: NDIS Capture LightWeight Filter
        Bind name: NdisCap
        Characteristics: 262200
        Class GUID: 1295444340-58149-4558-3210004
        Device Status: 0
        Help Text: Packet Capture Filter Driver
        ID: ms_ndiscap

Network service 7:
        Display name: QoS Packet Scheduler
        Bind name: Psched
        Characteristics: 262144
        Class GUID: 1295444340-58149-4558-3210004
        Device Status: 0
        Help Text: Quality of Service Packet Scheduler.  This component provides
 network traffic control, including rate-of-flow and prioritization services.
        ID: ms_pacer
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Intel(R) 82566DC Gigabit Network Connection
           Bound to: WAN Miniport (IP)
           Bound to: WAN Miniport (Network Monitor)
           Bound to: WAN Miniport (IPv6)

Network service 8:
        Display name: File and Printer Sharing for Microsoft Networks
        Bind name: LanmanServer
        Characteristics: 0
        Class GUID: 1295444340-58149-4558-3210004
        Device Status: 0
        Help Text: Allows other computers to access resources on your computer u
sing a Microsoft network.
        ID: ms_server
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Microsoft ISATAP Adapter #4
           Bound to: Microsoft Windows Mobile Remote Adapter
           Bound to: Microsoft ISATAP Adapter #2
           Bound to: Microsoft ISATAP Adapter #3
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Teredo Tunneling Pseudo-Interface
           Bound to: Microsoft ISATAP Adapter
           Bound to: Intel(R) 82566DC Gigabit Network Connection

Network service 9:
        Display name: NetBIOS Interface
        Bind name: NetBIOS
        Characteristics: 40
        Class GUID: 1295444340-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_netbios
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Microsoft ISATAP Adapter #4
           Bound to: Microsoft Windows Mobile Remote Adapter
           Bound to: Microsoft ISATAP Adapter #2
           Bound to: Microsoft ISATAP Adapter #3
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Teredo Tunneling Pseudo-Interface
           Bound to: Microsoft ISATAP Adapter
           Bound to: Intel(R) 82566DC Gigabit Network Connection

Network service 10:
        Display name: WFP Lightweight Filter
        Bind name: WfpLwf
        Characteristics: 262184
        Class GUID: 1295444340-58149-4558-3210004
        Device Status: 0
        Help Text: WFP Lightweight Filter
        ID: ms_wfplwf
           Bound to: VirtualBox Host-Only Ethernet Adapter
           Bound to: Apollo NDIS Driver for Windows Vista/7
           Bound to: Intel(R) 82566DC Gigabit Network Connection

Network service 11:
        Display name: Steelhead
        Bind name: RemoteAccess
        Characteristics: 40
        Class GUID: 1295444340-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_steelhead

Network service 12:
        Display name: Dial-Up Server
        Bind name: msrassrv
        Characteristics: 56
        Class GUID: 1295444340-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_rassrv

Network service 13:
        Display name: Remote Access Connection Manager
        Bind name: RasMan
        Characteristics: 40
        Class GUID: 1295444340-58149-4558-3210004
        Device Status: 0
        Help Text:
        ID: ms_rasman

I have omitted here output made by the line marked with (*) as it produces hundreds of lines that list binding paths for a given network device. Here is just one snippet from the full output:

           Binding Path: Token = ms_msclient->ms_tcpip6->ROOT\*ISATAP\0003; Enab
led: true
           Binding Path: Token = ms_msclient->ms_tcpip6->ROOT\*ISATAP\0001; Enab
led: true
           Binding Path: Token = ms_msclient->ms_tcpip6->ROOT\*ISATAP\0002; Enab
led: true
           Binding Path: Token = ms_msclient->ms_tcpip6->ROOT\NET\0000; Enabled:
 true
           Binding Path: Token = ms_msclient->ms_tcpip6->ROOT\*TEREDO\0000; Enab
led: true
           Binding Path: Token = ms_msclient->ms_tcpip6->ROOT\*ISATAP\0000; Enab
led: true
           Binding Path: Token = ms_msclient->ms_tcpip6->PCI\VEN_8086&DEV_104B&S
UBSYS_01DB1028&REV_02\3&172E68DD&0&C8; Enabled: true
           Binding Path: Token = ms_msclient->ms_tcpip6->ROOT\NET\0001; Enabled:
 true
           Bound to: Microsoft ISATAP Adapter
           Binding Path: Token = ms_msclient->ms_netbt_smb; Enabled: true
           Binding Path: Token = ms_msclient->ms_netbt->ms_tcpip6->ROOT\*ISATAP\
0003; Enabled: true

INetCfg API supports modifying networking configuration as well (e.g. changing the order of the protocol bindings). Changes can be made only after a lock is acquired. It is possible to search for a particular network item (without iterating through all of them).

Links and References:

Network Configuration Interfaces (MSDN)
Exploring Network Configuration with the INetCfg COM Interface (CodeProject)
Using COM in Your Windows Program (MSDN)
Introduction to Protocols (The Binding Process)

Tuesday 28 February 2012

Code Refactoring

I am dedicating this article to a list of refactoring techinques in addition to the highly cited Martin Fowler's book on Code Refactoring.

Replace Parameter with a New Method (Specialize Method)


Chapter "Replace Parameter with Method" describes when and how to remove passing an argument if method can retrieve argument's value. But I came across to a slightly different case - when some method is frequently called with an argument that it can retrieve:

Let class CConfig be defined as:



Let's assume that the following snippet occurs very often throughout the code:



LoadOption() is obviously able to retrieve m_nOptionSelected so why having two calls instead of the one - of the new method - LoadSelectedOption():



Now you can make a single method call, without a need to provide parameters:


Wednesday 15 February 2012

Static code analysis

One simple way of improving your code is passing it through some of static code analysis tools and fix reported errors and warnings. Such tools will usually point out lines in code that could possibly cause issues with buffer overruns, uninitialized memory, null pointer dereferences, memory and resource leaks, exception safety...or lines that contain code which style could be improved.

If you are using Visual Studio 2010, you can use its static code analysis: open Project Properties -> Configuartion Properties -> Code Analysis. Select desired build configuration and platform and tick Enable Code Analysis for C/C++ on Build. Output window will show code analysis report (search for Running Code Analysis for C/C++... lines).

I want to show here how it looks in the practice. Let's say we have some smelly code:

C.h:

#ifndef _C_H_
#define _C_H_

class C
{
   // unitialized member
   int m_n;
public:
   C()
   {  
      // unused variable
      int j;
   }

   void Init(char ch)
   {
      // C-style pointer cast
      m_n = (int)ch;
   }
};
#endif // _C_H_


main.cpp:

#include "C.h"

// unused function
int foo()
{
   int n;
   return 0;
}

int main()
{
   // unused variable
   int n1; 

   // dereferencing unitialized pointer
   int* pInt1;
   *pInt1 = 1;

   // dereferencing NULL pointer
   int* pInt2 = 0;
   *pInt2 = 2;

   // memory leak - no delete
   int* pInt3 = new int(2);

   // scope of n2 is unecessarily main()
   int n2 = 0;

   {
      char ch = 2;
      n2 = (int)ch;
   }

   int arr[2];
   arr[2] = 3;

   return 0;
}


I played recently with Cppcheck and this is what it reports for the code above:

Cppcheck-report

Visual Studio prints code analysis messages in the Output window and for the code above it contains the following:

1>------ Build started: Project: CppcheckTest, Configuration: Debug Win32 ------
1>Build started 15/02/2012 19:49:12.
1>InitializeBuildStatus:
1> Touching "Debug\CppcheckTest.unsuccessfulbuild".
1>ClCompile:
1> main.cpp
1>c:\...\cppchecktest\c.h(12): warning C4101: 'j' : unreferenced local variable
1>c:\...\cppchecktest\main.cpp(6): warning C4101: 'n' : unreferenced local variable
1>c:\...\cppchecktest\main.cpp(13): warning C4101: 'n1' : unreferenced local variable
1>c:\...\cppchecktest\main.cpp(35): warning C6201: Index '2' is out of valid index range '0' to '1' for possibly stack allocated buffer 'arr'
1>c:\...\cppchecktest\main.cpp(17): warning C6001: Using uninitialized memory 'pInt1': Lines: 13, 16, 17
1>c:\...\cppchecktest\main.cpp(21): warning C6011: Dereferencing NULL pointer 'pInt2': Lines: 13, 16, 17, 20, 21
1>c:\...\cppchecktest\main.cpp(35): warning C6386: Buffer overrun: accessing 'arr', the writable size is '8' bytes, but '12' bytes might be written: Lines: 13, 16, 17, 20, 21, 24, 27, 30, 31, 34, 35
1>c:\...\cppchecktest\main.cpp(17): warning C4700: uninitialized local variable 'pInt1' used
1>ManifestResourceCompile:
1> All outputs are up-to-date.
1>Manifest:
1> All outputs are up-to-date.
1>LinkEmbedManifest:
1> All outputs are up-to-date.
1> CppcheckTest.vcxproj -> C:\...\CppcheckTest\Debug\CppcheckTest.exe
1>FinalizeBuildStatus:
1> Deleting file "Debug\CppcheckTest.unsuccessfulbuild".
1> Touching "Debug\CppcheckTest.lastbuildstate".
1>
1>Build succeeded.
1>
1>Time Elapsed 00:00:04.38
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========


Links and References:
Analyzing Application Quality by Using Code Analysis Tools (MSDN)
How to: Enable and Disable Automatic Code Analysis for C/C++ (MSDN)
Cppcheck

Tuesday 14 February 2012

XML Data Binding - Part 3: CodeSynthesis XSD example

In my previous article about XML Data Binding, I demonstrated how to use gSOAP in order to convert data from XML document into in-memory C++ objects and vice versa. Today I will show how to use another tool, CodeSynthesis XSD, to perform the same task.

CodeSynthesis XSD depends on Apache Xerces-C++ XML parser so you need to download and set up Xerces in your development environment first. Setup of both tools is described in README.txt file you can find after unpacking downloaded CodeSynthesis XSD archive.

In order to compare gSOAP and CodeSynthesis Data Binding process, let's create a project that does the same XML processing, like gSOAP one: loads XML, reads and displays data, adds new element, displays data again and saves chnages to XML.

We are going to use the same XML schema - library.xsd:



If XML documents use XML schema grammars Xerces parser requires them to specify location of their XML schemas (by using an xsi:schemaLocation attribute if they use namespaces, and an xsi:noNamespaceSchemaLocation if not).



NOTE: Make sure xml document and its schema are in the same directory (application's working directory).

Similar to gSOAP case, we need to compile schema into C++ classes. CodeSynthesis schema compiler is xsd.exe and can be found in the bin directory of the package (e.g. ..\xsd-3.3.0-i686-windows\bin\). This directory should be added to Path environment variable. We want to generate C++/Tree mapping and code for serialization (object to XML; this code is not generated by default) so call XSD compiler with following parameters:

c:\test\XercesCodeSynthesis_Test1>xsd cxx-tree --generate-serialization library.xsd

It creates two files, library.hxx and library.cxx, and we need to include them into our project as they contain definitions of proxy classes.

Again, like we had with gSOAP, CodeSynthesis XSD generates classes that match XML document elements, by name and structure. We can see that in the header, library.hxx (some parts are omitted):



Schema complier has generated and Library_ functions that serialize/deserialize data to/from XML file.

main.cpp contains code that loads XML document into Library object, traverses through its member (vector) Books and displays all Book elements; it then adds a new Book to the collection, displays it again and serializes back to XML document in file:



Output:


Displaying all books in the library:

Book:
Title:Clean Code
Author:Robert C. Martin
ISBN: 0132350882
Copies available: 2

Book:
Title:The Pragmatic Programmer
Author:Andrew Hunt
ISBN: 020161622X
Copies available: 0

Book:
Title:Design patterns
Author:Erich Gamma
ISBN: 0201633612
Copies available: 1


Adding a new book:
Title: Effective C++
Author: Scott Meyers
ISBN:0321334876
Copies available: 50


Displaying all books in the library:

Book:
Title:Clean Code
Author:Robert C. Martin
ISBN: 0132350882
Copies available: 2

Book:
Title:The Pragmatic Programmer
Author:Andrew Hunt
ISBN: 020161622X
Copies available: 0

Book:
Title:Design patterns
Author:Erich Gamma
ISBN: 0201633612
Copies available: 1

Book:
Title:Effective C++
Author:Scott Meyers
ISBN: 0321334876
Copies available: 50

library.xml is changed - a new Book element has been added:



Links and References:
Boris Kolpackov: An Introduction to XML Data Binding in C++

Friday 10 February 2012

How to read command line arguments with NSIS

GetParameters copies all command line arguments into provided variable (as a string). GetOptions extracts value of a specified option within provided parameters string. The following example demonstrates how to get value of command line option "-s":

MyInstaller.nsi:



If we call this installer with following parameters:

"MyInstaller.exe" -t=12 -s=yes -k=abc

...a message box will display text: "s = yes".

GetOptions is not case sensitive so if we called it with "-S", the result would be the same. GetOptionsS is a case sensitive form of this function.

Thursday 9 February 2012

XML Data Binding - Part 2: gSOAP example

In my previous post, I explained the benefits of XML Data Binding. In this article I will show how to use gSOAP for conversion of data stored in XML format into objects and vice versa.

Download and unpack the latest gSOAP release package. In the previous article I said that XML Data Binding tools compile XML schemas and create C++ classes that represent XML elements. gSOAP's (Win32) compiler is located in ..\gsoap_2.8.6\gsoap-2.8\gsoap\bin\win32 directory and its full path (e.g. c:\tools\gsoap_2.8.6\gsoap-2.8\gsoap\bin\win32) should be added to Path environment variable. This directory contains two components of gSOAP XML compiler: wsdl2h.exe, which compiles XML schema to intermediate header file and soapcpp2.exe, which generates classes (in the header and source file that we need to include in our C++ project).

We need to get XML schema from our XML file. Let's use XML file based on the one from the previous article but modified by including namespace and using proper naming convention (title case for elements and camelcase for attributes):

library.xml:



We can generate schema from this XML in Visual Studio: select XML item in the main menu and click on Create Schema in the drop down menu. Visual Studio generates schema document in Russian doll design style. It supports only this XSD design pattern because it is the most restrictive one.

library.xsd:



Save both XML and XSD files in the project directory.

Now let us compile schema. This is a two step process. Schema is passed to wsdl2h.exe which generates intermediate header. soapcpp2.exe uses that header to create proxy C++ classes for data binding (header file with their declarations and source file with their definitions).

We need to provide namespace used in our XML document ("gt") as gSOAP would otherwise use its generic namespace name ("ns1") when generating data type names and when serializing our data object back to the XML.

c:\test\gSOAP_Test1>wsdl2h.exe -t "c:\tools\gsoap_2.8.6\gsoap-2.8\gsoap\
typemap.dat" -N "gt" Library.xsd

** The gSOAP WSDL/Schema processor for C and C++, wsdl2h release 2.8.6
** Copyright (C) 2000-2011 Robert van Engelen, Genivia Inc.
** All Rights Reserved. This product is provided "as is", without any warranty.

** The wsdl2h tool is released under one of the following two licenses:
** GPL or the commercial license by Genivia Inc. Use option -l for details.

Saving Library.h

Reading type definitions from type map file 'c:\tools\gsoap_2.8.6\
gsoap-2.8\gsoap\typemap.dat'

Reading file 'Library.xsd'...
Done reading 'Library.xsd'

To complete the process, compile with:
> soapcpp2 Library.h
or to generate C++ proxy and object classes:
> soapcpp2 -j Library.h

We just need to follow the instruction given in the report above - call soapcpp2:

c:\test\gSOAP_Test1>soapcpp2 -I "c:\tools\gsoap_2.8.6\gsoap-2.8\gsoap\
import" Library.h

** The gSOAP code generator for C and C++, soapcpp2 release 2.8.6
** Copyright (C) 2000-2011, Robert van Engelen, Genivia Inc.
** All Rights Reserved. This product is provided "as is", without any warranty.

** The soapcpp2 tool is released under one of the following two licenses:
** GPL or the commercial license by Genivia Inc.

Saving soapStub.h annotated copy of the input declarations
Saving gt.nsmap namespace mapping table
Saving soapH.h interface declarations
Saving soapC.cpp XML serializers

Compilation successful

c:\test\gSOAP_Test1>

As we can see in the report, class declarations are in the following header:

soapStub.h (irrelevant parts omitted):



If observing original XML document and generated classes, we can see the parallel between them: element types are mapped to classes; single children nodes and attributes are mapped to class members; sequence is mapped to a vector. _gt__Library class matches Library element. Its members, Books and Staff match XML elements of the same name. In XML, these nodes are of the sequence type so their C++ implementation (_gt__Library_Books and _gt__Library_Staff) uses STL collection type (vector) to model them. Books element contains Book elements so _gt__Library_Books's vector member contains elements of type _gt__Library_Books_Book. In the same way, Librarian element is mapped to _gt__Library_Staff_Librarian class and _gt__Library_Staff's vector contains its instances.

Class names look a bit ugly but that is because they are made by joining namespace name("gt") and element type name. If namespace isn't specified in the schema, gSOAP uses generic namespace name - "ns1". If element name contains underscore, that character is replaced with "_USCORE" because gSOAP maps hyphens to normal underscores [source].

For Russian doll styled schema, class members and vector elements are objects. This is not the case for schemas designed in Salami slice or Venetian blind styles: class members and vector elements are pointers to objects. This happens even if minOccurs attribute is set to 1. I don't know how to force gSOAP to generate classes that force composition class relationship for any design pattern of the schema provided. I found here one explanation of gSOAP's reasoning: gSOAP generates pointers when it needs to be able to represent a NULL value. If you have defined an element with minOccurs = "0", then you will get a pointer generated in your code. You can then inspect this pointer. If it is NULL, then you know that the element is not present. Conversely, you can choose to set the pointer, or not, to indicate that the element is present or not. Another author says: there are many different ways to define XML Schemas and the design choice can seriously impact the generation of implementation classes in the technology of your choice. There are different schema design styles such as the Russian Doll, Venetian Blind and Garden of Eden that can be followed.

Another generated header is soapH.h (snippet):



We can use these two generated functions to read the content of the root element (Library) into object and to write it back to the XML document. gSOAP compiler has done a great job for us!

Anyway, let's see what we can do with generated classes.

Before compiling your test project, make sure you have added the following paths to Additional Include Directories in Project Settings: c:\DEVELOPMENT\Toolkits\gsoap_2.8.6\gsoap-2.8\gsoap; c:\DEVELOPMENT\Toolkits\gsoap_2.8.6\gsoap-2.8\gsoap\import. Also, make sure you've included soapH.h, soapStub.h, soapC.cpp and stdsoap2.cpp into the project.

In order to use gSOAP engine, we need to create instance of gSOAP runtime context - struct soap. There is a sequence of commands that initialize and clean up this object so I wrapped it into RAII compliant class (CScopedSoap) which makes its usage exception safe.

Notice how it's easy to modify data when we are dealing with objects instead of digging and traversing DOM tree. Adding a new Book is nothing more than adding a new _gt__Library_Books_Book object at the end of the vector!

main.cpp:



Patch I applied in LoadXML() function is necessary as soap_read__gt__Library() for some reason sets mode of the standard input stream to BINARY although it reads data from a file stream. It never reverts stdio's mode back to TEXT. This has a consequence of getline() returning a string that contains Carriage Return character at the end and that character appears in new elements inserted into the XML document. I've posted a question about this on Stack Overflow and will update this article on this as soon as I clarify gSOAP's behaviour in this case.

This is the application's output:

Displaying all books in the library:

Book:
Title:Clean Code
Author:Robert C. Martin
ISBN: 0132350882
Copies available: 2

Book:
Title:The Pragmatic Programmer
Author:Andrew Hunt
ISBN: 020161622X
Copies available: 0

Book:
Title:Design patterns
Author:Erich Gamma
ISBN: 0201633612
Copies available: 1


Adding a new book:
Title: Effective C++
Author: Scott Meyers
ISBN:0321334876
Copies available: 50


Displaying all books in the library:

Book:
Title:Clean Code
Author:Robert C. Martin
ISBN: 0132350882
Copies available: 2

Book:
Title:The Pragmatic Programmer
Author:Andrew Hunt
ISBN: 020161622X
Copies available: 0

Book:
Title:Design patterns
Author:Erich Gamma
ISBN: 0201633612
Copies available: 1

Book:
Title:Effective C++
Author:Scott Meyers
ISBN: 0321334876
Copies available: 53

And XML contains a new Book element:

library.xml:



Links and References:

The gSOAP Toolkit for SOAP Web Services and XML-Based Applications
gSOAP 2.8.7 User Guide
Genivia gSOAP
Robert van Engelen: "gSOAP & Web Services"
gSOAP Yahoo group
gSOAP tagged question on Stack Overflow

Monday 6 February 2012

XML Data Binding - Part 1: Why do we need it?

Your application uses some XML parsing tool (Xerces, libxml, TinyXML, TinyXML++, RapidXml, PugiXML,...) in order to load XML file into a document object, then you traverse through a DOM tree structure, look for nodes, their children, search their attributes so can modify its content (add, modify or delete elements or attributes)...and all this usually requires lots of loops and string comparisons which creates huge, hard to maintain code. Wouldn't be better if you could load XML document into some object in memory which attributes match elements in your XML? You would then be dealing with (C++) objects instead of the complex DOM tree which is much quicker, easier, type safe and less error prone.

Let's say we have some XML that keeps track of the state of the local library. To keep model simple, we can say that library comprises books and staff. Each book has its title, author and ISBN number. Each member of the staff, librarian, has a name. XML document could look like this:

library.xml


We can map each class of nodes into a C++ class where class attributes are node's attributes and its children; siblings are stored in a vector. We need a single instance of the class which represents a root node. Its constructor loads XML document from a file on disk and its destructor saves (eventually modified) XML document back to the file. Our class model and use case might look like this:

main.cpp:



XML document was loaded into object, modified by adding a new book and saved back into the file in just three lines of code! Awesome! But this code is unfinished and actually doesn't work properly in the real life as I omitted the hardest bit: loading and parsing XML in library's constructor and serializing/marshalling object back to the file in the destructor. All I wanted to show was how quick and easy is to manipulate XMLs when representing them through objects - a concept which is known as XML Data Binding.

Another problem steams from the fact that for each new XML we would need to write completely new classes - doing this manually is a no way to go but luckily there are tools that do this automatically. They compile XML schema (a document which specifies XML document itself) into a set of classes, following precise rules of mapping XML into objects (Object/XML Mapping or O/X Mapping). In next two articles I will show how to use gSOAP and CodeSynthesis XSD for this.

Links and References:
XML Data Binding Tools