Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Dear Friends, Hi I am Raman Rattan Bhardwaj, this documents contains all the important questions that usually asked

during the Asp.Net,SQL SERVER Interview Questions, I had downloaded all the material from the Internet from various websites and collected to form a single film, u will find few repeated questions also, all the material are from the various websites, so I had just bind it into a single file. So for any mistake I am not responsible, this is just for the view purpose. My view was only to collect a material to a single file. Please, if u find any mistake in this file, please contact me to my email address raman.rattan85@gmail.com, so that I can able to correct it. ALL THE BEST Thanks Raman Rattan Bhardwaj. Contact me: 09958901108

SQL SERVER Interview Questions


1 General Questions of SQL SERVER... 2 2 Common Questions Asked. 8 3 Questions of SQL SERVER 2008 16 1) General Questions of SQL SERVER What is RDBMS? Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage. (Read More Here) What are the properties of the Relational tables? Relational tables have six properties: Values are atomic. Column values are of the same kind. Each row is unique. The sequence of columns is insignificant. The sequence of rows is insignificant. Each column must have a unique name. What is Normalization? Database normalization is a data design and organization process applied to data structures based on rules that help building rlational databases. In relational database design, the process of organizing data to minimize redundancy is called normalization. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database via the define relationships. What is Denormalization? Denormalization is the process of attempting to optimize the performance of a database by adding redundant data. It is sometimes necessary because current DBMSs implement

the relational model poorly. A true relational DBMS would allow for a fully normalized database at the logical level, while providing physical storage of data that is tuned for high performance. Denormalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database acces What are different normalization forms? 1NF: Eliminate Repeating Groups Make a separate table for each set of related attributes, and give each table a primary key. Each field contains at most one value from its attribute domain. 2NF: Eliminate Redundant Data If an attribute depends on only part of a multivalued key, remove it to a separate table. 3NF: Eliminate Columns Not Dependent On Key If attributes do not contribute to a description of the key, remove them to a separate table. All attributes must be directly dependent on the primary key. (Read More Here) BCNF: BoyceCodd Normal Form If there are nontrivial dependencies between candidate key attributes, separate them out into distinct tables. 4NF: Isolate Independent Multiple Relationships No table may contain two or more 1:n or n:m relationships that are not directly related. 5NF: Isolate Semantically Related Multiple Relationships There may be practical constrains on information that justify separating logically related manytomany relationships. ONF: Optimal Normal Form A model limited to only simple (elemental) facts, as expressed in Object Role Model notation. DKNF: DomainKey Normal Form A model free from all modification anomalies is said to be in DKNF. Remember, these normalization guidelines are cumulative. For a database to be in 3NF, it must first fulfill all the criteria of a 2NF and 1NF database. What is Stored Procedure? A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using diferent input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database. e.g. sp_helpdb, sp_renamedb, sp_depends etc. What is Trigger? A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS. Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed; DBMS automatically fires the trigger as a result of a data modification to the associated table. Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the databaselevel. Stored procedures, however, are not eventdrive and are not attached to a specific table as triggers are. Stored procedures are explicitly

executed by invoking a CALL to the procedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures. Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the trigger is fired because of data modification it can also cause another data modification, thereby firing another trigger. A trigger that contains data modification logic within itself is called a nested trigger. (Read More Here) What is View? A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original table. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard TSQL select command and can come from one to many different base tables or even other views. What is Index? An index is a physical structure containing pointers to the data. Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes; they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application. A table scan happens when there is no index available to help a query. In a table scan SQL Server examines every row in the table to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scans have a terrific impact on performance. What is a Linked Server? Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs usig TSQL Statements. With a linked server, you can create very clean, easy to follow, SQL statements that allow remote data to be retrieved, joined and combined with local data. Stored Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server. (Read More Here) What is Cursor? Cursor is a database object used by applications to manipulate data in a set on a rowby row basis, instead of the typical SQL commands that operate on all the rows in the set at one time. In order to work with a cursor we need to perform some steps in the following order: 1 Declare cursor Open cursor Fetch row from the cursor Process fetched row Close cursor Deallocate cursor (Read More Here) What is Collation? Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying case sensitivity, accent marks, kana character types and character width. (Read More Here) What is Difference between Function and Stored Procedure? UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be. UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables. Inline UDF's can be thought of as views that take parameters and can be used in JOINs and other Rowset operations. What is subquery? Explain properties of subquery?

Subqueries are often referred to as subselects, as they allow a SELECT statement to be executed arbitrarily within the body of another SQL statement. A subquery is executed by enclosing it in a set of parentheses. Subqueries are generally used to return a single row as an atomic value, though they may be used to compare values against multiple rows with the IN keyword. A subquery is a SELECT statement that is nested within another TSQL statement. A subquery SELECT statement if executed independently of the TSQL statement, in which it is nested, will return a resultset. Meaning a subquery SELECT statement can standalone and is not depended on the statement in which it is nested. A subquery SELECT statement can return any number of values, and can be found in, the column list of a SELECT statement, a FROM, GROUP BY, HAVING, and/or ORDER BY clauses of a TSQL statement. A Subquery can also be used as a parameter to a function call. Basically a subquery can be used anywhere an expression can be used. What are different Types of Join? Cross Join A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the seond table. The common example is when company wants to combine each product with a pricing table to analyze each product at each price. Inner Join A join that displays only the rows that have a match in both joined tables is known as inner Join. This is the default type of join in the Query and View Designer. Outer Join A join that includes rows even if they do not have related rows in the joined table is an Outer Join. You can create three different outer join to specify the unmatched rows to be included:

Left Outer Join: In Left Outer Join all rows in the firstnamed table i.e. "left" table, which appears leftmost in the JOIN clause are included. Unmatched rows in the right table do not appear.

Right Outer Join: In Right Outer Join all rows in the secondnamed table i.e. "right" table, which appears rightmost in the JOIN clause are included. Unmatched rows in the left table are not included. 1 Full Outer Join: In Full Outer Join all rows in all joined tables are included, whether they are matched or not.

Self Join
This is a particular case when one table joins to itself, with one or two aliases to avoid confusion. A self join can be of any type, as long as the joined tables are the same. A self join is rather unique in that it involves a relationship with only one table. The common example is when company has a hierarchal reporting structure whereby one member of staff reports to another. Self Join can be Outer Join or Inner Join What are primary keys and foreign keys? Primary keys are the unique identifiers for each row. They must contain unique values and cannot be null. Due to their importance in relational databases, Primary keys are the most fundamental of all keys and constraints. A table can have only one Primary key. Foreign keys are both a method of ensuring data integrity and a manifestation of the relationship between tables. What is User created? Defined Functions? What kind of UserDefined Functions can be

