Vous êtes sur la page 1sur 13

Ado .

net

what is the namespace in which .net has the data functionality classes?

Ans; system.data.

Can u give a overview of ADO.net architecture?

Ans: ADO.NET provides consistent access to data sources such as Microsoft SQL Server, as well as
data sources exposed through OLE DB and XML. Data-sharing consumer applications can use
ADO.NET to connect to these data sources and retrieve, manipulate, and update data.
The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes found in
System.Xml.dll.

What are the two fundamental objects in ADO.net?

Ans:- The DataTable Select Method - This method is overloaded to accept arguments to filter and
sort data rows returning an array of DataRow objects.
The DataView object sort, filter and find methods - This object uses the same filter arguments
supported by the Select method, but the DataView extrudes structures that can be bound to data-
aware controls.

What is difference between dataset and datareader ?


Ans :- Datasets store data in a disconnected cache. The structure of a dataset is similar to that of
a relational database; it exposes a hierarchical object model of tables, rows, and columns. In
addition, it contains constraints and relationships defined for the dataset.

DataReader - Provides a means of reading a forward-only stream of rows


Results are returned as the query executes, and are stored in the network buffer on the client
until you request them using the Read method of the DataReader. Using the DataReader can
increase application performance both by retrieving data as soon as it is available, rather than
waiting for the entire results of the query to be returned, and (by default) storing only one row at a
time in memory, reducing system overhead.

DataReader is a good choice when retrieving large amounts of data because the data is not
cached in memory

What are major difference between classic ADO and ADO.NET ?


Ans :- ADO uses Recordsets and cursors to access and modify data. Because of its inherent
design, Recordset can impact performance on the server side by tying up valuable resources. In
addition, COM marshalling - an expensive data conversion process - is needed to transmit a
Recordset.

ADO.NET addresses three important needs that ADO doesn't address:

1. Providing a comprehensive disconnected data-access model, which is crucial to the Web


environment
2. Providing tight integration with XML, and
3. Providing seamless integration with the .NET Framework (e.g., compatibility with the base
class library's type system).

From an ADO.NET implementation perspective, the Recordset object in ADO is eliminated in the
.NET architecture. In its place, ADO.NET has several dedicated objects led by the DataSet object
and including the DataAdapter, and DataReader objects to perform specific tasks. In addition,
ADO.NET DataSets operate in disconnected state whereas the ADO RecordSet objects operated
in a fully connected state.

In ADO, the in-memory representation of data is the recordset. In ADO.NET, it is the dataset.

What is the use of connection object ?


Ans :- The ADO Connection Object is used to create an open connection to a data source.
Through this connection, you can access and manipulate a database.

If you want to access a database multiple times, you should establish a connection using the
Connection object. You can also make a connection to a database by passing a connection string
via a Command or Recordset object. However, this type of connection is only good for one
specific, single query.

What is the use of command objects and what are the methods provided by the command
object ?
ANs :- The ADO Command object is used to execute a single query against a database. The
query can perform actions like creating, adding, retrieving, deleting or updating records.

If the query is used to retrieve data, the data will be returned as a RecordSet object. This means
that the retrieved data can be manipulated by properties, collections, methods, and events of the
Recordset object.

The major feature of the Command object is the ability to use stored queries and procedures with
parameters.

The methods of Command Objects are,


i) Cancel - Cancels an execution of a method
ii) CreateParameter - Creates a new Parameter object
iii) Execute - Executes the query, SQL statement or procedure in the CommandText property

What is the use of dataadapter ?


Ans :- A data adapter is the component that exists between the local repository (dataset) and the
physical database. It contains the four different commands (SELECT, INSERT, UPDATE and
DELETE). It uses these commands to fetch the data from the DB and fill into the dataset and to
perform updates done in the dataset to the physical database. It is the data adapter that is
responsible for opening and closing the database connection and communicates with the dataset.

What are basic methods of Dataadapter ?


Ans :- A DataAdapter is the object that bridges between the source data and the dataset object so
retrieve and updates can occur.

DataAdapter have following properties,

i) AcceptChangeDuringFill :- (read/write) a value indicating whether AcceptChanges is called on a


DataRow after it is added to the DataTable.
ii) TableMappings :- (read) a collection that provides the master mapping between a source table
and a DataTable.

Methods,

