.net interview questions wid answers

26
1 ADO.NET Sunday, January 15, 2012 What is the difference between Execute Reader, Execute Scalar and Execute Non Query methods? Execute Reader Execute Reader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object. Execute Scalar Execute Scalar will be used to return the single value, on execution of SQL Query or Stored procedure using command object. Execute Non Query If the command or stored procedure performs INSERT, DELETE or UPDATE operations, then we use Execute Non Query method. Execute Non Query method returns an integer specifying the number of rows inserted, deleted or updated. What are the different steps to access a database through ADO.NET? Create a connection to the database using a connection object. Open the Database Connection. Invoke a command to create a Dataset object using an adapter object. Use the Dataset object in code to display data or to change items in the database. Invoke a command to update the database from the Dataset object using an adapter object. Close the database connection. What are the Benefits of ADO.Net? ADO.Net offers following Benefits Interoperability: XML Format is one of the best formats for Interoperability.ADO.NET supports to transmit the data using XML format. Scalability: ADO.NET works on Dataset that can represent a whole database or even a data table as a disconnected object and thereby eliminates the problem of the constraints of number of databases being connected. In this way scalability is achieved. Performance: The performance in ADO.NET is higher in comparison to ADO that uses COM marshalling. Programmability: ADO.Net Data components in Visual studio help to do easy program to connect to the database.

Transcript of .net interview questions wid answers

Page 1: .net interview questions wid answers

1

ADO.NET

Sunday, January 15, 2012

What is the difference between Execute Reader, Execute Scalar and Execute Non Query methods?

Execute ReaderExecute Reader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object.

Execute ScalarExecute Scalar will be used to return the single value, on execution of SQL Query or Stored procedure using command object.

Execute Non QueryIf the command or stored procedure performs INSERT, DELETE or UPDATE operations, then we use Execute Non Query method. Execute Non Query method returns an integer specifying the number of rows inserted, deleted or updated.

What are the different steps to access a database through ADO.NET?

Create a connection to the database using a connection object.Open the Database Connection.Invoke a command to create a Dataset object using an adapter object.Use the Dataset object in code to display data or to change items in the database.Invoke a command to update the database from the Dataset object using an adapter object.Close the database connection.

What are the Benefits of ADO.Net?

ADO.Net offers following BenefitsInteroperability: XML Format is one of the best formats for Interoperability.ADO.NET supports to transmit the data using XML format.

Scalability: ADO.NET works on Dataset that can represent a whole database or even a data table as a disconnected object and thereby eliminates the problem of the constraints of number of databases being connected. In this way scalability is achieved.

Performance: The performance in ADO.NET is higher in comparison to ADO that uses COM marshalling.

Programmability:ADO.Net Data components in Visual studio help to do easy program to connect to the database.

What is Microsoft ADO.NET?

ADO.NET is one of the component in the Microsoft.NET framework which contains following features to Windows, web and distributed applications.

i. Data Access to the applications from Database in connected (Data reader object) and disconnected (Data set and data table) model.ii. Modify the data in database from application.

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 it's a .NET layer on top

Page 2: .net interview questions wid answers

2

of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.

Difference between Association rule mining and frequent itemset mining

An association rule is something like "A,B ? C", meaning that C tends to occur when A and B occur. An itemset is just a collection such as "A,B,C", and it is frequent if its items tend to co-occur. The usual way to look for association rules is to find all frequent itemsets and then postprocess them into rules

Named out assemblies and corresponding namespace of all .Net framework data provider.

a) .Net Framework Data Provider for SQL Server Assembly Name :- System.Data.dll NameSpace :- System.Data.SqlClient

b) .Net Framework Data Provider for OLE DB Server Assembly Name :- System.Data.dll NameSpace :- System.Data.OleDb

C) .Net Framework Data Provider for ODBCAssembly Name :- System.Data.ODBC

C) .Net Framework Data Provider for OracleAssembly Name :- System.Data.OracleClient.dllNameSpace :- System.Data.OracleClient

What are different .Net framework data provider.

The Four main types of .net framework data provider are a) .Net framework data provider for SQL server.b) .Net framework data provider for OLEDBc) .Net framework data provider for ODBCd) .Net framework data provider for Oracle.

List out Some feature of ADO.net The Key feature of ADO.Net are a) Disconnected Data Architecture b) Data cached in datasetsc) Scalability d) Data transfer in XML format.

What is Difference between SqlCommand and SqlCommandBuilder

SQLCommand is used to execute all kind of SQL queries like DML(Insert, update,Delete) & DDL like(Create table, drop table etc) where as SQLCommandBuilder object is used to build & execute SQL (DML) queries like select, insert, update & delete.

What is the Use of Connection Object ?

In order to interact with any database we need a Connection . This connection enables us to know the Server Name, User-Id,Password,Database Name. These are the main requirements to connect to a Database.

So in our Connection string we provide all those above mentioned properties as parameters.

Page 3: .net interview questions wid answers

