Sei sulla pagina 1di 23

Page Life Cycle:

Page request

The page request occurs before the page life cycle begins. When the page is
requested by a user, ASP.NET determines whether the page needs to be parsed
and compiled or whether a cached version of the page can be sent in response
without running the page.

Start

In the start step, page properties such as Request and Response are set. At this
stage, the page also determines whether the request is a postback or a new
request and sets the IsPostBack property.

Page
initialization

During page initialization, controls on the page are available and each control's
Unique ID property is set...

Load

During load, if the current request is a postback, control properties are loaded with
information recovered from view state and control state.

Validation

During validation, the Validate method of all validator controls is called, which sets
the IsValid property of individual validator controls and of the page.

Postback event If the request is a postback, any event handlers are called.
handling
Rendering

Before rendering, view state is saved for the page and all controls. During the
rendering phase, the page calls the Render method for each control, providing a
text writer that writes its output to the OutputStream of the page's Response
property.

Unload

Unload is called after the page has been fully rendered, sent to the client, and is
ready to be discarded. At this point, page properties such as Response and
Request are unloaded and any cleanup is performed.

Page Life Cycle Event:


Page Event

Typical Use

PreInit

Use this event for the following:

Check the IsPostBack property to determine whether this is the first


time the page is being processed.

Create or re-create dynamic controls.

Set a master page dynamically.

Read or set profile property values.

Init

Raised after all controls have been initialized. Use this event to read or
initialize control properties.

InitComplete

Use this event for processing tasks that require all initialization be complete.

PreLoad

Use this event if you need to perform processing on your page or control
before the Load event.
Before the Page instance raises this event, it loads view state for itself and all
controls, and then processes any postback data included with the Request
instance.

Load

The Page calls the OnLoad event method on the Page, then recursively does
the same for each child control, which does the same for each of its child
controls until the page and all controls are loaded.
Use the OnLoad event method to set properties in controls and establish
database connections.

Control events

Use these events to handle specific control events, such as a Button control's
Click event or a TextBox control's TextChanged event.
In a postback request, if the page contains validator controls, check the
IsValid property of the Page and of individual validation controls before
performing any processing.

LoadComplete

Use this event for tasks that require that all other controls on the page be
loaded.

PreRender

Before this event occurs:

The Page object calls EnsureChildControls for each control and for
the page.

Each data bound control whose DataSourceID property is set calls


its DataBind method. For more information, see Data Binding Events for
Data-Bound Controls later in this topic.

The PreRender event occurs for each control on the page. Use the event to
make final changes to the contents of the page or its controls.
SaveStateComplete Before this event occurs, ViewState has been saved for the page and for all
controls. Any changes to the page or controls at this point will be ignored.
Use this event perform tasks that require view state to be saved, but that do
not make any changes to controls.
Render

This is not an event; instead, at this stage of processing, the Page object calls
this method on each control.

Unload

This event occurs for each control and then for the page.

Page Life cycle Event in Dotnet 2.0


1. PreInit
2. Init
3. InitComplete
4. PreLoad
5. Load
6. LoadComplete
7. PreRender

8. PreRenderComplete
9. Unload
Page Life cycle Event in Dotnet 1.1
1. Init
2. Load
3. PreRender
4. Unload

Difference between Class and structure:


1. Classes are reference types and structs are value types. Since classes are reference type, a
class variable can be assigned null. But we cannot assign null to a struct variable, since
structs are value type.
2. When you instantiate a class, it will be allocated on the heap. When you
instantiate a struct, it gets created on the stack.
3. Classes can have explicit parameter less constructors. But structs cannot have
explicit parameter less constructors.
4. Classes must be instantiated using the new operator. But structs can be
instantiated without using the new operator.
5. Classes support inheritance. But there is no inheritance for structs.

Abstract Class:
An abstract class is a special kind of class whose object cannot be created. It only allows other
classes to inherit from it but cannot be instantiated. The advantage is that it forces certain hierarchies
for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on
the same hierarchies or standards.

Interface:
An interface has no implementation; it has only the definition of the methods without the body. It is a
contract that is used to define hierarchies for all subclasses or it defines specific set of methods and
their arguments.

Difference between Interface and Abstract class:


The main difference between them is that
1. A class can implement more than one interface but can only inherit from one abstract class.
2. Abstract class that might have one or more completed methods but at least one or more
methods are left uncompleted and declared abstract.
3. An interface cannot have access modifiers for the subs, functions, properties etc everything is
assumed as public but in abstract class have.
4. Interface speed is slower than abstract class because it requires more time to find the actual
method in the corresponding classes.
5. An abstract class can have fields and constants defined but in interface it is not allowed

