PHP-Interview Question

Question : What are the differences between Get and post methods in form submitting. Give the case where we can use get and we can use post methods?

Answer : When to use GET or POST

The HTML 2.0 specification says, in section Form Submission (and the HTML 4.0 specification repeats this with minor stylistic changes):

–>If the processing of a form is idempotent (i.e. it has no lasting observable effect on the state of the
world), then the form method should be GET. Many database searches have no visible side-effects and make ideal applications of query forms.

–>If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.

How the form data is transmitted?

quotation from the HTML 4.0 specification

–> If the method is “get” - -, the user agent takes the value of action, appends a ? to it, then appends the form data set, encoded using the application/x-www-form-urlencoded content type. The user agent then traverses the link to this URI. In this scenario, form data are restricted to ASCII codes.
–> If the method is “post” –, the user agent conducts an HTTP post transaction using the value of the action attribute and a message created according to the content type specified by the enctype
attribute.

Quote from CGI FAQ

Firstly, the the HTTP protocol specifies differing usages for the two methods. GET requests should always be idempotent on the server. This means that whereas one GET request might (rarely) change some state on the Server, two or more identical requests will have no further effect.

This is a theoretical point which is also good advice in practice. If a user hits “reload” on his/her browser, an identical request will be sent to the server, potentially resulting in two identical database or guestbook entries, counter increments, etc. Browsers may reload a GET URL automatically, particularly if cacheing is disabled (as is usually the case with CGI output), but will typically prompt the user before re-submitting a POST request. This means you’re far less likely to get inadvertently-repeated entries from POST.

GET is (in theory) the preferred method for idempotent operations, such as querying a database, though it matters little if you’re using a form. There is a further practical constraint that many systems have built-in limits to the length of a GET request they can handle: when the total size of a request (URL+params) approaches or exceeds 1Kb, you are well-advised to use POST in any
case.

I would prefer POST when I don’t want the status to be change when user resubmits. And GET
when it does not matter.

Question : Who is the father of PHP and explain the changes in PHP versions?

Answer : Rasmus Lerdorf is known as the father of PHP.PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current generation of PHP, which uses the Zend engine under the hood. PHP 5 uses Zend engine 2 which, among other things, offers many additional OOPs features.

Question : How can we submit a form without a submit button?

Answer : The main idea behind this is to use Java script submit() function in order to submit the form without explicitly clicking any submit button. You can attach the document.formname.submit() method to onclick, onchange events of different inputs and perform the form submission. you
can even built a timer function where you can automatically submit the form after xx seconds once the loading is done (can be seen in online test sites).

Question : In how many ways we can retrieve the data in the result set of
MySQL using PHP?

Answer : You can do it by 4 Ways

1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc

Question : What is the difference between mysql_fetch_object and
mysql_fetch_array?

Answer : mysql_fetch_object() is similar to mysql_fetch_array(), with one difference -
an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Question : What is the difference between $message and $$message?

Answer : It is a classic example of PHP’s variable variables. take the following example.

$message = “Shashi”;

$$message = “is a owner of http://www.shashionline.in/ “;

$message is a simple PHP variable that we are used to. But the $$message is not a very familiar face. It creates a variable name $message with the value “is a owner http://www.shashionline.in” assigned. break it like this${$message} => $message. Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically.

Question : How can we extract string ‘shashionline.in ‘ from a string info@shashionline.in using regular expression of PHP?

Answer : preg_match(”/^http://.+@(.+)$/”,’info@shashionline.in’,$found);
echo $found[1];

Question : How can we create a database using PHP and MySQL?

Answer : We can create MySQL database with the use of mysql_create_db(“Database Name”).

Question : What are the differences between require and include, include_once and require_once?

Answer :

The include() statement includes and evaluates the specified file.The documentation below also applies to require(). The two constructs are identical in every way except how they handle
failure. include() produces a Warning while require() results in a Fatal Error. In other words, use
require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. The include_once() statement includes and evaluates the
specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be
included again. As the name suggests, it will be included just once.include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc. require_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function
redefinitions, variable value reassignments, etc.

Question : Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?

Answer : Yes we can use include() more than one time in any page though it is not a very good practice.

Question : What are the different tables present in MySQL, which type of table is generated when we are creating a table in the following syntax:
create table employee (eno int(2),ename varchar(10)) ?

Answer : Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the default storage engine as of MySQL 3.23 and as a result if
we do not specify the table name explicitly it will be assigned to the
default engine.

Question : Functions in IMAP, POP3 AND LDAP?

Answer : You can find these specific information in PHP Manual.

Question : How can I execute a PHP script using command line?

Answer : As of version 4.3.0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, “php myScript.php”, assuming “php” is the command to invoke the CLI program.
Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.



Question : Suppose your Zend engine supports the mode <? ?>. Then how can you
configure your PHP Zend engine to support <?php ?>mode ?

Answer : In php.ini file:
set
short_open_tag=on
to make PHP support

Question : Shopping cart online validation i.e. how can we configure Paypal,
etc.?

Answer : We can find the detail documentation about different paypal integration process at the following site PayPal PHP
SDK : http://www.paypaldev.org/

Question : What is meant by nl2br()?

Answer : Inserts HTML line breaks
(
)
before all newlines in a string string nl2br (string); Returns string with ” inserted before all newlines.
For example: echo nl2br(”god blessn you”) will output “god bless
you” to your browser.

Question : Draw the architecture of Zend engine?

Answer : The Zend Engine is the internal compiler and runtime engine used by PHP4. Developed by Zeev Suraski and Andi Gutmans, the Zend Engine is an
abbreviation of their names. In the early days of PHP4, it worked as follows:

Zend Engine

The PHP script was loaded by the Zend Engine and compiled into Zend opcode. Opcodes, short for operation codes, are low level binary instructions. Then the opcode was executed and the HTML generated sent to the client. The opcode was flushed from memory after execution.Today, there are a multitude of products and techniques to help you speed up this process. In the following diagram, we show the how modern PHP scripts work; all the shaded boxes are optional.

Zend Engine

PHP Scripts are loaded into memory and compiled into Zend opcodes.

Question : What are the current versions of apache, PHP, and MySQL?

Answer : As of February, 2007 the current versions are PHP: php5.2.1
MySQL: MySQL 5.2
Apache: Apache 2.2.4
Note: visit
http://www.php.net/,
http://dev.mysql.com/downloads/mysql/,
http://www.apache.org/ to get current
versions.

Question : What are the reasons for selecting lamp (Linux, apache, MySQL,
PHP) instead of combination of other software programs, servers and operating systems?

Answer : All of those are open source resource. Security of Linux is very very more than windows. Apache is a better server that IIS both in functionality and security. MySQL is world most popular open source database. PHP is more faster that asp or any other scripting language.

Question : How can we encrypt and decrypt a data present in a MySQL table using MySQL?

Answer : AES_ENCRYPT () and AES_DECRYPT ()

Question : How can we encrypt the username and password using PHP?

Answer : The functions in this section perform encryption and decryption, and
compression and uncompression:

Encryption Decryption
AES_ENCRYT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSED_LENGTH()

Question : What are the features and advantages of object-oriented programming?

Answer : One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system.

Question : What are the differences between procedure-oriented languages and
object-oriented languages?

Answer : Traditional programming has the following characteristics:Functions are written sequentially, so that a change in programming can affect any code that follows it. If a function is used multiple times in a system (i.e., a piece of code that manages the date), it is often simply cut and pasted into each program (i.e., a change log, order function, fulfillment system, etc). If a date change is needed (i.e., Y2K when the code needed to be changed to handle four numerical digits instead of two), all these pieces of code must be found, modified, and tested. Code (sequences of computer instructions) and data (information on which the instructions operates on) are kept separate. Multiple sets of code can access and modify one set of data. One set of code may rely on data in multiple places. Multiple sets of code and data are required to work together. Changes made to any of the code sets and data sets can cause problems through out the system.Object-Oriented programming takes a radically different approach:Code and data are merged into one indivisible item – an object (the term “component” has also been used to describe an object.) An object is an abstraction of a set of real-world things (for example, an object may be created around “date”) The object would contain all information and
functionality for that thing (A date object it may contain labels like January, February, Tuesday, Wednesday.
It may contain functionality that manages leap years, determines if it is a business day or a holiday, etc., See Fig. 1). Ideally, information about a particular thing should reside in only one place in a system.The information within an object is encapsulated (or hidden) from the rest of the system. A system is composed of multiple objects (i.e., date function, reports, order processing, etc., See Fig 2). When one object needs information from another object, a request is sent asking for specific information. (for example, a report object may need to know what today’s date is and will send a request to the date object) These requests are called messages and each object has an interface that manages messages. OO programming languages include features such as “class”, “instance”, “inheritance”, and “polymorphism” that increase the power and
flexibility of an object.

Question : What is the use of friend function?

Answer : Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class. A friend declaration is essentially a prototype for a member function, but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match.

Question : What are the differences between public, private, protected,static, transient, final and volatile?

Answer : Public: Public declared items can be accessed everywhere.
Protected: Protected limits access to inherited and parent classes (and to the class that defines the item).
Private: Private limits visibility only to the class that defines the item.
Static: A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
Final: Final keyword prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Transient: A transient variable is a variable that may not be serialized.
Volatile: a variable that might be concurrently modified by multiple threads should be declared volatile. Variables declared to be volatile will not be optimized by the compiler because their value can change at any time.

Question : What are the different types of errors in PHP?

Answer : Three are three types of errors:1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although, as you will see, you can change this default behavior.2. Warnings: These are more serious errors - for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.3. Fatal errors: These are critical errors - for example,
instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place.

Question : What is the functionality of the function strstr and stristr?

Answer : strstr:
Returns part of haystack string from the first occurrence of needle to the end of haystack.If needle is not found, returns FALSE. If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This function is case-sensitive. For case-insensitive searches, use stristr().

Question : What are the differences between PHP 3 and PHP 4 and PHP 5?

Answer : Please read the release notes at
http://php.net/

Question : How can we convert asp pages to PHP pages?

Answer : There are lots of tools available for asp to PHP conversion. you can search Google for that. the best one is available at http://asp2php.naken.cc/

Question : What is the functionality of the function htmlentities?

Answer : Convert all applicable characters to HTML entities
This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

Question : How can we get second of the current time using date function?

Answer : $second = date(”s”);

Question : How can we convert the time zones using PHP?

Answer : By using date_default_timezone_get and
date_default_timezone_set function on PHP 5.1.0
// Discover what 8am in Tokyo relates to on the East Coast of the US

// Set the default timezone to Tokyo time:
date_default_timezone_set(’Asia/Tokyo’);

// Now generate the timestamp for that particular timezone, on Jan 1st, 2000
$stamp = mktime(8, 0, 0, 1, 1, 2000);

// Now set the timezone back to US/Eastern
date_default_timezone_set(’US/Eastern’);

// Output the date in a standard format (RFC1123), this will print:
// Fri, 31 Dec 1999 18:00:00 EST
echo ‘

‘, date(DATE_RFC1123, $stamp) ,’

‘; ?>

Question : What is meant by urlencode and urldecode?

Answer : URLencode returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form
is encoded, that is the same way as in application/x-www-form-urlencoded media type. urldecode decodes any %## encoding in the given string.

Question : What is the difference between the functions unlink and unset?

Answer : unlink() deletes the given file from the file system.
unset() makes a variable undefined.

Question : How can we register the variables into a session?

Answer : $_SESSION[’name’] = “Shashi”;

Question : How can we get the properties (size, type, width, height) of an image using PHP image functions?

Answer : To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function

Question : How can we get the browser properties using PHP?

Answer : By using
$_SERVER[’HTTP_USER_AGENT’] variable.

Question : What is the maximum size of a file that can be uploaded using PHP
and how can we change this?

Answer : By default the maximum size is 2MB. and we can change the following setup at php.iniupload_max_filesize = 2M

Question : How can we increase the execution time of a PHP script?

Answer : by changing the following setup at php.inimax_execution_time = 30; Maximum execution time of each script, in seconds

Question : How can we take a backup of a MySQL table and how can we restore it. ?

Answer : To backup: BACKUP TABLE tbl_name[,tbl_name…] TO ‘/path/to/backup/directory’
RESTORE TABLE tbl_name[,tbl_name…] FROM ‘/path/to/backup/directory’mysqldump: Dumping Table Structure and DataUtility to dump a database or a collection of database for backup or for transferring the data to another SQL server (not necessarily a MySQL server). The dump will contain SQL statements to create the table and/or populate the table. -t, –no-create-info Don’t write table creation information (the CREATE TABLE statement). -d, –no-data Don’t write any row information for the table. This is very useful if you just want to get a dump of the structure for a table!

Question : How can we optimize or increase the speed of a MySQL select query?

Answer : • First of all instead of using select * from table1, use select column1, column2, column3.. from table1
•Look for the opportunity to introduce index in the table you arequerying.
•use limit keyword if you are looking for any specific number of rows from the result set.

Question : How many ways can we get the value of current session id?

Answer : How many ways can we get the value of current session id? session_id() returns the session id for the current session.

Question : How can we destroy the session, how can we unset the variable of a session?

Answer : session_unregister — Unregister a global variable from the current session

session_unset — Free all session variables

Question : How can we destroy the cookie?

Answer : Set the cookie in past.

Question : How many ways we can pass the variable through the navigation between the pages?

Answer : •GET/QueryString
•POST

Question : What is the difference between ereg_replace() and eregi_replace()?

Answer : eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.

Question : What are the different functions in sorting an array?

Answer : Sort(), arsort(),
asort(), ksort(),
natsort(), natcasesort(),
rsort(), usort(),
array_multisort(), and
uksort().

Question : How can we know the count/number of elements of an array?

Answer : 2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)