3

Different Connection objects : SqlConnection, OleDbConnection, OdbcConnection

. OleDbConnection object is used with an OLE-Db Provider

OleDbConnection cnn ;

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;

Data Source=DatabaseName;";

cnn = new OleDbConnection(connetionString);

. SqlConnection object used the Tabular Data Services (TDS) With MS Sql Server.

SqlConnection con;

con = new SqlConnection("server=SERVER NAME;user id=ID;password=PASSWORD;database=DB NAME");

SqlCommand cmd;

cmd = new SqlCommand("DB Query Here",con);

. Using the OdbcConnection , we will create an OdbcCommand. From that command we can issue a Query and create an OdbcDataReader.

OdbcConnection DbConnection = new OdbcConnection("Connection String");

OdbcCommand DbCommand = DbConnection.CreateCommand();

DbCommand.CommandText = "Db Query Here";

OdbcDataReader DbReader = DbCommand.ExecuteReader();

What is the use of dataview?

Data view is used to sort and find data in a data table.

What is the use of data adapter?

These objects connect one or more Command objects to a Dataset object. They provide logic that would get data from the data store and populates the tables in the Dataset, or pushes the changes in the Dataset back into the data store.. An OleDbDataAdapter object is used with an OLE-DB provider. A SqlDataAdapter object uses Tabular Data Services with MS SQL Server.

What are the two fundamental objects in ADO.NET?

Data reader and Dataset are the two fundamental objects in ADO.NET.

What are the benefits of ADO.NET?

BENEFITS OF ADO.NET

1>Scalability:-ADO.NET works on DataSet that can represent a whole database or even a data table as a disconnected object and thereby

Page 4: .net interview questions wid answers

4

eliminates the problem of the constraints of number of databases being connected. In this way scalability is achieved.

2>Data Source Independence:-In ADO.NET DataSet is completely independent of data source and no way DataSet is controlled by the data source as it happens in case of RecordSet.

3>Interoperability:-As ADO.NET transmits the data using the format of XML which is not dependent on ADO.NET or windows platform.

4>Strongly Typed Fields:-It supports strongly typed fields by using CTS.

5>Performance:-The performance in ADO.NET is higher in comparison to ADO that uses COM marshalling.

6>Firewall:As in ADO.NET transmission is via XML format, therefore it can pass through firewalls.

What is GetSchemaTable() in ADO.NET

The GetSchemaTable method returns a DataTable property that contains the column schema for a DataReader. The DataTable contains one row for each field in the resultset. Each column maps to a property of the field in the resultset. The ColumnName property of the DataTable column is the name of the field's property, such as the ColumnName, DataType, ColumnSize, IsKeyColumn, or IsAutoIncrement property. The value of the DataTable column is the value of the field's property, such as the FirstName value for the ColumnName property.

ado VS ado.Net*)ado is connected mode always where as ado.net is connected as well as disconnected.*)ado ---recordset whereas ado.net ---dataset*)ado---c,c++whereas ado.net---- .net framework*)ado--server based whereas ado.net --client

What is Dataset?A DataSet is Disconnected Architecture,means their is no need to always open & close connection. It is cache of data retrieved from database. It is made up of collection of datatable. Dataset can be Typed & UnTyped usually, datasets are typed in Visual basic.A typed dataset is dataset which derived from dataset class & uses information in XML schema file(XSD file).An untyped dataset has no built in schema.it can contain tables,column & rows.but those are exposed only as collections

What is the default TimeOut for a SqlCommand.CommandTimeout property?

The default timeOut is 30 seconds.

If you want to increase the TimeOut see the below example codeFor example:-

SqlCommand cmd = new SqlCommand("select * from tablename", conn);

cmd.CommandTimeout = 50;

SqlDataReader dr = cmd.ExecuteReader();

What is a DataSet?

The Dataset is the central object in ADO.NET. DataSet is a nogical container of data. It represents a set of data tables referenced

Page 5: .net interview questions wid answers

5

as one unit in the application.

With this object you can get all the data you need from each table quickly, examine and change it while you are disconnected from the server and then update the server with changes in an efficient operation.

How to fill DataSet with data?

To fill DataSet with data we have to use Fill() method of DataAdapter object.

Fill() has several overloads. But the simple one is [CODE]Fill(DataSet, DataTable)[/CODE] The first parameter will take the name of the dataset to be filled and the second parameter specifies the name of the DataTable in the DataSet which will contain the data.

what is difference Between datareader and dataset ?

DataReader===========DataReader is like a forward only recordset. It fetches one row at a time so very less network cost compare to DataSet(Fethces all the rows at a time). DataReader is readonly so we can't do any transaction on them. DataReader will be the best choice where we need to show the data to the user which requires no transaction. As DataReader is forward only so we can't fetch data randomly. .NET Data Providers optimizes the datareader to handle huge amount of data.

