Sei sulla pagina 1di 149

WINFORMS

By
Balamurali Balaji
Microsoft MVP
What Are Windows Forms?
Screen real estate – graphical element that
appears on the desktop
Gives a program a Look and Feel
Used to present information to the user and
to accept input from the user. GUI – Graphical
User Interface
Are standard windows, multiple document
interface (MDI) windows, dialog boxes
Are objects with
 Properties which define their appearance
 Methods which define their behavior
 Events which define their interaction with users
What Are Windows Forms?
(cont…)
Forms are instances of classes
Like all objects in the .NET Framework
Forms are controls
Inherit from the Control class
Create them via
Windows Forms Designer (easier)
Code Designer (harder)
Windows Forms Features
 Simplicity and power
 Programming model for developing Windows applications
quickly (RAD)
 Rich graphics
 Windows Graphical Device Interface Plus (GDI+) that
supports alpha blending, texture brushes, advanced
transforms, rich text support, and more.
 Flexible controls
 Rich set of controls that encompass all of the controls
offered by Windows.
 Data awareness
 Windows Forms offers full support for the ADO.NET data
model (discussed further in later weeks)
Windows Forms Features
(cont…)
ActiveX control support
Easily host ActiveX controls in a Windows Forms
application.
Printing
printing framework for comprehensive reports.
Accessibility
Can build applications that support accessibility
aids, such as screen readers.
A Windows Form

• Buttons
• Menus
• Labels
• Textboxes
WinForms Applications
Typical forms-application design
One or more classes derived from
System.Windows.Form
Derived classes affect instance appearance and
behavior by setting properties
Derived classes create objects to implement GUI
controls
 Buttons, text boxes, menus, timers, custom controls,
etc.
Derived classes implement methods to handle
GUI events
 Buttons clicks, menu selections, mouse movements,
timer events, etc.
 Default behavior implemented by base classes
Creating Windows Forms

Typical forms-application threading


A single thread dedicated to UI
 Runs the message pump
 Can do other things, but blocks only briefly (or never)
Background or pooled threads used for lengthy
non-UI functionality
Typical forms-applications development
Also use classes in System.Drawing namespace
Design UI with VisualStudio .NET
 Possible to do anything directly via code
WinForms Objects
 The Application Object
 Used to process Window messages
 Start and Stop Applications and Threads
 The Form Object
 Representation of the Windows displayed
 Can support MDI forms also
 Control (no visual) and Rich Control Objects (visual)
 Represents GUI elements
 Handles keyboard, pointing device input and events
 Base class on which richer controls are based
Control Class
Base-class for all controls/forms in managed code
 Wraps an underlying OS window handle
Implements many
 Public Methods for performing actions on an instance
 Show(), Hide(), Invalidate(), etc.
 Properties for modifying settings of an instance
 Size, BackColor, ContextMenu, etc.
Derived classes override and specialize
functionality
 Specialized methods, properties, and events
 TextBox – PasswordChar, Undo(), Copy()
 Button – Image, PerformClick()
 The Form class is derived from Control
Instances of Control can contain child controls
Form Class
A specialized derivation of Control used to
implement a top-level window or dialog
Gains much of its functionality from base
classes
Specialized to
 Manage dialog buttons
 Contain a main menu
 Contain a title-bar, system menu, minimize/maximize
 Implement MDI
 Etc.
Your applications derive from Form to create
 Windows
 Dialog boxes
Using Controls
 Create the control
 Set properties and register for event notification
 Add the control to your forms Controls collection

class MyForm:Form{
public MyForm(){
Button ctrl = new Button(); // Create a button
ctrl.Text = "A Button"; // set its text

// Register OnButtonClicked as an event handler


ctrl.Click += new EventHandler(OnButtonClicked);
Controls.Add(ctrl); // Add the control to form
}

private void OnButtonClicked(Object sender, EventArgs e){


MessageBox.Show("The button was clicked!");
}
}
Setting Control Properties
Set at runtime or design time
Event Handling
Response to user interaction
A user presses a button – then what?
We must deal with their interaction
Double clicking a control at design time allows
modification the default event hander code.
Winforms/GUIs are event driven and they
generate events which we can use
Typical User Interactions
Moving or clicking a mouse
Clicking a button
Typing in a textbox
Selecting a menu item
Closing a window

All of these generate events


We handle the events generated by the .net
controls
No need to create our own
Event Handling in VS.net
Highlight the control
you wish to handle an
event for
Click on the events
button in Properties
Double-click the event
you want to handle
when it is generated at
runtime
Add required code in the
code designer
Event Handler
Passed two object references
Sender – reference to the object which raised the
event
EventArgs - base class for classes containing
event data
Remember VS does a lot of this for you

private void controlName_EventName(object sender,


System.EventArgs e)
{
// code to handle event
}
Button Control
 Abstract base class:
ButtonBase
 Common events –
Click
Raised when user
clicks the button
control. Default event
in VS.Net
 Common properties private void cmdColour_Click(object
sender, System.EventArgs e)
– Text {
The text displayed on // do something
}
the button
Working with Menu’s
 MainMenu, ContextMenu, and MenuItem are derived
from Menu
Menu includes a collection of MenuItem’s
 Create a MainMenu (or ContextMenu)
Use constructor parameters to set the text and
other details
 Add MenuItems to the MainMenu
Can add sub-MenuItem’s
Register event handlers
 Set Form’s Menu property to the instance of the
MainMenu
 Or just use Visual Studio
Adding Menus
// Create a menu
MainMenu menu = new
MainMenu();
MenuItem item =
menu.MenuItems.Add("&File");
item.MenuItems.Add(
new MenuItem("E&xit", new
EventHandler(OnExit)));

// Attach the menu to the