i) Fill - adds or refreshes rows in DataSet to match those in datasource using the DataSet name,
and create DataTable named "Table".
ii) FillSchema - adds a DataTable named "Table" to the specified DataSet and configures the
schema to match that in the data source based on the specified SchemaType.
iii) GetFillParameters - retrieves the parameters set by the user when executing a SQL select
statement.
iv) Update - Calls the respective insert, update or delete statements for respective action in the
specified DataSet from a DataTable named "Table".

What is Dataset object?


Ans :- A dataset is the local repository of the data used to store the tables and disconnected
record set. When using disconnected architecture, all the updates are made locally to dataset and
then the updates are performed to the database as a batch.

What are the various objects in Dataset ?


Ans :- DataSet objects are in-memory representations of data. They contain multiple DataTable
objects, which contain columns and rows, just like normal data base tables. You can even define
relations between tables to create parent-child relationships. The DataSet is specifically designed
to help manage data in memory and to support disconnected operations on data, when such a
scenario make sense. The DataSet is an object that is used by all of the Data Providers, which is
why it does not have a Data Provider specific prefix.

How do we connect to SQL SERVER , which namespace do we use ?


Ans :- system.data.sqlclient
dim con as sqlconnection(uname=sa pwd="" database=ddd)

How do we use stored procedure in ADO.NET and how do we provide parameters to the stored
procedures?
Ans :- Create a command object (SqlCommand, etc) and specify the stored procedure name
Set the CommandType property of the command object to the CommandType.StoredProcedure
enumeration value. This tells the runtime that the command used here is a stored procedure.

SqlCommand insertCommand = new SqlCommand("InsertProc", conn);


insertCommand.CommandType = CommandType.StoredProcedure;
dataAdapter.InsertCommand = insertCommand;
insertCommand.UpdatedRowSource = UpdateRowSource.None;

Which is the best place to store connectionstring in .NET projects ?


Ans :- The Web.config file might be a good place. In the system.configuration
namespace, you can find the appropriate methods to access this file in you
application.

What are steps involved to fill a dataset ?(Twist :- How can we use dataadapter to fill a dataset ?)
Ans:- Defining the connection string for the database server
Defining the connection (SqlConnection, OleDbConnection, etc) to the database using the
connection string
Defining the command (SqlCommand, OleDbCommand, etc) or command string that contains the
query
Defining the data adapter (SqlDataAdapter, OleDbDataAdapter, etc) using the command string
and the connection object
Creating a new DataSet object
If the command is SELECT, filling the dataset object with the result of the query through the data
adapter
Reading the records from the DataTables in the datasets using the DataRow and DataColumn
objects
If the command is UPDATE, INSERT or DELETE, then updating the dataset through the data
adapter
Accepting to save the changes in the dataset to the database
SqlDataAdapter objDataAdapter = new SqlDataAdapter ("Select
CompanyName, ContactName, City, Country, Region from
Suppliers", objConnect);

DataSet objDS = new DataSet();

objDataAdapter.Fill (objDS);

What are the various methods provided by the dataset object to generate XML?
Ans:- The DataSet is capable of reading and writing its data and schema as XML. This is
important if you consider that XML is an open, industry standard that is popular among most
software solutions providers. At this time, XML is pervasive - found both in Internet solutions and
in traditional applications. The fact that it is designed to both contain and describe data (data that
describes itself) makes it the perfect choice for a universal data container such as the DataSet.
Furthermore, the ability of a DataSet to both read and write data and schema as XML makes it
possible for you to both create and modify data in a DataSet using XML or XML enabled solution,
such as SQL Server 2000 and VFP. The methods for reading XML into a DataSet have, of course,
complimentary means of writing XML from a DataSet: WriteXml and WriteXmlSchema. Two
additional methods provided are: GetXml and GetXmlSchema. These methods return the data or
schema as a string.

How can we save all data from dataset ?


Ans:- DataTable dt = ds.Tables["Article"];
dt.Rows[2]["lines"] = 600;

da.Update(ds, "Article");

Here ‘da’ and ‘ds’ are the references of the DataAdapter and DataSet objects respectively.

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? How do we get changed value dataset?)

For tracking down changes Dataset has two methods which comes as rescue
“GetChanges“ and “HasChanges”.
1.GetChanges
Return’s dataset which are changed since it was loaded or since Acceptchanges was
executed.
2.HasChanges
This property indicate’s has any change’s been made since the dataset was loaded or
acceptchanges method was executed.
If we want to revert or abandon all change’s since the dataset was loaded use
“RejectChanges”.

How can we add/remove row’s in “DataTable” object of “DataSet” ?