Dataset=======DataSet is an in memory representation of a collection of Database objects including tables of a relational database schemas.DataSet is always a bulky object that requires a lot of memory space compare to DataReader. We can say that the DataSet is a small database because it stores the schema and data in the application memory area. DataSet fetches all data from the datasource at a time to its memory area. So we can traverse through the object to get the required data like querying database.

What are the differences between ADO and ADO.NET?

ADO relied on a connection based model. In the connected approach, the client had to be connected with the server and remain connected till the whole procedure or transaction was completed. Time resources and bandwidth became major constraints on such architecture.

To solve this problem the latter version of ADO used RecordSet. All the contents from the data source were copied into RecordSet. This allows clients to get disconnected from the server, work on the RecordSet and copy the changes back to the data source again. This approach did not succeed much because it requires COM marshalling to transmit disconnected data, it support only those datatypes that were defined by the COM standards and hence required type conversion.

ADO.NET can be used to access data sources using new .NET data providers as well as existing OLEDB data providers using the OLEDB.NET data provider.

What are the components of .NET DataProvider?

The .NET DataProvider is a set of components that includes the Connection, Command, DataReader and DataAdapter objects. It is used for connecting to a database , executing commands and retrieving results. Using the .NET data provider we can either access database directly or use the disconnected approach. For the disconnected approach we use DataSet class.

Connection Object:-It is used to connect to the data source. Data source can be any database file. The connection object contains information like the provider name, server name, datasource name, user name and password.

Command Object:- It is used for connect the connection object to a DataReader or DataAdapter object. The command object allow us to execute SQL statement or a stored procedure in a data source.

DataReader Object:- It is used to read the data in a fast and efficient manner from the database. It is generally used to extract one or a few records or specific field values or to execute simple SQL statement.

Page 6: .net interview questions wid answers

6

DataAdapter Object:- It is used to fill data from the database into the DataSet object. it is use din the disconnected approach.

What are the benefits of ADO.NET?

BENEFITS OF ADO.NET--------------------1>Scalability:-ADO.NET works on DataSet that can represent a whole database or even a data table as a disconnected object and thereby eliminates the problem of the constraints of number of databases being connected. In this way scalability is achieved.

2>Data Source Independence:-In ADO.NET DataSet is completely independent of data source and no way DataSet is controlled by the data source as it happens in case of RecordSet.

3>Interoperability:-As ADO.NET transmits the data using the format of XML which is not dependent on ADO.NET or windows platform.

4>Strongly Typed Fields:-It supports strongly typed fields by using CTS.

5>Performance:-The performance in ADO.NET is higher in comparison to ADO that uses COM marshalling.

6>Firewall:As in ADO.NET transmission is via XML format, therefore it can pass through firewalls.

Which method do you invoke on the DataAdapter control to load your generateddataset with data?

System.Data.Common.DataAdapter.Fill(System.Data.DataSet);

Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?

In ADO, the in-memory representation of data is the recordset. In ADO.NET, it is the dataset. There are important differences between them. o 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. A dataset usually also contains relationships. A relationship within a dataset is analogous to a foreign-key relationship in a database -that is, it associates rows of the tables with each other. For example, if a dataset contains a table about investors and another table about each investor's stock purchases, it could also contain a relationship connecting each row of the investor table with the corresponding rows of the purchase table. Because the dataset can hold multiple, separate tables and maintain information about relationships between them, it can hold much richer data structures than a recordset, including self-relating tables and tables with many-to-many relationships. o 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. DataRelation objects maintain information about master and detail records and provide a method that allows you to get records related to the one you are working with. For example, starting from the row of the Investor table for "Nate Sun," you can navigate to the set of rows of the Purchase table describing his purchases. 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. For more information about cursor functionality, see Data Access Technologies.o Minimized Open Connections: In ADO.NET you open connections only long enough to perform a database operation, such as a Select or Update. You can read rows into a dataset and then work with them without staying connected to the data source. In ADO the recordset can provide disconnected access, but ADO is designed primarily for connected access. There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you communicate with the database by

Page 7: .net interview questions wid answers

7

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. The important difference is that in ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database - by optimizing for performance, performing data validation checks, or adding any other extra processing. Data adapters, data connections, data commands, and data readers are the components that make up a .NET Framework data provider. Microsoft and third-party providers can make available other .NET Framework data providers that can be integrated into Visual Studio.o Sharing Data Between Applications. Transmitting an ADO.NET dataset between applications is much easier than transmitting an ADO disconnected recordset. To transmit an ADO disconnected recordset from one component to another, you use COM marshalling. To transmit data in ADO.NET, you use a dataset, which can transmit an XML stream.o Richer data types.COM marshalling provides a limited set of data types - those defined by the COM standard. Because the transmission of datasets in ADO.NET is based on an XML format, there is no restriction on data types. Thus, the components sharing the dataset can use whatever rich set of data types they would ordinarily use.o Performance. Transmitting a large ADO recordset or a large ADO.NET dataset can consume network resources; as the amount of data grows, the stress placed on the network also rises. Both ADO and ADO.NET let you minimize which data is transmitted. But ADO.NET offers another performance advantage, in that ADO.NET does not require data-type conversions. ADO, which requires COM marshalling to transmit records sets among components, does require that ADO data types be converted to COM data types.o Penetrating Firewalls.A firewall can interfere with two components trying to transmit disconnected ADO recordsets. Remember, firewalls are typically configured to allow HTML text to pass, but to prevent system-level requests (such as COM marshalling) from passing.

