Wednesday, February 16, 2011

Cricket World Cup 2011-- Youth Support for India....


सही विचार हैं.... आप के श्रीमान !

चिंता छोड़ो ... जीयो जीवन अपार
परीक्षा तोउ आती हर साल...

वर्ल्ड कप ना आएगा ... अगले साल......
वो कोई  IPL  तोउ नहीं ... जो आये हर बार......

जीवन एक परीक्षा हैं // हर पल ..एक इम्तिहान 
चिंता छोड़ो ... जीयो जीवन अपार
परीक्षा तोउ आती हर साल...

देश हमारा आच्हा खेले ..
जीत वर्ल्ड कप ले आये .."भारत माँ " के लाल
ये hee करते हैं हम दुआ .. और हैं मन  मैं हर-दम ध्यान ...

चिंता छोड़ो ... जीयो जीवन अपार

परीक्षा तोउ आती हर साल...

चार साल न होगा इन्तजार ......
हिंदुस्तान को जीताना हैं  इसी बार....
परीक्षा दे लेंगी अगले साल...
 
चिंता छोड़ो ... जीयो जीवन अपार
परीक्षा तोउ आती हर साल...

वो देखो ....
सचिन लगाये रनों के अम्बार ....
विश्व रेकॉर्ड्स की लगी झड़ी अपार...

चिंता छोड़ो ... जीयो जीवन अपार
परीक्षा तोउ आती हर साल...

--- कवी नीर





Monday, February 14, 2011

Setting up the Tab Order in MFC

Dialog boxes Controls get the focus in a specific order when the user hits the TAB key.


In VC++6 this order is decided through the interface (Dialog resource editor / Layout / Tab order - or Control-D).

In VC++.NET there are two new methods to access, set and change Tab order: Control .TapStop(boolean) and TabIndex(int).

- TabStop (there_is_a_tab_stop)

- TabIndex (index_of_tab_stop_the_lower_the_nearer)


Sunday, February 13, 2011

Amazon Customer Care Phone number

Amazon Customer Care Phone number
800‑201‑7575.

Algorithm to check the cross of the matrix

Algorithm to check the cross of the matrix using
where  m_matrix is an object of the IVSFlexGrid wrapper.
for (int i = 2; i < pGrid->GetRows(); ++i)
{
   if ( dLamount[i] > 0 && dHamount[i-1] > 0 )
   {
     double dAmountDifference = 0.0 ;
     damountDifference = dLamount[i] - dHamount[i-1];

      if ( damountDifference > 1 )
     {
        CString strMessage;
         strMessage.Format("Difference in the amount", damountDifference );

      if (IDYES == ::MessageBox(GetSafeHwnd(), strMessage, "", MB_ICONINFORMATION MB_YESNO))
      {
               return true;
}
else
{
     return false;
}
}
}
}
 
More Algorithms :
 
/*--------------------------------------------------------------------------------------

Function Name : GetPercentageValue()
Return Type : double
Usage : Function to get 2 Digits Precision;
without rounding it off. As per reqirement of Percentage value.
Author : Nikki
----------------------------------------------------------------------------------------*/

double CCustomRatingCompMatrix::GetPercentageValue( double x)
{
    double f, xi, xf;
    xf = modf( x, &xi );
    f = floor(xf *100+0.0)/100.0;
    return xi + f;
}

/*---------------------------------------------------------------------
Function Name : GetItemCount_PointEarnedValue()
Return Type : int
Usage : Get the ItemCount and PointEarn values
without rounding it off. As per reqirement of Percentage value.
Author :
-----------------------------------------------------------------------*/

int CMatrix::GetItemCount_PointEarnedValue(double x)
{
            return floor(((double)x*100))/100;
}


Remit2 India Customer Care Phone Number

Remit2India's customer care phone number  (Toll Free numbers )
mentioned below: 1-888-REMIT-TO (US & Canada) 0r 1-888-73648-86


0808-2346585 (U.K)
1-800-089-693 (Australia)

or email: infor@remit2India.com

Monday, February 7, 2011

Things you should never assume at work....

Some times back I had discussed about ..in general . Do your colleagues could be your best friend.
I'm not saying these are all my idea and epitome. It's just a collection of mine; from the various sources.
Since I'm very much interested in human psychology and human behaviour. That the reason I never miss to collect these type of articles and thoughts.

Today I'm having a very interesting topic; Things never assume at work.
As humans we often make assumptions; some times good . some time bad. Assumptions about people ; assumptions about places.
Assumptions about family members or assumptions about our work mates.
We often make bad assumptions and then become disappointed when situations don't work out.

Let's have a look on report provided by New York Daily News. reports says
My job completes me – It's not your whole life, avoid the Work, Sleep, Repeat cycle or else your sense of self will erode any time your job disappoints you.

 Carolyn Kepcher, author of the best-selling book 'Carolyn 101,' describes and enlighten on the areas in which it's important to maintain a healthy sense of reality:

Let's say you assume , your boss reads your mind – Lobby for your promotion and take the initiative of talking to your boss about it. Many workers make the mistake of not engaging in any self-promotion at all - and then suffer the crushing disappointment of not receiving a pay raise, or a promotion.

Co-workers are friends – Although you may find friends at work, it's very important to draw boundaries. Unlike friendships or romances gone awry, you have no choice but to see your co-workers every single workday.

Salaries are set fairly – It's one's responsibility to negotiate for a higher salary. Employers will pay what they feel they need to pay to hire and keep an employee, and nothing more.

H.R. is there to help – They will help you, but their true job is to protect the organization. There are certain areas in which it may be best not to seek the H.R. department''s assistance, such as using them as a shoulder to cry on for your every workplace woe.

You aren't indispensable – Millions of workers learned that their jobs are not as secure as they once thought. Being valuable is realistic, feeling irreplaceable is not.

My personal life is my business – only as long as something that reflects poorly upon your employer. For example, you're probably not free to bad-mouth them on Facebook . Even if you do not face disciplinary action, your future career will take a hit.

I'll sue – Don't be naive. Filing a lawsuit alone takes a lot of money. Even if you are right, sometimes your only decision is whether to stay or to go. Righting wrongs can be a very costly mission.

Bosses are cool when I slack off – Do not take your job for granted. While you're accepting their pay, it's important to honour your end of the bargain, or expect them to reward your poor attitude by bestowing your job to someone who actually wants it.