form
this.Menu = menu;
Dialog Boxes
Use ShowDialog to open a
dialog
Inherits from CommonDialog
Many Boxes already available
for you to use (see pic)
Return input values via
properties of dialog box
Dialog Boxes (cont…)
// simple // Open File
MessageBox.Show("Hi“, “The title”); OpenFileDialog ofd = new
// colour dialog (color) OpenFileDialog();
ColorDialog cd = new ColorDialog(); ofd.ShowDialog();
cd.ShowDialog();
// Print
// Save File
PrintDialog pd = new PrintDialog();
SaveFileDialog sfd = new
pd.PrinterSettings = new
PrinterSettings()
SaveFileDialog();
pd.ShowDialog(); sfd.ShowDialog();
// Font
FontDialog fd = new FontDialog(); // Folder Browser
fd.ShowDialog() FolderBrowserDialog fbd = new
FolderBrowserDialog();
fbd.ShowDialog();
Dialog Boxes (cont…)
Custom Dialog Boxes
private void cmdClose_Click(object sender,
System.EventArgs e)
{
MessageBoxButtons buttons =
MessageBoxButtons.YesNo;
DialogResult result = MessageBox.Show(this, "Do you
really want to close the app?","Close App?" , buttons,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign);
if(result == DialogResult.Yes)
Application.Exit();
}
Using Controls
Buttons
Text Controls
List Controls
Menus
Common Dialogs
More controls
Common Control Properties
All controls inherit from the class Control
Thus, they have some common properties and
methods
Properties
Backcolor, Enabled, Font, TabIndex, TabStop,
Visible
Methods
Hide(), Show()
TextBox
 Area for text input
from user
 Has provision for
Password handling
 Properties
Multiline, PasswordChar
(*), Readonly, Text
 Events
TextChanged (default
event in VS.net)
RichTextBox
Has similar properties
and events to TextBox
Advanced formatting
However
DetectUrls
linkClicked event
Opening and saving files
via LoadFile(), SaveFile()
CheckBox
Multiple options
true/false or yes/no
Event
CheckedChanged
when check box is
clicked
private void boldCheckBox_CheckedChanged( object sender, System.EventArgs e )
{
if (outputLabel.Font.Bold)
textLabel.Font = new Font(textLabel.Font.Name, textLabel.Font.Size);
else
textLabel.Font = new Font(textLabel.Font.Name, textLabel.Font.Size, FontStyle.Bold);
}
RadioButton
Allow a user to choose
from mutually
exclusive options
As opposed to the
checkBox
Event
CheckedChanged when
a radio button is clicked

private void radioGreen_CheckedChanged(object sender, System.EventArgs e)


{
this.lblColour.ForeColor = Color.Green;
this.lblColour.Text = "GO!";
}
TreeViews
Displays Node hierarchically on a tree
Nodes are objects that refer to other nodes
Parent node has child nodes which can also
have child nodes
Labels
Simple way of adding
text to a form
Typically used to
provide descriptive
text for a control
Set text at runtime
(no need for event)

private void radioRed_CheckedChanged(object sender, System.EventArgs e)


{
this.label1.Text = "You selected RED!";
}
PictureBox
 Used to display
graphics
 Bitmap, metafile, icon,
JPEG, GIF or PNG file
support
 Image property allows
the setting of the
image either at design
time or at run time.
 Clipping and
positioning through the
SizeMode property

this.pictureBox1.Image = new Bitmap("c:/temp/myPic.png");


LinkLabel
Similar to a Label control
except it can display a
hyperlink
private void Form1_Load(object sender, System.EventArgs e)
{
this.linklbl.Links.Add(0,linklbl.Text.Length,
"http://www.theage.com.au");

private void linklbl_LinkClicked(object sender,


System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
// Display the appropriate link based on the value of the
LinkData property of the Link object.

System.Diagnostics.Process.Start(e.Link.LinkData.ToString());
}
ListBox
Displays a list of items
Select by clicking
Single or multiple
selections using the
Selectionmode property
private void Form1_Load(object sender, System.EventArgs e)
{
this.listBox1.Items.Add("Item 1"); this.listBox1.Items.Add("Item 2");
this.listBox1.Items.Add("Item 3");this.listBox1.Items.Add("Item 4");
}
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
MessageBox.Show(this.listBox1.SelectedItem.ToString());
}
ComboBox
 Combination of
ListBox and TextBox
Editing Field
Similar properties and
functionality
Adding and selecting
Items same as ListBox
i.e. SelectedItem
property
Tab Control
A TabControl contains
tab pages
Common to Windows
apps
Tabs are represented
by TabPage objects
Good for screen
aesthetics -
uncluttering
Multiple Document Interface
(MDI)
Enables sub forms of a master form
Known as MDI parent and MDI child(ren)
Edit multiple documents at once
As opposed to SDI – Single Document Interface
MDI Applications (example)
Common Dialogs
OpenFileDialog, SaveFileDialog
Derived from FileDialog
Offers the OpenFile method
FontDialog
Raises an Apply event for preview
functionality
ColorDialog
PageSetupDialog
PrintDialog
More Controls
 CheckedListBox PrintPreviewControl
 ContextMenu PrintPreviewDialog
 DataGrid ProgressBar
 DateTimePicker PropertyGrid
 DomainUpDown, StatusBar
 ErrorProvider Timer
 GroupBox, ToolTip
 HScrollBar, TrackBar
 ImageList TreeView
Panel VScrollBar
Data bound Controls
 ADO.NET
 Managed Providers
 Using the OLE DB .NET Provider
 Data Binding
 Simple data binding
 Complex data binding
 Discussed at length in later weeks
Miscellaneous
 ActiveX Controls
Usable through wrappers
Usage like other controls

 Related classes
Keys
Cursors
System Information
Windows Forms Toolbox
Summary
 Windows Forms?
 Control Class
Setting Control Properties
 Event Handling
 Button Control
 Working with Menu’s
 Dialog Boxes
 Using Controls
Common Control Properties
 Multiple Document Interface (MDI)
 Common Dialogs
ACCESSING DATA WTH
ADO.NET
ADO.NET
Is the .NET technology for accessing
structured data
Uniform object oriented interface for
different data sources
relational data bases
XML data
other data sources
Designed for distributed and Web
applications
Provides 2 models for data access
connection-oriented
connectionless
Connection-oriented Vs Connection-
less
Connection-oriented
Keeps the connection to the data base alive
Intended for applications with:
 short running transactions
 only a few parallel accesses
 up-to-date data

Connectionless
No permanent connection to the data source
Data cached in main memory
Changes in main memory ≠ changes in data source
Intended for applications with:
 many parallel and long lasting accesses (e.g.: web applications)
Universal Data Access
Connection of (object-oriented)
programming languages and relational
data bases
Uniform programming model and API
Special implementations for data sources
MsSql
(providers)
DB2
API

Application
Oracle
ODBC
?
Provider
Data Providers
Microsoft’s layered architecture for data
access
ADO.NET

SQL Server
Oracle ODBC OLEDB
MySQL

SQL-data Non-SQL-data
MS SQL Server, Oracle, Directory Services, Mail,
Jet, Foxpro, ... Text, Video, ...
ADO.Net Providers

Driver Provider
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
The Provider Factory Model
A Factory class for each data provider derived from
base class DbProviderFactory
 Represents a common entry point for a variety of services specific to the
provider
 Developers need not know the data source they are going to access
 Common features, unique capabilities
 Generic data adapter and connection objects can be created

FactoryClass methods: CreateCommand, CreateConnection,


CreateDataAdapter, CreateParameter

To get the factory of a particular provider:


DbProviderFactory fact = DbProviderFactories.GetFactory(“System.Data.SqlClient”)
Provider Independent API
• Database Independent Coding
• System.Data.Common Namespace
• Provider Factory Class
‘example APINameSpace=“System.Data.SQLClient”
Public Function GetDS(byVal APINameSpace as String)as DataSet
Dim provider as DbProviderFactory =
dbProviderFactories.GetFactory(APINameSpace)
Dim connection As DbConnection-provider.CreateConnection
Dim adapter as DbDataAdapter = provider.CreateDataAdapter
‘code to connect command, connection and dataadapter…
adapter.fill(ds)
Return ds
End Function
Connection String Builders
Architecture of ADO.NET
connectionless connection-oriented
ADO.NET Content Components A D O . N E T M a n a g e d P ro v id e rs

DataSet D ataR eader


Tables
DataTable
Fill T ra n s a c t io n

D ata
A dapter
Update C om m and
Relations

DataTable DataRelation
C o n n e c t io n

ReadXml
WriteXml

D atabas e
XML file

Connectionless data flow C o n n e c t io n -o rie n t e d d a t a f lo w


ADO.Net object model

Fill
DataAdapter DataSet
Update
UpdateCommand

DeleteCommand
SelectCommand

InsertCommand

Errors Collection

Command

Connection Parameters

Data Source
ADO.NET and XML
Controls,
XSL/T, X-Path,
Designers,
etc
Code-gen, etc

DataSet XmlData-
Mapping Document

DataAdapter DataReader
XmlReader
Command
Connection
.NET Data Provider
ADO.NET and XML
 The DataSet
 Loads/saves XML data into/out of DataSet
 Schema can be loaded/saved as XSD
 Schema can be inferred from XML Data
 The DataSet can be associated with an
XmlDataDocument
 Exposes a relational view over structured XML
 According to the DataSet schema
 Allows strong typing, control binding, relational access of
XML data
 Allows XML tools (schema validation, XSL/T, XPath queries)
against relational data
 Preserves full fidelity of XML Document
Dataset and XML

// Load DataSet with XML


DataSet ds = new DataSet();
ds.ReadXml("inventory.xml");

// Add a record to the Inventory table


DataTable inventory = ds.Tables["Inventory"];
DataRow row = inventory.NewRow();
row["TitleID"]=1;
row["Quantity"]=25;
inventory.Rows.Add(row);

// Write out XML


ds.WriteXml("updatedinventory.xml");
Writing XML Schemas from
DataSet

SqlConnection conn = new


SqlConnection( "server=(local);uid=sa;pwd=;database=pubs"); SqlDataAdapter
da = new SqlDataAdapter( "select * from authors;select * from titleauthor", conn);
DataSet ds = new DataSet("OneMany");

da.TableMappings.Add("Table", "authors");
da.TableMappings.Add("Table1", "titleauthors");
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);

ds.Relations.Add( "au_ta", ds.Tables[0].Columns["au_id"],


ds.Tables[1].Columns["au_id"], true);
ds.Relations[0].Nested = true;
ds.WriteXmlSchema("one_to_many.xsd");
Typed DataSets
 XSD.exe, the XML schema generation tool, is used to generate a
typed DataSet from an XSD schema.
 A typed DataSet is a subclass of System.Data.DataSet in which the
tables that exist in the DataSet are derived by reading the XSD
schema information.
 DataRows, DataTables, and other items are available as strong
types
 Rather than refering DataSet.Tables[0] or
DataSet.Tables["customers"], you code like MyDataSet.Customers.
 Strongly typed variable names can be checked at compile time
rather than causing errors at runtime.
Loading a DataSet through
the XmlDataDocument

XmlDataDocument datadoc = new XmlDataDocument();


datadoc.DataSet.ReadXmlSchema("c:\\authors.xsd");
datadoc.Load ("c:\\authors.xml");
DataSet ds = datadoc.DataSet; // use DataSet as usual
foreach (DataTable t in ds.Tables)
Console.WriteLine( "Table " + t.TableName + " is in dataset");
Creating an
XmlDataDocument from a
DataSet

DataSet ds = new DataSet(); // load the DataSet


SqlDataAdapter da = new SqlDataAdapter( "select * from authors;select * from
titleauthor", "server=localhost;database=pubs;uid=sa");
da.MissingSchemaAction = MissingSchemaAction.AddWithKey; da.Fill(ds); // t
tweak the DataSet schema

ds.Tables[0].TableName = "authors";
ds.Tables[1].TableName = "titleauthor";
ds.Relations.Add( ds.Tables[0].Columns["au_id"], ds.Tables[1].Columns["au_id"]);
ds.Relations[0].Nested = true;

XmlDataDocument dd = new XmlDataDocument(ds); // write the document


dd.Save("c:\\temp\\xmldoc.xml"); // write the dataset
dd.DataSet.WriteXml("c:\\temp\\dataset.xml");
ADO.NET Assembly and
Namespaces
Assembly: System.Data.dll
Namespaces:

 System.Data general data types


 System.Data.Common classes for implementing providers
 System.Data.OleDb OLE DB provider
 System.Data.SqlClient Microsoft SQL Server provider
 System.Data.SqlTypes data types for SQL Server
 System.Data.Odbc ODBC provider (>.NET 1.1)
 System.Data.OracleClient Oracle provider (>.NET 1.1)
 System.Data.SqlServerCe Compact Framework
ADO.NET Assembly and
Namespaces
Assembly: System.Data.dll
Namespaces:

System.Data general data types


System.Data.Common classes for implementing providers
System.Data.OleDb OLE DB provider
System.Data.SqlClient Microsoft SQL Server provider
System.Data.SqlTypes data types for SQL Server
System.Data.Odbc ODBC provider (>.NET 1.1)
System.Data.OracleClient Oracle provider (>.NET 1.1)
System.Data.SqlServerCe Compact Framework
Example: Northwind
Database
Microsoft Example for SQL Server

 Reading of the table Employees


 Output of
 EmployeesID, LastName, FirstName

for all rows of table Employees

Run
Program Pattern for
Connection-oriented Data
Access
1.) Declare the connection
try {
1.) Request connection to database

2.) Execute SQL statements