Server.Transfer Vs Respose.Redirect:
1. Response. Redirect sends message to the browser saying it to move to some different page
while Server.transfer does not send any message to the browser but rather redirects the user
directly from the server itself. So client URL still remains the existing the URL. So in
Server.transfer there is no round trip while Response.redirect has a round trip hence puts a
load on the server

2. Using Sever.transfer you cannot redirect to a different server (Another website) while using
Response.redirect you can redirect to a different server also.
3. With Server.transfer you can preserve your information. It has a parameter called as
"preserve form, so the existing query string etc will be available in the calling page. This is
not possible in Response.redirect.
The Server.Transfer method also has a second parameter "preserve Form". If you set this to True,
using a statement such as Server.Transfer ("WebForm2.aspx", True), the existing query string and
any form variables will still be available to the page you are transferring to. If your WebForm1.aspx
has a Textbox control called TextBox1 and you transferred to WebForm2.aspx with the preserve
Form parameter set to true, you'd be able to retrieve the value of the original page Textbox control by
referencing Request. Form ("TextBox1").

Difference between String and string:


String is a class while string is a keyword. string is nothing but alias of String class.

Difference between String.Empty and Blank string:


The difference between string.Empty and is very small. String.empty will not create any object while
will create a new object in the memory for the checking. Hence string.empty is better in memory
management.

Difference between Convert.ToString() and Blank ToString():


The basic difference between them is Convert function handles NULLS while i.ToString()
does not it will throw a NULL reference exception error. So as good coding practice using
convert is always safe.

App_code folder:
The App_Code folder is meant to store your classes .wsdl files and typed datasets. Any of these items
stored in this folder are then automatically available to all the pages within your solution. The good
thing about the App_Code folder is that when you place something inside this folder VS 2005
automatically detects this and compiles it if it is a class automatically creates your XML Web
Serviceproxy classes or automatically creates a typed dataset for you from your .xsd files. After the
files are automatically compiled these items are then instantaneously available to any of your
ASP.NET pages that are in the same solution. App_Code directory contains reusable classes while
compiling the project all the classes create one dll at runtime that is accessed by websites if
necessary

Boxing and Unboxing:


C# data types are divided into value types, which are allocated on the stack, and reference types,
which are allocated on the heap.
Boxing is the term used to describe the transformation of a value type to a reference type. This
conversion can occur implicitly but we can also perform it manually.
int myIntNumber = 20;
object myObject = myIntNumber;
Unboxing is the term used to describe the reverse process, where the value of a previously boxed
value type is cast back to a value type. We use the term cast here, because this has to be done
explicitly. The syntax is similar to explicit type conversions already described:
int myIntNumber = 20;
object myObject = myIntNumber; // Box the int
int mySecondNumber = (int)myObject; // Unbox it back into an int

Sealed Classes:
Sealed class cannot be inherited. Use the sealed modifier in a class declaration to prevent inheritance
of the class. It is not permitted to use the abstract modifier with a sealed class. Structs are implicitly
sealed; therefore, they cannot be inherited.

Static Classes:
A class can be declared static, indicating that it contains only static members. It
is not possible to create instances of a static class using the new keyword. Static
classes are loaded automatically by the .NET Framework common language
runtime (CLR) when the program or namespace containing the class is loaded.
The main features of a static class are:

They only contain static members.

They cannot be instantiated.

They are sealed.