Thursday, February 3, 2011

convert double to string (non-cstring)?

Convert double to string (non-cstring)?


char str[10];
double num = 1.42463;
sprintf(str, "%.2f", num);

Example:
double dValidatedPercentageValue = 0;

dValidatedPercentageValue = RoundADouble(dValue);
char str[10];
sprintf(str, "%.2f", dValidatedPercentageValue);
pGrid->PutTextMatrix(Row, Col, _bstr_t(str));


Example:
Function to round of for 2 Decimal Precision:

double Matrix::RoundADouble(double x)

{
double f, xi, xf;
xf = modf(x,&xi);
f = floor(xf*100+0.5)/100.0;
return xi + f;
}

atof, _wtof, atoi, _wtoi, _atoi64, _wtoi64, atol, _wtol, _ttoi

Convert a string to double (atof and _wtof), integer (atoi, _atoi64, _wtoi and _wtoi64), or long integer (atol and _wtol).


double atof( const char *string );
double _wtof(const wchar_t *string );
int atoi(const char *string );
__int64 _atoi64(const char *string );
int _wtoi(const wchar_t *string );
__int64 _wtoi64(const wchar_t *string );
long atol(const char *string );
long _wtol(const wchar_t *string );
 
Parameters :  string (String to be converted.)

Return Value:
Each function returns the double, int, __int64, or long value produced by interpreting the input characters as a number. The return value is 0 (for atoi, _atoi64, _wtoi, and _wtoi64), 0L (for atol and _wtol), or 0.0 (for atof and _wtof) if the input cannot be converted to a value of that type. The return value is undefined in case of overflow.

Remarks
These functions convert a character string to a double-precision, floating-point value (atof and _wtof), an integer value (atoi, _atoi64, _wtoi and _wtoi64), or a long integer value (atol and _wtol).

The input string is a sequence of characters that can be interpreted as a numerical value of the specified type. The output value is affected by the setting of the LC_NUMERIC category in the current locale. For more information on the LC_NUMERIC category, see setlocale. The function stops reading the input string at the first character that it cannot recognize as part of a number. This character may be the null character ('\0' or L'\0') terminating the string.

The string argument to atof and _wtof has the following form:
[whitespace] [sign] [digits] [.digits] [ {d D e E }[sign]digits]

A whitespace consists of space or tab characters, which are ignored; sign is either plus (+) or minus ( – ); and digits are one or more decimal digits. If no digits appear before the decimal point, at least one must appear after the decimal point. The decimal digits may be followed by an exponent, which consists of an introductory letter (d, D, e, or E) and an optionally signed decimal integer.

atoi, _atoi64, atol, _wtoi, _wtoi64 and _wtol do not recognize decimal points or exponents. The string argument for these functions has the form:

[whitespace] [sign]digits    
where whitespace, sign, and digits are as described for atof and _wtof.

Example
// crt_atof.c

#include
#include

int main( void )
{
   char *s; double x; int i; long l;
   s = " -2309.12E-15"; /* Test of atof */

   x = atof( s );

   printf( "atof test: \"%s\"; float: %e\n", s, x );
    s = "7.8912654773d210"; /* Test of atof */

   x = atof( s );
  printf( "atof test: \"%s\"; float: %e\n", s, x );
  s = " -9885 pigs"; /* Test of atoi */
  i = atoi( s );

printf( "atoi test: \"%s\"; integer: %d\n", s, i );
s = "98854 dollars"; /* Test of atol */

l = atol( s );
printf( "atol test: \"%s\"; long: %ld\n", s, l );
}
 
OutPut
atof test: " -2309.12E-15"; float: -2.309120e-012

atof test: "7.8912654773d210"; float: 7.891265e+210
atoi test: " -9885 pigs"; integer: -9885
atol test: "98854 dollars"; long: 98854
 
QA:
How can you multiply  2 numeric values within 2 separate CString variables . How to get the value of the 2 values multiplied together if they are CStrings?
 
Answers
CString s1 ="22";

CString s2="33";

int nResult = atoi(s1)*atoi(s2);
You can use atof too (if are float or double).

Example 2
CString s1 = "22";

CString s2 = "33";
int n1 = atoi( (LPCTSTR) s1);
int n2 = atoi( (LPCTSTR) s2);
int nRes = n1 * n2;

Example 3
int nResult = atoi((LPCTSTR)s1)*atoi((LPCTSTR)s2);


Example 4
When you are using unicode app if CString is defined as unsigned short*

Then use  _wtoi() instead of atoi()

Example 5 (_ttoi )
When using CString, you should not use atoi or _wtoi.


Instead you should use _ttoi instead.

Example:

int nResult = _ttoi(s1)*_ttoi(s2);

The reason _ttoi is better, because then you can easily change your envirnment from UNICODE to ANSI, and back, with out having to change your source code.

_ttoi will automatically use the correct function for the current CString type.

In UNICODE CString uses WIDE charactors, and in ANSI CString uses normal ANSI single byte charactors.
So in practice, you should avoid using any of the ANSI string functions with CString, and use the TCHAR types instead.

Examples:
_tcsrev _strrev
_tcscpy strcpy
_tcscmp strcmp
_tcscat strcat

Note:
By default the VC++ applications are Multiple-byte aplications. Thereis a preprocessor #define directive which defines the symbol _MBCS (see project menu, settings, C/C++ tab)


You can make an application Unicode just removing the _MBCS symbol and adding _UNICODE symbol.
Depending on _UNICODE is defined or not CString (which is TCHAR*) is defined in one or other way. TCHAR is char* in _MBCS but is wchar_t* (unisigned short*) with _UNICODE.

To comple make your app unicode you must In the Output category of the Link tab in the Project Settings dialog box, set the Entry Point Symbol to wWinMainCRTStartup.

Using TCHAR still allows CString to have all its functions working. Actually, I think CString is based on TCHAR to work in both ANSII and UNICODE modes.


Then to convert you result back to a string, just us the format function:
myString.Format("%i", iResult);
After that you can use it to set your window text.

Please provide your comments...

Also Visit:


http://journeyallover.blogspot.com/2010/04/way-to-south-korea.html
http://journeyallover.blogspot.com/2010/04/frequently-asked-interview-question-in.html

http://journeyallover.blogspot.com/2010/04/biometrics.html


Floor Function : C++

Floor Function : C++

