Tuesday, November 17, 2009

Chapter 2: MFC Fundamentals and Architecture

Chapter 2: MFC Fundamentals and Architecture

The Microsoft Foundation Class (MFC) Library and Visual C++ provide an environment that you can use to easily create a wide variety of applications. This chapter discusses the various class types and primary architectures that are used in most applications.

Objectives

After completing this chapter, you will be able to:

® List the major categories of MFC classes, and the primary classes derived from each category.

® Describe the relationship of the foundation class CObject to the other MFC classes.

® Explain the key features CObject contributes to the classes derived from it.

® Define the main base classes used in a typical MFC application.

® Describe the document/view architecture and how this architecture applies to MFC.

® Describe the benefits and costs of document/view, non-document/view, and dialog-based application architectures.

® Describe how MFC maps messages to functions.

Introduction to MFC

The MFC Library is a collection of C++ classes and an application framework designed primarily for creating Microsoft Windows-based applications. This collection of classes extends the C++ language to include most of the basic structural elements used to create Windows programs. The application framework defines the structure of an application and handles many routine tasks for the application.

This section describes the relationship between MFC and Windows technology, and explains some key advantages that MFC and Visual C++ offer developers.

This section includes the following topics:


  1. MFC and the Win32 API
The MFC Library is built on top of the Win32 application programming interface (API). This API is a set of functions exposed by the operating system for use by applications. Through MFC, base classes are exposed that represent common objects in the Windows operating system, such as windows and menus.

MFC does not encapsulate, or wrap, the entire API, just the main structural components and components that are commonly used. Because MFC is written in C++, MFC developers can easily use the Win32 API to make native calls to the operating system.

To see an illustration that shows the relationship between MFC, the Windows Base Operating Services, and the Windows Operating System Extensions, click this icon.





MFC version 1.0 was little more than a thin wrapper for the Win32 API. However, each subsequent version of MFC provides significantly more features and functionality. MFC incorporates many names and constructions familiar to developers who have used the Microsoft Windows Software Development Kit (SDK). For example, MFC provides a member function named CWnd::InvalidateRect that corresponds to the Win32 function InvalidateRec.

Wrapper Classes for Operating System Extensions

MFC encapsulates important Microsoft Windows operating system extensions, including COM, ActiveX, ODBC, and Windows Internet APIs. The encapsulation is not complete. However, combining MFC and native API usage is usually simple.

Benefits of Using Visual C++

Visual C++ provides a productive visual development environment that gives you the tools you need to create a wide variety of applications, from client/server solutions to high-performance multimedia applications.

Visual C++ supports the latest in Windows operating system-based technology, including the Windows 95 operating system. Visual C++ offers full support for the common controls in the Windows 95 and Windows NT operating systems, as well as support for the Windows 95 Explorer shell. Most of the new Windows 95-based common controls are fully supported by Visual C++, and you can access them through MFC and the Win32 API.

Some other features that make Visual C++ an excellent choice for developing solutions are:

® Code reusability.

® Application wizards for MFC applications, DLLs, ActiveX controls, Active Template Library (ATL) projects, ATL Component Object Model (COM) objects, and ISAPI extensions.

® The integrated development environment of Developer Studio.

® Components and Controls Gallery, a place to store and access reusable components and controls.

® Support for the MFC Library.

® Portability and cross-platform support.

® Availability in Chinese, English, German, French, Italian, Korean, Japanese, and Spanish.

® Support for the latest C++ features.

Benefits of Using MFC

The Microsoft Foundation Class (MFC) Library enables you to build on the work of expert Windows developers. MFC shortens development time, makes code more portable, provides support without reducing programming freedom and flexibility, and provides easy access to hard-to-program user-interface elements and technologies such as ActiveX, OLE, and Internet programming. Furthermore, MFC simplifies database programming through data access objects (DAO) and Open Database Connectivity (ODBC), and simplifies network programming through Windows Sockets. MFC makes it easy to program such features as property sheets (tab dialog boxes), print preview, and floating, customizable toolbars.

By using MFC, you can add many features to your applications in an easy, object-oriented way. In MFC version 3.0, you could add ToolTips to your application by adding only three lines of code. With MFC 4.0, a similar amount of code enables ActiveX controls in your application. Now with MFC version 4.2, Visual C++ 5.0, the Gallery, and the wizards, you can add Active Template Library (ATL) components, Internet classes, and synchronization for multithreaded programs.

MFC offers the experienced C++ developer many advantages when developing full-featured Windows applications, front-end database applications, ActiveX controls and components, and Internet applications, such as:

® An application framework on which you can build a Windows application

® Compatibility with previous MFC versions and the new C++ classes

® The largest base of reusable C++ source code in the industry

® Integration with Visual C++

® Flexible, fast database access methods using DAO or ODBC

® Support for ActiveX and Internet technologies

® Support for popular data-binding technologies

® Support for Windows messaging API

® Support for multithreading


The MFC Class Hierarchy

The first step on the road to becoming an MFC developer is becoming familiar with the classes. This section gives you an overview of the kind of infrastructure MFC provides, including the classes and class hierarchy.

MFC provides nearly 250 classes designed to serve a wide range of programming needs. The first step in programming with MFC is to become familiar with these classes and learn how they are related to one another in the MFC hierarchy. Some classes are used directly, while others serve as base classes for the classes that you create.

When learning about the MFC classes, it is helpful to organize them into the following categories, which are the topics included in this section:

® CObject-Derived Classes

® Application Architecture Classes

® User-Interface Classes

® General-Purpose Classes

® ActiveX Classes

® Database Classes

® Internet Classes

® Global Afx Functions

These categories of MFC classes are not mutually exclusive. The majority of MFC classes are derived, either directly or indirectly, from CObject.


  1. CObject-Derived Classes
CObject is the base class for most of MFC and provides the foundation for serialization (loading and saving data to a file), run-time class information, diagnostic and debugging support (validations and dumps), and compatibility with collection classes.


CObject Hierarchy

To see an illustration that shows the relationship of CObject to the other classes in the MFC class hierarchy, click this icon.





The classes in MFC that are derived from CObject provide most of the structure and functionality of an MFC application. The following table lists some of the most important classes and describes the tasks they perform.

Category Base class Description

Command targets CCmdTarget For classes that are capable of handling the user's requests.

Applications CWinApp Represents the core of the application.
Documents CDocument Contains an application's data set.
Windows CWnd For graphical user interface (GUI) objects that are capable of handling general
Windows messages.
Frames CFrameWnd For an application's primary window frame.
Views CView Displays data and interacts with the document object.

In addition, there are many CObject-derived classes for other aspects of a Win32-based application, such as menus, graphics, file services, and so on.

Support for CObject-Derived Classes

CObject provides three basic types of support to classes that inherit from it, as shown in this table.

Type of support Description

Serialization In this context, serialization is the process of writing or reading an object to or from a persistent storage medium, such as a disk file.

Run-time class information Because it is derived from CRuntimeClass, objects derived from CObject contain information about their origins that is accessible at run time. This run-time type-checking feature gives functions the ability to react based on the type of object that is acted on.

Diagnostic output To aid in the development of an MFC application, CObject provides a number of diagnostic or debug output functions. Overriding these functions provides information about the execution of your program that is especially useful when program behavior is not as expected.

Classes Not Derived from CObject

MFC also contains a set of classes that are not derived from CObject. These classes are useful in situations where the overhead associated with CObject and run-time type identification are unnecessary. These classes fall into three general categories, as shown in the following table.

Category Examples

General utility classes for general programming CString, CTime, CTimeSpan, CRect, CPoint, CSize

MFC support classes to assist the architecture CArchive, CDumpContext, CRuntimeClass, CFileStatus, CMemoryState