Question : What is the PHP predefined variable that tells the What types of
images that PHP supports?

Answer : Though i am not sure if this is wrong or not, With the exif extension you are able to work with image meta data.

Question : How can I know that a variable is a number or not using a JavaScript?

Answer : bool is_numeric ( mixed var) Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is not a number.

Question : List out some tools through which we can draw E-R diagrams formysql.

Answer :
Case Studio
Smart Draw

Question : How can I retrieve values from one database server and store themin other database server using PHP?

Answer : WeWe can always fetch from one database and rewrite to another. Here is a nice solution of it.
$db1 = mysql_connect(”host”,”user”,”pwd”);
mysql_select_db(”db1?, $db1);
$res1 = mysql_query(”query”,$db1);
$db2 = mysql_connect(”host”,”user”,”pwd”);
mysql_select_db(”db2?, $db2);
$res2 = mysql_query(”query”,$db2);
At this point you can only fetch records from you previous ResultSet, i.e $res1 - But you cannot execute new query in $db1, even if yousupply the link as because the link was overwritten by the new db.so at this point the following script will fail
$res3 = mysql_query(”query”,$db1); //this will failSo how to solve that? take a look below.
$db1 = mysql_connect(”host”,”user”,”pwd”);
mysql_select_db(”db1?, $db1);
$res1 = mysql_query(”query”,$db1);
$db2 = mysql_connect(”host”,”user”,”pwd”, true);
mysql_select_db(”db2?, $db2);
$res2 = mysql_query(”query”,$db2);
So mysql_connect has another optional boolean parameter whichindicates whether a link will be created or not. As we connect to the $db2 with this optional parameter set to ‘true’, so both link willremain live. Now the following query will execute successfully.
$res3 = mysql_query(”query”,$db1);

Question : List out the predefined classes in PHP?

Answer : Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter

Question : How can I make a script that can be bi-language (supportsEnglish, German)?

Answer : You can maintain two separate language file for each of the language. All the labels are putted in both language files as variables and assign those variables in the PHP source. On run-time choose the required language option.

Question : What are the difference between abstract class and interface?

Answer : Abstract class: abstract classes are the class where one or moremethods are abstract but not necessarily all method has to be abstract.Abstract methods are the methods, which are declare in its class but notdefine. The definition of those methods must be in its extending class.Interface: Interfaces are one type of class where all the methods areabstract. That means all the methods only declared but not defined. Allthe methods must be define by its implemented class.

Question : How can we send mail using JavaScript?

Answer : JavaScript does not have any networking capabilities as it isdesigned to work on client site. As a result we can not send mails usingJavaScript. But we can call the client side mail protocol mailtovia JavaScript to prompt for an email to send. this requires the clientto approve it.

Question : How can we repair a MySQL table?

Answer : The syntex for repairing a MySQL table is REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended].This command will repair the table specified if the quick is given the MySQL will do a repair of only the index tree if the extended is givenit will create index row by row.

Question : What are the advantages of stored procedures, triggers, indexes?

Answer : A stored procedure is a set of SQL commands that can be compiled andstored in the server. Once this has been done, clients don’t need tokeep re-issuing the entire query but can refer to the stored procedure.This provides better overall performance because the query has to beparsed only once, and less information needs to be sent between theserver and the client. You can also raise the conceptual level by havinglibraries of functions in the server. However, stored procedures ofcourse do increase the load on the database server system, as more ofthe work is done on the server side and less on the client (application)side.Triggers will also be implemented. A trigger is effectively a type ofstored procedure, one that is invoked when a particular event occurs.For example, you can install a stored procedure that is triggered eachtime a record is deleted from a transaction table and that storedprocedure automatically deletes the corresponding customer from acustomer table when all his transactions are deleted.Indexes are used to find rows with specific column values quickly.Without an index, MySQL must begin with the first row and then readthrough the entire table to find the relevant rows. The larger thetable, the more this costs. If the table has an index for the columns inquestion, MySQL can quickly determine the position to seek to in themiddle of the data file without having to look at all the data. If atable has 1,000 rows, this is at least 100 times faster than readingsequentially. If you need to access most of the rows, it is faster toread sequentially, because this minimizes disk seeks.

Question : What is the maximum length of a table name, database name, andfieldname in MySQL?

Answer : The following table describes the maximum length for each type ofidentifier.

Identifier Maximum Length(bytes)
Database 64
Table 64
Column 64
Index 64
Alias 255

There are some restrictions on the characters that may appear inidentifiers.

Question : How many values can the SET function of MySQL take?

Answer : MySQL set can take zero or more values but at the maximum it cantake 64 values.

Question : What are the other commands to know the structure of table usingMySQL commands except explain command?

Answer : describe Table-Name;

Question : How many tables will create when we create table, what are they?

Answer : The ‘.frm’ file stores the table definition.The data file has a ‘.MYD’ (MYData) extension.The index file has a ‘.MYI’ (MYIndex) extension.

Question : What is the purpose of the following files having extensions 1) .frm2) .myd 3) .myi? What do these files contain?

Answer : In MySql, the default table type is MyISAM.Each MyISAM table is stored on disk in three files. The files have namesthat begin with the table name and have an extension to indicate thefile type.The ‘.frm’ file stores the table definition.The data file has a ‘.MYD’ (MYData) extension.The index file has a ‘.MYI’ (MYIndex) extension.

Question : What is maximum size of a database in MySQL?

Answer : If the operating system or filesystem places a limit on the numberof files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers offiles in a directory can place a practical limit on the number of tablesin a database. If the time required to open a file in the directoryincreases significantly as the number of files increases, databaseperformance can be adversely affected.The amount of available disk space limits the number of tables.MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAMstorage engine in MySQL 3.23, the maximum table size was increased to65536 terabytes (2567 – 1 bytes). With this larger allowed table size,the maximum effective table size for MySQL databases is usuallydetermined by operating system constraints on file sizes, not by MySQLinternal limits.The InnoDB storage engine maintains InnoDB tables within a tablespacethat can be created from several files. This allows a table to exceedthe maximum individual file size. The tablespace can include raw diskpartitions, which allows extremely large tables. The maximum tablespacesize is 64TB.The following table lists some examples of operating system file-sizelimits. This is only a rough guide and is not intended to be definitive.For the most up-to-date information, be sure to check the documentationspecific to your operating system.Operating System File-size LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4+ (using ext3 filesystem) 4TB
Solaris 9/10 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS+ 2TB

Question : Give the syntax of Grant and Revoke commands?

Answer : The generic syntax for grant is as following :
> GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY[password]now rights can be a) All privileges b) combination of create, drop, select, insert, update and delete etc. We can grant rights on all databse by using *.* or some specificdatabase by database.* or a specific table by database.table_name username@hotsname can be either username@localhost, username@hostname and username@% where hostname is any valid hostname and % represents any name, the *.*any condition password is simply the password of user.
The generic syntax for revoke is as following :
> REVOKE [rights] on [database/s] FROM [username@hostname] now rights can be as explained above a) All privileges b) combination of create, drop, select, insert, update and delete etc.username@hotsname can be either username@localhost, username@hostname and username@% where hostname is any valid hostname and % represents any name, the *.*any condition

Question : Explain Normalization concept?

Answer : The normalization process involves getting our data to conform tothree progressive normal forms, and a higher level of normalizationcannot be achieved until the previous levels have been achieved (thereare actually five normal forms, but the last two are mainly academic andwill not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of redundant datafrom horizontal rows. We want to ensure that there is no duplication ofdata in a given row, and that every column stores the least amount ofinformation possible (making the field atomic).Second Normal FormWhere the First Normal Form deals with redundancy of data across ahorizontal row, Second Normal Form (or 2NF) deals with redundancy ofdata in vertical columns. As stated earlier, the normal forms areprogressive, so to achieve Second Normal Form, your tables must alreadybe in First Normal Form.Third Normal Form I have a confession to make; I do not often use Third Normal Form. InThird Normal Form we are looking for data in our tables that is notfully dependant on the primary key, but dependant on another value inthe table.

Question : How can we find the number of rows in a table using MySQL?

Answer : Use this for mysql>SELECT COUNT(*) FROM table_name;

Question : How can we find the number of rows in a result set using PHP?

Answer :
$result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo “$num_rows rows found”;

Question : How many ways we can we find the current date using MySQL?

Answer :
SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use SELECT CURTIME();
CURRENT_TIME() = CURTIME()



Question : What are the advantages and disadvantages of Cascading StyleSheets?

Answer :
External Style Sheets
Advantages : Can control styles for multiple documents at once. Classes can becreated for use on multiple HTML element types in many documents.Selector and grouping methods can be used to apply styles under complex contexts.
Disadvantages : An extra download is required to import style information for eachdocument The rendering of the document may be delayed until the externalstyle sheet is loaded becomes slightly unwieldy for small quantities ofstyle definitions.
Embedded Style Sheets
Advantages : Classes can be created for use on multiple tag types in the document.Selector and grouping methods can be used to apply styles under complexcontexts. No additional downloads necessary to receive style information.
Disadvantages : This method can not control styles for multiple documents at once.
Inline Styles
Advantages : Useful for small quantities of style definitions. Can override otherstyle specification methods at the local level so only exceptions needto be listed in conjunction with other style methods.
Disadvantages : Does not distance style information from content (a main goal ofSGML/HTML). Can not control styles for multiple documents at once.Author can not create or control classes of elements to control multipleelement types within the document. Selector grouping methods can not beused to create complex element addressing scenarios

Question : What type of inheritance that PHP supports?

Answer : In PHP an extended class is always dependent on a single base class,that is, multiple inheritance is not supported. Classes are extendedusing the keyword ‘extends’.

Question : What is the difference between Primary Key andUnique key?

Answer : Primary Key: A column in a table whose values uniquely identify therows in the table. A primary key value cannot be NULL. Unique Key: Unique Keys are used to uniquely identify each row in thetable. There can be one and only one row for each unique key value. So NULL can be a unique key.There can be only one primary key for a table but there can be morethan one unique for a table.

Question : The structure of table view buyers is as follows:

Field Type Null Key Default Extra
user_pri_id int(15) PRI null auto_increment
userid varchar(10) YES null

the value of user_pri_id the last row 999 then What will happen inthe following conditions?Condition1: Delete all the rows and insert another row then.What is the starting value for this auto incremented field user_pri_id ,Condition2: Delete the last row(having the field value 999) andinsert another row then. What is the value for this auto incremented field user_pri_id.

Answer : In both cases let the value for auto increment field be n then nextrow will have value n+1 i.e. 1000.

Question : What are the advantages/disadvantages of MySQL and PHP?

Answer : Both of them are open source software (so free of cost), supportcross platform. php is faster then ASP and JSP.

Question : What is the difference between GROUP BY and ORDER BY in Sql?

Answer : ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columnsit should sort the result. If two rows will hawe the same value in col1it will try to sort them according to col2 and so on.GROUP BY[col1],[col2],…,[coln]; Tels DBMS to group results with same value ofcolumn col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, ifyou want to count all items in group, sum all values or view average.

Question : What is the difference between char and varchar data types?

Answer : Set char to occupy n bytes and it will take n bytes even if u rstoring a value of n-m bytesSet varchar to occupy n bytes and it will take only the required spaceand will not use the n byteseg. name char(15) will waste 10 bytes if we store ‘mizan’, if each chartakes a byteeg. name varchar(15) will just use 5 bytes if we store ‘mizan’, if eachchar takes a byte. rest 10 bytes will be free.

Question : What is the functionality of md5 function in PHP?

Answer : Calculate the md5 hash of a string. The hash is a 32-characterhexadecimal number. I use it to generate keys which I use to identifyusers etc. If I add random no techniques to it the md5 generated nowwill be totally different for the same string I am using.

Question : How can I load data from a text file into a table?

Answer : you can use LOAD DATA INFILE file_name; syntax to load datafrom a text file. but you have to make sure thata) data is delimitedb) columns and data matched correctly.

Question : How can we know the number of days between two given dates usingMySQL?

Answer : SELECT DATEDIFF(’2007-03-07?,’2005-01-01?);

Question : How can we know the number of days between two given dates using PHP?

Answer : $date1 = date(’Y-m-d’);
$date2 = ‘2006-08-15?;
$days = (strtotime($date1) - strtotime($date2)) / (60 * 60 * 24);

Question : More to come………

Answer : More to come

Posted in PHP. No Comments »

ASP-Interview Question

Question : How are scripts executed?
Answer :
ASP provides scripting engines that execute the corresponding scripting languages on the server side. Scripts should be encoded within the “< %…. %”.

Question : Explain the building blocks of Client/Server?
Answer :
The client side building block runs the client side of the application. The server side building block runs the server side of the application.

Question : Explain the POST & GET Method or Explain the difference between them.
Answer :
POST METHOD:
The POST method generates a FORM collection, which is sent as a HTTP request body. All the values typed in the form will be stored in the FORM collection.
GET METHOD:
The GET method sends information by appending it to the URL (with a question mark) and stored as A Querystring collection. The Querystring collection is passed to the server as name/value pair. The length of the URL should be less than 255 characters.

