Tuesday 2 September 2008

A simple intorduction to using the MFC collections

CArray, CList and CMap, Free Source Code Download

John McTainsh
Introduction.

This turorial will demonstrate the the MFC collection classes CList, CArray and CMap. These classes are an excillent way to manage dynamic data in a type safe manner. They are very easy to use and mostly encourage solid code.

Quick Start.
Collection Data Types.
Using CArray.
Using CList.
Using CMap.
Using pointers to objects.
A Quick Start.

Lets just use a simple List collection to start with. This example demonstartes a que of shoe sizes held as doubles. Items are added to the Tail of the que and removed from the Head for processing.

#include // MFC suport for Collections
...
//Declare the que object
CList m_lstShoeSize;

//Add items to the que
m_lstShoeSize.AddTail( 10.5 );
m_lstShoeSize.AddTail( 8.0 );
m_lstShoeSize.AddTail( 9.5 );
m_lstShoeSize.AddTail( 9.0 );

//Process (show) the items in the list.
for( POSITION pos = m_lstShoeSize.GetHeadPosition(); pos != NULL; )
{
_tprintf( _T("Shoe size is %4.1lf\n"), m_lstShoeSize.GetNext( pos ) );
}

//Process (remove) the items from the que
while( !m_lstShoeSize.IsEmpty() )
{
double dRemovedShoe = m_lstShoeSize.RemoveHead();
_tprintf( _T("Removing Shoe Size(%4.1lf)\n"), dRemovedShoe );
}

Collection data types.

Jump ahead to using CArray if you just want to skip the theory. In the previous example you would note the use of a template . The two parameters are used to define how data is stored and retrieved from the collection.
TYPE.

This is the type of data that is used to hold the elements internally and RETURNED from the collection. Get returns this data type.
ARG_TYPE.

This type is use to specify the type of data used to write (STORE) data to the collection. Set uses this data type. Often this type is a reference to the TYPE value. Some examples follow;

CList< PERSON*, PERSON* > m_lstPeople; //1 List of pointers to struct
CList< CString, CString > m_lstNames; //2 List of CStrings
CList< CString, CString&> m_lstNames; //3 .. same using references
CList< CString, LPCSTR > m_lstNames; //4 .. using constant pointers

Note 1: With regard sample 1, the list contains pointer not objects, so the objects must be created with new and deleted when no longer required.

Note 2: With regard sample 3, the ARG_TYPE parameter is used to indicate how the value will be passed into the collection, ie in the Add() method. It does NOT indicate a collection of referances.
Using CArray.

CArray is a collection that is best used for data that is to be accessed in a random or non sequensial manner. The array can dynamically shrink and grow as necessary. Array indexes always start at position 0. You can decide whether to fix the upper bound or allow the array to expand when you add elements past the current bound. Memory is allocated contiguously to the upper bound, even if some elements are null.

The following example adds two CTime objects to the array and then displays the contents of the entire array. The key functions are SetAtGrow which adds an item and increases the array size and the [] operator which is used to retrieve data from the array.

#include // MFC suport for Collections
...
CArray m_aryTime;

m_aryTime.SetAtGrow( 3, CTime::GetCurrentTime() );
m_aryTime.SetAtGrow( 5, CTime( 1999, 6, 12 ) );

for( int nCnt = 0; nCnt < m_aryTime.GetSize(); nCnt++ )
{
if( m_aryTime[nCnt].GetTime() != 0 )
{
_tprintf( _T("Time is %s\n"),
m_aryTime[nCnt].Format( _T("%d/%b/%y %H:%M") ) );
}
else
{
_tprintf( _T("Invalid Time\n") );
}
}

Using CList.

Lists are simular to arrays but are optimised for data that is read in a more sequensial manner such as ques and lists. See the example in Quick Start. earlier for a simple list example. Note items are added at the head or tail of the list. Retrival is from the head or tail of the list and via an iterative process.

#include // MFC suport for Collections
...
//Declare the que object
CList m_lstDepth;

//Add items to the que
m_lstDepth.AddTail( 100 );
m_lstDepth.AddTail( 85 );
m_lstDepth.AddTail( 95 );
m_lstDepth.AddTail( 90 );

//Process (show) the items in the list.
for( POSITION pos = m_lstDepth.GetHeadPosition(); pos != NULL; )
{
_tprintf( _T("Dive depth is %4d\n"), m_lstDepth.GetNext( pos ) );
}

Using CMap.