3.) Process result

4.) Release Resources


} catch ( Exception ) {
Handle exception
} finally {
try {
4.) Close connection
} catch (Exception)
{ Handle exception }
}
Example: EmployeeReader (1)
using System;
using System.Data;
using System.Data.OleDb;

public class EmployeeReader {


public static void Main() {

• Establish connection
string connStr = "provider=SQLOLEDB; data source=(local)\\NetSDK; " +
"initial catalog=Northwind; user id=sa; password=; ";
IDbConnection con = null; // declare connection object
try {
con = new OleDbConnection(connStr); // create connection object
con.Open(); // open connection

• Execute command
//----- create SQL command
IDbCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT EmployeeID, LastName, FirstName FROM Employees";
//----- execute SQL command; result is an OleDbDataReader
IDataReader reader = cmd.ExecuteReader();

// continue next page


Example: EmployeeReader (2)
• Read and process data rows
IDataReader reader = cmd.ExecuteReader();
object[] dataRow = new object[reader.FieldCount];

while (reader.Read()) {
int cols = reader.GetValues(dataRow);
for (int i = 0; i < cols; i++) Console.Write("| {0} " , dataRow[i]);
Console.WriteLine();
}

• Close connection
//----- close reader
reader.Close();
} catch (Exception e) {
Console.WriteLine(e.Message);
} finally {
try {
if (con != null)
// ----- close connection
con.Close();
} catch (Exception ex) { Console.WriteLine(ex.Message); }
}
}
}
Connection
 define data base connection