UserDefined Functions allow defining its own TSQL functions that can accept 0 or more parameters and return a single scalar data value or a table data type. Different Kinds of UserDefined Functions created are:
Scalar UserDefined Function

A Scalar userdefined function returns one of the scalar data types. Text, ntext, image and timestamp data types are not supported. These are the type of userdefined functions that most developers are used to in other programming languages. You pass in 0 to many parameters and you get a return value. Inline TableValue UserDefined Function An Inline TableValue userdefined function returns a table data type and is an exceptional alternative to a view as the userdefined function can pass parameters into a TSQL select command and in essence provide us with a parameterized, nonupdateable view of the underlying tables. Multistatement TableValue UserDefined Function A MultiStatement TableValue userdefined function returns a table and is also an exceptional alternative to a view as the function can support multiple TSQL statements to build the final result where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a TSQL select command or a group of them gives us the capability to in essence create a paameterized, nonupdateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of userdefined function, It can be used in the FROM clause of a TSQL command unlike the behavior found when using a stored procedure which can also return record sets. (Read Here For Example) What is Identity? Identity (or AutoNumber) is a column that automatically generates numeric values. A start and increment value can be set, but most DBA leave these at 1. A GUID column also generates numbers; the value of this cannot be controlled. Identity/GUID columns do not need to be indexed. What is DataWarehousing? 1 Subjectoriented, meaning that the data in the database is organized so that all the data elements relating to the same realworld event or object are linked together; Timevariant, meaning that the changes to the data in the database are tracked and recorded so that reports can be produced showing changes ver time; Nonvolatile, meaning that data in the database is never overwritten or deleted, once committed, the data is static, readonly, but retained for future reporting. Integrated, meaning that the database contains data from most or all of an organization's operational applications, and that this data is made consistent. 2) Common Questions Asked Which TCP/IP port does SQL Server run on? How can it be changed? SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties > Port number, both on client and the server. What are the difference between clustered and a nonclustered index? (Read More Here) A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A non clustered index is a special type of index in which the logical order of the index does not match the physical stored ordr of the rows on disk. The leaf node of a non clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.

What are the different index configurations a table can have? A table can have one of the following index configurations: 1 No indexes A clustered index A clustered index and many nonclustered indexes A nonclustered index Many nonclustered indexes

What are different types of Collation Sensitivity? Case sensitivity A and a, B and b, etc. Accent sensitivity a and , o and , etc. Kana Sensitivity When Japanese kana characters differently, it is called Kana sensitive. Hiragana and Katakana are treated

Width sensitivity A singlebyte character (halfwidth) and the same character represented as a doublebyte character (fullwidth) are treated differently than it is width sensitive. (Read More Here) What is OLTP (Online Transaction Processing)? In OLTP online transaction processing systems relational database design use the discipline of data modeling and generally follow the odd rules of data normalization in order to ensure absolute data integrity. Using these rules complex information is broken down into its most simple structures (a table) where all of the individual atomic level elements relate to each other and satisfy the normalization rules. What's the difference between a primary key and a unique key? Both primary key and unique key enforces uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only. (Read More Here) What is difference between DELETE & TRUNCATE commands? Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate commad. TRUNCATE 1 TRUNCATE is faster and uses fewer system and transaction log resources than DELETE. 2 TRUNCATE removes the data by deallocating the data pages used to store the tables data, and only the page deallocations are recorded in the transaction log. TRUNCATE removes all rows from a table, but the table structure, its columns, constraints, indexes and so on, remains. The counter used by an identity for new rows is reset to the seed for the column. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint. Because TRUNCATE TABLE is not logged, it cannot activate a trigger. TRUNCATE cannot be rolled back. TRUNCATE is DDL Command. TRUNCATE Resets identity of the table DELETE

1 DELETE removes rows one at a time and records an entry in the transaction log for each deleted row. If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement. DELETE Can be used with or without a WHERE clause DELETE Activates Triggers. DELETE can be rolled back. DELETE is DML Command. DELETE does not reset identity of the table. When is the use of UPDATE_STATISTICS command? This command is basically used when a large processing of data has occurred. If a large amount of deletions any modification or Bulk Copy into the tables has occurred, it has to update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? They specify a search condition for a group or an aggregate. But the difference is that HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a query whereas WHERE Clause is applied to each row before hey are part of the GROUP BY function in a query. (Read More Here)

What are the properties and different Types of SubQueries? Properties of SubQuery 1 A subquery must be enclosed in the parenthesis. A subquery must be put in the right hand of the comparison operator, and A subquery cannot contain an ORDERBY clause. A query can contain more than one subquery. Types of Subquery Singlerow subquery, where the subquery returns only one row. Multiplerow subquery, where the subquery returns multiple rows,. and Multiple column subquery, where the subquery returns multiple columns

What is SQL Profiler? SQL Profiler is a graphical instance of Microsoft SQL file or SQL Server table environment to see which slowly.

tool that allows system administrators to monitor events in an Server. You can capture and save data about each event to a to analyze later. For example, you can monitor a production stored procedures are hampering performances by executing too

Use SQL Profiler to monitor only the events in which you are interested. If traces are becoming too large, you can filter them based on the information you want, so that only a subset of the event data is collected. Monitoring too many events adds overhead to the server and the monitoring process and can cause the trace file or trace table o grow very large, especially when the monitoring process takes place over a long period of time. What are the authentication modes in SQL Server? How can it be changed? Windows mode and Mixed Mode SQL & Windows. To change authentication mode in SQL Server click Start, Programs, Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL

Server program grou. Select the server then from the Tools menu select SQL Server Configuration Properties, and choose the Security page. Which command using Query Analyzer will give you the version of SQL server and operating system? SELECT SERVERPROPERTY ('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition'). What is SQL Server Agent? SQL Server agent plays an important role in the daytoday administrator (DBA). It is often overlooked as one of the main management. Its purpose is to ease the implementation of tasks fullfunction scheduling engine, which allows you to schedule your (Read More Here) tasks of a database tools for SQL Server for the DBA, with its own jobs and scripts.

