Using ASO.NET and XML with ASP.NET (Primery Key, DataRow, RowState, DataTable, DataSet, Data Relations, Serialization to XML)
Major Connected and disconnected classes are:
When
working with disconnected data use at least DataTable class. DataTable
represents data in the form of Rows, Columns and constrains.
Employee
DataTable Creation:
Following
constrains can be applied on the DataColumn:
DataType(string,int),
MaxLength(-1 no limit), Unique, and AllowDBNull.
Creating
Primary Keys:
PK
can be based on single or multiple columns like:
employee.PrimaryKey = new DataColumn[] {empID};
Adding
Data with DataRow:
DataTable.Rows.Add
method is used. DataRow is created by DataTable to conform to schema. DataTable.Rows.Add
overload exists for array of objects. DataTable.Load can be used to load
and update data as defined by LoadOption enumeration.
|
LoadOption
|
Description
|
|
OverwriteRow
|
Overwrites “Original” and “Current”
version. RowState = Unchanged
|
|
PreserveCurrentValues
(default)
|
Overwrites the “Original” only. RowState
= Unchanged
|
|
UpdateCurrentValues
|
Overwrites the “Current” only.
If
new row
RowState = Added
If
Current == Orignal
RowState = Unchanged
Else
RowState = Modified
|
Binding
DataTable:
GridView1.DataSource =
employeeDataTable;
GridView1.DataBind();
For
list controls also specify DataTextField and DataValueField.
DataRowState:
Each row has a
state from one of the following:
|
DataRowState
|
Description
|
|
Detached
|
Row Created. Not Added to DataTable.
|
|
Added
|
Row is just added.
|
|
Unchanged
|
DataRow not changed since last call to
AcceptChanges().
|
|
Modified
|
DataRow is changed since last call
to AcceptChanges().
|
|
Deleted
|
Row deleted with Delete () method.
|
RowState
Demo:
|
|
|
DataRowVersion.
|
|||
|
Operation
|
RowState
|
Current
|
Default
|
Orignal
|
Proposed
|
|
Create a DataRow
|
Detached
|
-
|
|
NoVersion Exception
|
NoVersion Exception
|
|
Add Row to DataTable
|
Added
|
-
|
|
NoVersion Exception
|
NoVersion Exception
|
|
Set Price = 123
|
Added
|
123
|
123
|
NoVersion Exception
|
NoVersion Exception
|
|
RejectChanges()
|
Detached
|
-
|
-
|
NoVersion Exception
|
NoVersion Exception
|
|
Add Row Again
|
Added
|
-
|
-
|
NoVersion Exception
|
NoVersion Exception
|
|
AcceptChanges
|
Unchanged
|
-
|
-
|
-
|
-
|
|
Set Price = 234
|
Modified
|
-
|
234
|
-
|
234
|
|
AcceptChanges()
|
Unchanged
|
234
|
234
|
-
|
234
|
|
Set Price = 345
|
Modified
|
234
|
345
|
-
|
345
|
|
RejectChanges()
|
Unchanged
|
234
|
234
|
-
|
NoVersion Exception
|
|
Delete
|
Deleted
|
Exception
|
Exception
|
-
|
NoVersion Exception
|
|
RejectChanages()
|
Unchanged
|
234
|
234
|
-
|
NoVersion Exception
|
Holding
Multiple Copies of the DataRowVersion:
Each
DataRow maintains three copies of data Row.
To
retrieve a specific version of data pass DataRowVersion.(Default, Current,
Orignal, or Proposed).
DataRow.HasVersion can be use to test
whether a specific version of info exists or not.
Resetting
RowState with AcceptChanges and RejectChanges:
AcceptChanges
and RejectChanges are available at DataRow, DataTable, and DataSet.
DataLoaded
from DB - Added State
Accept
Changes - Unchanged
Modify
Rows - Modified Rows’ state will be modified
To
save Data call GetChanges() at DataSet level. It will return DataSet
with modified rows only.
Make
changes to DB.
Call
AcceptChanges(). - RowState = Unchanged of all rows
RejectChanges() will take rollback
to the last point of AcceptChanges().
To
explicitly set RowState call RowState.SetAdded() or RowState.SetModified().
To
undelete a DataRow call RejectChanges(). But it will also lose
changes made between the Accept changes and Delete calls.
Copy and
Clone of the DataTable:
DataTable DT2 =
employee.copy().
-
Copy Copies data and schema.
-
Clone only copies schema. An empty copy.
To
import a DataRow into a DataTable:
“Import”
method is used.
DataTable
DT3 = employee.Clone().
DT3.ImportRow(employee[0]);
DT3.ImportRow(“Mobi”,
“ikpk”, “100”);
To
Export DataTable into XML call:
Employee.WriteXML(
“emp.xml”);
To
change root element name specify the TableName. TableName will become
the root element.
Employee.TableName
= “EmployeeList”;
DataColumn.ColumnMapping
is to be specified to describe how a DataColumn is to be rendered into XML.
DataColumn.Attribute
DataColumn.Elment
DataColumn.Hiiden
(not rendered)
DataColumn.SimpleContent
(Text placed in between tags<></>)
To
write employee XML with schema use:
Employee.WriteXML(
“emp.xml”, XMLWriteMode.WriteSchema);
Result
will have schema at top then data after that.
To
Read Data Back:
DataTable DTemp = new DataTable();
DTemp.ReadXML(“emp.xml”);
Opening
a DataView Window in DataTable:
DataView
allows Filtering, Sorting, & RowStateFilter. DataView
also have AllowDelete, AllowEdit, and AllowNew properties.
Creating
and sorting in DataView:
DataView vemp = new DataView
(employee);
Vemp.Sort = “LastName ASC,
Salary DESC”;
Vemp.RowFilter= “LastName LIKE
‘%tim%’ AND salary > 2000”;
Vemp.RowStateFilter =
DataViewRowState.None;
GridView2.DataSource=vemp;
GridView2.DataBind();
DataViewRowState includes:
Added,
CurrentRows, Deleted(Orignal Version), ModifiedCurrent, ModifiedOriginal,
None(Clears RowStateFilter), Original( All original rows), Unchanged.
Using
DataSet Object:
DataSet
is memory based relational data representation. It’s primary disconnected data
object. It contains a collection of DataTables and DataRelations.
DataTables can contain Unique and Foreign Key constrains. DataSet includes
methods like Copy, Clone, and Merge.
If
a DataSet contains more than one table then to bind GridView to a specific
table provide the table name to GridView.
GridView1.DataSource
= CompanyListDatSet;
GridView1.DataMember
= “CompanyTable”;
Using
Typed DataSet:
Statement
like:
DataTable companyDataTable = CompanyList[“CompanyTable”];
But if “CompanyTable” is misspelled,
there will be a runtime error.
To
avoid this problem and to achieve facilities like altering Length and Data Type
like constrains at runtime without recompiling; use typed DataSet.
One
can create XSD file for the DataSet by hand or using GUI designer.
Adding
Relations:
CopmanyDataSet.Relations.Add( “Company_employee”/*Relation name*/,
companyTable.Columns[“Id”],
empTable.Columns[“CompanyID”]
);
Navigating
DataTables with DataRelations:
DataRelation relates two tables thus
provides a navigation path between two tables. DataRelation can be traversed
from parent to child and child to parent.
e.g.:
DataRelation drl =
companyList.Relations[“Company_Employee”];
DataRow drCompanyParent =
CompanyList.Tables[“Company”].Rows[0];
To
find employees of the company:
DataRow[] vCompanyEmployees =
drCompanyParent.GetChildRows(drl);
To
find company of a specific employee:
DataRow
vParentCompany =
CompanyDataSet.Tables[“EmployeeTable”].Rows[0].GetParent(drl);
Primary
and Foreign Key Constrains:
When
a DataRelation is based on PK and FK, one can specify dependence mode:
None:
InvalidConstrainException thrown if PK is updated/deleted.
SetDefault: FK is set to
default value if PK is updated/deleted.
SetNull: FK is set to
DBNull if PK is updated/deleted.
Serializing
and Desializing DataSet:
DataSet
can serialized; transferred over streams and deserialized at destination.
XML
and Binary serializations are supported.
To
Serialize as XML:
CompanyListDataSet.WriteXML(“companyList.xml”);
DataSet.DataSetName
is recommended to be set that will become the root element.
For
Compat XML production do specify:
DataColumn.ColumnMapping
= MappingType.Attribute;
To
nest employess of a company with company tags use:
CompanyListDataSet.Relations[“Employee_Company”].Nested
= true;
All
Data is written as String data type, to avoid this use:
CompanyListDataSet.WriteXML(“companyList.xml”,
XMLWriteMode.WriteSchema);
Or
Write Schema to seprate file:
CompanyListDataSet.WriteSchema(“CompanySchema.xsd”);
Serializing
a Changed DataSet as DiffGram:
DiffGram
saves the Orignal version of data as well. It is required when user works in
disconnected mode and afterward changes are being sent to server.
CompanyListDataSet.WriteXML(“companyList.xml”,
XMLWriteMode.DiffGram);
Deserializing
DataSet from XML:
DataSet
vCompanyList = new DataSet();
vCompanyList.ReadXML(“companyList.xml”);
OR
DataSet
vCompanyData = new DataSet();
vCompanyData.ReadXMLSchema(“empCompanies.xsd”);
vCompanyData.ReadXML(“companyList.xml”);
XMLReadMode
is recommended to be used:
XMLReadModes
are:
Auto: Source is
examined.
DiffGram: DiffGram changes
are to be applied.
Fragment: XML to bread as
fragments generated from SQL Server.
IgnoreSchema: Ignore schema
that is defined within file.
InferSchema: Columns are
created based on data. All of type string. If a Column exists in DataSet
previously its just used.
InferTypedSchema: Columns are
created and their type is identified from the data; if not identifiable then
its string.
ReadSchema: Embeded Schema is
searched for. If a DataTable exists in DataSet an exception is thrown.
Serializing
and Deserializing a Dataset in Binary Format:
Binary Serialized DataSet requires
less memory and is efficient.
Namespace
required are:
System.Runtime.Serialization.Formatters.Binary
System.IO
DataSet
vCompanyList = new DataSet();
vCompanyList.ReadXML(“companyList.xml”);
vCompanyList.RemotingFormat
= SerializationFormat.Binary;
FileStream
fs = new FileStream(“CompanyList.bin”, FileMode.Create);
BinaryFormatter
bf = new BinaryFormatter();
Bf.Serialize(fs,
vCompanyList);
For
small DataSet binary serialization takes more spaces than XML format. But for
Larger files Binary Serialization takes less space than XML.
To
Deserialize:
DataSet
vCompanyList = new DataSet();
FileStream
fs = new FileStream(“CompanyList.binl”, FileMode.Open);
BinaryFormatter
bf = new BinaryFormatter();
vCompanyList
= (DataSet)Bf.Deserialize(fs);
DataSet.Merge:
DataSet.Merge allows
merging of data from multiple sources including DataSet, DataTable, and
DataRow.