They cannot contain Instance Constructors (C# Programming Guide).

Creating a static class is therefore much the same as creating a class that
contains only static members and a private constructor. A private constructor
prevents the class from being instantiated.
Static classes are sealed and therefore cannot be inherited. Static classes cannot
contain a constructor, although it is still possible to declare a static constructor
to assign initial values or set up some static state.
State Management
View State:
We can store custom object into view state by converting it into a stream of bytes. This process is
called serialization. To make objects serializable, we need to add a <Serializable> attribute before
your class declaration. The limitation of view state is that if user navigates from one page to other data
will be loosed.
Cross-Page Posting:
The cross-page posting is done by PsotBackUrl property which is defined by the IButtonControl
interface .To use cross-posting, you simply set PostBackUrl to the name of another web form. When
the user clicks the button, the page will be posted to that new URL with the values from all the input
controls on the current page. In new page we can interact with previous page by the
Page.PreviousPage property.
By default, ASP.NET submits a form to the same page. In cross-page posting, the form is submitted to
a different page. This is done by setting the PostBackUrl property of the button(that causes postback)
to the desired page. In the code-behind of the page to which the form has been posted, use the
FindControl method of the PreviousPage property to reference the data of the control in the first
page
Query String:
With the help of query string we can transfer data from page to another page by adding information
with the URL. We can pass the parameters also.
Cookies:
Cookies provide a way by which we can store information for later use. Cookies are small files that
are created on the clients hard drive. The main drawback is that theyre easily accessible and
readable if the user finds and opens the corresponding file. Some users disable cookies on their
browsers, which will cause problems for web applications that require them.
Difference between View State Session and cashing:

Viewstate is used to store value for the current page only. Viewstate are valid for serializable data
only. Moreover Viewstate are not secured as data is exposed to client. Having a large ViewState will
cause a page to download slowly from the users side. Viewstate stores the state of controls in HTML
hidden fields. At times, this information can grow in size. This does affect the overall responsiveness
of the page, thereby affecting performance. The ideal size of a viewstate should be not more than 2530% of the page size.Viewstate can be compressed to almost 50% of its size.
Session saves value till the browser is not closed. This is user specific data that is stored in server
memory. Session state is valid for any type of data. Values stored in the session are available across
different pages in an application. It provides more security then others.
Cache also stored the value till the browser exists but when the system resource goes low then the
items in the cache are dropped directly.
The session object is used to maintain the session of each user. If one user enters in to the
application then they get session id if he leaves from the application then the session id is deleted. If
they again enter in to the application they get different session id. Session state is a state which is
maintained as a per-client basis. While application state allows you to store global objects that can
be accessed by any client.

Mutable type and Immutable type


Immutable type is types whose instance data, fields and properties, does not change after the
instance is created. Most value types are immutable, but the mutable type is a type whose instance
data, fields and properties, can be changed after the instance is created. Most Reference Types are
mutable.
String is an immutable type while StringBuilder is a mutable type

Control doesnt having events:


These are the fallowing controls which have no event
1. DirectoryEntry
2. DirectorySearcher
3. FolderBrowserDialog
4. HelpProvider
5. ImageList

Dotnet 2.0 Vs Dotnet 3.0:


The .NET Framework 3.0 is a superset of the .NET Framework 2.0.It is combination of .NET
Framework 2.0 components with new technologies. In addition to the .NET Framework 2.0, it includes
Windows Presentation Foundation (WPF), Windows Workflow Foundation (WF), Windows
Communication Foundation (WCF), and Windows CardSpace. The structure of the .NET Framework
3.0:

Exception handling:
1. The execution flow first enters the try block.
2. If no errors occur in the try block, execution proceeds normally through the block, and when
the end of the try block is reached, the flow of execution jumps to the finally block if one is
present; either error occurred or not(Step 5). However, if an error does occur within the try
block, execution jumps to a catch block (next step).
3. The error condition is handled in the catch block.
4. At the end of the catch block, execution automatically transfers to the finally block if one is
present.
5. The finally block is executed (if present).

Difference between == and Equal


a == b is used to compare the references of two objects a.Equals(b) is used to compare
two objects

Marshalling
Marshalling is a process of transforming or serializing data from one application domain and exporting
it to another application domain. There are two types of marshalling.
Marshal by value: a copy of an object is created by the server and is passed and used by
the client.
Marshal by reference: the client creates a proxy to access the object.

Session state management in ASP.NET


Types of sessions:

InProc: The default way to use sessions. InProc is the fastest way to store and access
sessions.
OutProc:
i. State server: 15% slower than InProc. Session is serialized and stored in aspnet_state.exe
process. Stateserver sessions can be stored on a separate machine too.
ii. SQL Server: 25% slower than InProc. Used when data is to be serialized and stored in SQL
Server database.

In-Process state management:

The In-Process type of Session state management stores the session in memory on the web
server.
In order to have a user always reconnect to the same web-server, a sticky server is needed.

Out-of-Process state management:

Out-of-Process Session state management stores data in an external data source.


The external data source may be a SQL Server or a State Server service.

Out-of-Process state management requires the objects in a session to be serializable..

If we rate these modes according to performance then the ranks would be


1. InProc
2. StateServer
3. SQLServer
But if we rate the same from reliability perspective then the ranks would be
1. SQLServer
2. StateServer
3. InProc

Property
But C# provides a built in mechanism called properties which provides SET and GET to access the
data fields

<acces_modifier><return_type><property_name>
{
get
{
}
set
{
}
}
We can have a static property for which we dont need to create the object of class.
A Base class property can be polymorphically overridden in a Derived class. But remember that the
modifiers like virtual, override etc are using at property level, not at accessor level.
A property inside a class can be declared as abstract by using the keyword abstract. Remember that
an abstract property in a class carries no code at all. The get/set accessors are simply represented
with a semicolon

Generic
Generics are used to make the code much more reusable. They are a type of data structure that
contains code that remains the same; however, the data type of the parameters can change with each
use. Additionally, the usage within the data structure adapts to the different data type of the passed
variables. In summary, a generic is a code template that can be applied to use the same code
repeatedly. Each time the generic is used, it can be customized for different data types without
needing to rewrite any of the internal code.
A generic is defined using a slightly different notation. The following is the basic code for a generic
named Compare that can compare two items of the same type and return the larger or smaller value,
depending on which method is called:
public class Compare<ItemType, ItemType>
{
public ItemType Larger(ItemType data, ItemType data2)
{
// logic...
}
public ItemType Smaller(ItemType data, ItemType data2)
{
// logic...
}
}
This generic could be used with any data type, ranging from basic data types such as integers to
complex classes and structures. When you use the generic, you identify what data type you are using
with it. For example, to use an integer with the previous Compare generic, you would enter code
similar to the following:
Compare<int, int> compare = new Compare<int, int>;
int MyInt = compare.Larger(3, 5);

Out and Ref

The out and the ref parameters are used to return values in the same variables, that you pass an an
argument of a method. These both parameters are very useful when your method needs to return
more than one values.
In this article, I will explain how do you use these parameters in your C# applications.

The out Parameter


The out parameter can be used to return the values in the same variable passed as a parameter of
the method. Any changes made to the parameter will be reflected in the variable.
public class mathClass
{
public static int TestOut(out int iVal1, out int iVal2)
{
iVal1 = 10;
iVal2 = 20;
return 0;
}
public static void Main()
{
int i, j; // variable need not be initialized
Console.WriteLine(TestOut(out i, out j));
Console.WriteLine(i);
Console.WriteLine(j);
}}

The ref parameter


The ref keyword on a method parameter causes a method to refer to the same variable that was
passed as an input parameter for the same method. If you do any changes to the variable, they will be
reflected in the variable.
You can even use ref for more than one method parameters.
namespace TestRefP
{ using System;
public class myClass
{
public static void RefTest(ref int iVal1 )
{
iVal1 += 2;
}
public static void Main()
{ int i; // variable need to be initialized
i = 3;
RefTest(ref i );
Console.WriteLine(i);
} }}
When we pass a parameter as ref to a method, the method refers to the same variable and changes
made will affect the actual variable.Even the variable passed as out parameter is similar to ref, but
there are few implementation differences when you use it in C# .
Argument passed as ref must be initialized before it is passed to the method, where as in case of out
its is not necessary,but after a call to the method as an out parameter the variable must be initialized.
When to use ref and out parameter: out parameter can be used when we want to return more than
one value from a method.

Difference between Out and Ref

The out keyword causes arguments to be passed by reference. This is similar to the ref keyword,
except that ref requires that the variable be initialized before being passed.
This means inside your method implementation which takes an out parameter you have to set a value
before you can use it. At least you have to assign a value before you can return.
This also means you can not use the out parameter to pass a value to the method. (With ref you can)
The ref and out keywords are treated differently at run-time, but they are treated the same at compile
time. Therefore methods cannot be overloaded if one method takes a ref argument and the other
takes an out argument.

Object Oriented Programming


Object Oriented Programming is a problem solving technique to develop software systems. It is a
technique to think real world in terms of objects. Object maps the software model to real world
concept. These objects have responsibilities and provide services to application or other objects.

Class:
A class is a blue print for object. A class describes all the attributes of objects, as well as the methods
that implement the behaviour of member objects

Object:
It is a basic unit of a system. Objects are members of a class. Attributes and behaviour of an object
are defined by the class definition.

Characteristics or property of Object Oriented Systems:


Abstraction It allows complex real world to be represented in simplified manner. Example colour
is abstracted to RGB. By just making the combination of these three colours we can achieve any
colour in world. Its a model of real world or concept.

Encapsulation It is a process of hiding all the internal details of an object from the outside
world.

Polymorphism It refers One name multiple forms. This can be achieved by overloading and
overriding.

Inheritance is the ability to use all of the functionality of an existing class, and extend those
capabilities without re-writing the original class.

Communication using messages When application wants to achieve certain task it can
only be done using combination of objects. A single object can not do the entire task.

Encapsulation Vs Abstraction:
Encapsulation is basically, wrapping up of data members and methods.
As you said, you hide the data for security such as making the variables as private, and expose the
property to access the private data which would be public. So, when you access the property you can
validate the data and set it.
Example:
Class Demo
{
private int _mark;
public int Mark
{
get { return _mark; }
set { if (_mark > 0) _mark = value; else _mark = 0; }

}
}
Abstraction have the methods which will be common for all the derived class would need. It contains
the skeleton which needs to be implemented by the derived class also, which will be declared as
abstract method.
Example:
abstract class CurryBase
{
public abstract void doCurryMasala();
}
public class FishCurry : CurryBase
{
public void doCurryMasala()
{
// Add Fish Curry specific contents also.
}
}
Encapsulation is the concept of binding data with methods...
Abstraction is nothing but hiding of data...in the sense hiding of complexity and providing
functionality...

Type safe:
Type safe means preventing programs from unauthorized access of memory and accesses only the
memory locations for which it is authorized to access.
For example, type-safe code cannot directly read values from another object's private fields or code
areas.

Callback:
A callback function is a function that is passed to another function (in the form of a pointer to the
callback function) so that the second function can call it. This is simply of way of making the second
function more flexible without the second function needing to know a lot of stuff.

Delegate:
Delegates are similar to C++ function pointers, but are type safe. Once a delegate is assigned a
method, it behaves exactly like that method. Any method that matches the delegate's signature, which
consists of the return type and parameters, can be assigned to the delegate. Delegates can be used
to define callback methods. Multiple methods can be assigned on a single event.

Defining a Delegate in C#:


public class DelegateAndEvent : System.Web.UI.Page
{
//declare delegate and its signature
public delegate int SomethingDelegate(int x,int y);
protected void Page_Load(object sender, EventArgs e)
{
//assign function of same signature like delgate
SomethingDelegate del = new SomethingDelegate(function1);
int ss = del(2, 3);
//adding multiple function of same signature in invocation list
del += new SomethingDelegate(function2);
//removing the function1() method from the invocation list

del -= new SomethingDelegate(function1);


int dd = del(2,3);
}
private int function1(int p,int q)
{
return p * q;
}
private int function2(int a,int b)
{
return a + b;
}
}

Event:
Event is a way for a class or object to notify other classes or objects when something of interest
occurs. The class that sends (or raises) the event is called the publisher and the classes that receive
(or handle) the event are called subscribers. An event can have multiple subscribers. A subscriber can
handle multiple events from multiple publishers.
public partial class UserControl_GeneralInfo :System.Web.UI.UserControl
{
public delegate void IndexChangeEvent();
public event IndexChangeEvent IndexChange;
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
IndexChange();
}
// Invoke the Changed event; called whenever drop down index changes
protected virtual void OnIndexChange()
{
if (IndexChange != null)
{
IndexChange();
}
}
}
public partial class EventListner : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Hooking up to an event
IdOfUserConrol.IndexChange += new
UserControl_GeneralInfo.IndexChangeEvent(function1);
}