Can a stored procedure call itself or recursive stored procedure? How much level SP nesting is possible? Yes. Because TransactSQL supports recursion, you can write stored procedures that call themselves. Recursion can be defined as a method of problem solving wherein the solution is arrived at by repetitively applying it to substs of the problem. A common application of recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by th same processing steps. Stored procedures are nested when one stored procedure calls another or executes managed code by referencing a CLR routine, type, or aggregate. You can nest stored procedures and managed code references up to 32 levels. What is Log Shipping? Log shipping is the process of automating the backup of database and transaction log files on a production SQL server, and then restoring them onto a standby server. Enterprise Editions only supports log shipping. In log shipping the transactional log file from one server is automatically updated into the backup database on the other servr. If one server fails, the other server will have the same db and can be used this as the Disaster Recovery plan. The key feature of log shipping is that it will automatically backup transaction logs throughout the day and automatically resore them on the standby server at defined interval. Name 3 ways to get an accurate count of the number of records in a table? SELECT * FROM table1 SELECT COUNT(*) FROM table1 SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2 What does it mean to have QUOTED_IDENTIFIER ON? What are the implications of having it OFF? When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation marks, and literals must be delimited by single quotation marks. When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all TransactSQL rules for identifiers. What is the difference between a Local and a Global temporary table? A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement. A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection is closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time. What is the STUFF function and how does it differ from the REPLACE function? STUFF function is used to overwrite existing characters. Using this syntax, STUFF (string_expression, start, length, replacement_characters), string_expression is the string that will have characters substituted, start is the starting position, length is the number

of characters in the string that are substituted, and replacement_characters are the new characters interjected into the string. REPLACE function to replace existing characters of all occurrences. Using the syntax REPLACE (string_expression, search_string, replacement_string), where every incidence of search_string found in the string_expression will be replaced with replacement_string. What is PRIMARY KEY? A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table should have a primary key constraint to uniquely identify each row and only one primary key constraint can be creaed for each table. The primary key constraints are used to enforce entity integrity. What is UNIQUE KEY constraint? A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints. What is FOREIGN KEY? A FOREIGN KEY constraint prevents any actions that would destroy links between tables with the corresponding data values. A foreign key in one table points to a primary key in another table. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity. What is CHECK Constraint? A CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity. What is NOT NULL Constraint? A NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints. (Read More Here) How to get @@ERROR and @@ROWCOUNT at the same time? If @@Rowcount is checked after Error checking statement then it will have 0 as the value of @@Recordcount as it would have been reset. And if @@Recordcount is checked before the errorchecking statement then @@Error would get reset. To get @@error and @@rowcount at the same time do both in same statement and store them in local variable. SELECT @RC = @@ROWCOUNT, @ER = @@ERROR What is a Scheduled Jobs or What is a Scheduled Tasks? Scheduled tasks let user automate processes that run on regular or predictable cycles. User can schedule administrative tasks, such as cube processing, to run during times of slow business activity. User can also determine the order in which tasks run by creating job steps within a SQL Server Agent job. E.g. back up database, Update Stats of Tables. Job steps give user control over flow of execution. If one job fails, user can configure SQL Server Agent to continue to run the remaining tasks or to stop execution. What are the advantages of using Stored Procedures? 1 Stored procedure can reduced network traffic and latency, boosting application performance. Stored procedure execution plans can be reused, staying cached in SQL Server's memory, reducing server overhead. Stored procedures help promote code reuse. Stored procedures can encapsulate logic. You can change stored procedure code without affecting clients. Stored procedures provide better security to your data. What is a table called, if it has neither Cluster nor Noncluster Index? What is it used for?

Unindexed table or Heap. Microsoft Press Books and Book on Line (BOL) refers it as Heap. A heap is a table that does not have a clustered index and, therefore, the pages are not linked by pointers. The IAM pages are the only structures that link the pages in a table together. Unindexed tables are good for fast storing of data. Many times it is better to drop all indexes from table and then do bulk of inserts and to restore those indexes after that. Can SQL Servers linked to other servers like Oracle? SQL Server can be linked to any server provided it has OLEDB provider from Microsoft to allow a link. E.g. Oracle has an OLEDB provider for oracle that Microsoft provides to add it as linked server to SQL Server group . What is BCP? When does BulkCopy is a tool used not copy the structures import a data file into a it used? to copy huge amount of data from tables and views. BCP does same as source to destination. BULK INSERT command helps to database table or view in a userspecified format.

What command do we use to rename a db, a table and a column? To rename db sp_renamedb oldname , newname If someone is using db it will not accept sp_renmaedb. In that case first bring db to single user using sp_dboptions. Use sp_renamedb to rename database. Use sp_dboptions to bring database to multi user mode. E.g. USE master; GO EXEC sp_dboption AdventureWorks, 'Single User', True GO EXEC sp_renamedb 'AdventureWorks', 'AdventureWorks_New' GO EXEC sp_dboption AdventureWorks, 'Single User', False GO To rename Table We can change the table name using sp_rename as follows, sp_rename oldTableName newTableName E.g. SP_RENAME Table_First, Table_Last GO To rename Column The script for renaming any column : sp_rename TableName.[OldcolumnName], NewColumnName, Column E.g. sp_RENAME Table_First.Name, NameChange , COLUMN GO What are sp_configure commands and set commands? Use sp_configure to display or change serverlevel settings. To change databaselevel settings, use ALTER DATABASE. To change settings that affect only the current user session, use the SET statement. E.g. sp_CONFIGURE show advanced, 0 GO RECONFIGURE GO sp_CONFIGURE GO You can run following command and check advance global configuration settings. sp_CONFIGURE show advanced, 1 GO RECONFIGURE GO sp_CONFIGURE GO (Read More Here) How to implement onetoone, onetomany and manytomany relationships while designing tables? OnetoOne relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. OnetoMany relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.

ManytoMany relationships are implemented using a junction table with the keys from both the tables forming the composite primary key f the junction table. What is an execution plan? When would you use it? How would you view the execution plan? An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL Servr query optimizer for a stored procedure or adhoc query and is a very useful tool for a developer to understand the performance characteristics of a query or stored procedur since the plan is the one that SQL Server will place in its cache and use to execute the stored procedure or query. From within Query Analyzer is an option called "Show Execution Plan" (located on the Query dropdown menu). If this option is turned on it will display query execution plan in separate window when query is ran again.

3) Questions of SQL SERVER 2008