“Datatable” provides “NewRow” method to add new row to “DataTable”.”DataTable”
has “DataRowCollection” object which has all rows in a “DataTable” object.
Following are the methods provided by “DataRowCollection” object :-
1.Add
Add’s a new row in DataTable
2.Remove
Remove’s a “DataRow” object from “DataTable”
3.RemoveAt
Remove’s a “DataRow” object from “DataTable” depending on index position of the
“DataTable”.
What’s basic use of “DataView” ?

“DataView” represent’s a complete table or can be small section of row’s depending on


some criteria.It’s best used for sorting and finding data with in “datatable”.
Dataview has the following method’s :-
1.Find
Take’s a array of value’s and return’s the index of the row.
2.FindRow
This also takes array of values but returns a collection of “DataRow”.
If we want to manipulate data of “DataTable” object create “DataView” (Using the
“DefaultView” we can create “DataView” object) of the “DataTable” object. and use
the following functionalities :-
3.AddNew
Add’s a new row to the “DataView” object.
4.Delete
Deletes the specified row from “DataView” object.

What’s difference between “DataSet” and “DataReader”?

Dataset
1)It is disconnected with database
2)It is both readonly and forward only

DataReader
1)It is connected with database
2)It is forward only

Following are the major difference between “DataSet” and “DataReader” :-


1. “DataSet” is a disconnected architecture , while “DataReader” has live
connection while reading data.So if we want to cache data and pass to a
different tier “DataSet” forms the best choice and it has decent XML support.
2.When application needs to access data from more than one table “DataSet”
forms the best choice.
3.If we need to move back while reading record’s , “datareader” does not support
this functionality.
4.But one of the biggest drawbacks of DataSet is speed.As “DataSet” carry
considerable overhead because of relations,multiple tables etc speed is slower
than “DataReader”.Always try to use “DataReader” whereever possible. , as
it’s meant specially for speed performance.

How can we load multiple tables in a DataSet ?


You can use the same dataadapter and a dataset and use the different table name and pass
different sql query to load the dataset with different tables.
ds.Tables.Add(dt);

where ds is a DataSet and dt is a datatable.

How can we add relations between tables in a dataset?

In a DataSet with multiple DataTable objects, you can use DataRelation objects to relate one table
to another, to navigate through the tables, and to return child or parent rows from a related table.
The arguments required to create a DataRelation are a name for the DataRelation being created,
and an array of one or more DataColumn references to the columns that serve as the parent and
child columns in the relationship. After you have created a DataRelation, you can use it to navigate
between tables and to retrieve values.

Adding a DataRelation to a DataSet adds, by default, a UniqueConstraint to the parent table and
a ForeignKeyConstraint to the child table. For more information about these default constraints, see
Adding Constraints to a Table.

The following code example creates a DataRelation using two DataTable objects in a DataSet.
Each DataTable contains a column named CustID, which serves as a link between the two
DataTable objects. The example adds a single DataRelation to the Relations collection of the
DataSet. The first argument in the example specifies the name of the DataRelation being created.
The second argument sets the parent DataColumn and the third argument sets the child
DataColumn.

Whats the use of command builder?

What the CommandBuilder can do is relieve you of the responsibility of writing your own action
queries by automatically constructing the SQL code, ADO.NET Command objects, and their
associated Parameters collections given a SelectCommand. Cool. And it works, but only in a very
limited way, and for a price, as I'll describe in this article. And unlike the DACW, the code and
commands created by the CommandBuilder are unseen—in another black box.

What is the difference between optimistic locking 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 user’s 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 browser based application 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 DataAdapter 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 Datetime 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 is
the best practice used by industries for locking.
Update table1 set field1=@test where
LastTimeStamp=@CurrentTimeStamp

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.

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 one or
more command 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.


.net Framework questions
What is IL? (Twist: - What is MSIL or CIL, What is JIT?)
The life cycle of a .NET program starts when the compiler translates the source code into
Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that
can be efficiently converted to native code. When we execute the code, MSIL is converted to
CPU-specific code, which is done by a just-in-time (JIT) compiler. Because the common
language runtime supplies one or more JIT compilers, the same set of MSIL can be JIT-compiled
and executed on any supported architecture.

What is CLR?

Common Language Runtime (CLR) manages the execution of code and provides
different services like Garbage collection and support for Base Class Libraries etc.
The main constituents of CLR are described below

The common Language Runtime (CLR) a rich set of features for cross-language
development and deployment. CLR supports both Object Oriented Languages as
well as procedural languages. CLR provides security, garbage collection, cross
language exception handling, cross language inheritance and so on.