protected void function1()


{
//perform action here
}

Event doesnt have any return type. We can use ant access modifier with event. We can have static
event which can raise static methods.

Hiding:
When two elements in a program have same name, one of them can hide and shadow the other one.
So in such cases the element which shadowed the main element is referenced.

class Exapmle1
{
static void Main(string[] args)
{
BC objBC;
DC objDC;
objBC = new BC();
objDC = new DC();
objBC.Display(); //BC::Display
objDC.Display(); //DC::Display
objBC = new DC();
objBC.Display(); //BC::Display
}
}
class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}

Difference between Hiding and overriding:


The difference lies when you call the derived class object with a base class variable. In class of
overriding although you assign a derived class object to base class variable it will call the derived
class function. In case of shadowing or hiding the base class function will be called.
While in shadowing you can change the signature of function also in derived class but in hiding it is
not allowed.

Similarities between Class and structure:


1. Both can have constructors, methods, properties, fields, constants, enumerations, events,
and event handlers.
2. Structures and classes can implement interface.
3. Both of them can have constructors with and without parameter.
4. Both can have delegates and events.

Difference between Class and structures:


1. Structures are value types and classes are reference types. So structures use stack and
classes use heap.
2. Structures members can not be declared as protected, but class members can be. You can
not do inheritance in structures.
3. Structures do not require constructors while classes require.
4. Objects created from classes are terminated using Garbage collector. Structures are not
destroyed using GC.