What are the basic functions for master, msdb, model, tempdb and resource databases? The master database holds information for all databases located on the SQL Server instance and is theglue that holds the enginetogether. Because SQL Server cannot start without a functioning masterdatabase, you must administer this database with care. The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping. The tempdb holds temporary objects such as global and local temporary tables and stored procedures. The model is essentially a template database used in the creation of any new user database created in the instance. The resoure Database is a readonly database that contains all the system objects that are included with SQL Server. SQL Server system objects, such as sys.objects, are physically persisted in the Resource database, but they logically appear in the sys schema of every database. The Resource database does not contain user data or user metadata. What is Service Broker? Service Broker is a messagequeuing technology in SQL Server that allows developers to integrate SQL Server fully into distributed applications. Service Broker is feature which provides facility to SQL Server to send an asynchronous, transactional message. it allows a database to send a message to another database without waiting for the response, so the application will continue to function if the remote database is temporarily unavailable. (Read More Here) Where SQL server user names and passwords are stored in SQL server? They get stored in System Catalog Views sys.server_principals and sys.sql_logins. What is Policy Management? Policy Management in SQL SERVER 2008 allows you to define and enforce policies for configuring and managing SQL Server across te enterprise. PolicyBased Management is configured in SQL Server Management Studio (SSMS). Navigate to the Object Explorer and expand the Management node and the Policy Management node; you will see the Policies, Conditions, and Facets nodes. (Read More Here)

What is Replication and Database Mirroring? Database mirroring can be used with replication to provide availability for the publication database. Database mirroring involves two copies of a single database that typically reside on different computers. At any given time, only one copy of the database is currently available to clients which are known as the principal database. Updates made by clients to the principal database are applied on the other copy of the database, known as the mirror database. Mirroring involves applying the transaction log from every insertion, update, or deletion made on the principal database onto the mirror database. What are Sparse Columns? A sparse column is another tool used to reduce the amount of physical storage used in a database. They are the ordinary columns that have an optimized storage for null values. Sparse columns reduce the space requirements for null values at the cost of more overhead to retrieve nonnull values. (Read More Here) What does TOP Operator Do? The TOP operator is used to specify the number of rows to be returned by a query. The TOP operator has new addition in SQL SERVER 2008 that it accepts variables as well as literal values and can be used with NSERT, UPDATE, and DELETES statements. What is CTE? CTE is an abbreviation Common Table Expression. A Common Table Expression (CTE) is an expression that can be thought of as a temporary result set which is defined within the execution of a single SQL statemnt. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. (Read More Here) What is MERGE Statement? MERGE is a new feature that provides an efficient way to perform multiple DML operations. In previous versions of SQL Server, we had to write separate statements to INSERT, UPDATE, or DELETE data based on certain conditions, but now, using MERGE statement we can include the logic of such data modifications in one statement that even checks when the data is mtched then just update it and when unmatched then insert it. One of the most important advantages of MERGE statement is all the data is read and processed only once. (Read More Here) What is Filtered Index? Filtered Index is used to index a portion of rows in a table that means it applies filter on INDEX which improves query performnce, reduce index maintenance costs, and reduce index storage costs compared with fulltable indexes. When we see an Index created with some where clause then that is actually a FILTERED INDEX. Which are new data types introduced in SQL SERVER 2008? The GEOMETRY Type: The GEOMETRY data type is a system .NET common language runtime (CLR) data type in SQL Server. This type represents data in a twodimensional Euclidean coordinate system. The GEOGRAPHY Type: The GEOGRAPHY datatypes functions are the same as with GEOMETRY. The difference between the two is that when you specify GEOGRAPHY, you are usually specifying points in terms of latitude and longitude. New Date and Time Datatypes: SQL Server 2008 introduces four new datatypes related to date and time: DATE, TIME, DATETIMEOFFSET, and DATETIME2.

DATE: The new DATE type just stores the date itself. It is based on the Gregorian calendar and handles years from 1 to 9999. TIME: The new TIME (n) type stores time with a range of 00:00:00.0000000 through 23:59:59.9999999. The precision is allowed with this type. TIME supports seconds down to 100 nanoseconds. The n in TIME (n) defines this level of fractional second precision, from 0 to 7 digits of precision.

The DATETIMEOFFSET Type: DATETIMEOFFSET (n) is the timezoneaware version of a datetime datatype. The name will appear less odd when you consider what it really is: a date + a time + a timezone offset. The offset is based on how far behind or ahead you are from Coordinated Universal Time (UTC) time.

1 The DATETIME2 Type: It is an extension of the datetime type in earlier versions of SQL Server. This new datatype has a date range covering dates from January 1 of year 1 through December 31 of year 9999. This is a definite improvement over the 1753 lower boundary of the datetime datatype. DATETIME2 not only includes the larger date range, but also has a timestamp and the same fractional precision that TIME type provides What are the Advantages of using CTE? 1 Using CTE improves the readability and makes maintenance of complex queries easy. The query can be divided into separate, simple, logical building blocks which can be then used to build more complex CTEs until final result set is generated. CTE can be defined in functions, stored procedures, triggers or even views. After a CTE is defined, it can be used as a Table or a View and can SELECT, INSERT, UPDATE or DELETE Data. How can we rewrite subqueries into simple select statements or with joins? Yes we can write using Common Table Expression (CTE). A Common Table Expression (CTE) is an expression that can be thought of as a temporary result set which is defined within the execution of a single SQL statemnt. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. E.g. USE AdventureWorks GO WITH EmployeeDepartment_CTE AS ( SELECT EmployeeID,DepartmentID,ShiftID FROM HumanResources.EmployeeDepartmentHistory ) SELECT ecte.EmployeeId,ed.DepartmentID, ed.Name,ecte.ShiftID FROM HumanResources.Department ed INNER JOIN EmployeeDepartment_CTE ecte ON ecte.DepartmentID = ed.DepartmentID GO What is CLR? In SQL Server 2008, SQL Server objects such as userdefined functions can be created using such CLR languages. This CLR language support extends not only to userdefined functions, but also to stored procedures and triggers. You can develop such CLR addons to SQL Server using Visual Studio 2008. (Read More Here) What are synonyms? Synonyms give you the ability to provide alternate names for database objects. You can alias object names; for example, using the Employee table as Emp. You can also shorten names. This is especially useful when dealing with three and four part names; for example, shortening server.database.owner.object to object. (Read More Here) What is LINQ? Language Integrated Query (LINQ) adds the ability to query objects using .NET languages. The LINQ to SQL object/relational mapping (O/RM) framework provides the following basic features:

Tools to create classes (usually called entities) mapped to database tables Compatibility with LINQs standard query operations

The DataContext class, with features such as entity record monitoring, automatic SQL statement generation, record concurrency detection, and much more .

ASP.NET Interview Questions