Templatized versions of the collection classes that take a user-defined pointer CTypedPointerArray
  1. Application Architecture Classes

The application architecture classes represent the basic architectural elements of an application and include CWinApp, which represents the application itself. To see an illustration that shows the architecture classes in the MFC object hierarchy, click this icon.






Some of the architectural classes include CWinApp, CDocument, CCmdTarget, and CWinThread. These classes are the first to be instantiated when the application starts, and they have significant responsibility.

The following table describes these four classes in more detail.

Class name Description


CWinApp This class represents the application itself. All MFC applications derive a class from CWinApp.Depending on the type of framework chosen, the application object is responsible for:

® Initializing the application.

® Building the document template structures.

® Providing the message loop with retrieved messages from the message queue and

dispatching these messages to the appropriate location.

® Cleaning up the application on exit.


CDocument This is the base class for documents in applications that use document/view architecture. A document is simply an abstract representation of a program's data.A major architectural task for the developer is to determine how data is to be stored in the document, and how and to what extent the document will provide access to that data.


CCmdTarget This is the foundation class for message map architecture in MFC. The capabilities that a class inherits from CCmdTarget enable it to serve as a target for a special class of messages, known as command messages. These messages are generated when the user chooses a command from a menu.

CWinThread This class encapsulates threading capabilities of the operating system. Member functions enable MFC applications to create and manipulate threads.
  1. User-Interface Classes
Typically, the user-interface classes encompass the elements of a Windows-based application that are visible to the user. These include windows, dialog boxes, menus, and controls. The user-interface classes also encapsulate the Windows device context and graphics device interface (GDI) drawing objects.

To see an illustration that shows the user-interface classes within the MFC object hierarchy, click this icon.



Some of the user-interface classes include CWnd, CView, CGdiObject, and CMenu.

CWnd

CWnd is the base class for all MFC windows, and defines the basic functionality of a window and a window's default response to most messages. CWnd is sometimes used directly to derive classes, but more often, classes are derived from the other built-in classes that are derived from CWnd. The following table shows some of the classes that are derived from CWnd.

Class Description

CFrameWnd Models the behavior of a single document interface (SDI) frame window.

CControlBar Serves as the base class for toolbars, status bars, and other controls.

CDialog Encapsulates the functionality of dialog boxes.

CButton, CListBox, CScrollBar, and so forth Corresponds to controls such as buttons, list boxes, and scroll bars.

CView

Most applications provide the user with one or more views of the underlying data. For example, Microsoft Excel provides a worksheet view and a graphic view of the same data. The CView class, derived from CWnd, is the base class that provides the visible representation in a document/view application.

CGdiObject

The graphics device interface (GDI) portion of Windows is designed to provide applications with a device-independent and feature-rich set of drawing capabilities. The GDI contains a number of "objects" that are used to display output, such as brushes, pens, and fonts. CGdiObject is a wrapper class that provides MFC applications with the ability to create and use these objects.

CMenu

Menus are one of the main methods by which users interact with applications. An application's menu items not only give the user the ability to invoke an action, but they also provide information to the user about the state of the application and what options are currently available.

The CMenu class provides an object-oriented interface to menus. Through the CMenu class interface, the application can dynamically control its menus at run time.


  1. General-Purpose Classes
MFC includes a number of general-purpose classes that do not encapsulate the Win32 API. These classes represent simple data types such as points and rectangles and more complex data types such as strings.

To see an illustration that shows the general-purpose classes within the MFC CObject hierarchy, click this icon.



The following table lists some commonly used general-purposes classes and describes the tasks they perform.

Class Task

CFile File I/O

CString Managing string variables

CException Exception handling

CByteArray, CIntArray, CStringArray, CStringList, CObList Working with data structures such as arrays and linked lists

CPoint, CSize, CRect, CTime, CTimeSpan Miscellaneous


  1. ActiveX Classes
MFC provides classes that simplify the process of adding ActiveX capabilities to your applications and significantly reduce development time. The ActiveX classes work with the other application framework classes to provide easy access to the ActiveX API. Using the ActiveX classes, you can:

® Create ActiveX controls and ActiveX control containers.

® Use Automation to control one program with another.

® Create compound documents, which enable users to create and edit documents containing various types of data, including text, graphics, spreadsheets, and sound. These various data objects can be created by different applications.

® Create OLE objects that can be embedded in compound documents.

® Use drag-and-drop to copy data between applications.

Note This course does not cover creating ActiveX components. For information about how to create and modify ActiveX components using MFC, see Mastering MFC Development Using Visual C++ 5, listed in the Library.

To see an illustration that shows the ActiveX and OLE classes within the MFC object hierarchy, click this icon.



ActiveX classes can be divided into the categories shown in the following table.

Category Common classes

ActiveX control classes COleControlModule, COleControl, CConnectionPoint, CPictureHolder, CFontHolder, COlePropertyPage, CPropExchange, CMonikerFile, CAsyncMonikerFile, CDataPathProperty, CCachedDataPathProperty, COleCmdUI, COleSafeArray

Active Document classes CDocObjectServer, CDocObjectServerItem

ActiveX-related classes COleObjectFactory, COleMessageFilter, COleStreamFile, CRectTracker

Automation classes COleDispatchDriver, COleDispatchException

Container classes COleDocument, COleLinkingDoc, CDocItem, COleClientItem

OLE server classes COleServerDoc

OLE drag-and-drop and data transfer classes COleDropSource, COleDataSource, COleDropTarget,

COleDataObject

OLE common dialog classes COleDialog, COleInsertDialog, COlePasteSpecialDialog, COleLinksDialog, COleChangeIconDialog, COleConvertDialog, COlePropertiesDialog, COleUpdateDialog, COleChangeSourceDialog, COleBusyDialog


  1. Database Classes
Accessing data and connecting to databases are two of the most common Windows environment programming tasks. MFC provides classes that enable operations on databases through Open Database Connectivity (ODBC) and the data access objects (DAO).

To see an illustration that shows the database classes within the MFC object hierarchy, click this icon.



Note This course does not cover creating database applications. For information about how to create database applications using MFC, see Mastering MFC Development Using Visual C++ 5 listed in the Library.

CDatabase and CDaoDatabase

A CDatabase or CDaoDatabase object represents a connection to a data source through which you can operate on the data source. A data source is a specific instance of data that is hosted by a database.

CRecordset and CDaoRecordset

A CRecordset or CDaoRecordset object represents a set of records selected from a data source. Known as recordsets, CRecordset and CDaoRecordset objects are available in two forms: dynasets and snapshots. A dynaset is a dynamic recordset that stays synchronized with updates by other users. A snapshot is a static recordset that reflects the state of the database at the time the recordset is requested. CDaoRecordset also can directly represent a table in a database.

®Internet Classes

Creating applications that interact with the Internet, intranets, or both, is becoming a major focus for developers. MFC includes the WinInet APIs and the Internet Server API (ISAPI), which provide classes for client-side and server-side applications, respectively.

To see an illustration that shows the Internet classes within the MFC object hierarchy, click this icon.



Note This course does not cover creating Internet applications. For information about creating Internet applications using MFC, see Mastering MFC Development Using Visual C++ 5, listed in the Library.

Client-Side Classes

This table describes MFC Internet classes related to the client-side applications.

Class Description

CInternetSession Creates and initializes one or more simultaneous Internet sessions. Specific application-level services can be established by using the member functions GetHttpConnection, GetFtpConnection, and GetGopherConnection.

CHttpConnection Manages an application's connection to an HTTP server.

CFtpConnection Manages an application's FTP connection and provides for member functions that enable you to create applications that explore remote directories, retrieve files, and otherwise manage remote file systems.