Question : What are the advantages of using ASP?
Answer :
HTML is used only to create static web pages (which displays information) With the use of ASP one can create dynamic web pages,where client can communicate with the web server and vice versa. Thus using ASP interactive webpages can be created.

Question : What is the maximum data can be sent as a querystring?
Answer :
Maximum length is 2084 in IE…

Question : what are the tools used for editing in IIS?
Answer :
IIS Metabase Explorer is a freeware tool to allow editing of the IIS metabase. Essentially this has a similar featureset to Microsoft’s MetaEdit and Metabase Explorer except that it runs on all versions of Windows from 98 through to 2003. In addition the software includes a trace window feature which allows you to track all activity in the metabase including IIS itself or any other administration tool.

Question : What is connection pooling ?
Answer :
A connection pool is a set of database connections that are available for an application to use. Connection Pooling is the concept of using a connection pool for enhanced performance.

Question : How many types of cookies are available in asp?
Answer :
There are 2 types of cookies Persistent and Non-persistent.

Question : What is http header?
Answer :
HTTP headers expose a great deal of information about your client as well as the server you are working, the application you are designing, as well as the environment you are in (SSL, etc.).The functionality for this is held in “Request.ServerVariables”, so you only need to access that. For example, Request.ServerVariables(”ALL_HTTP”) or Request.ServerVariables(”HTTP_USER_AGENT”). You need to know the specific name of the header that you want. It is extremely simple to display all the HTTP headers in ASP. Here’s a code snippit that will do it for you: < % for each header in Request.ServerVariables response.write header & ” = ” & Request.ServerVariables(header) & ” < br>< br> ” next % > Just delete the spaces near the angle brackets and run it on IIS. You’ll get a list of all the HTTP headers along with the actual value for the header. Make sure to try this with different browsers and on different computers with different operating systems if you can. You’ll immediately see the differences.

Question : What is the difference between Server-side validation and Client-side validation?
Answer :
Client side validation is processed the client side before submitting the form. The advantage of using the client side validation is , it reduces the netork trafiic , since the validation is processed in the client machine itself. Eg, email, isnumeric, isdate etc.
Server side validation is processed in the server. Some data cannot be validated in the client side and it has to be validated in the server side. Eg, Date between the two dates in the database.

Question : How long is a SessionID guaranteed to be unique?
Answer :
It is unique per client. A client cannot have two sessions with the same SessionID.




Question : What are the advantages of using ASP?
Answer :
Minimizes network traffic by limiting the need for the browser and server to talk to each other.

Makes for quicker loading time since HTML pages are only downloaded.

Allows to run programs in languages that are not supported by the browser.

Can provide the client with data that does not reside on the client’s machine.

Provides improved security measures since the script cannot be viewed by the browser.

Question : How to handle Error in ASP?
Answer :
Using On Error Resume Next.

Question : What are the event handlers of Session Object?
Answer :
Application_OnStart – This event will be fired when the first visitor hits the page.
Application_OnEnd – This event runs when the server is stoppe.

Question : What is the result of using Option Explicit?
Answer :
All variables must be dimensioned before use.

Question : Which is the default Scripting Language on the client side?
Answer :
JavaScript.

Question : What is a session?
Answer :
A user accessing an application is known as a session.

Posted in ASP. No Comments »

C# .NET interview questions

  1. Are private class-level variables inherited?

Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

  1. Why does DllImport not work for me?

All methods marked with the DllImport attribute must be marked as public static extern.

  1. Why does my Windows application pop up a console window every time I run it?

Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe, not /target:exe.

  1. Why do I get an error (CS1006) when trying to declare a method without specifying a return type?

If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)




  1. Why do I get a syntax error when trying to declare a variable called checked?

The word checked is a keyword in C#.

  1. Why do I get a security exception when I try to run my C# app?

Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what’s happening, just move the executable over to your local drive and see if it runs without the exceptions. One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) by using the caspol.exe tool.

  1. Why do I get a CS5001: does not have an entry point defined error when compiling?

The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows: class test { static void Main(string[] args) {} }

  1. What optimizations does the C# compiler perform when you use the /optimize+ compiler option?

The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.

  1. What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)?

The syntax for calling another constructor is as follows: class B { B(int i) { } } class C : B { C() : base(5) // call base constructor B(5) { } C(int i) : this() // call C() { } public static void Main() {} }

  1. What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development?

Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.




  1. What is the difference between a struct and a class in C#?

From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.

  1. My switch statement works differently than in C++! Why?

C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#:

   switch(x)
{
case 0: // do something
case 1: // do something as continuation of case 0
default: // do something in common with
//0, 1 and everything else
break;
   }

To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit):

class Test
{
public static void Main() {
int x = 3;
switch(x)
{
case 0: // do something
goto case 1;
case 1: // do something in common with 0
goto default;
default: // do something in common with 0, 1, and anything else
break;
}
}
}
  1. Is there regular expression (regex) support available to C# developers?

Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.




  1. Is there any sample C# code for simple threading?

Yes:

using System;
using System.Threading;
class ThreadTest
{
public void runme()
{
Console.WriteLine("Runme Called");
}
public static void Main(String[] args)
{
ThreadTest b = new ThreadTest();
Thread t = new Thread(new ThreadStart(b.runme));
t.Start();
}
}
  1. Is there an equivalent of exit() for quitting a C# .NET application?

Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.

  1. Is there a way to force garbage collection?

Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn’t seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().




  1. Is there a way of specifying which block or loop to break out of when working with nested loops?

The easiest way is to use goto:

using System;
class BreakExample
{
public static void Main(String[] args) {
for(int i=0; i<3; i++)
{
Console.WriteLine("Pass {0}: ", i);
for( int j=0 ; j<100 ; j++ )
{
if ( j == 10)
goto done;
Console.WriteLine("{0} ", j);
}
Console.WriteLine("This will not print");
}
done:
Console.WriteLine("Loops complete.");
}
}
  1. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace?

There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.

ASP.NET Interview Questions

Q1.what are the new features in ASP.NET 2.0?

A1. ASP.NET is a programming framework built on the common language runtime that can be used on a server to build powerful Web applications. The first version of ASP.NET offered several important advantages over previous Web development models. ASP.NET 2.0 improves upon that foundation by adding support for several new and exciting features in the areas of developer productivity, administration and management, extensibility, and performance.

1) New Server Controls: ASP.NET 2.0 introduces many new server controls that enable powerful declarative support for data access, login security, wizard navigation, menus, treeviews, portals, and more. Many of these controls take advantage of core application services in ASP.NET for scenarios like data access, membership and roles, and personalization.

* Data Controls: gridview, detailsview, and formview

* Navigation Controls: treeview, menu, and sitemappath

* Login Controls: login forms, create user forms, password retrieval, and custom UI for logged in users or roles

* Web Part Controls

2) Master Pages: This feature provides the ability to define common structure and interface elements for your site, such as a page header, footer, or navigation bar, in a common location called a “master page”, to be shared by many pages in your site.

In one simple place you can control the look, feel, and much of functionality for an entire Web site. This improves the maintainability of your site and avoids unnecessary duplication of code for shared site structure or behavior.

3) Themes and Skins. The themes and skins features in ASP.NET 2.0 allow for easy customization of your site’s look-and-feel. You can define style information in a common location called a “theme”, and apply that style information globally to pages or controls in your site. Like Master Pages, this improves the maintainability of your site and avoid unnecessary duplication of code for shared styles.

4) Personalization. Using the new personalization services in ASP.NET 2.0 you can easily create customized experiences within Web applications. The Profile object enables developers to easily build strongly-typed, sticky data stores for user accounts and build highly customized, relationship based experiences. At the same time, a developer can leverage Web Parts and the personalization service to enable Web site visitors to completely control the layout and behavior of the site, with the knowledge that the site is completely customized for them. Personalizaton scenarios are now easier to build than ever before and require significantly less code and effort to implement.
5) Localization. Enabling globalization and localization in Web sites today is difficult, requiring large amounts of custom code and resources. ASP.NET 2.0 and Visual Studio 2005 provide tools and infrastructure to easily build Localizable sites including the ability to auto-detect incoming locale’s and display the appropriate locale based UI. Visual Studio 2005 includes built-in tools to dynamically generate resource files and localization references. Together, building localized applications becomes a simple and integrated part of the development experience.
6) Administration and Management – New tools like Configuration API, ASP.NET MMC Admin Tool, Pre-compilation Tool, Health Monitoring and Tracing have been introduced.

Q2. What is Visual Web Developer? Is it Different from Visual Studio 2005?

A2. Visual Web Developer 2005 Express Edition is part of the Microsoft Visual Studio 2005 family, and is the best development tool for building data driven web applications with ASP.NET 2.0. As part of the Express family, Visual Web Developer provides a seamless upgrade path to Visual Studio Standard, Professional, and Team System.

Yes its different from Visual Studio 2005, this one is available as a free download while Visual Studio 2005 has several versions that may be purchased from MS. ¼br>
Q3. What are features of Visual Web Developer?

A3. Intellisense Everywhere - the popup code hints which appear while you type — has a dramatic impact on your productivity as a developer. While support for Intellisense in Visual Studio .NET 2003 is excellent today, support for Intellisense in Visual Web Developer gets even better.

In Visual Web Developer, Intellisense pops up everywhere. For example, you can take full advantage of Intellisense within the script blocks in single file ASP.NET pages. In addition, Visual Web Developer also supports Intellisense for ASP.NET Page Directives and for inline CSS style attributes within a page.

Visual Web Developer also provides Intellisense for all sections within a Web.Config configuration file, as well as any generic XML file that contains a DTD or XML Schema reference.

HTML Source Preservation
Visual Web Developer respects your HTML. The formatting of your HTML markup — including all white space, casing, indention, carriage returns, and word wrapping — is now preserved exactly as originally written, even when switching back and forth between the design view and source view of the page. You can completely trust Visual Web Developer to never modify your markup.

HTML Formatting Options
Visual Web Developer enables you to precisely control the format of all HTML and ASP.NET Server Control markup generated using the WYSIWYG designer. You can now configure the tag casing, attribute quotation, indention style and word wrap characteristics of every html or server control tag in a page. You can set these formatting options as defaults for all markup, as well as optionally override each formatting option on a per tag/control basis. This provides you with the flexibility to fully control exactly how you want your markup to be generated.

Tag Navigator
The HTML source editor within Visual Web Developer ships with a new Tag Navigator feature that enables developers to easily track their location and navigate within a complicated HTML document. The Tag Navigator displays the current “path” within the source of an HTML page by displaying a list of all the HTML tags which contain the tag where your cursor is currently located. Clicking on any of the nodes enables developers to optionally change the source level selection, and quickly move up and down a deep HTML hierarchy.

Tag Outlining
Tag Outlining enables you to work more effectively with large HTML documents. With Tag Outlining, you can right-click any HTML tag in the source editor and select Collapse Tag to hide the entire contents of the tag. Collapsing different regions of the HTML source code contained in a page makes it easier to focus on the particular region of the page which you need to edit.
Flexible Browser Targeting and Validation
Visual Web Developer enables you to easily target a specific HTML standard or browser when writing your HTML pages. For example, you can target your HTML pages to work with a particular browser such as Netscape Navigator 4.0 or Internet
Explorer 6.0. Alternatively, you can target a particular HTML standard such as XHTML 1.0 Strict or XHTML 1.0 Transitional.

Q4. What is Code Refactoring?

A4. Its a feature of Visual Web Express & Visual Studio 2005. Code Refactoring
Code Refactoring enables you to easily and systematically make changes to your code. Code Refactoring is supported everywhere that you can write code including both code-behind and single-file ASP.NET pages. For example, you can use Code Refactoring to automatically promote a public field to a full property.

Q5. What is Intellitask?

A5. Intellitask is like a super smart clipboard designed for working with code. Intellitask improves your productivity by enabling you to easily apply standard code snippets anywhere within the source editor. Simply by right-clicking, you can inject common code into your pages. Visual Web Developer will ship with more than 200 web specific Intellitask code snippets out of the box. Better yet, you can add your own code templates to Intellitask so that you can quickly modify your code in the future.

Q6. How to we edit templates & tables while developing applications in ASP.NET 2.0?

A6. Visual Web Developer has better designer support for editing templates. You can take advantage of the new template editing features when working with data controls such as the DataList and GridView controls.




When adding a control to a template in the designer, you can easily specify the databound expressions to associate with the control properties. For example, if you drag a TextBox control onto a template, you can bind the TextBox control’s Text property to a particular field from the data control’s data source. The Edit Databindings dialog box provided by the Visual Web Developer template editing designer enables you to easily bind particular fields by name.

Visual Web Developer has better HTML table editing features. The improved Insert Table dialog box enables you to quickly control the look and feel of the new table when it is added to the designer surface. In addition, Visual Web Developer provides the ability to resize tables, table columns and table rows graphically within the designer surface (just click and hold down the appropriate element to size it).

Q7. Do we need FrontPage Server Extensions with ASP.NET 2.0 applications?

A7. When we create ASP.NET 2.0 applications on Visual Web Developer OR Visual Studio 2005, We dont need Frontpage Server Extensions as we required in ASP.NET 1.1. When you create a new IIS project, you can now view all of the Web sites and applications configured on your machine. You can even create new IIS Web applications or virtual directories directly from the New Web Site dialog box.

Frontpage Server Extensions (FPSE) are no longer required for locally developed IIS web applications. You can create and fully manage your websites without having to install or configure them.