01. What is the CLR? Ans : CLR = Common Language Runtime. The CLR is a set of standard resources that (in theory) any .NET program can take advantage of, regardless of programming language. Many .NET framework classes Development, debugging, and profiling tools Execution and code management IL-to-native translators and optimizers What this means is that in the .NET world, different programming languages will be more equal in capability than they have ever been before, although clearly not all languages will support all CLR services. 02. What is the CTS? Ans : CTS = Common Type System. This is the range of types that the .NET runtime understands, and therefore that .NET applications can use. However note that not all .NET languages will support all the types in the CTS. The CTS is a superset of the CLS. 03. What is the CLS? Ans : CLS = Common Language Specification. This is a subset of the CTS which all .NET languages are expected to support. The idea is that any program which uses CLS-compliant types can interoperate with any .NET program written in any language. In theory this allows very tight interop between different .NET languages - for example allowing a C# class to inherit from a VB class. 04. What is IL? Ans : IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code (of any language) is compiled to IL. The IL is then converted to machine code at the point where the software is installed, or at run-time by a JustIn-Time (JIT) compiler. 05. What does 'managed' mean in the .NET context? Ans : The term 'managed' is the cause of much confusion. It is used in various places within .NET, meaning slightly different things.Managed code: The .NET framework provides several core run-time services to the programs that run within it - for example exception handling and security. For these services to work, the code must provide a minimum level of information to the runtime. Such code is called managed code. All C# and Visual Basic.NET code is managed by default. VS7 C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/com+). Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector. C# and VB.NET data is always managed. VS7 C++ data is unmanaged by default, even when using the /com+ switch, but it can be marked as managed using the __gc keyword.Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. When using ME C++, a class can be marked with the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector, but it also means more than that. The class becomes a fully paid-up member of the .NET community with the benefits and restrictions that brings. An example of a benefit is proper interop with classes written in other languages - for example, a managed C++ class can inherit from a VB class. An example of a restriction is that a managed class can only inherit from one base class. 06. What is reflection? Ans : All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly. Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries.

Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember ) , or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder). 07. What is the difference between Finalize and Dispose (Garbage collection) ? Ans : Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions for C++). The garbage collector calls this method at some point after there are no longer any valid references to the object. In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object. Dispose can be called even if other references to the object are alive. Note that even when you provide explicit control by way of Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose. 08. What is Partial Assembly References? Ans : Full Assembly reference: A full assembly reference includes the assembly's text name, version, culture, and public key token (if the assembly has a strong name). A full assembly reference is required if you reference any assembly that is part of the common language runtime or any assembly located in the global assembly cache. 09. Changes to which portion of version number indicates an incompatible change? Ans : Major or minor. Changes to the major or minor portion of the version number indicate an incompatible change. Under this convention then, version 2.0.0.0 would be considered incompatible with version 1.0.0.0. Examples of an incompatible change would be a change to the types of some method parameters or the removal of a type or method altogether. Build. The Build number is typically used to distinguish between daily builds or smaller compatible releases. Revision. Changes to the revision number are typically reserved for an incremental build needed to fix a particular bug. You'll sometimes hear this referred to as the "emergency bug fix" number in that the revision is what is often changed when a fix to a specific bug is shipped to a customer. 10. How to set the debug mode? Debug Mode for ASP.NET applications - To set ASP.NET appplication in debugging mode, edit the application's web.config and assign the "debug" attribute in < compilation > section to "true" as show below: < configuration > < system.web > < compilation defaultLanguage="vb" debug="true" / > .... ... .. < / configuration > This case-sensitive attribute 'debug tells ASP.NET to generate symbols for dynamically generated files and enables the debugger to attach to the ASP.NET application. ASP.NET will detect this change automatically, without the need to restart the server. Debug Mode for ASP.NET Webservices - Debugging an XML Web service created with ASP.NET is similar to the debugging an ASP.NET Web application. 11. What is managed and unmanaged code? Ans : The .NET framework provides several core run-time services to the programs that run within it for example exception handling and security. For these services to work, the code must provide a minimum level of information to the runtime. i.e., code executing under the control of the CLR is called managed code. For example, any code written in C# or Visual Basic .NET is managed code.

Code that runs outside the CLR is referred to as "unmanaged code." COM components, ActiveX components, and Win32 API functions are examples of unmanaged code. 12. Describe the advantages of writing a managed code application instead of unmanaged one. What's involved in certain piece of code being managed? "Advantage includes automatic garbage collection,memory management,security,type checking,versioning Managed code is compiled for the .NET run-time environment. It runs in the Common Language Runtime (CLR), which is the heart of the .NET Framework. The CLR provides services such as security, memory management, and cross-language integration. Managed applications written to take advantage of the features of the CLR perform more efficiently and safely, and take better advantage of developers existing expertise in languages that support the .NET Framework. Unmanaged code includes all code written before the .NET Framework was introducedthis includes code written to use COM, native Win32, and Visual Basic 6. Because it does not run inside the .NET environment, unmanaged code cannot make use of any .NET managed facilities." 13. What is Boxing and UnBoxing? Ans : Boxing is implicit conversion of ValueTypes to Reference Types (Object). UnBoxing is explicit conversion of Reference Types (Object) to its equivalent ValueTypes. It requires type-casting.

14. What is the sequence of operation takes place when a page is loaded?
BeginTranaction - only if the request is transacted Init - every time a page is processed LoadViewState - Only on postback ProcessPostData1 - Only on postback Load - every time ProcessData2 - Only on Postback RaiseChangedEvent - Only on Postback RaisePostBackEvent - Only on Postback PreRender - everytime BuildTraceTree - only if tracing is enabled SaveViewState - every time Render - Everytime End Transaction - only if the request is transacted Trace.EndRequest - only when tracing is enabled UnloadRecursive - Every request

15. What are the different types of assemblies available and their purpose? Ans : Private, Public/shared and Satellite Assemblies. Private Assemblies : Assembly used within an application is known as private assemblies. Public/shared Assemblies : Assembly which can be shared across applicaiton is known as shared assemblies. Strong Name has to be created to create a shared assembly. This can be done using SN.EXE. The same has to be registered using GACUtil.exe (Global Assembly Cache). Satellite Assemblies : These assemblies contain resource files pertaining to a locale (Culture+Language). These assemblies are used in deploying an Gloabl applicaiton for different languages. 16. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other? Server.Transfer() : client is shown as it is on the requesting page only, but the all the content is of the requested page. Data can be persist accros the pages using Context.Item collection, which is one of the best way to transfer data from one page to another keeping the page state alive. Response.Dedirect() :client know the physical location (page name and query string as well).