string ConnectionString {get; set;}
Open and close connection
void Close();
void Open();
 Properties of connection object

string Database {get;}


int ConnectionTimeout {get;}
ConnectionState State {get;}
 Creates Command-Object

Command CreateCommand();
Creates Transaction-Object

ITransaction BeginTransaction();
Transaction BeginTransaction(IsolationLevel lvl);
ConnectionString
Key-value-pairs separated by semicolon (;)
 name of the provider
 identification of data source
 authentication of user
 other database-specific settings

e.g.: OLEDB:
"provider=SQLOLEDB; data source=127.0.0.1\\NetSDK;
initial catalog=Northwind; user id=sa; password=; "
"provider=Microsoft.Jet.OLEDB.4.0;data
source=c:\bin\LocalAccess40.mdb;"
"provider=MSDAORA; data source=ORACLE8i7; user
id=OLEDB; password=OLEDB;"
Command Objects
0..1 * 1 *
Transaction Command Parameter

Connection

Command objects define SQL statements or stored


procedures
Executed for a connection
May have parameters
May belong to a transaction
ExecuteReader Method
DataReader ExecuteReader()
DataReader ExecuteReader( CommandBehavior behavior );

public enum CommandBehavior {


CloseConnection, Default, KeyInfo, SchemaOnly,
SequentialAccess, SingleResult, SingleRow
}

 Executes the data base query specified in CommandText


 Result is an DataReader object

Example:
cmd.CommandText =
"SELECT EmployeeID, LastName, FirstName FROM Employees ";
DataReader reader = cmd.ExecuteReader();
ExecuteNonQuery Method
int ExecuteNonQuery();

Executes the non-query operation


specified in CommandText
UPDATE
INSERT
DELETE
CREATE TABLE
…
Example:
Result is number of affected rows

cmd.CommandText = "UPDATE Empls SET City = ’Seattle’ WHERE iD=8";


int affectedRows = cmd.ExecuteNonQuery();
ExecuteScalar Method
object ExecuteScalar();

 Returns the value of the 1st column of the 1st row


delivered by the database query
 CommandText typically is an aggregate function

Example:

cmd.CommandText = " SELECT count(*) FROM Employees ";


int count = (int) cmd.ExecuteScalar();
Parameter
 Command objects allow for input and
output parameters <<interface>>
IDbCommand
...
 Parameter objects specify IDataParameterCollection
Parameters {get;}
Name: name of the parameter ...

Value: value of the parameter


Parameters *
DataType: data type of the <<interface>>
parameter IDataParameter
//----- Properties
Direction: direction of the DbType DbType {get; set;}
ParameterDirection Direction {get; set;}
parameter string ParamterName {get; set;}
object Value {get; set;}
Input ...
Output
InputOutput <<interface>>
IDbDataParameter
ReturnValue
//----- Properties
int Size {get; set;}
...
Working with Parameters
Define SQL command with place holders
OLEDB: Identification of parameters by position ("?")
SQL Server: Identification of parameters by name ("@name")

OleDbCommand cmd = new OleDbCommand();


cmd.CommandText = "DELETE FROM Empls WHERE EmployeeID = ?";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "DELETE FROM Empls WHERE EmployeeID = @ID";
Adding parameter and Assigning Value
cmd.Parameters.Add( new OleDbParameter("@ID", OleDbType.BigInt));
cmd.Parameters["@ID"].Value = 1234;
cmd.ExecuteNonQuery();
DataReader
ExecuteReader() returns DataReader
object
DataReader ExecuteReader()
DataReader ExecuteReader( CommandBehavior behavior );

DataReader allows sequential reading of


result (row
bool Read()
by Arow) B C

Result table of a SELECT statement


Result table of a SELECT statement
DataReader
Read reads next row
bool Read();

Access to column values using indexers

object this[int] {get;}


object this[string] {get;}
Typed access to column values using access methods

bool GetBoolean(int idx);


byte GetByte(int idx);
...
Getting meta information
string GetDataTypeName(int i);
string GetName(int idx);
int GetOrdinal(string name);
...
DataSet
 Main memory data base
relational structure
object oriented interface
 DataSet consists of
collection of DataTables
collection of DataRelations
 DataTables consists of
collection of DataTableColumns (= schema
definition)
collection of DataTableRows (= data)
DefaultView (DataTableView, see later)
 DataRelations
associate two DataTable objects
define ParentTable and ParentColumns
and ChildTable and ChildColumns
DataSet Structure
DataSet
DataTable
DataTable schema
.Tables[...]
.Columns[..]
.Columns[...] DataColumn DataColumn

.Rows[...]
.Rows[..] DataRow
data
DataRow

.DefaultView DataView
...
.Relations[...]
DataRelation
DataRelation
...
DataSet Class Diagram
DataRelation

