About your (electronic) self
whoami --- returns your username. Sounds useless, but isn't. You may need to find out who it is who forgot to log out somewhere, and make sure *you* have logged out.
finger & .plan files
of course you can finger yourself, too. That can be useful e.g. as a quick check whether you got new mail. Try to create a useful .plan file soon. Look at other people's .plan files for ideas. The file needs to be readable for everyone in order to be visible through 'finger'. Do 'chmod a+r .plan' if necessary. You should realize that this information is accessible from anywhere in the world, not just to other people on turing.
passwd --- lets you change your password, which you should do regularly (at least once a year). See the LRB guide and/or look at help password.
ps -u yourusername --- lists your processes. Contains lots of information about them, including the process ID, which you need if you have to kill a process. Normally, when you have been kicked out of a dialin session or have otherwise managed to get yourself disconnected abruptly, this list will contain the processes you need to kill. Those may include the shell (tcsh or whatever you're using), and anything you were running, for example emacs or elm. Be careful not to kill your current shell - the one with the number closer to the one of the ps command you're currently running. But if it happens, don't panic. Just try again :) If you're using an X-display you may have to kill some X processes before you can start them again. These will show only when you use ps -efl, because they're root processes.
kill PID --- kills (ends) the processes with the ID you gave. This works only for your own processes, of course. Get the ID by using ps. If the process doesn't 'die' properly, use the option -9. But attempt without that option first, because it doesn't give the process a chance to finish possibly important business before dying. You may need to kill processes for example if your modem connection was interrupted and you didn't get logged out properly, which sometimes happens.
quota -v --- show what your disk quota is (i.e. how much space you have to store files), how much you're actually using, and in case you've exceeded your quota (which you'll be given an automatic warning about by the system) how much time you have left to sort them out (by deleting or gzipping some, or moving them to your own computer).
du filename --- shows the disk usage of the files and directories in filename (without argument the current directory is used). du -s gives only a total.
last yourusername --- lists your last logins. Can be a useful memory aid for when you were where, how long you've been working for, and keeping track of your phonebill if you're making a non-local phonecall for dialling in.
Welcome to the world of e Gyan.This is an attempt to put together and share the vast and vivid knowledge.The focus will be on sharing of our knowledge on- Latest tools and techniques.etc.So, go ahead and share the Gyan.
Thursday, February 17, 2011
Unix Commands
Files
ls --- lists your files
ls -l --- lists your files in 'long format', which contains lots of useful information, e.g. the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified.
ls -a --- lists all files, including the ones whose filenames begin in a dot, which you do not always want to see.
There are many more options, for example to list files by size, by date, recursively etc.
more filename --- shows the first part of a file, just as much as will fit on one screen. Just hit the space bar to see more or q to quit. You can use /pattern to search for a pattern.
emacs filename --- is an editor that lets you create and edit a file.
mv filename1 filename2 --- moves a file (i.e. gives it a different name, or moves it into a different directory (see below)
cp filename1 filename2 --- copies a file
rm filename --- removes a file. It is wise to use the option rm -i, which will ask you for confirmation before actually deleting anything. You can make this your default by making an alias in your .cshrc file.
diff filename1 filename2 --- compares files, and shows where they differ
wc filename --- tells you how many lines, words, and characters there are in a file
chmod options filename --- lets you change the read, write, and execute permissions on your files. The default is that only you can look at them and change them, but you may sometimes want to change these permissions. For example, chmod o+r filename will make the file readable for everyone, and chmod o-r filename will make it unreadable for others again. Note that for someone to be able to actually look at the file the directories it is in need to be at least executable. See help protection for more details.
File Compression
gzip filename --- compresses files, so that they take up much less space. Usually text files compress to about half their original size, but it depends very much on the size of the file and the nature of the contents. There are other tools for this purpose, too (e.g. compress), but gzip usually gives the highest compression rate. Gzip produces files with the ending '.gz' appended to the original filename.
gunzip filename --- uncompresses files compressed by gzip.
gzcat filename --- lets you look at a gzipped file without actually having to gunzip it (same as gunzip -c). You can even print it directly, using gzcat filename | lpr
printing
lpr filename --- print. Use the -P option to specify the printer name if you want to use a printer other than your default printer. For example, if you want to print double-sided, use 'lpr -Pvalkyr-d', or if you're at CSLI, you may want to use 'lpr -Pcord115-d'. See 'help printers' for more information about printers and their locations.
lpq --- check out the printer queue, e.g. to get the number needed for removal, or to see how many other files will be printed before yours will come out
lprm jobnumber --- remove something from the printer queue. You can find the job number by using lpq. Theoretically you also have to specify a printer name, but this isn't necessary as long as you use your default printer in the department.
genscript --- converts plain text files into postscript for printing, and gives you some options for formatting. Consider making an alias like alias ecop 'genscript -2 -r \!* | lpr -h -Pvalkyr' to print two pages on one piece of paper.
dvips filename --- print .dvi files (i.e. files produced by LaTeX). You can use dviselect to print only selected pages. See the LaTeX page for more information about how to save paper when printing drafts.
ls --- lists your files
ls -l --- lists your files in 'long format', which contains lots of useful information, e.g. the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified.
ls -a --- lists all files, including the ones whose filenames begin in a dot, which you do not always want to see.
There are many more options, for example to list files by size, by date, recursively etc.
more filename --- shows the first part of a file, just as much as will fit on one screen. Just hit the space bar to see more or q to quit. You can use /pattern to search for a pattern.
emacs filename --- is an editor that lets you create and edit a file.
mv filename1 filename2 --- moves a file (i.e. gives it a different name, or moves it into a different directory (see below)
cp filename1 filename2 --- copies a file
rm filename --- removes a file. It is wise to use the option rm -i, which will ask you for confirmation before actually deleting anything. You can make this your default by making an alias in your .cshrc file.
diff filename1 filename2 --- compares files, and shows where they differ
wc filename --- tells you how many lines, words, and characters there are in a file
chmod options filename --- lets you change the read, write, and execute permissions on your files. The default is that only you can look at them and change them, but you may sometimes want to change these permissions. For example, chmod o+r filename will make the file readable for everyone, and chmod o-r filename will make it unreadable for others again. Note that for someone to be able to actually look at the file the directories it is in need to be at least executable. See help protection for more details.
File Compression
gzip filename --- compresses files, so that they take up much less space. Usually text files compress to about half their original size, but it depends very much on the size of the file and the nature of the contents. There are other tools for this purpose, too (e.g. compress), but gzip usually gives the highest compression rate. Gzip produces files with the ending '.gz' appended to the original filename.
gunzip filename --- uncompresses files compressed by gzip.
gzcat filename --- lets you look at a gzipped file without actually having to gunzip it (same as gunzip -c). You can even print it directly, using gzcat filename | lpr
printing
lpr filename --- print. Use the -P option to specify the printer name if you want to use a printer other than your default printer. For example, if you want to print double-sided, use 'lpr -Pvalkyr-d', or if you're at CSLI, you may want to use 'lpr -Pcord115-d'. See 'help printers' for more information about printers and their locations.
lpq --- check out the printer queue, e.g. to get the number needed for removal, or to see how many other files will be printed before yours will come out
lprm jobnumber --- remove something from the printer queue. You can find the job number by using lpq. Theoretically you also have to specify a printer name, but this isn't necessary as long as you use your default printer in the department.
genscript --- converts plain text files into postscript for printing, and gives you some options for formatting. Consider making an alias like alias ecop 'genscript -2 -r \!* | lpr -h -Pvalkyr' to print two pages on one piece of paper.
dvips filename --- print .dvi files (i.e. files produced by LaTeX). You can use dviselect to print only selected pages. See the LaTeX page for more information about how to save paper when printing drafts.
Useful UNIX Utilities for Shell Programmers
Useful UNIX Utilities for Shell Programmers
at—at, batch—execute commands at a later time
awk—pattern scanning and processing language
banner—make posters
basename—with a directory name delivers portions of the pathname
bc—processes precision arithmetic
bdiff—compares two big files
cal—displays a calendar
cat—concatenates and displays files
chmod—change the permissions mode of a file
chown—changes owner of file
clear—clears the terminal screen
cmp—compares two files
compress—compress, uncompress, zcat compress, uncompress files, or display expanded files
cp—copies files
cpio—copy file archives in and out
cron—the clock daemon
crypt—encodes or decodes a file
cut—removes selected fields or characters from each line of a file
date—displays the date and time or sets the date
diff—compares two files for differences diff [–bitw] [–c | –Cn
du—summarizes disk usage
echo—echoes arguments
egrep—searches a file for a pattern using full regular expressions
expr—evaluates arguments as an expression
fgrep—search a file for a character string
file—determines the type of a file by looking at its contents
find—finds files
finger—displays information about local and remote users
fmt—simple text formatters
fold—folds long lines
ftp—file transfer program
getopt(s)—parses command line options
grep—searches a file for a pattern
groups—prints group membership of user
id—prints the username, user ID, group name and group ID
jsh—the standard, job control shell
line—reads one line
logname—gets the name of the user running the process
lp—sends output to a printer (AT&T)
lpr—sends output to a printer (UCB)
lpstat—print information about the status of the LP print service (AT&T)
lpq—print information about the status of the printer (UCB)
ls—lists contents of directory
mail—mail, rmail—read mail or send mail to users
mailx—interactive message processing system
make—maintains, updates, and regenerates groups of related programs and files
mesg—permits or denies messages resulting from the write command
mkdir—creates a directory
more—browse or page through a text file
mv—move or rename files
nawk—pattern scanning and processing language
newgrp—log in to a new group
news—prints news items
nice—runs a command at low priority
nohup—makes commands immune to hangups and quits
od—octal dump
pack—pack, pcat, unpack—compresses and expands files
passwd—changes the login password and password attributes
paste—merges same lines of several files or subsequent lines of one file
pcat—(see pack)
pg—displays files a page at a time
pr—prints files
ps—reports process status
pwd—displays the present working directory name
rcp—remote file copy
rlogin—remote login
rm—removes files from directories
rmdir—removes a directory
rsh—starts a remote shell
ruptime—shows the host status of local machines
rwho—who is logged in on local machines
script—creates a typescript of a terminal session
sed—streamlined editor
size—prints section sizes in bytes of object files
sleep—suspends execution for some number of seconds
sort—sort and/or merge files
spell—finds spelling errors
split—splits a file into pieces
strings—finds any printable strings in an object or binary file
stty—sets the options for a terminal
su—become superuser or another user
sum—calculates a checksum for a file
sync—updates the superblock and sends changed blocks to disk
tabs—set tab stops on a terminal
tail—displays the tail end of a file.
talk—allows you to talk to another user
tar—stores and retrieves files from an archive file, normally a tape device
tee—replicates the standard output
telnet—communicates with a remote host
test—evaluates an expression
time—displays a summary of time used by this shell and its children
timex—times a command; reports process data and system activity
touch—updates access time and/or modification time of a file
tput—initializes a terminal or queries the terminfo database
tr—translates characters
true—provide successful exit status
tsort —topological sort
tty—gets the name of the terminal
umask—sets file-creation mode mask for permissions
uname—prints name of current machine
uncompress—restores files to their original state after they have been compressed using the
compress command
uniq—reports on duplicate lines in a file
units—converts quantities expressed in standard scales to other scales
unpack—expands files created by pack
uucp—copy files to another system, UNIX-to-UNIX system copy
uuencode—uuencode, uudecode—encode a binary file into ASCII text in order to send it through email,or convert it back into its original form
wc—counts lines, words, and characters
what—extracts SCCS version information from a file by printing information found after the @(#)
pattern
which—locates a command and displays its pathname or alias (UCB)
whereis—locates the binary, source, and manual page files for a command (UCB)
who—displays who is logged on the system
write—writes a message to another user
xargs—constructs an argument list(s) and executes a command
zcat—uncompress a compressed file to standard output. Same as uncompress –c
at—at, batch—execute commands at a later time
awk—pattern scanning and processing language
banner—make posters
basename—with a directory name delivers portions of the pathname
bc—processes precision arithmetic
bdiff—compares two big files
cal—displays a calendar
cat—concatenates and displays files
chmod—change the permissions mode of a file
chown—changes owner of file
clear—clears the terminal screen
cmp—compares two files
compress—compress, uncompress, zcat compress, uncompress files, or display expanded files
cp—copies files
cpio—copy file archives in and out
cron—the clock daemon
crypt—encodes or decodes a file
cut—removes selected fields or characters from each line of a file
date—displays the date and time or sets the date
diff—compares two files for differences diff [–bitw] [–c | –Cn
du—summarizes disk usage
echo—echoes arguments
egrep—searches a file for a pattern using full regular expressions
expr—evaluates arguments as an expression
fgrep—search a file for a character string
file—determines the type of a file by looking at its contents
find—finds files
finger—displays information about local and remote users
fmt—simple text formatters
fold—folds long lines
ftp—file transfer program
getopt(s)—parses command line options
grep—searches a file for a pattern
groups—prints group membership of user
id—prints the username, user ID, group name and group ID
jsh—the standard, job control shell
line—reads one line
logname—gets the name of the user running the process
lp—sends output to a printer (AT&T)
lpr—sends output to a printer (UCB)
lpstat—print information about the status of the LP print service (AT&T)
lpq—print information about the status of the printer (UCB)
ls—lists contents of directory
mail—mail, rmail—read mail or send mail to users
mailx—interactive message processing system
make—maintains, updates, and regenerates groups of related programs and files
mesg—permits or denies messages resulting from the write command
mkdir—creates a directory
more—browse or page through a text file
mv—move or rename files
nawk—pattern scanning and processing language
newgrp—log in to a new group
news—prints news items
nice—runs a command at low priority
nohup—makes commands immune to hangups and quits
od—octal dump
pack—pack, pcat, unpack—compresses and expands files
passwd—changes the login password and password attributes
paste—merges same lines of several files or subsequent lines of one file
pcat—(see pack)
pg—displays files a page at a time
pr—prints files
ps—reports process status
pwd—displays the present working directory name
rcp—remote file copy
rlogin—remote login
rm—removes files from directories
rmdir—removes a directory
rsh—starts a remote shell
ruptime—shows the host status of local machines
rwho—who is logged in on local machines
script—creates a typescript of a terminal session
sed—streamlined editor
size—prints section sizes in bytes of object files
sleep—suspends execution for some number of seconds
sort—sort and/or merge files
spell—finds spelling errors
split—splits a file into pieces
strings—finds any printable strings in an object or binary file
stty—sets the options for a terminal
su—become superuser or another user
sum—calculates a checksum for a file
sync—updates the superblock and sends changed blocks to disk
tabs—set tab stops on a terminal
tail—displays the tail end of a file.
talk—allows you to talk to another user
tar—stores and retrieves files from an archive file, normally a tape device
tee—replicates the standard output
telnet—communicates with a remote host
test—evaluates an expression
time—displays a summary of time used by this shell and its children
timex—times a command; reports process data and system activity
touch—updates access time and/or modification time of a file
tput—initializes a terminal or queries the terminfo database
tr—translates characters
true—provide successful exit status
tsort —topological sort
tty—gets the name of the terminal
umask—sets file-creation mode mask for permissions
uname—prints name of current machine
uncompress—restores files to their original state after they have been compressed using the
compress command
uniq—reports on duplicate lines in a file
units—converts quantities expressed in standard scales to other scales
unpack—expands files created by pack
uucp—copy files to another system, UNIX-to-UNIX system copy
uuencode—uuencode, uudecode—encode a binary file into ASCII text in order to send it through email,or convert it back into its original form
wc—counts lines, words, and characters
what—extracts SCCS version information from a file by printing information found after the @(#)
pattern
which—locates a command and displays its pathname or alias (UCB)
whereis—locates the binary, source, and manual page files for a command (UCB)
who—displays who is logged on the system
write—writes a message to another user
xargs—constructs an argument list(s) and executes a command
zcat—uncompress a compressed file to standard output. Same as uncompress –c
const char *p and char * const p
Difference between const char *p and char * const p?
The former declares a pointer to a constant character; the latter declares a constant pointer to a character.
"char const *p" is a pointer to a constant character (you can't change the character);
"char * const p" is a constant pointer to a (variable) character (i.e. you can't change the pointer).
const char *p => cannot change the contents to which it is pointing
char *const p => cannot change the pointer address..
const char *p => cannot change the contents to which it is pointing
char *const p => cannot change the pointer address to which it is pointing
The former declares a pointer to a constant character; the latter declares a constant pointer to a character.
"char const *p" is a pointer to a constant character (you can't change the character);
"char * const p" is a constant pointer to a (variable) character (i.e. you can't change the pointer).
const char *p => cannot change the contents to which it is pointing
char *const p => cannot change the pointer address..
const char *p => cannot change the contents to which it is pointing
char *const p => cannot change the pointer address to which it is pointing
A shallow copy , Deep Copy and Smart Pointer
A shallow copy of an object copies all of the member field values. This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied -- the field in both the original object and the copy will then point to the same dynamically allocated memory, which is not usually what you want. The default copy constructor and assignment operator make shallow copies.
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disasterous consequences.
Smart Pointer
The simplest example of a smart pointer is auto_ptr, which is included in the standard C++ library. You can find it in the header.
Automatic cleanup don't need to remember to free the pointer,
Automatic initialization don't need to initialize the auto_ptr to NULL
Dangling pointers a pointer that points to an object that is already deleted
Since C++ does not provide automatic garbage collection like some other languages, smart pointers can be used for that purpose.
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disasterous consequences.
Smart Pointer
The simplest example of a smart pointer is auto_ptr, which is included in the standard C++ library. You can find it in the header
Automatic cleanup don't need to remember to free the pointer,
Automatic initialization don't need to initialize the auto_ptr to NULL
Dangling pointers a pointer that points to an object that is already deleted
Since C++ does not provide automatic garbage collection like some other languages, smart pointers can be used for that purpose.
AVOID CURSORS
If possible, avoid using SQL Server cursors. They generally use a lot of SQL Server resources and reduce the performance and scalability of your applications. If you need to perform row-by-row operations, try to find another method to perform the task.
Here are some alternatives to using a cursor:
• Use WHILE LOOPS
• Use temp tables
• Use derived tables
• Use correlated sub-queries
• Use the CASE statement
• Perform multiple queries
If you do find you must use a cursor, try to reduce the number of records to process.
One way to do this is to move the records that need to be processed into a temp table first, and then create the cursor to use the records in the temp table, not from the original table. This of course assumes that the subsets of records to be inserted into the temp table are substantially less than those in the original table.
The lower the number of records to process, the faster the cursor will finish.
If you have no choice but to use a server-side cursor in your application, try to use a FORWARD-ONLY or FAST-FORWARD, READ-ONLY cursor. When working with unidirectional, read-only data, use the FAST_FORWARD option instead of the FORWARD_ONLY option, as it has some internal performance optimizations to speed performance. This type of cursor produces the least amount of overhead on SQL Server.
If you are unable to use a fast-forward cursor, then try the following cursors in this order, until you find one that meets your needs. They are listed in the order of their performance characteristics, from fastest to slowest: dynamic, static, and keyset.
Avoid using static/insensitive and keyset cursors, unless you have no other choice. This is because they cause a temporary table to be created in TEMPDB, which increases overhead and can cause resource contention issues.
If you have no choice but to use cursors in your application, try to locate the SQL Server tempdb database on its own physical device for best performance. This is because cursors use the tempdb for temporary storage of cursor data. The faster your disk array running tempdb, the faster your cursor will be.
Using cursors can reduce concurrency and lead to unnecessary locking and blocking. To help avoid this, use the READ_ONLY cursor option if applicable, or if you need to perform updates, try to use the OPTIMISTIC cursor option to reduce locking. Try to avoid the SCROLL_LOCKS cursor option, which reduces concurrency.
When you are done using a cursor, don't just CLOSE it, you must also DEALLOCATE it. Deallocation is required to free up the SQL Server resources used by the cursor. If you only CLOSE the cursor, locks are freed, but SQL Server resources are not. If you don't DEALLOCATE your cursors, the resources used by the cursor will stay allocated, degrading the performance of your server until they are released.
If it is appropriate for your application, try to load the cursor as soon as possible by moving to the last row of the result set. This releases the share locks created when the cursor was built, freeing up SQL Server resources.
If you have to use a cursor because your application needs to manually scroll through records and update them, try to avoid client-side cursors, unless the number of rows is small or the data is static. If the number of rows is large, or the data is not static, consider using a server-side keyset cursor instead of a client-side cursor. Performance is usually boosted because of a reduction in network traffic between the client and the server. For optimum performance, you may have to try both types of cursors under realistic loads to determine which is best for your particular environment.
When using a server-side cursor, always try to fetch as small a result set as possible. This includes fetching only those rows and columns the client needs immediately. The smaller the cursor, no matter what type of server-side cursor it is, the fewer resources it will use, and performance will benefit.
If you need to perform a JOIN as part of your cursor, keyset and static cursors are generally faster than dynamic cursors, and should be used when possible.
Here are some alternatives to using a cursor:
• Use WHILE LOOPS
• Use temp tables
• Use derived tables
• Use correlated sub-queries
• Use the CASE statement
• Perform multiple queries
If you do find you must use a cursor, try to reduce the number of records to process.
One way to do this is to move the records that need to be processed into a temp table first, and then create the cursor to use the records in the temp table, not from the original table. This of course assumes that the subsets of records to be inserted into the temp table are substantially less than those in the original table.
The lower the number of records to process, the faster the cursor will finish.
If you have no choice but to use a server-side cursor in your application, try to use a FORWARD-ONLY or FAST-FORWARD, READ-ONLY cursor. When working with unidirectional, read-only data, use the FAST_FORWARD option instead of the FORWARD_ONLY option, as it has some internal performance optimizations to speed performance. This type of cursor produces the least amount of overhead on SQL Server.
If you are unable to use a fast-forward cursor, then try the following cursors in this order, until you find one that meets your needs. They are listed in the order of their performance characteristics, from fastest to slowest: dynamic, static, and keyset.
Avoid using static/insensitive and keyset cursors, unless you have no other choice. This is because they cause a temporary table to be created in TEMPDB, which increases overhead and can cause resource contention issues.
If you have no choice but to use cursors in your application, try to locate the SQL Server tempdb database on its own physical device for best performance. This is because cursors use the tempdb for temporary storage of cursor data. The faster your disk array running tempdb, the faster your cursor will be.
Using cursors can reduce concurrency and lead to unnecessary locking and blocking. To help avoid this, use the READ_ONLY cursor option if applicable, or if you need to perform updates, try to use the OPTIMISTIC cursor option to reduce locking. Try to avoid the SCROLL_LOCKS cursor option, which reduces concurrency.
When you are done using a cursor, don't just CLOSE it, you must also DEALLOCATE it. Deallocation is required to free up the SQL Server resources used by the cursor. If you only CLOSE the cursor, locks are freed, but SQL Server resources are not. If you don't DEALLOCATE your cursors, the resources used by the cursor will stay allocated, degrading the performance of your server until they are released.
If it is appropriate for your application, try to load the cursor as soon as possible by moving to the last row of the result set. This releases the share locks created when the cursor was built, freeing up SQL Server resources.
If you have to use a cursor because your application needs to manually scroll through records and update them, try to avoid client-side cursors, unless the number of rows is small or the data is static. If the number of rows is large, or the data is not static, consider using a server-side keyset cursor instead of a client-side cursor. Performance is usually boosted because of a reduction in network traffic between the client and the server. For optimum performance, you may have to try both types of cursors under realistic loads to determine which is best for your particular environment.
When using a server-side cursor, always try to fetch as small a result set as possible. This includes fetching only those rows and columns the client needs immediately. The smaller the cursor, no matter what type of server-side cursor it is, the fewer resources it will use, and performance will benefit.
If you need to perform a JOIN as part of your cursor, keyset and static cursors are generally faster than dynamic cursors, and should be used when possible.
IMP C++ FAQ
What is a dangling pointer?
A dangling pointer arises when you use the address of an object after
its lifetime is over. This may occur in situations like returning
addresses of the automatic variables from a function or using the
address of the memory block after it is freed. The following
code snippet shows this:
class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value is " << *ptr; } }; void SomeFunc(Sample x) { cout << "Say i am in someFunc " << endl; } int main() { Sample s1 = 10; SomeFunc(s1); s1.PrintVal(); }In the above example when PrintVal() function is called it is called by the pointer that has been freed by the destructor in SomeFunc. How many ways can an argument be passed to a subroutine?
An argument can be passed in two ways. They are Pass by Value and Passing by Reference.
Passing by value: This method copies the value of an argument into the formal parameter of the subroutine.
Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.
What is the difference between procedural and object-oriented programs?
1. In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code.
2. In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.
What are the advantages of OOPL?
Object oriented programming languages directly represent the real life objects. The features of OOPL as inheritance, polymorphism, encapsulation makes it powerful.
Can a method be overloaded based on different return type but same argument type ?
No, because the methods can be called without using their return type in which case there is ambiguity for the compiler.
What is Downcasting ?
Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy.
What is meant by ?method-wars??
Before 1994 there were different methodologies like Rumbaugh, Booch, Jacobson, Meyer etc who followed their own notations to model the systems. The developers were in a dilemma to choose the method which best accomplishes their needs. This particular span was called as ?method-wars?
Differentiate Aggregation and containment?
Aggregation is the relationship between the whole and a part. We can add/subtract some properties in the part (slave) side. It won?t affect the whole part.
Best example is Car, which contains the wheels and some extra parts. Even though the parts are not there we can call it as car.
But, in the case of containment the whole part is affected when the part within that got affected. The human body is an apt example for this relationship. When the whole body dies the parts (heart etc) are died.
Differentiate persistent & non-persistent objects?
Persistent refers to an object?s ability to transcend time or space. A persistent object stores/saves its state in a permanent storage system with out losing the information represented by the object.
A non-persistent object is said to be transient or ephemeral. By default objects are considered as non-persistent.
List out some of the object-oriented methodologies.
Object Oriented Development (OOD) (Booch 1991,1994).
Object Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991).
Object Modeling Techniques (OMT) (Rumbaugh 1991).
Object Oriented Software Engineering (Objectory) (Jacobson 1992).
Object Oriented Analysis (OOA) (Shlaer and Mellor 1992).
The Fusion Method (Coleman 1991).
When does a name clash occur?
A name clash occurs when a name is defined in more than one place. For example., two different class libraries could give two different classes the same name. If you try to use many class libraries at the same time, there is a fair chance that you will be unable to compile or link the program because of name clashes.
Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its super classes.
If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
)
What is the difference between shadow and override?
Overriding is used to redefines only the methods, but shadowing redefines the entire element.
What is multithreading?
Multithreading is the mechanism in which more than one thread run independent of each other within the process.
What are inner class and anonymous class?
Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.
What is the difference between superclass and subclass?
A super class is a class that is inherited whereas sub class is a class that does the inheriting.
What is difference between overloading and overriding?
a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method.
b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass.
c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass.
d) Overloading must have different method signatures whereas overriding must have same signature
A dangling pointer arises when you use the address of an object after
its lifetime is over. This may occur in situations like returning
addresses of the automatic variables from a function or using the
address of the memory block after it is freed. The following
code snippet shows this:
class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value is " << *ptr; } }; void SomeFunc(Sample x) { cout << "Say i am in someFunc " << endl; } int main() { Sample s1 = 10; SomeFunc(s1); s1.PrintVal(); }In the above example when PrintVal() function is called it is called by the pointer that has been freed by the destructor in SomeFunc. How many ways can an argument be passed to a subroutine?
An argument can be passed in two ways. They are Pass by Value and Passing by Reference.
Passing by value: This method copies the value of an argument into the formal parameter of the subroutine.
Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.
What is the difference between procedural and object-oriented programs?
1. In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code.
2. In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.
What are the advantages of OOPL?
Object oriented programming languages directly represent the real life objects. The features of OOPL as inheritance, polymorphism, encapsulation makes it powerful.
Can a method be overloaded based on different return type but same argument type ?
No, because the methods can be called without using their return type in which case there is ambiguity for the compiler.
What is Downcasting ?
Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy.
What is meant by ?method-wars??
Before 1994 there were different methodologies like Rumbaugh, Booch, Jacobson, Meyer etc who followed their own notations to model the systems. The developers were in a dilemma to choose the method which best accomplishes their needs. This particular span was called as ?method-wars?
Differentiate Aggregation and containment?
Aggregation is the relationship between the whole and a part. We can add/subtract some properties in the part (slave) side. It won?t affect the whole part.
Best example is Car, which contains the wheels and some extra parts. Even though the parts are not there we can call it as car.
But, in the case of containment the whole part is affected when the part within that got affected. The human body is an apt example for this relationship. When the whole body dies the parts (heart etc) are died.
Differentiate persistent & non-persistent objects?
Persistent refers to an object?s ability to transcend time or space. A persistent object stores/saves its state in a permanent storage system with out losing the information represented by the object.
A non-persistent object is said to be transient or ephemeral. By default objects are considered as non-persistent.
List out some of the object-oriented methodologies.
Object Oriented Development (OOD) (Booch 1991,1994).
Object Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991).
Object Modeling Techniques (OMT) (Rumbaugh 1991).
Object Oriented Software Engineering (Objectory) (Jacobson 1992).
Object Oriented Analysis (OOA) (Shlaer and Mellor 1992).
The Fusion Method (Coleman 1991).
When does a name clash occur?
A name clash occurs when a name is defined in more than one place. For example., two different class libraries could give two different classes the same name. If you try to use many class libraries at the same time, there is a fair chance that you will be unable to compile or link the program because of name clashes.
Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its super classes.
If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
)
What is the difference between shadow and override?
Overriding is used to redefines only the methods, but shadowing redefines the entire element.
What is multithreading?
Multithreading is the mechanism in which more than one thread run independent of each other within the process.
What are inner class and anonymous class?
Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.
What is the difference between superclass and subclass?
A super class is a class that is inherited whereas sub class is a class that does the inheriting.
What is difference between overloading and overriding?
a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method.
b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass.
c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass.
d) Overloading must have different method signatures whereas overriding must have same signature
MFC FAQ
What is CSingleDocTemplate?
It’s a document template class used to create single document interface SDI applications. Only one document can be opened at a time. It identifies the document class used to manage the application's data, the frame window class that encloses views of that data, and the view class used to draw visual representations of the data. The document template also stores a resource ID that the framework uses to load menus, accelerators, and other resources that shape the application's user interface.
What is the difference between hinstance and hprevinstance in WinMain function?
hInstance is used for things like loading resources and any other task which is performed on a per-module basis. A module is either the EXE or a DLL loaded into your program. hPrevInstance used to be the handle to the previously run instance of your program (if any) in Win16. It is always NULL for Win32 programs.
Explain about MDI and CMultiDocTemplate ?
MDI applications are designed using the doc-view architectures in which there could be many views associated with a single document object and an application can open multiple docuements at the same time for eg:WORD.
In MDI terms, your main window is called the Frame, this is probably the only window you would have in a SDI (Single Document Interface) program. In MDI there is an additional window, called the MDI Client Window which is a child of your Frame window. CMultiDocTemplate is the document template class used to create MDI applications..The document template also stores a resource ID that the framework uses to load menus, accelerators, and other resources that shape the application's user interface.
Tell me the different controls in MFC ?
CAnimateCtrl,CButton,CEdit,CListBox,CComboBox,CRic hEditCtrl,CStatic, CTreeCtrl,CToolTipCtrl,CIPAddressCtrl,CTabCtrl,CDa teTimeCtrl,CHeaderCtrl,CListCtrl,CMonthCalCtrl,COl eCtrl,CProgressCtrl,CScrollBar,CSliderCtrl,CStatus BarCtrl,CTollBarCtrl etc.,
What is the use of OnInitDialog ?
This message is sent to the dialog box during the Create, CreateIndirect, or DoModal calls, which occur immediately before the dialog box is displayed. This can be used to intialize the dialog controls or show/hide the controls etc.,
What is the functioning of UpdateData() funciton ?
This is to initialize data in a dialog box, or to retrieve and validate dialog data.
The framework automatically calls UpdateData with bSaveAndValidate set to FALSE when a modal dialog box is created in the default implementation of CDialog::OnInitDialog. The call occurs before the dialog box is visible. The default implementation of CDialog::OnOK calls this member function with bSaveAndValidate set to TRUE to retrieve the data, and if successful, will close the dialog box. If the Cancel button is clicked in the dialog box, the dialog box is closed without the data being retrieved.
How to handle RTTI in MFC ?
Run-Time Type Information is a mechanism that allows the type of an object to be determined during the program execution.
3 main elements to RTTI in MFC are
1.Dynamic_cast operator
Used for conversion of polymorphic types.
2.typeid - used for identifying the exact type of an object
3. type_info class
used to hold the type information returned by typeid.
What is serialization ?which function is responsible for serializing data ?
Searialization is the process of streaming the object data to or from a persistent storage medium. It's useful in Doc-View Architecture. CObject :: Serialize() function is used to do serialization
Explain about different kinds of threads in MFC?
2 types of thread in MFc are UserInterface thread and worker thread. UserInterface threads maintain the message loops and used to handles user input,creates windows and process messges sent to those windows.Worker thread don't use message loops and mainly used to perform background operations such as printing etc.,Created using AfxBeginThread bypassing ThreadFunction to create worker thread and Runtime class object to create a user interface thread.
What is a message map, and what is the advantage of a message map over virtual function?
MessageMap is a logical table that maps the windows messages to the member functions of the class. We use message maps over virtual function because of lots of overhead. If every windows message had a virtual function associated with it , there would be several hundred bytes per window class of vtable. Message maps means we only pay for the messages we use.
How to update all the views whenever document got updated ?
call UpdateAllViews()- which updates all views associated with the document by calling OnUpdate() function of all the views.
Given two processes, how can they share memory?
Processes and thread are very similar but they differ in the way they share their resources. Processes are independent and have its own address space. If two independent processes want to communicate they do this by using the following techniques 1.Message Passing 2.Sockets 3. named pipes
How to restrict only one instance of a class object to be created?
Create a Named Mutex.
HANDLE hMutex=CreateMutex(TRUE,_T(“NamedMutex”))
How do I dynamically change the mainframe menu?
CMenu newMenu;
newMenu.LoadMenu (IDR_MENU1);
AfxGetMainWnd()->SetMenu( &newMenu );
AfxGetMainWnd()->DrawMenuBar();
newMenu.Detach ();
What is serialization? Which function is responsible for serializing data ?
Serialization is the process of converting an object into sequence of bits so that it can be stored and retrieved from storage medium e.g. file. Serialize () is responsible for serialization of data
It’s a document template class used to create single document interface SDI applications. Only one document can be opened at a time. It identifies the document class used to manage the application's data, the frame window class that encloses views of that data, and the view class used to draw visual representations of the data. The document template also stores a resource ID that the framework uses to load menus, accelerators, and other resources that shape the application's user interface.
What is the difference between hinstance and hprevinstance in WinMain function?
hInstance is used for things like loading resources and any other task which is performed on a per-module basis. A module is either the EXE or a DLL loaded into your program. hPrevInstance used to be the handle to the previously run instance of your program (if any) in Win16. It is always NULL for Win32 programs.
Explain about MDI and CMultiDocTemplate ?
MDI applications are designed using the doc-view architectures in which there could be many views associated with a single document object and an application can open multiple docuements at the same time for eg:WORD.
In MDI terms, your main window is called the Frame, this is probably the only window you would have in a SDI (Single Document Interface) program. In MDI there is an additional window, called the MDI Client Window which is a child of your Frame window. CMultiDocTemplate is the document template class used to create MDI applications..The document template also stores a resource ID that the framework uses to load menus, accelerators, and other resources that shape the application's user interface.
Tell me the different controls in MFC ?
CAnimateCtrl,CButton,CEdit,CListBox,CComboBox,CRic hEditCtrl,CStatic, CTreeCtrl,CToolTipCtrl,CIPAddressCtrl,CTabCtrl,CDa teTimeCtrl,CHeaderCtrl,CListCtrl,CMonthCalCtrl,COl eCtrl,CProgressCtrl,CScrollBar,CSliderCtrl,CStatus BarCtrl,CTollBarCtrl etc.,
What is the use of OnInitDialog ?
This message is sent to the dialog box during the Create, CreateIndirect, or DoModal calls, which occur immediately before the dialog box is displayed. This can be used to intialize the dialog controls or show/hide the controls etc.,
What is the functioning of UpdateData() funciton ?
This is to initialize data in a dialog box, or to retrieve and validate dialog data.
The framework automatically calls UpdateData with bSaveAndValidate set to FALSE when a modal dialog box is created in the default implementation of CDialog::OnInitDialog. The call occurs before the dialog box is visible. The default implementation of CDialog::OnOK calls this member function with bSaveAndValidate set to TRUE to retrieve the data, and if successful, will close the dialog box. If the Cancel button is clicked in the dialog box, the dialog box is closed without the data being retrieved.
How to handle RTTI in MFC ?
Run-Time Type Information is a mechanism that allows the type of an object to be determined during the program execution.
3 main elements to RTTI in MFC are
1.Dynamic_cast operator
Used for conversion of polymorphic types.
2.typeid - used for identifying the exact type of an object
3. type_info class
used to hold the type information returned by typeid.
What is serialization ?which function is responsible for serializing data ?
Searialization is the process of streaming the object data to or from a persistent storage medium. It's useful in Doc-View Architecture. CObject :: Serialize() function is used to do serialization
Explain about different kinds of threads in MFC?
2 types of thread in MFc are UserInterface thread and worker thread. UserInterface threads maintain the message loops and used to handles user input,creates windows and process messges sent to those windows.Worker thread don't use message loops and mainly used to perform background operations such as printing etc.,Created using AfxBeginThread bypassing ThreadFunction to create worker thread and Runtime class object to create a user interface thread.
What is a message map, and what is the advantage of a message map over virtual function?
MessageMap is a logical table that maps the windows messages to the member functions of the class. We use message maps over virtual function because of lots of overhead. If every windows message had a virtual function associated with it , there would be several hundred bytes per window class of vtable. Message maps means we only pay for the messages we use.
How to update all the views whenever document got updated ?
call UpdateAllViews()- which updates all views associated with the document by calling OnUpdate() function of all the views.
Given two processes, how can they share memory?
Processes and thread are very similar but they differ in the way they share their resources. Processes are independent and have its own address space. If two independent processes want to communicate they do this by using the following techniques 1.Message Passing 2.Sockets 3. named pipes
How to restrict only one instance of a class object to be created?
Create a Named Mutex.
HANDLE hMutex=CreateMutex(TRUE,_T(“NamedMutex”))
How do I dynamically change the mainframe menu?
CMenu newMenu;
newMenu.LoadMenu (IDR_MENU1);
AfxGetMainWnd()->SetMenu( &newMenu );
AfxGetMainWnd()->DrawMenuBar();
newMenu.Detach ();
What is serialization? Which function is responsible for serializing data ?
Serialization is the process of converting an object into sequence of bits so that it can be stored and retrieved from storage medium e.g. file. Serialize () is responsible for serialization of data
MFC FAQ
What is the difference between GetMessage and PeekMessage ?
GetMessage function waits for a message to be placed in the queue before returning where as PeekMessage function does not wait for a message to be placed in the queue before returning.
What’s the difference between PostMessage and SendMessage?
The PostMessage function places (posts) a message in the message queue associated with the thread that created the specified window and then returns without waiting for the thread to process the message.
The SendMessage function sends the specified message to a window or windows. The function calls the window procedure for the specified window and does not return until the window procedure has processed the message.
Name the Synchronization objects ?
Following are the synchronization objects
1) Critical Section
2) Event
3) Mutex
4) Semaphore
Classes provided for above synchronization objects are:
1) CCriticalSection
2) CEvent
3) CMutex
4) CSemaphore
What is the difference between ASSERT and VERIFY?
The main difference between ASSERT and VERIFY is when you compile the release build of the program.
ASSERT will not be present in the release build version of the executables/dlls, and its expression that would have been evaluated will be deleted.
VERIFY will be present in the release build version of the executables/dlls but its expression that would have been evaluated will be left intact.
What is thread & process?
Threads are similar to processes, but differ in the way that they share resources. Threads are distinguished from processes in that processes are typically independent, carry considerable state information and have separate address spaces. Threads typically share the memory belonging to their parent process.
what is the use of AFX_MANAGE_STATE ?
By default, MFC uses the resource handle of the main application to load the resource template. If you have an exported function in a DLL, such as one that launches a dialog box in the DLL, this template is actually stored in the DLL module. You need to switch the module state for the correct handle to be used. You can do this by adding the following code to the beginning of the function:
AFX_MANAGE_STATE(AfxGetStaticModuleState( ));
This swaps the current module state with the state returned from AfxGetStaticModuleState until the end of the current scope.
If all your resources lies in the single DLL you can even change the default handle to the DLL handle with the help of AfxSetResourceHandle function.
Why wizards generate enum IDD for dialogs?
It's good programming practice to do it this way, as from the client code you can always refer to the CMyDlg::IDD without worrying what the actual constant is.
What is the base class for MFC Framework ?
CObject
What is the use of CCmdTarget ?
It is the base class for the MFC library message map architecture.Which maps commands/messages to the member functions to handle them. Classes derived from this are CWnd,CWinApp,CFrameWnd,CView, CDocument .
What is document-view architecture ? Give me one real time example for SDI ?
Document/view architecture, which defines a program structure that relies on document objects to hold an application's data and on view objects to render views of that data. MFC provides the infrastructure for documents and views in the classes CDocument and CView.
example of SDI is a wordpad application
Can you explain the relashionship between document,frame and view ?
The frame window is the application's top-level window. It's normally a WS_OVERLAPPEDWINDOW-style window with a resizing border, a title bar, a system menu, and minimize, maximize, and close buttons.
The view is a child window sized to fit the frame window so that it becomes the frame window's client area.
The application's data is stored in the document object, a visible representation of which appears in the view.
For an SDI application, the frame window class is derived from CFrameWnd, the document class is derived from CDocument, and the view class is derived from CView or a related class such as CScrollView.
How to access document object from view ?
Using GetDocument() function within a CView class.
What is the entry point for window based applications ?
WinMain() is the entry point for window based applications.
What is model and modeless dialog box ? Give some examples?
When we create Modal Dialog Box we can't move to other windows until this dialog is closed. For eg: MessageBox, where we can't move to the other window until we press ok or cancel.
When we create Modeless Dilaog Box we can swap to the other windows. For eg: like a conventional window.
How to create open & save dialogs ?
In CommonDialogs class we have to use CFileDialog class where the first parameter TRUE for open dialog and FALSE for Save dialog.
For file open:
CFileDialog SampleDlg(TRUE,NULL,NULL,OFN_OVERWRITEPROMPT,"Text Files (*.txt)|*.txt|Comma Separated Values(*.csv)|*.csv||");
int iRet = SampleDlg.DoModal();
GetMessage function waits for a message to be placed in the queue before returning where as PeekMessage function does not wait for a message to be placed in the queue before returning.
What’s the difference between PostMessage and SendMessage?
The PostMessage function places (posts) a message in the message queue associated with the thread that created the specified window and then returns without waiting for the thread to process the message.
The SendMessage function sends the specified message to a window or windows. The function calls the window procedure for the specified window and does not return until the window procedure has processed the message.
Name the Synchronization objects ?
Following are the synchronization objects
1) Critical Section
2) Event
3) Mutex
4) Semaphore
Classes provided for above synchronization objects are:
1) CCriticalSection
2) CEvent
3) CMutex
4) CSemaphore
What is the difference between ASSERT and VERIFY?
The main difference between ASSERT and VERIFY is when you compile the release build of the program.
ASSERT will not be present in the release build version of the executables/dlls, and its expression that would have been evaluated will be deleted.
VERIFY will be present in the release build version of the executables/dlls but its expression that would have been evaluated will be left intact.
What is thread & process?
Threads are similar to processes, but differ in the way that they share resources. Threads are distinguished from processes in that processes are typically independent, carry considerable state information and have separate address spaces. Threads typically share the memory belonging to their parent process.
what is the use of AFX_MANAGE_STATE ?
By default, MFC uses the resource handle of the main application to load the resource template. If you have an exported function in a DLL, such as one that launches a dialog box in the DLL, this template is actually stored in the DLL module. You need to switch the module state for the correct handle to be used. You can do this by adding the following code to the beginning of the function:
AFX_MANAGE_STATE(AfxGetStaticModuleState( ));
This swaps the current module state with the state returned from AfxGetStaticModuleState until the end of the current scope.
If all your resources lies in the single DLL you can even change the default handle to the DLL handle with the help of AfxSetResourceHandle function.
Why wizards generate enum IDD for dialogs?
It's good programming practice to do it this way, as from the client code you can always refer to the CMyDlg::IDD without worrying what the actual constant is.
What is the base class for MFC Framework ?
CObject
What is the use of CCmdTarget ?
It is the base class for the MFC library message map architecture.Which maps commands/messages to the member functions to handle them. Classes derived from this are CWnd,CWinApp,CFrameWnd,CView, CDocument .
What is document-view architecture ? Give me one real time example for SDI ?
Document/view architecture, which defines a program structure that relies on document objects to hold an application's data and on view objects to render views of that data. MFC provides the infrastructure for documents and views in the classes CDocument and CView.
example of SDI is a wordpad application
Can you explain the relashionship between document,frame and view ?
The frame window is the application's top-level window. It's normally a WS_OVERLAPPEDWINDOW-style window with a resizing border, a title bar, a system menu, and minimize, maximize, and close buttons.
The view is a child window sized to fit the frame window so that it becomes the frame window's client area.
The application's data is stored in the document object, a visible representation of which appears in the view.
For an SDI application, the frame window class is derived from CFrameWnd, the document class is derived from CDocument, and the view class is derived from CView or a related class such as CScrollView.
How to access document object from view ?
Using GetDocument() function within a CView class.
What is the entry point for window based applications ?
WinMain() is the entry point for window based applications.
What is model and modeless dialog box ? Give some examples?
When we create Modal Dialog Box we can't move to other windows until this dialog is closed. For eg: MessageBox, where we can't move to the other window until we press ok or cancel.
When we create Modeless Dilaog Box we can swap to the other windows. For eg: like a conventional window.
How to create open & save dialogs ?
In CommonDialogs class we have to use CFileDialog class where the first parameter TRUE for open dialog and FALSE for Save dialog.
For file open:
CFileDialog SampleDlg(TRUE,NULL,NULL,OFN_OVERWRITEPROMPT,"Text Files (*.txt)|*.txt|Comma Separated Values(*.csv)|*.csv||");
int iRet = SampleDlg.DoModal();
SQL JOIN
SQL JOIN
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables.
Tables in a database are often related to each other with keys.
A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table.
Different SQL JOINs
JOIN: Return rows when there is at least one match in both tables
LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
FULL JOIN: Return rows when there is a match in one of the tables
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables.
Tables in a database are often related to each other with keys.
A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table.
Different SQL JOINs
JOIN: Return rows when there is at least one match in both tables
LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
FULL JOIN: Return rows when there is a match in one of the tables
Database Normalization Basics
What is Normalization?
Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process: eliminating redundant data (for example, storing the same data in more than one table) and ensuring data dependencies make sense (only storing related data in a table). Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.
First Normal Form (1NF)
First normal form (1NF) sets the very basic rules for an organized database:
•Eliminate duplicative columns from the same table.
•Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).
Second Normal Form (2NF)
Second normal form (2NF) further addresses the concept of removing duplicative data:
•Meet all the requirements of the first normal form.
•Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
•Create relationships between these new tables and their predecessors through the use of foreign keys.
Third Normal Form (3NF)
Third normal form (3NF) goes one large step further:
•Meet all the requirements of the second normal form.
•Remove columns that are not dependent upon the primary key.
Fourth Normal Form (4NF)
Finally, fourth normal form (4NF) has one additional requirement:
•Meet all the requirements of the third normal form.
•A relation is in 4NF if it has no multi-valued dependencies.
Remember, these normalization guidelines are cumulative. For a database to be in 2NF, it must first fulfill all the criteria of a 1NF database.
Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process: eliminating redundant data (for example, storing the same data in more than one table) and ensuring data dependencies make sense (only storing related data in a table). Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.
First Normal Form (1NF)
First normal form (1NF) sets the very basic rules for an organized database:
•Eliminate duplicative columns from the same table.
•Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).
Second Normal Form (2NF)
Second normal form (2NF) further addresses the concept of removing duplicative data:
•Meet all the requirements of the first normal form.
•Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
•Create relationships between these new tables and their predecessors through the use of foreign keys.
Third Normal Form (3NF)
Third normal form (3NF) goes one large step further:
•Meet all the requirements of the second normal form.
•Remove columns that are not dependent upon the primary key.
Fourth Normal Form (4NF)
Finally, fourth normal form (4NF) has one additional requirement:
•Meet all the requirements of the third normal form.
•A relation is in 4NF if it has no multi-valued dependencies.
Remember, these normalization guidelines are cumulative. For a database to be in 2NF, it must first fulfill all the criteria of a 1NF database.
DataBase Connection String Reference
What is a connection string?
Rules for connection strings
All SQL Server SqlConnection properties
SQL Server Data Types Reference
http://www.connectionstrings.com/
Rules for connection strings
All SQL Server SqlConnection properties
SQL Server Data Types Reference
http://www.connectionstrings.com/
Subscribe to:
Posts (Atom)