Q8. Can we develop web pages directly on an FTP server?

A8. Yes. Visual Web Developer now has built-in support for editing and updating remote web projects using the standard File Transfer Protocol (FTP). You can quickly connect to a remote Web site using FTP within the New Web Site and Open Web Site dialog box.

Q9. What is precompilation in ASP.NET 2.0? What is a pre-compiled website?

A9. When the first request arrives at your web application there is a mind-numbing amount of work to do. The worker process starts, the runtime initializes, ASPX pages are parsed and compiled to intermediate language, methods are just-in-time compiled to native code - and the list goes on and on. If you want to cut out some of the overhead and improve the startup time of your application, then you’ll want to look at the precompile features in ASP.NET 2.0.

Although pre-compilation will give our site a performance boost, the difference in speed will only be noticeable during the first request to each folder. Perhaps a more important benefit is the new deployment option made available by the precompile - the option to deploy a site without copying any of the original source code to the server. This includes the code and markup in aspx, ascx, and master files.

There are 2 types of pre-compilation:
(i) In Place Precompilation
(ii) Precompilation for Deployment

In Place Precompilation -> By default, ASP.NET dynamically parses and compiles all the ASPX pages in a folder when the first request arrives for a page inside that folder. ASP.NET also needs to compile applicable files in the special folders, like App_Code, on the first request, and any code-behind files associated with ASPX and ASCX files. The runtime caches all the compilation results in order to quickly process later requests, and does not need to recompile again unless someone edits a file. This behavior gives us a great deal of flexibility, including the flexibility to change code and arkup and instantly have the changes reflected in the next browser request.

The price for this flexibility is the performance hit on the first request. Some people have found their ASP.NET applications to be slow starters. These people usually work in the sales department and perform software demos in front of customers. In place pre-compilation makes the “first hit” to a web application and forces all pages and code in the application to compile.

The tool to use for pre-compilation is the aspnet_compiler executable, which you can find in the %WINDIR%Microsoft.NETFrameworkv2.x.xxxx directory. If we have a web application in the WebSite1 virtual directory under IIS, we could use the following command line to compile the pplication.

C:WindowsMicrosoft.NETFrameworkv2.0.50215>aspnet_compiler -v /Website1

The –v parameter specifies that we are passing a virtual path to our web site. On servers with multiple websites you may need

to use the –m parameter and specify the full IIS metabase path to the application (-m /LM/W3SVC/1/Root/WebSite1).

The pre-compiled code will end up inside of the Temporary ASP.NET File directory, just as it would when the runtime compiles files for a browser request. Inside of the bin directory for the compiled site, you’ll find the assemblies (dll files). The compiler generates special filenames to avoid naming collisions. In the shot below, the dll starting with App_Code contains the code from the App_Code directory – not too surprising. Each folder containing aspx, or ascx files will compile into a dll prefixed with App_Web. The files with a .compiled extension contain XML with information about which original source code file maps to which assembly.

You may find these files in the following location of your computer.
C:windowsMicrosoft.NETFrameworkv2.0.50727Temporary ASP.NET Files

With the compiled files in place your web application should have a slightly better startup time, but a primary benefit to in place pre-compilation will be the ability to ensure the web application is error free. If you happen to modify a class or web form and leave an error in the file, the aspnet_compiler will fail and display the compiler error. The tool will also display any warnings, but warning will not stop compilation.
Pre-compilation For Deployment –> Pre-compilation for deployment creates an ‘executable’ (no source code) version of your web application. With pre-compilation for deployment you give the aspnet_compiler the path to your source code, and the path to a target directory for the compilation results, like below.

aspnet_compiler -p “C:MyDevelopmentWebSite1″ -v / C:MyStage

This command will compile the site and place the result in C:Staging. You must still specify –v as a parameter, even though we are not using a virtual path as either a source or a destination. Instead, the compiler will use this parameter to resolve application root references (~).

The pre-compilation for deployment step will recreate your web site’s folder structure in the destination directory. All of the static files (HTML files, image files, configuration files) are copied into the folder structure exactly as they appear in the source folder hierarchy. A bin directory will appear in the target directory with all of the assemblies and .compiled files.

The target directory will contain no source code. All of the classes in the App_Code folder are now compiled into one or more assemblies in the bin directory, and no .cs or .vb files will exist in the target directory. Master page files will also compile to the bin directory and not exist. All the code and markup in ASPX, ASCX, and ASHX files, along with any associated code-behind files, will live inside of one or more assemblies in the bin directory, although these files will still exist in the target directory, they exist as nearly empty ‘marker’ files. If you open an ASPX file in a pre-compiled target directory you’ll see the following content:

This is a marker file generated by the precompilation tool, and should not be deleted!

Once the application finishes compiling you can FTP or XCOPY the target directory to a web server (or map a virtual directory to the target directory), and the application will be ready to run. A benefit to pre-compilation for deployment is that no one can make changes to the web application by tweaking the source code – no source code exists! In fact, you can’t even place a new ASPX file into the existing application directory structure without causing an error.

Q10. If a web application is pre-compiled, How do you make changes to it?

A10. Making a change to your site will require you to make a change in the original source code, pre-compile the application again, and redeploy all files to the server.

When we recompile an already pre-compiled website, what should be kept in mind?

Pre-compilation generates unique filenames for some assemblies in the bin folder, and these filenames will change each time the pre-compiler executes. The first time you run aspnet_compiler you might see App_Web_murhs6vm.dll in the bin directory, the next time you might see App_Web_gvohdjw.dll with the same compiled code, even though no source file has changed. This means you might have unneeded dlls in your bin directory if you keep repeatedly copy files to the server without cleanup.¼br>
Q11. Is Visual Web Developer XHTML compliant?

A11. Yes.

Q12. What are server controls?

A12. ASP.NET pages can contain server controls, which are programmable server-side objects that typically represent a UI element in the page, such as a textbox or image. Server controls participate in the execution of the page and produce their own markup rendering to the client. The principle advantage of server controls is that they enable developers to get complex rendering and behaviors from simple building-block components, dramatically reducing the amount of code it takes to produce a dynamic Web page. Another advantage of server controls is that it is easy to customize their rendering or behavior. Server controls expose properties that can be set either declaratively (on the tag) or programmatically (in code). Server controls (and the page itself) also expose events that developers can handle to perform specific actions during the page execution or in response to a client-side action that posts the page back to the server (a “postback”). Server controls also simplify the problem of retaining state across round-trips to the server, automatically retaining their values across successive postbacks.

Server controls are declared within an .aspx file using custom tags or intrinsic HTML tags that contain a runat=”server” attribute value. Intrinsic HTML tags are handled by one of the controls in the System.Web.UI.HtmlControls namespace. Any tag that doesn’t explicitly map to one of the controls is assigned the type of System.Web.UI.HtmlControls.HtmlGenericControl.

Q13. How do server control handle events?

A13. ASP.NET server controls can optionally expose and raise server events, which can be handled by page developers. A page developer may accomplish this by declaratively wiring an event to a control (where the attribute name of an event wireup indicates the event name and the attribute value indicates the name of a method to call).

Sub EnterBtn_Click(Sender As Object, E As EventArgs)
Message.Text = “Hi ” & Name.Text & “, wazzup there!”
End Sub

Q14. How to Navigate to another page?

A14. The following sample demonstrates how to use the <asp:hyperlink runat=server> control to navigate to another page (passing custom query string parameters along the way). The sample then demonstrates how to easily get access to these query string parameters from the target page.

<asp:hyperlink id=”hl_Link” runat=server text=”click here” NavigateUrl=”www.somelink.com“>
</asp:hyperlink>

This navigation triggers when a click is made on the hyperlink. If we want navigation to trigger through code, we may use response.redirect(URL) or server.transfer(URL)

Q15. What is Simplified Code Behind Model in ASP.NET 2.0?

A15. ASP.NET 2.0 introduces an improved runtime for code-behind pages that simplifies the connections between the page and code. In this new code-behind model, the page is declared as a partial class, which enables both the page and code files to be compiled into a single class at runtime. The page code refers to the code-behind file in the CodeFile attribute of the <%@ Page %> directive, specifying the class name in the Inherits attribute. Note that members of the code behind class must be either public or protected (they cannot be private).

Example

Codebehind

Partial Class CodeBehind_vb_aspx
Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Label1.Text = “Hello ” & TextBox1.Text
End Sub
End Class





Inline Code

<%@ page language=”VB” CodeFile=”CodeBehind_vb.aspx.vb” Inherits=”CodeBehind_vb_aspx” %>

<html>
<head>
<title>ASP.NET CodeBehind Pages</title>
</head>
<body>
<form runat=”server”>
<h1>Welcome to ASP.NET 2.0!</h1>
<b>Enter Your Name:</b>
<asp:TextBox ID=”TextBox1″ Runat=”server”/>
<asp:Button ID=”Button1″ Text=”Click Me” OnClick=”Button1_Click” Runat=”server”/>
<br />
<br />
<asp:Label ID=”Label1″ Text=”Hello” Runat=”server” />
</form>
</body>
</html>

Q16. Whats the advantage of Simplified Code Behind model?

A16. The advantage of the simplified code-behind model over previous versions is that you do not need to maintain separate declarations of server control variables in the code-behind class. Using partial classes (new in 2.0) allows the server control IDs of the ASPX page to be accessed directly in the code-behind file. This greatly simplifies the maintenance of code-behind pages.

Q17. Whats the use of App_Code directory in ASP.NET 2.0?

A17. Just as pages can be compiled dynamically at runtime, so can arbitrary code files (for example .cs or .vb files). ASP.NET 2.0 introduces the App_Code directory, which can contain standalone files that contain code to be shared across several pages in your application. Unlike ASP.NET 1.x, which required these files to be precompiled to the Bin directory, any code files in the App_Code directory will be dynamically compiled at runtime and made available to the application. It is possible to place files of more than one language under the App_Code directory, provided they are partitioned in subdirectories (registered with a particular language in Web.config).

Q18. Can we put code created in different languages in the same App_Code directory?

A18. By default, the App_Code directory can only contain files of the same language. However, you may partition the App_Code directory into subdirectories (each containing files of the same language) in order to contain multiple languages under the

App_Code directory. To do this, you need to register each subdirectory in the Web.config file for the application.

<configuration>
<system.web>
<compilation>
<codeSubDirectories>
<add directoryName=”Subdirectory”/>
</codeSubDirectories>
</compilation>
</system.web>
</configuration>

Q19. Whats the difference between Bin folder and App_Code folder?