//----- Properties
Relations string RelationName {get; set;}
DataSet * DataTable ParentTable {get;}
DataColumn[] ParentColumns {get;}
//----- Properties
ParentRelations DataTable ChildTable {get;}
string DataSetName {get; set;} * DataColumn[] ChildColumns {get;}
ChildRelations ...
DataRelationsCollectionRelations {get;}
DataTableCollection *
Transaction Tables
1 {get;}
PropertyCollection ExtendedProperties {get;}
string NameSpace {get;}
bool HasErrors {get;}
... DataColumn

//----- Properties
*
bool AllowDBNull {get; set;} ChildColumns
bool AutoIncrement {get; set;}
int AutoIncrementSeed {get; set;} *
* Tables Columns int AutoIncrementStep {get; set;} ParentColumns
* string ColumnName {get; set;}
Type DataType {get; set;}
DataTable string Expression {get; set;}
bool ReadOnly {get; set;}
//----- Properties bool Unique {get; set;}
string TableName {get;} ...
DataRelationsCollectionChildRelations {get;}
DataRelationsCollectionParentRelations {get;}
ConstraintCollectionConstraints {get;}
DataColumnCollection Columns {get;} DataRow
DataView DefaultView {get;}
bool HasErrors {get;} //----- Properties
DataColumn[] PrimaryKey{get; set;} string DataSetName {get; set;}
DataRowCollection Rows {get;} DataRelationsCollectionRelations {get;}
... DataTableCollectionTables {get;}
* PropertyCollectionExtendedProperties {get;}
Rows string NameSpace {get;}
bool HasErrors {get;}
...
Example: Person Contacts
Concept Realisation as data set

Person Contact DataTable „Person“ DataTable „Contact“


ID ID DataColumn „ID“
DataColumn „ID“
FirstName FirstName
DataColumn „FirstName“ DataColumn „FirstName“

„P ersonHasContacts“
Name Name
DataColumn „Name“

DataRelation
DataColumn „Name“
NickName
DataColumn „NickName“
EMail
DataColumn „EMail“
Phone
DataColumn „Phone“
PersonID
DataColumn „PersonID“
DataSet

Implementation steps:
 Define schema
 Define data
 Access data
DataSet: Change
Management
DataSets maintain all changes
Changes are accepted with
acceptChanges
or discarded with rejectChanges

...
if (ds.HasErrors) {
ds.RejectChanges();
} else {
ds.AcceptChanges();
}
}
Data Adapter
DataAdapter for connectionless connection-oriented
connection to date
ADO.NET Managed
source ADO.NET Content
Components Providers

Fill: Filling the DataSet DataAdapter


Fill
DataSet SelectCommand

Update: Writing back UpdateCommand

changes Update
InsertCommand

DeleteCommand

DataAdapters use IDbConnection

Command objects ReadXml


SelectCommand WriteXml

InsertCommand Database

XML file
DeleteCommand
UpdateCommand Verbindungsloser Datenfluss Verbindungsorientierter Datenfluss
What is new in ADO.NET
 Language-Integrated Query (LINQ)
 Introducing query capabilities directly into the .NET Framework 3.5
programming languages. Query operations are expressed in the
language itself and not as string literals embedded in the application
code.
LINQ to ADO.NET
 LINQ to ADO.NET consists of two separate technologies:
 LINQ to DataSet and LINQ to SQL. 

 The LINQ provider converts the source data into IEnumerable-


based object collections for both querying and updating

 LINQ to DataSet
 Provides LINQ capabilities for disconnected data stored in a DataSet.
 Provides richer, optimized querying over the DataSet

 LINQ to SQL
 Provides a run-time infrastructure for managing relational data as objects.
 Enables you to directly query SQL Server database schemas. 
LINQ to DataSet
 To query over data cached in a DataSet object
 To query over data that has been consolidated
from one or more data sources.
 Builds on and uses the existing ADO.NET 2.0
architecture, and is not meant to replace
ADO.NET 2.0 in application code
 The minimum requirement is a reference to
System.Core.dll and a using directive for
System.Linq. By default, these are supplied if
you create a new Visual C# 2008 project. LINQ
to DataSet also requires a reference to
System.Data.dll, System.Data.Linq and
System.Data.DataSetExtensions.dll
LINQ to SQL
 LINQ to SQL supports queries against an object model that is mapped to the data structures of a Microsoft SQL
Server database without using an intermediate conceptual model.
1. Each table is represented by a separate class, tightly coupling the object model to the database schema.
2. Translates language-integrated queries in the object model into Transact-SQL and sends them to the database for execution.
3. When the database returns the results, LINQ to SQL translates the results back into objects

 LINQ to SQL object model expressed in the programming language of the developer is mapped to the data model of a
relational database. Operations on the data are then conducted according to the object model.
 For example, you do not issue database commands (INSERT) to the database. Instead, you change values and
execute methods within your object model. When you want to query the database or send it changes, LINQ to SQL
translates your requests into the correct SQL commands and sends those commands to the database.
LINQ to SQL

LINQ to SQL Object Model Relational Data Model

Entity class Table


Class member Column
Association Foreign-key relationship
Method Stored Procedure or Function

To create an object model from the metadata of an existing relational


database, you may use the Object Relational Designer in Visual Studio
.NET & COM
INTEROPERABILITY
.NET Interoperability
Why Interoperability?
The .NET platform is new
The Win32 platform is well established
No one wants to start from scratch
Use of existing code in .NET applications
is essential
Interoperability goes both ways
Interoperability Options
 .NET clients can use:
 Win32 COM server objects (RCW)
 Win32 DLL exports (P/Invoke)
 Win32 COM clients can use:
 .NET objects (CCW)
 Win32 clients can use:
 .NET method exports (Inverse P/Invoke)
Interop Basics
 COM ↔ .NET Interoperability is usually called
Com Interop
 COM/Win32 ↔ .NET requires marshaling of
parameters
 COM Interop requires some reconciliation of
COM reference counting and .NET GC
mechanisms
 Interoperability requires some proxy / thunk /
wrapper to be in place (automated)
.NET → COM (RCW)
 RCW – Runtime Callable Wrappers:
.NET wrapper around COM object
 Type library importer (TlbImp.exe) generates an
Interop Assembly
 Delphi 8 & “Diamondback” IDEs do it just as well
 Interop Assemblies have a common naming
convention: Interop.LibraryName.dll
(LibraryName is the type library name, not the
COM server name)
.NET → COM (RCW)

Let’s make an Interop Assembly