Context.Items loses the persisitance when nevigate to destination page. In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but they're difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes 7scalability problems. As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client. 17.Describe the role of inetinfo.exe, aspnet_isapi.dll and aspnet_wp.exe in the page loading process ? Ans : inetinfo.exe is the Microsoft IIS server running, handling ASP.NET requests among other things. When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request to the actual worker process aspnet_wp.exe. 18. Where do you store the information about the users locale? Ans : System.Web.UI.Page.Culture 19. Describe the difference between inline and code behind. Ans : Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page. 20. What is different b/w webconfig.xml & Machineconfig.xml Web.config & machine.config both are configuration files.Web.config contains settings specific to an application where as machine.config contains settings to a computer. The Configuration system first searches settings in machine.config file & then looks in application configuration files.Web.config, can appear in multiple directories on an ASP.NET Web application server. Each Web.config file applies configuration settings to its own directory and all child directories below it. There is only Machine.config file on a web server. If I'm developing an application that must accomodate multiple security levels though secure login and my ASP.NET web appplication is spanned across three web-servers (using round-robbin load balancing) what would be the best approach to maintain login-in state for the users? Use the state server or store the state in the database. This can be easily done through simple setting change in the web.config. <SESSIONSTATE StateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1; user id=sa; password=" cookieless="false" timeout="30" /> You can specify mode as stateserver or sqlserver. Where would you use an iHTTPModule, and what are the limitations of any approach you might take in implementing one "One of ASP.NET's most useful features is the extensibility of the HTTP pipeline, the path that data takes between client and server. You can use them to extend your ASP.NET applications by adding pre- and post-processing to each HTTP request coming into your application. For example, if you wanted custom authentication facilities for your application, the best technique would be to intercept the request when it comes in and process the request in a custom HTTP module. 21. How is the DLL Hell problem solved in .NET? Ans : Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly. 22. What are the ways to deploy an assembly? Ans : An MSI installer, a CAB archive, and XCOPY command.

23. What is a satellite assembly? Ans : When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies. 24. What namespaces are necessary to create a localized application? Ans : System.Globalization and System.Resources. 25. What is the smallest unit of execution in .NET? Ans : an Assembly. 26. When should you call the garbage collector in .NET? Ans : As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice. 27. How do you convert a value-type to a reference-type? Ans : Use Boxing. 28. What happens in memory when you Box and Unbox a value-type? Ans : Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack 29. Describe the difference between a Thread and a Process? Ans : A Process is an instance of an running application. And a thread is the Execution stream of the Process. A process can have multiple Thread. When a process starts a specific memory area is allocated to it. When there is multiple thread in a process, each thread gets a memory for storing the variables in it and plus they can access to the global variables which is common for all the thread. Eg.A Microsoft Word is a Application. When you open a word file,an instance of the Word starts and a process is allocated to this instance which has one thread. 30. What is the difference between an EXE and a DLL? Ans : You can create an objects of Dll but not of the EXE. Dll is an In-Process Component whereas EXE is an OUt-Process Component.Exe is for single use whereas you can use Dll for multiple use. Exe can be started as standalone where dll cannot be. 31. What is strong-typing versus weak-typing? Which is preferred? Why? Ans : Strong typing implies that the types of variables involved in operations are associated to the variable, checked at compile-time, and require explicit conversion; weak typing implies that they are associated to the value, checked at run-time, and are implicitly converted as required. (Which is preferred is a disputable point, but I personally prefer strong typing because I like my errors to be found as soon as possible.) 32. What is the GAC? What problem does it solve? Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies that are to be shared by several applications on the computer. This area is typically the folder under windows or winnt in the machine. All the assemblies that need to be shared across applications need to be done through the Global assembly Cache only. However it is not necessary to install assemblies into the global assembly cache to make them accessible to COM interop or unmanaged code. There are several ways to deploy an assembly into the global assembly cache: Use an installer designed to work with the global assembly cache. This is the preferred option for installing assemblies into the global assembly cache.

Use a developer tool called the Global Assembly Cache tool (Gacutil.exe), provided by the .NET Framework SDK. Use Windows Explorer to drag assemblies into the cache. GAC solves the problem of DLL Hell and DLL versioning. Unlike earlier situations, GAC can hold two assemblies of the same name but different version. This ensures that the applications which access a particular assembly continue to access the same assembly even if another version of that assembly is installed on that machine. 33. What is an Asssembly Qualified Name? Is it a filename? How is it different? An assembly qualified name isn't the filename of the assembly; it's the internal name of the assembly combined with the assembly version, culture, and public key, thus making it unique. e.g. (""System.Xml.XmlDocument, System.Xml, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"") 34. How is a strongly-named assembly different from one that isnt strongly-named? Strong names are used to enable the stricter naming requirements associated with shared assemblies. These strong names are created by a .NET utility sn.exe Strong names have three goals: Name uniqueness. Shared assemblies must have names that are globally unique. Prevent name spoofing. Developers don't want someone else releasing a subsequent version of one of your assemblies and falsely claim it came from you, either by accident or intentionally. Provide identity on reference. When resolving a reference to an assembly, strong names are used to guarantee the assembly that is loaded came from the expected publisher. Strong names are implemented using standard public key cryptography. In general, the process works as follows: The author of an assembly generates a key pair (or uses an existing one), signs the file containing the manifest with the private key, and makes the public key available to callers. When references are made to the assembly, the caller records the public key corresponding to the private key used to generate the strong name. Weak named assemblies are not suitable to be added in GAC and shared. It is essential for an assembly to be strong named. Strong naming prevents tampering and enables assemblies to be placed in the GAC alongside other assemblies of the same name 35. Explain the importance and use of each, Version, Culture and PublicKeyToken for an assembly. This three alongwith name of the assembly provide a strong name or fully qualified name to the assembly. When a assebly is referenced with all three. PublicKeyToken: Each assembly can have a public key embedded in its manifest that identifies the developer. This ensures that once the assembly ships, no one can modify the code or other resources contained in the assembly. Culture: Specifies which culture the assembly supports Version: The version number of the assembly.It is of the following form major.minor.build.revision. Explain the differences between public, protected, private and internal. These all are access modifier and they governs the access level. They can be applied to class, methods, fields. Public: Allows class, methods, fields to be accessible from anywhere i.e. within and outside an assembly. Private: When applied to field and method allows to be accessible within a class. Protected: Similar to private but can be accessed by members of derived class also. Internal: They are public within the assembly i.e. they can be accessed by anyone within an assembly but outside assembly they are not visible.