A19. The Bin directory is like the Code directory, except it can contain precompiled assemblies. This is useful when you need to use code that is possibly written by someone other than yourself, where you don’t have access to the source code (VB or C# file) but you have a compiled DLL instead. Simply place the assembly in the Bin directory to make it available to your site.

By default, all assemblies in the Bin directory are automatically loaded in the app and made accessible to pages. You may need to Import specific namespaces from assemblies in the Bin directory using the @Import directive at the top of the page.

<@ Import Namespace=”MyCustomNamespace”>

Q20. How to register Assemblies in GAC (Global Assembly Cache)?

A20. The .NET Framework 2.0 includes a number of assemblies that represent the various parts of the Framework. These assemblies are stored in the global assembly cache, which is a versioned repository of assemblies made available to all applications on the machine (not just a specific application, as is the case with Bin and App_Code). Several assemblies in the Framework are automatically made available to ASP.NET applications. You can register additional assemblies by registration in a Web.config file in your application.

<configuration>
<compilation>
<assemblies>
<add assembly=”System.Data, Version=1.0.2411.0,
Culture=neutral,
PublicKeyToken=b77a5c561934e089″/>
</assemblies>
</compilation>
</configuration>

Note that you still need to use an @Import directive to make the namespaces in these assemblies available to individual pages.

Q21. Can we bind data to Server Controls without writing code in ASP.NET 2.0?

A21. Yes. ASP.NET 2.0 enables a declarative solution for data binding which requires no code at all for the most common data scenarios, such as:
Selecting and displaying data
Sorting, Paging and Caching Data
Updating, Inserting and Deleting Data
Filtering or Master-Details Using Parameters

ASP.NET 2.0 introduces two types of server controls that participate in this declarative data binding model. These two types of data controls handle the complexity of the stateless Web model for data scenarios, so developers don’t need to understand page request lifecycle events just to perform data binding. Another benefit of this control-based model is that it can be easily extended to support additional data access storage providers.

Q22. What are data source controls?

A22. Data source controls have no rendering, but instead represent a particular backend data store, for example a database, business object, XML file, or XML Web Service. Data source controls also enable rich capabilities over data - such as sorting, paging, filtering, updating, deleting, and inserting - that data-bound UI controls can automatically use. ASP.NET includes the following server controls out-of-the-box:

SqlDataSource Enables binding to a SQL database represented by an ADO.NET provider, such as Microsoft™ SQL Server, OLEDB, ODBC, or Oracle.
ObjectDataSource Enables binding to a middle-tier object such as a data access layer or business component.
AccessDataSource Enables binding to a Microsoft™ Access (Jet) database.
SiteMapDataSource Enables binding to the hierarchy exposed by an ASP.NET 2.0 site navigation provider.
XmlDataSource Enables binding to an XML file or document.

Q23. What are data bound controls?

A23. Data-bound controls are UI controls that render data as markup to the requesting client device or browser. A data-bound control can auto-bind to data exposed from a data source and will fetch data at the appropriate time in the page request lifecycle. These controls can optionally take advantage of data source capabilities such as sorting, paging, filtering, updating, deleting, and inserting. A data-bound control connects to a data source control through its DataSourceID property.

You may be familiar with some of the data-bound controls in ASP.NET v1.x, such as DataGrid, DataList, Repeater, and list controls like DropDownList. ASP.NET 2.0 contains several new data-bound controls as well, such as:

GridView Renders data in a grid format. This control is an evolution of the DataGrid control, and can automatically take advantage of data source capabilities.
DetailsView Renders a single data item in a table of label/value pairs, similar to the form view in Microsoft™ Access. This control can also automatically take advantage of data source capabilities.
FormView Renders a single data item at a time in a form defined by a custom template. Renders a single data item in a table of label/value pairs, similar to the form view in Microsoft™ Access. This control can also automatically take advantage of data source capabilities.
TreeView Renders data in a hierarchical tree view of expandable nodes.
Menu Renders data in a hierarchical dynamic menu (including flyouts).

Q24. What is a Master Page? How do we use it?

A24. A Master Page is a page that contains markup and controls that should be shared across multiple pages in your site. For example, if all of your pages should have the same header and footer banners or the same navigation menu, you could define this in a Master Page once, and then all pages associated to this Master Page would inherit those common elements. The advantage of defining the header, footer, and navigation in a Master Page is that these elements need only be defined once, instead of multiple times in duplicate code across the pages in your site.

Defining a Master Page is just like defining a normal page. Master Pages can contain markup, controls, or code, or any combination of these elements. However, a Master Page can contain a special type of control, called a ContentPlaceHolder control. A ContentPlaceHolder defines a region of the master page rendering that can be substituted with content from a page associated to the master. A ContentPlaceHolder can also contain default content, just in case the derive page does not need to override this content. The syntax of a ContentPlaceHolder control is given below:

<%– ContentPlaceHolder control –%>
<asp:contentplaceholder id=”FlowerText” runat=”server”/>

<%– ContentPlaceHolder with default content –%>
<asp:contentplaceholder id=”FlowerText” runat=”server”>
<h3>Welcome to my florist website!</h3>
</asp:contentplaceholder>

To differentiate a Master Page from a normal page, a Master Page is saved under the .master file extension. A page can derive from a Master Page by defining a MasterPageFile attribute on its Page directive, as demonstrated below. A page that is associated to a Master Page is called a Content Page.

<%@ Page MasterPageFile=”Site.master” %>

Q25. What is a Content Page? How do we use it?

A25. A Content Page can declare Content controls that specifically override content placeholder sections in the Master Page. A Content control is associated to a particular ContentPlaceHolder control through its ContentPlaceHolderID property. A Content Page may only contain markup and controls inside Content controls; it cannot have any top-level content of its own. It can, however, have directives or server-side code.

<%@ Page MasterPageFile=”Site.master” %>

<asp:content id=”Content1″ contentplaceholderid=”FlowerText” runat=”server”>
Santa Clause will definitely meet you this Christmas!
</asp:content>
<asp:content id=”Content2″ contentplaceholderid=”FlowerPicture” runat=”server”>
<asp:Image id=”image1″ imageurl=”~/images/santa.jpg” runat=”server”/>
</asp:content>





Q26. How does Content page access a master page?

A26. In addition to overriding content, it is possible for a Content Page to programmatically access its Master Page. A Content Page creates a strongly-typed reference to the Master Page using the <%@ MasterType %> directive, specifying the virtual path to the master page:

<%@ MasterType VirtualPath=”Site.master” %>

The Content Page can then reference the Master Page using the Master property of the Page class:

Master.FooterText = “This is my custom footer”
Dim adr As AdRotator = Master.FindControl(”MyAdRotator”)

In the code example above, FooterText is a public property exposed on the Master Page, while MyAdRotator is a control on the Master Page.

Q27. Can we have multiple number of Master pages in an ASP.NET 2.0 web application?

A27. Yes.

Q28. Can we have multiple SiteMapPath controls in an ASP.NET 2.0 web application?

A28. Yes.

Q29. How to create a read-only Data Report using GridView?

A29. The simplest type of data-driven page is a read-only report, which displays data but does not allow the user to manipulate the presentation or modify the data. To create a read-only report against a SQL database, first configure a SqlDataSource on the page and then connect a data-bound control such as GridView to the data source by specifying its DataSourceID property. The example below shows a GridView control associated to a SqlDataSource control.

<form runat=”server”>
<asp:GridView ID=”GridView1″ DataSourceID=”SqlDataSource1″ runat=”server”/>
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”
SelectCommand=”SELECT [au_id], [au_lname], [au_fname] FROM [authors]”
ConnectionString=”<%$ ConnectionStrings:Pubs %>” />
</form>

The SqlDataSource ConnectionString property specifies the connection string to the database and the SelectCommand property specifies the query to execute to retrieve data. The connection string can be specified literally in the page, but in this case the property is assigned using a new expression syntax that retrieves the value from Web.config.

<configuration>
<connectionStrings>
<add name=”Pubs” connectionString=”Server=(local);Integrated Security=True;Database=UrDatabaseName;”
providerName=”System.Data.SqlClient” />
</connectionStrings>
</configuration>

Q30. How do we sort data in a GridView?

A30. The SqlDataSource control supports sorting when its DataSourceMode property is set to “DataSet”. To enable the sorting UI in the GridView, set the AllowSorting property to true. This causes the GridView to render link buttons for its column headers that can be clicked to sort a column. The GridView control passes the SortExpression associated with the column field to the data source control, which returns the sorted data to the GridView.
Q31. Can we sort data from a SQLDataSource when mode is set to DataReader?

A31. No. Sorting is only supported by SqlDataSource when in DataSet mode.

Inline Code looks like this…

<asp:GridView ID=”GridView1″ AllowSorting=”true” runat=”server” DataSourceID=”SqlDataSource1″
AutoGenerateColumns=”False”>
<Columns>
<asp:BoundField HeaderText=”ID” DataField=”au_id” SortExpression=”au_id” />
<asp:BoundField HeaderText=”Last Name” DataField=”au_lname” SortExpression=”au_lname” />
<asp:BoundField HeaderText=”First Name” DataField=”au_fname” SortExpression=”au_fname” />
<asp:BoundField HeaderText=”Phone” DataField=”phone” SortExpression=”phone” />
<asp:BoundField HeaderText=”Address” DataField=”address” SortExpression=”address” />
<asp:BoundField HeaderText=”City” DataField=”city” SortExpression=”city” />
<asp:BoundField HeaderText=”State” DataField=”state” SortExpression=”state” />
<asp:BoundField HeaderText=”Zip Code” DataField=”zip” SortExpression=”zip” />
<asp:CheckBoxField HeaderText=”Contract” SortExpression=”contract” DataField=”contract” />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”
SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors]”
ConnectionString=”<%$ ConnectionStrings:Pubs %>” />

Q32. How do we enable paging in a GridView?

A32. You can enable paging UI in the GridView by setting the AllowPaging property to true. The GridView can automatically page over any return value from a data source that supports the ICollection interface. The DataView returned by SqlDataSource when in DataSet mode supports this interface, so GridView can page over the result. When in DataReader mode, the GridView cannot page over the data returned by SqlDataSource.

Inline Code looks like this…

<asp:GridView ID=”GridView1″ AllowSorting=”true” AllowPaging=”true” PageSize=”3″ runat=”server”
DataSourceID=”SqlDataSource1″ AutoGenerateColumns=”False”>
<PagerSettings Mode=”NextPreviousFirstLast” Position=”TopAndBottom” FirstPageImageUrl=”~/Images/First.gif”
LastPageImageUrl=”~/Images/Last.gif” NextPageImageUrl=”~/Images/Next.gif” PreviousPageImageUrl=”~/Images/Prev.gif” />
<PagerStyle ForeColor=”White” HorizontalAlign=”Right” BackColor=”#284775″ />
<Columns>
<asp:BoundField HeaderText=”ID” DataField=”au_id” SortExpression=”au_id” />
<asp:BoundField HeaderText=”Last Name” DataField=”au_lname” SortExpression=”au_lname” />
<asp:BoundField HeaderText=”First Name” DataField=”au_fname” SortExpression=”au_fname” />
<asp:BoundField HeaderText=”Phone” DataField=”phone” SortExpression=”phone” />
<asp:BoundField HeaderText=”Address” DataField=”address” SortExpression=”address” />
<asp:BoundField HeaderText=”City” DataField=”city” SortExpression=”city” />
<asp:BoundField HeaderText=”State” DataField=”state” SortExpression=”state” />
<asp:BoundField HeaderText=”Zip Code” DataField=”zip” SortExpression=”zip” />
<asp:CheckBoxField HeaderText=”Contract” SortExpression=”contract” DataField=”contract” />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors]”
ConnectionString=”<%$ ConnectionStrings:Pubs %>” />

Q33. How do we set the number of Records in a GridView to display?

A33. Use the PageSize property. It Gets or sets the number of records to display on a page in a GridView control.

Q34. What is the TopPagerRow property of a GridView?

A34. Gets a GridViewRow object that represents the top pager row in a GridView control.

Q35. Describe the Hotspot class?

A35. It implements the basic functionality common to all hot spot shapes. Its Namespace: System.Web.UI.WebControls

You cannot directly create instances of the abstract HotSpot class. Instead, this class is inherited by the CircleHotSpot, RectangleHotSpot, and PolygonHotSpot classes to provide the common basic functionality for a hot spot. You must derive from the HotSpot class to create a custom hot spot class that represents a unique shape that you define. However, you can define most shapes using the CircleHotSpot, RectangleHotSpot, and PolygonHotSpot classes. Its used in an ImageMap control.

Q36. What is ImageMap Control?

A36. It is a control that displays an image on a page. When a hot spot region that is defined within the ImageMap control is clicked, the control either generates a postback to the server or navigates to a specified URL.

Inline code example…

<asp:ImageMap
AccessKey=”string”
AlternateText=”string”
BackColor=”color name|#dddddd”
BorderColor=”color name|#dddddd”
BorderStyle=”NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|
Inset|Outset”
BorderWidth=”size”
CssClass=”string”
DescriptionUrl=”uri”
Enabled=”True|False”
EnableTheming=”True|False”
EnableViewState=”True|False”
ForeColor=”color name|#dddddd”
GenerateEmptyAlternateText=”True|False”
Height=”size”
HotSpotMode=”NotSet|Navigate|PostBack|Inactive”
ID=”string”
ImageAlign=”NotSet|Left|Right|Baseline|Top|Middle|Bottom|
AbsBottom|AbsMiddle|TextTop”
ImageUrl=”uri”
OnClick=”Click event handler”
OnDataBinding=”DataBinding event handler”
OnDisposed=”Disposed event handler”
OnInit=”Init event handler”
OnLoad=”Load event handler”
OnPreRender=”PreRender event handler”
OnUnload=”Unload event handler”
runat=”server”
SkinID=”string”
Style=”string”
TabIndex=”integer”
Target=”string”
ToolTip=”string”
Visible=”True|False”
Width=”size”
>
<asp:CircleHotSpot
AccessKey=”string”
AlternateText=”string”
HotSpotMode=”NotSet|Navigate|PostBack|Inactive”
NavigateUrl=”uri”
PostBackValue=”string”
Radius=”integer”
TabIndex=”integer”
Target=”string|_blank|_parent|_search|_self|_top”
X=”integer”
Y=”integer” />
<asp:PolygonHotSpot
AccessKey=”string”
AlternateText=”string”
Coordinates=”string”
HotSpotMode=”NotSet|Navigate|PostBack|Inactive”
NavigateUrl=”uri”
PostBackValue=”string”
TabIndex=”integer”
Target=”string|_blank|_parent|_search|_self|_top”
/>
<asp:RectangleHotSpot
AccessKey=”string”
AlternateText=”string”
Bottom=”integer”
HotSpotMode=”NotSet|Navigate|PostBack|Inactive”
Left=”integer”
NavigateUrl=”uri”
PostBackValue=”string”
Right=”integer”
TabIndex=”integer”
Target=”string|_blank|_parent|_search|_self|_top”
Top=”integer” />
</asp:ImageMap>





Q37. How do we Update & Delete data in a GridView?

A37. GridView control can automatically render UI for modifying data through Update and Delete operations, provided the associated data source is configured to support these capabilities. The SqlDataSource control supports Update operations when its UpdateCommand property is set and Delete operations when its DeleteCommand property is set to a valid update or delete command or stored procedure. The UpdateCommand or DeleteCommand should contain parameter placeholders for each value that will be passed by the GridView control (more on this below). You can also specify an UpdateParameters or DeleteParameters collection to set properties for each parameter, such as the parameter data type, input/output direction, or default value.

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”
ConnectionString=”<%$ ConnectionStrings:Pubs %>”
SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors]”
UpdateCommand=”UPDATE [authors] SET [au_lname] = @au_lname, [au_fname] = @au_fname, [state] = @state WHERE [au_id] =
@au_id”
DeleteCommand=”DELETE FROM [authors] WHERE [au_id] = @au_id”/>

To enable the UI in the GridView for Updates or Deletes, you can either set the AutoGenerateEditButton and AutoGenerateDeleteButton properties to true, or you can add a CommandField to the GridView control and enable its ShowEditButton and ShowDeleteButton properties. The GridView supports editing or deleting one row at a time. For editing, the user places the row in edit mode by clicking the Edit button, and then confirms the Update by clicking the Update button while the row is in edit mode. The user can also click the Cancel button to abort the edit operation and return to read-only mode.