What is the use of DataSet?

DataSet acts as a virtual table. The value is retrieved from the database and stores in the DataSet. Then we can pass the data to the DataGrid through DataSet.

What is Dataview in ADO Dot Net ?

The DataView provides different views of the data stored in a DataTable. That is we can customize the views of data from a DataTable. DataView can be used to sort, filter, and search the data in a DataTable , additionally we can add new rows and modify the content in a DataTable.

We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to the DefaultView property of the DataTable.

DataView dView = new DataView(dTbl);dView = dataSet.Tables(0).DefaultView;

Name the classes are found in System.Data.Common NameSpace?

1)DataColumnMapping2)DataTableMapping

Name the classes that are contained in System.Data NameSpace?

DataSetDataTableDataColumnDataRowDataRealationConstraint

Which is the default Provider Name of the Providers used to access the DataBase?

System.Data.SqlClient

Page 8: .net interview questions wid answers

8

Does ADO.NET supports automatic connection pooling?

Yes. There is a pooling property with connection string. By default it is set to true. Use this property to specify that a particular connection should not participate in the pool, but instead should be destroyed when it is closed.

Between Windows Authentication and SQL Server Authentication, 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.

What connections does Microsoft SQL Server support?

Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).

To perform asynchronous data access, what must be added to the connection string?

Select Correct Answer.

1. BeginExecute=true2. MultiThreaded=true3. MultipleActiveResultSets=true4. Asynchronous=true

Correct Answer:4. Asynchronous=true

You are working with a DataSet and want to be able to display data, sorted different ways. How do you do so?

Select the correct answer.

1. Use the Sort method on the DataTable object.2. Use the DataSet object's Sort method.3. Use a DataView object for each sort.4. Create a DataTable for each sort, using the DataTable object's Copy method, and then Sort the result

Correct Answer is :3. Use a DataView object for each sort.

Best Method to retrieve two values from Database (SQL Server)

ExecuteNonQuery() using Output parameter.

How to add auto increment column in the DataTable?

To add auto increment column in the DataTable, we can set the AutoIncrement property of the DataColumn object as true and specify the seed value after adding that field into the DataTable object. // create columns for the DataTable

DataTable dTable = new DataTable();

Page 9: .net interview questions wid answers

9

DataColumn auto = new DataColumn("AutoID", typeof(System.Int32));

dTable.Columns.Add(auto);

// specify it as auto increment field

auto.AutoIncrement = true;

auto.AutoIncrementSeed = 1;

auto.ReadOnly = true;

Explain about LINQ?

Language integrated query or LINQ provides developers to query data. It uses strongly typed queries and results. Developer productivity increases by the usage of compile time error checking and intellisense. This feature is common on number of data types.

Explain about Db enumerator?

This base class is added to ADO.NET 2.0. This class facilitates the process of obtaining a list of data sources. SQL server returns instances that are available on the network. Programmers do have choice of tools in their hands with this feature.

Explain about data provider?

ADO.NET has two primary parts in its architecture out of which one is data provider. It has its own set of objects and it consists of its own classes. Some of them are connection, parameter, data reader, command and data adapter. This provides access to data sources such as Oracle, SQL server, etc.

Difference between Response.Expires and Response.ExpiresAbsolute?

Response.Expires This property specifies the number of minutes before a page cached in the browser expires ie. if the user returns to the same page before the specified number of minutes the cached version of the page is displayed.

Response.ExpiresAbsolute Using this property we can set the date and/or time at which page cached in the browser expires.

What is the location of Global Assembly Cache on the system?

C:\$WINDOWS\assembly

How can we check that some changes have been made to dataset since it was loaded?

The changes made to the dataset can be tracked using the GetChanges and HasChanges methods.GetChanges():-------------The GetChanges returns dataset which are changed since it was loaded or since Acceptchanges was executed.

HasChanges():------------The HasChanges property indicates if any changes were made to the dataset since it was loaded or if acceptchanges method was executed.

Page 10: .net interview questions wid answers

10

RejectChanges():----------------The RejectChanges can be used to revert thee changes made to the dataset since it was loaded

How to decide on the design consideration to take a Datagrid, datalist or repeater ?

Many make a blind choice of choosing datagrid directly, but that's not the right way.

Datagrid provides ability to allow the end-user to sort, page, and edit its data. But it comes at a cost of speed. Second the display format is simple that is in row and columns. Real life scenarios can be more demanding that

With its templates, the DataList provides more control over the look and feel of the displayed data than the DataGrid.