CGopherConnection Manages an application's Gopher connection and enables the application to search for and retrieve various types of documents.

CFileFind This class, the base class for CFtpFileFind and CGopherFileFind, supports searching, locating, and returning information about found files. All these classes support wildcard searches.

Server-Side Classes
This table describes MFC Internet classes related to the server-side applications.

Class Description

CHttpServer Use this class to create and manage a server extension DLL, also known as an Internet server application (ISA). ISAs are used to extend an Internet server's capabilities.

CHttpServerContext Used by CHttpServer to encapsulate the instance of a single client-side request.

CHttpFilter Use this class to create a DLL to filter incoming and outgoing client data.

CHttpFilterContext Used by CHttpFilter to encapsulate the instance of a single notification for a single client.

CHtmlStream Encapsulates an HTML data buffer to be used by a CHttpServer to respond to the client.

® Global Afx Functions

MFC provides some functions that are not members of classes. These are global functions whose names begin with Afx. Class member functions can only be called in the context of the class to which they belong, but Afx functions are available to all classes and functions in an application. The following table lists some commonly used Afx functions and describes the tasks they perform.

Function Description

AfxAbort() Unconditionally terminates an application.

AfxMessageBox() Displays a Windows message box.
AfxGetApp() Returns a pointer to the project's CWinApp object.
AfxGetAppName() Returns a pointer to a string containing the application name.
AfxGetMainWnd() Returns a pointer to the main frame window.
AfxGetInstanceHandle() Returns a handle (HINSTANCE) to the current instance of the application.

Documents, Views, and the Application Framework

MFC provides an application framework on which you can build applications for Windows. The framework provides a set of starter files for an application and supplies standard user-interface features that you can implement in your application. You provide the rest of the code, specifically those things needed for your application.

Your work with the framework is based largely on a few major MFC classes and several Visual C++ tools. Some of the classes encapsulate the Win32 API. Other classes encapsulate application objects such as documents, views, and the application itself. Still others encapsulate ActiveX, database, and Internet features.

This section presents an overview of the application framework, the major objects that make up your application and how they are created, and a brief look at how messages are handled in the MFC environment. This section includes the following topics:



  1. Document/View Architecture
The MFC document/view architecture provides a single, consistent way of coordinating application data, referred to as a document, and views of that data. A document is a data object with which the user interacts in an editing session. A view is a window object through which the user interacts with the document. This topic provides a broad overview of document/view architecture. For detailed information, see Chapter 4: Creating MFC Applications.

Document/view architecture is important because applications that use documents and views derive the greatest benefit from the application framework. You can write MFC applications without using documents and views; however, to get the most out of the framework and take advantage of advanced MFC features, you must use document/view architecture. For more information about non-document/view architecture, see Writing Applications in Non-Document/View in Chapter 4: Creating MFC Applications.

To see an illustration that shows how a single set of data can be viewed or displayed in more than one way by a document/view application, click this icon.




As shown in the previous illustration, Microsoft Graph is a good example of an application that separates the data from the interface. The user can select a set of values from the data in a spreadsheet view, and then display the same information as a bar chart or a three-dimensional bar chart. If the user changes values or changes the range of data that is selected in the spreadsheet view, the chart view is updated. The application can also present two views of the same type; changes made in one view would also appear in the other.

To see a demonstration that shows how the Microsoft Excel application uses document/view architecture, click this icon.

SDI and MDI Applications

MFC makes it easy to work with both single document interface (SDI) and multiple document interface (MDI) applications.

SDI applications allow only one document frame window at a time. MDI applications allow multiple document frame windows to be open in the same instance of an application. An MDI application has a window within which the user can open multiple MDI child windows that are themselves frame windows, each containing a separate document. In some applications, the child windows can be of different types, such as chart windows and spreadsheet windows. In that case, the menu bar can change as MDI child windows of different types are activated.

Note Under Windows 95, applications will increasingly be SDI as the operating system moves toward a "document-centered" view. This course teaches you how to create SDI applications using MFC. For information about how to create MDI applications, see Mastering MFC Development Using Visual C++ 5 listed in the Library.
  1. Objects in an SDI Application
Document/view architecture provides the framework for documents and views in the base classes CDocument and CView. The CWinApp, CFrameWnd, and CDocTemplate classes work in conjunction with CDocument and CView to ensure that all the pieces of the application fit together. You will learn more about how to implement these classes in an application in later chapters.


The following table lists the application objects and related classes in an SDI application and describes the major tasks each object performs.

Object Description

Document Your document class (derived from CDocument) specifies your application's data.

View Your view class (derived from CView) is the user's window to the data. The view class specifies how the user sees your document's data and interacts with it.

Frame window Views are displayed inside document frame windows using the CFrameWnd

class. In an SDI application, the document frame window is also the main frame window for the application.

Document template A document template orchestrates the creation of documents, views, and frame windows. A particular document-template class (derived from CDocTemplate) creates and manages all open documents of one type. Use class CSingleDocTemplate for SDI applications.

Application Your application class (derived from CWinApp) controls all of the objects above and specifies the application's behavior such as initialization and cleanup.

In an SDI application, each document template creates and manages one document. The user views and manipulates a document through a view contained inside a frame window. The application objects cooperatively respond to user actions, bound together by commands and other messages. The following illustration shows the relationship between the document/view objects in a running SDI application.

Non-Document/View Architecture

Although most of the discussion about Visual C++ and MFC functionality assumes use of the document/view architecture, this is not a requirement. The benefits associated with document/view architecture also carry with them potentially significant performance and size costs. In some cases, document/view may not be the right choice for your application.

For example, applications that compress files may need only a dialog box that requests file names and displays a progress bar. A main frame window and a view are not needed; document/view architecture would provide little, if any, benefit in this instance. For another example, consider an application that provides a single database recordset to a simple database browser. The document/view architecture could be used, but it may be more effective for the view (the browser) to hold the recordset directly.

Remember that an MFC application consists of a number of objects that you can combine in many ways to create a program solution. Some possible combinations in a non-document/view application include:

® A CWinApp object and a modal dialog box. In such applications, the dialog box is responsible for storing and displaying data.

® A CWinApp object, a main frame (CFrameWnd) window, and a view. In such applications, the view usually is located where any data is stored and displayed.

Regardless of the combination you choose, the non-document/view application usually begins with the override of the CWinApp::InitInstance function. At this point, the main window, either a dialog box or other window, is created.


  1. Messages
Communication between the operating system, applications, and application components is conducted through various types of messages. For example, when creating an instance of an application, the operating system sends a series of messages to the application, which then responds appropriately to initialize itself. Keyboard and mouse activity cause the operating system to generate messages and send them to the proper application. User-interface components, such as command buttons and list boxes, generate messages to their parent windows.

There are many types of messages; two of the most important are standard Windows messages and command messages. The MFC architecture supports Windows messages through the CWnd class and its derived classes, such as CView and CFrameWnd. MFC supports command messages through any of the classes derived from the CCmdTarget class. A command message originates from a menu item, command button, or accelerator key. In Chapter 6: Handling Messages, you will learn how to handle Windows and command messages in MFC applications.

Message Maps

Before you start writing MFC applications, it is important to understand how MFC maps messages to the functions that will handle the messages. The application framework implements the message map data structure, which provides the link between the message ID and the function that will handle the message. Each entry consists of a message-specific macro. Standard Windows messages all have predefined macros containing an implicit ID and handler name. Command message macros contain an explicit ID and handler name.

Below is an example of a message map for the CMyView class with two entries. Note that the base class is included to allow the framework to continue searching for a given handler if one does not exist within this class. Every standard Windows message has a macro of the form ON_WM_xxx, where xxx is the name of the message. A simple convention is used to generate the handler function name. The name of the function starts with "On." This is followed by the name of the message with the "WM_" removed and only the first letter of each word capitalized. In the following example, the handler name would be OnCreate:

BEGIN_MESSAGE_MAP(CMyView, CView)

ON_WM_CREATE()

ON_COMMAND(ID_APPLY_SEQUENCE, OnApplySequence)

END_MESSAGE_MAP()



You can add a message map entry by using ClassWizard or the WizardBar in Developer Studio. Alternatively, you can add the entry manually.


Self-Check Questions

1. Which one of the following statements is true about MFC's relationship to the Win32 API?


A. The current version of MFC does not wrap any of the Windows operating system extensions.

B. MFC represents a high-level encapsulation of the Windows API.

C. A program can easily mix MFC- and API-level calls.

D. MFC completely encapsulates the Windows API, freeing the developer from all SDK dependence.



2. Which one of the following is not a potential benefit of MFC?

A. MFC reduces complexity by providing a higher-level abstraction of Windows.

B. MFC simplifies database programming through the DAO and ODBC classes.

C. A developer needs less knowledge and skill to program with MFC than with the Windows SDK.

D. MFC displays many of the stronger features of the C++ language, including support for object-oriented

techniques, stronger type checking, exception handling, and so on.



3. Which one of the following is a primary function of the application class?

A. It starts the application’s message loop.

B. It forms the primary window for the application.

C. It acts as a binder for the frame, view, and document objects and a set of GUI resources in an application.

D. It contains member functions to enumerate through all the views in an application.



4. Which one of the following is not considered to be one of the main classes that comprise the application framework?

A. CObject

B. CWinApp

C. CView

D. CFrameWnd

Chapter 1: Windows Fundamentals and Architecture

Chapter 1: Windows Fundamentals and Architecture

When you develop Windows-based applications, you can choose from a wide variety of programming environments depending on the requirements of your application. Many developers are choosing the C++ language for developing Windows-based applications because it is object-oriented in nature and provides a simplified approach to dealing with the complexity of Windows and the wide range of application programming interface (API) functions. Using C++, combined with a class library, further simplifies the development process by grouping the API functions into logical units and encapsulating the basic behavior of windows and other objects in reusable classes.


This course focuses on the Microsoft Foundation Class (MFC) Library, the class library created by Microsoft to be used in combination with Visual C++, the Microsoft version of C++. You can use these tools together to develop Windows-based C++ applications.

MFC extends the object-oriented programming model used in Windows-based applications. Since MFC is based on the Windows programming model, you need a basic understanding of Windows architecture before learning how to use the classes in your applications. If you're coming to MFC from a traditional Windows programming background, such as C and the Windows SDK, you're already familiar with these concepts. If you're new to Windows programming, then this chapter is for you.

This chapter provides an overview of the Windows programming architecture and briefly takes you behind the scenes to see how Windows-based applications work.

Objectives

At the end of this chapter, you will be able to:

® Define processes, threads, and multitasking.

® Describe the structure of memory management.

® Explain the purpose of messages and the concept of event-driven programming.

® Describe the minimum components of a simple Windows-based application.

® Explain how an application is initialized and windows are created.

Understanding Windows Architecture: Before you begin writing MFC applications, you should understand several key architectural features of Windows-based applications and the Windows operating system.

This section explains the run-time structure of Windows-based applications. Here you will learn about the differences between applications, processes, and threads of execution. You will also learn about how the Windows operating system manages processes and threads in order to maximize performance.
This section includes the following topics:


  1. Processes
The term "process" and the more common term "application" are sometimes used interchangeably. However, in the Windows environment, there is a distinction between a process and an application.

An application is a static sequence of instructions that makes up an executable file. A process is usually defined as an instance of a running application. A process has its own private address space, contains at least one thread, and owns certain resources, such as files, allocated memory, and pipes.

A process consists of:

® An executable program

® A private address space in memory

® System resources, such as files, pipes, communications ports, and semaphores

® At least one thread, where a thread is a path of execution


  1. The Virtual Memory System
In an operating system where multiple processes are allowed, each process must be protected against corruption by other processes in memory. The Windows operating system is designed to provide this protection.

There are two types of memory in the Windows operating system:
® Physical memory

Consists of the amount of physical RAM.

® Virtual memory

Consists of 4 gigabytes (GB) of addresses, or 232 bytes of addressable memory that is available to your application. This is not 4 GB of actual physical memory. Each application is given 2 GB of addresses while the operating system reserves 2 GB for its own use.

Note In Windows NT, an application may have up to 3 GB of addresses for its own use.

How the Virtual Memory System Works

When an application is started, the following process occurs:

1. The operating system creates a new process. Each process is assigned 2 GB of virtual addresses (not memory) for its own use.

2. The virtual memory manager maps the application code into a location in the application's virtual addresses, and loads currently needed code into physical memory. (The virtual address has no relationship to the location of the application code in physical memory.)

3. If your application uses any dynamic-link libraries, the DLLs are mapped into the process's virtual address space and loaded into physical memory when needed.

4. Space for items such as data and stacks is allocated from physical memory and mapped into the virtual address space.

5. The application begins execution by using the addresses in its virtual address space, and the virtual memory manager maps each memory access to a physical location.

The application never directly accesses physical memory. The virtual memory manager controls all access to physical memory through requests for access by using the virtual addresses.

To see an animation that explains how virtual memory and physical memory work, click this icon.

Benefits of Using a Virtual Memory System

A virtual memory system helps both to ensure robust application execution and to simplify memory management.

As mentioned earlier, one concern about running an application in a multitasking environment is protecting that application's execution from intrusion by other applications. Forcing applications to use virtual memory allows the operating system to provide strict physical memory partitioning between applications. If an application requests private memory space, the operating system will provide a map between that application and physical memory.

Virtual memory also allows applications to view memory as a flat, 2 GB of memory space without having to contend with the physical memory management architecture that is used by the operating system.

Threads and Multitasking

While a process can be thought of as a task that the operating system must perform, such as running a spreadsheet application, a thread represents one of possibly many tasks needed to accomplish the job. For example, controlling the user interface, printing, and calculating the spreadsheet may be tasks of the spreadsheet application that are assigned to individual threads. A thread runs in the address space of its process and uses the resources allocated to its process.

A process can have a single thread, or it can be "multithreaded.” A multithreaded process is useful when a task requires considerable time to process. The task can run within one thread, while another task runs within a separate thread. The threads can be scheduled for execution independently on the processor, which allows both operations to appear to occur at the same time. The benefit to the user is that work can continue while the first thread completes its task. Another benefit is that on a multiprocessor system running Windows NT, two or more threads can run concurrently, one on each processor.

Multitasking is the ability of an operating system to give the appearance of simultaneous running of multiple threads. The operating system achieves multitasking by allowing each thread to be active for a relatively short amount of time (tens of milliseconds), and then switching to the next scheduled thread. This process, called "context switching," is done by:

1. Running a thread until the thread's time slot is exhausted or until the thread must wait for a resource to become available.

2. Saving the thread's context.

3. Loading another thread's context.

4. Repeating this sequence as long as there are threads waiting to execute.

To see an illustration of context switching in a multitasking operating system, click this icon.




  1. Threads, Messages, and Message Queues
Each thread of execution has its own virtual input queue for processing messages from hardware, from other processes, or from the operating system. These queues operate asynchronously — that is, when one process posts a message to another thread's queue, the posting function returns without having to wait for the other thread to process the message. The thread that has received the message can access and process the message when it is ready.

Of special interest is the handling of keyboard and mouse events. A special system thread, known as the raw input thread (RIT), receives all key and mouse events. Whenever the RIT receives hardware events from the processor, its sole function is to place them on the virtual input queue of the appropriate thread. Thus, under normal circumstances, no application thread need wait for its hardware events.