Inline code example…

<asp:GridView ID=”GridView1″ AllowSorting=”true” AllowPaging=”true” Runat=”server”
DataSourceID=”SqlDataSource1″ AutoGenerateEditButton=”true” DataKeyNames=”au_id”
AutoGenerateColumns=”False”>
<Columns>
<asp:BoundField ReadOnly=”true” HeaderText=”ID” DataField=”au_id” SortExpression=”au_id” />
<asp:BoundField HeaderText=”Last Name” DataField=”au_lname” SortExpression=”au_lname” />
<asp:BoundField HeaderText=”First Name” DataField=”au_fname” SortExpression=”au_fname” />
<asp:BoundField HeaderText=”Phone” DataField=”phone” SortExpression=”phone” />
<asp:BoundField HeaderText=”Address” DataField=”address” SortExpression=”address” />
<asp:BoundField HeaderText=”City” DataField=”city” SortExpression=”city” />
<asp:BoundField HeaderText=”State” DataField=”state” SortExpression=”state” />
<asp:BoundField HeaderText=”Zip Code” DataField=”zip” SortExpression=”zip” />
<asp:CheckBoxField HeaderText=”Contract” SortExpression=”contract” DataField=”contract” />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1″ Runat=”server” SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [phone],
[address], [city], [state], [zip], [contract] FROM [authors]”
UpdateCommand=”UPDATE [authors] SET [au_lname] = @au_lname, [au_fname] = @au_fname, [phone] = @phone, [address] =
@address, [city] = @city, [state] = @state, [zip] = @zip, [contract] = @contract WHERE [au_id] = @au_id”
ConnectionString=”<%$ ConnectionStrings:Pubs %>” />

Notice the naming convention for parameters in the Update statement assigned to UpdateCommand. The automatic capability of GridView and other data-bound controls to invoke the Update operation relies on this naming convention in order to work.

Parameters are expected to be named the same as the associated field values returned by the SelectCommand. Using this naming convention makes it possible to align the values passed by the data-bound control to the data source with the parameters in the SQL update statement.

Q38. What is the DataKeyNames property?

A38. An important property that plays a special role in Update and Delete operations is the DataKeyNames property. This property is typically set to the names of fields from the data source that are part of a primary key used to match a given row in the data source. Multiple keys are comma-separated when specifying this property declaratively, although it is common to only have one primary key field. The values of fields specified by the DataKeyNames property are round-tripped in viewstate for the sake of retaining original values to pass to an Update or Delete operation, even if that field is not rendered as one of the columns in the GridView control. When the GridView invokes the data source Update or Delete operation, it passes the values of these fields to the data source in a special Keys dictionary, separate from the Values dictionary that contains new values entered by the user while the row is in edit mode (for update operations). The contents of the Values dictionary are obtained from the input controls rendered for the row in edit mode. To exclude a value from this dictionary, set the ReadOnly property to true on the corresponding BoundField in the Columns collection. If you are using the GridView designer in Visual Studio, the ReadOnly property is set to true for primary key fields by default.

Q39. How do we filter GridView data in ASP.NET 2.0 as compared to Datagrid in ASP.NET 1.1?

A39. A common scenario in data-driven pages is the ability to filter data in a report. For example, suppose the user could select from a set of field values in a DropDownList to filter the report grid to only display rows with a matching field value. In ASP.NET v1.x, you would have needed to perform the following steps in code:
Cancel databinding in Page_Load if the request is a postback
Handle SelectedIndexChanged event
Add DropDownList SelectedValue to command’s Parameters collection
Execute the command and call DataBind

In ASP.NET 2.0, this code is eliminated through the use of declarative Data Parameter objects. A data parameter allows external values to be declaratively associated with data source operations. These parameters are usually associated with a variable in a command expression or property, for example a parameter in a SQL statement or stored procedure for

SqlDataSource. Data source controls expose parameter collection properties that can contain parameter objects for each supported data operation. For example:

<asp:DropDownList ID=”DropDownList1″ … runat=”server”/>

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”
ConnectionString=”<%$ ConnectionStrings:Pubs %>”
SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors] WHERE [state] = @state”>
<SelectParameters>
<asp:ControlParameter Name=”state” ControlID=”DropDownList1″ PropertyName=”SelectedValue” />
</SelectParameters>
</asp:SqlDataSource>

Inline code example…

<asp:GridView ID=”GridView1″ AllowSorting=”True” AllowPaging=”True” Runat=”server”
DataSourceID=”SqlDataSource1″ AutoGenerateEditButton=”True” DataKeyNames=”au_id”
AutoGenerateColumns=”False”>
<Columns>
<asp:BoundField ReadOnly=”true” HeaderText=”ID” DataField=”au_id” SortExpression=”au_id” />
<asp:BoundField HeaderText=”Last Name” DataField=”au_lname” SortExpression=”au_lname” />
<asp:BoundField HeaderText=”First Name” DataField=”au_fname” SortExpression=”au_fname” />
<asp:BoundField HeaderText=”Phone” DataField=”phone” SortExpression=”phone” />
<asp:BoundField HeaderText=”Address” DataField=”address” SortExpression=”address” />
<asp:BoundField HeaderText=”City” DataField=”city” SortExpression=”city” />
<asp:BoundField HeaderText=”State” DataField=”state” SortExpression=”state” />
<asp:BoundField HeaderText=”Zip Code” DataField=”zip” SortExpression=”zip” />
<asp:CheckBoxField HeaderText=”Contract” SortExpression=”contract” DataField=”contract” />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1″ Runat=”server” SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [phone],

[address], [city], [state], [zip], [contract] FROM [authors] WHERE [state] = @state”
UpdateCommand=”UPDATE [authors] SET [au_lname] = @au_lname, [au_fname] = @au_fname, [phone] = @phone, [address] =

@address, [city] = @city, [state] = @state, [zip] = @zip, [contract] = @contract WHERE [au_id] = @au_id”
ConnectionString=”<%$ ConnectionStrings:Pubs %>”>
<SelectParameters>
<asp:QueryStringParameter Name=”state” QueryStringField=”state” DefaultValue=”CA” />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name=”au_lname” />
<asp:Parameter Name=”au_fname” />
<asp:Parameter Name=”phone” />
<asp:Parameter Name=”address” />
<asp:Parameter Name=”city” />
<asp:Parameter Name=”state” />
<asp:Parameter Name=”zip” />
<asp:Parameter Name=”contract” />
<asp:Parameter Name=”au_id” />
</UpdateParameters>
</asp:SqlDataSource>





Q40. How do we enabling Caching for a DataSource Control?

A40. To enable caching for the SqlDataSource control (and also ObjectDataSource), set the EnableCaching property to true. You can specify the length of time (in seconds) to store an entry in the cache using the CacheDuration property. You can also set the CacheExpirationPolicy property to either Sliding or Absolute just as you can do from the cache API. Caching is only supported on the SqlDataSource control when the DataSourceMode property is set to “DataSet”. For example, if you set CacheDuration to 5 and SlidingExpiration to Absolute, the SqlDataSource will retrieve data from the database on the first request to the page and store this data in the cache. For subsequent requests, the SqlDataSource will attempt to retrieve the cache entry to serve the request without going back to the original database. After 5 seconds (or perhaps earlier, if cache memory pressure is high), the cache entry will be purged and a subsequent request to the page causes SqlDataSource to go back to the database again (repeating the caching process with the new data).

If you instead set CacheDuration to 5 and SlidingExpiration to Sliding, the cached data will have its time-to-live periodically refreshed as long as the data source requests the cached data once every 5 seconds. If a page requests the cached data at least once every 5 seconds, and there is no cache memory pressure, the cached data effectively remains in the cache forever. On the other hand, if no requests are made for the cached data within a 5 second time period, then the cached item is purged and the next time a request occurs the SqlDataSource control will go back to the original database again.

The example below demonstrates caching with the SqlDataSource control. The TimeStamp column updates each time the query is executed, so you can see how often the data is retrieved from the database versus retrieved from the cache. Note that approximately every five seconds, the TimeStamp updates.

Inline Code Example of Caching…

<asp:DropDownList ID=”DropDownList1″ DataSourceID=”SqlDataSource2″ AutoPostBack=”true”
DataTextField=”state” Runat=”server” />
<asp:SqlDataSource ID=”SqlDataSource2″ Runat=”server” SelectCommand=”SELECT DISTINCT [state] FROM [authors]”
ConnectionString=”<%$ ConnectionStrings:Pubs %>” />
<br />
<br />
<asp:GridView ID=”GridView1″ AllowSorting=”True” AllowPaging=”True” Runat=”server”
DataSourceID=”SqlDataSource1″ AutoGenerateEditButton=”True” DataKeyNames=”au_id”
AutoGenerateColumns=”False”>
<Columns>
<asp:BoundField DataField=”TimeStamp” HeaderText=”TimeStamp” ReadOnly=”True”>
<ItemStyle Font-Bold=”True” />
</asp:BoundField>
<asp:BoundField ReadOnly=”True” HeaderText=”ID” DataField=”au_id” SortExpression=”au_id” />
<asp:BoundField HeaderText=”Last Name” DataField=”au_lname” SortExpression=”au_lname” />
<asp:BoundField HeaderText=”First Name” DataField=”au_fname” SortExpression=”au_fname” />
<asp:BoundField HeaderText=”Phone” DataField=”phone” SortExpression=”phone” />
<asp:BoundField HeaderText=”Address” DataField=”address” SortExpression=”address” />
<asp:BoundField HeaderText=”City” DataField=”city” SortExpression=”city” />
<asp:BoundField HeaderText=”State” DataField=”state” SortExpression=”state” />
<asp:BoundField HeaderText=”Zip Code” DataField=”zip” SortExpression=”zip” />
<asp:CheckBoxField HeaderText=”Contract” SortExpression=”contract” DataField=”contract” />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1″ Runat=”server” SelectCommand=”SELECT DatePart(second, GetDate()) As TimeStamp,

[au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors] WHERE [state] =

@state”
UpdateCommand=”UPDATE [authors] SET [au_lname] = @au_lname, [au_fname] = @au_fname, [phone] = @phone, [address] =
@address, [city] = @city, [state] = @state, [zip] = @zip, [contract] = @contract WHERE [au_id] = @au_id”
ConnectionString=”<%$ ConnectionStrings:Pubs %>” CacheDuration=”5″ EnableCaching=”True”>
<SelectParameters>
<asp:ControlParameter Name=”state” ControlID=”DropDownList1″ />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name=”au_lname” />
<asp:Parameter Name=”au_fname” />
<asp:Parameter Name=”phone” />
<asp:Parameter Name=”address” />
<asp:Parameter Name=”city” />
<asp:Parameter Name=”state” />
<asp:Parameter Name=”zip” />
<asp:Parameter Name=”contract” />
<asp:Parameter Name=”au_id” />
</UpdateParameters>
</asp:SqlDataSource>

Q41. How to do a language switch in the Masterpage?

A41. Declare a dropdown as usual in the master page. Instead of overriding the InitializeCulture() place the same code in the Application_BeginRequest event handler in the global.asax. It is very similar to InitializeCulture() in the sense that it occurs early and no controls are ready yet. We have a little problem though, now the control is declared in a template and its name and id attributes rendered differently.

Another collection like the form variables collection that is also not originally server collection is the cookies collection. I use the cookie but it can be any of the ways for cross page communication that do not depend on server controls, like profile, session, querystring etc. We cannot use a cookie to carry the culture name value which comes from the dropdown selected item value, because the culture would always be a step behind. It would be set early on but later the dropdown selection change it but the resources for the previous culture come up. So normally only the page containing the dropdown would be a step behind, but because the dropdown is in the master page it appears that the whole site is ALWAYS ONE STEP BEHIND.

If, however, in the cookie, we pass the control name (which is information that never changes, so we can never be behind), instead of the culture name( which we can never keep up with), and then use that key to get the form variable value, we have pieced ourselves a workaround.

in the master page:

<asp:DropDownList runat=”server” ID=”DropDownList1″ AutoPostBack=”true”

OnSelectedIndexChanged=”DropDownList1_SelectedIndexChanged”>
<asp:ListItem Value=”en” Text=”English” />
<asp:ListItem Value=”fr” Text=”French” />
<asp:ListItem Value=”de” Text=”German” />
</asp:DropDownList>

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){
HttpCookie cookie = new HttpCookie(”DropDownName”);
cookie.Value=DropDownList1.UniqueID;
Response.SetCookie(cookie);
}

In global.asax

void Application_BeginRequest(Object sender, EventArgs e){
string lang = string.Empty;//default to the invariant culture
HttpCookie cookie = Request.Cookies["DropDownName"];

if (cookie != null && cookie.Value != null)
lang = Request.Form[cookie.Value];

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
}

Notice, there is absolutely no code in any of the content pages. Thats it ten lines of code and we are done for the whole site. This is not complete code, just a tip and trick of using master page and the .net event model to globalize code.
Q42. How to send a mail using System.Net.Mail?

Imports

System.Net.Mail
Public