.NET → COM (RCW)
Use Primary Interop Assembly if available
Primary Interop Assemblies are provided
and signed by the COM component’s
creator
E.g. adodb.dll for MDAC objects
Microsoft Office XP Primary Interop
Assemblies available from MSDN web site
.NET → COM (RCW)
RCW manages COM object reference
count
COM object is released during RCW
garbage collection
RCW turns HRESULTs into .NET exceptions
.NET → COM (RCW)
 A coclass Foo becomes an RCW FooClass
 Interfaces keep the same name
 An additional interface Foo is generated,
combining the coclass’ default interface and a
helper interface for the default event interface
 An event method Bar from an event interface
IEvents gets turned into a delegate type
IEvents_BarEventHandler.
 These COM events can be hooked up like
normal .NET events
.NET → COM (RCW)
 Early binding:
 Straightforward - get an interface reference from the
construction of the RCW
 Call methods or access properties
 Exposed events can be set up just like normal .NET events
 If the type library importer does not provide
appropriate parameter type marshaling you can
tweak it using creative round tripping
 Little other choice exists
.NET → COM (RCW)
 Late binding:
 This is possible without the Interop Assembly
 Uses reflection to operate
 New instance (CreateOleObject) through:
 System.Type.GetTypeFromProgID
 Activator.CreateInstance
 Current instance (GetActiveOleObject) through:
 Marshal.GetActiveObject

 Methods invoked through


 System.Type.InvokeMember
 Parameters passed in an object array
.NET → COM (RCW)
 Late binding:
 Reference parameters are fiddly
 Overloaded InvokeMember requires single element
array of ParameterModifier
 ParameterModifier is an array of Boolean flags
 Flag is True for reference parameter
 Flag is False for value parameter
COM → .NET (CCW)
 CCW – COM Callable Wrappers:
COM wrapper around .NET object
 Assembly registration utility (RegAsm.exe)
 CCW ensures it will be marked for garbage collection
when external reference count reaches 0
 CCW turns .NET exceptions into HRESULTs
 Assembly must be accessible to CLR:
installed in GAC
resident in application directory (or available for probing)
COM → .NET (CCW)
Late binding simply requires the
assembly to be registered
Late binding uses a ProgID registered by
RegAsm.exe: AssemblyName.ClassName
(e.g. MyAssembly.MyClass)
COM → .NET (CCW)
 Early binding relies on an Interop Type Library:
 use the /tlb option with RegAsm
 use the import wizard in “Diamondback”
 .NET objects may choose to implement a defined
interface or not
 The Guid attribute can be used to give a .NET
interface an IID (traditional Delphi syntax should
also work*)

* And does in “Diamondback”, but not in Delphi 8


COM → .NET (CCW)
 The ClassInterface attribute controls
whether and how an interface will be
manufactured to expose the class:
 AutoDispatch - dispinterface for late binding (the
default)
 AutoDual – for early binding (versioning issues)
interface is class name with _ prefix
 None – IDispatch access only
 Use AutoDual if you have no interface
 Use None if you implement an interface (the suggested
approach to avoid interface versioning issues)
COM → .NET (CCW)
 Importing a Delphi assembly’s Interop Type
Library requires some forethought, due to the
symbols exposed by default
 Use [assembly: ComVisible(False)] and
[ComVisible(True)] to control default visibility
 Early binding from Win32 uses the creator class
in the type library import unit, as usual, or any of
the other standard options
.NET → Win32 (P/Invoke)
 Platform Invocation Service, usually referred to
as Platform Invoke, or simply P/Invoke (or even
PInvoke):
 DllImport attribute (from
System.Runtime.InteropServices) is needed for
routines with text parameters
 Standard Delphi DLL import syntax works
otherwise
 Uses DllImport behind the scenes
 Caveat is string parameters
.NET → Win32 (P/Invoke)
 //Win32
 procedure FooA(Msg: PChar); cdecl;
 begin
 MessageBox(0, Msg, 'Foo',
MB_OK or MB_ICONQUESTION);
 end;

 //.NET
 procedure Foo(const Msg: String);
 ...
 [DllImport('bar.dll',
 EntryPoint = 'FooA',
 CharSet = CharSet.Ansi,
 CallingConvention =
 CallingConvention.Cdecl)]
 procedure Foo(const Msg: String); external;
.NET → Win32 (P/Invoke)
 The big issue with P/Invoke is ensuring the
parameters are marshaled across correctly.
 String parameters are generally catered for with
DllImport.CharSet:
 Ansi
 None
 Unicode
 Auto*

*
uses Ansi on Win9x and Unicode on NT platforms
.NET → Win32 (P/Invoke)
 Use Windows.pas and Delphi.Vcl.Windows.pas as
guidelines for parameter type translation
 MarshalAs parameter attribute from
System.Runtime.InteropServices
 Used to fix parameter marshaling when the
default marshaling is inappropriate
.NET → Win32 (P/Invoke)
 Other issues surround Win32 error codes:
 DllImport.SetLastError
 Marshal.GetLastWin32Error
 GetLastError
 HResult values:
 safecall (Win32 COM)
 DllImport.PreserveSig (.NET)
.NET → Win32 (P/Invoke)
 Performance:
 P/Invoke calls cost ~10 machine instructions
 Cost rises for each extra job (marshaling etc.)
 By default security is on
 UnmanagedCode permission
 SuppressUnmanagedCodeSecurity attribute
omits security check stack walk
.NET → Win32 (P/Invoke)
 New in Delphi “Diamondback”
 Virtual Library Interfaces (VLI) aka Dynamic
PInvoke
 Makes a set of functions implemented in a DLL
look like an interface implemented by an
object
 Uses new overload of Supports
.NET → Win32 (P/Invoke)

Let’s see some VLI


Win32 → .NET methods
 Little known mechanism (Inverse P/Invoke),
primarily discussed in:
 Inside Microsoft .NET IL Assembler, Serge Lidin,
Microsoft Press
 Uses method transition thunks
 Only supported by Managed C++ and IL
 Oh, and Delphi for .NET
Win32 → .NET methods
 Very trivial mechanism in Delphi: managed exports
 Simply use an exports clause as you do in Win32 when
exporting functions from DLLs
 Caveats:
 Must mark the project source as containing unsafe code:
{$UNSAFECODE ON}
 Can only export “global” routines
 Can not export static class methods this way
 Can also be accomplished in other languages
 Much more involved (as indeed it is when exposing Delphi
static class methods)
 Involves creative round-tripping to expose assembly methods
Win32 → .NET methods

 Round-tripping:
 Disassemble a compiled assembly to