To see an animation that shows how messages are handled by the system message queue, click this icon.

Event-Driven Programming
Central to understanding how Windows-based applications work is the concept of event-driven programming. To hear an expert in the field describe event-driven programming, click this icon.

The best way to understand event-driven programming is to contrast it with the procedural programming of MS-DOS. Under MS-DOS, users enter command-line parameters in order to control how an application runs. Under Windows, users start the application first, and then Windows waits until users express their choices by selecting items within a graphical user interface (GUI). A Windows-based application thus starts and then waits until the user clicks a button or selects a menu item before anything happens. This is known as event-driven programming.

Anatomy of a Windows-Based Application
Knowing the elements that make up a Windows-based application and how windows communicate information between the application and the user is important to writing effective MFC applications.

In this section, you will learn about the essential components of a Windows-based application and get a brief introduction to how messages are processed in the Windows environment.

This section includes the following topics:

Elements of a Windows-Based Application
The basic elements that make up a Windows-based application include code, user interface resources, and library modules invoked by the application through dynamic linking.


Code

The primary content of any application is executable code. Windows-based applications have two required functions. One, called WinMain, provides an entry point for the operating system. The second function, a window procedure, is needed to handle messages from the operating system.

User Interface Resources

Many application-defined elements of an application's graphical user interface (GUI), such as menus and dialog boxes, are stored as templates and references in a special read-only section of the corresponding executable or DLL file. When required, Windows reads from this resource section and constructs the GUI element dynamically.

Note that while resources are primarily used to store information about the GUI elements of an application, any read-only information could be placed in the resource section. The advantage is that resources are shipped as part of the executable file, minimizing the need for additional files to be shipped with an application.

The following table lists the common Win32 resources.

Resource type Description


Accelerator Stores the keystrokes and their command associations.

Bitmap Contains a graphical image in Windows-compatible format.

Dialog box Details the controls, layouts, and attributes for dialog boxes.

Icon Stores special sets of bitmaps for icons.

Menu Details the text and layout for menus and their items.

String table Stores character strings and an associated ID value.

Toolbar Details toolbar layouts and contains references to the special bitmaps that are used to draw the button faces.

Version information Maintains program status information, such as program name, author, copyright data, version number, and so on.

Cursor Contains the special bitmap that is used to draw the cursor.



Library Modules

Microsoft Windows, along with most modern operating systems, supports dynamic linking, a method for invoking library modules at run time. A library module is a binary file that contains the executable library routines. A library module that can be loaded in this manner is called a dynamic-link library, or DLL.


  1. ow an Application Is Started


For a Windows-based application to get up and running, several events must occur first. When a user starts an application, the following events occur in sequence:

1. The operating system creates a new process and an initial thread.

2. The application code is loaded into memory.

3. Dynamic-link libraries also are loaded into memory, if your application uses them.

4. Space for items, such as data and stacks, is allocated from physical memory and mapped into the virtual address space.

5. The application begins execution.


  1. How a Window Processes Messages
Most Windows users are familiar with the term “window” and the visual elements that characterize applications. From a developer's standpoint, windows take on a new meaning. In a Windows-based application, windows are the primary method of communicating information from the application to the user. Similarly, the user uses the window to communicate with the application, thus achieving the desired behavior to accomplish a task.

The following steps explain how a Windows-based application prepares itself to receive messages that are sent to it by the system queue.

1. When a Windows-based application is started, the operating system connects with the application at a predefined entry point. This entry point is defined in the WinMain function, a required function in all Windows-based applications.

2. The application then creates one or more windows. Each window contains a window procedure that is responsible for determining what the window displays and how the window responds to user input.

3. A section of code called a message loop retrieves messages from the message queue and gives them back to Windows to send to the appropriate window procedure. This gives the application a chance to preprocess messages before they are sent to a window.

The code to implement each of the steps in this process is presented in a sample application and described in detail in Analyzing a Simple Windows-Based Application later in this chapter.

The following illustration shows how messages passed from the system queue are processed by the application.


Analyzing a Simple Windows-Based Application

In this section, you will examine the source code for a simple SDK-level Windows-based application. Since MFC applications are based on the Windows programming model, this will help you better understand how an MFC application is initialized, how windows get created, and how messages are handled.

All Windows-based applications must contain two functions, at a minimum, to provide functionality for the application as follows:

® The WinMain function

This function defines the initial entry point to the application from the operating system. It is also used to create the initial window and to start a message pump.

® A window procedure function

This function processes all messages sent from the operating system to a window. Every window, no matter how simple or how complex, has an associated window procedure.

Let's look at a simple application so you can see what is needed to create a minimal Windows-based application. This sample application simply displays a window and draws "Hello, world!" in the center of its viewing area. To see the complete code for the sample application, click this icon.

// Standard Windows header file.

#include <windows.h>// Forward declaration for the message handler.

LRESULT CALLBACK MyWndProc(HWND, UINT, WPARAM, LPARAM);

// WinMain: required for all Windows applications.

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpszCmdLine, int nCmdShow)
{

char szApplicationName[] = "Simple Hello App";

HWND hwnd;
MSG msg;

// Window class data structure

WNDCLASS wc;

wc.style = CS_HREDRAW | CS_VREDRAW; // style: causes repaint when resizing

wc.lpfnWndProc = (WNDPROC) MyWndProc; // the window procedure
wc.cbClsExtra = 0; // number of extra bytes following the class structure
wc.cbWndExtra = 0; // number of extra bytes following the window instance
wc.hInstance = hInstance; // this instance that the window procedure is within
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); // the class icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // the class cursor
wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);// background brush
wc.lpszMenuName = NULL; // the menu resource name
wc.lpszClassName = szApplicationName; // the app name

// Register the window.

RegisterClass(&wc);

// Now create the window.

hwnd = CreateWindow(
szApplicationName, // registered class name
szApplicationName, // window name
WS_OVERLAPPEDWINDOW, // window style
CW_USEDEFAULT, // x position of window
CW_USEDEFAULT, // y position of window
CW_USEDEFAULT, // width of window
CW_USEDEFAULT, // height of window
HWND_DESKTOP, // handle to parent window
NULL, // handle to menu identifier
hInstance, // handle to application instance
NULL // pointer to window-creation data
);

// Display the window.

ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);

// Pump messages until a quit message is received.

while(GetMessage(&msg, NULL, 0,0))
{
TranslateMessage(&msg); // translates virtual-key messages into character messages
DispatchMessage(&msg); // dispatches a message to the window procedure
}

return msg.wParam;

}

// This function is called by Windows to handle messages for this application.

LRESULT CALLBACK MyWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
LPCTSTR text= "Hello, world!";
switch(message)
{
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);

// Draw the text approximately in the middle of the window.

// (The upper left corner of the string will be centered.)
RECT rect;
GetClientRect(hwnd, &rect);
TextOut(hdc, (rect.right-rect.left)/2, (rect.bottom-rect.top)/2, text, strlen(text));

EndPaint(hwnd, &ps);

return 0;

// Handle the Exit situation

case WM_DESTROY:
PostQuitMessage(0);
return 0;

}

// Call the default handler so that all messages are processed.
return DefWindowProc(hwnd, message, wParam, lParam);
}

Note To run this application, create a new Win32 application, and then add a new .cpp file. Cut and paste this code into it, and then build and run the application.

In this section, we will focus on the segments of code in the sample application that pertain to all Windows-based applications. This section includes the following topics:

The WinMain Function

Every Windows-based application must contain a WinMain function. WinMain is required to perform three basic tasks:

1. Register the class of the window with the operating system.