36. What is difference between MetaData and Manifest? Metadata and Manifest forms an integral part of an assembly( dll / exe ) in .net framework . Out of which Metadata is a mandatory component , which as the name suggests gives the details about various components of IL code viz : Methods , properties , fields , class etc. Essentially Metadata maintains details in form of tables like Methods Metadata tables , Properties Metadata tables , which maintains the list of given type and other details like access specifier , return type etc. Now Manifest is a part of metadata only , fully called as manifest metadata tables , it contains the details of the references needed by the assembly of any other external assembly / type , it could be a custom assembly or standard System namespace . Now for an assembly that can independently exists and used in the .Net world both the things ( Metadata with Manifest ) are mandatory , so that it can be fully described assembly and can be ported anywhere without any system dependency . Essentially .Net framework can read all assembly related information from assembly itself at runtime . But for .Net modules , that cant be used independently , until they are being packaged as a part of an assembly , they dont contain Manifest but their complete structure is defined by their respective metadata . Ultimately . .Net modules use Manifest Metadata tables of parent assembly which contain them . 37. How do assemblies find each other? By searching directory paths. There are several factors which can affect the path (such as the AppDomain host, and application configuration files), but for private assemblies the search path is normally the application's directory and its sub-directories. For shared assemblies, the search path is normally same as the private assembly path plus the shared assembly cache. 38. How does assembly versioning work? Each assembly has a version number called the compatibility version. Also each reference to an assembly (from another assembly) includes both the name and version of the referenced assembly.The version number has four numeric parts (e.g. 5.5.2.33). Assemblies with either of the first two parts different are normally viewed as incompatible. If the first two parts are the same, but the third is different, the assemblies are deemed as 'maybe compatible'. If only the fourth part is different, the assemblies are deemed compatible. However, this is just the default guideline - it is the version policy that decides to what extent these rules are enforced. The version policy can be specified via the application configuration file. 38. What is garbage collection? Garbage collection is a system whereby a run-time component takes responsibility for managing the lifetime of objects and the heap memory that they occupy. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time. 40. Why doesn't the .NET runtime offer deterministic destruction? Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away - it only finds out during the next sweep of the heap. Futhermore, this type of algorithm works best by performing the garbage collection sweep as rarely as possible. Normally heap exhaustion is the trigger for a collection sweep. 41. Is the lack of deterministic destruction in .NET a problem? It's certainly an issue that affects component design. If you have objects that maintain expensive or scarce resources (e.g. database locks), you need to provide some way for the client to tell the object to release the resource when it is done. Microsoft recommend that you provide a method called Dispose() for this purpose. However, this causes problems for distributed objects - in a distributed system who calls the Dispose() method? Some form of reference-counting or ownership-management mechanism is needed to handle distributed objects - unfortunately the runtime offers no help with this.

42. What is the use of JIT ? JIT (Just - In - Time) is a compiler which converts MSIL code to Because the common language runtime supplies a JIT compiler for each supported CPU architecture, developers can write a set of MSIL that can be JIT-compiled and run on computers with different architectures. However, your managed code will run only on a specific operating system if it calls platform-specific native APIs, or a platform-specific class library. JIT compilation takes into account the fact that some code might never get called during execution. Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as needed during execution and stores the resulting native code so that it is accessible for subsequent calls. The loader creates and attaches a stub to each of a type's methods when the type is loaded. On the initial call to the method, the stub passes control to the JIT compiler, which converts the MSIL for that method into native code and modifies the stub to direct execution to the location of the native code. Subsequent calls of the JIT-compiled method proceed directly to the native code that was previously generated, reducing the time it takes to JIT-compile and run the code. 43.What is delay signing? Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development. 44. Whats the difference between Response.Write() and Response.Output.Write()? Ans : Response.Output.Write() allows you to write formatted output. 45. When during the page processing cycle is ViewState available? Ans : After the Init() and before the Page_Load(), or OnLoad() for a control. 46. Whats a bubbled event? Ans : When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their event handlers, allowing the main DataGrid event handler to take care of its constituents. 47. What data types do the RangeValidator control support? Ans : Integer, String, and Date. 48. Explain the differences between Server-side and Client-side code? Ans : Server-side code executes on the server. Client-side code executes in the client's browser. 49. What type of code (server or client) is found in a Code-Behind class? Ans : The answer is server-side code since code-behind is executed on the server. However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code. 50. Should user input data validation occur server-side or client-side? Why? Ans : All user input data validation should occur on the server at a minimum. Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user. 51. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset? Valid answers are: A DataSet can represent an entire relational database in memory, complete with tables, relations, and views. A DataSet is designed to work without any continuing connection to the original data source. Data in a DataSet is bulk-loaded, rather than being loaded on demand. There's no concept of cursor types in a DataSet. DataSets have no current record pointer You can use For Each loops to move through the data.

You can store many edits in a DataSet, and write them to the original data source in a single operation. Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources. 52. What are the Application_Start and Session_Start subroutines used for? Ans : This is where you can set the specific variables for the Application and Session objects. 53. Can you explain what inheritance is and an example of when you might use it? Ans : When you want to inherit (use the functionality of) another class. Example: With a base class named Employee, a Manager class could be derived from the Employee base class. 54. Whats MSIL, and why should developers need an appreciation of it if at all? Ans : MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer. 55. Which method do you invoke on the DataAdapter control to load your generated dataset with data? Ans : The Fill() method. 56. Can you edit data in the Repeater control? Ans : No, it just reads the information from its data source. 57. Which template must you provide, in order to display data in a Repeater control? Ans : ItemTemplate. 58. How can you provide an alternating color scheme in a Repeater control? Ans : Use the AlternatingItemTemplate. 59. What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control? Ans : You must set the DataSource property and call the DataBind method. 60. Name two properties common in every validation control? Ans : ControlToValidate property and Text property. 61. Which control would you use if you needed to make sure the values in two different controls matched? Ans : CompareValidator control. 62. How many classes can a single .NET DLL contain? Ans : It can contain many classes. 63. What is the lifespan for items stored in ViewState? Ans : Item stored in ViewState exist for the life of the current page. This includes postbacks (to the same page). 64. What does the "EnableViewState" property do? Why would I want it on or off? Ans : It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate. 65. What are the different types of Session state management options available with ASP.NET? Ans : ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server. Out-of-Process Session state