Dispose method:
.NET provides Finalize method in which we can clean up our resources. But relying on this is not
always good so the best is to implement Idisposable interface and implement the Dispose method
where you can put your clean up routines.

Array List:
Array is whose size can increase and decrease dynamically. Array list can hold item of different types.
You can access any item in array using the INDEX value of the array position.

HashTable:
You can access array using INDEX value of array, but how many times you know the real value of
index. Hashtable provides way of accessing the index using a user identified KEY value, thus
removing the INDEX problem.

Finalize method:
.NET Garbage collector does almost clean up but unmanaged resources (ex: - File, Database
connection objects etc) is outside the scope of .NET framework we have to explicitly clean our
resources. For these types of objects .NET framework provides Finalize method which can be
overridden and clean up code for unmanaged resources can be put in this section.

Indexer:
An indexer is a member that enables an object to be indexed in the same way as an array. We can
not have static indexer.

Event bubbling:
Server controls like Datagrid, DataList, Repeater can have other child controls inside them. Example
DataGrid can have combo box inside datagrid. These child control do not raise there events by
themselves, rather they pass the event to the container parent (which can be a datagrid, datalist,
repeater), which passed to the page as ItemCommand event. As the child control send there events
to parent this is termed as event bubbling.

@ Register directives:
@Register directive informs the compiler of any custom server control added to the page.