double floor ( double x );

float floor ( float x );
long double floor ( long double x );

Round down value
Returns the largest integral value that is not greater than x.

Parameters :   x  (Floating point value. )

Return Value: The largest integral value not greater than x.

/* floor example */

#include
#include

int main ()
{
    printf ("floor of 2.3 is %.1lf\n", floor (2.3) );
printf ("floor of 3.8 is %.1lf\n", floor (3.8) );
printf ("floor of -2.3 is %.1lf\n", floor (-2.3) );
printf ("floor of -3.8 is %.1lf\n", floor (-3.8) );
return 0;
}

Output:


floor of 2.3 is 2.0
floor of 3.8 is 3.0
floor of -2.3 is -3.0
floor of -3.8 is -4.0

Other Function:
ceil      :  Round up value (function)

fabs     :  Compute absolute value (function)
modf    :  Break into fractional and integral parts (function)







Wednesday, February 2, 2011

LOCALE_SDECIMAL LOCALE_IDIGITS

LOCALE_SDECIMAL


Character(s) used for the decimal separator, for example, "." in "3.14" or "," in "3,14". The maximum number of characters allowed for this string is four, including a terminating null character.

LOCALE_IDIGITS


Number of fractional digits placed after the decimal separator. The maximum number of characters allowed for this string is two, including a terminating null character. For example, 2 for 5.00, 1 for 5.0.

strtod, wcstod

Convert string to double

Convert strings to a double-precision value.


double strtod(  const char *nptr,   char **endptr );

double wcstod(  const wchar_t *nptr,  wchar_t **endptr );

Parameters
nptr       :     Null-terminated string to convert.
endptr    :    Pointer to character that stops scan.

Return Value
strtod returns the value of the floating-point number, except when the representation would cause an overflow, in which case the function returns +/–HUGE_VAL. The sign of HUGE_VAL matches the sign of the value that cannot be represented. strtod returns 0 if no conversion can be performed or an underflow occurs.

wcstod returns values analogously to strtod. For both functions, errno is set to ERANGE if overflow or underflow occurs.

Remarks

Each function converts the input string nptr to a double. The strtod function converts nptr to a double-precision value. strtod stops reading the string nptr at the first character it cannot recognize as part of a number. This may be the terminating null character. wcstod is a wide-character version of strtod; its nptr argument is a wide-character string. Otherwise, these functions behave identically.

Generic-Text Routine Mappings
TCHAR.H routine|  _UNICODE & _MBCS not defined | _MBCS defined | _UNICODE defined
_tcstod                    |                 strtod                                    |       strtod             |          wcstod

The LC_NUMERIC category setting of the current locale determines recognition of the radix character in nptr; for more information, see setlocale. If endptr is not NULL, a pointer to the character that stopped the scan is stored at the location pointed to by endptr. If no conversion can be performed (no valid digits were found or an invalid base was specified), the value of nptr is stored at the location pointed to by endptr.

strtod expects nptr to point to a string of the following form:
[whitespace] [sign] [digits] [.digits] [ {d D e E}[sign]digits]

A whitespace may consist of space and tab characters, which are ignored; sign is either plus (+) or minus (–); and digits are one or more decimal digits. If no digits appear before the radix character, at least one must appear after the radix character. The decimal digits can be followed by an exponent, which consists of an introductory letter (d, D, e, or E) and an optionally signed integer. If neither an exponent part nor a radix character appears, a radix character is assumed to follow the last digit in the string. The first character that does not fit this form stops the scan.

Requirements

strtod   and wcstod or


Example:
/* strtod example */

#include
#include

int main ()
{
char szOrbits[] = "365.24 29.53";
char * pEnd;
double d1, d2;

d1 = strtod (szOrbits,&pEnd);
d2 = strtod (pEnd,NULL);

printf ("The moon completes %.2lf orbits per Earth year.\n", d1/d2);
return 0;
}

Output:

The moon completes 12.37 orbits per Earth year.

atof Convert string to double (function)

strtol Convert string to long integer (function)
strtoul Convert string to unsigned long integer (function)

Convert string to double with two decimal precision C++







VSFlexGrid Introduction and Implementation : MFC

VSFlexGrid Introduction

The VSFlexGrid control is a powerful, full-featured grid. It provides new ways to display, edit, format, organize,   summarize, and print tabular data.

The VSFlexGrid control was designed to be used either in unbound mode, where the grid "owns" the data, or in databound  mode, where the grid is used to view and edit data that that belongs to a database.

VSFlexGrid 8.0 ships with three versions of the VSFlexGrid control. Each version has its own OCX file and supports a  different type of data binding:

The following sections walk you through the main features in the VSFlexGrid control:
Basic Operations
Describes how to set up the grid dimensions and layout, and the concepts of "current cell" and "selection".

Editing Cells

Describes how to implement simple text editing, drop-down lists and combo lists, cell buttons, editing masks, and data validation.

Formatting Cells    : Describes how to customize the appearance of the grid by formatting numbers, dates, and boolean values, or by  changing fonts, colors, alignment, and pictures for individual cells or ranges.

Merging Cells
Describes how to change the grid display so that cells with similar contents are merged, creating "grouped" views that highlight relationships in the data.

Outlining and Summarizing
Describes how to add subtotals to grids and how to build outline trees.

Data Binding (ADO and DAO)  :   Discusses the basic aspects of ADO/OLEDB and DAO data-binding.

Other types of Data Binding     :
Discusses how you can bind the VSFlexGrid control to arrays of Variants, to other VSFlexGrid controls, or to custom  data sources that you can implement yourself.

Saving, Loading, and Printing   :  Describes how you can save the contents or formatting of a grid and re-load it later, or exchange grid data with other  applications such as Microsoft Access and Excel. This section also shows how you can print grids.

Using VSFlexGrid in Visual C++
Shows useful techniques and programming tips on how to use the VSFlexGrid control in Visual C++, both in MFC and  in ATL projects.

OCX File Description

VSFLEX8.OCX This version provides support for ADO/OLEDB  data Binding, the latest data binding standard from  Microsoft. It requires ADO to be installed.

VSFLEX8D.OCX This version provides support for DAO data binding, the more traditional type of data
binding supported by Visual Basic's built-in Data Control.

VSFLEX8L.OCX This version has no support for data-binding. Use it when your application does not
require data-binding and you want to reduce the number of components your application depends on.