It offers better performance than datagrid Repeater control allows for complete and total control. With the Repeater, the only HTML emitted are the values of the databinding statements in the templates along with the HTML markup specified in the templates-no "extra" HTML is emitted, as with the DataGrid and DataList. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time. But repeater does not provide editing features like datagrid so everything has to be coded by programmer. However, the Repeater does boast the best performance of the three data Web controls. Repeater is fastest followed by Datalist and finally datagrid.

What is Thread.Join() in threading ?

There are two versions of Thread.Join :- . Thread.join(). . Thread.join(Integer) this returns a Boolean value. The Thread.Join method is useful for determining if a thread has completed before starting another task. The Join method waits a specified amount of time for a thread to end. If the thread ends before the time-out, Join returns true; otherwise it returns False. Once you call Join, the calling procedure stops and waits for the thread to signal that it is done. Example you have "Thread1" and "Thread2" and while executing 'Thread1" you call "Thread2.Join()".So "Thread1" will wait until "Thread2" has completed its execution and the again invoke "Thread1". Thread.Join(Integer) ensures that threads do not wait for a long time. If it exceeds a specific time which is provided in integer the waiting thread will start.

What the way to stop a long running thread ?

Thread.Abort() stops the thread execution at that moment itself.

What is Suspend and Resume in Threading ?

It is Similar to Sleep and Interrupt. Suspend allows you to block a thread until another thread calls Thread.Resume. The difference between Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The thread does not suspend until the .NET runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state. Note :- In threading interviews most people get confused with Sleep and Suspend. They look very similar.

How can we make a thread sleep for infinite period?

You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread.Sleep (System.Threading.Timeout.Infinite). To interrupt this sleep you can call the Thread.Interrupt method.

What's Thread.Sleep() in threading ?

Page 11: .net interview questions wid answers

11

Thread's execution can be caused by calling the Thread.Sleep method. This method takes an integer value that determines how long the thread should sleep. Example Thread.CurrentThread.Sleep(2000).

How can you reference current thread of the method ?

"Thread.CurrentThread" refers to the current thread running in the method."CurrentThread" is a public static property.

What does AddressOf operator do in background ?

The AddressOf operator creates a delegate object to the BackgroundProcess method. A delegate within VB.NET is a type-safe, object-oriented function pointer. After the thread has been instantiated, you begin the execution of the code by calling the Start() method of the thread.

How can we change priority and what the levels of priority are provided by .NET ?

Thread Priority can be changed by using Threadname.Priority = ThreadPriority.Highest. In the sample provided look out for code where the second thread is ran with a high priority. Following are different levels of Priority provided by .NET :- . ThreadPriority.Highest . ThreadPriority.AboveNormal . ThreadPriority.Normal . ThreadPriority.BelowNormal . ThreadPriority.Lowest

Can we have multiple threads in one App domain ?

One or more threads run in an AppDomain. An AppDomain is a runtime representation of a logical process within a physical process. Each AppDomain is started with a single thread, but can create additional threads from any of its threads. Note :- All threading classes are defined in System.Threading namespace.

What is CODE Access security?

CAS is part of .NET security model that determines whether or not a piece of code is allowed to run and what resources it can use while running. Example CAS will allow an application to read but not to write and delete a file or a resource from a folder.

What is COM ?

Microsoft's COM is a technology for component software development. It is a binary standard which is language independent. DCOM is a distributed extension of COM.

What is Reference counting in COM ?

Reference counting is a memory management technique used to count how many times an object has a pointer referring to it. The first time it is created, the reference count is set to one. When the last reference to the object is nulled, the reference count is set to zero and the object is deleted. Care must be exercised to prevent a context switch from changing the reference count at the time of deletion. In the methods that follow, the syntax is shortened to keep the scope of the discussion brief and manageable.

Can you describe IUKNOWN interface in short ?

Every COM object supports at least one interface, the IUnknown interface. All interfaces are classes derived from the base class IUnknown. Each interface supports methods access data and perform operations transparently to the programmer. For example, IUnknown supports three methods, AddRef, Release(), and QueryInterface(). Suppose that pinterf is a pointer to an IUnknown.

Page 12: .net interview questions wid answers

12

pinterf->AddRef() increments the reference count. pinterf->Release() decrements the reference count, deleting the object when the reference count reaches zero. pinterf->QueryInterface( IDesired, pDesired) checks to see if the current interface (IUnknown) supports another interface, IDesired, creates an instance (via a call to CoCreateInstance()) of the object if the reference count is zero (the object does not yet exist), and then calls pDesired->AddRef() to increment the reference count (where pDesired is a pointer to IDesired) and returns the pointer to the caller.

ado.net

Description

To introduce ADO.NET and to describe how to make connections to databases and run stored procedures and SQL statements in a connected design

1. Which of the following statements about stored procedures are true? Choose more than one option. 1. They reside on the client 2. They reside on the server True 3. You can encapsulate multiple SQL statements in a stored procedure True 4. You encapsulate a single SQL statement in each stored procedure