Class MailHelper
”’ <summary>
”’ Sends an mail message
”’ </summary>
”’ <param name=”from”>Sender address</param>
”’ <param name=”recepient”>Recepient address</param>
”’ <param name=”bcc”>Bcc recepient</param>
”’ <param name=”cc”>Cc recepient</param>
”’ <param name=”subject”>Subject of mail message</param>
”’ <param name=”body”>Body of mail message</param>
Public Shared Sub SendMailMessage(ByVal from As String, ByVal recepient As String, ByVal bcc As String, ByVal cc As

String, ByVal subject As String, ByVal body As String)
‘ Instantiate a new instance of MailMessage
Dim mMailMessage As New MailMessage()
‘ Set the sender address of the mail message
mMailMessage.From = New MailAddress(from)
‘ Set the recepient address of the mail message
mMailMessage.To.Add(New MailAddress(recepient))

‘ Check if the bcc value is nothing or an empty string
If Not bcc Is Nothing And bcc <> String.Empty Then
‘ Set the Bcc address of the mail message
mMailMessage.Bcc.Add(New MailAddress(bcc))
End If

‘ Check if the cc value is nothing or an empty value
If Not cc Is Nothing And cc <> String.Empty Then
‘ Set the CC address of the mail message
mMailMessage.CC.Add(New MailAddress(cc))
End If

‘ Set the subject of the mail message
mMailMessage.Subject = subject
‘ Set the body of the mail message
mMailMessage.Body = body

‘ Set the format of the mail message body as HTML
mMailMessage.IsBodyHtml = True
‘ Set the priority of the mail message to normal
mMailMessage.Priority = MailPriority.Normal

‘ Instantiate a new instance of SmtpClient
Dim mSmtpClient As New SmtpClient()
‘ Send the mail message
mSmtpClient.Send(mMailMessage)
End Sub
End Class

Web.config

<?

xml version=”1.0″?>
<configuration>
<system.net>
<mailSettings>
<smtp from=”
defaultEmail@yourdomain.com“>
<network host=”smtp.yourdomain.com” port=”25″ userName=”yourUserName” password=”yourPassword”/>
</smtp>
</mailSettings>
</system.net>
</configuration>

Q43. Does the ASP.NET Development Server support running web pages from a computer other than the local computer?

A43. No. It will not serve pages to another computer. Additionally, it will not serve files that are outside of the application scope. The ASP.NET Development Server provides an efficient way to test pages locally before you publish the pages to a production server running IIS.

Q44. Whats the difference between running pages on ASP.NET Development Server and IIS?

A44. An important difference between the ASP.NET Development Server and IIS is the security context in which the respective servers run your ASP.NET pages. This difference can affect your testing because of differences in how the pages run.

When you run a page using the ASP.NET Development Server, the page runs in the context of your current user account. For example, if you are running as an administrator-level user, a page running in the ASP.NET Development Server will have administrator-level privileges. In contrast, in IIS, ASP.NET by default runs in the context of the special user (ASPNET or NETWORK SERVICES) that typically has limited privileges. The ASPNET or NETWORK SERVICES accounts are local to the server computer (not domain accounts), which restricts access to resources on other computers.

If you are simply reading and running the code in ASP.NET pages, this difference is not very important. However, the different security contexts for the two Web servers can affect your testing of the following:

  • Access to other resources that the page requires This can include reading and writing files other than Web pages, reading and writing the Windows registry, and so on.
  • Database access When working with the ASP.NET Development Server, you can typically rely on Windows Integrated authentication to access SQL Server. However, when the same page runs in IIS under the ASPNET or NETWORK SERVICES account, the page is running in the context of a local user, and you often have to configure the page to use a connection string that includes information about a user and password.
  • Code access security If your page involves access to resources that are protected under different zones, the page might run differently under the ASP.NET Development Server and IIS.

.NET Interview Questions

What is .NET?
.NET is essentially a framework for software development.It is similar in nature to any other software development framework (J2EE etc) in that it provides a set of runtime containers/capabilities, and a rich set of pre-built functionality in the form of class libraries and APIs
The .NET Framework is an environment for building, deploying, and running Web Services and other applications. It consists of three main parts: the Common Language Runtime, the Framework classes, and ASP.NET.1. How many languages .NET is supporting now?
When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl, etc. The site DotNetLanguages.Net says 44 languages are supported.

2. How is .NET able to support multiple languages?
A language should comply with the Common Language Runtime standard to become a .NET language. In .NET, code is compiled to Microsoft Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in .NET environment. So after compilation to this IL the language is not a barrier. A code can call or use a function written in another language.

3. How ASP .NET different from ASP?
Scripting is separated from the HTML, Code is compiled as a DLL, these DLLs can be executed on the server.

4. What is smart navigation?
The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed.

5. What is view state?
The web is stateless. But in ASP.NET, the state of a page is maintained in the in the page itself automatically. How? The values are encrypted and saved in hidden controls. this is done automatically by the ASP.NET. This can be switched off / on for a single control

6. How do you validate the controls in an ASP .NET page?
Using special validation controls that are meant for this. We have 6 Validation controls.

7. Can the validation be done in the server side? Or this can be done only in the Client side?
Client side is done by default. Server side validation is also possible. We can switch off the client side and server side can be done.

8. How to manage pagination in a page?
Using pagination option in DataGrid control. We have to set the number of records for a page, then it takes care of pagination by itself.




9. What is ADO .NET and what is difference between ADO and ADO.NET?
ADO.NET is stateless mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships between the tables and select insert and updates to the database. I can update the actual database as a batch.
11. Observations between VB.NET and VC#.NET?
Choosing a programming language depends on your language experience and the scope of the application you are building. While small applications are often created using only one language, it is not uncommon to develop large applications using multiple languages.
For example, if you are extending an application with existing XML Web services, you might use a scripting language with little or no programming effort. For client-server applications, you would probably choose the single language you are most comfortable with for the entire application. For new enterprise applications, where large teams of developers create components and services for deployment across multiple remote sites, the best choice might be to use several languages depending on developer skills and long-term maintenance expectations.

The .NET Platform programming languages - including Visual Basic .NET, Visual C#, and Visual C++ with managed extensions, and many other programming languages from various vendors - use .NET Framework services and features through a common set of unified classes. The .NET unified classes provide a consistent method of accessing the platform’s functionality. If you learn to use the class library, you will find that all tasks follow the same uniform architecture. You no longer need to learn and master different API architectures to write your applications.

In most situations, you can effectively use all of the Microsoft programming languages. Nevertheless, each programming language has its relative strengths and you will want to understand the features unique to each language. The following sections will help you choose the right programming language for your application.

Visual Basic .NET

Visual Basic .NET is the next generation of the Visual Basic language from Microsoft. With Visual Basic you can build .NET applications, including Web services and ASP.NET Web applications, quickly and easily. Applications made with Visual Basic are built on the services of the common language runtime and take advantage of the .NET Framework.

Visual Basic has many new and improved features such as inheritance, interfaces, and overloading that make it a powerful object-oriented programming language. Other new language features include free threading and structured exception handling. Visual Basic fully integrates the .NET Framework and the common language runtime, which together provide language interoperability, garbage collection, enhanced security, and improved versioning support. A Visual Basic support single inheritance and creates Microsoft intermediate language (MSIL) as input to native code compilers.

Visual Basic is comparatively easy to learn and use, and Visual Basic has become the programming language of choice for hundreds of thousands of developers over the past decade. An understanding of Visual Basic can be leveraged in a variety of ways, such as writing macros in Visual Studio and providing programmability in applications such as Microsoft Excel, Access, and Word.

Visual Basic provides prototypes of some common project types, including:

• Windows Application.
• Class Library.
• Windows Control Library.
• ASP.NET Web Application.
• ASP.NET Web Service.
• Web Control Library.
• Console Application.
• Windows Service.
• Windows Service.

Visual C# .NET

Visual C# (pronounced C sharp) is designed to be a fast and easy way to create .NET applications, including Web services and ASP.NET Web applications. Applications written in Visual C# are built on the services of the common language runtime and take full advantage of the .NET Framework.

C# is a simple, elegant, type-safe, object-oriented language recently developed by Microsoft for building a wide range of applications. Anyone familiar with C and similar languages will find few problems in adapting to C#. C# is designed to bring rapid development to the C++ programmer without sacrificing the power and control that are a hallmark of C and C++. Because of this heritage, C# has a high degree of fidelity with C and C++, and developers familiar with these languages can quickly become productive in C#. C# provides intrinsic code trust mechanisms for a high level of security, garbage collection, and type safety. C# supports single inheritance and creates Microsoft intermediate language (MSIL) as input to native code compilers.

C# is fully integrated with the .NET Framework and the common language runtime, which together provide language interoperability, garbage collection, enhanced security, and improved versioning support. C# simplifies and modernizes some of the more complex aspects of C and C++, notably namespaces, classes, enumerations, overloading, and structured exception handling. C# also eliminates C and C++ features such as macros, multiple inheritance, and virtual base classes. For current C++ developers, C# provides a powerful, high-productivity language alternative.

Visual C# provides prototypes of some common project types, including:

• Windows Application.
• Class Library.
• Windows Control Library.
• ASP.NET Web Application.
• ASP.NET Web Service.
• Web Control Library.
• Console Application.
• Windows Service.

12. Advantages of migrating to VB.NET ?
Visual Basic .NET has many new and improved language features — such as inheritance, interfaces, and overloading that make it a powerful object-oriented programming language. As a Visual Basic developer, you can now create multithreaded, scalable applications using explicit multithreading. Other new language features in Visual Basic .NET include structured exception handling, custom attributes, and common language specification (CLS) compliance.
The CLS is a set of rules that standardizes such things as data types and how objects are exposed and interoperate. Visual Basic .NET adds several features that take advantage of the CLS. Any CLS-compliant language can use the classes, objects, and components you create in Visual Basic .NET. And you, as a Visual Basic user, can access classes, components, and objects from other CLS-compliant programming languages without worrying about language-specific differences such as data types.CLS features used by Visual Basic .NET programs include assemblies, namespaces, and attributes.

These are the new features to be stated briefly:

Inheritance
Visual Basic .NET supports inheritance by allowing you to define classes that serve as the basis for derived classes. Derived classes inherit and can extend the properties and methods of the base class. They can also override inherited methods with new implementations. All classes created with Visual Basic .NET are inheritable by default. Because the forms you design are really classes, you can use inheritance to define new forms based on existing ones.

Exception Handling
Visual Basic .NET supports structured exception handling, using an enhanced version of the Try…Catch…Finally syntax supported by other languages such as C++.

Structured exception handling combines a modern control structure (similar to Select Case or While) with exceptions, protected blocks of code, and filters. Structured exception handling makes it easy to create and maintain programs with robust, comprehensive error handlers.

Overloading
Overloading is the ability to define properties, methods, or procedures that have the same name but use different data types. Overloaded procedures allow you to provide as many implementations as necessary to handle different kinds of data, while giving the appearance of a single, versatile procedure. Overriding Properties and Methods The Overrides keyword allows derived objects to override characteristics inherited from parent objects. Overridden members have the same arguments as the members inherited from the base class, but different implementations. A member’s new implementation can call the original implementation in the parent class by preceding the member name with MyBase.

Constructors and Destructors
Constructors are procedures that control initialization of new instances of a class. Conversely, destructors are methods that free system resources when a class leaves scope or is set to Nothing. Visual Basic .NET supports constructors and destructors using the Sub New and Sub Finalize procedures.




Data Types
Visual Basic .NET introduces three new data types. The Char data type is an unsigned 16-bit quantity used to store Unicode characters. It is equivalent to the .NET Framework System. Char data type. The Short data type, a signed 16-bit integer, was named Integer in earlier versions of Visual Basic. The Decimal data type is a 96-bit signed integer scaled by a variable power of 10. In earlier versions of Visual Basic, it was available only within a Variant.

Interfaces
Interfaces describe the properties and methods of classes, but unlike classes, do not provide implementations. The Interface statement allows you to declare interfaces, while the Implements statement lets you write code that puts the items described in the interface into practice.

Delegates
Delegates objects that can call the methods of objects on your behalf are sometimes described as type-safe, object-oriented function pointers. You can use delegates to let procedures specify an event handler method that runs when an event occurs. You can also use delegates with multithreaded applications. For details, see Delegates and the AddressOf Operator.

Shared Members
Shared members are properties, procedures, and fields that are shared by all instances of a class. Shared data members are useful when multiple objects need to use information that is common to all. Shared class methods can be used without first creating an object from a class.

References
References allow you to use objects defined in other assemblies. In Visual Basic .NET, references point to assemblies instead of type libraries. For details, see References and the Imports Statement. Namespaces Namespaces prevent naming conflicts by organizing classes, interfaces, and methods into hierarchies.

Assemblies
Assemblies replace and extend the capabilities of type libraries by, describing all the required files for a particular component or application. An assembly can contain one or more namespaces.

Attributes
Attributes enable you to provide additional information about program elements. For example, you can use an attribute to specify which methods in a class should be exposed when the class is used as a XML Web service.

Multithreading
Visual Basic .NET allows you to write applications that can perform multiple tasks independently. A task that has the potential of holding up other tasks can execute on a separate thread, a process known as multithreading. By causing complicated tasks to run on threads that are separate from your user interface, multithreading makes your applications more responsive to user input.

13. Advantages of VB.NET

First of all, VB.NET provides managed code execution that runs under the Common Language Runtime (CLR), resulting in robust, stable and secure applications. All features of the .NET framework are readily available in VB.NET.

VB.NET is totally object oriented. This is a major addition that VB6 and other earlier releases didn’t have.