AppSetting Section:
Web.config file defines configuration for a webproject. Using AppSetting section we can define user
defined values. Example below defined is ConnectionString section which will be used through out
the project for database connection.
<appSettings>
<add
key="ConnectionString"
value="server=xyz;pwd=www;database=testing"
/>
</appSettings>

Using user or custom control in Page:


Register the ASCX control in page using the <%@ Register directive. Example
<%@ Register tagprefix="Accounting" Tagname="footer" Src="Footer.ascx" %>
Now to use the above accounting footer in page you can use the below directive.
<Accounting:footer runat="server" />

Authentication Vs Authorization
Authentication is taking the credentials like username and password and allow him to access the
application
Authorization is allowing a person to access a page after authentication. It can be set in the webconfig
file.

ADO.Net
ADO.Net Architecture:
The two main components of ADO.NET for accessing and manipulating data are the data providers
and the Dataset. Data Provider provides access to data source like SQL server oracle server. It
provides object to achieve functionalities like opening and closing connection, retrieve data and
update data. There are four main sections of a data provider.
1.
2.
3.
4.

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. 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 Datatable and relations.

The fundamental objects in ADO.Net are Dataset and DataReader.

Connection Object:
The Connection object creates the connection to the database. Microsoft Visual Studio .NET provides
two types of Connection classes: the SqlConnection object, which is designed specifically to connect
to Microsoft SQL Server 7.0 or later, and the OleDbConnection object, which can provide
connections to a wide range of database types like Microsoft Access and Oracle. The Connection
object contains all of the information required to open a connection to the database and close the
connection.

Command Object:
Command objects are used to execute commands to a database across a data connection. The
Command object is represented by two classes: SqlCommand and OleDbCommand

1. ExecuteNonQuery: - Executes the command defined in the CommandText 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.
2. ExecuteReader: - Executes the command defined in the CommandText. Returns a "reader"
object that is connected to the resulting rowset within the database, allowing the rows to be
retrieved.
3. ExecuteScalar: - Executes the command defined in the CommandText property. Returns only
single value (effectively the first column of the first row of the resulting rowset) any other
returned columns and rows are discarded. It is fast and efficient

DataAdapter:
It works as bridge between the database and a Dataset. The DataAdapter object is represented by
two classes: OleDbDataAdapter and SqlDataAdapter. The DataAdapter is used either to fill a
DataTable or Dataset with data from the database with its Fill method. After the memory-resident data
has been manipulated, the DataAdapter can commit the changes to the database by calling the
Update method There are three most commonly used methods of Dataadapter :1. Fill: - Executes the SelectCommand 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 datasource if there is a primary key in the table in the DataSet.
2. 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.
3. Update: - When the Update method is called, changes in the DataSet are copied back to the
database and the appropriate InsertCommand, DeleteCommand, or UpdateCommand is
executed.

DataReader:
The DataReader object provides a forward-only, read-only, connected stream recordset from a
database. Because only one row is in memory at a time, the DataReader provides the lowest
overhead in terms of system performance but requires the exclusive use of an open Connection
object for the lifetime of the DataReader. Command method Executereader takes a parameter called
as CommandBehavior where in we can specify saying close connection automatically after the
Datareader is close.
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

Return only schema


SqlDataReader dr = cmd.ExecuteReader(CommandBehavior. SchemaOnly);
Returns only single row
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior. SingleResult);
Returns only single value
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior. SingleValue);

DataSet:
The DataSet class exists in the System.Data namespace. The Classes contained in the DataSet class
are:
1. DataTable
2. DataColumn
3. DataRow
4. Constraint
5. DataRelation
Dataset object contain collection of DataTable objects. Each DataTable object contains a collection of
DataRow objects and a collection of DataColumn 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 DefaultView object for each

table. This is used to create a DataView object based on the table, so that the data can be searched,
filtered or otherwise manipulated while displaying the data.

Methods provided by the dataset:


1.
2.
3.
4.
5.
6.
7.
8.

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.
AcceptChanges: - It commits all the changes since last time Acceptchanges has been
executed.
GetChanges: - For tracking down changes this method returns the changes which are
changed in dataset since it was loaded or since Acceptchanges was executed.
HasChanges: - This property indicates that has any changes been made since the dataset
was loaded or acceptchanges method was executed.
Clone: - It only copies structure, does not copy data.
Copy: - Copies both structure and data.