VSFLEX8U.OCX This is a Unicode version that provides support for  ADO/OLEDB data binding. It only runs on  Windows NT systems.

VSFlexGrid properties cross-referenced by function.
Basic Operations
The VSFlexGrid control has two properties that determine its dimensions: Rows and Cols. When used in bound mode,  these properties are set automatically based on how much data is available on the data source. In unbound mode, you  can set them to arbitrary values.

There are two basic types of rows and columns: fixed and scrollable. Fixed rows remain on the top of the grid when  the user scrolls the grid vertically, and fixed columns remain on the left of the grid when the user scrolls the grid  horizontally. Fixed cells are useful for displaying row and column header information. They cannot be selected or edited  by the user. The number of fixed rows and columns is set by the FixedRows and FixedCols properties.

The AllowUserResizing property allows the user to resize rows and columns by dragging the edges of the fixed cells.

The ExplorerBar property allows the user to move and sort columns by clicking and dragging the header rows.

i) Cursor
ii) Selection
iii) Variations
Cursor  :    The grid has a cursor, which is the cell defined by the Row and Col properties. The cursor displays a focus rectangle  while the grid is active. The user may move the cursor with the keyboard or the mouse, and edit the contents of the cell,   if the grid is editable. Changing the Row and Col properties in code also moves the cursor.

The Row property may be set to values between zero and Rows - 1 to select a row, or to -1 to hide the cursor. The  Col property may be set to values between zero and Cols - 1 to select a column, or to -1 to hide the cursor.

Setting the Row and Col properties does not ensure that the new cursor is visible. For that, use the ShowCell method.

Selection  :   The grid also has a selection, which is a rectangular range of cells defined by two opposing corners: the cursor (Row,  Col properties) and the cell defined by the RowSel and ColSel properties. The user may change the selection using the  keyboard or the mouse. Changing the RowSel and ColSel properties in code also changes the selection.

When the Row or Col properties change, RowSel and ColSel are automatically reset and the selection collapses into a  single cell, the cursor. To create selection in code, either set RowSel and ColSel after setting Row and Col, or use the  Select method.

Several grid properties apply to the cursor or to the selection, depending on the setting of the FillStyle property. These  include Text and all properties with names that start with Cell (CellBackColor, CellForeColor, etc.)

Variations
For some applications, only a cursor makes sense, and no selection. In these cases, set the AllowSelection property  to False. This will prevent the user from extending the selection with the keyboard or the mouse.

Some applications require selections to be made row by row, list-box style. In these cases, set the SelectionMode  property to flexSelectionListBox (3) and retrieve the selected status for each row through the IsSelected() property.

Editing Cells:   The main property related to editing is the Editable property. You must set it to a non-zero value to allow users to edit   the contents of the grid. The flexEDKbd (1) setting allows users to start editing a cell by typing into it. The  flexEDKbdMouse (2) setting also allows users to double-click a cell to start editing it.

i) Editing Text, Lists, and Combos
ii) Cell Buttons
iii) Masks
iv) Validation
v) Controlling Edit Mode

Editing Text, Lists, and Combos :  Once you set the Editable property to a non-zero value, users may edit text by selecting a cell and then typing into it.  This is the most basic type of editing.

Often, the user's choices will be limited to a list of possible values. In these cases, you can let them select the choice  from a drop-down list. To do this, build a string containing all the choices separated by pipe characters (e.g.  "True", "False" "Don't know") and assign it to the ColComboList() property of the column for which the choices apply.

Each column may have a different list. After this, the grid will display an arrow next to the cell. When the user clicks the  arrow or presses a key, the list will drop down and offer the choices available.

A third option is one where there are typical values for a cell, but the user should be allowed to type something else as  well. This can be accomplished with drop-down combos, a combination of text box and drop-down list. To create  combos, just start the choice list with a pipe character (e.g. " True", "False", "Don't know"), then assign it to the ColComboList as before.

In some cases, cells in the same column may need different lists. For example, a property list may show properties on  the first column and their values on the second. The values depend on the property, so valid choices change from one  row to the next. In these cases, you should trap the BeforeEdit event and set the ComboList property to the  appropriate list for the current cell.

Cell Buttons:
Certain types of cell may require sophisticated editors other than text boxes or choice lists. For example, if a cell  contains a file name or a color, it should be edited with a dialog box. In these cases, set the ColComboList property to an ellipsis ("…"). The control will display a button next to the cell and will fire the CellButtonClick event when the user  clicks on it. You can trap the event, show the dialog, and update the cell's contents with the user's selection.

Masks
The VSFlexGrid control supports masked editing, where an input mask is used to automatically validate the input as  the user types. This is done through the ColEditMask property, which takes a string that defines what characters are valid for each input position. Masks may be used with regular text fields and with drop-down combo fields.

Mask strings have two types of characters: literal characters, which become part of the input, and template characters, which serve as placeholders for characters belonging to specific categories (e.g. digits or alphabetic). For example, you  could use a mask like "(999) 999-9999" for entering phone numbers (the digit "9" is a placeholder that stands for any  digit). For details on the syntax used to build the mask strings, see the EditMask property in the control reference  section.

If different cells in the same column need different masks, trap the BeforeEdit event and set the EditMask property to  an appropriate value for the current cell.

Validation
In many cases, edit masks alone are not enough to ensure that the data enters by the user was valid. For example, a mask won't let you specify a range of possible values, or validate the current cell based on the contents of another cell.

In these cases, trap the ValidateEdit event and see if the value contained in the EditText property is a valid entry for the current cell (at this point, the Text property still has the original value in it). If the input is invalid, set the Cancel  parameter to True and the grid will remain in edit mode until the user types a valid entry.

Controlling Edit Mode
You can determine whether the grid is in edit mode by reading the value of the EditWindow property. If this property returns zero, the grid is not in edit mode. If it returns a non-zero value, the grid is in edit mode and the value returned is the handle of the edit window.

You can force the grid into edit mode at any time using the EditCell method. You can even allow the user to edit fixed cells by selecting them in code (using the Select method) and then invoking the EditCell method. You can cancel the  edit mode by selecting the current cell (e.g. .Select .Row, .Col).

Formatting Cells