2. Create the window in memory and initialize its attributes so it can be displayed.

3. Create a message loop that checks to see if there are any messages for the window in its message queue.

Each of these tasks is described in detail below.

Registering the Window Class

The entry point for every window application is the WinMain function. The WinMain function creates and initializes a WNDCLASS data structure, which is then registered by calling the API function RegisterClass. This data structure defines characteristics of a window, such as the address of the message handler, the window's background color, the application icon, and the default cursor.

// Window structure

WNDCLASS wc;

wc.style = CS_HREDRAW | CS_VREDRAW; // style: causes repaint when resizing

wc.lpfnWndProc = (WNDPROC) MyWndProc; // the window procedure

wc.cbClsExtra = 0; // number of extra bytes following the class structure

wc.cbWndExtra = 0; // number of extra bytes following the window instance

wc.hInstance = hInstance; // this instance that the window procedure is within

wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); // the class icon

wc.hCursor = LoadCursor(NULL, IDC_ARROW); // the class cursor

wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1); // background brush

wc.lpszMenuName = NULL; // the menu resource name

wc.lpszClassName = szApplicationName; // the app name

// Register the window.

RegisterClass(&wc);

Creating and Displaying the Window

Once the window class is registered, WinMain calls the CreateWindow function to create the application's window. CreateWindow further defines the type of window by passing information about its name, location, and size.

// Now create the window.

hwnd = CreateWindow(

szApplicationName, // registered class name

szApplicationName, // window name

WS_OVERLAPPEDWINDOW, // window style

CW_USEDEFAULT, // x position of window

CW_USEDEFAULT, // y position of window

CW_USEDEFAULT, // width of window

CW_USEDEFAULT, // height of window

HWND_DESKTOP, // handle to parent window

NULL, // handle to menu identifier

hInstance, // handle to application instance

NULL // pointer to window-creation data

);

The window is then made visible by calling the following functions:

// Display the window.

ShowWindow(hwnd, nCmdShow);

UpdateWindow(hwnd);

Processing Messages

Finally, the message loop retrieves and dispatches messages. This is accomplished by using a while loop.

// Pump messages until a quit message is received.

while(GetMessage(&msg, NULL, 0,0))

{

TranslateMessage(&msg); // translates virtual-key messages into character messages

DispatchMessage(&msg); // dispatches a message to the window procedure

}

The GetMessage function retrieves a message from the message queue and places it in the MSG data structure. The TranslateMessage function translates virtual-key messages into character messages. The DispatchMessage function dispatches a message to a window procedure.

On receiving a WM_QUIT message, the GetMessage function returns 0, the WinMain function ends, and the program terminates.

The Window Procedure

One of the primary purposes of registering a window class is to associate a window to a "window procedure." The window procedure determines what the window displays in its client area and how the window responds to user input. Window procedures can handle messages with code added by the developer, or by passing messages along to the default window procedure.

The default window procedure, DefWindowProc, is provided by the Windows system and implements many common Win32-based application behaviors, such as minimizing, restoring, or maximizing a window, displaying menu resources, and so on. If DefWindowProc does not handle a message, it is ignored.

In the sample program, the window procedure is called MyWndProc. A window procedure can have any name (as long as it doesn't conflict with some other name, of course). A Windows-based application can contain more than one window procedure, each with a different name.

Typically, you use a switch and case statement to handle the message as shown in the following code. The MyWndProc function handles two messages, WM_PAINT and WM_DESTROY. The DefWindowProc window procedure must be called to handle all other messages.

// This function is called by Windows to handle messages for this application.

LRESULT CALLBACK MyWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)

{

PAINTSTRUCT ps;

HDC hdc;
LPCTSTR text= "Hello, world!";

switch(message)
{
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);

// Draw the text approximately in the middle of the window.

// (The upper left corner of the string will be centered.)
RECT rect;
GetClientRect(hwnd, &rect);
TextOut(hdc, (rect.right-rect.left)/2, (rect.bottom-rect.top)/2, text, strlen(text));

EndPaint(hwnd, &ps);

return 0;

// Handle the Exit situation

case WM_DESTROY:
PostQuitMessage(0);
return 0;

}

// Call the default handler so that all messages are processed.
return DefWindowProc(hwnd, message, wParam, lParam);
}

Windows Functions and MFC

Since MFC applications are based on the Windows development model, they depend on the functionality provided by the WinMain function and window procedure functions.
The WinMain Function and MFC
As with all Windows-based programs, MFC applications have a WinMain function. In an MFC application, however, you don't write WinMain. It is supplied by the framework and is called when the application starts up. For more information, see Classes in a Minimal MFC Application in Chapter 4.

The Window Procedure and MFC

MFC has an internal messaging system that handles most messages generated by the classes. However, when a message cannot be handled within MFC, the application relies on the default window procedure, DefWindowProc, to handle messages. For more information, see How MFC Processes Messages in Chapter 6.

Self-Check Questions

1. Which of the following statements is true about Windows architecture?


d A. A process can have zero or more threads.

d B. Each process is allocated 1 MB of virtual memory on startup, and additional 64K blocks as required.

d C. Under Win32 multitasking, the highest priority thread will always have unconditional access to the

processor.

d D. Keyboard and mouse events are handled asynchronously.


2. Which of the following is not a standard Win32 GUI resource type?

d A. Version Information

d B. Device Context

d C. Accelerator

d D. Cursor


3. Which of the following is a required function for all Windows-based applications?

d A. WinMain

d B. WndMgr

dd C. MyWndProc

d D. GetMenu


4. When WinMain calls the API RegisterClass function, the following data structure is registered:

d A. MSG

d B. WNDCLASS

d C. PAINTSTRUCT

ddd D. RECT

Telecommunications and Networks









Untitled Document

























































































































































































































































































































































































































































































































































































Chapter Outline

Key Terms

Study Questions

The Evolution of Networking

telecommunications

What factors have encouraged the growth of networking?

Data Transmission Characteristics

 

The transmission of data over networks is characterized by what three factors?

Bandwidth

bandwidth


bits per second (bps)


broadband medium


narrowband medium

Explain the difference between a broadband medium and a narrowband medium, and provide examples of each.

Analog and Digital Transmission

analog signal


frequency range


pitch


modem


modulation


demodulation


dial-up modem


internal modem


external modem


Personal Computer Memory Card International Association (PCMCIA) modem

What applications are analog signals used for?


What system do computers use to transform data into digital signals?


What are two major functions of modems?


Explain the difference between an internal modem and an external modem.


What is the advantage of each type of modem?

Parallel and Serial Transmission

parity bit


serial transmission


parallel transmission

Explain the difference between a parallel and serial port.


What is the advantage of parallel transmission?


What are two common connectors for serial ports?

Communications Media

communications medium

Communications media are classified into what two broad categories?

Wired Communications Media

 

Why would a user use wired communication media instead of wireless?

Twisted-Pair Cable

twisted-pair cable

What are the advantages of twisted-pair cable?

Coaxial Cable

coaxial cable


cable modem

What are the advantages of coaxial cable?


What device must be installed to use a cable modem?

Fiber-Optic Cable

fiber-optic cable

What are five advantages of fiber-optic cables?


What is the most important advantage of fiber-optic cables?

Integrated Services Digital


Network (ISDN)Lines

Integrated Services Digital Network (ISDN) line

What device is required for the use of an ISDN line?

Digital Subscriber Line (DSL)

Digital Subscriber Line (DSL)

What advantage does a DSL offer users who are connected to the Internet?

T Lines

T line


T1 line


T3 line

What is a major disadvantage of T lines?


What are two popular types of T lines?


How does a T3 line differ from a T1 line?

Wireless Communications Media

 

What six types of technology are included under the category of wireless communications media?