management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable. 66. What is the difference between Value Types and Reference Types? Ans : Value Types uses Stack to store the data where as the later uses the Heap to store the data. 67. What are user controls and custom controls? Custom controls: A control authored by a user or a third-party software vendor that does not belong to the .NET Framework class library. This is a generic term that includes user controls. A custom server control is used in Web Forms (ASP.NET pages). A custom client control is used in Windows Forms applications. User Controls: In ASP.NET: A user-authored server control that enables an ASP.NET page to be reused as a server control. An ASP.NET user control is authored declaratively and persisted as a text file with an .ascx extension. The ASP.NET page framework compiles a user control on the fly to a class that derives from the System.Web.UI.UserControl class. 68. What are the validation controls? A set of server controls included with ASP.NET that test user input in HTML and Web server controls for programmer-defined requirements. Validation controls perform input checking in server code. If the user is working with a browser that supports DHTML, the validation controls can also perform validation using client script. 69. Where do you add an event handler? It's the Attributesproperty, the Add function inside that property. e.g. btnSubmit.Attributes.Add("onMouseOver","someClientCode();") 70. What data type does the RangeValidator control support? Integer,String and Date.

C# Interview Questions 1. Whats the implicit name of the parameter that gets passed into the class set
method? Value, and its datatype depends on whatever variable were changing. class. Notice that its double colon in C++.

2. How do you inherit from a class in C#? Place a colon and then the name of the base 3. Does C# support multiple inheritance? No, use interfaces instead. 4. When you inherit a protected class-level variable, who is it available to? Classes in
the same namespace.

5. 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.

6. Describe the accessibility modifier protected internal. Its available to derived

classes and classes within the same Assembly (and naturally from the base class its declared in). as a parameter, but want to keep the no parameter one. How many constructors should I write? Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if theres no implementation in it.

7. C# provides a default constructor for me. I write a constructor that takes a string

8. Whats the top .NET class that everything is derived from? System.Object. 9. Hows method overriding different from overloading? When overriding, you change
the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

10. What does the keyword virtual mean in the method definition? The method can be
over-ridden.

11. Can you declare the override method static while the original method is non-

static? No, you cant, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override. methods in inherited classes, have to be protected in the base class to allow any sort of access.

12. Can you override private virtual methods? No, moreover, you cannot access private 13. Can you prevent your class from being inherited and becoming a base class for

some other classes? Yes, thats what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. Its the same concept as final class in Java. ridden? Yes, just leave the class public and make the method sealed.

14. Can you allow class to be inherited, but prevent the method from being over15. Whats an abstract class? A class that cannot be instantiated. A concept in C++ known 16. When do you absolutely have to declare a class as abstract (as opposed to freewilled educated choice or decision based on UML diagram)? When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden. which must be implemented in the inherited classes.

as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, its a blueprint for a class without any implementation.

17. Whats an interface class? Its an abstract class with public abstract methods all of 18. Why cant you specify the accessibility modifier for methods inside the interface?
They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, its public by default.

19. Can you inherit multiple interfaces? Yes, why not. 20. And if they have conflicting method names? Its up to you to implement the method
inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares youre okay.

21. Whats the difference between an interface and abstract class? In the interface all
methods must be abstract; in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes. parameters, different order of parameters.

22. How can you overload a method? Different parameter data types, different number of 23. If a base class has a bunch of overloaded constructors, and an inherited class has
another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

24. Whats the difference between System.String and System.StringBuilder classes?


System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

25. Whats the advantage of using System.Text.StringBuilder over System.String?


StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time its being operated on, a new instance is created.

26. Can you store multiple data types in System.Array? No.

27. Whats the difference between the System.Array.CopyTo() and


System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow.

28. How can you sort the elements of the array in descending order? By calling Sort()
and then Reverse() methods.

29. Whats the .NET datatype that allows the retrieval of data by a unique key?
HashTable.

30. Whats class SortedList underneath? A sorted HashTable. 31. Will finally block get executed if the exception had not occurred? Yes. 32. Whats the C# equivalent of C++ catch (), which was a catch-all statement for
any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

33. Can multiple catch blocks be executed? No, once the proper catch code fires off, the 34. Why is it a bad idea to throw your own exceptions? Well, if at that point you know
that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project. they were referred to as function pointers.

control is transferred to the finally block (if there are any), and then whatever follows the finally block.

35. Whats a delegate? A delegate object encapsulates a reference to a method. In C++ 36. Whats a multicast delegate? Its a delegate that points to and eventually fires off
several methods.

37. Hows the DLL Hell problem solved in .NET? Assembly versioning allows the
application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

38. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and
XCOPY command.

39. Whats a satellite assembly? When you write a multilingual or multi-cultural application
in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies. System.Globalization, System.Resources.

40. What namespaces are necessary to create a localized application? 41. Whats the difference between // comments, /* */ comments and ///
comments? Single-line, multi-line and XML documentation comments.

42. How do you generate documentation from the C# file commented properly with a
command-line compiler? Compile it with a /doc switch. line code example and multiple-line code example.

43. Whats the difference between <c> and <code> XML documentation tag? Single 44. Is XML case-sensitive? Yes, so <Student> and <student> are different elements. 45. What debugging tools come with the .NET SDK? CorDBG command-line debugger, 46. What does the This window show in the debugger? It points to the object thats
pointed to by this reference. Objects instance data is shown. and DbgCLR graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.

47. What does assert() do? In debug compilation, assert takes in a Boolean condition as a
parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

48. Whats the difference between the Debug class and Trace class? Documentation
looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

49. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The


tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.

50. Where is the output of TextWriterTraceListener redirected? To the Console or a text


file depending on the parameter passed to the constructor. to the DbgClr debugger.

51. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process 52. What are three test cases you should go through in unit testing? Positive test cases
(correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly). you are debugging via Visual Studio.NET, just go to Immediate window.

53. Can you change the value of a variable while debugging a C# application? Yes, if 54. Explain the three services model (three-tier application). Presentation (UI),
business (logic and underlying code) and data (from storage or other sources).

55. What are advantages and disadvantages of Microsoft-provided data provider

classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but its a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines. only dataset from the data source when the command is executed.

56. Whats the role of the DataReader class in ADO.NET connections? It returns a read57. What is the wildcard character in SQL? Lets say you want to query database with
LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve La%.

58. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one

unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no in-between case where something has been updated and something hasnt), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after). Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).

59. What connections does Microsoft SQL Server support? Windows Authentication (via 60. Which one is trusted and which one is untrusted? Windows Authentication is trusted
because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.

61. Why would you use untrusted verificaion? Web Services might use it, as well as nonWindows applications.

62. What does the parameter Initial Catalog define inside Connection String? The
database name to connect to.

63. Whats the data provider name to connect to Access database? Microsoft.Access. 64. What does Dispose method do with the connection object? Deletes it from the
memory.

65. What is a pre-requisite for connection pooling? Multiple processes must agree that
they will share the same connection, where every parameter is the same, including the security settings.

You might also like