One of the main strengths of the VSFlexGrid control is the ability to customize almost every aspect of the appearance of the entire grid and individual cells. There are properties that affect the whole grid, such as Font, BackColor,  ForeColor, and GridLines. Others are specific to rows and columns, such as RowHeight(), RowHidden(), ColWidth(), ColAlignment(), and ColFormat(). Finally, the Cell property allows you to format arbitrary ranges and individual cells.

Formatting cell contents
i)  Formatting cell appearance
ii)  Conditional formatting
iii)  Formatting cell contents

The ColFormat() property controls how cell contents are formatted for display. It takes as a parameter a format string similar to the one used by Visual Basic's Format function. For example, you may set ColFormat() to "#.###,##",  Currency", or "Long Date". This property does not affect the cell's contents, only the way it is displayed.
You may also use check boxes to display boolean values. To do this, set the ColDataType() property to flexDTBoolean.

The grid will automatically display check boxes and handle them if the grid is editable.

Formatting cell appearance:
By default, the VSFlexGrid control will align strings to the left and numbers and dates to the right of each column. You may override this default using the ColAlignment() property.

For the ultimate in cell formatting control, use the Cell property. This property allows you to set or retrieve every aspect of a range's formatting. You may set a cell's contents, font, back color, fore color, alignment, and picture,  among other options.

If you need even more control over the appearance of the cells, use the OwnerDraw property and the DrawCell event  to paint the cell yourself, using Windows API calls.

Conditional formatting :
To format cells based on their contents, trap the CellChanged event and apply the formatting using the Cell property.
For example, you can make negative values red and bold or give values above a certain threshold a blue background.

Outlining and Summarizing:
The VSFlexGrid control has methods and properties that allow you to summarize data and display it in a hierarchical  manner. To summarize data, use the Subtotal method. To display hierarchical views of the data, use the OutlineBar  and OutlineCol properties.

i)  Creating Subtotals
ii)  Creating Outline Trees
iii)  Creating Subtotals

The Subtotal method adds subtotal rows that contain aggregate data for the regular (data) rows.
Subtotal supports hierarchical aggregates. For example, you may call it several times in a row using different
parameters to get sales figures by Product, Region, and Salesperson. You may also calculate aggregates other than sums (e.g. averages or percentages) and format the subtotal rows to highlight them.

For example, assuming you had a VSFlexGrid control named fg containing Product, Region, Salesperson, and Sales  information, you could summarize it with the following code:

' clear existing subtotals
fg.Subtotal flexSTClear
' get an Grand total (use 1 instead of columns index)
fg.Subtotal flexSTSum, -1, 3, , 1, vbWhite, True
' total per Product (column 0)
fg.Subtotal flexSTSum, 0, 3, , vbRed, vbWhite, True
' total per Region (column 1)
fg.Subtotal flexSTSum, 1, 3, , vbBlue, vbWhite, True
' show an OutlineBar on column 0
fg.OutlineBar = flexOutlineBarSimple

After executing this code, the grid would look like having the subtotal rows created by the Subtotal method differ from regular rows in three aspects:
1) Subtotal rows can be automatically removed by invoking the Subtotal method with the flexSTClear parameter. This is useful to provide dynamic views of the data, where the user may move columns and re-sort the data, making it necessary to recalculate the subtotals.

2) Subtotal rows can be used as nodes in an outline, allowing you to collapse and expand groups of rows to present an overview of the data or to reveal its details. To see the outline tree, you need to set the OutlineBar property to a nonzero  value. Because the outline is a hierarchical structure, each row has a level that defines how deep into the outline  the node is. This level can be set or retrieved through the RowOutlineLevel() property.

3) When the grid is bound to a data source, the subtotal rows do not correspond to actual data. Thus, if you navigate the recordset using the MoveFirst and MoveNext methods, the subtotal rows will be skipped.

Using VSFlexGrid in Visual C++
The VSFlexGrid control can be used in Visual C++ as well as in Visual Basic.
This part of the manual was written to help experienced C++ programmers get started using the VSFlexGrid control in VC++. If you don't know C++, MFC, or ATL, you may skip this section, as it probably won't make much sense to you.
Until recently, using ActiveX controls in Visual C++ meant you had to use the MFC (Microsoft Foundation Classes) framework, because this was the only reasonable way to get the ActiveX hosting capabilities and Wizard support most programmers want. With the release of Microsoft Visual Studio 6, however, this situation has changed. You can now use  ATL (Active Template Library) and native compiler support for COM to create projects that do not depend on MFC. In  fact, even if your project is based on MFC you should take advantage of the native COM support to improve the  performance of your applications.

Using VSFlexGrid in MFC projects
i)  Handling Optional Parameters in MFC 
ii) Handling Picture Properties in MFC
iii) Dual Interfaces in MFC
iv) Using VSFlexGrid in ATL projects

Handling Pictures in ATL projects
Creating Controls Dynamically in ATL
Using VSFlexGrid in MFC projects
To use the VSFlexGrid control in MFC projects, you will normally follow these steps:
1.   GetRecordCount() Returns the number of records in the data source.
GetFieldName(Fld&) Returns the name of field number Fld (ranging from zero to GetFieldCount() -1).
GetData(Fld&, Rec&) Returns the data in field Fld , record Rec (ranging from zero to GetRecordCount() - 1).

SetData(Fld&, Rec&, Data$) Returns the data in field Fld ,  record Rec.

