Monday, December 21, 2009

Serialization in VC++

Reading and Writing Documents—SDI Applications
 Serialization: What Is It?

The term "serialization" might be new to you, but it's already seen some use in the world of object-oriented programming. The idea is that objects can be persistent, which means they can be saved on disk when a program exits and then can be restored when the program is restarted. This process of saving and restoring objects is called serialization. In the MFC library, designated classes have a member function named Serialize(). When the application framework calls Serialize() for a particular object, for example, an object of class CStudent, the data for the student is either saved on disk or read from disk. In the MFC library, serialization is not a substitute for a database management system. All the objects associated with a document are sequentially read from or written to a single disk file. It's not possible to access individual objects at random disk file addresses. If you need database capability in your application, consider using the Microsoft Open Database Connectivity (ODBC) software or Data Access Objects (DAO). The MFC framework already uses structured storage (for database) for container programs that support embedded objects. 

Reading and Writing Documents—SDI Applications
Disk Files and Archives

How do you know whether Serialize() should read or write data? How is Serialize() connected to a disk file? With the MFC library, objects of class CFile represent disk files. A CFile object encapsulates the binary file handle that you get through the Win32 function CreateFile(). This is not the buffered FILE pointer that you'd get with a call to the C runtime fopen() function; rather, it's a handle to a binary file. The application framework uses this file handle for Win32 ReadFile(), WriteFile(), and SetFilePointer() calls.

If your application does no direct disk I/O but instead relies on the serialization process, you can avoid direct use of CFile objects. Between the Serialize() function and the CFile object is an archive object of class CArchive, as shown in Figure 1.

The CArchive object buffers data for the CFile object, and it maintains an internal flag that indicates whether the archive is storing (writing to disk) or loading (reading from disk). Only one active archive is associated with a file at any one time. The application framework takes care of constructing the CFile and CArchive objects, opening the disk file for the CFile object and associating the archive object with the file. All you have to do (in your Serialize() function) is load data from or store data in the archive object. The application framework calls the document's Serialize() function during the File Open and File Save processes. 




Reading and Writing Documents—SDI Applications
Figure 1: The serialization process.

A serializable class must be derived directly or indirectly from CObject. In addition (with some exceptions), the class declaration must contain the DECLARE_SERIAL macro call, and the class implementation file must contain the IMPLEMENT_SERIAL macro call. See the Microsoft Foundation Class Reference for a description of these macros. This module's CStudent class example is modified from the class in Module 10 to include these macros. 

Reading and Writing Documents—SDI Applications
Writing a Serialize Function

In Module 10, you saw a CStudent class, derived from CObject, with these data members:

public:
CString m_strName;
int m_nGrade;

Now, your job is to write a Serialize() member function for CStudent. Because Serialize() is a virtual member function of class CObject, you must be sure that the return value and parameter types match the CObject declaration. The Serialize() function for the CStudent class is below.

