Qns
Qns
Qns
It has software components which help in data access and services. This can be used to make changes to RDBMS and non relational data base systems. This technology is considered to be the forefront of Active X data objects. 2) Explain about Active X data objects (ADO)? Active X data objects are used to access data sources and it is based upon the Component object model. This technology allows data base developers to write program without the knowledge of how database is implemented. Knowledge of SQL is absolutely not necessary to write programs in ADO. 3) What are the different languages which implement ADO? There are several languages which implement ADO technology out of which these are some of the basic they are VB script in ASP, Visual Basic, Delphi, C++, and Microsoft environments. ADO.NET is a new addition to ADO. 4) State some of the basic steps required to access and manipulate data? Some of the basic steps which should be taken to access and manipulate data are as follows. * Creating connection object which helps to connect to a database. * Record set object should be created which facilitates connection to receive data. * Opening of the connection * Passing the desired name for your table and performing necessary functions on the fetched data. * Changes can be done by using the commands update and update batch. 5) Name some of the top level objects which ADO consists? Some of the several objects which ADO consists are as follows they are * Connection object is responsible for creating a connection to the database. * Record object represents data which is not from the database. * Parameter object represents a sql parameter * Stream object is responsible to represent data from a text page or web page. 6) Explain about RDO? A remote data object is also called as RDO in short. This represents data access application programming interface used in operating systems of windows. This was primarily designed for visual basic application ns. This feature allows data base developers to interact directly with Open data base connectivity. 7) Explain about Data access objects or DAO? DAO is used for database access on windows platform. It creates a work space object in which applications or operations are performed. There are two types of database engines they are Jet database engine and ODBC direct database engine.
8) 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. 9) Explain about the command Data reader? This feature should be used when you have a long list of results and you need to process one at a time. It provides only two features which is read and forward only. Records should be accessed sequentially. Previously accessed records cannot be accessed again. 10) 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. 11) Explain about Data services? ADO.NET has number of combinations of patterns and resources of libraries. This creates a feature which integrates data services with web. It contains formats which represent data such as JSON and plain XML. This form of interaction enables developers to interact with normal http commands. 12) Explain LINQ to Entities? This feature allows LINQ query capabilities and it specifically forms a part of the .NET framework. This feature allows developers to program in ADO.NET and ORM. This feature also allows access to third party database. This provides new features to entity data. 13) Explain about command builder class feature? Implementation of INSERT, DELETE and UPDATE commands is automatic and this class provides the necessary automation. You cannot extend or change the command builder while keeping the base algorithm intact to create action statements. 14) 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. 15) How can you find a problem in the data stack? Problem can arise from these following instances they are: 1) Mismatch of schema between the client and database. 2) Network library problems or non existence of data. 3) Wrong SQL generated. 4) Wrong programming logic.
16) Compare and explain about ADO.NET and Visual Stuidio.NET? If you are planning to create specialized sub classes of the data set then it is better to use visual studio as it has features supporting database schema. Access can be obtained to each field through strongly types properties. Intellisense is much helpful. 17) Explain about the relationship of XML and ADO.NET? ADO.NET utilizes the power of XML by providing disconnected access to data. This is designed with the help of XML classes in .NET Framework which form the components of single architecture. 18) What is ADO.NET? ADO.NET is a part of the Microsoft .NET Framework. This framework provides the set of classes that deal with data communication between various layers of the software architecture and the database. It provides a continuous access to different data source types such as SQL Server versions 7, 2000, 2005. It also provides connectivity options to data sources through OLE DB and XML. Connectivity may be established with other databases like Oracle, MySQL etc. as well. ADO.NET has the ability to separate data access mechanisms, data manipulation mechanisms and data connectivity mechanisms. ADO.NET introduces along with it the disconnected architecture. In a disconnected architecture, data may be stored in a DataSet. It contains providers for connecting to databases, commands for execution and retrieval of results. The classes for ADO.NET are stored in the DLL System.Data.dll. 2 :: can we connect two dataadapters to same data source using single connection at same time? yes,we can connect two dataadapters to same datasource using single connection at same time. There is a technology in ado.net 2.0 called MARS usinng Mars in connection string we can do it. for eg: cn.ConnectionString = "server=(local); database=employee; integrated security=sspi; MultipleActiveResultSets=True"; 3 :: Can we do database operations without using any of the ADO.net objects? No its not at all possible. 4 :: If we are not returning any records from the database, which method is to be used? There is a method called Execute Non Query. This method executes the Update, Delete etc. This does not return any rows but will give the number of rows affected. 5 :: how can i retrieve two tables of data at a time by using data reader? Data reader read and forward only, how is it possible to get 2 tables of data at a time?
yes this is possible If we execute 2 select command either in stored procedure or in select command and then executereader method fired of command object. it return 2 tables in datareader. like : string str="Select * from a;select * from b"; cmd.commandtext=str; dr=cmd.executereader(); Now it return 2 tables in datareader (dr).
6 :: Explain ExecuteNonQuery? // Summary: // Executes a Transact-SQL statement against the connection and returns the number of rows affected. // Returns: // The number of rows affected. 7 :: What is the ExecuteScalar method? // Summary: Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. // Returns: The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. 8 :: Which one of the following objects is a high-level abstraction of the Connection and Command objects in ADO.NET? DataReader DataSet DataTable DataView DataAdapter Answer: DataAdapter 9 :: How can we load multiple tables in to Dataset? DataSet ds=new DataSet();
SqlDataAdapter dap=new SqlDataAdapter(Select * from ,); dap.Fill(ds,"TableOne"); SqlDataAdapter dap1=new SqlDataAdapter(Select * from ,); dap1.Fill(ds,"tableTwo"); 10 :: What is connection String? connection String - a string which contains address of the database we want to connect to Why are Server control tags shown in the browser instead of the controls it represents? This is because the server control tags were not converted into their respecting HTML element tags by ASP.Net. This happens when ASP.Net is not properly registered with IIS. .Net framework provides an Administration utility that manages the installation and uninstallation of multiple versions of ASP.NET on a single machine. You can find the file in C:\WINNT\Microsoft.NET\Framework\v**\aspnet_regiis.exe use the command: aspnet_regiis.exe -u ---> to uninstall current asp.net version. use the command: aspnet_regiis.exe -i ---> to install current asp.net version What are the Best practices for side-by-side execution of Framework 1.1 and 2.0? In ASP.NET, applications are said to be running side by side when they are installed on the same computer, but use different versions of the .NET Framework. Can I have VS.NET and the Visual Studio 6.0 installed on the same machine? Yes! VS.Net works with the .Net framework, while VS6.0 works with MFC or the Windows API directly, for the most part. They can be installed and run on the same machine without any considerations. What is Assembly name and name space? An assembly is a logical unit of code. Physically it may exist as dll or an exe. which can contain one or more files and they can be any file types like image files, text files etc. along with DLLs or EXEs. When you compile your source code by default the exe/dll which is generated is actually an assembly and every assembly file contains information about itself which is called as Assembly Manifest. Namespace is an abstract container providing context for the items it holds and allows disambiguation of items having the same name (residing in different namespaces. It can also be said as a context for identifiers. So under a namespace you can have multiple assemblies. what is capacity of dataset? DataSet is logical represantation of database so it can store as much as database. What is deployment? How do you deploy .Net and Java applications
Deployment - It is the procedure to deploy Web Application on the Server. You can deploy .Net application by simply Xcopy and create virtual directory for the application on server. Where this DataSet is Stored? Dataset is an in-memory representation of a database. Its stored no where but in memory. Goes off when GC stats after a little sleep. How different are interface and abstract class in .Net? When a class is not provided with full functionality then it is declared as abstract.it doesn't support instance creation as well as it cannot be overridable to child class.interface is a colection of methods only without functionality.interface is 90% same as abstract class. How does vs.net 2005 support biztalkserver? if you install biztalk server it provides Biztalk Project in the project types like webproject, windows project, console project. We use rest of the products of the Biztalk like adapters and all those thing and use them in .net. what is marshaling? Marshaling performs the necessary conversions in data formats between managed and unmanaged code. CLR allows managed code to interoperate with unmanaged code using COM Marshaler(Component of CLR). Can you explain the difference between an ADO.NET Dataset and an ADO Recordset? 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. In .NET Compact Framework, can I free memory explicitly without waiting for garbage collector to free the memory?
.NET Compact Framework come with CLR which perform automatic garbage collector to free the memory without using destector(perform garbage collector when is declear Can you enforce constraints and relations on tables inside a DataSet? Yes, the collection of DataTable objects from a DataSet can relate to each other with the DataRelation objects. You can also put in execution of data integrity in the DataSet by using UniqueKeyConstraint and ForeignKeyConstraint objects. What happens when you apply AcceptChanges() method on a DataSet? When you will apply AcceptChanges() method to a DataSet, then it will call AcceptChanges() method on each table within the DataSet. This method will also have in both the DataRow and DataTable classes. When AcceptChanges() calls at the DataTable level, it causes the AcceptChanges method for each DataRow. When AcceptChanges() call on the DataSet, then the edit mode of DataRow objects will end successfully with editing. The RowState property of each DataRow also changes. The added and modified rows become as it is, and deleted rows are removed. What is the use of DataSet.HasChanges() Method? This method is used to made changes into the DataSet including new, modify, and delete rows. It will return a Boolean value that is either true or false according to the changes made in DataSet. This can also be used to update a DataSource, if there is some change. What happens when you apply RejectChanges method on a DataSet? Let's consider, a DataSet contains 3 tables. When you will apply RejectChanges() method, it will be automatically invoked on all the 3 tables in the dataset. So any changes that were done with the tables will be rolled back. When you call DataTable.RejectChanges method, the rows that are in edit-mode will cancel their edit. It will remove the new added rows. It will also return back all modified and deleted rows to its original state. What is the use of SqlParameter.Direction Property? This Property is used to initialize the Sql Parameter type and sets some of its properties such as inputonly , output-only , bidirectional , or a stored procedure which will return value parameter. The default property is Input. What is Connection Pooling ? Connection Pooling will make a single connection instance, which allows that instance to connect to all the databases. Advantage is that it does not open and close the connection object multiple times. What is the role of data provider? The .NET data provider layer resides between the application and the database. Its task is to take care of all their interactions. The .NET Data provider can be demonstrated to be: SQL Server data provider OLEDB data provider ODBC Data Provider
ADO.NET supports the following OLE DB Providers: SQLOLEDB - Microsoft OLE DB Provider for SQL Server. MSDAORA - Microsoft OLE DB Provider for Oracle. Microsoft.Jet.OLEDB.4.0 - OLE DB Provider for Microsoft Jet What is DataViewManager? DataViewManager is used to manage view settings of the tables in a DataSet. A DataViewManager is best suited for views that consist of a combination of multiple tables. The properties like ApplyDefaultSort, Sort, RowFilter, and RowStateFilter are referenced using DataViewSetting. Components of data providers in ADO.NET? Connection Object: The Connection object represents the connection to the database. The Connection object has ConnectionString which contains all the information required to connect to the database. Command Object: The command object is used to execute stored procedures and command on the database. It contains methods such as ExecuteNonQuery, ExecuteScalar and ExecuteReader. ExecuteNonQuery: It executes a command that doesnt return any record, such as INSERT, UPDATE and DELETE. ExecuteScalar: It executes and returns a single value from a database. ExecuteReader: It returns a result set by the DataReader object. DataReader Object: It provides a connected, forward-only and read-only recordset from a database. The Command.ExecuteReader method creates and returns a DataReader object. Since it is connected to the database throughout its lifetime, it requires the use of connection object. DataAdapter Object: This object acts like a communication bridge between the database and a dataset. It fills the dataset with data from the database. The dataset stores the data in the memory and it allows changes. The DataAdapter update method can transmit the changes to the database. What are the different DataAdapter Object properties present? Select Command: This command is used to select the data from the database. Insert Command: This command is used to insert a row into the table. Delete Command: This command is used to delete the existing rows in the table. Update Command: This command is used to update the values of records present in table. Define connected and disconnected data access in ADO.NET? In connected data access you can connect through the DataReader objects of data provider. This object requires exclusive use of the connection object. It can provide fast and forward-only data access. It doesn't allow editing. Disconnected data access is achieved through the DataAdapter object. This object establishes connection, executes the command, load data in the DataSet. The Dataset works independent of database. It contains data in the memory and can edit the data. The changes in the data can be transmitted to the database using Update method of DataAdapter object.
Describe Command Type property of a SQLCommand in ADO.NET? A SQLCommand has CommandType property which can take Text, Storedprocedure or TableObject as parameter. If it is set to Text, the command executes SQL string that is set to CommandText property. When set to StoredProcedure, the command runs the stored procedure of the database. If the property is set to TableObject, the command returns the entire content of the table indicated by the CommandText property. Give Expansions of ODBC,OLE,OLE DB,ADO? 1.ODBC-Open Database Connectivity. 2.OLE-Object Linking and Embedding. 3.OLE DB-Object Linking and Embedding for Database. 4.ADO-ActiveX Data Object. How to convert a DataSet to a DataReader? DataTableReader rd = ds.Tables[0].CreateDataReader(); What is a DataSet? The Dataset is the central object in ADO.NET. DataSet is a logical container of data. It represents a set of data tables referenced 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 Fill(DataSet, DataTable) 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 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 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. 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. DataAdapter Object:- It is used to fill data from the database into the DataSet object. it is used in the disconnected approach. 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. How can you update the records in database using datareader? Well, You cannot update. DataReader is just used for reading the data in forward only mode. You can achieve this using Dataset but not by DataReader. 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; Stored procedure return more than one resut set and datareader used to fetch record, how you fetch second result set using datareader? Posted by: Bprasad Use DataReader.NextResult() True - It Check more result remain to read and reader will forward to next result. False - No more result set found Name the classes that are contained in System.Data NameSpace? DataSet DataTable DataColumn DataRow DataRealation Constraint Overview: ADO.NET Interview Questions - Microsoft Ado.NET Interview Questions asked in top companies like CTS,Wipro,Infosys,Sasken,TCS,HP,IBM,Patni,etc What is Microsoft ADO.NET? Visual Studio .NET provides access to databases through the set of tools and namespaces collectively referred to as Microsoft ADO.NET What are the 3 major types of connection objects in ADO.NET? OleDbConnection object : Use an OleDbConnection object to connect to a Microsoft Access or thirdparty database, such as MySQL. OLE database connections use the OleDbDataAdapter object to perform commands and return data. SqlConnection object : Use a SqlConnection object to connect to a Microsoft SQL Server database. SQL database connections use the SqlDataAdapter object to perform commands and return data. OracleConnection object : Use an OracleConnection object to connect to Oracle databases. Oracle database connections use the OracleDataAdapter object to perform commands and return data. This connection object was introduced in Microsoft .NET Framework version 1.1. List the 4 common ADO.NET Namespaces? System.Data : Contains Classes, types, and services for creating and accessing data sets and their subordinate objects System.Data.SqlClient : Contains Classes and types for accessing Microsoft SQL Server databases System.Data.OracleClient : Contains Classes and types for accessing Oracle databases (Microsoft .NET Framework version 1.1 and later)
System.Data.OleDb : Contains Classes and types for accessing other databases List all the steps in order, to access a database through ADO.NET? 1. Create a connection to the database using a connection object. 2. Invoke a command to create a DataSet object using an adapter object. 3. Use the DataSet object in code to display data or to change items in the database. 4. Invoke a command to update the database from the DataSet object using an adapter object. 5. Close the database connection if you explicitly opened it in step 2 using the Open method. Invoking commands without first invoking the Open method implicitly opens and closes the connection with each request. Why will you usually create an ASPNET user account in the Database for an ASP.NET web application? Web applications run using the ASPNET user account. The SQL database administrator will have to set up this account and grant it permissions before your Web application will have access to a SQL database. For file-based databases, such as Microsoft Access, you must grant permissions on the database file to the ASPNET user account using Windows file security settings. What is the difference between DataReader and DataAdapter? 1. Data Reader is read only forward only and much faster than DataAdapter. 2. If you use DataReader you have to open and close connection explicitly where as if you use DataAdapter the connection is automatically opened and closed. 3. DataReader is connection oriented where as Data Adapter is disconnected Can you inherit from SqlConnection Class? No, you cannot inheirt from SqlConnection Class. SqlConnection Class is a sealed class. It is a compile time error. Will the connection be closed, if the SqlConnection object goes out of scope? No, If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. What happens if connection pooling is enabled? If connection pooling is enabled and when you call Close or Dispose methods, then the connection is returned to the connection pool. This connection can then be resused.If connection pooling is disabled and when you call Close or Dispose methods, the underlying connection to the server is actually closed. How do you ensure that the database connections are always closed? To ensure that the database connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block. using (SqlConnection ConnectionObject = new SqlConnection()) { ConnectionObject.Open(); //The database connection will be closed when the control exits the using code block } How do you read an XML file into a DataSet? Using the DataSet objects ReadXML method.
When do you use ExecuteReader, ExecuteNonQuery, ExecuteScalar methods? If the command or stored procedure that is being executed returns a set of rows, then we use ExecuteReader method. If the command or stored procedure that is being executed returns a single value then we use ExecuteScalar method. If the command or stored procedure performs INSERT, DELETE or UPDATE operations, then we use ExecuteNonQuery method. ExecuteNonQuery method returns an integer specifying the number of rows inserted, deleted or updated. Can your class inherit from SqlCommand Class? No, you cannot inheirt from SqlCommand Class. SqlCommand Class is a sealed class. It is a compile time error. Give an example that shows how to execute a stored procedure in ADO.NET? using (SqlConnection ConnectionObject = new SqlConnection()) { //Specify the name of the stored procedure to execute and the Connection Object to use SqlCommand CommandObject = new SqlCommand("StoredProcedureName", ConnectionObject); //Specify the SQL Command type is a stored procedure CommandObject.CommandType = CommandType.StoredProcedure; //Open the connection ConnectionObject.Open(); //Execute the Stored Procedure int RecordsAffected = CommandObject.ExecuteNonQuery(); } Can you reuse a SqlCommand object? Yes, you can reset the CommandText property and reuse the SqlCommand object.
What are the methods that can ensure asynchronous execution of the Transact-SQL statement or stored procedure? BeginExecuteNonQuery BeginExecuteReader
What is SqlCommand.CommandTimeout Property used for? CommandTimeout Property is used to Get or set the wait time before terminating the attempt to execute a command and generating an error. //Specify the CommandTimeout property value SqlCommand CommandObject = new SqlCommand("StoredProcedureName", ConnectionObject); //Wait for 10 seconds to execute the Stored procedure CommandObject.CommandTimeout = 10; The time is in seconds. The default is 30 seconds. What is data access layer? Data Access layer is actually a part of Architecture layer. It has 2 tier,3 tier or N tier Layer. Generally we
use 3 tier Layer 1) Presentation layer,Business Logic layer and then Data Access Layer. Data Access layer is a medium to talk between database and Business Logic layer.It helps to maintain flexibility,resuablity and even secuity also. In security SQL Injection can be stopped with 3 iter Archietcture. I have two textboxes one for user name and another for password . i have a table name compare(which contains name,passwod etc.,) my doubt is how compare username textbox with name column and how compare password textbox with passwod column. i want the code? sqlconnection con = new sqlconnection(""); sqlcommand cmd = new sqlcommand("select * from table-name",con); //write this code in the button click event con.open(); dr = cmd.executereader(); while(dr.read()) { if(textbox1.text==dr.getvalue(0).tostring()&& textbox2.text==dr.getvalue(1).tostring()) { msgbox.show("successful"); } } con.close(); else { msgbox.show("not success"); } What are the different row versions available in table? There are four types of Row versions. Current: The current values for the row. This row version does not exist for rows with a RowState of Deleted. Default : The row the default version for the current DataRowState. For a DataRowState value of Added, Modified or Current, the default version is Current. For a DataRowState of Deleted, the version is Original. For a DataRowState value of Detached, the version is Proposed. Original: The row contains its original values. Proposed: The proposed values for the row. This row version exists during an edit operation on a row, or for a row that is not part of a DataRowCollection.
What are the two fundamental objects in ADO.NET? Datareader and Dataset are the two fundamental objects in ADO.NET What we do with the object of ado.net dataset after using it? Can we dispose it or can we set it nothing? Is it must or not? we use dispose What provider ADO.net use by default ? Ado.net uses no Dataprovider by default and this is absolutely correct answered. there is no other choice for this question How you will set the data relation between two columns? ADO.NET provides DataRelation object to set relation between two columns. It helps to enforce the following constraints, a unique constraint, which guarantees that a column in the table contains no duplicates and a foreign-key constraint, which can be used to maintain referential integrity. A unique constraint is implemented either by simply setting the Unique property of a data column to true, or by adding an instance of the Unique Constraint class to the DataRelation object's ParentKeyConstraint. As part of the foreign-key constraint, you can specify referential integrity rules that are applied at three points, when a parent record is updated, when a parent record is deleted and when a change is accepted or rejected. DataSet d = new DataSet(); DataColumn parentDC = new DataColumn(d.Tables["parentTable"].Columns["id"]); DataColumn childDC = new DataColumn(d.Tables["ChildTable"].Columns["id"]); DataRelation ds = new DataRelation("relation name",parentDC, childDC); d.Relations.Add(ds); What is the provider and namespaces being used to access oracle database? The provider name is oledb and the namespace is system.data.oledb Explain acid properties? The term ACID conveys the role transactions play in mission-critical applications. Coined by transaction processing pioneers, ACID stands for atomicity, consistency, isolation, and durability. These properties ensure predictable behavior, reinforcing the role of transactions as all-or-none propositions designed to reduce the management load when there are many variables. Atomicity A transaction is a unit of work in which a series of operations occur between the BEGIN TRANSACTION and END TRANSACTION statements of an application. A transaction executes exactly once and is atomic ?all the work is done or none of it is. Operations associated with a transaction usually share a common intent and are interdependent. By performing only a subset of these operations, the system could compromise the overall intent of the transaction. Atomicity eliminates the chance of processing a subset of operations. Consistency
A transaction is a unit of integrity because it preserves the consistency of data, transforming one consistent state of data into another consistent state of data. Consistency requires that data bound by a transaction be semantically preserved. Some of the responsibility for maintaining consistency falls to the application developer who must make sure that all known integrity constraints are enforced by the application. For example, in developing an application that transfers money, you should avoid arbitrarily moving decimal points during the transfer. Isolation A transaction is a unit of isolation ? allowing concurrent transactions to behave as though each were the only transaction running in the system.Isolation requires that each transaction appear to be the only transaction manipulating the data store, even though other transactions may be running at the same time. A transaction should never see the intermediate stages of another transaction. Transactions attain the highest level of isolation when they are serializable. At this level, the results obtained from a set of concurrent transactions are identical to the results obtained by running each transaction serially. Because a high degree of isolation can limit the number of concurrent transactions, some applications reduce the isolation level in exchange for better throughput. Durability A transaction is also a unit of recovery. If a transaction succeeds, the system guarantees that its updates will persist, even if the computer crashes immediately after the commit. Specialized logging allows the system's restart procedure to complete unfinished operations, making the transaction durable. Which method do you invoke on the DataAdapter control to load your generated dataset with data? SqlDataAdapter adap=new SqlDataAdapter("Select * from temp",Conn); DataSet ds = new DataSet(); //Here we load the table to dataset adap.Fill(ds); What are the attirbutes of DataSet? DataSet DataTabel DataColumns Datarow DataPrimaryKey DataForgeinKey What is data Adapter? Data adapter is bridge between Connection and DataSet , Data adapter in passing the sql query and fill in dataset How to find the count of records in a dataset? DS.Tables["tabname"].Rows.Count; we can get count of the records.
How can we add/remove row is in Data Table object of Dataset? Data table provides NewRow method to add new row to Data Table. Data Table has DataRowCollection object that has all rows in a Data Table object. Following are the methods provided by DataRowCollection object:Add Adds a new row in Data Table Remove It removes a Data Row object from Data Table Remove At It removes a Data Row object from Data Table depending on index position of the Data Table. What is basic use of Data View? Data View represents a complete table or can be small section of rows depending on some criteria. It is best used for sorting and finding data with in data table. Data view has the following methods:Find It takes an array of values and returns the index of the row. Find Row This also takes array of values but returns a collection of Data Row. If we want to manipulate data of Data Table object create Data View (Using the Default View we can create Data View object) of the Data Table object and use the following functionalities:Add New Adds a new row to the Data View object. Delete Deletes the specified row from Data View object. What is the difference between Dataset and Data Reader ? Twist: - Why is Dataset slower than Data Reader is? Fourth point is the answer to the twist. Note:- This is my best question and we expect everyone to answer it. It is asked almost 99% in all companies....Basic very Basic cram it. Following are the major differences between Dataset and Data Reader: Dataset is a disconnected architecture, while Data Reader has live connection while reading data. If we want to cache data and pass to a different tier Dataset forms the best choice and it has decent XML support. When application needs to access data from more than one table Dataset forms the best choice. If we need to move back while reading records, data reader does not support this functionality. However, one of the biggest drawbacks of Dataset is speed. As Dataset carry considerable overhead because of relations, multiple tables etc speed is slower than Data Reader. Always try to use Data Reader wherever possible, as it is meant especially for speed performance.
How can we load multiple tables in a Dataset? objCommand.CommandText = "Table1" objDataAdapter.Fill(objDataSet, "Table1") objCommand.CommandText = "Table2" objDataAdapter.Fill(objDataSet, "Table2") Above is a sample code, which shows how to load multiple Data Table objects in one Dataset object. Sample code shows two tables Table1 and Table2 in object ObjDataSet. lstdata.DataSource = objDataSet.Tables("Table1").DefaultView In order to refer Table1 Data Table, use Tables collection of Datasets and the Default view object will give you the necessary output. How can we add relation between tables in a Dataset? Dim objRelation As DataRelation objRelation=New DataRelation("CustomerAddresses",objDataSet.Tables("Customer").Columns("Custid") ,objDataSet.Tables("Addresses").Columns("Custid_fk")) objDataSet.Relations.Add(objRelation) Relations can be added between Data Table objects using the Data Relation object. Above sample, code is trying to build a relationship between Customer and Addresses Data table using Customer Addresses Data Relation object. What is the use of Command Builder? Command Builder builds Parameter objects automatically. Below is a simple code, which uses command builder to load its parameter objects. Dim pobjCommandBuilder As New OleDbCommandBuilder(pobjDataAdapter) pobjCommandBuilder.DeriveParameters(pobjCommand) Be careful while using Derive Parameters method as it needs an extra trip to the Data store, which can be very inefficient Whats difference between Optimistic and Pessimistic locking ? In pessimistic locking when user wants to update data it locks the record and till then no one can update data. Other users can only view the data when there is pessimistic locking. In optimistic locking multiple users can open the same record for updating, thus increase maximum concurrency. Record is only locked when updating the record. This is the most preferred way of locking practically. Now a days in browser based application it is very common and having pessimistic locking is not a practical solution. How many ways are there to implement locking in ADO.NET? Following are the ways to implement locking using ADO.NET:-
When we call Update method of Data Adapter it handles locking internally. If the Dataset values are not matching with current data in Database, it raises concurrency exception error. We can easily trap this error using Try. Catch block and raise appropriate error message to the user. Define a Date time stamp field in the table. When actually you are firing the UPDATE SQL statements, compare the current timestamp with one existing in the database. Below is a sample SQL which checks for timestamp before updating and any mismatch in timestamp it will not update the records. This I the best practice used by industries for locking. Update table1 set field1=@test where Last Timestamp=@Current Timestamp Check for original values stored in SQL SERVER and actual changed values. In stored procedure check before updating that the old data is same as the current Example in the below shown SQL before updating field1 we check that is the old field1 value same. If not then some one else has updated and necessary action has to be taken. Update table1 set field1=@test where field1 = @oldfield1value Locking can be handled at ADO.NET side or at SQL SERVER side i.e. in stored procedures. For more details of how to implementing locking in SQL SERVER read What are different locks in SQL SERVER? in SQL SERVER chapter. How can we perform transactions in .NET? The most common sequence of steps that would be performed while developing a transactional application is as follows: Open a database connection using the Open method of the connection object. Begin a transaction using the Begin Transaction method of the connection object. This method provides us with a transaction object that we will use later to commit or rollback the transaction. Note that changes caused by any queries executed before calling the Begin Transaction method will be committed to the database immediately after they execute. Set the Transaction property of the command object to the above mentioned transaction object. Execute the SQL commands using the command object. We may use oneormorecommand objects for this purpose, as long as the Transaction property of all the objects is set to a valid transaction object. Commit or roll back the transaction using the Commit or Rollback method of the transaction object. Close the database connection. What is difference between Dataset? Clone and Dataset. Copy? Clone: - It only copies structure, does not copy data. Copy: - Copies both structure and data. Can you explain the difference between an ADO.NET Dataset and an ADO Record set? There two main basic differences between record set and dataset:-
With dataset you an retrieve data from two databases like oracle and sql server and merge them in one dataset , with record set this is not possible All representation of Dataset is using XML while record set uses COM. Record set cannot be transmitted on HTTP while Dataset can be. Explain in detail the fundamental of connection pooling? When a connection is opened first time, a connection pool is created and is based on the exact match of the connection string given to create the connection object. Connection pooling only works if the connection string is the same. If the connection string is different, then a new connection will be opened, and connection pooling will not be used. What is Maximum Pool Size in ADO.NET Connection String? Maximum pool size decides the maximum number of connection objects to be pooled. If the maximum pool size is reached and there is no usable connection available the request is queued until connections are released back in to pool. So its always a good habit to call the close or dispose method of the connection as soon as you have finished work with the connection object. How to enable and disable connection pooling? For .NET it is enabled by default but if you want to just make sure set Pooling=true in the connection string. To disable connection pooling set Pooling=false in connection string if it is an ADO.NET Connection. If it is an OLEDBConnection object set OLE DB Services=-4 in the connection string. What extra features does ADO.Net 2.0 have ? Bulk Copy Operation Bulk copying of data from a data source to another data source is a newly added feature in ADO.NET 2.0. ADO.NET inrtoduces bulk copy classes which provide fastest way to transfer\ data from once source to the other. Each ADO.NET data provider has bulk copy classes. For example, in SQL .NET data provider, the bulk copy operation is handled by SqlBulkCopy class, which can read a DataSet, DataTable, DataReader, or XML objects.
Data Paging A new method is introduced ExecutePageReader which takes three parameters - CommandBehavior, startIndex, and pageSize. So if you want to get rows ony from 10 - 20, you can simply call this method with start index as 10 and page size as 10.
Batch Update If you want to update large number of data on set ADO.NET 2.0 provides UpdateBatchSize property, which allows you to set number of rows to be updated in a batch. This increases the performance dramatically as round trip to the server is minimized.
Load and Save Methods In previous version of ADO.NET, only DataSet had Load and Save methods. The Load method can load data from objects such as XML into a DataSet object and Save method saves the data to a persistent media. Now DataTable also supports these two methods. You can also load a DataReader object into a DataTable by using the Load method.
New Data Controls In toolbox you can see three new controls - DataGridView, DataConnector, and DataNavigator. DataReader's New Execute Methods Some new execute methods introduced are ExecutePageReader, ExecuteResultSet, and ExecuteRow. 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 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 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; To perform asynchronous data access, what must be added to the connection string? Select Correct Answer.
1. BeginExecute=true 2. MultiThreaded=true 3. MultipleActiveResultSets=true 4. Asynchronous=true Correct Answer: 4. Asynchronous=true 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(); 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; Why edit is not possible in repeater? It has no such feature.
Difference between SqlCommand and SqlCommandBuilder? a) SQLCommand is used to execute all kind of SQL queries like DML(Insert, update,Delete) & DDL like(Create table, drop table etc) b)SQLCommandBuilder object is used to build & execute SQL (DML) queries like select, insert, update & delete. Why can\'t we use Multiple inheritance and garbage collector paralelly in .net? FYI, .net doesn't support the mutiple inheritance, perhaps you may talk about multi-level inheritance. In the later case, if a class is inherited from another class, at the time of creating instance, it will obviously give a call to its base class constructor (ie bottom - top approach). Likewise the constructor execution is takes place in top down approach (ie. base class constructor is executed and the derived class constructor is executed). So for GC, it will collect only when an object does not have any reference. As we see previously, the derived is constructed based on base class. There is a reference is set to be. Obviously GC cannot be collected. What is ADO.NET? ADO.NET is the primary relational data access model for Microsoft .NET-based applications. It may be used to access data sources for which there is a specific .NET Provider, or, via a .NET Bridge Provider, for which there is a specific OLE DB Provider, ODBC Driver, or JDBC Driver. ADO.NET is sometimes considered an evolution of ADO technology, but it is important to note that some major changes were
made between the two. How to find the given query is optimised one or not? First Excute Sql Quries in Query Analzer,see How much time 2 take Excute , if Less than the ur desired Time, then it will Optimize query. How to copy the contents from one table to another table and how to delete the source table in ado.net? It is possible DataSet ds; sqlAdap.Fill(ds); Datatable dt = ds.Tables[0].copy(); //now the structure and data are copied into 'dt' ds.Tables.remove(ds.Table[0]); //now the source is removed from the 'ds' How to call the SQL commands asynchronously in ADO.NET version 2.0? executescalar() executereader() executenonquery() these comes with Begin and End like Beginexecutescalr() Endexecutescalar().......by using these command we can achieve asynch comm in ado.net What is typed and untyped dataset? A DataSet can be Typed or Untyped. The difference between the two lies in the fact that a Typed DataSet has a schema and an Untyped DataSet does not have one. It should be noted that the Typed Datasets have more support in Visual studio.I loaded the dataset with a table of 10 records. One of the records is deleted from the backend, How do you check whether all the 10 records were present while updating the data(Which event and steps) and throw the exception. By Using the Transactions we can check the Exact Numbers of the rows to be updated and if the updation fails then the Transaction will be rollbacked. Can dataReader hold data from multiple tables? data reader can hold data from multiple tables and datareader can hold more than one table. string query="select * from employee; select * from student"; sqlcommand cmd=new sqlcommand(query, connection); sqldatareader dr=cmd.executeReader(); if(dr.hasrows) { dr.read(); gridview1.DataSource=dr; gridview1.Databind(); if(dr.nextresult) {
gridview2.datasource=dr; gridview2.databind(); } } dr.colse(); connection.close(); What's Connection Pooling? Connection pooling is the ability of re-use your connection to the Database.This means if you enable Connection pooling in the connection object, actually you enable the re-use of the connection to more than one user.The connection pooling is enabled by default in the connection object.If you disable the connection pooling, this means the connection object which you create will not be re-used to any other user than who create that object. Shall I Enable/Disable Connection pool? Let's do an example to use what the time has required if we enable/disable the connection pool in an application. What is different between SqlCommand object and Command Behaviour Object DO.NET Command Object - The Command object is similar to the old ADO command object.It is used to store SQL statements that need to be executed against a data source.The Command object can execute SELECT statements, INSERT, UPDATE, or DELETE statements,stored procedures, or any other statement understood by the database. CommandBehaviour:Provides a description of the results of the query and its effect on the database. Like, Command cmd=new Command("SQL",conn,CommandBehaviour.CloseConnection); What is bubbled event can u pls explain? All heavy controls like grid view,datagrid or datalist,repeater controls contains the child controls like button or link button, when we click this button then the event will be raised,that events are handled by parant controls,that is called event bubbling,means event is bubbled from bottom(chield)to up(parant). Once data is fetched into dataset connection gets closed. but in datareader connection is always maintained...then why datareader is fast and mainly recommended ? Datareader is forwardonly thus is fast and is mostly used while retrieving the data from the database.
When multiple users attempt to modify data at the same time Ex user 1 is updating record at same.time user2 deleted record sucessfully.now user1 has press update button . how to handle concurrency? Have one column with in Database table with datatype as TimeStamp and while selecting the row we will read the TimeStamp value, which we can compare at the time of updation, if both values are same then we can update that row otherwise we can resist the user from updating saying that someone has updated the row, you can't update it.
What is method to get XML and schema from Dataset? // Summary: // Returns the XML representation of the data stored in the System.Data.DataSet. // // Returns: // A string that is a representation of the data stored in the System.Data.DataSet. // Summary: // Returns the XML Schema for the XML representation of the data stored in the // System.Data.DataSet. // // Returns: // String that is the XML Schema for the XML representation of the data stored // in the System.Data.DataSet. If a table contains 20000 records . In a page at each time 100 records to be displayed. What are the steps u will take to improve performance? will you use dataset or datareader? We have to use a dataset because on using datareader forward only paging can be achieved. Suppose if you are at 1000 page and you want to go back to 999th page, if you use datareader it cannot be achieved, since it does not support backward navigation. Dataset supports forward and backward navigation Can we connect two data adapters to same data source using single connection at same time? Yes,we can connect two dataadapters to same datasource using single connection at same time. There is a technology in ado.net 2.0 called MARS usinng Mars in connection string we can do it. for eg:cn.ConnectionString = "server=(local); database=employee; integrated security=sspi; MultipleActiveResultSets=True"; Can we do database operations without using any of the ADO.net objects? No its not at all possible.
If we are not returning any records from the database, which method is to be used? There is a method called Execute Non Query. This method executes the Update, Delete etc. This does not return any rows but will give the number of rows affected. How can i retrieve two tables of data at a time by using data reader? Data reader read and forward only, how is it possible to get 2 tables of data at a time yes this is possible If we execute 2 select command either in stored procedure or in select command and then executereader method fired of command object. it return 2 tables in datareader like : string str="Select * from a;select * from b"; cmd.commandtext=str; dr=cmd.executereader(); Now it return 2 tables in datareader (dr).
ExecuteNonQuery? // Summary: // Executes a Transact-SQL statement against the connection and returns the number of rows affected. // Returns: // The number of rows affected. What is the ExecuteScalar method? // Summary: Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. // Returns: The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty.
Which one of the following objects is a high-level abstraction of the Connection and Command objects in ADO.NET? DataReader DataSet DataTable DataView DataAdapter Answer: DataAdapter How can we load multiple tables in to Dataset? DataSet ds=new DataSet(); SqlDataAdapter dap=new SqlDataAdapter(Select * from ,); dap.Fill(ds,"TableOne"); SqlDataAdapter dap1=new SqlDataAdapter(Select * from ,); dap1.Fill(ds,"tableTwo"); connection String - a string which contains address of the database we want to connect to. Delegate - is an important element of C# and is extensively used in every type of .NET application. A delegate is a class whose object (delegate object) can store a set of references to methods. How do you update a Dataset in ADO.Net and How do you update database through Dataset? a. Update a dataset; Dataset ds = new dataset(); SqlDataAdapter adp = new SqlDataAdapter(Query,connection); Adp.fill(ds); Again you can add/update Dataset as below SqlDataAdapter adp1 = new SqlDataAdapter(Query1,connection); Adp1.fill(ds); b. Update database through dataset. SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter); Foreach(datarow dr in ds.table[0].rows) { Dr[column Name] = value; mySqlDataAdapter.Update(ds); }
What are the steps to connect to a database? 1. Create a connection. This requires a connection string, which can be given declaratively or put in a well defined place like the .config files. Advantage of keeping in .config files is that it enables use of Connection Pooling by .Net framework, else even one small change in connection string will cause CLR to think it's not the same connection and will instantiate new connection for other request. 2. Open the connection and keep it open until done, typically done as using (con) { //use } 3. If using connected data model, create a SqlCommand object, decorate it with desired command, command type (stored procedure for eg), add any parameters and their values to the command, and then consume the command by using ExcuteReader or ExecuteScalar. In case of ExecuteReader, we will get back a handle to a fast-forward, read only pointer to the recordset. We can also decorate Command object with multiple recordsets in 2.0 and execute one by one (MARS - Multiple Active Record Sets) 4. If using disconnected data model, create a DataAdapter object, decorate it with desired SELECT, INSERT, UPDATE, DELETE commands, add parameters as necessary and then fill up a DataSet or DataTable using the DataAdapter. Subsequent SQL can be executed using insert, update, delete commands on the dataset. How do you connect to SQL Server Database without using sqlclient? You can connect sql using oledbname space . What is Partial class? A Partial class is a class that can be split into two or more classes. This means that a class can be physically separated into other parts of the class within the same namespace. All the parts must use the partial keyword. All the other classes should also have the same access modifier. At the compile time, all the partial classes will be treated as a single class. Let us list some advantages of having partial classes. What are the advantages and disadvantages of using datalist? Adv: the DataList's display is defined via templates,DataList allows for much more customization of the rendered HTML markup , by which it is more user-friendly displays of data. DisAdv: adding such functionality with the DataList takes more development time than with the DataGrid, as, 1. The Edit/Update/Cancel buttons that can be created in a DataGrid via the EditCommandColumn column type, must be manually added to the DataList, and 2. The DataGrid BoundColumn column types automatically use a TextBox Web control for the editing interface, whereas with the DataList you must explicitly specify the editing interface for the item being edited via the EditItemTemplate. 3. We can't do the paging and sorting with datalist controls. What is the difference between data reader and data adapter? DateReader is an forward only and read only cursor type if you are accessing data through DataRead it shows the data on the web form/control but you can not perform the paging feature on that
record(because it's forward only type). Reader is best fit to show the Data (where no need to work on data) DataAdapter is not only connect with the Databse(through Command object) it provide four types of command (InsertCommand, UpdateCommand, DeleteCommand, SelectCommand), It supports to the disconnected Architecture of .NET show we can populate the records to the DataSet. where as Dataadapter is best fit to work on data. What is the difference between data reader & data set? 1) DataSet is disconnected object type. It uses XML to store data. 2) It fetches all data from the data source at a time 3) Modifications can be updated to the actual database 4) It will reduce the application performance. Does SQLClient and OLEdb class share the same functionality? No, each have its own functionality, ex : for sql client , there is SqlConnection object and for oledb client , there is OleDBConnection What is the namespace in which .NET has the data functionality class? Following are the namespaces provided by .NET for data management:-
System. Data This contains the basic objects used for accessing and storing relational data, such as DataSet, DataTable, and Data Relation. Each of these is independent of the type of data source and the way we connect to it. System.Data.OleDB It contains the objects that we use to connect to a data source via an OLE-DB provider, such as OleDbConnection, OleDbCommand, etc. These objects inherit from the common base classes, and so have the same properties, methods, and events as the SqlClient equivalents. System.Data.SqlClient: This contains the objects that we use to connect to a data source via the Tabular Data Stream (TDS) interface of Microsoft SQL Server (only). This can generally provide better performance as it removes some of the intermediate layers required by an OLE-DB connection. System.XML This Contains the basic objects required to create, read, store, write, and manipulate XML documents according to W3C recommendations. Can you give an overview of ADO.NET architecture? The most important section in ADO.NET architecture is Data Provider. Data Provider provides access to data source (SQL SERVER, ACCESS, ORACLE).In short it provides object to achieve functionalities like opening and closing connection, retrieve data, and update data. In the below figure, you can see the four main sections of a data provider:-
Connection Command object (This is the responsible object to use stored procedures) Data Adapter (This object acts as a bridge between data store and dataset) Data reader (This object reads data from data store in forward only mode). Dataset object represents disconnected and cached data. If you see the diagram, it is not in direct connection with the data store (SQL SERVER, ORACLE etc) rather it talks with Data adapter, who is responsible for filling the dataset. Dataset can have one or more Data table and relations. Figure: - 9.1 ADO.NET Architecture Data View object is used to sort and filter data in Data table Note:- This is one of the favorite questions in .NET. Just paste the picture in your mind and during interview try to refer that image. What are the two fundamental objects in ADO.NET? Data reader and Dataset are the two fundamental objects in ADO.NET. What is difference between dataset and data reader? Following are some major differences between dataset and data reader:-
Data Reader provides forward-only and read-only access to data, while the Dataset object can hold more than one table (in other words more than one row set) from the same data source as well as the relationships between them.
Dataset is a disconnected architecture while data reader is connected architecture. Dataset can persist contents while data reader cannot persist contents, they are forward only. What are major difference between classic ADO and ADO.NET? Following are some major differences between both : In ADO we have recordset and in ADO.NET we have dataset. In recordset we can only have one table. If we want to accommodate more than one tables we need to do inner join and fill the recordset. Dataset can have multiple tables. All data persist in XML as compared to classic ADO where data persisted in Binary format also. What is the use of connection object? They are used to connect a data to a Command object. An OleDbConnection object is used with an OLE-DB provider A SqlConnection object uses Tabular Data Services (TDS) with MS SQL Server
What is the use of command objects? They are used to connect connection object to Data reader or dataset. Following are the methods provided by command object: ExecuteNonQuery: Executes the command defined in the Command Text property against the connection defined in the Connection property for a query that does not return any row (an UPDATE, DELETE, or INSERT). Returns an Integer indicating the number of rows affected by the query. ExecuteReader: Executes the command defined in the Command Text property against the connection defined in the Connection property. Returns a "reader" object that is connected to the resulting row set within the database, allowing the rows to be retrieved. ExecuteScalar: Executes the command defined in the Command Text property against the connection defined in the Connection property. Returns only single value (effectively the first column of the first row of the resulting row set any other returned columns and rows are discarded. It is fast and efficient when only a "singleton" value is required 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 basic methods of Data adapter? There are three most commonly used methods of Data adapter:Fill: Executes the Select Command to fill the Dataset object with data from the data source. It an also be used to update (refresh) an existing table in a Dataset with changes made to the data in the original data source if there is a primary key in the table in the Dataset. FillSchema :Uses the SelectCommand to extract just the schema for a table from the data source, and creates an empty table in the DataSet object with all the corresponding constraints.Update:- Calls the respective InsertCommand, UpdateCommand, or DeleteCommand for each inserted, updated,or deleted row in the DataSet so as to update the original data source with the changes made to the content of the DataSet. This is a little like the UpdateBatch method provided by the ADO Recordset object, but in the DataSet it can be used to update more than one table. What is Dataset object? The Dataset provides the basis for disconnected storage and manipulation of relational data. We fill it
from a data store, work with it while disconnected from that data store, then reconnect and flush changes back to the data store if required. What are the various objects in Dataset? Dataset has a collection of Data Table object within the Tables collection. Each Data Table object contains a collection of Data Row objects and a collection of Data Column objects. There are also collections for the primary keys, constraints, and default values used in this table, which is called as constraint collection, and the parent and child relationships between the tables. Finally, there is a Default View object for each table. This is used to create a Data View object based on the table, so that the data can be searched, filtered, or otherwise manipulated while displaying the data. Note: - Look back again to the main diagram for ADO.NET architecture for visualizing this answer in pictorial form. What is Delegate? Delegate is an important element of C# and is extensively used in every type of .NET application. A delegate is a class whose object (delegate object) can store a set of references to methods. How do you update a Dataset in ADO.Net and How do you update database through Dataset? a. Update a dataset; Dataset ds = new dataset(); SqlDataAdapter adp = new SqlDataAdapter(Query,connection); Adp.fill(ds); Again you can add/update Dataset as below SqlDataAdapter adp1 = new SqlDataAdapter(Query1,connection); Adp1.fill(ds);
What are the advantages and disadvantages of using datalist? Adv: the DataList's display is defined via templates,DataList allows for much more customization of the rendered HTML markup , by which it is more user-friendly displays of data. DisAdv:adding such functionality with the DataList takes more development time than with the DataGrid, as, 1. The Edit/Update/Cancel buttons that can be created in a DataGrid via the EditCommandColumn column type, must be manually added to the DataList, and 2. The DataGrid BoundColumn column types automatically use a TextBox Web control for the editing interface, whereas with the DataList you must explicitly specify the editing interface for the item being edited via the EditItemTemplate. 3. we can't do the paging and sorting with datalist controls. What is the difference between data reader and data adapter? DateReader is an forward only and read only cursor type if you are accessing data through DataRead it shows the data on the web form/control but you can not perform the paging feature on that record(because it's forward only type). Reader is best fit to show the Data (where no need to work on data) DataAdapter is not only connect with the Databse(through Command object) it provide four types of command (InsertCommand, UpdateCommand, DeleteCommand, SelectCommand), It supports to the
disconnected Architecture of .NET show we can populate the records to the DataSet. where as Dataadapter is best fit to work on data. What is the difference between data reader and data set? 1) DataSet is disconnected object type. It uses XML to store data. 2) It fetches all data from the data source at a time 3) Modifications can be updated to the actual database 4) It will reduce the application performance. Does SQLClient and OLEdb class share the same functionality? No, each have its own functionality, ex : for sql client , there is SqlConnection object and for oledb client , there is OleDBConnection Why edit is not possible in repeater? It has no such feature. b. Update database through dataset. SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter); Foreach(datarow dr in ds.table[0].rows) { Dr[column Name] = value; mySqlDataAdapter.Update(ds); } What are the steps to connect to a database? 1. Create a connection. This requires a connection string, which can be given declaratively or put in a well defined place like the .config files. Advantage of keeping in .config files is that it enables use of Connection Pooling by .Net framework, else even one small change in connection string will cause CLR to think it's not the same connection and will instantiate new connection for other request. 2. Open the connection and keep it open until done, typically done as using (con) { //use } 3. If using connected data model, create a SqlCommand object, decorate it with desired command, command type (stored procedure for eg), add any parameters and their values to the command, and then consume the command by using ExcuteReader or ExecuteScalar. In case of ExecuteReader, we will get back a handle to a fast-forward, read only pointer to the recordset. We can also decorate Command object with multiple recordsets in 2.0 and execute one by one (MARS - Multiple Active Record Sets) 4. If using disconnected data model, create a DataAdapter object, decorate it with desired SELECT, INSERT, UPDATE, DELETE commands, add parameters as necessary and then fill up a DataSet or DataTable using the DataAdapter. Subsequent SQL can be executed using insert, update, delete commands on the dataset. How do you connect to SQL Server Database without using sqlclient? you can connect sql using oledbname space . What is Partial class? A Partial class is a class that can be split into two or more classes. This means that a class can be
physically separated into other parts of the class within the same namespace. All the parts must use the partial keyword. All the other classes should also have the same access modifier. At the compile time, all the partial classes will be treated as a single class. Let us list some advantages of having partial classes. How can we add/remove row is in Data Table object of Dataset? Data table provides NewRow method to add new row to Data Table. Data Table has DataRowCollection object that has all rows in a Data Table object. Following are the methods provided by DataRowCollection object:Add Adds a new row in Data Table Remove It removes a Data Row object from Data Table Remove At It removes a Data Row object from Data Table depending on index position of the Data Table. What is basic use of Data View? Data View represents a complete table or can be small section of rows depending on some criteria. It is best used for sorting and finding data with in data table. Data view has the following methods:Find It takes an array of values and returns the index of the row. Find Row This also takes array of values but returns a collection of Data Row. If we want to manipulate data of Data Table object create Data View (Using the Default View we can create Data View object) of the Data Table object and use the following functionalities:Add New Adds a new row to the Data View object. Delete Deletes the specified row from Data View object. What is the difference between Dataset and Data Reader ? Twist: - Why is Dataset slower than Data Reader is?Fourth point is the answer to the twist. Note:- This is my best question and we expect everyone to answer it. It is asked almost 99% in all companies....Basic very Basic cram it. Following are the major differences between Dataset and Data Reader: Dataset is a disconnected architecture, while Data Reader has live connection while reading data. If we want to cache data and pass to a different tier Dataset forms the best choice and it has decent XML support. When application needs to access data from more than one table Dataset forms the best choice.
If we need to move back while reading records, data reader does not support this functionality. However, one of the biggest drawbacks of Dataset is speed. As Dataset carry considerable overhead because of relations, multiple tables etc speed is slower than Data Reader. Always try to use Data Reader wherever possible, as it is meant especially for speed performance. How can we load multiple tables in a Dataset? objCommand.CommandText = "Table1" objDataAdapter.Fill(objDataSet, "Table1") objCommand.CommandText = "Table2" objDataAdapter.Fill(objDataSet, "Table2") Above is a sample code, which shows how to load multiple Data Table objects in one Dataset object. Sample code shows two tables Table1 and Table2 in object ObjDataSet. lstdata.DataSource = objDataSet.Tables("Table1").DefaultView In order to refer Table1 Data Table, use Tables collection of Datasets and the Default view object will give you the necessary output. How can we add relation between tables in a Dataset? Dim objRelation As DataRelation objRelation=New DataRelation("CustomerAddresses",objDataSet.Tables("Customer").Columns("Custid") ,objDataSet.Tables("Addresses").Columns("Custid_fk")) objDataSet.Relations.Add(objRelation) Relations can be added between Data Table objects using the Data Relation object. Above sample, code is trying to build a relationship between Customer and Addresses Data table using Customer Addresses Data Relation object. What is the use of Command Builder? Command Builder builds Parameter objects automatically. Below is a simple code, which uses command builder to load its parameter objects. Dim pobjCommandBuilder As New OleDbCommandBuilder(pobjDataAdapter) pobjCommandBuilder.DeriveParameters(pobjCommand) Be careful while using Derive Parameters method as it needs an extra trip to the Data store, which can be very inefficient Whats difference between Optimistic and Pessimistic locking ? In pessimistic locking when user wants to update data it locks the record and till then no one can update data. Other users can only view the data when there is pessimistic locking. In optimistic locking multiple users can open the same record for updating, thus increase maximum concurrency. Record is only locked when updating the record. This is the most preferred way of locking
practically. Now a days in browser based application it is very common and having pessimistic locking is not a practical solution. How many ways are there to implement locking in ADO.NET? Following are the ways to implement locking using ADO.NET: When we call Update method of Data Adapter it handles locking internally. If the Dataset values are not matching with current data in Database, it raises concurrency exception error. We can easily trap this error using Try. Catch block and raise appropriate error message to the user. Define a Date time stamp field in the table. When actually you are firing the UPDATE SQL statements, compare the current timestamp with one existing in the database. Below is a sample SQL which checks for timestamp before updating and any mismatch in timestamp it will not update the records. This I the best practice used by industries for locking. Update table1 set field1=@test where Last Timestamp=@Current Timestamp Check for original values stored in SQL SERVER and actual changed values. In stored procedure check before updating that the old data is same as the current Example in the below shown SQL before updating field1 we check that is the old field1 value same. If not then some one else has updated and necessary action has to be taken. Update table1 set field1=@test where field1 = @oldfield1value Locking can be handled at ADO.NET side or at SQL SERVER side i.e. in stored procedures. For more details of how to implementing locking in SQL SERVER read What are different locks in SQL SERVER? in SQL SERVER chapter. How can we perform transactions in .NET? The most common sequence of steps that would be performed while developing a transactional application is as follows: Open a database connection using the Open method of the connection object. Begin a transaction using the Begin Transaction method of the connection object. This method provides us with a transaction object that we will use later to commit or rollback the transaction. Note that changes caused by any queries executed before calling the Begin Transaction method will be committed to the database immediately after they execute. Set the Transaction property of the command object to the above mentioned transaction object. Execute the SQL commands using the command object. We may use oneormorecommand objects for this purpose, as long as the Transaction property of all the objects is set to a valid transaction object. Commit or roll back the transaction using the Commit or Rollback method of the transaction object. Close the database connection. What is difference between Dataset? Clone and Dataset. Copy? Clone: - It only copies structure, does not copy data.
Copy: - Copies both structure and data. Can you explain the difference between an ADO.NET Dataset and an ADO Record set? There two main basic differences between record set and dataset: With dataset you an retrieve data from two databases like oracle and sql server and merge them in one dataset , with record set this is not possible All representation of Dataset is using XML while record set uses COM. Record set cannot be transmitted on HTTP while Dataset can be. Explain in detail the fundamental of connection pooling? When a connection is opened first time, a connection pool is created and is based on the exact match of the connection string given to create the connection object. Connection pooling only works if the connection string is the same. If the connection string is different, then a new connection will be opened, and connection pooling will not be used. What is Maximum Pool Size in ADO.NET Connection String? Maximum pool size decides the maximum number of connection objects to be pooled. If the maximum pool size is reached and there is no usable connection available the request is queued until connections are released back in to pool. So its always a good habit to call the close or dispose method of the connection as soon as you have finished work with the connection object. How to enable and disable connection pooling? For .NET it is enabled by default but if you want to just make sure set Pooling=true in the connection string. To disable connection pooling set Pooling=false in connection string if it is an ADO.NET Connection. If it is an OLEDBConnection object set OLE DB Services=-4 in the connection string. What extra features does ADO.Net 2.0 have ? Bulk Copy Operation Bulk copying of data from a data source to another data source is a newly added feature in ADO.NET 2.0. ADO.NET inrtoduces bulk copy classes which provide fastest way to transfer\ data from once source to the other. Each ADO.NET data provider has bulk copy classes. For example, in SQL .NET data provider, the bulk copy operation is handled by SqlBulkCopy class, which can read a DataSet, DataTable, DataReader, or XML objects.
Data Paging A new method is introduced ExecutePageReader which takes three parameters - CommandBehavior, startIndex, and pageSize. So if you want to get rows ony from 10 - 20, you can simply call this method with start index as 10 and page size as 10.
Batch Update
If you want to update large number of data on set ADO.NET 2.0 provides UpdateBatchSize property, which allows you to set number of rows to be updated in a batch. This increases the performance dramatically as round trip to the server is minimized.
Load and Save Methods In previous version of ADO.NET, only DataSet had Load and Save methods. The Load method can load data from objects such as XML into a DataSet object and Save method saves the data to a persistent media. Now DataTable also supports these two methods. You can also load a DataReader object into a DataTable by using the Load method.
New Data Controls In toolbox you can see three new controls - DataGridView, DataConnector, and DataNavigator. DataReader's New Execute Methods Some new execute methods introduced are ExecutePageReader, ExecuteResultSet, and ExecuteRow. How do we use stored procedure in ADO.NET and how do we provide parameters to the stored procedures?
ADO.NET provides the SqlCommand object, which provides the functionality of executing stored procedures. Note :- Sample code is provided in folder WindowsSqlClientCommand. There are two stored procedures created in same database Employees which was created for the previous question.
CREATE PROCEDURE SelectByEmployee @FirstName nvarchar(200) AS Select FirstName from Employees where FirstName like @FirstName + '%' CREATE PROCEDURE SelectEmployee AS Select FirstName from Employees If txtEmployeeName.Text.Length = 0 Then objCommand = New SqlCommand(SelectEmployee) Else objCommand = New SqlCommand(SelectByEmployee) objCommand.Parameters.Add(@FirstName, Data.SqlDbType.NVarChar, 200) objCommand.Parameters.Item(@FirstName).Value = txtEmployeeName.Text.Trim() End If In the above sample, not much has been changed only that the SQL is moved to the stored procedures. There are two stored procedures one is Select Employee which selects all the employees and the other is SelectByEmployee which returns employee name starting with a specific character. As you can see to provide parameters to the stored procedures, we are using the parameter object of the command object. In such question interviewer expects two simple answers one is that we use command object to execute
stored procedures and the parameter object to provide parameter to the stored procedure. Above sample is provided only for getting the actual feel of it. Be short be nice and get a job. How can we force the connection object to close after my data reader is closed? Command method Execute reader takes a parameter called as Command Behavior where in we can specify saying close connection automatically after the Data reader is close. PobjDataReader = pobjCommand.ExecuteReader (CommandBehavior.CloseConnection) I want to force the data reader to return only schema of the data store rather than data. PobjDataReader = pobjCommand.ExecuteReader (CommandBehavior.SchemaOnly) How can we fine-tune the command object when we are expecting a single row? Again, CommandBehaviour enumeration provides two values Single Result and Single Row. If you are expecting a single value then pass CommandBehaviour.SingleResult and the query is optimized accordingly, if you are expecting single row then pass CommandBehaviour.SingleRow and query is optimized according to single row. Which is the best place to store connection string in .NET projects? Config files are the best places to store connection strings. If it is a web-based application Web.config file will be used and if it is a windows application App.config files will be used. What are the steps involved to fill a dataset? Twist: - How can we use data adapter to fill a dataset? Sample code is provided in WindowsDataSetSample folder in CD.LoadData has all the implementation of connecting and loading to dataset. This dataset is finally bind to a List Box. Below is the sample code. Private Sub LoadData() Dim strConnectionString As String strConnectionString = AppSettings.Item(ConnectionString) Dim objConn As New SqlConnection(strConnectionString) objConn.Open() Dim objCommand As New SqlCommand(Select FirstName from Employees) objCommand.Connection = objConn Dim objDataAdapter As New SqlDataAdapter() objDataAdapter.SelectCommand = objCommand Dim objDataSet As New DataSet End Sub In such type of questions interviewer is looking from practical angle, that have you worked with dataset and datadapters. Let me try to explain the above code first and then we move to what steps should be told during interview. Dim objConn As New SqlConnection(strConnectionString) objConn.Open()
First step is to open the connection. Again, note the connection string is loaded from config file. Dim objCommand As New SqlCommand(Select FirstName from Employees) objCommand.Connection = objConn Second step is to create a command object with appropriate SQL and set the connection object to this command. Dim objDataAdapter As New SqlDataAdapter() objDataAdapter.SelectCommand = objCommand
Third steps is to create the Adapter object and pass the command object to the adapter object. objDataAdapter.Fill(objDataSet) Fourth step is to load the dataset using the Fill method of the data adapter. lstData.DataSource = objDataSet.Tables(0).DefaultView lstData.DisplayMember = FirstName lstData.ValueMember = FirstName Fifth step is to bind to the loaded dataset with the GUI. At this moment sample has list box as the UI. Binding of the UI is done by using Default View of the dataset. Just to revise every dataset has tables and every table has views. In this sample, we have only loaded one table i.e. Employees table so we are referring that with an index of zero. Just say all the five steps during interview and you will see the smile on the interviewers face and appointment letter in your hand. What are the various methods provided by the dataset object to generate XML? Note:- XML is one of the most important leap between classic ADO and ADO.NET. So this question is normally asked more generally how can we convert any data to XML format. Best answer is convert in to dataset and use the below methods. ReadXML Reads a XML document in to Dataset. GetXML This is a function, which returns the string containing XML document. Writexml This writes a XML data to disk. How can we save all data from dataset? Dataset has Accept Changes method, which commits all the changes since last time Accept changes has been executed. Note :- This book does not have any sample of Acceptchanges. We leave that to readers as homework sample. But yes from interview aspect that will be enough. How can we check that some changes have been made to dataset since it was loaded? Twist: - How can we cancel all changes done in dataset? Twist: - How do we get values, which are changed, in a dataset?
For tracking down changes, Dataset has two methods, which comes as rescue Get Changes and Has Changes. Get Changes Returns dataset, which are changed since it, was loaded, or since Accept changes was executed. Has Changes Or abandon all changes since the dataset was loaded use Reject Changes This property indicates that has any changes been made since the dataset was loaded or accept changes method was executed. Note:- One of the most misunderstood things about these properties is that it tracks the changes of actual database. That is a fundamental mistake; actually the changes are related to only changes with dataset and have nothing to with changes happening in actual database. As dataset are disconnected and do not know anything about the changes happening in actual database. If a table contains 20000 records . In a page at each time 100 records to be displayed. What are the steps u will take to improve performance? Will you use dataset or datareader? we have to use a dataset because on using datareader forward only paging can be achieved. Suppose if you are at 1000 page and you want to go back to 999th page, if you use datareader it cannot be achieved, since it does not support backward navigation. Dataset supports forward and backward navigation What is data access layer? Data Access layer is actually a part of Architecture layer. It has 2 tier,3 tier or N tier Layer. Generally we use 3 tier Layer 1) Presentation layer,Business Logic layer and then Data Access Layer. Data Access layer is a medium to talk between database and Business Logic layer. It helps to maintain flexibility,resuablity and even secuity also. In security SQL Injection can be stopped with 3 iter Archietcture. What are the different row versions available in table? There are four types of Rowversions. Current: The current values for the row. This row version does not exist for rows with a RowState of Deleted. Default : The row the default version for the current DataRowState. For a DataRowState value of Added, Modified or Current, the default version is Current. For a DataRowState of Deleted, the version is Original. For a DataRowState value of Detached, the version is Proposed. Original: The row contains its original values. Proposed: The proposed values for the row. This row version exists during an edit operation on a row, or for a row that is not part of a DataRowCollection. What are the two fundamental objects in ADO.NET? Datareader and Dataset are the two fundamental objects in ADO.NET What we do with the object of ado.net dataset after using it?Can we dispose it or can we set it nothing?Is it must or not?
we use dispose What provider ADO.net use by default? Ado.net uses no Dataprovider by default and this is absulotely correct answere. there is no other choice for this question What is the provider and namespaces being used to access oracle database? The provider name is oledb and the namespace is system.data.oledb Explain acid properties? The term ACID conveys the role transactions play in mission-critical applications. Coined by transaction processing pioneers, ACID stands for atomicity, consistency, isolation, and durability. These properties ensure predictable behavior, reinforcing the role of transactions as all-or-none propositions designed to reduce the management load when there are many variables. What is Atomicity? A transaction is a unit of work in which a series of operations occur between the BEGIN TRANSACTION and END TRANSACTION statements of an application. A transaction executes exactly once and is atomic ? all the work is done or none of it is. Operations associated with a transaction usually share a common intent and are interdependent. By performing only a subset of these operations, the system could compromise the overall intent of the transaction. Atomicity eliminates the chance of processing a subset of operations. What is Isolation? A transaction is a unit of isolation ? allowing concurrent transactions to behave as though each were the only transaction running in the system. Isolation requires that each transaction appear to be the only transaction manipulating the data store, even though other transactions may be running at the same time. A transaction should never see the intermediate stages of another transaction. Transactions attain the highest level of isolation when they are serializable. At this level, the results obtained from a set of concurrent transactions are identical to the results obtained by running each transaction serially. Because a high degree of isolation can limit the number of concurrent transactions, some applications reduce the isolation level in exchange for better throughput. What is data Adapter? Data adapter is bridge between Connection and DataSet , Data adapter in passing the sql query and fill in dataset How to find the count of records in a dataset? DS.Tables["tabname"].Rows.Count; We can get count of the records.
How can we connect to Microsoft Access, FoxPro, and Oracle etc? Microsoft provides System.Data.OleDb namespace to communicate with databases like success , Oracle etc. In short, any OLE DB-Compliant database can be connected using System.Data.OldDb namespace. Note :- Small sample of OLEDB is provided in WindowsAppOleDb which uses Nwind.mdb in bin directory to display data in Listbox. Private Sub loadData() Dim strPath As String strPath = AppDomain.CurrentDomain.BaseDirectory Dim objOLEDBCon As New OleDbConnection(Provider=Microsoft.Jet.OLEDB.4.0;Data Source = & strPath & Nwind.mdb) Dim objOLEDBCommand As OleDbCommand Dim objOLEDBReader As OleDbDataReader Try objOLEDBCommand = New OleDbCommand(Select FirstName from Employees) objOLEDBCon.Open() objOLEDBCommand.Connection = objOLEDBCon objOLEDBReader = objOLEDBCommand.ExecuteReader() Do While objOLEDBReader.Read() lstNorthwinds.Items.Add(objOLEDBReader.GetString(0)) Loop Catch ex As Exception Throw ex Finally objOLEDBCon.Close() End Try End Sub The main heart is the Load data () method which actually loads the data in list box. Note:- This source code has the connectionstring hard coded in the program itself which is not a good programming practice. For windows application the best place to store connectionstring is App.config. Also note that AppDomain.CurrentDomain.BaseDirectory function gives the current path of the running exe which is BIN and the MDB file is in that directory. Also note that the final block which executes irrespective that there is error or not. Thus ensuring that all the connection to the datastore is freed. Its best practice to put all clean up statements in finally block thus ensuring that the resources are deallocated properly. How do we connect to SQL SERVER, which namespace do we use? Below is the code, after the code we will try to understand the same in a more detailed manner. For this sample, we will also need a SQL Table setup, which I have imported, using the DTS wizard. Private Sub LoadData() note :- with and end with makes your code more readable Dim strConnectionString As String
Dim objConnection As New SqlConnection Dim objCommand As New SqlCommand Dim objReader As SqlDataReader Try this gets the connectionstring from the app.config file. note if this gives error see where the MDB file is stored in your pc and point to thastrConnectionString = AppSettings.Item(ConnectionString) take the connectiostring and initialize the connection object With objConnection .ConnectionString = strConnectionString .Open() End With objCommand = New SqlCommand(Select FirstName from Employees) With objCommand .Connection = objConnection objReader = .ExecuteReader() End With looping through the reader to fill the list box Do While objReader.Read() lstData.Items.Add(objReader.Item(FirstName)) Loop Catch ex As Exception Throw ex Finally objConnection.Close() End Try Note:- The above code is provided in CD in folder WindowsAppSqlClient. Comments in the code do explain a lot but we will again iterate through the whole code later. LoadData is the main method which loads the data from SQL SERVER. Before running this code you have to install SQL SERVER in your machine. As we are dealing with SQLCLIENT we need to setup database in SQL SERVER. For this sample I have imported access Nwind.mdb in SampleAccessDatabase folder in CD in to SQlSERVER. Depending on computer you will also have to change the connectionstring in Web.config file. For setting up the sample SQL table, we can use the DTS import wizard to import the table. See the below figure which is using data source as Microsoft Access. While importing the database author had, give the database name as Employees. Figure: - 9.2 Loading Nwind.mdb in SQL SERVER for the sample Figure :- 9.3 Load only the Employee table. To make it simple we will only import the employee table as that is the only thing needed in our sample code. Figure: - 9.4 View of loaded Employee table Now from interview point of view definitely you are not going to say the whole source code, which is given in the book. Interviewer expects only the broader answer of what are the steps needed to connect to SQL SERVER. For fundamental sake author has explained the whole source code. In short, you have to explain the Load Data method in broader way. Following are the steps to connect to SQL SERVER:-
First imports the namespace System.Data.SqlClient. Create a connection object as shown in Load Data method. With objConnection .Connection String = strConnectionString .Open () End With Create the command object with the SQL. Also, assign the created connection object to command object and execute the reader. ObjCommand = New SqlCommand (Select First Name from Employees) With objCommand .Connection = objConnection Breeder = .Execute Reader () End With Finally loop through the reader and fill the list box. If old VB programmers are expecting the move next command it is replaced by Read () which returns true if there is any data to be read. If the .Read () return is false that means that its end of data reader and there is no more data to be read. Do while objReader.Read () lstData.Items.Add (objReader.Item (First Name)) Loop Do not forget to close the connection object. Note:- In LoadData you will see that connectionstring is stored in Web.config file and is loaded using AppSettings.Item(ConnectionString). While running this sample live on your database do not forget to change this connectionstring accordingly to your machine name and SQL SERVER or else the source code will not run. Difference between SqlCommand and SqlCommandBuilder? a) SQLCommand is used to execute all kind of SQL queries like DML(Insert, update,Delete) & DDL like(Create table, drop table etc) b)SQLCommandBuilder object is used to build & execute SQL (DML) queries like select, insert, update & delete. Why can not we use Multiple inheritance and garbage collector paralelly in .net? .net doesn't support the mutiple inheritance, perhaps you may talk about multi-level inheritance. In the later case, if a class is inherited from another class, at the time of creating instance, it will obviously give a call to its base class constructor (ie bottom - top approach). Like wise the constructor execution is takes place in top down approach (ie. base class constructor is executed and the derived class constructor is executed). So for GC, it will collect only when an object does not have any reference. As we see previously, the derived is constructed based on base class. There is a reference is set to be. Obviously GC cannot be collected. How to find the given query is optimised one or not? First Excute Sql Quries in Query Analzer,see How much time 2 take Excute , if Less then the ur desired
Time, then it will Optimize query How to copy the contents from one table to another table and how to delete the source table in ado.net? it is possible DataSet ds; sqlAdap.Fill(ds); Datatable dt = ds.Tables[0].copy(); //now the structure and data are copied into 'dt' ds.Tables.remove(ds.Table[0]); //now the source is removed from the 'ds' How to call the SQL commands asynchronously in ADO.NET version 2.0? executescalar() executereader() executenonquery() these comes with Begin and End like Beginexecutescalr() Endexecutescalar().......by using these command we can achieve asynch comm in ado.net What is typed and untyped dataset? A DataSet can be Typed or Untyped. The difference between the two lies in the fact that a Typed DataSet has a schema and an Untyped DataSet does not have one. It should be noted that the Typed Datasets have more support in Visual studio. I loaded the dataset with a table of 10 records. One of the records is deleted from the backend, How do you check whether all the 10 records were present while updating the data(Which event and steps) and throw the exception. By Using the Transactions we can check the Exact Numbers of the rows to be updated and if the updation fails then the Transaction will be rollbacked. Can dataReader hold data from multiple tables? Data reader can hold data from multiple tables and datareader can hold more than one table. string query="select * from employee; select * from student"; sqlcommand cmd=new sqlcommand(query, connection); sqldatareader dr=cmd.executeReader(); if(dr.hasrows) { dr.read(); gridview1.DataSource=dr; gridview1.Databind(); if(dr.nextresult) {
gridview2.datasource=dr; gridview2.databind(); } } dr.colse(); connection.close(); What is different between SqlCommand object and Command Behavior Object? DO.NET Command Object - The Command object is similar to the old ADO command object. It is used to store SQL statements that need to be executed against a data source. The Command object can execute SELECT statements, INSERT, UPDATE, or DELETE statements, stored procedures, or any other statement understood by the database. What is bubbled event can u pls explain? All heavy controls like grid view,datagrid or datalist,repeater controls cantains the chield controls like button or link button, when we click this button then the event will be raised, that events are handled by parant controls,that is called event bubbling,means event is bubbled from bottom(chield)to up(parant). If a table contains 20000 records . In a page at each time 100 records to be displayed. What are the steps u will take to improve performance? Will you use dataset or datareader? we have to use a dataset because on using datareader forward only paging can be achieved. Suppose if you are at 1000 page and you want to go back to 999th page, if you use datareader it cannot be achieved, since it does not support backward navigation. Dataset supports forward and backward navigation What is data access layer? Data Access layer is actually a part of Architecture layer. It has 2 tier,3 tier or N tier Layer. Generally we use 3 tier Layer 1) Presentation layer,Business Logic layer and then Data Access Layer. Data Access layer is a medium to talk between database and Business Logic layer. It helps to maintain flexibility,resuablity and even secuity also. In security SQL Injection can be stopped with 3 iter Archietcture. What are the different row versions available in table? There are four types of Rowversions. Current: The current values for the row. This row version does not exist for rows with a RowState of Deleted. Default : The row the default version for the current DataRowState. For a DataRowState value of Added, Modified or Current, the default version is Current. For a DataRowState of Deleted, the version is Original. For a DataRowState value of Detached, the version is Proposed. Original: The row contains its original values. Proposed: The proposed values for the row. This row version exists during an edit operation on a row, or for a row that is not part of a DataRowCollection.
What are the two fundamental objects in ADO.NET? Datareader and Dataset are the two fundamental objects in ADO.NET What we do with the object of ado.net dataset after using it?Can we dispose it or can we set it nothing?Is it must or not? we use dispose What provider ADO.net use by default? Ado.net uses no Dataprovider by default and this is absulotely correct answere. there is no other choice for this question What is the provider and namespaces being used to access oracle database? The provider name is oledb and the namespace is system.data.oledb Explain acid properties? The term ACID conveys the role transactions play in mission-critical applications. Coined by transaction processing pioneers, ACID stands for atomicity, consistency, isolation, and durability. These properties ensure predictable behavior, reinforcing the role of transactions as all-or-none propositions designed to reduce the management load when there are many variables. What is Atomicity? A transaction is a unit of work in which a series of operations occur between the BEGIN TRANSACTION and END TRANSACTION statements of an application. A transaction executes exactly once and is atomic ? all the work is done or none of it is. Operations associated with a transaction usually share a common intent and are interdependent. By performing only a subset of these operations, the system could compromise the overall intent of the transaction. Atomicity eliminates the chance of processing a subset of operations. What is Isolation? A transaction is a unit of isolation ? allowing concurrent transactions to behave as though each were the only transaction running in the system. Isolation requires that each transaction appear to be the only transaction manipulating the data store, even though other transactions may be running at the same time. A transaction should never see the intermediate stages of another transaction. Transactions attain the highest level of isolation when they are serializable. At this level, the results obtained from a set of concurrent transactions are identical to the results obtained by running each transaction serially. Because a high degree of isolation can limit the number of concurrent transactions, some applications reduce the isolation level in exchange for better throughput. What is data Adapter? Data adapter is bridge between Connection and DataSet , Data adapter in passing the sql query and fill in dataset
How to find the count of records in a dataset? DS.Tables["tabname"].Rows.Count; We can get count of the records. What is Delegate? Delegate is an important element of C# and is extensively used in every type of .NET application. A delegate is a class whose object (delegate object) can store a set of references to methods. How do you update a Dataset in ADO.Net and How do you update database through Dataset? a. Update a dataset; Dataset ds = new dataset(); SqlDataAdapter adp = new SqlDataAdapter(Query,connection); Adp.fill(ds); Again you can add/update Dataset as below SqlDataAdapter adp1 = new SqlDataAdapter(Query1,connection); Adp1.fill(ds);
What are the advantages and disadvantages of using datalist? Adv: the DataList's display is defined via templates,DataList allows for much more customization of the rendered HTML markup , by which it is more user-friendly displays of data. DisAdv:adding such functionality with the DataList takes more development time than with the DataGrid, as, 1. The Edit/Update/Cancel buttons that can be created in a DataGrid via the EditCommandColumn column type, must be manually added to the DataList, and 2. The DataGrid BoundColumn column types automatically use a TextBox Web control for the editing interface, whereas with the DataList you must explicitly specify the editing interface for the item being edited via the EditItemTemplate. 3. we can't do the paging and sorting with datalist controls. What is the difference between data reader and data adapter? DateReader is an forward only and read only cursor type if you are accessing data through DataRead it shows the data on the web form/control but you can not perform the paging feature on that record(because it's forward only type). Reader is best fit to show the Data (where no need to work on data) DataAdapter is not only connect with the Databse(through Command object) it provide four types of command (InsertCommand, UpdateCommand, DeleteCommand, SelectCommand), It supports to the disconnected Architecture of .NET show we can populate the records to the DataSet. where as Dataadapter is best fit to work on data. What is the difference between data reader and data set? 1) DataSet is disconnected object type. It uses XML to store data. 2) It fetches all data from the data source at a time 3) Modifications can be updated to the actual database 4) It will reduce the application performance. Does SQLClient and OLEdb class share the same functionality? No, each have its own functionality,
ex : for sql client , there is SqlConnection object and for oledb client , there is OleDBConnection Why edit is not possible in repeater? It has no such feature. b. Update database through dataset. SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter); Foreach(datarow dr in ds.table[0].rows) { Dr[column Name] = value; mySqlDataAdapter.Update(ds); } What are the steps to connect to a database? 1. Create a connection. This requires a connection string, which can be given declaratively or put in a well defined place like the .config files. Advantage of keeping in .config files is that it enables use of Connection Pooling by .Net framework, else even one small change in connection string will cause CLR to think it's not the same connection and will instantiate new connection for other request. 2. Open the connection and keep it open until done, typically done as using (con) { //use } 3. If using connected data model, create a SqlCommand object, decorate it with desired command, command type (stored procedure for eg), add any parameters and their values to the command, and then consume the command by using ExcuteReader or ExecuteScalar. In case of ExecuteReader, we will get back a handle to a fast-forward, read only pointer to the recordset. We can also decorate Command object with multiple recordsets in 2.0 and execute one by one (MARS - Multiple Active Record Sets) 4. If using disconnected data model, create a DataAdapter object, decorate it with desired SELECT, INSERT, UPDATE, DELETE commands, add parameters as necessary and then fill up a DataSet or DataTable using the DataAdapter. Subsequent SQL can be executed using insert, update, delete commands on the dataset. How do you connect to SQL Server Database without using sqlclient? you can connect sql using oledbname space . What is Partial class? A Partial class is a class that can be split into two or more classes. This means that a class can be physically separated into other parts of the class within the same namespace. All the parts must use the partial keyword. All the other classes should also have the same access modifier. At the compile time, all the partial classes will be treated as a single class. Let us list some advantages of having partial classes. How do we use stored procedure in ADO.NET and how do we provide parameters to the stored procedures?
ADO.NET provides the SqlCommand object, which provides the functionality of executing stored procedures.
Note :- Sample code is provided in folder WindowsSqlClientCommand. There are two stored procedures created in same database Employees which was created for the previous question.
CREATE PROCEDURE SelectByEmployee @FirstName nvarchar(200) AS Select FirstName from Employees where FirstName like @FirstName + '%' CREATE PROCEDURE SelectEmployee AS Select FirstName from Employees If txtEmployeeName.Text.Length = 0 Then objCommand = New SqlCommand(SelectEmployee) Else objCommand = New SqlCommand(SelectByEmployee) objCommand.Parameters.Add(@FirstName, Data.SqlDbType.NVarChar, 200) objCommand.Parameters.Item(@FirstName).Value = txtEmployeeName.Text.Trim() End If In the above sample, not much has been changed only that the SQL is moved to the stored procedures. There are two stored procedures one is Select Employee which selects all the employees and the other is SelectByEmployee which returns employee name starting with a specific character. As you can see to provide parameters to the stored procedures, we are using the parameter object of the command object. In such question interviewer expects two simple answers one is that we use command object to execute stored procedures and the parameter object to provide parameter to the stored procedure. Above sample is provided only for getting the actual feel of it. Be short be nice and get a job. How can we force the connection object to close after my data reader is closed? Command method Execute reader takes a parameter called as Command Behavior where in we can specify saying close connection automatically after the Data reader is close. PobjDataReader = pobjCommand.ExecuteReader (CommandBehavior.CloseConnection) I want to force the data reader to return only schema of the data store rather than data. PobjDataReader = pobjCommand.ExecuteReader (CommandBehavior.SchemaOnly) How can we fine-tune the command object when we are expecting a single row? Again, CommandBehaviour enumeration provides two values Single Result and Single Row. If you are expecting a single value then pass CommandBehaviour.SingleResult and the query is optimized accordingly, if you are expecting single row then pass CommandBehaviour.SingleRow and query is optimized according to single row. Which is the best place to store connection string in .NET projects? Config files are the best places to store connection strings. If it is a web-based application Web.config file will be used and if it is a windows application App.config files will be used. What are the steps involved to fill a dataset? Twist: - How can we use data adapter to fill a dataset? Sample code is provided in WindowsDataSetSample folder in CD.LoadData has all the implementation
of connecting and loading to dataset. This dataset is finally bind to a List Box. Below is the sample code. Private Sub LoadData() Dim strConnectionString As String strConnectionString = AppSettings.Item(ConnectionString) Dim objConn As New SqlConnection(strConnectionString) objConn.Open() Dim objCommand As New SqlCommand(Select FirstName from Employees) objCommand.Connection = objConn Dim objDataAdapter As New SqlDataAdapter() objDataAdapter.SelectCommand = objCommand Dim objDataSet As New DataSet End Sub In such type of questions interviewer is looking from practical angle, that have you worked with dataset and datadapters. Let me try to explain the above code first and then we move to what steps should be told during interview. Dim objConn As New SqlConnection(strConnectionString) objConn.Open() First step is to open the connection. Again, note the connection string is loaded from config file. Dim objCommand As New SqlCommand(Select FirstName from Employees) objCommand.Connection = objConn Second step is to create a command object with appropriate SQL and set the connection object to this command. Dim objDataAdapter As New SqlDataAdapter() objDataAdapter.SelectCommand = objCommand
Third steps is to create the Adapter object and pass the command object to the adapter object. objDataAdapter.Fill(objDataSet) Fourth step is to load the dataset using the Fill method of the data adapter. lstData.DataSource = objDataSet.Tables(0).DefaultView lstData.DisplayMember = FirstName lstData.ValueMember = FirstName Fifth step is to bind to the loaded dataset with the GUI. At this moment sample has list box as the UI. Binding of the UI is done by using Default View of the dataset. Just to revise every dataset has tables and every table has views. In this sample, we have only loaded one table i.e. Employees table so we are referring that with an index of zero. Just say all the five steps during interview and you will see the smile on the interviewers face and appointment letter in your hand. What are the various methods provided by the dataset object to generate XML? Note:- XML is one of the most important leap between classic ADO and ADO.NET. So this question is
normally asked more generally how can we convert any data to XML format. Best answer is convert in to dataset and use the below methods. ReadXML Reads a XML document in to Dataset. GetXML This is a function, which returns the string containing XML document. Writexml This writes a XML data to disk. How can we save all data from dataset? Dataset has Accept Changes method, which commits all the changes since last time Accept changes has been executed. Note :- This book does not have any sample of Acceptchanges. We leave that to readers as homework sample. But yes from interview aspect that will be enough. How can we check that some changes have been made to dataset since it was loaded? Twist: - How can we cancel all changes done in dataset? Twist: - How do we get values, which are changed, in a dataset? For tracking down changes, Dataset has two methods, which comes as rescue Get Changes and Has Changes. Get Changes Returns dataset, which are changed since it, was loaded, or since Accept changes was executed. Has Changes Or abandon all changes since the dataset was loaded use Reject Changes This property indicates that has any changes been made since the dataset was loaded or accept changes method was executed. Note:- One of the most misunderstood things about these properties is that it tracks the changes of actual database. That is a fundamental mistake; actually the changes are related to only changes with dataset and have nothing to with changes happening in actual database. As dataset are disconnected and do not know anything about the changes happening in actual database. How can we connect to Microsoft Access, FoxPro, and Oracle etc? Microsoft provides System.Data.OleDb namespace to communicate with databases like success , Oracle etc. In short, any OLE DB-Compliant database can be connected using System.Data.OldDb namespace. Note :- Small sample of OLEDB is provided in WindowsAppOleDb which uses Nwind.mdb in bin directory to display data in Listbox. Private Sub loadData() Dim strPath As String strPath = AppDomain.CurrentDomain.BaseDirectory Dim objOLEDBCon As New OleDbConnection(Provider=Microsoft.Jet.OLEDB.4.0;Data Source = & strPath & Nwind.mdb) Dim objOLEDBCommand As OleDbCommand Dim objOLEDBReader As OleDbDataReader
Try objOLEDBCommand = New OleDbCommand(Select FirstName from Employees) objOLEDBCon.Open() objOLEDBCommand.Connection = objOLEDBCon objOLEDBReader = objOLEDBCommand.ExecuteReader() Do While objOLEDBReader.Read() lstNorthwinds.Items.Add(objOLEDBReader.GetString(0)) Loop Catch ex As Exception Throw ex Finally objOLEDBCon.Close() End Try End Sub The main heart is the Load data () method which actually loads the data in list box. Note:- This source code has the connectionstring hard coded in the program itself which is not a good programming practice. For windows application the best place to store connectionstring is App.config. Also note that AppDomain.CurrentDomain.BaseDirectory function gives the current path of the running exe which is BIN and the MDB file is in that directory. Also note that the final block which executes irrespective that there is error or not. Thus ensuring that all the connection to the datastore is freed. Its best practice to put all clean up statements in finally block thus ensuring that the resources are deallocated properly. How do we connect to SQL SERVER, which namespace do we use? Below is the code, after the code we will try to understand the same in a more detailed manner. For this sample, we will also need a SQL Table setup, which I have imported, using the DTS wizard. Private Sub LoadData() note :- with and end with makes your code more readable Dim strConnectionString As String Dim objConnection As New SqlConnection Dim objCommand As New SqlCommand Dim objReader As SqlDataReader Try this gets the connectionstring from the app.config file. note if this gives error see where the MDB file is stored in your pc and point to thastrConnectionString = AppSettings.Item(ConnectionString) take the connectiostring and initialize the connection object With objConnection .ConnectionString = strConnectionString .Open() End With objCommand = New SqlCommand(Select FirstName from Employees)
With objCommand .Connection = objConnection objReader = .ExecuteReader() End With looping through the reader to fill the list box Do While objReader.Read() lstData.Items.Add(objReader.Item(FirstName)) Loop Catch ex As Exception Throw ex Finally objConnection.Close() End Try Note:- The above code is provided in CD in folder WindowsAppSqlClient. Comments in the code do explain a lot but we will again iterate through the whole code later. LoadData is the main method which loads the data from SQL SERVER. Before running this code you have to install SQL SERVER in your machine. As we are dealing with SQLCLIENT we need to setup database in SQL SERVER. For this sample I have imported access Nwind.mdb in SampleAccessDatabase folder in CD in to SQlSERVER. Depending on computer you will also have to change the connectionstring in Web.config file. For setting up the sample SQL table, we can use the DTS import wizard to import the table. See the below figure which is using data source as Microsoft Access. While importing the database author had, give the database name as Employees. Figure: - 9.2 Loading Nwind.mdb in SQL SERVER for the sample Figure :- 9.3 Load only the Employee table. To make it simple we will only import the employee table as that is the only thing needed in our sample code. Figure: - 9.4 View of loaded Employee table Now from interview point of view definitely you are not going to say the whole source code, which is given in the book. Interviewer expects only the broader answer of what are the steps needed to connect to SQL SERVER. For fundamental sake author has explained the whole source code. In short, you have to explain the Load Data method in broader way. Following are the steps to connect to SQL SERVER: First imports the namespace System.Data.SqlClient. Create a connection object as shown in Load Data method. With objConnection .Connection String = strConnectionString .Open () End With Create the command object with the SQL. Also, assign the created connection object to command object and execute the reader. ObjCommand = New SqlCommand (Select First Name from Employees) With objCommand .Connection = objConnection
Breeder = .Execute Reader () End With Finally loop through the reader and fill the list box. If old VB programmers are expecting the move next command it is replaced by Read () which returns true if there is any data to be read. If the .Read () return is false that means that its end of data reader and there is no more data to be read. Do while objReader.Read () lstData.Items.Add (objReader.Item (First Name)) Loop Do not forget to close the connection object. Note:- In LoadData you will see that connectionstring is stored in Web.config file and is loaded using AppSettings.Item(ConnectionString). While running this sample live on your database do not forget to change this connectionstring accordingly to your machine name and SQL SERVER or else the source code will not run. Difference between SqlCommand and SqlCommandBuilder? a) SQLCommand is used to execute all kind of SQL queries like DML(Insert, update,Delete) & DDL like(Create table, drop table etc) b)SQLCommandBuilder object is used to build & execute SQL (DML) queries like select, insert, update & delete. Why can not we use Multiple inheritance and garbage collector paralelly in .net? .net doesn't support the mutiple inheritance, perhaps you may talk about multi-level inheritance. In the later case, if a class is inherited from another class, at the time of creating instance, it will obviously give a call to its base class constructor (ie bottom - top approach). Like wise the constructor execution is takes place in top down approach (ie. base class constructor is executed and the derived class constructor is executed). So for GC, it will collect only when an object does not have any reference. As we see previously, the derived is constructed based on base class. There is a reference is set to be. Obviously GC cannot be collected. How to find the given query is optimised one or not? First Excute Sql Quries in Query Analzer,see How much time 2 take Excute , if Less then the ur desired Time, then it will Optimize query How to copy the contents from one table to another table and how to delete the source table in ado.net? it is possible DataSet ds; sqlAdap.Fill(ds); Datatable dt = ds.Tables[0].copy(); //now the structure and data are copied into 'dt' ds.Tables.remove(ds.Table[0]); //now the source is removed from the 'ds'
How to call the SQL commands asynchronously in ADO.NET version 2.0? executescalar() executereader() executenonquery() these comes with Begin and End like Beginexecutescalr() Endexecutescalar().......by using these command we can achieve asynch comm in ado.net What is typed and untyped dataset? A DataSet can be Typed or Untyped. The difference between the two lies in the fact that a Typed DataSet has a schema and an Untyped DataSet does not have one. It should be noted that the Typed Datasets have more support in Visual studio. I loaded the dataset with a table of 10 records. One of the records is deleted from the backend, How do you check whether all the 10 records were present while updating the data(Which event and steps) and throw the exception. By Using the Transactions we can check the Exact Numbers of the rows to be updated and if the updation fails then the Transaction will be rollbacked. Can dataReader hold data from multiple tables? Data reader can hold data from multiple tables and datareader can hold more than one table. string query="select * from employee; select * from student"; sqlcommand cmd=new sqlcommand(query, connection); sqldatareader dr=cmd.executeReader(); if(dr.hasrows) { dr.read(); gridview1.DataSource=dr; gridview1.Databind(); if(dr.nextresult) { gridview2.datasource=dr; gridview2.databind(); } } dr.colse(); connection.close(); What is different between SqlCommand object and Command Behavior Object? DO.NET Command Object - The Command object is similar to the old ADO command object. It is used to store SQL statements that need to be executed against a data source. The Command object can execute SELECT statements, INSERT, UPDATE, or DELETE statements,
stored procedures, or any other statement understood by the database. What is bubbled event can u pls explain? All heavy controls like grid view,datagrid or datalist,repeater controls cantains the chield controls like button or link button, when we click this button then the event will be raised, that events are handled by parant controls,that is called event bubbling,means event is bubbled from bottom(chield)to up(parant). 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 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 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; To perform asynchronous data access, what must be added to the connection string? Select Correct Answer. 1. BeginExecute=true 2. MultiThreaded=true 3. MultipleActiveResultSets=true 4. Asynchronous=true Correct Answer: 4. Asynchronous=true
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(); 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; It has no such feature.
Difference between SqlCommand and SqlCommandBuilder? a) SQLCommand is used to execute all kind of SQL queries like DML(Insert, update,Delete) & DDL like(Create table, drop table etc) b)SQLCommandBuilder object is used to build & execute SQL (DML) queries like select, insert, update & delete. Why can\'t we use Multiple inheritance and garbage collector paralelly in .net? FYI, .net doesn't support the mutiple inheritance, perhaps you may talk about multi-level inheritance. In the later case, if a class is inherited from another class, at the time of creating instance, it will obviously give a call to its base class constructor (ie bottom - top approach). Like wise the constructor execution is takes place in top down approach (ie. base class constructor is executed and the derived class constructor is executed). So for GC, it will collect only when an object does not have any reference. As we see previously, the derived is constructed based on base class. There is a reference is set to be. Obviously GC cannot be collected. What is ADO.NET? ADO.NET is the primary relational data access model for Microsoft .NET-based applications. It may be used to access data sources for which there is a specific .NET Provider, or, via a .NET Bridge Provider, for which there is a specific OLE DB Provider, ODBC Driver, or JDBC Driver. ADO.NET is sometimes considered an evolution of ADO technology, but it is important to note that some major changes were made between the two. How to find the given query is optimised one or not? First Excute Sql Quries in Query Analzer,see How much time 2 take Excute , if Less then the ur desired Time, then it will Optimize query. How to copy the contents from one table to another table and how to delete the source table in ado.net? It is possible
DataSet ds; sqlAdap.Fill(ds); Datatable dt = ds.Tables[0].copy(); //now the structure and data are copied into 'dt' ds.Tables.remove(ds.Table[0]); //now the source is removed from the 'ds' How to call the SQL commands asynchronously in ADO.NET version 2.0? executescalar() executereader() executenonquery() these comes with Begin and End like Beginexecutescalr() Endexecutescalar().......by using these command we can achieve asynch comm in ado.net What is typed and untyped dataset? A DataSet can be Typed or Untyped. The difference between the two lies in the fact that a Typed DataSet has a schema and an Untyped DataSet does not have one. It should be noted that the Typed Datasets have more support in Visual studio.I loaded the dataset with a table of 10 records. One of the records is deleted from the backend, How do you check whether all the 10 records were present while updating the data(Which event and steps) and throw the exception. By Using the Transactions we can check the Exact Numbers of the rows to be updated and if the updation fails then the Transaction will be rollbacked. Can dataReader hold data from multiple tables? data reader can hold data from multiple tables and datareader can hold more than one table. string query="select * from employee; select * from student"; sqlcommand cmd=new sqlcommand(query, connection); sqldatareader dr=cmd.executeReader(); if(dr.hasrows) { dr.read(); gridview1.DataSource=dr; gridview1.Databind(); if(dr.nextresult) { gridview2.datasource=dr; gridview2.databind(); } } dr.colse(); connection.close(); What's Connection Pooling? Connection pooling is the ability of re-use your connection to the Database.This means if you enable Connection pooling in the connection object, actually you enable the re-use of the connection to more
than one user.The connection pooling is enabled by default in the connection object.If you disable the connection pooling, this means the connection object which you create will not be re-used to any other user than who create that object.
Shall I Enable/Disable Connection pool? Let's do an example to use what the time has required if we enable/disable the connection pool in an application. What is different between SqlCommand object and Command Behaviour Object DO.NET Command Object - The Command object is similar to the old ADO command object.It is used to store SQL statements that need to be executed against a data source.The Command object can execute SELECT statements, INSERT, UPDATE, or DELETE statements,stored procedures, or any other statement understood by the database. CommandBehaviour:Provides a description of the results of the query and its effect on the database. Like, Command cmd=new Command("SQL",conn,CommandBehaviour.CloseConnection); What is bubbled event can u pls explain? All heavy controls like grid view,datagrid or datalist,repeater controls contains the child controls like button or link button, when we click this button then the event will be raised,that events are handled by parant controls,that is called event bubbling,means event is bubbled from bottom(chield)to up(parant). Once data is fetched into dataset connection gets closed. but in datareader connection is always maintained...then why datareader is fast and mainly recommended ? Datareader is forwardonly thus is fast and is mostly used while retrieving the data from the database.
When multiple users attempt to modify data at the same time Ex user 1 is updating record at same.time user2 deleted record sucessfully.now user1 has press update button . how to handle concurrency? Have one column with in Database table with datatype as TimeStamp and while selecting the row we will read the TimeStamp value, which we can compare at the time of updation, if both values are same then we can update that row otherwise we can resist the user from updating saying that someone has updated the row, you can't update it. What is method to get XML and schema from Dataset? // Summary: // Returns the XML representation of the data stored in the System.Data.DataSet. // // Returns: // A string that is a representation of the data stored in the System.Data.DataSet. // Summary: // Returns the XML Schema for the XML representation of the data stored in the
// System.Data.DataSet. // // Returns: // String that is the XML Schema for the XML representation of the data stored // in the System.Data.DataSet. If a table contains 20000 records . In a page at each time 100 records to be displayed. What are the steps u will take to improve performance? will you use dataset or datareader? We have to use a dataset because on using datareader forward only paging can be achieved. Suppose if you are at 1000 page and you want to go back to 999th page, if you use datareader it cannot be achieved, since it does not support backward navigation. Dataset supports forward and backward navigation ADO.NET 2.0 Interview Questions and Answers asked in IBM,Wipro,HP,CTS.ADO .Net Interview Questions and most frequently asked ADO .Net Interview Questions during Interviews Can we connect two data adapters to same data source using single connection at same time? Yes,we can connect two dataadapters to same datasource using single connection at same time. There is a technology in ado.net 2.0 called MARS usinng Mars in connection string we can do it. for eg:cn.ConnectionString = "server=(local); database=employee; integrated security=sspi; MultipleActiveResultSets=True"; Can we do database operations without using any of the ADO.net objects? No its not at all possible.
If we are not returning any records from the database, which method is to be used? There is a method called Execute Non Query. This method executes the Update, Delete etc. This does not return any rows but will give the number of rows affected. How can i retrieve two tables of data at a time by using data reader? Data reader read and forward only, how is it possible to get 2 tables of data at a time yes this is possible If we execute 2 select command either in stored procedure or in select command and then executereader method fired of command object. it return 2 tables in datareader like : string str="Select * from a;select * from b"; cmd.commandtext=str; dr=cmd.executereader(); Now it return 2 tables in datareader (dr).
ExecuteNonQuery? // Summary: // Executes a Transact-SQL statement against the connection and returns the number of rows affected. // Returns: // The number of rows affected. What is the ExecuteScalar method? // Summary: Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. // Returns: The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty.
Which one of the following objects is a high-level abstraction of the Connection and Command objects in ADO.NET? DataReader DataSet DataTable DataView DataAdapter Answer: DataAdapter How can we load multiple tables in to Dataset? DataSet ds=new DataSet(); SqlDataAdapter dap=new SqlDataAdapter(Select * from ,); dap.Fill(ds,"TableOne"); SqlDataAdapter dap1=new SqlDataAdapter(Select * from ,); dap1.Fill(ds,"tableTwo"); connection String - a string which contains address of the database we want to connect to. Delegate - is an important element of C# and is extensively used in every type of .NET application. A delegate is a class whose object (delegate object) can store a set of references to methods. How do you update a Dataset in ADO.Net and How do you update database through Dataset? a. Update a dataset; Dataset ds = new dataset(); SqlDataAdapter adp = new SqlDataAdapter(Query,connection); Adp.fill(ds); Again you can add/update Dataset as below SqlDataAdapter adp1 = new SqlDataAdapter(Query1,connection); Adp1.fill(ds);
b. Update database through dataset. SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter); Foreach(datarow dr in ds.table[0].rows) { Dr[column Name] = value; mySqlDataAdapter.Update(ds); } What are the steps to connect to a database? 1. Create a connection. This requires a connection string, which can be given declaratively or put in a well defined place like the .config files. Advantage of keeping in .config files is that it enables use of Connection Pooling by .Net framework, else even one small change in connection string will cause CLR to think it's not the same connection and will instantiate new connection for other request. 2. Open the connection and keep it open until done, typically done as using (con) { //use } 3. If using connected data model, create a SqlCommand object, decorate it with desired command, command type (stored procedure for eg), add any parameters and their values to the command, and then consume the command by using ExcuteReader or ExecuteScalar. In case of ExecuteReader, we will get back a handle to a fast-forward, read only pointer to the recordset. We can also decorate Command object with multiple recordsets in 2.0 and execute one by one (MARS - Multiple Active Record Sets) 4. If using disconnected data model, create a DataAdapter object, decorate it with desired SELECT, INSERT, UPDATE, DELETE commands, add parameters as necessary and then fill up a DataSet or DataTable using the DataAdapter. Subsequent SQL can be executed using insert, update, delete commands on the dataset. How do you connect to SQL Server Database without using sqlclient? You can connect sql using oledbname space . What is Partial class? A Partial class is a class that can be split into two or more classes. This means that a class can be physically separated into other parts of the class within the same namespace. All the parts must use the partial keyword. All the other classes should also have the same access modifier. At the compile time, all the partial classes will be treated as a single class. Let us list some advantages of having partial classes. What are the advantages and disadvantages of using datalist? Adv: the DataList's display is defined via templates,DataList allows for much more customization of the rendered HTML markup , by which it is more user-friendly displays of data.
DisAdv: adding such functionality with the DataList takes more development time than with the DataGrid, as, 1. The Edit/Update/Cancel buttons that can be created in a DataGrid via the EditCommandColumn column type, must be manually added to the DataList, and 2. The DataGrid BoundColumn column types automatically use a TextBox Web control for the editing interface, whereas with the DataList you must explicitly specify the editing interface for the item being edited via the EditItemTemplate. 3. We can't do the paging and sorting with datalist controls. What is the difference between data reader and data adapter? DateReader is an forward only and read only cursor type if you are accessing data through DataRead it shows the data on the web form/control but you can not perform the paging feature on that record(because it's forward only type). Reader is best fit to show the Data (where no need to work on data) DataAdapter is not only connect with the Databse(through Command object) it provide four types of command (InsertCommand, UpdateCommand, DeleteCommand, SelectCommand), It supports to the disconnected Architecture of .NET show we can populate the records to the DataSet. where as Dataadapter is best fit to work on data. What is the difference between data reader & data set? 1) DataSet is disconnected object type. It uses XML to store data. 2) It fetches all data from the data source at a time 3) Modifications can be updated to the actual database 4) It will reduce the application performance. Does SQLClient and OLEdb class share the same functionality? No, each have its own functionality, ex : for sql client , there is SqlConnection object and for oledb client , there is OleDBConnection What is the namespace in which .NET has the data functionality class? Following are the namespaces provided by .NET for data management:-
System. Data This contains the basic objects used for accessing and storing relational data, such as DataSet,
DataTable, and Data Relation. Each of these is independent of the type of data source and the way we connect to it. System.Data.OleDB It contains the objects that we use to connect to a data source via an OLE-DB provider, such as OleDbConnection, OleDbCommand, etc. These objects inherit from the common base classes, and so have the same properties, methods, and events as the SqlClient equivalents. System.Data.SqlClient: This contains the objects that we use to connect to a data source via the Tabular Data Stream (TDS) interface of Microsoft SQL Server (only). This can generally provide better performance as it removes some of the intermediate layers required by an OLE-DB connection. System.XML This Contains the basic objects required to create, read, store, write, and manipulate XML documents according to W3C recommendations. Can you give an overview of ADO.NET architecture? The most important section in ADO.NET architecture is Data Provider. Data Provider provides access to data source (SQL SERVER, ACCESS, ORACLE).In short it provides object to achieve functionalities like opening and closing connection, retrieve data, and update data. In the below figure, you can see the four main sections of a data provider: Connection Command object (This is the responsible object to use stored procedures) Data Adapter (This object acts as a bridge between data store and dataset) Data reader (This object reads data from data store in forward only mode). Dataset object represents disconnected and cached data. If you see the diagram, it is not in direct connection with the data store (SQL SERVER, ORACLE etc) rather it talks with Data adapter, who is responsible for filling the dataset. Dataset can have one or more Data table and relations. Figure: - 9.1 ADO.NET Architecture Data View object is used to sort and filter data in Data table Note:- This is one of the favorite questions in .NET. Just paste the picture in your mind and during interview try to refer that image. What are the two fundamental objects in ADO.NET? Data reader and Dataset are the two fundamental objects in ADO.NET. What is difference between dataset and data reader? Following are some major differences between dataset and data reader:-
Data Reader provides forward-only and read-only access to data, while the Dataset object can hold more than one table (in other words more than one row set) from the same data source as well as the
Dataset is a disconnected architecture while data reader is connected architecture. Dataset can persist contents while data reader cannot persist contents, they are forward only. What are major difference between classic ADO and ADO.NET? Following are some major differences between both : In ADO we have recordset and in ADO.NET we have dataset. In recordset we can only have one table. If we want to accommodate more than one tables we need to do inner join and fill the recordset. Dataset can have multiple tables. All data persist in XML as compared to classic ADO where data persisted in Binary format also. What is the use of connection object? They are used to connect a data to a Command object. An OleDbConnection object is used with an OLE-DB provider A SqlConnection object uses Tabular Data Services (TDS) with MS SQL Server What is the use of command objects? They are used to connect connection object to Data reader or dataset. Following are the methods provided by command object: ExecuteNonQuery: Executes the command defined in the Command Text property against the connection defined in the Connection property for a query that does not return any row (an UPDATE, DELETE, or INSERT). Returns an Integer indicating the number of rows affected by the query. ExecuteReader: Executes the command defined in the Command Text property against the connection defined in the Connection property. Returns a "reader" object that is connected to the resulting row set within the database, allowing the rows to be retrieved. ExecuteScalar: Executes the command defined in the Command Text property against the connection defined in the Connection property. Returns only single value (effectively the first column of the first row of the resulting row set any other returned columns and rows are discarded. It is fast and efficient when only a "singleton" value is required 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 basic methods of Data adapter? There are three most commonly used methods of Data adapter:Fill: Executes the Select Command to fill the Dataset object with data from the data source. It an also be used to update (refresh) an existing table in a Dataset with changes made to the data in the original data source if there is a primary key in the table in the Dataset. FillSchema :Uses the SelectCommand to extract just the schema for a table from the data source, and creates an empty table in the DataSet object with all the corresponding constraints.Update:- Calls the respective InsertCommand, UpdateCommand, or DeleteCommand for each inserted, updated,or deleted row in the DataSet so as to update the original data source with the changes made to the content of the DataSet. This is a little like the UpdateBatch method provided by the ADO Recordset object, but in the DataSet it can be used to update more than one table. What is Dataset object? The Dataset provides the basis for disconnected storage and manipulation of relational data. We fill it from a data store, work with it while disconnected from that data store, then reconnect and flush changes back to the data store if required. What are the various objects in Dataset? Dataset has a collection of Data Table object within the Tables collection. Each Data Table object contains a collection of Data Row objects and a collection of Data Column objects. There are also collections for the primary keys, constraints, and default values used in this table, which is called as constraint collection, and the parent and child relationships between the tables. Finally, there is a Default View object for each table. This is used to create a Data View object based on the table, so that the data can be searched, filtered, or otherwise manipulated while displaying the data. Note: - Look back again to the main diagram for ADO.NET architecture for visualizing this answer in pictorial form.