Microwave Systems

microwave system

What factor determines the distance between microwave stations?


Where are microwave stations usually located and why?

Satellite Systems

communications satellite


transponder


earth station


geosynchronous orbit

Where are communications satellites positioned?


Explain how a communication satellite functions.


What is an important benefit of satellite systems?


For what applications are satellite systems most appropriate?

Infrared Technology

infrared technology

What are three common uses for infrared technology?

Cellular Technology

cellular technology


cell


wireless service provider (WSP)

How do signals sent by cell phones reach their final destination?


With what mobile devices can wireless modems be used?

Wi-Fi Technology

Wi-Fi (802.11 protocol)


wireless access point


hotspot

What is the most commonly used wireless technology today?


How can home networks take advantage of Wi-Fi technology?

Bluetooth Technology

Bluetooth

What are some common uses of Bluetooth technology?

Network Classifications

 

Into what three categories are networks classified?

Networks Classified by Architecture

network architecture

What are the two major architectural designs for networks?

Client/Server Architecture

client/server architecture


client


server

What are the proposes of a server?


What is a major advantage of a client/server?

Peer-to Peer Architecture

peer-to-peer architecture

What are the advantages and disadvantages of peer-to peer architecture?

Networks Classified by Coverage

 

What is the difference between local area networks (LANs) and wide area networks (WANs)?

Local Area Networks (LANs)

local area network (LAN)


file server


print server

What advantages do LANs offer multiple users?

Wide Area Networks (WANs)

wide area network (WAN)


metropolitan area network (MAN)


public access network (PAN)


value added network (VAN)


virtual private network (VPN)

What types of organizations are likely to use WANs?


What are four major types of WANs?


What services are offered by value added networks (VANs)?


What well-know service provider is a VAN?


What factors make VPNs an attractive option?

Networks Classified by Users

 

Networks can be classified into what two groups of users?

Intranets

intranet


firewall

Why is it difficult for unauthorized users to gain access to an intranet?

Extranets

extranet

Why is it difficult for unauthorized users to gain access to an extranet?


Explain how mobile workers can connect with their companies while in the field.

Network Topologies

network topology


node

Explain the difference between network topology and the actual wiring path of a network.


What are the three common network topologies?

Bus Topologies

bus topology


bus


transceiver


terminator

What do messages sent by the transceiver contain?


Explain why problems occur if two or more computers send messages at the same time.


What serious problem may occur if there is a broken connection along the bus?


What type of cables are used by bus topologies?

Star Topologies

star topology (hub-and-spoke topology)

In star topology, what is the function of the hub?


What is the major disadvantage of star topology?

Ring Topologies

ring topology


token

What is a potential drawback of ring topologies?

Hybrid Topologies

hybrid topology

Why would businesses choose to use a hybrid topology?

Physical vs. Logical Topologies

 

Explain the two levels of meaning for the term “typology.”


Explain the difference between bus and ring.

Network Hardware

 

What does setting up a computer network generally require?

Hubs

hub

What is the major function of a hub?

Switches

switch

Why does a network switch render a higher performance than a hub?

Repeaters

repeater (amplifier)

What major advantage does a repeater offer?

Routers

router

What is the purpose of a cable/DSL router?

Gateways

gateway

What two items combine to form a gateway?

Bridges

bridge

What is the major purpose of a bridge?

Network Interface Cards

network interface card (NIC)

What is the most common LAN architecture?


What is necessary for a client computer to communicate with another computer?

Network Software

network operating system (NOS)

What is the most important type of networking software?


What are the major advantages of Netware?

Communications Software and Protocols

 

What are the major applications of communications software?

Communications Utilities Features

 

What three useful features are offered by communications software programs?

Communications Protocols

protocol


Open Systems Interconnection (OSI) Reference Model (OSI model)

What are six communications protocols, and what is the purpose of each protocol?

Directional Protocols

simplex transmission


half-duplex transmission


full-duplex transmission

What are the three possible directions for directional protocols?


Explain the differences between simple transmission, half-duplex transmission, and full-duplex transmission.

Asynchronous and Synchronous Transmission Protocols

asynchronous transmission


start bit


stop bit


synchronous transmission


synch byte

Explain the differences between asynchronous and synchronous transmission protocols.


To communicate with each other, why must computers use the same transmission method?

Local Area Network (LAN) Protocols

Ethernet protocol


token ring protocol

A broken ring protocol is used by which networks?


Explain how a token can carry both an address and a message.

Wide Area Network (WAN) Protocols

Systems Network Architecture (SNA)


polling protocol


Feber Distributed Data Interface (FDDI)

What is a major application of FDDI?

Internet and Web Protocols

Transmission Control Protocol/Internet Protocol (TCP/IP)


Hypertext Transfer Protocol (HTTP)


File Transfer Protocol (FTP)

What is packet switching?


What do the letters HTTP indicate?


What is a URL?


What is an advantage of using FTP?

Electronic Mail Protocols

Simple Mail Transfer Protocol (SMTP)


mail server


Post Office Protocol (POP) server

Explain how electronic mail is sent and received with SMTP and POP.

Wireless Application Protocols

Wireless Application Protocol (WAP)


Internet Protocol (IP)


802.11 protocol


802.11b protocol


802.11a protocol


802.11g protocol


3G

What wireless communication devices allow users to exchange information?


What is the major benefit of wireless LANs?


What is a major disadvantage of IP?


What industry standard is the basis upon which most new wireless devices are being designed and built?


What three variations of the 802.11b protocol are widely used?


Explain the differences between 802.11a and 802.11b.


What is the major advantage of 3G cellular technology?







C++ note









Untitled Document







What do you mean by procedural programming?


Conventional programming using high level languages such as COBOL, C, and FORTAN is known as procedure-oriented programming. Procedural programming employs top down programming approach where a program is viewed as a sequence of task to be performed. A number of functions are written to implement these tasks.


Characteristics of procedural programming language


Emphasis is on doing things.


What do you mean by virtual destructor?


                Just like ordinary virtual functions destructors can also be declared as virtual, whereas constructor cannot be Virtual. When a derived object pointed is deleted, destructors of all its base classes as well as destructor of derived classes are involved if we declare base class pointer as virtual.


But if the destructor in base class is non-virtual then only the destructor of the base class is invoked when the base class pointer pointing to the derived class object is deleted.



//Code of virtual destructor


#include<iostream.h>


#include<string.h>


class parent


{


                protected:


                                char*name;


                public:


                                parent (char*x)


                                {


                                                name=new char[strlen(x)+1];


                                                strcpy(name x);


                                }


                                virtual void show()


                                {


                                                cout<<"parents name:"<<name;


                                }


                                virtual ~parent()


                                {


                                                delete name;


                                                cout<<"parent destroyed"<<endl;


                                }


};


class child:public parent


{


                private:


                                char*name;


                public:


                                child(char*x1,char x2):parent(x1)


                                {


                                                name=new char[strlen(x2)+1];


                                                strcpy(name,x2);


                                }


                                void show()


                                {


                                                cout<<endl<<"childs name:"<<name;


                                }


                                ~child()


                                {


                                                delete name;


                                                cout<<endl<<"child destroyed";


                                }


};


void main()


{


                parent *p1;


                p1=new parent("parent");


                p1->show();


                delete p1;


                p1=new child (parent from child class:."child");


                p1->parent::show();


                delete p1;


                getch();


}


Output


Parent name: parent


Parent destroyed


Child name: child


Parent name: parent from child class


Child destroyed


Parent destroyed



If we remove virtual keyword in the definition of destructor of base class, the second last output line (“child destroyed”) is not obtained virtual function used in following situation:


It is used when one class needs to delete object of derived class that are addresses by the base class pointer and invoked a base class destructor to release resources allocated to it.