Topic title: Architecture of ADO.NET 2. Which of the following fully qualified names describes the data adapter for a SQL 2000 server? Choose an option.

System.Data.SqlClient.DataAdapter

System.Data.SqlClient.SqlDataAdapter True

System.Data.SqlDataAdapter

System.Xml.SqlDataAdapter

Topic title: Working with ADO.NET connections in VB.NET 3. Assuming that ReadNextOrder expects one parameter, which options accurately describe this code? Dim cnnOrders As SqlConnection Dim cmd As SqlCommand, drOrders As SqlDataReader cmd = New SqlCommand ("ReadNextOrder", cnnOrders) drOrders = cmd.ExecuteReader () Choose more than one option.

The connection must be opened explicitly True

The CommandType property must be set to StoredProcedure True

The ExecuteNonQuery method should be used for all stored procedures

The ExecuteReader method call will fail because no parameter has been added to the Parameters collection True

Topic title: Distributed data-access requirements 4. Which of the following attributes in a ConnectionString specifies the SQL Server server used when a connection is open? Choose an option.

Initial Catalog

Provider

Data Source True

ConnectionTimeout

Page 13: .net interview questions wid answers

13

Topic title: Distributed data-access requirements 5. Connected data-access applications are generally ___________ more than disconnected data-access applications. Choose an option below to fill in the blank.

complicated distributed scalable secure True suited to the Internet

Topic title: Pooling ADO.NET connections in VB.NET 6. Which of the following statements about the DataReader object are true? Choose more than one option.

The DataReader points to the first row of the result set after Read is first called True

You create a new DataReader using one of several overloaded constructors

You use the ExecuteScalar method of the Command object to obtain a DataReader

You use the NextResult method on the DataReader to get the next result set True

Topic title: Pooling ADO.NET connections in VB.NET 7. Which of the following methods of a DataReader enable you to obtain column metadata? Choose more than one option.

GetString

GetName True

GetOrdinal True

GetSchemaTable True

GetDateTime

Topic title: Defining an ADO.NET Connection object in VB.NET 8. Which of the following are implementations of Command classes for .NET data providers? Choose more than one option.

OdbcCommand objects True

OleDbCommand objects True

SqlCommand objects True

XMLCommand objects

Topic title: Defining an ADO.NET Connection object in VB.NET 9. Which of the following SqlConnection.ConnectionString attributes determines the number a seconds a connection can stay in a pool? Choose an option.

Connection Duration

Connection Lifetime True

Connection TimeOut

Connection Reset

Topic title: Pooling ADO.NET connections in VB.NET

Page 14: .net interview questions wid answers

14

10. To specify the name of a stored procedure in .NET code, you use a _____________ object. Choose an option below to fill in the blank.

DataSet SqlCommand True SqlConnection SqlDataAdapter

Topic title: Architecture of ADO.NET Which of the following objects exclusively contains metadata about tables? Choose an option.

The DataColumn object True

The DataRow object

The DataView object

The SqlDataAdapter object

Topic title: Distributed data-access requirements 11. Which of these namespaces do you need to reference to connect to a SQL database using the .NET provider for OLEDB? Choose more than one option.

System.Data True

System.Data.Connect

System.Data.Oledb True

System.Data.SqlClient

Topic title: Architecture of ADO.NET 13. What happens when you try to make the following assignment to an OleDbConnection.ConnectionString property and then try to open that connection? cnNew.ConnectionString = "Data Source=8044DYSZ033R\SQLLOCAL; Initial" & _ "Catalog=Northwind; User ID=sa;" cnNew.Open() Choose an option.

It fails to compile

It compiles and runs correctly

It compiles but throws an ArgumentException because no Provider is included True

It compiles but throws an OleDbException when you attempt to open it

Topic title: Architecture of ADO.NET 14. What happens when you try to make the following assignment to an OleDbConnection.ConnectionString property and then try to open that connection? cnNew.ConnectionString = "Data Source=8044DYSZ033R\SQLLOCAL; Initial" & _ "Catalog=Northwind; User ID=sa;" cnNew.Open() Choose an option.

It fails to compile

It compiles and runs correctly

It compiles but throws an ArgumentException because no Provider is included True

It compiles but throws an OleDbException when you attempt to open it

Page 15: .net interview questions wid answers

15

Topic title: Working with ADO.NET connections in VB.NET 15. Which combination of classes do you use when passing arguments to a stored procedure through the SQL .NET Data Provider? Choose an option.

Argument and SqlCommand

Parameter and SqlCommand

SqlArgument and SqlCommand

SqlParameter and SqlCommand True

Topic title: Working with ADO.NET connections in VB.NET 16. A Command object's property indicates whether an object encapsulates a stored procedure or a SQL statement, or is requesting a full table. Choose an option below to fill in the blank.

Connection CommandType True CommandText Parameters