void CStudent::Serialize(CArchive& ar)
{
TRACE("Entering CStudent::Serialize\n");
    if (ar.IsStoring())
      {
         ar << m_strName << m_nGrade;
       }
else 
Reading and Writing Documents—SDI Applications
     {
        ar >> m_strName >> m_nGrade;
     }


Reading and Writing Documents—SDI Applications
Most serialization functions call the Serialize() functions of their base classes. If CStudent were derived from CPerson, for example, the first line of the Serialize() function would be:

CPerson::Serialize(ar);

The Serialize() function for CObject (and for CDocument, which doesn't override it) doesn't do anything useful, so there's no need to call it. Notice that ar is a CArchive reference parameter that identifies the application's archive object. The CArchive::IsStoring member function tells us whether the archive is currently being used for storing or loading. The CArchive class has overloaded insertion operators (<<) and extraction operators (>>) for many of the C++ built-in types, as shown in the following table.


Reading and Writing Documents—SDI Applications
Type
Description
BYTE
8 bits, unsigned
WORD
16 bits, unsigned
LONG
32 bits, signed
DWORD
32 bits, unsigned
float
32 bits
double
64 bits, IEEE standard
int
32 bits, signed
short
16 bits, signed
char
8 bits, unsigned
unsigned
32 bits, unsigned
Table 1
 


Reading and Writing Documents—SDI Applications
The insertion operators are overloaded for values; the extraction operators are overloaded for references. Sometimes you must use a cast to satisfy the compiler. Suppose you have a data member m_nType that is an enumerated type. Here's the code you would use:

ar << (int) m_nType;
ar >> (int&) m_nType;

MFC classes that are not derived from CObject, such as CString and CRect, have their own overloaded insertion and extraction operators for CArchive.



Reading and Writing Documents—SDI Applications




Thursday, December 3, 2009

VC++ Exception Handling

Exception Processing

 The macros and global functions fall into the following categories:


·         Exception macros, which structure your exception handler.

·         Exception-throwing functions, which generate exceptions of specific types.

·         Termination functions, which cause program termination.

Exception Macros   
TRY
Designates a block of code for exception processing.
CATCH
Designates a block of code for catching an exception from the preceding TRY block.
CATCH_ALL
Designates a block of code for catching all exceptions from the preceding TRY block.
AND_CATCH
Designates a block of code for catching additional exception types from the preceding TRY block.
AND_CATCH_ALL
Designates a block of code for catching all other additional exception types thrown in a preceding TRY block.
END_CATCH
Ends the last CATCH or AND_CATCH code block.
END_CATCH_ALL
Ends the last CATCH_ALL code block.
THROW
Throws a specified exception.
THROW_LAST
Throws the currently handled exception to the next outer handler.
   
Exception-Throwing Functions  
AfxThrowArchiveException
Throws an archive exception.
AfxThrowFileException
Throws a file exception.
AfxThrowMemoryException
Throws a memory exception.
AfxThrowNotSupportedException
Throws a not-supported exception.
AfxThrowResourceException
Throws a Windows resource-not-found exception.
AfxThrowUserException
Throws an exception in a user-initiated program action.
OLE Exception Functions  
AfxThrowOleDispatchException
Throws an exception within an OLE automation function.
AfxThrowOleException
Throws an OLE exception.
   
DAO Exception Functions  
AfxThrowDAOException
Throws a CDaoException from your own code.
AfxThrowDBException
Throws a CDBException from your own code.
Termination Functions  
AfxAbort
Called to terminate an application when a fatal error occurs.


Exception Handling in Visual C++


Visual C++ supports three kinds of exception handling:

(1) C++ exception handling

(2) Structured exception handling

(3) MFC exceptions




When to Use Exceptions 


Three categories of outcomes can occur when a function is called during program execution: normal execution, erroneous execution, or abnormal execution. Each category is described below.


  Normal execution 


The function may execute normally and return. Some functions return a result code to the caller, which indicates the outcome of the function. The possible result codes are strictly defined for the function and represent the range of possible outcomes of the function. The result code can indicate success or failure or can even indicate a particular type of failure that is within the normal range of expectations. For example, a file-status function can return a code that indicates that the file does not exist. Note that the term "error code" is not used because a result code represents one of many expected outcomes.

     Erroneous execution 


The caller makes some mistake in passing arguments to the function or calls the function in an inappropriate context. This situation causes an error, and it should be detected by an assertion during program development. 



Abnormal execution 


Abnormal execution includes situations where conditions outside the program's control, such as low memory or I/O errors, are influencing the outcome of the function. Abnormal situations should be handled by catching and throwing exceptions.





















Exception class
Meaning
CMemoryException Class
Out-of-memory
CFileException Class
File exception
CArchiveException Class
Archive/Serialization exception
CNotSupportedException Class
Response to request for unsupported service
CResourceException Class
Windows resource allocation exception
CDaoException Class
Database exceptions (DAO classes)
CDBException Class
Database exceptions (ODBC classes)
COleException Class
OLE exceptions
COleDispatchException Class
Dispatch (automation) exceptions
CUserException Class
Exception that alerts the user with a message box, then throws a generic CException Class


Thursday, November 26, 2009

CImageList Class

CImageList Class

An "image list" is a collection of same-sized images, each of which can be referred to by its zero-based index. Image lists are used to efficiently manage large sets of icons or bitmaps. All images in an image list are contained in a single, wide bitmap in screen device format. An image list may also include a monochrome bitmap that contains masks used to draw images transparently (icon style). The Microsoft Win32 application programming interface (API) provides image list functions that enable you to draw images, create and destroy image lists, add and remove images, replace images, merge images, and drag images.

 
CImageList::Create

Initializes an image list and attaches it to a CImageList Class object.

BOOL Create(
   int cx,
   int cy,
   UINT nFlags,
   int nInitial,
   int nGrow 
);
BOOL Create(
   UINT nBitmapID,
   int cx,
   int nGrow,
   COLORREF crMask 
);
BOOL Create(
   LPCTSTR lpszBitmapID,
   int cx,
   int nGrow,
   COLORREF crMask 
);
BOOL Create(
   CImageList& imagelist1,
   int nImage1,
   CImageList& imagelist2,
   int nImage2,
   int dx,
   int dy 
);
BOOL Create(
   CImageList* pImageList 
);
 

Parameters
cx
Dimensions of each image, in pixels.
cy
Dimensions of each image, in pixels.
nFlags
Specifies the type of image list to create. This parameter can be a combination of the following values, but it can include only one of the ILC_COLOR values.
Value
Meaning
ILC_COLOR
Use the default behavior if none of the other ILC_COLOR* flags is specified. Typically, the default is ILC_COLOR4; but for older display drivers, the default is ILC_COLORDDB.
ILC_COLOR4
Use a 4-bit (16 color) device-independent bitmap (DIB) section as the bitmap for the image list.
ILC_COLOR8
Use an 8-bit DIB section. The colors used for the color table are the same colors as the halftone palette.
ILC_COLOR16
Use a 16-bit (32/64k color) DIB section.
ILC_COLOR24
Use a 24-bit DIB section.
ILC_COLOR32
Use a 32-bit DIB section.
ILC_COLORDDB
Use a device-dependent bitmap.
ILC_MASK
Uses a mask. The image list contains two bitmaps, one of which is a monochrome bitmap used as a mask. If this value is not included, the image list contains only one bitmap. See Drawing Images from an Image List for additional information on masked images.
nInitial
Number of images that the image list initially contains.
nGrow
Number of images by which the image list can grow when the system needs to resize the list to make room for new images. This parameter represents the number of new images the resized image list can contain.
nBitmapID
Resource IDs of the bitmap to be associated with the image list.
crMask
Color used to generate a mask. Each pixel of this color in the specified bitmap is changed to black, and the corresponding bit in the mask is set to one.
lpszBitmapID
A string containing the resource IDs of the images.
imagelist1
A reference to a CImageList object.
nImage1
Index of the first existing image.
imagelist2
A reference to a CImageList object.
nImage2
Index of the second existing image.
dx
Offset of the x-axis of the second image in relationship to the first image, in pixels.
dy
Offset of the y-axis of the second image in relationship to the first image, in pixels.
pImageList
A pointer to a CImageList object.
  
Return Value
 
Nonzero if successful; otherwise 0.


 Example


m_myImageList.Create(32, 32, ILC_COLOR8, 0, 4);


CImageList::Add
Call this function to add one or more images or an icon to an image list.

int Add(
   CBitmap* pbmImage,
   CBitmap* pbmMask 
);
int Add(
   CBitmap* pbmImage,
   COLORREF crMask 
);
int Add(
   HICON hIcon 
);

Parameters
pbmImage
Pointer to the bitmap containing the image or images. The number of images is inferred from the width of the bitmap.
pbmMask
Pointer to the bitmap containing the mask. If no mask is used with the image list, this parameter is ignored.
crMask
Color used to generate the mask. Each pixel of this color in the given bitmap is changed to black and the corresponding bit in the mask is set to one.
hIcon
Handle of the icon that contains the bitmap and mask for the new image.

Return Value
 
Zero-based index of the first new image if successful; otherwise – 1.

Example


// Add my icons.
 
m_myImageList.Add(AfxGetApp()->LoadIcon(IDI_ICON1));
m_myImageList.Add(AfxGetApp()->LoadIcon(IDI_ICON2));
 
// Add my bitmap, make all black pixels transparent.
 
CBitmap bm;
bm.LoadBitmap(IDB_BITMAP1);
m_myImageList.Add(&bm, RGB(0, 0, 0));

CImageList::Attach
Call this function to attach an image list to a CImageList object.

BOOL Attach(
   HIMAGELIST hImageList 
);

Parameters
hImageList
A handle to an image list object.

Return Value
 
Nonzero if the attachment was successful; otherwise 0.

 Example


void AddQuestion(HIMAGELIST hmyImageList)
{
   CImageList imgList;
 
   // Attach the image list handle to the CImageList object.
   imgList.Attach(hmyImageList);
 
   // Add a new icon to the image list.
   imgList.Add(AfxGetApp()->LoadStandardIcon(IDI_QUESTION));
 
   // Detach the handle from the CImageList object.
   imgList.Detach();
}


CImageList::Write
Call this function to write an image list object to an archive.

BOOL Write(
   CArchive* pArchive 
);

Parameters
pArchive
A pointer to a CArchive object in which the image list is to be stored.

Return Value
Nonzero if successful; otherwise 0.

Example

// Open the archive to store the image list in.
CFile   myFile(_T("myfile.data"), CFile::modeCreate | CFile::modeWrite);
CArchive ar(&myFile, CArchive::store);
 
// Store the image list in the archive.
m_myImageList.Write(&ar);

How to Draw Triangle in VC++

FileName : TriangleView.h

class CTriangleView : public CView
{
 ...
 CPoint tr[3],ct;
 int rad;
 double rd;
 CRect rc;
...
};


FileName : TriangleView.cpp


 #include "math.h"
...

CTriangleView::CTriangleView()
{
    // TODO: add construction code here
    rd=0.0174532935;
}

void CTriangleView::OnDraw(CDC* pDC)
{
    CTriangleDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    // TODO: add draw code for native data here
    int i=0;
    GetClientRect (rc);
    ct.x = (rc.left + rc.right )/2;
    ct.y = (rc.top + rc.bottom )/2;
    rad=ct.x/2;
    while(i<3)
    {
    tr[i].x = ct.x + rad * sin(i*120*rd);
    tr[i].y = ct.y - rad * cos(i*120*rd);
    i++;
    }
    pDC->Polygon (tr,3);
}

CDC Text Functions

CDC::DrawText
Draws formatted text in the specified rectangle.
CDC::DrawTextEx
Draws formatted text in the specified rectangle using additional formats.
CDC::ExtTextOut
Writes a character string within a rectangular region using the currently selected font.
CDC::GetCharABCWidthsI
Retrieves the widths, in logical units, of consecutive glyph indices in a specified range from the current TrueType font.
CDC::GetCharacterPlacement
Retrieves various types of information on a character string.
CDC::GetCharWidthI
Retrieves the widths, in logical coordinates, of consecutive glyph indices in a specified range from the current font.
CDC::GetOutputTabbedTextExtent
Computes the width and height of a character string on the output device context.
CDC::GetOutputTextExtent
Computes the width and height of a line of text on the output device context using the current font to determine the dimensions.
CDC::GetOutputTextMetrics
Retrieves the metrics for the current font from the output device context.
CDC::GetTabbedTextExtent
Computes the width and height of a character string on the attribute device context.
CDC::GetTextAlign
Retrieves the text-alignment flags.
CDC::GetTextCharacterExtra
Retrieves the current setting for the amount of intercharacter spacing.
CDC::GetTextExtent
Computes the width and height of a line of text on the attribute device context using the current font to determine the dimensions.
CDC::GetTextExtentExPointI
Retrieves the number of characters in a specified string that will fit within a specified space and fills an array with the text extent for each of those characters.
CDC::GetTextExtentPointI
Retrieves the width and height of the specified array of glyph indices.
CDC::GetTextFace
Copies the typeface name of the current font into a buffer as a null-terminated string.
CDC::GetTextMetrics
Retrieves the metrics for the current font from the attribute device context.
CDC::GrayString
Draws dimmed (grayed) text at the given location.
CDC::SetTextAlign
Sets the text-alignment flags.
CDC::SetTextCharacterExtra
Sets the amount of intercharacter spacing.
CDC::SetTextJustification
Adds space to the break characters in a string.
CDC::TabbedTextOut
Writes a character string at a specified location, expanding tabs to the values specified in an array of tab-stop positions.
CDC::TextOut
Writes a character string at a specified location using the currently selected font.


Question List

Practical Question

Dialog Based Program

1. Write an Application to show the current ProgressBar value in EditBox as it incremented 1 to 100.
2. Create Dialog based Application with command button and MessageBox () (Use all Parameters) to print the message with no of clicks whenever user clicks on command button.
3.Write an Application to Split the Entered Text in EditBox and then enter them in ListBox with Uppercase.
(Hint : EditBox :"this is my book"
List Box: THIS
IS
MY
BOOK
4. Write a program to move values from one ListBox to another (1. One by One as User Select, All at Once).
5.Create a Dialog based Application with Static Texts to get the information like Computer Name, Total Memory, Free Memory and Total Load on processor.
6.Create Dialog Based Application to Read and Write a Data from Text file. Use EditBox to Show data.
7.Craete Dialog based Application Which read data from Text file in Reverse order. Show data in EditBox.


SDI/MDI Program

1. Write a program to Animate Circle.
2. Write a program to draw a line using three different mouse events.
3.Write an Apllication to Change Font in SDI.
(Hint : Use Menu for Opening CFontDialog)
4.Write a VC++ project that Draws a Polygon. And Clicking within it Changes its Border Color.
5.Write an Application to Show Current Cursor Position of Mouse in StatusBar.
6.Write an Application to Show Current Date(DD-MM-YYYY) format in StatusBar.
7. Write an Application to Make Simple Web Browser using HtmlView and ReBar.
8. Write an Application to Manipulate Database using (ODBC/ADO/DAO) Connectivity. User can perform Add, Update, Delete, MoveNext, MovePrevious, MoveLast and MoveFirst.