an IL source file with the .NET
disassembler: ildasm.exe
 Modify the IL code, or add additional IL
files, possibly to include features not
supported by the original compiler
 Reassemble the IL code with the .NET
assembler: ilasm.exe
Win32 → .NET methods

 Creative round-tripping:
 Disassemble a compiled assembly to
an IL source file with the .NET
disassembler: ildasm.exe
 Modify the IL code, or add additional IL
files, possibly to include features not
supported by the original compiler
 Reassemble the IL code with the .NET
assembler: ilasm.exe
Win32 → .NET methods

Let’s see some round tripping


Win32 → .NET methods
IL modifications to export .NET
methods:
Modify IL manifest:
Modify .corflags directive to cater for XP issue
Declare a v-table fixup table
Declare data space for the v-table fixup table
Modify implementations of methods to
be exported:
Mark each method with the .vtentry and
.export directives
Win32 → .NET methods
 IL file assembly manifest (original):

.module dotNetAssembly.dll
.imagebase 0x00400000
.subsystem 0x00000002
.file alignment 512
.corflags 0x00000001
 IL file assembly manifest (modified):

.module dotNetAssembly.dll
.imagebase 0x00400000
.subsystem 0x00000002
.file alignment 512
.corflags 0x00000002
.data VT_01 = int32[2]
.vtfixup [2] int32
fromunmanaged at VT_01
Win32 → .NET methods
Two IL methods (original):
.method public static void DoSomething(
int32 I) cil managed
{

.maxstack 1
IL_0000: ldarg.0
// rest of code omitted for brevity
} // end of method Unit::DoSomething
.method public static void DoSomethingElse(
[in] string Msg) cil managed
{

.maxstack 1
IL_0000: ldarg.0
// rest of code omitted for brevity
} // end of method Unit::DoSomethingElse
Win32 → .NET methods
Two IL methods (exported):
.method public static void DoSomething(
int32 I) cil managed
{
.vtentry 1:1
.export [1] as DoSomething
.maxstack 1
IL_0000: ldarg.0
// rest of code omitted for brevity
} // end of method Unit::DoSomething
.method public static void DoSomethingElse(
[in] string Msg) cil managed
{
.vtentry 1:2
.export [2] as DoSomethingElse
.maxstack 1
IL_0000: ldarg.0
// rest of code omitted for brevity
} // end of method Unit::DoSomethingElse
Win32 → .NET methods
 Potential maintenance issue: must modify IL
generated from disassembling every built
executable
 Workaround is a utility to automate the process
(perhaps a command-line utility)
 One such utility (almost) is mme.exe (Managed
Method Exporter)*
 mme.exe is actually a simple GUI app
XML
XML - Overview
 XML stands for EXtensible Markup Language
 XML is a markup language much like HTML
 XML was designed to describe data
 XML tags are not predefined. You must define
your own tags
 XML uses a Document Type Definition (DTD) or
an XML Schema to describe the data
 XML with a DTD or XML Schema is designed to be
self-descriptive
 XML is a W3C Recommendation
XML - Overview
 XML was designed to describe data and to focus
on what data is.
 HTML was designed to display data and to focus
on how data looks.
 The tags used to mark up HTML documents and
the structure of HTML documents are predefined.
 XML allows the author to define his own tags and
his own document structure.
Different Kinds of Data
 Structured
 Highly regular, homogeneous structure
 Row sets, Comma delimited files
 Semi-Structured
 Heterogeneous structure
 Sparse Occurrences of data
 De-normalized
 HTML and XML documents
 Unstructured
 Documents/Content
Types of XML documents
 Data-centric
 Regular structure, e.g. Order, Customer, Part
 Fine grained
 Basis for Web-services
 Document-centric
 Irregular structure, e.g. Book, Email, XHTML document
 Coarse grained
 No hard separation between the two document
types
 One document may be a combination of both, e.g. semi-
structured
XML in .NET Framework
 Extensible Markup Language (XML) is a meta-markup
language that provides a format for describing structured
data. XML enables a new generation of Web-based data
viewing and manipulation applications. XML is the universal
language for data on the Web. XML gives developers the
power to deliver structured data from a wide variety of
applications to the desktop for local computation and
presentation.
 System.Xml Namespace has a comprehensive set of XML
classes for parsing, validation, and manipulation of XML data
using readers, writers, and World Wide Web Consortium
(W3C) DOM-compliant components. It also covers XML Path
Language (XPath) queries and Extensible Stylesheet
Language Transformations (XSLT).
XML Classes – A quick view
 The XmlTextReader class provides fast, non-cached, forward only read access to XML data.
 The XmlNodeReader class provides an XmlReader over the given DOM node subtree.
 The XmlValidatingReader class provides DTD, XDR and XSD Schema validation.
 The XmlTextWriter class provides a fast, forward only way of generating XML.
 The XmlDocument class implements the W3C Document Object Model level 1 and 2 Core
 The XmlDataDocument class provides an implementation of an XmlDocument that can be
associated with a DataSet. Structured XML can be viewed and manipulated simultaneously
through the DataSet's relational representation or the XmlDataDocument's tree representation.
 The XPathDocument class provides a fast and performant cache for XML document processing
for XSLT.
 The XPathNavigator class provides a W3C XPath 1.0 data model over a store with a cursor
style model for navigation.
 The XslTransform class is a W3C XSLT 1.0 specification compliant XSLT processor for
transforming XML documents.
 The XmlSchema Object Model classes provide a navigable set of classes which directly reflect
the W3C XSD specification. They provide the ability to programmatically create an XSD schema.
SAX vs XML
 Like the Simple API for XML (SAX) reader, the XmlReader is a forward-only, read-only
cursor. It provides fast, non-cached stream access to the input. It can read a stream or
a document. It allows the user to pull data and skip records of no interest to the
application.
 The big difference lies in the fact that the SAX model is a "push" model, where the
parser pushes events to the application, notifying the application every time a new
node has been read, while applications using XmlReader can pull nodes from the
reader at will..
XML Documents
XmlDocument class
 implements the W3C Document Object Model (DOM) Level 1
Core and the Core DOM Level 2.
 The DOM is an in-memory (cache) tree representation of an
XML document and enables the navigation and editing of this
document.
 Because XmlDocument implements the IXPathNavigable
interface it can also be used as the source document for the
XslTransform class.

XmlDataDocument class
 extends XmlDocument and allows structured data to be stored,
retrieved, and manipulated through a relational DataSet.
 allows components to mix XML and relational views of the