Topic title: Architecture of ADO.NET Which method releases unmanaged resources when a connection is closed? Choose an option.

Delete

Dispose True

Open

Topic title: Working with ADO.NET connections in VB.NET 17. You use Visual Studio .NET's ___________ to create sequences of SQL commands. Choose an option below to fill in the blank.

Toolbox Query Analyzer tool True Properties window

Topic title: Distributed data-access requirements 18. Which of the following attributes in a ConnectionString sets the name of the OLE DB or SQL database? Choose an option.

Initial Catalog True

Provider

Data Source

ConnectionTimeout

Topic title: Architecture of ADO.NET 19. If a connection has a nonfatal error, the ____________ event is thrown. Incorrect. The correct option is as follows InfoMessage True OleDbException SqlException StateChange

Topic title: Distributed data-access requirements

Page 16: .net interview questions wid answers

16

20. _______________ eliminates the need for database locks and protracted database connections and facilitates data exchange between tiers. Choose an option below to fill in the blank.

A 2-tier application architecture The use of in-memory data caches True The use of strongly typed data XML messaging

Topic title: Defining an ADO.NET Connection object in VB.NET 21. If both the ________________ of a client's Connection object match those of a dormant connection in a pool, the client can obtain a connection in that pool. Choose an option below to fill in the blank.

connection context and database context connection context and security context security context and pooling context security context and transaction context True

Topic title: Defining an ADO.NET Connection object in VB.NET 22. Which of the following SqlConnection.ConnectionString attributes specifies the number of connections that are automatically allocated to a new pool when it's created by a unique connection? Choose an option.

Init Pool Size

Max Pool Size

Min Pool Size True

Start Pool Size

Topic title: Working with ADO.NET connections in VB.NET 23. When you are stepping through a stored procedure, which of the following types of information are displayed in the Autos window? Choose more than one option.

Debug information

The contents of the call stack

The types of the procedure's variables True

The values of the procedure's variables True

Topic title: Defining an ADO.NET Connection object in VB.NET 24. Which of the following elements is always incorporated in a Command object? Incorrect. The correct option is as follows

A Connection object True

A database table name

A set of parameters

A SQL statement string

The name of a stored procedure

Topic title: Pooling ADO.NET connections in VB.NET 25. The Read method returns the value _____________ when there is no more data to be read in a DataSet.

Page 17: .net interview questions wid answers

17

Choose an option below to fill in the blank.

Null 0 -1 False True

Topic title: Defining an ADO.NET Connection object in VB.NET 26. In which of the following situations is the use of a connected strategy always necessary? Choose more than one option.

When you're using a web application that uses ASP.NET

When you're modifying database structure True

When you're performing operations directly on a database True

When you need to read data as XML

Topic title: Pooling ADO.NET connections in VB.NET 27. What is the default setting of the ParameterDirection property of a stored-procedure parameter? Choose an option.

Input True

InputOutput

Output

ReturnValue

Topic title: Architecture of ADO.NET 28. Which of the following collections are encapsulated in the DataSet object? Choose an option.

Adapters and Views

Commands and Connections

Rows, Columns, and Constraints

Tables and Relations True

Topic title: Distributed data-access requirements 29. In a tiered data-access application, each tier comprises a discrete ____________________. Choose an option below to fill in the blank.

application server group of users separated logically section of application functionality True set of application data

Topic title: Working with ADO.NET connections in VB.NET 30. The __________________ method returns the number of rows affected by the execution of a DDL command. Choose an option below to fill in the blank.

ExecuteScalar ExecuteReader ExecuteXMLReader ExecuteNonQuery True

Page 18: .net interview questions wid answers

18

How to clear all rows of the GridView?

make DataSource as null.

GridView1.DataSource = null;

What is the difference between VB.NET and C#?

Well this is the most debatable issue in .NET community and people treat their languages like religion. It's a subjective matter which language is best. Some like VB.NET's natural style and some like professional and terse C# syntaxes. Both use the same framework and speed is also very much equivalents. But still let's list down some major differences between them:-

Advantages VB.NET :-

.Has support for optional parameters which makes COM interoperability much easy.

.With Option Strict off late binding is supported.Legacy VB functionalities can be used by using Microsoft.VisualBasic namespace. .Has the WITH construct which is not in C#. .The VB.NET parts of Visual Studio .NET compiles your code in the background. While this is considered an advantage for small projects, people creating very large projects have found that the IDE slows down considerably as the project gets larger.

Advantages of C#

.XML documentation is generated from source code but this is now been incorporated in Whidbey.

.Operator overloading which is not in current VB.NET but is been introduced in Whidbey.

.Use of this statement makes unmanaged resource disposal simple.

.Access to Unsafe code. This allows pointer arithmetic etc, and can improve performance in some situations. However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as the name implies).This is the major difference that you can access unmanaged code in C# and not in VB.NET.

What is concept of Boxing and Unboxing ?