Difference between Dataset and DataReader:


1. DataReader provides forward-only and read-only access to data and can access one table at
a time, while the Dataset object can hold more than one table from the same data source as
well as the relationships between them.
2. Dataset is a disconnected architecture while DataReader is connected architecture.
3. We can perform transaction in dataset but not in datareader.
4. Dataset communicates with the dataadapter only whereas datareader communicates with the
command object.

DataView:
A DataView enables you to create different views of the data stored in a DataTable. Using a
DataView, you can expose the data in a table with different sort orders, and you can filter the data by
row state or based on a filter expression.
A DataView provides you with a dynamic view of a single set of data, much like a database view, to
which you can apply different sorting and filtering criteria. Unlike a database view, however,
a DataView cannot be treated as a table and cannot provide a view of joined tables. You also cannot
exclude columns that exist in the source table, nor can you append columns, such as computational
columns, that do not exist in the source table. Every Datatable has a default view which has all the
row and columns.

Creating a DataView
If we need to display only a subset of the rows in your DataTable sorted in some specific fashion. We
can do this by creating your own DataView and specifying the DataTable, RowFilter, Sort, and
DataViewRowState by either using the full DataView Constructor or the individual properties.
public DataView(DataTable table, string RowFilter, string Sort, DataViewRowState RowState)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public DataTable GetTable()
{
string connectionString = ".Northwind.";DataTable customers = new
DataTable("Customers");
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand selectAllCustomers = connection.CreateCommand();
selectAllCustomers.CommandText = "SELECT * FROM [Customers]";
connection.Open();
customers.Load(selectAllCustomers.ExecuteReader
(CommandBehavior.CloseConnection));
}

return customers;
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = GetTable().DefaultView;
}
private void btnSortByCity_Click(object sender, EventArgs e)
{
DataView dv = new DataView(GetTable());
dv.Sort = "City ASC";
dataGridView1.DataSource = dv;
}
private void btnOnlyMexico_Click(object sender, EventArgs e)
{
DataView dv = new DataView(GetTable());
dv.RowFilter = "Country = 'Mexico'";
dataGridView1.DataSource = dv;
}
private void btnDeletedRowsOnly_Click(object sender,
EventArgs e)
{
DataView dv = new DataView(GetTable());
dv.Table.Rows[0].Delete();
dv.Table.Rows[1].Delete();
dv.RowStateFilter = DataViewRowState.Deleted;
dataGridView1.DataSource = dv;
}
private void btnEverythingGoes_Click(object sender,
EventArgs e)
{
DataView dv = new DataView(GetTable(),"Region = 'SP'
and Country = 'Brazil'", "ContactName",
DataViewRowState.CurrentRows);
dataGridView1.DataSource = dv;
}
}

DataViewRowState options

Description

CurrentRows

The Current row version of all Unchanged, Added,


and Modified rows. This is the default.

Added

The Current row version of all Added rows.

Deleted

The Original row version of all Deleted rows.

ModifiedCurrent

The Current row version of all Modified rows.

ModifiedOriginal

The Original row version of all Modified rows.

None

No rows.

OriginalRows

The Original row version of all Unchanged, Modified,


and Deleted rows.

Unchanged

The Current row version of all Unchanged rows.

Methods in DataView:
Find It takes an array of values and returns the index of the row.
FindRow This also takes array of values but returns a collection of DataRow.

If we want to manipulate data of DataTable object create DataView of the DataTable object and use
the following functionalities:

AddNew Adds a new row to the DataView object.


Delete Deletes the specified row from DataView object.

Difference between classic ADO and ADO.NET:


1. As in classic ADO we had client and server side cursors they are no more present in
ADO.NET. Note it's a disconnected model so they are no more applicable.
2. Locking is not supported due to disconnected model.
3. All data persist in XML as compared to classic ADO where data persisted in Binary
format also.

Access data from SQL server with the help of dataset:


string connString = "Data Source=.;Initial Catalog=RND;Integrated
Security=True";
string sql = @"select * from Lalit";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql);
cmd.Connection = conn;
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Lalit");
GridView1.DataSource = ds.Tables["Lalit"].DefaultView;
GridView1.DataBind();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
finally
{
conn.Close();
}

Access data from SQL Server with datareader:


string connString = "Data Source=.;Initial Catalog=RND;Integrated
Security=True";
string sql = @"select * from Lalit";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql);
cmd.Connection = conn;
try
{
conn.Open();
SqlDataReader dr =
cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
Console.WriteLine("{0}\t{1}\t\t{2}", dr[0].ToString(),
dr[1].ToString(), dr[0].ToString());
}
}

