Winforms & Ado

Embed Size (px)

Citation preview

  • 8/8/2019 Winforms & Ado

    1/149

    WINFORMS

    ByBalamurali Balaji

    Microsoft MVP

  • 8/8/2019 Winforms & Ado

    2/149

    What Are Windows Forms?

    Screen real estate graphical element thatappears 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 GraphicalUser Interface

    Are standard windows, multiple documentinterface (MDI) windows, dialog boxes

    Are objects withProperties which define their appearance

    Methods which define their behaviorEvents which define their interaction with users

  • 8/8/2019 Winforms & Ado

    3/149

    What Are Windows Forms?(cont)Forms are instances of classesLike all objects in the .NET Framework

    Forms are controls

    Inherit from the Control classCreate them viaWindows Forms Designer (easier)Code Designer (harder)

  • 8/8/2019 Winforms & Ado

    4/149

    Windows Forms Features

    Simplicity and powerProgramming model for developing Windows applications

    quickly (RAD)Rich graphics

    Windows Graphical Device Interface Plus (GDI+) thatsupports alpha blending, texture brushes, advancedtransforms, rich text support, and more.

    Flexible controlsRich set of controls that encompass all of the controls

    offered by Windows.

    Data awarenessWindows Forms offers full support for the ADO.NET data

    model (discussed further in later weeks)

  • 8/8/2019 Winforms & Ado

    5/149

    Windows Forms Features(cont)

    ActiveX control supportEasily host ActiveX controls in a Windows Forms

    application.

    Printingprinting framework for comprehensive reports.

    AccessibilityCan build applications that support accessibility

    aids, such as screen readers.

  • 8/8/2019 Winforms & Ado

    6/149

    A Windows Form

    ButtonsButtons

    MenusMenus LabelsLabels TextboxesTextboxes

  • 8/8/2019 Winforms & Ado

    7/149

    WinForms ApplicationsTypical forms-application designOne or more classes derived from

    System.Windows.FormDerived classes affect instance appearance and

    behavior by setting propertiesDerived classes create objects to implement GUI

    controlsButtons, text boxes, menus, timers, custom controls,

    etc.Derived classes implement methods to handle

    GUI eventsButtons clicks, menu selections, mouse movements,timer events, etc.

    Default behavior implemented by base classes

  • 8/8/2019 Winforms & Ado

    8/149

    Creating Windows Forms

    Typical forms-application threadingA single thread dedicated to UIRuns the message pumpCan do other things, but blocks only briefly (or never)

    Background or pooled threads used for lengthynon-UI functionality

    Typical forms-applications developmentAlso use classes in System.Drawing namespace

    Design UI with VisualStudio .NETPossible to do anything directly via code

  • 8/8/2019 Winforms & Ado

    9/149

    WinForms ObjectsThe Application ObjectUsed to process Window messages

    Start and Stop Applications and Threads

    The Form Object

    Representation of the Windows displayedCan 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

  • 8/8/2019 Winforms & Ado

    10/149

    Control Class

    Base-class for all controls/forms in managed codeWraps an underlying OS window handle

    Implements manyPublic Methods for performing actions on an instanceShow(), Hide(), Invalidate(), etc.

    Properties for modifying settings of an instanceSize, BackColor, ContextMenu, etc.

    Derived classes override and specializefunctionalitySpecialized methods, properties, and eventsTextBox PasswordChar, Undo(), Copy()

    Button Image, PerformClick()The Form class is derived from Control

    Instances of Control can contain child controls

  • 8/8/2019 Winforms & Ado

    11/149

    Form Class

    A specialized derivation of Control used toimplement a top-level window or dialog

    Gains much of its functionality from baseclasses

    Specialized to

    Manage dialog buttonsContain a main menuContain a title-bar, system menu, minimize/maximizeImplement MDIEtc.

    Your applications derive from Form to createWindowsDialog boxes

  • 8/8/2019 Winforms & Ado

    12/149

    Using ControlsCreate 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!");

    }

    }

  • 8/8/2019 Winforms & Ado

    13/149

    Setting Control Properties

    Set at runtime or design time

  • 8/8/2019 Winforms & Ado

    14/149

    Event HandlingResponse to user interactionA user presses a button then what?

    We must deal with their interaction

    Double clicking a control at design time allowsmodification the default event hander code.

    Winforms/GUIs are event driven and theygenerate events which we can use

  • 8/8/2019 Winforms & Ado

    15/149

    Typical User InteractionsMoving or clicking a mouseClicking a button

    Typing in a textbox

    Selecting a menu itemClosing a window

    All of these generate eventsWe handle the events generated by the .netcontrolsNo need to create our own

  • 8/8/2019 Winforms & Ado

    16/149

    Event Handling in VS.netHighlight the control

    you wish to handle anevent for

    Click on the events

    button in PropertiesDouble-click the event

    you want to handlewhen it is generated atruntime

    Add required code in thecode designer

  • 8/8/2019 Winforms & Ado

    17/149

    Event HandlerPassed two object referencesSender reference to the object which raised the

    eventEventArgs - base class for classes containing

    event dataRemember VS does a lot of this for you

    private void controlName_EventName(object sender,System.EventArgs e){

    // code to handle event}

  • 8/8/2019 Winforms & Ado

    18/149

    Button Control Abstract base class:

    ButtonBase

    Common events ClickRaised when user

    clicks the buttoncontrol. Default eventin VS.Net

    Common properties TextThe text displayed on

    the button

    private void cmdColour_Click(objectsender, System.EventArgs e)

    {

    // do something

    }

  • 8/8/2019 Winforms & Ado

    19/149

    Working with MenusMainMenu, ContextMenu, and MenuItem are derived

    from MenuMenu includes a collection of MenuItems

    Create a MainMenu (or ContextMenu)Use constructor parameters to set the text and

    other detailsAdd MenuItems to the MainMenuCan add sub-MenuItemsRegister event handlers

    Set Forms Menu property to the instance of theMainMenu

    Or just use Visual Studio

  • 8/8/2019 Winforms & Ado

    20/149

    Adding Menus

    // Create a menuMainMenu menu = newMainMenu();MenuItem item =menu.MenuItems.Add("&File");

    item.MenuItems.Add(new MenuItem("E&xit", new

    EventHandler(OnExit)));

    // Attach the menu to theform

    this.Menu = menu;

  • 8/8/2019 Winforms & Ado

    21/149

    Dialog BoxesUse 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

  • 8/8/2019 Winforms & Ado

    22/149

    Dialog Boxes (cont)// simpleMessageBox.Show("Hi, The title);

    // colour dialog (color)

    ColorDialog cd = new ColorDialog();

    cd.ShowDialog();

    // Print

    PrintDialog pd = new PrintDialog();

    pd.PrinterSettings = newPrinterSettings()

    pd.ShowDialog();

    // Font

    FontDialog fd = new FontDialog();

    fd.ShowDialog()

    // Open FileOpenFileDialog ofd = new

    OpenFileDialog();

    ofd.ShowDialog();

    // Save FileSaveFileDialog sfd = new

    SaveFileDialog();

    sfd.ShowDialog();

    // Folder Browser

    FolderBrowserDialog fbd = new

    FolderBrowserDialog();

    fbd.ShowDialog();

  • 8/8/2019 Winforms & Ado

    23/149

    Dialog Boxes (cont)

  • 8/8/2019 Winforms & Ado

    24/149

    Custom Dialog Boxesprivate void cmdClose_Click(object sender,

    System.EventArgs e)

    {

    MessageBoxButtons buttons =MessageBoxButtons.YesNo;

    DialogResult result = MessageBox.Show(this, "Do youreally want to close the app?","Close App?" , buttons,MessageBoxIcon.Question,

    MessageBoxDefaultButton.Button1,MessageBoxOptions.RightAlign);

    if(result == DialogResult.Yes)

    Application.Exit();

    }

  • 8/8/2019 Winforms & Ado

    25/149

    Using ControlsButtonsText Controls

    List Controls

    MenusCommon Dialogs

    More controls

  • 8/8/2019 Winforms & Ado

    26/149

    Common Control PropertiesAll controls inherit from the class ControlThus, they have some common properties and

    methods

    PropertiesBackcolor, Enabled, Font, TabIndex, TabStop,

    Visible

    MethodsHide(), Show()

  • 8/8/2019 Winforms & Ado

    27/149

    TextBox Area for text input

    from user

    Has provision forPassword handling

    PropertiesMultiline, PasswordChar

    (*), Readonly, Text

    Events

    TextChanged (defaultevent in VS.net)

  • 8/8/2019 Winforms & Ado

    28/149

    RichTextBox

    Has similar propertiesand events to TextBox

    Advanced formatting

    HoweverDetectUrlslinkClicked eventOpening and saving files

    via LoadFile(), SaveFile()

  • 8/8/2019 Winforms & Ado

    29/149

    CheckBox

    Multiple optionstrue/false or yes/no

    EventCheckedChanged

    when check box isclicked

    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);

    }

  • 8/8/2019 Winforms & Ado

    30/149

    RadioButton

    Allow a user to choosefrom mutuallyexclusive optionsAs opposed to the

    checkBoxEventCheckedChanged when

    a radio button is clicked

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

    {

    this.lblColour.ForeColor = Color.Green;

    this.lblColour.Text = "GO!";

    }

  • 8/8/2019 Winforms & Ado

    31/149

    TreeViewsDisplays Node hierarchically on a treeNodes are objects that refer to other nodes

    Parent node has child nodes which can alsohave child nodes

  • 8/8/2019 Winforms & Ado

    32/149

    LabelsSimple way of adding

    text to a form

    Typically used toprovide descriptive

    text for a controlSet text at runtime

    (no need for event)

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

    {

    this.label1.Text = "You selected RED!";

    }

  • 8/8/2019 Winforms & Ado

    33/149

    PictureBox

    Used to displaygraphicsBitmap, metafile, icon,JPEG, GIF or PNG filesupport

    Image property allowsthe setting of theimage either at designtime or at run time.

    Clipping andpositioning through the

    SizeMode property

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

  • 8/8/2019 Winforms & Ado

    34/149

    LinkLabel

    Similar to a Label controlexcept it can display ahyperlink

    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());

    }

  • 8/8/2019 Winforms & Ado

    35/149

    ListBoxDisplays a list of itemsSelect by clicking

    Single or multipleselections using theSelectionmode 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());

    }

  • 8/8/2019 Winforms & Ado

    36/149

  • 8/8/2019 Winforms & Ado

    37/149

  • 8/8/2019 Winforms & Ado

    38/149

    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

  • 8/8/2019 Winforms & Ado

    39/149

    MDI Applications (example)

  • 8/8/2019 Winforms & Ado

    40/149

  • 8/8/2019 Winforms & Ado

    41/149

  • 8/8/2019 Winforms & Ado

    42/149

    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

  • 8/8/2019 Winforms & Ado

    43/149

    Miscellaneous

    ActiveX ControlsUsable through wrappersUsage like other controls

    Related classesKeysCursorsSystem Information

  • 8/8/2019 Winforms & Ado

    44/149

    Windows Forms Toolbox

  • 8/8/2019 Winforms & Ado

    45/149

    SummaryWindows Forms?Control ClassSetting Control Properties

    Event HandlingButton Control

    Working with MenusDialog BoxesUsing ControlsCommon Control Properties

    Multiple Document Interface (MDI)Common Dialogs

  • 8/8/2019 Winforms & Ado

    46/149

    ACCESSING DATA WTHADO.NET

  • 8/8/2019 Winforms & Ado

    47/149

    ADO.NETIs the .NET technology for accessing

    structured dataUniform object oriented interface for

    different data sources

    relational data basesXML dataother data sources

    Designed for distributed and Web

    applicationsProvides 2 models for data accessconnection-oriented

    connectionless

    Connection-oriented Vs Connection-

  • 8/8/2019 Winforms & Ado

    48/149

    Connection oriented Vs Connectionless

    Connection-orientedKeeps the connection to the data base aliveIntended for applications with:short running transactions

    only a few parallel accesses

    up-to-date data

    ConnectionlessNo permanent connection to the data source

    Data cached in main memory

    Changes in main memory changes in data sourceIntended for applications with:many parallel and long lasting accesses (e.g.: web applications)

  • 8/8/2019 Winforms & Ado

    49/149

    Universal Data Access

    Connection of (object-oriented)programming languages and relationaldata bases

    Uniform programming model and API

    Special implementations for data sources(providers)

    A

    PI

    Provider

    ODBC

    MsSql

    DB2

    OracleApplication

    ?

  • 8/8/2019 Winforms & Ado

    50/149

    Data Providers

    Microsofts layered architecture for dataaccess

    SQL-data

    MS SQL Server, Oracle,

    Jet, Foxpro, ...

    SQL Server

    Oracle

    MySQL

    ODBC

    Non-SQL-data

    Directory Services, Mail,

    Text, Video, ...

    OLEDB

    ADO.NET

    ADO N t P id

  • 8/8/2019 Winforms & Ado

    51/149

    ADO.Net Providers

    Driver Provider

    SQLOLEDB Microsoft OLE DB provider for SQLServer

    MSDAORA Microsoft OLE DB provider for Oracle

    Microsoft.Jet.OLEDB.4.0 OLE DB provider for Microsoft Jet

  • 8/8/2019 Winforms & Ado

    52/149

    P id I d d API

  • 8/8/2019 Winforms & Ado

    53/149

    Provider Independent API

    example APINameSpace=System.Data.SQLClient

    Public Function GetDS(byVal APINameSpace as String)as DataSetDim 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

    Database Independent Coding

    System.Data.Common Namespace

    Provider Factory Class

  • 8/8/2019 Winforms & Ado

    54/149

    Connection String Builders

  • 8/8/2019 Winforms & Ado

    55/149

    Architecture of ADO.NET

    D a t a b a s e

    C o n n e c t i o n -o r ie n t e d d a t a f l o w

    A D O .N E T M ana ge d P rov ide rs

    D at a

    A dap te r

    C o n n e c t i o n

    D a taR eade r

    C om m an d

    T rans ac t ion

    ADO.NET Content Components

    XML file

    Connectionless data flow

    DataSet

    Tables

    Relations

    DataTable

    ReadXmlWriteXml

    DataTable DataRelation

    Update

    Fill

    connection-orientedconnectionless

    ADO Net object model

  • 8/8/2019 Winforms & Ado

    56/149

    ADO.Net object model

    DataAdapter

    Command

    DataSet

    Errors Collection

    Connection Parameters

    Data Source

    Fill

    Update

    Se

    lec

    tCo

    mman

    d

    Insert

    Co

    mman

    d

    Up

    dat

    eC

    omman

    d

    De

    lete

    Co

    mman

    d

    ADO NET and XML

  • 8/8/2019 Winforms & Ado

    57/149

    .NET Data Provider

    DataReader

    Command

    Connection

    Mapping

    ADO.NET and XML

    Controls,

    Designers,Code-gen, etc

    DataSet

    XmlReader

    XSL/T, X-Path,

    etc

    XmlData-

    Document

    DataAdapter

    ADO NET d XML

  • 8/8/2019 Winforms & Ado

    58/149

    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 anXmlDataDocument

    Exposes a relational view over structured XML According to the DataSet schema

    Allows strong typing, control binding, relational access ofXML data

    Allows XML tools (schema validation, XSL/T, XPath queries)

    against relational data Preserves full fidelity of XML Document

  • 8/8/2019 Winforms & Ado

    59/149

    Dataset and XML

    // Load DataSet with XMLDataSet ds = new DataSet();ds.ReadXml("inventory.xml");

    // Add a record to the Inventory tableDataTable inventory = ds.Tables["Inventory"];DataRow row = inventory.NewRow();row["TitleID"]=1;row["Quantity"]=25;

    inventory.Rows.Add(row);

    // Write out XMLds.WriteXml("updatedinventory.xml");

    Writing XML Schemas from

  • 8/8/2019 Winforms & Ado

    60/149

    Writing XML Schemas fromDataSet

    SqlConnection conn = newSqlConnection( "server=(local);uid=sa;pwd=;database=pubs"); SqlDataAdapterda = 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");

  • 8/8/2019 Winforms & Ado

    61/149

    Typed DataSets

    XSD.exe, the XML schema generation tool, is used to generate a

    typedDataSet 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

  • 8/8/2019 Winforms & Ado

    62/149

    Loading a DataSet throughthe 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");

    XmlDataDocument from a

  • 8/8/2019 Winforms & Ado

    63/149

    XmlDataDocument from aDataSet

    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 A bl d

  • 8/8/2019 Winforms & Ado

    64/149

    ADO.NET Assembly andNamespaces

    Assembly: System.Data.dllNamespaces:

    System.Data general data types

    System.Data.Common classes for implementing providersSystem.Data.OleDb OLE DB providerSystem.Data.SqlClient Microsoft SQL Server providerSystem.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

    AD .NET Assem y an

  • 8/8/2019 Winforms & Ado

    65/149

    yNamespaces

    Assembly: System.Data.dll

    Namespaces:

    System.Data general data types

    System.Data.Common classes for implementing providers

    System.Data.OleDb OLE DB providerSystem.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

    xamp e: or w n

  • 8/8/2019 Winforms & Ado

    66/149

    pDatabase

    Microsoft Example for SQL Server

    Reading of the table Employees

    Output of

    EmployeesID, LastName, FirstName

    for all rows of table Employees

    Run

    Connection-oriented Data

    http://../Folien_DE/SAMPLES/5-3-EmplReader.exehttp://../Folien_DE/SAMPLES/5-3-EmplReader.exe
  • 8/8/2019 Winforms & Ado

    67/149

    Connection-oriented DataAccess

    1.) Declare the connectiontry {

    1.) Request connection to database

    3.) Process result

    2.) Execute SQL statements

    4.) Release Resources

    } catch( Exception ) {

    Handle exception

    } finally {

    try {

    4.) Close connection

    } catch(Exception)

    { Handle exception }

    }

    Example: EmployeeReader (1)

  • 8/8/2019 Winforms & Ado

    68/149

    Example: EmployeeReader (1)

    using System;

    using System.Data;

    using System.Data.OleDb;

    publicclass EmployeeReader {

    publicstaticvoid Main() {

    // continue next page

    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

    Establish connection

    //----- 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();

    Execute command

  • 8/8/2019 Winforms & Ado

    69/149

    Connection

  • 8/8/2019 Winforms & Ado

    70/149

    Connection

    define data base connection

    Open and close connection

    Properties of connection object

    Creates Command-Object

    Creates Transaction-Object

    string ConnectionString {get; set;}

    string Database {get;}

    int ConnectionTimeout {get;}

    ConnectionState State {get;}

    Command CreateCommand();

    ITransaction BeginTransaction();

    Transaction BeginTransaction(IsolationLevel lvl);

    voidClose();

    void Open();

  • 8/8/2019 Winforms & Ado

    71/149

    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;datasource=c:\bin\LocalAccess40.mdb;"

    "provider=MSDAORA; data source=ORACLE8i7; userid=OLEDB; password=OLEDB;"

  • 8/8/2019 Winforms & Ado

    72/149

  • 8/8/2019 Winforms & Ado

    73/149

    cmd.CommandText =

    "SELECT EmployeeID, LastName, FirstName FROM Employees ";

    DataReader reader = cmd.ExecuteReader();

    ExecuteReader Method

    Executes the data base query specified in CommandText

    Result is an DataReader object

    DataReaderExecuteReader()

    DataReaderExecuteReader( CommandBehavior behavior );

    public enumCommandBehavior{

    CloseConnection, Default, KeyInfo, SchemaOnly,

    SequentialAccess, SingleResult, SingleRow

    }

    Example:

  • 8/8/2019 Winforms & Ado

    74/149

    ExecuteScalar Method

  • 8/8/2019 Winforms & Ado

    75/149

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

    int count = (int) cmd.ExecuteScalar();

    ExecuteScalar Method

    Returns the value of the 1st column of the 1st rowdelivered by the database query

    CommandText typically is an aggregate function

    object ExecuteScalar();

    Example:

    P t

  • 8/8/2019 Winforms & Ado

    76/149

    Parameter

    Command objects allow for input andoutput parameters

    Parameter objects specifyName: name of the parameter

    Value: value of the parameterDataType: data type of the

    parameterDirection: direction of the

    parameter

    InputOutput

    InputOutput

    ReturnValue

    IDbCommand

    IDataParameter

    IDbDataParameter

    //----- Properties

    DbTypeDbType {get; set;}ParameterDirection Direction {get; set;}

    string ParamterName {get; set;}

    object Value {get; set;}

    ...

    //----- Properties

    int Size {get; set;}...

    Parameters *

    ...

    IDataParameterCollectionParameters {get;}

    ...

    Working with Parameters

  • 8/8/2019 Winforms & Ado

    77/149

    Working with Parameters

    Define SQL command with place holdersOLEDB: 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

  • 8/8/2019 Winforms & Ado

    78/149

    DataReader

    ExecuteReader() returns DataReaderobject

    DataReader allows sequential reading ofresult (row by row)

    bool Read()A B C

    Result table of a SELECT statement

    Result table of a SELECT statement

    DataReaderExecuteReader()

    DataReaderExecuteReader( CommandBehavior behavior );

    D t R d

  • 8/8/2019 Winforms & Ado

    79/149

    DataReader

    Read reads next rowbool Read();

    Access to column values using indexers

    objectthis[int] {get;}

    objectthis[string] {get;}

    Typed access to column values using access methods

    boolGetBoolean(int idx);

    byte GetByte(int idx);

    ...

    Getting meta information

    stringGetDataTypeName(int i);

    stringGetName(int idx);

    intGetOrdinal(string name);

    ...

    DataSet

  • 8/8/2019 Winforms & Ado

    80/149

    Main memory data baserelational structureobject oriented interface

    DataSet consists ofcollection of DataTablescollection of DataRelations

    DataTables consists ofcollection of DataTableColumns (= schema

    definition)collection of DataTableRows (= data)DefaultView (DataTableView, see later)

    DataRelationsassociate two DataTable objectsdefine ParentTable and ParentColumns

    and ChildTable and ChildColumns

  • 8/8/2019 Winforms & Ado

    81/149

    DataSet

    .Tables[...]

    .Relations[...]

    ...

    DataSet Structure

    DataTable

    .Columns[..]

    .Rows[..]

    DataTable

    .Columns[...]

    .Rows[...]

    .DefaultView

    ...

    DataRow

    DataRowdata

    DataColumn

    schema

    DataColumn

    DataView

    DataRelationDataRelation

  • 8/8/2019 Winforms & Ado

    82/149

    DataSet Class Diagram

    DataSet

    Transaction 1

    //----- PropertiesstringDataSetName {get; set;}DataRelationsCollectionRelations {get;}DataTableCollectionTables {get;}PropertyCollection ExtendedProperties{get;}stringNameSpace{get;}boolHasErrors {get;}

    ...

    DataTable

    //----- PropertiesstringTableName {get;}DataRelationsCollectionChildRelations {get;}DataRelationsCollectionParentRelations {get;}ConstraintCollectionConstraints{get;}

    DataColumnCollectionColumns{get;}DataViewDefaultView {get;}boolHasErrors{get;}DataColumn[]PrimaryKey{get; set;}DataRowCollectionRows{get;}...

    * Tables

    DataColumn

    //----- PropertiesboolAllowDBNull {get; set;}boolAutoIncrement {get; set;}intAutoIncrementSeed {get; set;}intAutoIncrementStep {get; set;}stringColumnName{get; set;}TypeDataType {get; set;}stringExpression{get; set;}boolReadOnly{get; set;}boolUnique{get; set;}...

    Columns*

    DataRow

    //----- PropertiesstringDataSetName {get; set;}DataRelationsCollectionRelations {get;}DataTableCollectionTables {get;}PropertyCollectionExtendedProperties{get;}stringNameSpace {get;}bool HasErrors {get;}

    ...

    *Rows

    DataRelation

    //----- PropertiesstringRelationName{get; set;}DataTableParentTable{get;}DataColumn[]ParentColumns{get;}DataTableChildTable{get;}DataColumn[]ChildColumns{get;}...

    Relations

    *

    ParentRelations*

    ChildRelations*

    *

    ParentColumns

    *ChildColumns

  • 8/8/2019 Winforms & Ado

    83/149

    Example: Person Contacts

    Implementation steps:Define schemaDefine dataAccess data

    Person

    ID

    FirstName

    Name

    Contact

    ID

    FirstName

    Name

    NickName

    Phone

    EMail

    PersonID

    Concept Realisation as data set

    DataSet

    Dat

    aRelation

    Person

    HasContacts

    DataTable Person

    DataColumn ID

    DataColumn FirstName

    DataColumn Name

    DataTable Contact

    DataColumn ID

    DataColumn FirstName

    DataColumn Name

    DataColumn NickName

    DataColumn EMail

    DataColumn Phone

    DataColumn PersonID

    DataSet: Change

  • 8/8/2019 Winforms & Ado

    84/149

    DataSet: ChangeManagement

    DataSets maintain all changesChanges are accepted with

    acceptChanges

    or discarded with rejectChanges

    ...

    if(ds.HasErrors) {

    ds.RejectChanges();

    } else {ds.AcceptChanges();

    }

    }

  • 8/8/2019 Winforms & Ado

    85/149

    Data AdapterDataAdapter forconnection to datesource

    Fill: Filling theDataSet

    Update: Writing backchanges

    DataAdapters use

    Command objectsSelectCommand

    InsertCommand

    DeleteCommand

    UpdateCommand

    connection-orientedconnectionless

    ADO.NET Content

    Components

    Database

    XML file

    Verbindungsloser Datenfluss Verbindungsorientierter Datenfluss

    DataSet

    ReadXmlWriteXml

    ADO.NET Managed

    Providers

    DataAdapter

    IDbConnection

    Update

    Fill

    DeleteCommand

    UpdateCommand

    InsertCommand

    SelectCommand

    What is new in ADO NET

  • 8/8/2019 Winforms & Ado

    86/149

    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 thelanguage itself and not as string literals embedded in the applicationcode.

    LINQ t ADO NET

  • 8/8/2019 Winforms & Ado

    87/149

    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.

  • 8/8/2019 Winforms & Ado

    88/149

    LINQ to DataSet

    To query over data cached in a DataSet object

    To query over data that has been consolidatedfrom one or more data sources.

    Builds on and uses the existing ADO.NET 2.0architecture, and is not meant to replaceADO.NET 2.0 in application code

    The minimum requirement is a reference toSystem.Core.dll and a using directive forSystem.Linq. By default, these are supplied ifyou create a new Visual C# 2008 project. LINQto DataSet also requires a reference toSystem.Data.dll, System.Data.Linq and

    System.Data.DataSetExtensions.dll

  • 8/8/2019 Winforms & Ado

    89/149

    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 arelational 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 andexecute methods within your object model. When you want to query the database or send it changes, LINQ to SQLtranslates your requests into the correct SQL commands and sends those commands to the database.

  • 8/8/2019 Winforms & Ado

    90/149

    LINQ to SQL

    LINQ to SQL Object Model Relational Data Model

    Entity class Table

    Class member Column

    Association Foreign-key relationshipMethod 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

  • 8/8/2019 Winforms & Ado

    91/149

    .NET & COMINTEROPERABILITY

  • 8/8/2019 Winforms & Ado

    92/149

    .NET Interoperability

    Why Interoperability?The .NET platform is new

    The Win32 platform is well established

    No one wants to start from scratchUse of existing code in .NET applications

    is essential

    Interoperability goes both ways

  • 8/8/2019 Winforms & Ado

    93/149

    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)

  • 8/8/2019 Winforms & Ado

    94/149

    Interop Basics

    COM .NET Interoperability is usually calledCom Interop

    COM/Win32 .NET requires marshaling of

    parametersCOM Interop requires some reconciliation of

    COM reference counting and .NET GCmechanisms

    Interoperability requires some proxy / thunk /wrapper to be in place (automated)

  • 8/8/2019 Winforms & Ado

    95/149

    .NET COM (RCW)

    RCW Runtime Callable Wrappers:.NET wrapper around COM object

    Type library importer (TlbImp.exe) generates an

    Interop AssemblyDelphi 8 & Diamondback IDEs do it just as well

    Interop Assemblies have a common namingconvention: Interop.LibraryName.dll(LibraryName is the type library name, not theCOM server name)

  • 8/8/2019 Winforms & Ado

    96/149

    .NET COM (RCW)

    Lets make an Interop Assembly

  • 8/8/2019 Winforms & Ado

    97/149

    .NET COM (RCW)

    Use Primary Interop Assemblyif available

    Primary Interop Assemblies are providedand signed by the COM components

    creatorE.g. adodb.dll for MDAC objects

    Microsoft Office XP Primary Interop

    Assemblies available from MSDN web site

  • 8/8/2019 Winforms & Ado

    98/149

    .NET COM (RCW)

    RCW manages COM object referencecount

    COM object is released during RCW

    garbage collectionRCW turns HRESULTs into .NET exceptions

  • 8/8/2019 Winforms & Ado

    99/149

    .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 ahelper interface for the default event interface

    An event method Bar from an event interfaceIEvents gets turned into a delegate type

    IEvents_BarEventHandler.These COM events can be hooked up like

    normal .NET events

    ( )

  • 8/8/2019 Winforms & Ado

    100/149

    .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 provideappropriate parameter type marshaling you cantweak it using creative round tripping

    Little other choice exists

    CO ( C )

  • 8/8/2019 Winforms & Ado

    101/149

    .NET COM (RCW)

    Late binding:This is possible withoutthe Interop Assembly

    Uses reflection to operate

    New instance (CreateOleObject) through:

    System.Type.GetTypeFromProgIDActivator.CreateInstance

    Current instance (GetActiveOleObject) through:Marshal.GetActiveObject

    Methods invoked through

    System.Type.InvokeMember

    Parameters passed in an object array

    NET COM (RCW)

  • 8/8/2019 Winforms & Ado

    102/149

    .NET COM (RCW)

    Late binding:Reference parameters are fiddly

    Overloaded InvokeMember requires single elementarray ofParameterModifier

    ParameterModifier is an array of Boolean flagsFlag is True for reference parameterFlag is False for value parameter

  • 8/8/2019 Winforms & Ado

    103/149

    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 0CCW turns .NET exceptions into HRESULTsAssembly must be accessible to CLR:installed in GACresident in application directory (or available for probing)

  • 8/8/2019 Winforms & Ado

    104/149

    COM .NET (CCW)

    Late binding simply requires theassembly to be registered

    Late binding uses a ProgID registered by

    RegAsm.exe:AssemblyName.ClassName(e.g. MyAssembly.MyClass)

    ( )

  • 8/8/2019 Winforms & Ado

    105/149

    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 definedinterface or not

    The Guid attribute can be used to give a .NETinterface an IID (traditional Delphi syntax shouldalso work*)

    * And does in Diamondback, but notin Delphi 8

    CO (CC )

  • 8/8/2019 Winforms & Ado

    106/149

    COM .NET (CCW)

    The ClassInterface attribute controlswhether and how an interface will bemanufactured 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 suggestedapproach to avoid interface versioning issues)

    COM NET (CCW)

  • 8/8/2019 Winforms & Ado

    107/149

    COM .NET (CCW)

    Importing a Delphi assemblys Interop TypeLibrary requires some forethought, due to thesymbols exposed by default

    Use[assembly: ComVisible(False)]

    and[ComVisible(True)] to control default visibility

    Early binding from Win32 uses the creator classin the type library import unit, as usual, or any ofthe other standard options

  • 8/8/2019 Winforms & Ado

    108/149

  • 8/8/2019 Winforms & Ado

    109/149

    NET Wi 32 (P/I k )

  • 8/8/2019 Winforms & Ado

    110/149

    .NET Win32 (P/Invoke)

    The big issue with P/Invoke is ensuring theparameters 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 Wi 32 (P/I k )

  • 8/8/2019 Winforms & Ado

    111/149

    .NET Win32 (P/Invoke)

    Use Windows.pas and Delphi.Vcl.Windows.pas asguidelines for parameter type translation

    MarshalAs parameter attribute fromSystem.Runtime.InteropServices

    Used to fix parameter marshaling when thedefault marshaling is inappropriate

    NET Win32 (P/Invoke)

  • 8/8/2019 Winforms & Ado

    112/149

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

  • 8/8/2019 Winforms & Ado

    113/149

    .NET Win32 (P/Invoke)

    Performance:

    P/Invoke calls cost ~10 machine instructions

    Cost rises for each extra job (marshaling etc.)

    By default security is onUnmanagedCode permission

    SuppressUnmanagedCodeSecurity attributeomits security check stack walk

    NET Win32 (P/Invoke)

  • 8/8/2019 Winforms & Ado

    114/149

    .NET Win32 (P/Invoke)

    New in Delphi Diamondback

    Virtual Library Interfaces (VLI) aka DynamicPInvoke

    Makes a set of functions implemented in a DLLlook like an interface implemented by anobject

    Uses new overload ofSupports

    NET Win32 (P/Invoke)

  • 8/8/2019 Winforms & Ado

    115/149

    .NET Win32 (P/Invoke)

    Lets see some VLI

    Win32 NET methods

  • 8/8/2019 Winforms & Ado

    116/149

    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

  • 8/8/2019 Winforms & Ado

    117/149

    Win32 .NET methods

    Very trivial mechanism in Delphi: managed exports

    Simply use an exports clause as you do in Win32 whenexporting functions from DLLs

    Caveats: Must mark the project source as containing unsafe code:

    {$UNSAFECODE ON} Can only export global routines Can notexport static class methods this way

    Can also be accomplished in other languages

    Much more involved (as indeed it is when exposing Delphistatic class methods)

    Involves creative round-tripping to expose assembly methods

    Win32 NET methods

  • 8/8/2019 Winforms & Ado

    118/149

    Win32 .NET methods

    Round-tripping:

    Disassemble a compiled assembly toan 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

  • 8/8/2019 Winforms & Ado

    119/149

    Win32 .NET methods

    Creative round-tripping:

    Disassemble a compiled assembly toan 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

  • 8/8/2019 Winforms & Ado

    120/149

    Win32 .NET methods

    Lets see some round tripping

    Win32 NET methods

  • 8/8/2019 Winforms & Ado

    121/149

    Win32 .NET methods

    IL modifications to export .NETmethods:Modify IL manifest:

    Modify .corflags directive to cater for XP issueDeclare a v-table fixup tableDeclare data space for the v-table fixup table

    Modify implementations of methods tobe exported:Mark each method with the .vtentry and.export directives

    Win32 NET methods

  • 8/8/2019 Winforms & Ado

    122/149

    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] int32fromunmanaged at VT_01

  • 8/8/2019 Winforms & Ado

    123/149

    Win32 NET methods

  • 8/8/2019 Winforms & Ado

    124/149

    Win32 .NET methods

    Two IL methods (exported):

    .method public static void DoSomething(int32 I) cil managed

    { .vtentry 1:1.export [1] as DoSomething.maxstack 1IL_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 1IL_0000: ldarg.0// rest of code omitted for brevity

    } // end of method Unit::DoSomethingElse

    Win32 NET methods

  • 8/8/2019 Winforms & Ado

    125/149

    Win32 .NET methods

    Potential maintenance issue: must modify ILgenerated from disassembling every builtexecutable

    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

  • 8/8/2019 Winforms & Ado

    126/149

    XML

  • 8/8/2019 Winforms & Ado

    127/149

    XML - Overview

  • 8/8/2019 Winforms & Ado

    128/149

    XML was designed to describe data and to focuson what data is.

    HTML was designed to display data and to focuson how data looks.

    The tags used to mark up HTML documents andthe structure of HTML documents are predefined.

    XML allows the author to define his own tags andhis own document structure.

    Different Kinds of Data

  • 8/8/2019 Winforms & Ado

    129/149

    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

  • 8/8/2019 Winforms & Ado

    130/149

    Types of XML documentsData-centricRegular structure, e.g. Order, Customer, PartFine grained

    Basis for Web-services

    Document-centric

    Irregular structure, e.g. Book, Email, XHTML documentCoarse grained

    No hard separation between the two documenttypes

    One document may be a combination of both, e.g. semi-structured

    XML in .NET Framework

  • 8/8/2019 Winforms & Ado

    131/149

    Extensible Markup Language (XML) is a meta-markuplanguage that provides a format for describing structured

    data. XML enables a new generation of Web-based dataviewing and manipulation applications. XML is the universallanguage for data on the Web. XML gives developers thepower to deliver structured data from a wide variety ofapplications 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 datausing readers, writers, and World Wide Web Consortium(W3C) DOM-compliant components. It also covers XML Path

    Language (XPath) queries and Extensible StylesheetLanguage Transformations (XSLT).

    XML Classes A quick view

  • 8/8/2019 Winforms & Ado

    132/149

    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 beassociated with a DataSet. Structured XML can be viewed and manipulated simultaneouslythrough the DataSet's relational representation or the XmlDataDocument's tree representation.

    The XPathDocument class provides a fast and performant cache for XML document processingfor XSLT.

    The XPathNavigator class provides a W3C XPath 1.0 data model over a store with a cursorstyle model for navigation.

    The XslTransform class is a W3C XSLT 1.0 specification compliant XSLT processor fortransforming XML documents.

    The XmlSchema Object Model classes provide a navigable set of classes which directly reflectthe W3C XSD specification. They provide the ability to programmatically create an XSD schema.

    http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.htmlhttp://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html
  • 8/8/2019 Winforms & Ado

    133/149

    XML Documents

  • 8/8/2019 Winforms & Ado

    134/149

    XmlDocument class

    implements the W3C Document Object Model (DOM) Level 1Core and the Core DOM Level 2.

    The DOM is an in-memory (cache) tree representation of anXML document and enables the navigation and editing of thisdocument.

    Because XmlDocument implements the IXPathNavigableinterface it can also be used as the source document for theXslTransform class.

    XmlDataDocument classextends 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

    http://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/f1d3d8e7-138f-befc-3f1d-236c8afb38f0.htmhttp://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/97c21cf9-a20e-b20e-3112-32f074fd2e56.htmhttp://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/97c21cf9-a20e-b20e-3112-32f074fd2e56.htmhttp://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/f1d3d8e7-138f-befc-3f1d-236c8afb38f0.htm
  • 8/8/2019 Winforms & Ado

    135/149

    The XPathDocument classprovides 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 usedto select, evaluate, navigate, and in some cases, edit the underlyingXML 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 asinstances 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 usingthe CanEdit property of the XPathNavigator class.

    XMLs Effect on RelationalTechnology

    http://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/6e030232-9f06-7b79-c48d-0bddb80929c5.htmhttp://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/d62252c9-0fa8-03e2-832c-e63f18ed1785.htmhttp://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/d62252c9-0fa8-03e2-832c-e63f18ed1785.htmhttp://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/1b4c2af8-f0d1-12ee-9817-ee7806f899d1.htmhttp://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/caf72fcf-6d27-be0b-fc64-31a9dc08b4b4.htmhttp://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/caf72fcf-6d27-be0b-fc64-31a9dc08b4b4.htmhttp://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/1b4c2af8-f0d1-12ee-9817-ee7806f899d1.htmhttp://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/d62252c9-0fa8-03e2-832c-e63f18ed1785.htmhttp://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/d62252c9-0fa8-03e2-832c-e63f18ed1785.htmhttp://ms-help//MS.MSDNQTR.v90.en/fxref_system.xml/html/6e030232-9f06-7b79-c48d-0bddb80929c5.htm
  • 8/8/2019 Winforms & Ado

    136/149

    Technology

    XML has challenged relational technology in some interestingways:Representing hierarchy, sparse data, order, schema evolutionThese are all known problems in the relational world; however, XML

    is providing unprecedented push

    Relational technology will continue store data for businessHighly normalized data will continue to exist for efficiency andflexibility

    Relational technology must and will step up to the needs ofXML but we need mapping too!

    SQL Server 2000: SQLXML

  • 8/8/2019 Winforms & Ado

    137/149

    Microsofts 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

  • 8/8/2019 Winforms & Ado

    138/149

    FOR XML (raw, auto, nested, explicit)

    SQL language extension to retrieve XML instead of rowsetsXML ViewsWork with your relational database as if it was XML file (through

    annotated schema)

    BulkloadShred large XML files into existing tables

    UpdategramsUpdate through XML View

    XPath query support

    ArchitectureBCP/SQLBCP/SQLXMLXML

  • 8/8/2019 Winforms & Ado

    139/149

    Query ProcessorQuery Processor

    Annotated XSDAnnotated XSD

    Mapping SchemasMapping Schemas

    XPathXPath

    QueryQuery

    XMLXML

    SQLSQL

    ServerServer

    RowsetsRowsets

    FOR XMLFOR XML

    SQLSQL

    QueriesQueries

    FOR XMLFOR XMLQueriesQueries

    SQLSQLQueriesQueries

    FOR XMLFOR XML

    QueriesQueries

    FOR XMLFOR XML

    XMLBulkloadXMLBulkloadBCP/SQLBCP/SQLXMLXML

    UpdategramsUpdategramsSQL update/SQL update/insert/ deleteinsert/ delete

    XMLXML

    ADO.NET and XML

    C t l

  • 8/8/2019 Winforms & Ado

    140/149

    .NET Data Provider

    DataReader

    Command

    Connection

    Mapping

    Controls,

    Designers,

    Code-gen, etc

    DataSet

    XmlReader

    XSL/T, X-Path,

    etc

    XmlData-

    Document

    DataAdapter

    ADO.NET and XML

  • 8/8/2019 Winforms & Ado

    141/149

    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 anXmlDataDocument

    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

  • 8/8/2019 Winforms & Ado

    142/149

    Dataset and XML

    // Load DataSet with XMLDataSet ds = new DataSet();ds.ReadXml("inventory.xml");

    // Add a record to the Inventory tableDataTable inventory = ds.Tables["Inventory"];DataRow row = inventory.NewRow();row["TitleID"]=1;row["Quantity"]=25;

    inventory.Rows.Add(row);

    // Write out XMLds.WriteXml("updatedinventory.xml");

    Writing XML Schemas fromDataSet

  • 8/8/2019 Winforms & Ado

    143/149

    DataSet

    SqlConnection conn = newSqlConnection( "server=(local);uid=sa;pwd=;database=pubs"); SqlDataAdapterda = 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

  • 8/8/2019 Winforms & Ado

    144/149

    yped a aSe s

    XSD.exe, the XML schema generation tool, is used to generate a

    typedDataSet 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 XSDschema information.

    DataRows, DataTables, and other items are available as strongtypes

    Rather than refering DataSet.Tables[0] orDataSet.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 throughthe XmlDataDocument

  • 8/8/2019 Winforms & Ado

    145/149

    e a a ocu e

    XmlDataDocument datadoc = new XmlDataDocument();

    datadoc.DataSet.ReadXmlSchema("c:\\authors.xsd");

    datadoc.Load ("c:\\authors.xml");

    DataSet ds = datadoc.DataSet; // use DataSet as usualforeach (DataTable t in ds.Tables)

    Console.WriteLine( "Table " + t.TableName + " is in dataset");

    XmlDataDocument from aDataSet

  • 8/8/2019 Winforms & Ado

    146/149

    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 documentdd.Save("c:\\temp\\xmldoc.xml"); // write the dataset

    dd.DataSet.WriteXml("c:\\temp\\dataset.xml");

    XML Web Service FoundationSimple, Open, Broad Industry Support

  • 8/8/2019 Winforms & Ado

    147/149

    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

  • 8/8/2019 Winforms & Ado

    148/149

    Creating standard ReportInserting fields and using special fieldsSorting data and Grouping data

    Creating summary total and grand totalCalling Crystal Report From Vb.Net ApplicationCreating Sub ReportsPrinting Report

    Exporting Report

    CRYSTAL REPORT

  • 8/8/2019 Winforms & Ado

    149/149

    DemoCreate a report based on single tableCreate a report based on multiple table