Create a new dialog-based MFC project.
2.. Go to the resource editor, open the dialog, right-click on it, select "Insert ActiveX control", and pick the
VSFlexGrid control from the list (if the grid is not on the list, it hasn't been registered on your computer).
3. Hold down the CTRL key and double-click on the grid. This will cause Developer Studio to generate wrapper classes through which you can interact with the control. When the wrapper classes are ready, select a name  for the control (e.g. m_Grid).

4. From now on, things are pretty much the same as in VB. You can right-click on the control to implement event handlers, and access the controls properties and methods through the m_Grid variable. Most properties are  exposed through GetPropertyName and SetPropertyName member functions. Unfortunately, enumerated  values get translated into longs instead of their proper enumeration symbols, but that's a relatively minor  inconvenience. (And one that can be avoided, read on).

If you take a look at the CVSFlexGrid wrapper generated by Developer Studio, you will see that the class is derived  from CWnd. This means you can move, size, show, or hide the control as if it were a regular window. The wrapper  class also has a handy Create function that lets you create new instances of the control. For example, if you add this  declaration to the main dialog's header file:

class CMyDlg : public Cdialog
{
// Construction
public:
// standard constructor
CMyDlg(CWnd* pParent = NULL);
// new VSFlexGrid
CvsFlexGrid m_GridDynamic;

//You can create the control by adding the following code to the dialog's OnInitDialog function:
BOOL CMyDlg::OnInitDialog()
{
// Wizard-generated code
     . . .
// TODO: Add extra initialization here
// create a second instance of the VSFlexGrid control
RECT rc;
GetClientRect(&rc);
InflateRect(&rc, -5, -5);
rc.left = (rc.left + rc.right) / 2;
m_GridDynamic.Create(NULL, WS_VISIBLE, rc, this, 100);

return TRUE; // return TRUE
}

The problem with this second approach is that you have to hook up the event handlers manually. You can do this by copying the code created by the Wizard for the first control (it involves using several macros to define an "event sink").

Hooking up the events manually is not difficult, but it is a tedious and error-prone process. Unless you have a good  reason to create the controls dynamically, you should stick to the resource editor and the Wizard.

This covers most of what you need to know about using ActiveX controls in MFC. There are a couple of issues that  deserve additional explanation (at least our tech support department gets many questions on these): handling optional  parameters, Picture properties, and dual interfaces.

Handling Optional Parameters in MFC

Optional parameters in COM interfaces are always of type VARIANT. To omit them in Visual Basic, you simply don't  supply a value for them at all. The wrapper classes created by the MFC Wizard, however, require that you supply  VARIANTS for all parameters, optional or not. In these cases, what you need to do is create a VARIANT of type  VT_ERROR, and use that in place of the optional parameters.

For example, the VSFlexGrid control has an AutoSize method that takes three optional parameters. To invoke  AutoSize omitting the optional parameters, you could write:

COleVariant vtNone(0L, VT_ERROR);
m_Grid.AutoSize(1, vtNone, vtNone, vtNone);

Notice that the VARIANT is created with a 0L value instead of simply 0. This is required by the compiler to define   whether the zero is a short or a long integer.

Handling Picture Properties in MFC

OLE Pictures are objects in their own right. They have methods that retrieve their size, type, and so on. As such, setting or retrieving Picture properties involves dealing with their IDispatch pointers (IDispatch is the basic type of Automation COM interface). The question is, how do I create one of these interfaces to give to the control? The easiest way is through an MFC helper class called CPictureHolder. This class, declared in the AFXCTL.H file, has methods that allow you to create and manage OLE pictures.

The code below shows how you can use the CPictureHolder class to set the VSFlexGrid control's CellPicture  property:

#include // declare CPictureHolder class
void CJnkDlg::OnButton1()
{
// create CPictureHolder
CPictureHolder pic;
// load a picture from a bitmap resource
pic.CreateFromBitmap(IDB_BITMAP1);

// get the LPDISPATCH pointer
LPDISPATCH pPic = pic.GetPictureDispatch();
// assign LPDISPATCH to control
m_Grid.SetCellPicture(pPic);

// don't forget to release the LPDISPATCH
pPic->Release();

}

Besides setting the picture property, the code above illustrates an important point when dealing with COM interfaces.

Notice how the LPDISPATCH pointer is obtained, used, and released. Failing to release COM pointers results in objects dangling in memory and wasting resources.

Some properties and methods require that you pass pictures in VARIANT parameters (e.g. the Cell property). To do this, initialize a ColeVariant as follows:

COleVariant vPic;
V_VT(&vPic) = VT_DISPATCH;
V_DISPATCH(&vPic) = pic.GetPictureDispatch();

Notice that in this case you must not release the LPDISPATCH pointer, because the COleVariant destructor will do that automatically when vPic goes out of scope.

Dual Interfaces in MFC. The wrapper classes created by the MFC wizard are very helpful, and for a while they were the best you could get. With  Visual Studio 6, however, the compiler has built-in COM support, including a different way to create wrapper classes for COM objects through the new #import compiler directive. These "native" wrapper classes are faster and more flexible  than the ones generated by MFC:

The MFC wrappers are based on the IDispatch interface, so every method or property you access needs to pack its parameters into VARIANTS and go through a call to the Invoke method. The native wrappers, by contrast, take advantage of dual interfaces to access properties and methods via direct calls, which is much faster.



The native wrappers are more complete and configurable. They include object-defined enumerations, default values for  optional parameters, and an optional VB-like syntax for accessing properties. These new features allow you to write
m_spGrid->MousePointer = flexHourglass;
m_spGrid->AutoSize(1);

instead of,
m_Grid.SetMousePointer(11);

COleVariant vtNone(0L, VT_ERROR);
m_Grid.AutoSize(1, vtNone, vtNone, vtNone);

Taking advantage of dual interfaces in existing MFC projects is easy. All you have to do is include the appropriate
#import statement in your StdAfx.h file, then create a pointer and assign it to the existing control. For example, assuming you have an MFC-based m_Grid control, all the extra code you would need would be this:

// include this statement in the StdAfx.h file
#import "c:\windows\system\vsflex8l.ocx" no_namespace

// note: to use the OLEDB/ADO version of the control, you need to #import "msdatsrc.tlb" as well.
//#import "c:\windows\system\msdatsrc.tlb" no_namespace
//#import "c:\windows\system\vsflex8l.ocx" no_namespace

Then, instead of using the control in the usual way, declare a variable of type IVSFlexGridPtr, initialize it by setting it to m_Grid.GetControlUnknown(), and use it instead of m_Grid. The two routines listed below illustrate the difference between the two approaches (both routines fill a grid 1000 times with a string and report how long it took them to do it):

// Using the MFC-generated wrapper class
void CMyDlg::BenchDispatchClick()
{
CString strText = "Hello.";

DWORD tStart = GetTickCount();
for (long i = 0; i < 1000; i++)’
for (long r = m_Grid.GetFixedRows(); r < m_Grid.GetRows(); r++)

for (long c = m_Grid.GetFixedCols(); c < m_Grid.GetCols(); c++)
Grid.SetTextMatrix(r, c, (LPCTSTR)strText);

DWORD tElapsed = GetTickCount() - tStart;

CString str;
str.Format("Done in %d seconds using dispatch interface.", (int)(tElapsed / 1000));
MessageBox(str);
}

// Using the native wrapper class (#import-based)
void CMyDlg::BenchDualClick()
{
IVSFlexGridPtr spGrid = m_Grid.GetControlUnknown();
_bstr_t strText = "Hello.";
DWORD tStart = GetTickCount();

for (long i = 0; i < 1000; i++)
for (long r = spGrid->FixedRows; r < spGrid->Rows; r++)
for (long c = spGrid->FixedCols; c < spGrid->Cols; c++)

spGrid->PutTextMatrix(r, c, strText);
DWORD tElapsed = GetTickCount() - tStart;

CString str;
str.Format("Done in %d seconds using dual interface.",(int)(tElapsed / 1000));
MessageBox(str);
}

The code looks very similar, except for the dot notation used with the m_Grid variable and the arrow used with the spGrid variable. The big difference is in execution speed. The MFC/Dispatch version takes 30 seconds to fill the grid 1000 times, while the native/dual version takes only 8 seconds. The dual version is over three times faster than the traditional MFC/Dispatch version.

In functions that only set a few properties, it probably doesn't matter much which type of wrapper class you choose. But in functions with lengthy for statements that access properties or methods several hundred times, you should definitely consider using the #import statement/ dual interface approach.

Using VSFlexGrid in ATL projects

Using the VSFlexGrid control in ATL is not much different than using it in MFC projects. You can still use Wizards and a rich set of low-level support classes. What you don't get is the higher-level classes, document/view architecture, and other amenities provided by MFC.

To use the VSFlexGrid control in ATL projects, you will normally follow these steps:

1. Create a new ATL COM project of type "Executable".
2. Select the "Insert New ATL Object…" menu option, select the "Miscellaneous" object type, then choose
"Dialog". Pick any name for the dialog.

3. Go to the resource editor, open the dialog, right-click on it, select "Insert ActiveX control", and pick the
VSFlexGrid control from the list (if the grid is not on the list, it hasn't been registered on your computer). You
may also want to set the dialog's ClipChildren property to True to make it repaint more smoothly.

4. Right-click on the control and select the "Events…" option. Then select the grid control from the list on the
right and the list on the left will show all the events available for the control. Select the ones you want to
handle by double-clicking them, and click OK when you are done. This will automatically insert an #import
statement into the dialog header file.

5. Edit the #import statement and remove all qualifiers except for no_namespace. If you are using the
OLEDB/ADO version of the VSFlexGrid control, then you need two #import statements instead of one (this is because the OLEDB/ADO version of the grid relies on the Microsoft DataSource object, which needs to be imported as well):

#import "c:\windows\system\msdatsrc.tlb" no_namespace
#import "c:\windows\system\vsflex8l.ocx" no_namespace

6. Now the control is on the form, but you can't talk to it yet. To get a pointer to the control, open the dialog
header file and edit the OnInitDialog function so it looks like this:

IVSFlexGridPtr m_spGrid; // pointer to the control
CAxWindow m_wndGrid; // pointer to the host window

LRESULT OnInitDialog(UINT uMsg, WPARAM wParam,LPARAM lParam, BOOL& bHandled)
{

m_wndGrid = GetDlgItem(IDC_VSFLEXGRID1); // get host window
m_wndGrid.QueryControl(&m_spGrid); // get control

m_wndGrid.SetFocus(); // activate the control

AtlAdviseSinkMap(this, True); // hook up events
return 1; // let the system set the focus
}

7. This code declares a pointer to the control and one to the control's host window. When the dialog initiates, the code makes m_wndGrid point to the host window and queries it for the contained control, which is stored in the m_spControl variable. From then on, you may move and resize the control through its host window (m_wndGrid) and access the control's properties and methods through the control pointer (m_spControl).

8. The only thing missing is the code that displays the dialog. That needs to be added to the project's main cpp file. Here's the code that you will need:

#include "MyProject_i.c"
#include "MyDlg.h" // add this line
// wizard-generated code . . .
//////////////////////////////////////////////////////////////////

extern "C" int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpCmdLine, int /*nShowCmd*/)
{
// wizard-generated code . . .

CMyDlg dlg; // create the dialog
dlg.DoModal(); // show the dialog

//MSG msg; // comment these lines out
//while (GetMessage(&msg, 0, 0, 0))
// DispatchMessage(&msg);

// wizard-generated code . . .
}

That's about it. You could clean up this project by removing the references to the idl and rgs files, which it doesn't need (it is just an EXE, not a COM server). See the samples on the distribution CD to find out what changes are necessary or refer to the ATL documentation for more details.

Handling Pictures in ATL projects

If you are not using MFC, you can't use the MFC CPictureHolder class. But you can use the CPicHolder class provided in the samples on the distribution CD. CPicHolder is actually more powerful than CPictureHolder because it provides methods for loading pictures from disk files and from the clipboard. Once you include the CPicHolder class in your  project, you can handle pictures just as we discussed earlier, when dealing with MFC projects.

The samples on the distribution CD include other useful classes, such as CToolTip, and a file named AtlControls.h that is part of a Visual Studio sample and defines ATL wrapper classes for all Windows common controls.

Creating Controls Dynamically in ATL

As in MFC, you can create controls dynamically with ATL. These are the steps required:

1. Insert the appropriate #import statement in the dialog header file or in the StdAfx.h file.
2. Add two member variables to your dialog or window class:

CAxWindow m_wndGrid; // host window
IVSFlexGridPtr m_spGrid; // pointer to control

3. When the dialog or window is created, create the control and its host window, and attach the control to the window:

// initialize ATL ActiveX hosting
AtlAxWinInit();

// create the control (will fail if not registered)
m_spGrid.CreateInstance(__uuidof(VSFlexGrid)));
ATLASSERT(m_spGrid != NULL);

// create the host window (nID = IDC_GRID1)
// the nID is needed if you want to sink events.

RECT rc;
GetClientRect(&rc);

m_wndGrid.Create(m_hWnd, rc, NULL, WS_CHILD WS_VISIBLE, 0, IDC_GRID1);

// attach the control to the host window
CComPtr spHost;

m_wndGrid.QueryHost(&spHost1);
spHost->AttachControl(m_spGrid, m_wndGrid);

As in MFC, this approach requires you to hook up the event handlers manually. You can also copy wizard-generated code, which does two things: it adds an IDispEventImpl declaration to your class so it inherits the ATL event handling mechanisms, and adds an event sink map to your class using BEGIN_SINK_MAP, SINK_ENTRY, and  END_SINK_MAP macros. You still need to add the call to AtlAdviseSinkMap in order to start getting the events.

Also in ATL, unless you have a good reason to create the controls dynamically, you should still stick to the resource editor and the Wizard.

VSFlexGrid Introduction
http://humano.ya.com/peprestauracio/

Simple Implementation

Implementing the Events:

BEGIN_EVENTSINK_MAP(CMatrix, CDialogEx)

     ON_EVENT(CMatrix, IDC_MATRIX, 23, CMatrix::ValidateEditAlternateMatrix, VTS_I4 VTS_I4 VTS_PBOOL)


ON_EVENT(CMatrix, IDC_CUSTOM_COMP_MATRIX, 24, CMatrix::AfterEditCustomCompMatrix, VTS_I4 VTS_I4)


ON_EVENT(CMatrix, IDC_CUSTOM_COMP_MATRIX, 4, CMatrix::OnLeaveCell, VTS_NONE ) //Validation updated.


END_EVENTSINK_MAP()

Validate Matrix

bool CMatrix::ValidateMatrix()

{
    // Do the data validation here
   IVSFlexGridPtr pGrid = m_fgMatrix.GetControlUnknown();
    CString csAmount,cs1Amount,csPercentage,cs2Amount;


    long lRow, lColumn = 1;
    double dAmount = 0, dOldAmount = 0, d1Amount = 0, d2Amount = 0, dPercent = 0 ;

// Validate the thresholds (They must increase in value)
for(lRow = 1; lRow < pGrid->GetRows();lRow++)
{


    cs2Amount = V_BSTR(&pGrid->GetCell(flexcpText, lRow, 1));
    cs1Amount = V_BSTR(&pGrid->GetCell(flexcpText, lRow, 2));
    csPercentage = V_BSTR(&pGrid->GetCell(flexcpText, lRow, 3));


if (cs1Amount == "" && cs2Amount == "" && csPercentage == "")
{
   continue;
}


    csAmount = V_BSTR(&pGrid->GetCell(flexcpText, lRow+1, 1));
   d1Amount = pLocale->GetRawCurrency(csHighAmount);
   d2Amount = pLocale->GetRawCurrency(csLowAmount);
   dPercent = pLocale->GetRawNumber(csPercentage);


if (d1Amount <=0 )
{
   g_SysUtil.SysOK(this, IGTI18N::GetString(_T("IDS_MATRIX_HIGHER_AMOUNT_VALIDATE")));
   return false;
}

if (dPercent != 0)
{
if (dAmount <= d2Amount)
{
    g_SysUtil.SysOK(this, IGTI18N::GetString(_T("IDS__MATRIX_AMOUNT_VAL")));
    GetDlgItem(IDC_MATRIX)->SetFocus();
    pGrid->Select(lRow, lColumn);


   return false;
}


if(cs1Amount == "" && csPercentage != "" csPercentage == "" && cs1Amount != "" )
{
    g_SysUtil.SysOK(this, IGTI18N::GetString(_T("IDS_CUSTOM_MATRIX_FIELD_NULL")));
    GetDlgItem(IDC__MATRIX)->SetFocus();


   if ( csPercentage == "")
   pGrid->Select(lRow, 3);


else
    pGrid->Select(lRow, 1);


return false;
}


dAmount = g_pLocale->GetRawCurrency(csAmount);
dOldAmount = g_pLocale->GetRawCurrency(csHighAmount);


if( dAmount != 0 && dAmount <= dOldAmount)
{
   g_SysUtil.SysOK(this, IGTI18N::GetString(_T("IDS__AMOUNT_VALIDATE")));
   GetDlgItem(IDC__MATRIX)->SetFocus();


   pGrid->Select(lRow, lColumn);
   return false;
}
}


else
{
   g_SysUtil.SysOK(this, IGTI18N::GetString(_T("IDS_MATRIX_PERCENTAGE_VALIDATE")));
   return false;
}

}
return true;
}

Validate Empty Matrix

bool CMatrix::ValidateEmptyMatrix()

{


  // Do the validation if Matrix is Empty...
   IVSFlexGridPtr pGrid = m_fgMatrix.GetControlUnknown();
   CString csAmount,cs1Amount,csPercentage,cs2Amount;
   long lRow, lColumn = 1;


   double dAmount = 0, dOldAmount = 0, d1Amount = 0, d2Amount = 0, dPercent = 0 ;
// Validate the thresholds (They must increase in value)


for(lRow = 1; lRow < pGrid->GetRows();lRow++)
{
   csAmount2 = V_BSTR(&pGrid->GetCell(flexcpText, lRow, 1));
   csAmount 1= V_BSTR(&pGrid->GetCell(flexcpText, lRow, 2));
   csPercentage = V_BSTR(&pGrid->GetCell(flexcpText, lRow, 3));

if (csAmount1 == "" && cs1Amount == "" && csPercentage == "")
{
   m_bEmptyMatrix = true;
   continue;
}


if (csHighAmount != "" && csLowAmount != "" && csPercentage != "")
{
  m_bEmptyMatrix = false;
 break;
}

}


if (m_bEmptyMatrix)
{


SetMatrixDlgFlag(false);
//g_SysUtil.SysOK(this, IGTI18N::GetString(_T("IDS__MATRIX_CANNOT_EMPTY")));
return false;
}
return true;
}

Event Handler

void CMatrix::OnLeaveCell()

{
    long lRow = 0;
    long lCol = 0;


    BOOL bCancelFlag = FALSE;
    IVSFlexGridPtr pGrid = m_fgMatrix.GetControlUnknown();

    lRow = pGrid->GetRow();
    lCol = pGrid->GetCol();

    ValidateEditAlternateMatrix(lRow, lCol, &bCancelFlag);


if(bCancelFlag)
{
    m_fgMatrix.SetFocus();
    pGrid->Select(lRow, lCol);
}


}


Please provide your comments...

Also Visit:
http://journeyallover.blogspot.com/2010/04/way-to-south-korea.html
http://journeyallover.blogspot.com/2010/04/frequently-asked-interview-question-in.html
http://journeyallover.blogspot.com/2010/04/biometrics.html

Health Benefits of Cashews

  Benefits of Cashews. Healthy food is an integral part of healthy body. Regular exercises such as Yoga and healthy diet is important to...