catch (Exception ex)


{
Console.WriteLine("Error: " + ex);
}
finally
{
conn.Close();
}

Use SP to fetch data with condison:


string connString = "Data Source=.;Initial Catalog=RND;Integrated
Security=True";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SPTest";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
try
{
conn.Open();
cmd.Parameters.AddWithValue("@input", 'A');
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Lalit");
GridView1.DataSource = ds.Tables["Lalit"].DefaultView;
GridView1.DataBind();

}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
finally
{
conn.Close();
}

Add and remove rows from DataTable 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 Adds a new row in DataTable
2. Remove Removes a DataRow object from DataTable.
3. RemoveAt Removes a DataRow object from DataTable depending on index position of the
DataTable.
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("DateTimeValue", typeof(DateTime)));
for (int i = 0; i < 9; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = DateTime.Now;
dt.Rows.Add(dr);
}

GridView1.DataSource = new DataView(dt);


GridView1.DataBind();

Add Relation between tables in a Dataset:


DataRelation dra = new DataRelation("Add_Of_Emp",
ds.Tables["EMP_Details"].Columns["emp_id"],
ds.Tables["EMP_Address"].Columns["emp_id"]);
ds.Relations.Add(dra);

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.

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

Implement locking in ADO.NET:


Following are the ways to implement locking using ADO.NET:

1. 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.
2. 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 is the best practice used by industries for locking.
Update table1 set field1=@test where pastTimeStamp=@CurrentTimeStamp
3. 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.

Perform transactions in .NET:


With Enterprise Services we get automatic transactions. Using transactions with
System.EnterpriseServices has the advantage that its not necessary to deal with transactions
explicitly; transactions are automatically created by the runtime. You just have to add the attribute
[Transaction] with the transactional requirements to the class. The [AutoComplete] attribute marks the
method to automatically set the status bit for the transaction: if the method succeeds, the success bit
is set, so the transaction can commit. If an exception happens, the transaction is aborted.
using
using
using
using

System;
System.Data.SqlClient;
System.EnterpriseServices;
System.Diagnostics;

[Transaction(TransactionOption.Required)]

public partial class _Default: ServicedComponent


{
[AutoComplete]
public void AddCourse(Course c)
{
string conString = "";
SqlConnection connection = new SqlConnection(conString);
SqlCommand courseCommand = connection.CreateCommand();
courseCommand.CommandText = "INSERT INTO Courses (Number, Title) VALUES
(@Number, @Title)";
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
try
{
courseCommand.Transaction = tx;
courseCommand.Parameters.AddWithValue("@Number", c.Number);
courseCommand.Parameters.AddWithValue("@Title", c.Title);
courseCommand.ExecuteNonQuery();
tx.Commit();
}
catch (Exception ex)
{
Trace.WriteLine("Error: " + ex.Message);
tx.Rollback();
}
finally
{
connection.Close();
}
}
}

Difference between an ADO.NET Dataset and an ADO Recordset:

There two main basic differences between recordset and dataset:


With dataset you an retrieve data from two databases like oracle and SQWL server and
merge them in one dataset, with recordset this is not possible
All representation of Dataset is using XML while recordset uses COM.
Recordset can not be transmitted on HTTP while Dataset can be.

Connection pooling:
Opening a database connection is a time consuming operation. Connection pooling increases the
performance of Web applications by reusing active database connections instead of creating a new
connection with every request. Connection pool manager maintains a pool of open database
connections. When a new connection requests come in, the pool manager checks if the pool contains
any unused connections and returns one if available. If all connections currently in the pool are busy
and the maximum pool size has not been reached, the new connection is created and added to the
pool. When the pool reaches its maximum size all new connection requests are being queued up until
a connection in the pool becomes available or the connection attempt times out.
Connection pooling behaviour is controlled by the connection string parameters. The following are
four parameters that control most of the connection pooling behaviour:
1. Connect Timeout - controls the wait period in seconds when a new connection is requested,
if this timeout expires, an exception will be thrown. Default is 15 seconds.
2. Max Pool Size - specifies the maximum size of your connection pool. Default is 100. Most
Web sites do not use more than 40 connections under the heaviest load but it depends on
how long your database operations take to complete.
3. Min Pool Size - initial number of connections that will be added to the pool upon its creation.
Default is zero; however, you may chose to set this to a small number such as 5 if your
application needs consistent response times even after it was idle for hours. In this case the
first user requests won't have to wait for those database connections to establish.

4. Pooling - controls if your connection pooling on or off. Default as you may've guessed is true.
Read on to see when you may use Pooling=false setting. If it is an OLEDBConnection object
set OLE DB Services=-4 in the connection string.

Potrebbero piacerti anche