The Common Type System, support both Object Oriented Programming


languages as well as procedural languages. Basically CTS provides rich type
system that is intended to support wide range of languages.

CLS (Common Language Specification) defines a subset of Common Type


System, which all language compilers targeting CLR must adhere to. CLS is a
subset of CTS.

All compilers under .NET will generate Intermediate Language no matter what
language is used to develop an application. In fact, CLR will not be aware of the
language used to develop an application. All language compilers will generate a
uniform, common language called Intermediate Language. For this reason IL can
be called as The language of CLR A platform for cross language
development.

What is CLS?

It provides the set of specificaiton which has to be adhered by any new language
writer / Compiler writer for .NET Framework. This ensures Interoperability. For
example: Within a ASP.NET application written in C#.NET language, we can refer to
any DLL written in any other language supported by .NET Framework. As of now
.NET Supports around 32 languages.

What is manage code ?


Managed code: A code that is managed by CLR is know as
Manged code for example C#,j#,Vb.Net etc

Unmanged code: A code that is not managed by CLR is known

as Unmanaged by unmanaged code. for example c++, java, c etc

what is Assembly?

Assemblies are the building blocks of .NET Framework applications; they form the fundamental
unit of deployment, version control, reuse, activation scoping, and security permissions. An
assembly is a collection of types and resources that are built to work together and form a logical
unit of functionality. An assembly provides the common language runtime with the information
it needs to be aware of type implementations. To the runtime, a type does not exist outside the
context of an assembly.

What are the different type of assemblies?

Assemblies are the building blocks of .NET Framework applications.

Public assembly- are the dll/exe file that can be used in different application. The main advantage
of public assemblies is code reusability.

Private assembly -is the assembly used inside the application

Shared assembly- to run multiple versions of an application or component on the same computer.

Satellite assembly -used for multi-cultural application in .NET

What is Namespace?
Namespace is a group of classes, structures, interfaces, enumerations, and delegates,
organized in a logical hierarchy by function, that enable you to access the core
functionality you need in your applications.

what is the Difference between Namespace and Assembly ?

Namespace:
1) it is a Collection of names wherein each name is Unique.
2)They form the logical boundary for a Group of classes.
3)Namespace must be specified in Project-Properties.

Assembly:
1) It is an Output Unit.
2)It is a unit of Deployment & a unit of versioning.
3)Assemblies contain MSIL code.
4)Assemblies are Self-Describing. [e.g. metadata,manifest]
5)An assembly is the primary building block of a .NET Framework application.
6)It is a collection of functionality that is built, versioned, and deployed as a single implementation
unit (as one or more files).
7)All managed types and resources are marked either as accessible only within their
implementation unit, or by code outside that unit
What is manifest?
Assembly metadata is stored in Manifest.Manifest contains all the metadata needed to do the
following things
1.Version of assembly
2.Security identity
3.Scope of the assembly
4.resolve references to resources and classes.
5The assembly manifest can be stored in either a PE file (an .exe or .dll) with
Microsoft intermediate language (MSIL) code or in a stand-alone PE file that
contains only assembly manifest information.
Strong name is similar to GUID(It is supposed to be unique in space and time) in COM
components.Strong Name is only needed when we need to deploy assembly in GAC.Strong
Names helps GAC to differentiate between two versions.Strong names use public key
cryptography(PKC) to ensure that no one can spoof it.

If you want to view a assembly how t o you go about it (Twist : what is ILDASM?)?
Ildasm basically converts the whole exe or Dll in tit IL code . to Run ILDASM you hav to go to
C:\program files\ Microsoft visual studio.net 2003\sdk\v1.1\bin.

What is the concept of Strongnames?


A strong name consists of the assembly's identity — its simple text name, version number, and
culture information (if provided) — plus a public key and a digital signature. It is generated
from an assembly file (the file that contains the assembly manifest, which in turn contains the
names and hashes of all the files that make up the assembly), using the corresponding private
key

How to add and remove assembly from GAC?

The gacutil.exe that ships with .NET can be used to add or remove a shared
assembly from the GAC.

To add a shared assembly, from the command line enter:

gacutil.exe /i myassembly.dll

To remove a shared assembly, from the command line enter:

gacutil.exe /u myassembly.dll

what is delay signing?

When we talk about the Assembly then the first thing comes into our mind is the
security for high level development. Delayed signing is the terminology when we are
certifying the assembly which will prevent hi-jacking of that assembly.