The CMap object is an simple collection, but unlike arrays and lists, which index and order the data they store, maps associate keys and values. To access a value stored in a map, specifying the value¢Î associated key. This is simular to a hash table.

#include // MFC suport for Collections
...
CMap m_mapAddress;

m_mapAddress[_T( "10.1.1.102" )] = _T("BILL");
m_mapAddress[_T( "10.1.1.108" )] = _T("MAILSERVER");
m_mapAddress[_T( "10.1.1.112" )] = _T("DevLaptop01");
m_mapAddress[_T( "10.1.1.10" )] = _T("PALEALE");
m_mapAddress[_T( "10.1.3.1" )] = _T("PTRAK");

CString sMachine;
CString sUnknownIP = _T( "?0.?.?.112" );
sUnknownIP.Replace( _T("?"), _T("1") );
m_mapAddress.Lookup( sUnknownIP, sMachine );

_tprintf( _T("Machine at IP %s is %s\n"), sUnknownIP, sMachine );

Using pointers to objects.

In all the previous examples the items in the list all supported the assigment = operator. This makes it possible to add and retrieve data from the collection. Items that do not support the assignment operator can still be saved to a collection but must be created and destroyed manualy. The objects must be dynamically allocated using the new operator, ie the "free store" or "heap" this ensures they are not deleted once they go out of scope. Therefore when removed from the list they must be manually deleted. A destructor is often good place to perform this task. The following example shows a list of PERSON structures that are created, displayed and deleted.

NOTE: Unlike other collections, pointers return the actual object rather than a copy, so changes made to the returned object are perminent.

#include // MFC suport for Collections
...
//Person structure
#define LEN_CLOTH_SIZE (5) //Max cloth size length
typedef struct _PERSON
{
int nHeight; //in cm
CString sFullName; //Name
COleDateTime tmBirthDate; //Birthday
TCHAR szShirt[LEN_CLOTH_SIZE]; //Shirt size
} PERSON, *LPPERSON;
...

CList< LPPERSON, LPPERSON > m_lstPeople;

//Bilbos details
LPPERSON lpPerson = new PERSON;
lpPerson->nHeight = 95;
lpPerson->sFullName = _T("Bilbo Baggins");
_tcscpy( lpPerson->szShirt, _T("XOS") );
lpPerson->tmBirthDate = COleDateTime( 1965, 6, 22, 3, 0, 0 );
m_lstPeople.AddTail( lpPerson );

//Fredo details
lpPerson = new PERSON;
lpPerson->nHeight = 49;
lpPerson->sFullName = _T("Fredo Frog");
_tcscpy( lpPerson->szShirt, _T("OS") );
lpPerson->tmBirthDate = COleDateTime( 1965, 1, 5, 18, 0, 0 );
m_lstPeople.AddTail( lpPerson );

//Display the People in the que
POSITION posPerson = m_lstPeople.GetHeadPosition();
while( posPerson != NULL )
{
LPPERSON lpDisplayPerson = m_lstPeople.GetNext( posPerson );
_tprintf( _T("Name .........%s\n"), lpDisplayPerson->sFullName );
_tprintf( _T("Height %d\n"), lpDisplayPerson->nHeight );
_tprintf( _T("Shirt size %s\n"), lpDisplayPerson->szShirt );
_tprintf( _T("Birthday %s\n\n"), lpDisplayPerson->tmBirthDate.
Format( _T("%d/%b/%y %H:%M") ) );
}

//Free out the list
while( !m_lstPeople.IsEmpty() )
{
LPPERSON lpLostPerson = m_lstPeople.RemoveHead();
delete lpLostPerson;
}

Tuesday 24 June 2008

CMake, cross-platform make

Welcome to CMake, the cross-platform, open-source build system. CMake is a family of tools designed to build, test and package software. CMake is used to control the software compilation process using simple platform and compiler independent configuration files. CMake generates native makefiles and workspaces that can be used in the compiler environment of your choice. CMake is quite sophisticated: it is possible to support complex environments requiring system introspection, pre-processor generation, code generation and template instantiation. In addition to controling the build process, CMake includes CTest for testing and CPack for packaging. Please go here to learn more about CMake.
CMake was developed by Kitware as part of the NLM Insight Segmentation and Registration Toolkit project. The ASCI VIEWS project also provided support in the context of their parallel computation environment.

http://www.cmake.org/HTML/index.html

Sunday 15 June 2008

15 Tools to Help You Develop Faster Web Pages