underlying data.
XPath
 The XPathDocument class
 provides a fast, read-only, in-memory representation of an XML
document using the XPath data model.
 The XmlDocument and XPathDocument classes implement the
IXPathNavigable interface and return an XPathNavigator object used
to select, evaluate, navigate, and in some cases, edit the underlying
XML data.
 CreateNavigator method initializes a read-only XPathNavigator object
for navigating through nodes in this XPathDocument.
 The XPathNavigator class
 Availbale in the System.Xml.XPath namespace, it is an abstract class which
defines a cursor model for navigating and editing XML information items as
instances of the XQuery 1.0 and XPath 2.0 Data Model.
 XPathNavigator objects created by XPathDocument objects are read-only
 XPathNavigator objects created by XmlDocument objects can be edited.
 An XPathNavigator object's read-only or editable status is determined using
the CanEdit property of the XPathNavigator class.
XML’s Effect on Relational
Technology
 XML has challenged relational technology in some interesting
ways:
 Representing hierarchy, sparse data, order, schema evolution
 These are all known problems in the relational world; however, XML
is providing unprecedented push

 Relational technology will continue store data for business


 Highly normalized data will continue to exist for efficiency and
flexibility

 Relational technology must and will step up to the needs of


XML… but we need mapping too!
SQL Server 2000: SQLXML
 Microsoft’s Mapping technology (and more…)
 Shipped with SQL Server 2000
 Two subsequent releases have shipped to the Web
 Provides a rich XML view of relational data
 Semi-structured, hierarchical view of flat
relational data
 Two-way view: query and update
 Multiple access mechanisms (HTTP, ADO,
ADO.NET, SOAP)
 Middle-tier and Server side support
Query/Update Technologies
 FOR XML (raw, auto, nested, explicit)
 SQL language extension to retrieve XML instead of rowsets

 XML Views
 Work with your relational database as if it was XML file (through
annotated schema)
 Bulkload
 Shred large XML files into existing tables

 Updategrams
 Update through XML View

 XPath query support


Architecture
XML BCP/SQL
XMLBulkload
SQL update/
insert/ delete
Updategrams
XML
SQL
Annotated XSD Server
Mapping Schemas
SQL
Queries
FOR XML Rowsets
Query

Query Processor FOR XML SQL


XML Queries FOR XML Queries
XPath
Queries
FOR XML
ADO.NET and XML
Controls,
XSL/T, X-Path,
Designers,
etc
Code-gen, etc

DataSet XmlData-
Mapping Document

DataAdapter DataReader
XmlReader
Command
Connection
.NET Data Provider

ADO.NET
The DataSet
and XML
 Loads/saves XML data into/out of DataSet
 Schema can be loaded/saved as XSD
 Schema can be inferred from XML Data
 The DataSet can be associated with an
XmlDataDocument
 Exposes a relational view over structured XML
 According to the DataSet schema
 Allows strong typing, control binding, relational access of
XML data
 Allows XML tools (schema validation, XSL/T, XPath queries)
against relational data
 Preserves full fidelity of XML Document
Dataset and XML

// Load DataSet with XML


DataSet ds = new DataSet();
ds.ReadXml("inventory.xml");

// Add a record to the Inventory table


DataTable inventory = ds.Tables["Inventory"];
DataRow row = inventory.NewRow();
row["TitleID"]=1;
row["Quantity"]=25;
inventory.Rows.Add(row);

// Write out XML


ds.WriteXml("updatedinventory.xml");
Writing XML Schemas from
DataSet

SqlConnection conn = new


SqlConnection( "server=(local);uid=sa;pwd=;database=pubs"); SqlDataAdapter
da = new SqlDataAdapter( "select * from authors;select * from titleauthor", conn);
DataSet ds = new DataSet("OneMany");

da.TableMappings.Add("Table", "authors");
da.TableMappings.Add("Table1", "titleauthors");
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);

ds.Relations.Add( "au_ta", ds.Tables[0].Columns["au_id"],


ds.Tables[1].Columns["au_id"], true);
ds.Relations[0].Nested = true;
ds.WriteXmlSchema("one_to_many.xsd");
Typed DataSets
 XSD.exe, the XML schema generation tool, is used to generate a
typed DataSet from an XSD schema.
 A typed DataSet is a subclass of System.Data.DataSet in which the
tables that exist in the DataSet are derived by reading the XSD
schema information.
 DataRows, DataTables, and other items are available as strong
types
 Rather than refering DataSet.Tables[0] or
DataSet.Tables["customers"], you code like MyDataSet.Customers.
 Strongly typed variable names can be checked at compile time
rather than causing errors at runtime.
Loading a DataSet through
the XmlDataDocument

XmlDataDocument datadoc = new XmlDataDocument();


datadoc.DataSet.ReadXmlSchema("c:\\authors.xsd");
datadoc.Load ("c:\\authors.xml");
DataSet ds = datadoc.DataSet; // use DataSet as usual
foreach (DataTable t in ds.Tables)
Console.WriteLine( "Table " + t.TableName + " is in dataset");
Creating an
XmlDataDocument from a
DataSet

DataSet ds = new DataSet(); // load the DataSet


SqlDataAdapter da = new SqlDataAdapter( "select * from authors;select * from
titleauthor", "server=localhost;database=pubs;uid=sa");
da.MissingSchemaAction = MissingSchemaAction.AddWithKey; da.Fill(ds); // t
tweak the DataSet schema

ds.Tables[0].TableName = "authors";
ds.Tables[1].TableName = "titleauthor";
ds.Relations.Add( ds.Tables[0].Columns["au_id"], ds.Tables[1].Columns["au_id"]);
ds.Relations[0].Nested = true;

XmlDataDocument dd = new XmlDataDocument(ds); // write the document


dd.Save("c:\\temp\\xmldoc.xml"); // write the dataset
dd.DataSet.WriteXml("c:\\temp\\dataset.xml");
XML Web Service Foundation
Simple, Open, Broad Industry Support

Publish, Find, Use Services: UDDI


Service Description: WSDL
Service Interactions: SOAP
Universal Data Format: XML
Ubiquitous Communications: Internet
CRYSTAL REPORT

Creating standard Report


Inserting fields and using special fields
Sorting data and Grouping data
Creating summary total and grand total
Calling Crystal Report From Vb.Net Application
Creating Sub Reports
Printing Report
Exporting Report
CRYSTAL REPORT

Demo
 Create a report based on single table
 Create a report based on multiple table