The .NET framework comes with ADO.NET, which follows the disconnected paradigm, i.e. once the required records are fetched the connection no longer exists. It also retrieves the records that are expected to be accessed in the immediate future. This enhances Scalability of the application to a great extent.

VB.NET uses XML to transfer data between the various layers in the DNA Architecture i.e. data are passed as simple text strings.

Error handling has changed in VB.NET. A new Try-Catch-Finally block has been introduced to handle errors and exceptions as a unit, allowing appropriate action to be taken at the place the error occurred thus discouraging the use of ON ERROR GOTO statement. This again credits to the maintainability of the code.

Another great feature added to VB.NET is free threading against the VB single-threaded apartment feature. In many situations developers need spawning of a new thread to run as a background process and increase the usability of the application. VB.NET allows developers to spawn threads wherever they feel like, hence giving freedom and better control on the application.

Security has become more robust in VB.NET. In addition to the role-based security in VB6, VB.NET comes with a new security model, Code Access security. This security controls on what the code can access. For example you can set the security to a component such that the component cannot access the database. This type of security is important because it allows building components that can be trusted to various degrees.

The CLR takes care of garbage collection i.e. the CLR releases resources as soon as an object is no more in use. This relieves the developer from thinking of ways to manage memory. CLR does this for them.

14. Using ActiveX Control in .Net
ActiveX control is a special type of COM component that supports a User Interface. Using ActiveX Control in your .Net Project is even easier than using COM component. They are bundled usually in .ocx files. Again a proxy assembly is made by .Net utility AxImp.exe (which we will see shortly) which your application (or client) uses as if it is a .Net control or assembly.

Making Proxy Assembly For ActiveX Control: First, a proxy assembly is made using AxImp.exe (acronym for ActiveX Import) by writing following command on Command Prompt:

C:> AxImp C:MyProjectsMyControl.ocx

This command will make two dlls, e.g., in case of above command

MyControl.dll
AxMyControl.dll

The first file MyControl.dll is a .Net assembly proxy, which allows you to reference the ActiveX as if it were non-graphical object.
The second file AxMyControl.dll is the Windows Control, which allows u to use the graphical aspects of activex control and use it in the Windows Form Project.

Adding Reference of ActiveX Proxy Assembly in your Project Settings: To add a reference of ActiveX Proxy Assembly in our Project, do this:

o Select ProjectàAdd Reference (Select Add Reference from Project Menu).
o This will show you a dialog box, select .Net tab from the top of window.
o Click Browse button on the top right of window.
o Select the dll file for your ActiveX Proxy Assembly (which is MyControl.dll) and click OK o Your selected component is now shown in the ‘Selected Component’ List Box. Click OK again Some More On Using COM or ActiveX in .Net

.Net only provides wrapper class or proxy assembly (Runtime Callable Wrapper or RCW) for COM or activeX control. In the background, it is actually delegating the tasks to the original COM, so it does not convert your COM/activeX but just imports them.

A good thing about .Net is that when it imports a component, it also imports the components that are publically referenced by that component. So, if your component, say MyDataAcsess.dll references ADODB.dll then .Net will automatically import that COM component too!

The Visual Studio.NET does surprise you in a great deal when u see that it is applying its intellisense (showing methods, classes, interfaces, properties when placing dot) even on your imported COM components!!!! Isn’t it a magic or what?

When accessing thru RCW, .Net client has no knowledge that it is using COM component, it is presented just as another C# assembly.

U can also import COM component thru command prompt (for reference see Professional C# by Wrox)

U can also use your .Net components in COM, i.e., export your .net components (for reference see Professional C# by Wrox)

15. What is Machine.config?
Machine configuration file: The machine.config file contains settings that apply to the entire computer. This file is located in the %runtime install path%Config directory. There is only one machine.config file on a computer. The Machine.Config file found in the “CONFIG” subfolder of your .NET Framework install directory (c:WINNTMicrosoft.NETFramework{Version Number}CONFIG on Windows 2000 installations). The machine.config, which can be found in the directory $WINDIR$Microsoft.NETFrameworkv1.0.3705CONFIG, is an XML-formatted configuration file that specifies configuration options for the machine. This file contains, among many other XML elements, a browserCaps element. Inside this element are a number of other elements that specify parse rules for the various User-Agents, and what properties each of these parsings supports.

For example, to determine what platform is used, a filter element is used that specifies how to set the platform property based on what platform name is found in the User-Agent string. Specifically, the machine.config file contains:

platform=Win95
platform=Win98
platform=WinNT


That is, if in the User-Agent string the string “Windows 95″ or “Win95″ is found, the platform property is set to Win95. There are a number of filter elements in the browserCaps element in the machine.config file that define the various properties for various User-Agent strings.

Hence, when using the Request.Browser property to determine a user’s browser features, the user’s agent string is matched up to particular properties in the machine.config file. The ability for being able to detect a user’s browser’s capabilities, then, is based upon the honesty in the browser’s sent User-Agent string. For example, Opera can be easily configured to send a User-Agent string that makes it appear as if it’s IE 5.5. In this case from the Web server’s perspective (and, hence, from your ASP.NET Web page’s perspective), the user is visiting using IE 5.5, even though, in actuality, he is using Opera.

16. What is Web.config?
In classic ASP all Web site related information was stored in the metadata of IIS. This had the disadvantage that remote Web developers couldn’t easily make Web-site configuration changes. For example, if you want to add a custom 404 error page, a setting needs to be made through the IIS admin tool, and you’re Web host will likely charge you a flat fee to do this for you. With ASP.NET, however, these settings are moved into an XML-formatted text file (Web.config) that resides in the Web site’s root directory. Through Web.config you can specify settings like custom 404 error pages, authentication and authorization settings for the Web sitempilation options for the ASP.NET Web pages, if tracing should be enabled, etc.




The Web.config file is an XML-formatted file. At the root level is the tag. Inside this tag you can add a number of other tags, the most common and useful one being the system.web tag, where you will specify most of the Web site configuration parameters. However, to specify application-wide settings you use the tag.
For example, if we wanted to add a database connection string parameter we could have a Web.config file like so.

17. What is the difference between ADO and ADO.NET?
ADO uses Recordsets and cursors to access and modify data. Because of its inherent design, Recordset can impact performance on the server side by tying up valuable resources. In addition, COM marshalling - an expensive data conversion process - is needed to transmit a Recordset. ADO.NET addresses three important needs that ADO doesn’t address:
1. Providing a comprehensive disconnected data-access model, which is crucial to the Web environment
2. Providing tight integration with XML, and
3. Providing seamless integration with the .NET Framework (e.g., compatibility with the base class library’s type system). From an ADO.NET implementation perspective, the Recordset object in ADO is eliminated in the .NET architecture. In its place, ADO.NET has several dedicated objects led by the DataSet object and including the DataAdapter, and DataReader objects to perform specific tasks. In addition, ADO.NET DataSets operate in disconnected state whereas the ADO RecordSet objects operated in a fully connected state.

In ADO, the in-memory representation of data is the recordset. In ADO.NET, it is the dataset. A recordset looks like a single table. If a recordset is to contain data from multiple database tables, it must use a JOIN query, which assembles the data from the various database tables into a single result table. In contrast, a dataset is a collection of one or more tables. The tables within a dataset are called data tables; specifically, they are DataTable objects. If a dataset contains data from multiple database tables, it will typically contain multiple DataTable objects. That is, each DataTable object typically corresponds to a single database table or view. In this way, a dataset can mimic the structure of the underlying database.
In ADO you scan sequentially through the rows of the recordset using the ADO MoveNext method. In ADO.NET, rows are represented as collections, so you can loop through a table as you would through any collection, or access particular rows via ordinal or primary key index. A cursor is a database element that controls record navigation, the ability to update data, and the visibility of changes made to the database by other users. ADO.NET does not have an inherent cursor object, but instead includes data classes that provide the functionality of a traditional cursor. For example, the functionality of a forward-only, read-only cursor is available in the ADO.NET DataReader object.
There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source.

17. What is the difference between VB and VB.NET?
Now VB.NET is object-oriented language. The following are some of the differences:
Data Type Changes
The .NET platform provides Common Type System to all the supported languages. This means that all the languages must support the same data types as enforced by common language runtime. This eliminates data type incompatibilities between various languages. For example on the 32-bit Windows platform, the integer data type takes 4 bytes in languages like C++ whereas in VB it takes 2 bytes. Following are the main changes related to data types in VB.NET:

. Under .NET the integer data type in VB.NET is also 4 bytes in size.
. VB.NET has no currency data type. Instead it provides decimal as a replacement.
. VB.NET introduces a new data type called Char. The char data type takes 2 bytes and can store Unicode characters.
. VB.NET do not have Variant data type. To achieve a result similar to variant type you can use Object data type. (Since every thing in .NET including primitive data types is an object, a variable of object type can point to any data type).
. In VB.NET there is no concept of fixed length strings.
. In VB6 we used the Type keyword to declare our user-defined structures. VB.NET introduces the structure keyword for the same purpose.
Declaring Variables
Consider this simple example in VB6:
Dim x,y as integer

In this example VB6 will consider x as variant and y as integer, which is somewhat odd behavior. VB.NET corrects this problem, creating both x and y as integers.
Furthermore, VB.NET allows you to assign initial values to the variables in the declaration statement itself:
br> Dim str1 as string = Hello

VB.NET also introduces Read-Only variables. Unlike constants Read-Only variables can be declared without initialization but once you assign a value to it, it cannot be changes.

Initialization here
Dim readonly x as integer
In later code
X=100
Now x can’t be changed
X=200 *********** Error **********
Property Syntax
In VB.NET, we anymore don’t have separate declarations for Get and Set/Let. Now, everything is done in a single property declaration. This can be better explained by the following example.
Public [ReadOnly | WriteOnly] Property PropertyName as Datatype
Get
Return m_var
End Get
Set
M_var = value
End Set
End Property

Example:
Private _message as String
Public Property Message As String
Get
Return _message
End Get
Set
_message = Value
End Set
End Property

ByVal is the default - This is a crucial difference betwen VB 6.0 and VB.NET, where the default in VB 6.0 was by reference. But objects are still passed by reference.

Invoking Subroutines In previous versions of VB, only functions required the use of parentheses around the parameter list. But in VB.NET all function or subroutine calls require parentheses around the parameter list. This also applies, even though the parameter list is empty.

User-Defined Types - VB.NET does away with the keyword Type and replaces it with the keyword Structure
Public Structure Student
Dim strName as String
Dim strAge as Short
End Structure

Procedures and Functions




In VB6 all the procedure parameters are passed by reference (ByRef) by default. In VB.NET they are passed by value (ByVal) by default. Parantheses are required for calling procedures and functions whether they accept any parameters or not. In VB6 functions returned values using syntax like: FuntionName = return_value. In VB.NET you can use the Return keyword (Return return_value) to return values or you can continue to use the older syntax, which is still valid.

Scoping VB.NET now supports block-level scoping of variables. If your programs declare all of the variables at the beginning of the function or subroutine, this will not be a problem. However, the following VB 6.0 will cause an issue while upgrading to VB .NET

Do While objRs.Eof
Dim J as Integer
J=0
If objRs(”flag”)=”Y” then
J=1
End If
objRs.MoveNext
Wend
If J Then
Msgbox “Flag is Y”
End If

In the above example the variable J will become out of scope just after the loop, since J was declared inside the While loop.

Exception Handling

The most wanted feature in earlier versions of VB was its error handling mechanism. The older versions relied on error handlers such as “On Error GoTo and On Error Resume Next. VB.NET provides us with a more stuructured approach. The new block structure allows us to track the exact error at the right time. The new error handling mechanism is refered to as Try…Throw…Catch…Finally. The following example will explain this new feature.

Sub myOpenFile()
Try
Open “myFile” For Output As #1
Write #1, myOutput
Catch
Kill “myFile”
Finally
Close #1
End try
End Sub

The keyword SET is gone - Since everything in VB.NET is an object. So the keyword SET is not at all used to differentiate between a simple variable assignment and an object assignment. So, if you have the following statement in VB 6.0

Set ObjConn = Nothing
Should be replaced as
ObjConn = Nothing.
Constructor and Destructor

The constructor procedure is one of the many new object-oriented features of VB.NET. The constructor in VB.NET replaces the Class_Initialize in VB 6.0. All occurance of Class_Initialize in previous versions of VB should now be placed in a class constructor. In VB.NET, a constructor is added to a class by adding a procedure called New. We can also create a class destructor, which is equivalent to Class_Terminate event in VB 6.0, by adding a sub-procedure called Finalize to our class. Usage of Return In VB.NET, we can use the keyword return to return a value from any function. In previous versions, we used to assign the value back with the help of the function name itself. The following example explains this:

Public Function Sum (intNum1 as Integer, intNum2 as Integer) as Integer
Dim intSum as Integer
intSum = intNum1 + intNum2
Return intSum
End Function
Static Methods

VB.NET now allows you to create static methods in your classes. Static methods are methods that can be called without requiring the developer to create instance of the class. For example, if you had a class named Foo with the non-static method NonStatic() and the static method Static(), you could call the Static() method like so:

Foo.Static()

However, non-static methods require than an instance of the class be created, like so:

Create an instance of the Foo class
Dim objFoo as New Foo()
Execute the NonStatic() method
ObjFoo.NonStatic()

To create a static method in a VB.NET, simply prefix the method definition with the keyword Shared.

Posted in .Net. No Comments »