Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
class MyForm:Form{
public MyForm(){
Button ctrl = new Button(); // Create a button
ctrl.Text = "A Button"; // set its text
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
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
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
da.TableMappings.Add("Table", "authors");
da.TableMappings.Add("Table1", "titleauthors");
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);
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;
Run
Program Pattern for
Connection-oriented Data
Access
1.) Declare the connection
try {
1.) Request connection to database
• 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();
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
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
Example:
cmd.CommandText =
"SELECT EmployeeID, LastName, FirstName FROM Employees ";
DataReader reader = cmd.ExecuteReader();
ExecuteNonQuery Method
int ExecuteNonQuery();
Example:
.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
„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
changes Update
InsertCommand
DeleteCommand
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.
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
//.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)
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
.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
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
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
da.TableMappings.Add("Table", "authors");
da.TableMappings.Add("Table1", "titleauthors");
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);
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;
Demo
Create a report based on single table
Create a report based on multiple table