Response times, availability, and stability are vital factors to bear in mind when creating and maintaining a web application. If you’re concerned about your web pages’ speed or want to make sure you’re in tip-top shape before starting or launching a project, here’s a few useful, free tools to help you create and sustain high-performance web applications.

I’ve tried to include a wide variety of tools that are easy to use, and have tried to keep them as OS and technology-independent as possible so that everyone can find a tool or two.
http://sixrevisions.com/tools/faster_web_page/

Friday 13 June 2008

Debugging Windows Error Reporting

If you’re a software developer, chances are that you have written an application, and this application has crashed. When this happened, it probably put up a dialog that looks something like this:



How do you figure out what went wrong?

Strategy #1: Extract the minidump from Windows Error Reporting
Windows Error reporting has already created a minidump of the crash. So one way to find out what went wrong is just to look at the minidump. This works really well if your application is written in native code and there is no debugger on the machine where the crash occurs. You can use it for managed code too, but you will need to use sos.dll to analyze the dump (see MSDN). Open a command prompt (Start->Run, cmd.exe), and switch to your temp directory:

C:\Documents and Settings\greggm>cd /d %tmp%


Look for the dump file that Windows Error Reporting produced. It will have a '.dmp' or '.mdmp' extension and the date should be shortly after the crash happened:


C:\DOCUME~1\greggm\LOCALS~1\Temp>dir *.*dmp
Volume in drive C has no label.
Volume Serial Number is 70E3-6676

Directory of C:\DOCUME~1\greggm\LOCALS~1\Temp

05/24/2007 08:54 AM 109,570 4A88835.dmp
1 File(s) 109,570 bytes
0 Dir(s) 25,379,823,616 bytes free

Mark the file as read-only. This will prevent Windows Error Reporting from deleting the file after you dismiss the dialog:

C:\DOCUME~1\greggm\LOCALS~1\Temp>attrib +r 4A88835.dmp

Now dismiss windows error reporting and copy the dump file wherever you want. You can analyze the dump in Visual Studio by opening the dump file as a project (File->Open Project), and start debugging (F5).



Strategy #2: Access the dump from Online Crash Analysis
Microsoft has a program to allow ISVs to access the crashes in their applications that have been submitted by users. If the person experiencing the crash is a customer, this is a great way to find out what happened. See the winqual site for more information.



Strategy #3: Debug the crash through Just-In-Time Debugging
Probably everyone already knows about this, so I won’t spend much time discussing it. However, as long as the application is crashing on a computer that has a debugger installed, this is the easiest option. The only thing tricky that I will mention is that in Windows Vista, depending on your computers Windows Error Reporting settings, you might actually need to click the 'Send information' button before Windows Vista will present you with a second dialog that allows you to debug.

Tuesday 10 June 2008

Watir - Automated testing that doesn’t hurt

Watir is a simple open-source library for automating web browsers. It allows you to write tests that are easy to read and easy to maintain. It is optimized for simplicity and flexibility.

Watir drives browsers the same way people do. It clicks links, fills in forms, presses buttons. Watir also checks results, such as whether expected text appears on the page.

Watir is a Ruby library that works with Internet Explorer on Windows. Watir is currently being ported to support Firefox and Safari.

Like other programming languages, Ruby gives you the power to connect to databases, read data files, export XML and structure your code into reusable libraries. Unlike other programing languages, Ruby is concise and often a joy to read.

Watir stands for “Web Application Testing in Ruby”. It is pronounced water.

http://wtr.rubyforge.org/

Tuesday 3 June 2008

The 100 top Web apps for 2008

These are the 100 best Web 2.0 applications, chosen by Webware readers and Internet users across the globe. Over 1.9 million votes were cast to select these Webware 100 winners: http://www.webware.com/html/ww/100/2008/winners.html

Tuesday 27 May 2008

Speed Up Your Website - By Example

Introduction
"We live only to discover beauty, all else is a form of waiting. Khalil Gibran", if you agree with this saying, then you are well aware of what it mean to minimize wait for your web audiences.Building an HTML page, adding images, CSS and JS has become piece of cake over last few years, but delivering these rich-contents with a Performance to client browser is still a daunting task. This narrow down check list will help you to review your web site to minimize download time.
Note: This article describes only Front-End engineering issues, No Programming/CGI scripting/Data Structure/Database/Multimedia optimization techniques are discussed in this article.

http://www.codeproject.com/KB/HTML/SpeedUpWebsite.aspx