Delayed signing refers to a technique of partially signing assemblies while they are in
development phase. So, signing an assembly basically certifies that assembly by the
manufacturer and prevents tampering and hi-jacking of that assembly. This is
achievable by using public key/private key encoding of parts of the assembly. The
public key is embedded in the assembly and will be used by third-parties who want
to reference the assembly. There are many more benefits to signing an assembly,
but the main purpose of delayed signing is to allow a company to protect and control
its private key and only use it during the packaging process. A delayed signed
assembly can still be used like a signed assembly, you just can't package and ship it.

Steps to certify the Assembly:-

Delays sign a .NET app:

sn -k keypair.snk

1. sn -p keypair.snk public.snk
2. Build assembly with:
[assembly: AssemblyDelaySign("false")]
[assembly: AssemblyKeyFile("..\\..\\keypair.snk")]
3. sn -Vr AssemblyName.dll
4. This step is critical and is not mentioned anywhere. Exit and restart every
instance of VisualStudio running. Until you do this Visual Studio will not know
of the sn -Vr from step 4 and you will get
"COM Interop registration failed. The check of the signature failed for
assembly AssemblyName.dll"

What is garbage collection?


The .NET garbage collector provides a high-speed allocation service with good use of memory and
no long-term fragmentation problems. This article explains how garbage collectors work, then goes
on to discuss some of the performance problems that might be encountered in a garbage-collected
environment.

Can we force garbage collector to run?


Yes we can force garbage collection by invoking the (GC.Collect) method from the program.
This is not advisable and should be used only in extreme cases.

What is reflection?
Refelction is the mechanism of discovering class information solely at run
time.Wondering where it would be useful? Imagine,you are in visual studio IDE
(Integrated devolopment environment) and as you type "object." you would see all
the methods,properties and events associated with that object.An other example
would be an Object browser.

What are the different type of jit?

Types of jit : prejit,ecno jit,normal jit

pre jit : convert source code to native code in single completion of cycle.Normally
this can be done at the time of deployment.

econo jit : coverts the only called methods to native code,however it can be removed
when are not required.

normal jit : compliled the called methods to native code.In the the methods can be
compiles for the first time.For latter calls it can be displayed using cached items.

What are value types and reference types?


A data type is a value type if it holds the data within its own memory allocation. A reference type
contains a pointer to another memory location that holds the data.

Value types
Value types include the following:

• All numeric data types

• Boolean, Char, and Date

• All structures, even if their members are reference types

• Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte,

UShort, UInteger, or ULong

Reference Types

Reference types include the following:

• String

• All arrays, even if their elements are value types

• Class types, such as Form

• Delegates

What is the concept of boxing and unboxing?

Boxing:
means converting value-type to reference-type.
Eg:
int I = 20;
string s = I.ToSting();

UnBoxing:
means converting reference-type to value-type.
Eg:
int I = 20;
string s = I.ToString(); //Box the int
int J = Convert.ToInt32(s); //UnBox it back to an int.

Note:

Performance Overheads due to boxing and unboxing as the boxing makes a copy of
value type from stack and place it inside an object of type System.Object in the heap.

What is the difference between VB.net and C3.net?


VB.NET
1)no unsigned int
2)Loosely typed language
3)no operator overloading
4)no pointers
5)no auto XML documentation
6)no automatic memory management

C#.net

1) supports unsigned int


2)strongly typed language
3)supports operator overloading
4)supports pointers
5)supports auto XML documentation
6)supports automatic memory
management

What’s difference between system exception and application exception?

There r 2 important classes in the hierarchy that r derived from System.Exception:


1) System.SystemException -> This class is for exceptions that r usually thrown by the .net
runtime, or which r considered to be of a generic nature and must be thrown by almost any
application. For example, StackOverflowException will be thrown by the .net runtime if it detects
the stack is full. On the other hand, u might choose to throw ArgumentException or it’s subclasses
in ur code, if u detect that a method has been called with inappropriate arguments. Subclasses of
System.SystemException includes classes that represent both fatal and non-fatal errors.
2) System.ApplicationException-> This class is important, becoz it is the intended base for any
class of exception defined by third parties. Hence, if u define any exceptions covering error
conditions unique to ur application, u should derive these directly or indirectly from
System.ApplicationException

What is code access security?

Code Access Security Policy Tool - caspol.exe


The Code Access Security Policy tool enables users and administrators to modify security
policy for the machine policy level, the user policy level and the enterprise policy level.
Please refer to the MSDN documentation for additional information.

Vous aimerez peut-être aussi