Boxing permits any value type to be implicitly converted to type object or to any interface type implemented by value type. Boxing is a process in which object instances are created and copy values in to that instance. Unboxing is vice versa of boxing operation where the value is copied from the instance in to appropriate storage location. Below is sample code of boxing and unboxing where integer data type is converted in to object and then vice versa. Dim x As Integer Dim y As Object x = 10' boxing processy = x' unboxing process x = y

What are Value types and Reference types?

Value types directly contain their data which are either allocated on the stack or allocated in-line in a structure. Reference types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. Variables that are value types each have their own copy of the data, and therefore operations on one variable do not affect other variables. Variables that are reference types can refer to the same object; therefore, operations on one variable can affect the same object referred to by another variable. All types derive from the System.Object base type.

What are different types of JIT?

JIT compiler is a part of the runtime execution environment. In Microsoft .NET there are three types of JIT compilers:.Pre-JIT: - Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application. .Econo-JIT: - Econo-JIT compiles only those methods that are called at runtime. However, these compiled methods are removed

Page 19: .net interview questions wid answers

19

when they are not required..Normal-JIT :- Normal-JIT compiles only those methods that are called at runtime. These methods are compiled the first time they are called, and then they are stored in cache. When the same methods are called again, the compiled code from cache is used for execution.

Can we force garbage collector to run?

System.GC.Collect() forces garbage collector to run. This is not recommended but can be used if situations arise.

What is Difference between NameSpace and Assembly?

Assembly is physical grouping of logical units. Namespace logically groups classes.

Namespace can span multiple assembly.

What is NameSpace?

Namespace has two basic functionality :-NameSpace Logically group types, example System.Web.UI logically groups our UI related features.

In Object Oriented world many times its possible that programmers will use the same class name.By qualifying NameSpace with classname this collision is able to be removed.

What are the different types of Assembly?

There are two types of assembly Private and Public assembly.

A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath. A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful, e.g. Crystal report classes which will be used by all application for Reports.

What is a Managed Code?

Managed code runs inside the environment of CLR i.e. .NET runtime. In short all IL are managed code. But if you are using some third party software example VB6 or VC++ component they are unmanaged code as .NET runtime (CLR) does not have control over the source code execution of the language.

What is a CLS(Common Language Specification)?

This is a subset of the CTS which all .NET languages are expected to support. It was always a dream of Microsoft to unite all different languages in to one umbrella and CLS is one step towards that. Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.

What is a CTS?

In order that two language communicate smoothly CLR has CTS (Common Type System).Example in VB you have "Integer" and in C++ you have "long" these datatypes are not compatible so the interfacing between them is very complicated. In order to able that two different languages can communicate Microsoft introduced Common Type System. So "Integer" datatype in VB6 and "int" datatype in C++ will convert it to System.int32 which is datatype of CTS. CLS which is covered in the coming question is subset of CTS.

If you have undergone COM programming period interfacing VB6 application with VC++ application was a real pain as the datatype of both languages did not have a common ground where they can come and interface, by having CTS interfacing is smooth.

Page 20: .net interview questions wid answers

20

What is a CLR?

Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework. All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program. For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL, Java has Java Virtual Machine etc. Similarly .NET has CLR. Following are the responsibilities of CLR ? Garbage Collection :- CLR automatically manages memory thus eliminating memory leaks. When objects are not referred GC automatically releases those memories thus providing efficient memory management. ? Code Access Security :- CAS grants rights to program depending on the security configuration of the machine. Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file. CAS will take care that the code runs under the environment of machines security configuration. ? Code Verification :- This ensures proper code execution and type safety while the code runs. It prevents the source code to perform illegal operation such as accessing invalid memory locations etc. ? IL( Intermediate language )-to-native translators and optimizer's :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL code.

Difference between Dataset and Datareader?

Data Set is a connectionless service and Data reader is a connection oriented service. Dataset is used to store the data, it contains collections of Datatable. Datareader is used to connect to the database for retrieving data.Data Reader - Forward only where as Dataset - Can loop through dataset.Data Reader - Connected Recordset where as DataSet - Disconnected RecordsetData Reader - Less Memory Occupying where as DataSet - It occupies more memoryData Reader - Only Single Table can be used where as Dataset - Datatable Concept allows data to be stored in multiple tables.Data Reader - Read only where as DataSet - Can add/update/delete using the datasetData Reader - No relationship can be maintained where as DataSet - Relationship can be maintained.Data Reader - No Xml Storage available where as DataSet - Can be stored as XML.The Dataset is a core of disconnected architecture. Disconnected architecture means once you have retrieved the data from the database the data source is dropped. The disconnected data become very commonly. The dataset for the disconnected data from the Dataset object. The DataReader is a readonly, forward only stream from the database. While using the datareader can improve the application performance reduces the system overhead because only one buffer row at a time in memory.

Shashi Ray

What is the difference between Data Reader & Dataset?

Data Reader is connected datasource, read only, forward only record set.

Dataset is disconnected datatsource resides in memory database that can store multiple tables, relations and constraints;