When delete operation is performed on an object by a pointer or reference the program will first call the object destructor instead of the destructor associated with the pointer or reference  type if the destructor is defined as virtual.



“this” pointer



C++ uses a unique keyword called ‘this’ to represent an object that invokes a member function


This is a pointer that points to the object for which this function was called.


-for e.g. the function call A.max() will set the pointer this to the address of the object A


This unique pointer is automatically passed to a member function when it is called. The pointer ‘this ’ acts as an implicit argument to call the member functions


This pointer refers to an object that currently invokes a member functions


Syntax:


class  test


{


                Int data;


                public:


                                func(){..;}


                                func()


                                {


                                                this->data;


                                                this->func();


                                }


};


Complex add(complex c2)


{


                Complex t;


                t.real=real+c2.real;


                t.imag=imag+c2.imag;


                return *this;


}


Therefore, this pointer can be used to return objects


For e.g.


#include<iostream.h>


Class person


{


                Int age;


                Public:


                                person(int a)


                                {age=a;}


                                Void disp;ay()


                                {Cout<<age;}


                                Person greater(person&);


};


Person person::greater(person &x)


{


                If(age,x.age)


                                return x;


                else


                                return *this;


}


void main()


{


                person per(15), per(13);


                person p=per.greater(pet);


cout <<”the greater age is :”;


p.display();


}


Output


The greater age is:15



 



TEMPLATES


Templates are one of the features added in C++ recently. It is a new concept which enable is to define generic classes and functions and thus provides supports for generic programming and provides flexible


Generic programming is an approach where generic types are used as parameters in algorithms so that they work for variety of suitable data-types and data structure.


A template can be used to create a family of classes or functions. For e.g.: a class template for an array class would enable us to create array of various data-types such ass int array and float array etc.


A template can be considered as a kind of macro when ana object of a specific type is defined for actual use, the template definition for that class is substituted with the required data type. Since a template is defined with a parameter that would be replaced by specific data type at the time of actual use of class or function, the templates are sometime also called vparameterized classes or function.


Class templates


The general format of a class template is:


Template<class T>


Class classname


{


                …………


                //class member specification


                //with anonymous type T


                //when even appropriate


                ……….


};


The syntax for defining an object of a template class is:


classname<type>objectname(arg_list);



#include<>m.h


Const size=3;


template<class t>


class vector


{


t *v;       //type t vector


public:


vector()


{


                v=new T[size];


for(int i=0;i<size;i++)


                v[i]=0;


}


vector(T*a)


{


                for(int i=0;i<size;i++)


                v[i]=a[i];


}


T operator *(vector &y)


{


                T sum=0;


                for(in i=0;i<size;i++)


                                Sum+=this->v[i]*y.v[i];


                return sum;


}


};


Void main()


{


                int x[3]={1,2,3};


                int y[3]={4,5,6};


vector <int> v1;


vector<int> v2;


v1=x;


v2=y;


int R=v1*v2;


cout<<”R=”<<R<<endl;


float x1[3]={1.1, 2.2,3.3};


float x2[3]={4.4,5.5,6.6};


vector<float> v3;


vector<float>v4;


v3=x1;


v4=x2;


float R1=v3*v4;


cout<<”R1=”<<R1;


}



Class template with multiple parameters:



Template <class T1, class T2>


Class classname


{


                -------------------


                --------------------// body of class


}







DOMAIN NAME
1. Internet domain names are easier to remember than IP addresses.
2. An important purpose of domain names is to provide easily recognizable and
memorial names to numerically addressed Internet resources. This
abstraction allows any resource (e.g., website) to be moved to a different
physical location in the address topology of the network, globally or locally
in an intranet. Such a move usually requires changing the IP address of a
resource and the corresponding translation of this IP address to and from its
domain name.
A domain name is an identification label to define realms of administrative
autonomy, authority, or control in the Internet, based on the Domain Name
System (DNS).
Domain names are also used as simple identification labels to indicate
ownership or control of a resource
Domain name appear as a component in Uniform Resource Locators (URLs)
for Internet resources such as web sites.
For Example:
URL: http://www.example.net/index.html
Domain name: www.example.net
Registered domain name: example.net
HIERARCHY OF DOMAIN NAME:
There is no limitation of sub-domain level or domain hierarchy.
Top-level domains
Every domain name ends in a top-level domain (TLD) or first-level domain
name, which is always either one of a small list of generic names (three or
more characters), or a two-character territory code.
Prominent examples are the top-level Internet domains .com, .net and .org.
Second-level and lower level domains
Below the top-level domains in the domain name hierarchy are the
second-level domain (SLD) names. These are the names directly to the
left of .com, .net, and the other top-level domains.
Next are third-level domains, which are written immediately to the left of
a second-level domain. There can be fourth- and fifth-level domains, and
so on, with virtually no limitation.
Second-level (or lower-level) domain names are often created based on
the name of a company, product or service.
DOMAIN NAME SYSTEM
Domain Name System (DNS) is a hierarchical naming system for
computers, services, or any resource participating in the Internet.
It translates domain names meaningful to humans into the numerical (binary)
identifiers associated with networking equipment for the purpose of locating
and addressing these devices world-wide.
The Domain Name System makes it possible to assign domain names to
groups of Internet users in a meaningful way, independent of each user's
physical location. Because of this, World Wide Web (WWW) hyperlinks and

Internet contact information can remain consistent and constant even if the
current Internet routing arrangements.
The Domain Name System distributes the responsibility of assigning domain
names and mapping those names to IP addresses by designating authoritative
name servers for each domain.
WEB SERVER
1. A computer program that is responsible for accepting HTTP requests from
clients, and serving them HTTP responses along with optional data contents,
which usually are web pages such as HTML documents and linked objects
(images, etc.).
Vendor Product Web Sites Hosted Percent
Apache Apache 96,531,033 52.05%
Microsoft IIS 61,023,474 32.90%
Google GWS 9,864,303 5.32%
nginx nginx 3,462,551 1.87%
lighttpd lighttpd 2,989,416 1.61%
Oversee Oversee 1,847,039 1.00%
Others - 9,756,650 5.26%
Total - 185,474,466 100.00%
ISSUES OF DOMAIN NAME REGISTRATION
 Check the domain name first, whether domain name is valid or not.
 Domain name cannot register if it was already reserved.
 The availability of the domain name can be checked in whois.com,
whois.net, etc. if domain name is not reserved or available then we go for
registration.
 An end-user cannot directly register and manage their domain name
information with ICANN. A designated registrar must be chosen.
 When a registrar registers a .com domain name for the end-user, it must
pay a maximum annual fee of US$6.86 to VeriSign and a US$0.20
administration fee to ICANN. VeriSign is the registry manager for .com
gTLD.
 Most domain registrars price their services and products to address both the
annual fees and the administration fees that must be paid to ICANN.
 The maximum period of registration of a domain name is generally 10
years.

Monday, November 16, 2009

Nepal Tourist Photoed

CLICK THE LINK AND GET THE GALLERY

NEPAL TOURIST LINK


CLICK IN THE PICTURE AND GET THE REAL VIEW AND GALLERY


Mount Everest, Nepal, by celia chang Mount Everest, Nepal, with Nuptse Mount Everest, Nepal, from Kala Patthar Mount Everest, Nepal, with panorama of Himalayas Mount Everest, Nepal, with prayer flags mount Everest Photo Gallery, Sagarmatha screen saver Pashupati Temple Address one of the holiest place of hindu Nepalese Hindu women perform rituals for the Hindu god Lord Shiva, the god of destruction, at the Pashupati temple in Kathmandu wallpapers of pashu pati nath screensavers of pashupati nath historical place of nepal