Вы находитесь на странице: 1из 152

The .

NET Framework Class Library

Dr. Wolfgang Beer


Software Competence Center Hagenberg

Dr. Herbert Praehofer


Institute for System Software
Johannes Kepler University Linz

© University of Linz, Institute for System Software, 2004


published under the Microsoft Curriculum License
.NET Framework Class Library
Overview
Collections
Reflection
Threading
Streaming
Processing XML Data
Networking
Windows Forms
Summary
.NET Technology

VB C++ C# JScript J#
Text Editor
ASP.NET
Windows
Web Forms Web Services
Mobile Internet Toolkit Forms
.NET Class Library
MS Visual
ADO.NET and XML WebMatrix
Studio.NET
.NET Base Class Library (BCL)
Common Language Runtime WebService
Studio
Operating System (WinXP, 2000, ...)

.NET Framework .NET Development Tools

3
Motivation Class Library
• Building blocks in the form of classes and components
– Input/output
– GUI programming
– Networking
– Sets and lists
– Strings
– …

• Robust, stable and high quality basis

• Enables simple and productive software development

4
.NET Class Library
• .NET provides a comprehensive class library
– ca. 100
200 namespaces with about 2000
4500 types
– for different areas (see overview)
• Supports important technologies like:
– XML
– cryptography
– reflection
– multi-threading
– …
• Unique basis for different programming languages

5
.NET Class Library
System.Web System.Windows.Forms
Services UI Design Component
ASP.NET
Description HtmlControls Model
Web Forms
Discovery Web Services
WebControls Windows
WebInternetASP.NET
Mobile Toolkit
Protocols
Services Forms
System.Drawing
Caching Security Drawing2D Printing
Configuration SessionState Imaging Text

System.Data System.Xml
OleDb
ADO.NET
ADO.NETSqlClient
Common SQLTypes
and XML
XSLT
XPath
Serialization

Collections IO Security Runtime


Configuration .NET Base
Net Class Library
ServiceProcess InteropServices
Remoting
Diagnostics
Globalization
Reflection
Resources
(BCL)Threading
Text
Serialization
6
.NET Framework Class Library
Overview
Collections
Reflection
Threading
Streaming
Processing XML Data
Networking
Windows Forms
Summary
Collections
• Collections = sets, lists, and dictionaries of objects
• C# only supports arrays
• .NET class library contains namespaces for object
collections
– System.Collections: untyped collections
– System.Collections.Generic (since .NET 2.0): typed (generic)
collections

8
.NET Framework Class Library
Overview
Collections
Untyped Collections
Typed Collections
Reflection
Threading
Streaming
Processing XML Data
Networking
Windows Forms
Summary
Collections
IEnumerable IEnumerator
Types for dealing with IEnumerator GetEnumerator() Object Current
sets, lists and bool MoveNext()
dictionaries void Reset()
ICollection
namespace System.Collections int Count
void CopyTo(Array a, int pos)

IList IDictionary Stack Queue BitArray


object this[int i] ICollection Keys
void Clear() ICollection Values
int Add(object x) object this[object key]
void Insert(int pos, object x) void Clear()
void Remove(object x) void Add(object key, object value)
void RemoveAt(int pos) void Remove(object key)
bool Contains(object x) bool Contains(object key)
int IndexOf(object x)

No special type for sets

Array ArrayList ListDictionary Hashtable SortedList


10
IEnumerable and IEnumerator (1)
• Anything which is enumerable is represented by interface IEnumerable

interface IEnumerable
<<interface>>{ <<interface>>
IEnumerator GetEnumerator();
IEnumerable IEnumerator
}

• IEnumerator realizes an iterator

interface IEnumerator {
object Current {get;}
bool MoveNext();
void Reset();
}

11
IEnumerable and IEnumerator (2)
• Classes which implement IEnumerable are:
– Array
– ArrayList
– String
– Hashtable
– and many more.

• For all IEnumerables foreach–statement can be used

Example:

int[] a = {1, 6, 8, 9, 15}; // object of abstract type Array


foreach (int i in a) System.Console.WriteLine(i);

12
Interface ICollection
• Basic interface for collections

int Count {get;}


interface ICollection {
– number of elements
<<interface>>
//---- Properties
IEnumerable
int Count {get;}
bool IsSynchronized {get;}
bool IsSynchronized {get;}
– collection synchronised?
object SyncRoot {get;}
//---- Methods
<<interface>>
object SyncRoot {get;} void CopyTo(Array a, int index);
– returns object for synchronisation
ICollection
}
void CopyTo(Array a, int index);
– copies the elements into array
(starting at position index)

13
Interface IList
• Interface for object collections with a defined order

interface IList {
object this [ int index ] {get; set;} • Indexer for accessing
<<interface>>
elements based on position
IEnumerable
int Add(object value);
void Insert(int index,object value); • Adding,
<<interface>> inserting and
void Remove(object value);
ICollection removing elements
void RemoveAt(int index);
void Clear();
• Testing containment of
bool Contains(object value);
<<interface>> <<interface>> elements
IList IDictionary
bool IsFixedSize {get;}
• Is list of fixed length?
bool IsReadOnly {get;}
• Is list read-only?
...
}
14
Class Array (1)
• Arrays in .NET are instances of classes derived from base class Array
• Array implements IList, ICollection and IEnumerable
• Arrays are of fixed size (isFixedSize == true)
• Array provides a rich interface

public abstract class Array :


<<interface>>
ICloneable, IList,IEnumerable
ICollection, IEnumerable {
//---- Properties
public int Length {get;} • Getting length and
public int Rank {get;} <<interface>> number of dimensions
ICollection
//----- Methods
public int GetLength(int dimension); • Getting length and
<<interface>>
public int GetLowerBound(int dimension); lower and upper bound
IList
public int GetUpperBound(int dimension); for each dimension

public object GetValue(int idx);


• Getting and setting
public object GetValue(int[] idx);
values
Array
public void SetValue(object val, int idx);
ArrayList
public void SetValue(object val, int[] idx);
15
Class Array (2)

//----- statische Methoden
public static int IndexOf(Array a, object val); • Searching for positions
public static int LastIndexOf(Array a, object value); of elements

public static void Sort(Array a);


• Sorting of arrays
public static void Sort(Array a, IComparer comparer);
public static void Reverse(Array a);

public static int BinarySearch(Array a, object val); • Binary search in sorted


public static int BinarySearch(Array a, object val, IComparer c); arrays
public static void Copy(Array srcArray, Array destArray, int len);
public static Array CreateInstance(Type elementType, int len); • Copying and creating
public static Array CreateInstance(Type elementType, int[] len); arrays

}

16
Example Array

• Creation of array with Array.CreateInstance


int[] i = (int[]) Array.CreateInstance(typeof(Int32), 6);

which is equivalent to
int[] i = new int[6];

• Setting values and sorting


i[0] = 3; i[1] = 1; i[2] = 5; i[3] = 2; i[4] = 9; i[5] = 4;
Array.Sort(i); // Sorts the elements in the array

• Output of elements with foreach statement


foreach (int elem in i)
Console.Write("{0} ", elem);

Elemente: 1 2 3 4 5 9
17
Class ArrayList (1)
• ArrayList realizes dynamically growing list

public class ArrayList :


IList, ICollection, IEnumerable, ICloneable {
<<interface>>
IEnumerable
public ArrayList(); • Constructors
public ArrayList(ICollection c);
<<interface>>
public ArrayList(int capacity);
ICollection

virtual int Capacity {get;set;} • Capacity


<<interface>>
public virtualArrayList
IList GetRange(intindex, int count); • Accessing,
public virtual void AddRange(ICollection c);
public virtual void InsertRange(int index, ICollection c); inserting,
setting,
public virtual
Arrayvoid SetRange(int i, ICollection c);
ArrayList removing elements
public virtual void RemoveRange(int index, int count);

18
Class ArrayList (2)

public virtual void Sort(); • Sorting and searching
public virtual void Reverse();
public virtual int BinarySearch(object o);
public virtual int LastIndexOf(object o);

public static ArrayList Adapter(IList list); • Creation of wrappers


public static ArrayList FixedSize(ArrayList l);
public static ArrayList ReadOnly(ArrayList l);
public static ArrayList Synchronized(ArrayList list);

public virtual void CopyTo(Array a); • Copying elements


public virtual object[] ToArray();

public virtual void TrimToSize();


• Trimming to actual size
}

19
Example ArrayList
• Creating ArrayList and adding values
ArrayList a = new ArrayList();
a.Add(3); a.Add(1); a.Add(2); a.Add(4); a.Add(9);

• Sorting the elements in the ArrayList


a.Sort();
foreach (int i in a) Console.WriteLine(i);

Elemente: 1 2 3 4 5 9

• Inverting the elements in the ArrayList


a.Reverse();
foreach (int i in a) Console.WriteLine(i);

Elemente: 9 4 3 2 1

20
Sorting: IComparable and IComparer
• IComparable is interface for types with order
public interface IComparable {
int CompareTo(object obj); // -1 if this < obj, 0 if this == obj, 1 if this > obj
}

Types implementing IComparable are


– value types like Int32, Double, DateTime, …
– class Enum as base class of all enumeration types
– class String

• IComparer is interface for the realization of compare operators


public interface IComparer {
int Compare(object x, object y); // -1 if x < y, 0 if x == y, 1 if x > y
}
IComparer implementations:
– Comparer, CaseInsensitiveComparer: for string comparisons

21
Example IComparer
• Creation of an array of strings
string[] names = string[] {“frank”, “john”, “Bill”, “paul”, “Frank”};

• Sorting the strings using a case-insensitive comparer


IComparer ciComparer = new CaseInsensitiveComparer ();
Array.Sort(names, ciComparer);

• Binary search for a name


int pos = Array.BinarySearch("John“, ciComparer);

• Inverting the array


names = Array.Reverse(names, ciComparer);

22
Example IComparable (1)
• Type Vector represents two-dimensional vector
• implements IComparable
• sorting is done based on the length of the vector
public class Vector : IComparable {
x
private double x, y;

public Vector(double x, double y) { this.x = x; this.y = y; } y

public double Length { get { return Math.Sqrt( x*x + y*y ); } }

public int CompareTo(object obj) {


if(obj is Vector) {
if(this.Length < ((Vector)obj).Length) return -1;
else if(this.Length > ((Vector)obj).Length) return 1;
else return 0;
}
throw new ArgumentException();
}

23
Example IComparable (2)

• Creation of array of Vector objects


Vector[] vArray = { new Vector(1.5,2.3), new Vector(3,6), new Vector(2,2) };

• Elements in array are sorted based on length of vectors

Array.Sort(vArray);
dumpArray(vArray);
Array.Reverse(vArray);
dumpArray(vArray);

24
Interface IDictionary
• IDictionary is interface for collections of key-value pairs

interface IDictionary : ICollection, IEnumerable {


<<interface>>
IEnumerable
object this[object key] {get; set;} • Indexer for accessing elements by
key
void Add(object key, object value);
void Remove(object key);
<<interface>> • Adding,
ICollection
bool Contains(object key); removing,
containment
ICollection Keys {get;};
ICollection Values {get;}; • Keys
• Values

<<interface>> <<interface>>
IDictionaryEnumerator GetEnumerator(); • Accessing an iterator for key-value
pairs
IList IDictionary

}

25
IDictionaryEnumerator and DictionaryEntry
• IDictionaryEnumerator is iterator over key-value pairs
• IDictionaryEntry represents key-value pair

interface IDictionary : ICollection, IEnumerable {



IDictionaryEnumerator GetEnumerator();

}

public struct DictionaryEntry {


public interface IDictionaryEnumerator :
//----- Constructor
IEnumerator {
public DictionaryEntry
(object key, object value);
//----- Properties
public DictionaryEntry Entry {get;};
//----- Properties
public object Key {get;};
public object Key {get;};
public object Value {get;};
public object Value {get;};
}
}
26
Dictionary Hashtable
• Hashtable is an implementation of IDictionary
• organised by hash code of keys
 key objects must implement GetHashCode and Equals methods

public class Hashtable <<interface>>


: IDictionary, ICollection,
IEnumerable, … { IEnumerable

public Hashtable(); • Constructors


public Hashtable(IDictionary d);
<<interface>>
public Hashtable(int ICollection
capacity);
• Indexer for accessing elements
public virtual object this[object key] {get; set;}
by key
<<interface>> • Testing, if key and value
public virtual bool ContainsKey(object
IDictionary key);
public virtual bool ContainsValue(object val); contained

protected IHashCodeProvider Hcp {get; set;} • Setting and getting a


… SortedList HashCodeProviders !
Hashtable
}

27
Example Hashtable
• Creating Hashtable and adding Person objects using the social
security number as key
public class Person {
public Person(string fn, string ln) {
Hashtable h = new Hashtable(); …
h.Add(3181030750, new Person("Mike", "Miller")); }
h.Add(1245010770, new Person("Susanne", "Parker")); public override string ToString() {

h.Add(2345020588, new Person("Roland", "Howard")); }
h.Add(1245300881, new Person("Douglas", "Adams")); ...
}

• Iterating over the entries and printing out values and keys
foreach (DictionaryEntry x in h)
Console.WriteLine(x.Value + ": " + x.Key);

• Testing for containment of an entry with a particular key


if (h.Contains(1245010770))
Console.WriteLine("Person mit SNr. 1245010770: " + h[1245010770]);

28
HashCodeProvider
• HashCodeProvider allows the creation of hash codes independent of
key objects

public interface IHashCodeProvider {


int GetHashCode( object obj );
}

• On creation of Hashtable the HashCodeProvider can be set (has to


be done together with compatible comparer)
public class Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, … {
public Hashtable(IHashCodeProvider hcp, IComparer cmp);

}

Example:
Hashtable table = new Hashtable(
new CaseInsensitiveHashCodeProvider(), new CaseInsensitiveComparer());
29
Dictionary SortedList
• SortedList is second implementation of IDictionary
• dynamic list of key-value pairs sorted by key!

public class SortedList : IDictionary, ICollection, … {


public SortedList(); • Constructors
<<interface>>
public SortedList(IComparer c);
IEnumerable
public virtual object this[object key] {get; set;}; • Indexer for accessing elements by key

<<interface>> i);
public virtual object GetByIndex(int • Accessing values and keys based on
ICollection
public virtual object GetKey(int i); index position

public virtual IList GetKeyList(); • List of keys


<<interface>>
public virtual IList GetValueList(); and values
IDictionary
public virtual int IndexOfKey(object key); • Position of key
public virtual int IndexOfValue(object value); and value

void RemoveAt(intSortedList
public virtualHashtable i); • Removing an entry at a given position

} 30
Special Collections
public class Queue : ICollection, IEnumerable, ICloneable {
• Queue public virtual void Clear();
public virtual bool Contains(object o);
public virtual object Dequeue();
public virtual void Enqueue(object o);
public virtual object<<interface>>
Peek();
… IEnumerable
}

public class Stack : ICollection, IEnumerable, ICloneable {


• Stack <<interface>>
public virtual void Clear();
ICollection o);
public virtual bool Contains(object
IEnumerable
public virtual object Peek();
public virtual object Pop();
public virtual void Push(object o);

}

public sealed class BitArray : ICollection, IEnumerable, ICloneable {


• BitArray BitArray
public Queue
bool this[int index] {get; set;} Stack
public int Length {get; set;}
public BitArray And(BitArray val);
public BitArray Not();
public BitArray Or(BitArray a);

} 31
.NET Framework Class Library
Overview
Collections
Untyped Collections
Typed Collections
Reflection
Threading
Streaming
Processing XML Data
Networking
Windows Forms
Summary
Generic Collections
Namespace System.Collections.Generic provides generic classes for collections

IEnumerable IEnumerator

IEnumerable<T> IEnumerator<T>
IEnumerator<T> GetEnumerator() T Current

IComparable
ICollection<T> Stack<T> Queue<T>
int Count
void Clear() IComparable<T>
bool Contains(T item) int CompareTo(T obj ))
void Add(T item)
void Remove(T item)
void CopyTo(Array a, int pos)
IComparer

IList<T> LinkedList<T>
T this[int i] IComparer<T>
void Insert(int pos, T x) int Compare(T x, T y)
void RemoveAt(int pos)
int IndexOf(T x)

Comparer<T>

List<T> 33
IEnumerable<T> and IEnumerator<T> (1)

• interface IEnumerable<T> for anything which is enumerable

Type parameter T defines type of elements !

<<interface>> : IEnumerable<<interface>>
interface IEnumerable<T> {
IEnumerator<T> GetEnumerator(); IEnumerator<T>
IEnumerable<T>
}

• IEnumerator<T> realizes an iterator

interface IEnumerator<T> : IEnumerator {


T Current {get;}
bool MoveNext();
void Reset();
}
34
IEnumerable<T> and IEnumerator<T> (2)
• Use foreach-statement with IEnumarables

public class Person {


public string ssNr;
public string name;
public Person(string ssNr, string name) {
this.ssNr = ssNr;
Example: Array this.name = name;
}
public override string ToString() {
return ssNr + ", " + name;
}
Person[] persons = new Person[10]; }
foreach (Person p in persons)
System.Console.WriteLine(p.ToString());

35
IEnumerable<T> and IEnumerator<T> (3)
• Use foreach-statement with IEnumarables

public class Person {


public string ssNr;
public string name;
public Person(string ssNr, string name) {
this.ssNr = ssNr;
Example: List<T> this.name = name;
}
public override string ToString() {
return ssNr + ", " + name;
}
}
List<Person> persons = new List<Person>();
foreach (Person p in persons)
System.Console.WriteLine(p.ToString());

36
Interface ICollection<T>
• Base interface for collections

interface ICollection<T>:
IEnumarable<T> {
//---- Properties
<<interface>>
int Count {get;} • number of elements
IEnumerable<T>
bool IsReadOnly {get;} • read only?

//---- Methods
void Add(T elem); • adding an element
<<interface
bool Remove(T elem); >> • removing an element
ICollection<T>
void Clear(); • remove all
bool Contains(T elem); • containment
void CopyTo(T[] a, int index); • copies elements into array a
} (beginning at position index)

37
Class LinkedList<T>
• Linked list implementation of ICollection<T>
• works with LinkedListNode<T>
public class sealed LinkedListNode<T> {
public T Value { get; set; }
public LinkedListNode<T> Next { get; }
public LinkedListNode<T> Previous { get; }
public class LinkedList<T>: ICollection<T> {
//---- Properties
<<interface>> }
… ICollection<T>
public LinkedListNode<T> First { get; } • first node
public LinkedListNode<T> Last { get; } • last node

//---- Methods
public LinkedListNode<T> AddFirst ( T value) • add first node with value
public LinkedListNode<T> AddLast ( T value) • add last node with value
<<interface>>
public LinkedList
LinkedListNode<T> AddAfter
IList<T>
( <T> • add new node after node
LinkedListNode<T> node, T value )

}
38
Interface IList<T>
• Interface for collections with positioned access

interface IList<T>: ICollection<T>: {

//---- Properties
<<interface>>
T this[int index] {get; set;} • Indexer for direct access
ICollection<T>
//---- Methods
void Insert(int index, T elem); • adding an element at position index
<<interface
bool RemoveAt(int >>
index); • removing an element at position index
int IndexOf(T elem); • Position of element elem
} IList<T>

39
IComparable<T> and IComparer<T>
• IComparable<T> is interface for types with order

public interface IComparable<T> {


int CompareTo(T obj); // -1 if x < y, 0 if x == y, 1 if x > y
}

• IComparer<T> is interface for realizing comparison objects


public interface IComparer <T> {
int Compare(T x, T y); // -1 if x < y, 0 if x == y, 1 if x > y
}

40
Example IComparer<T>
Base class Person
• Comparer for Persons

public class PersonComparer<T> : IComparer<T> where T: Person {


// compare SSN of persons 1 and 2
public int Compare(T person1, T person2) {
return person1.svNr.CompareTo(person2.svNr);
}
}

public class TestComparer {


public static void Main(string[] argv) {
Person[] persons = { new Person("030819778345", "Herbert Miller"),
new Person("010519506534", "Mary Master"),
new Person("100719654298", “Harry Monster") };
Array.Sort(persons, new PersonComparer<Person>());
foreach (Person p in persons) {
Console.WriteLine(p.ToString());
}
} 010519506534, Mary Master
} 030819778345, Herbert Miller
100719654298, Harry Monster
41
Class List<T> (1)
• Standard implementation of IList<T>

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T> {


// IEnumerable<T>: GetEnumerator • properties and methods of
// ICollection<T>: Count, CopyTo, Add, Contains, ... implemented interfaces
<<interface>>
// IList<T>: Insert, RemoveAt, IndexOf, ...

//----- Constructors IList<T>


public List();
public List(IEnumerable<T> collection); • constructors
public List(int capacity);

//----- Properties
List<T>
virtual int Capacity {get; set;}
public int Count { get; } • reserved space in list
public T this [int index] { get; set; } • number of elements
… • indexer for positioned access

42
Class List<T>(2)
//----- Methods
public virtual IList<T> GetRange(int index, int count); • subset
public virtual void AddRange(IEnumerable<T> c); • adding a set of elements
public virtual void InsertRange(int i, IEnumerable<T> c); • inserting a set of elements
public virtual void RemoveRange(int index, int count); • removing a set of elements
public virtual int LastIndexOf(T e); • last position where e occurs

public virtual int BinarySearch(T e); • binary serach for e


public virtual int BinarySearch(T e, IComparer<T>); • binary search with IComparer

public virtual void Sort(); • sorting


public virtual void Reverse(); • inversion of elements
public virtual T[] ToArray(); • copying elements into T[] array
public virtual void TrimExcess(); • setting capacity to current number
of elements
}

43
Example List<T> (1)
using System;
using System.Collections.Generic;
...
List<Person> list = new List<Person>();

list.Add(new Person("030819778345", "Herbert Miller"));


list.Add(new Person("010519506534", "Mary Master"));
list.Add(new Person("100719654298", "Harry Monster"));

list.Sort(new PersonComparer<Person>());
Output:
foreach (Person p in list) Console.WriteLine(p); 010519506534, Mary Master
030819778345, Herbert Miller
100719654298, Harry Monster

list.Reverse();
for (int i = 0; i < list.Count; i++) Console.WriteLine(list[i]);
100719654298, Harry Monster
030819778345, Herbert Miller
010519506534, Mary Master

44
Example List<T> (2)
using System;
using System.Collections.Generic;
...
List<string> list = new List<string>();
list.Add("Anton"); list.Add("Dora"); list.Add("Berta"); list.Add("Emil"); list.Add("Caesar");

list.Sort();

int i = list.BinarySearch("Emil");
Console.WriteLine("Pos. {0}: {1}", i, list[i]);
Pos. 4: Emil

StringComparer ignoreCaseComparer = StringComparer.CurrentCultureIgnoreCase;


i = list.BinarySearch("berta", ignoreCaseComparer);
Console.WriteLine(" Pos. {0}: {1}", i, list[i]);
Pos. 1: Berta

//----- Conversion to static array


string[] arr = list.ToArray(); Anton
foreach (string s in arr) Console.WriteLine(s); Berta

45
Class Queue<T>
• Queue<T> realizes buffer with FIFO strategy
public class Queue<T> : ICollection, IEnumerable<T> {

// IEnumerable<T>: GetEnumerator • implementation of interfaces


// ICollection<T>: Count, CopyTo, ... ICollection and IEnumerable

public Queue(); • constructors


public Queue(IEnumerable<T> c);
public Queue(int capacity);

//----- Methods
public virtual void Enqueue(T elem); • appending element in the back
public virtual T Dequeue(); • removing first element
public virtual T Peek(); • accessing first element without
… removing it
}

46
Example Queue<T>

using System;
using System.Collections.Generic;
...
Queue<string> q = new Queue<string>();
q.Enqueue("Anton"); q.Enqueue("Berta");
q.Enqueue("Caesar"); q.Enqueue("Dora");
while (q.Count > 0) Console.Write(q.Dequeue());

Anton Berta Caesar Dora

47
Class Stack<T>
• Stack<T> realizes generic stack with LIFO strategy
public class Stack<T> : ICollection, IEnumerable<T> {

// IEnumerable<T>: GetEnumerator • implementation of interfaces


// ICollection<T>: Count, CopyTo, ... ICollection und IEnumerable

//----- Constructors
public Stack(); • constructors
public Stack(IEnumerable<T> c);
public Stack(int capacity);

//----- Methods
public virtual void Push(T elem); • putting element on the stack
public virtual T Pop(); • removing topmost element
public virtual T Peek(); • reading topmost element without
… removing it
}

48
Example Stack<T>

Stack<string> s = new Stack<string>();


s.Push("Anton"); s.Push("Berta"); s.Push("Caesar");
s.Push("Dora");
while (s.Count > 0) Console.Write(s.Pop());
Dora Caesar Berta Anton

49
Generic Dictionary Classes
• Generic types for mappings from keys to values

ICollection <KeyValuePair<int, Person>>


ICollection <KeyValuePair <TKey, TValue> >

IDictionary <TKey, TValue>


IDictionary <int, Person>
ICollection<TKey> Keys
ICollection<TValue> Values
TValue this[TKey key]
void Add(TKey key, TValue value)
void Remove(TKey key)
bool ContainsKey(TKey key)
bool TryGetValue(TKey key, out TValue value)

Dictionary <TKey,TValue> SortedList <TKey,TValue> SortedDictionary <TKey,TValue>

Realization with Realization with Realization with


50
hashtable array tree
Interface IDictionary<TKey, TValue>
• General interface for mappings public struct KeyValuePair<TKey, TValue> {
from keys to values public KeyValuePair(TKey key, TValue value);
public TKey Key {get; } p
public TValue Value {get; }
interface IDictionary<TKey, TValue>: }
ICollection<KeyValuePair<TKey, TValue>>,
IEnumerable<KeyValuePair<TKey, TValue>> {

// inherits from ICollection<T>: Count, CopyTo, ...

//----- Properties Acess to:


ICollection<TKey> Keys {get;} • set of keys
ICollection<TValue> Values {get;} • set of values
TValue this[TKey key] {get; set;} • value for an key

//----- Methods
void Add(TKey key, TValue value); • adding a key-value pair
void Remove(TKey key); • Removing a value for a key
bool ContainsKey(TKey key); • Checking if value for key contained
bool TryGetValue(TKey key, out TValue value); • trial to access value for an key;
} returns false if unsuccessful
51
Class Dictionary<TKey, TValue>
• Implementation of IDictionary<TKey, TValue> with hashtable

public class Dictionary<TKey, TValue> :


IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>,
IEnumerable<KeyValuePair<TKey, TValue>>, ... {
//----- implemented interfaces
// ICollection: Count, CopyTo, ...
// IDictionary: Clear, Add, Remove, Contains, GetEnumerator, Indexer, ...

//----- Constructors
public Dictionary();
public Dictionary(int capacity);
public Dictionary(IEqualityComparer<TKey> comparer);
public Dictionary(IDictionary<TKey, TValue> d);

//----- Methods
public virtual bool ContainsKey(TKey key);
public virtual bool ContainsValue(TValue val);
...
}

52
Example Dictionary<TKey, TValue>
• Dictionary with SSN as keys and Person-objects as values

public class DictionaryExample {


public static void Main() {
Dictionary<long, Person> tab = new Dictionary<long, Person>();
tab.Add(3181030750, new Person("3181030750", "Mike Miller"));
tab.Add(1245010770, new Person("1245010770", "Susanne Parker"));
tab.Add(2345020588, new Person("2345020588", "Roland, Howard"));
tab.Add(1245300881, new Person("1245300881", "Douglas Adams"));
foreach (KeyValuePair<long, Person> e in tab)
Console.WriteLine(e.Value + ": " + e.Key);
if (tab.ContainsKey(1245010770))
Console.WriteLine("Person with SSN 1245010770: " + tab[1245010770]);
}
} 3181030750, Mike Miller: 3181030750
1245010770, Susanne Parker: 1245010770
2345020588, Roland, Howard: 2345020588
1245300881, Douglas Adams: 1245300881
Person with SSN 1245010770: 1245010770, Susanne Parker

53
Class SortedDictionary<TKey, TValue>
• Sorted according to keys
• Implementation with tree
public class SortedDictionary<TKey, TValue> :
IDictionary<TKey, TValue>, ICollection<KeyVauePair<TKey, TValue>>,
IEnumerable<KeyVauePair<TKey, TValue>>, ... {
//----- Constructors
public SortedDictionary();
public SortedDictionary(IComparer<TKey> c);

//----- Properties
public virtual IComparer<TKey> Comparer { get; }
public virtual TValue this [ TKey ] { get; set; }
//----- Methods
public virtual void Add(TKey key, TValue value); // adds key-value pair
public virtual void RemoveAt(int i); // removes key-value pair with position i
public virtual bool ContainsKey(TKey key); // key contained?
public virtual bool ContainsValue(TValue val); // value contained?
public virtual int IndexOfKey(TKey key); // returns position of key
public virtual int IndexOfValue(TValue value); // returns position of value …
}
54
Example SortedDictionary<TKey, TValue>
• Create a SortedDictionary-Objects with <long, Person>
SortedDictionary<long, Person> persons = new SortedDictionary<long, Person>();

• Adding of Person-objects with SSN as key


persons.Add(3181030750, new Person("Mike", "Miller"));
persons.Add(1245010770, new Person("Susanne", "Parker"));
persons.Add(2345020588, new Person("Roland", "Howard"));
persons.Add(1245300881, new Person("Douglas", "Adams"));

• Output of entries in sorted order


foreach (KeyValuePair<long, Person> pEntry in persons) {
long ssn = pEntry.Key;
Person person = pEntry.Value;
System.Console.WriteLine("SSN {0} : {1}", ssn, person.ToString());
}
SSN 1245010770 : Susanne Parker
SSN 1245300881 : Douglas Adams
SSN 2345020588 : Roland Howard
SSN 3181030750 : Mike Miller
55
.NET Framework Class Library
Overview
Collections
Reflection
Threading
Streaming
Processing XML Data
Networking
Windows Forms
Summary
Reflection
• Permits access to meta-information of types at run-time
• System.Reflection allows:
– Getting meta-information about assemblies, modules and types
– Getting meta-information about the members of a type
– Dynamic creation of instances of a type at run-time
– Search for methods and their dynamic invocation at run-time
– Accessing values of properties and fields of an object
– Design of new types at run time
 namespace System.Reflection.Emit

57
Reflection Class Hierarchy
Assembly

GetTypes()

* BaseType
Type
Interfaces
*

GetFields() * FieldInfo

GetMethods() * MethodInfo
MethodBase
GetConstructors() * ConstructorInfo MemberInfo

GetProperties() * PropertyInfo

GetEvents() * EventInfo

58
Class Assembly
• Class Assembly loads assemblies and their meta-data
• Provides access to its meta-data

public class Assembly {

public static Assembly Load(string name); • Loading an assembly

public virtual string FullName {get;} • Name,


public virtual string Location {get;} storage location,
public virtual MethodInfo EntryPoint {get;} entry point of the assembly

public Module[] GetModules(); • Getting modules and


public virtual Type[] GetTypes(); all in the assembly defined types
public virtual Type GetType(string typeName); • Getting type with name typeName

public object CreateInstance(string typeName); • Creation of an object of type


... typeName
}

59
Class Type
• Type used for meta-description of all types in the run-time system
• Provides access to the meta-information about its members

public abstract class Type : MemberInfo, IReflect {


GetCustomAttributes()
public abstract
Assembly
string FullName
MemberInfo
{get;}; *
Object • Type name
public abstract Type BaseType {get;}; • Direct base type
public Type[] GetInterfaces(); • List of implemented interfaces

public bool IsAbstract


*
{get;};
Type
public boolGetTypes()
IsClass {get;}; • Properties of type
public bool IsPublic {get;}; EventInfo

FieldInfo

public ConstructorInfo[] GetConstructors();


MethodBase • Getting constructors,
public virtual EventInfo[] GetEvents();
events,
public FieldInfo[] GetFields(); fields,
public MethodInfo[] GetMethods();
ConstructorInfo methods,
public PropertyInfo[] GetProperties(); properties
... MethodInfo

PropertyInfo 60
Example Reflection (1)
• C# program "HelloWorld" • Compiling and
creating assembly
namespace Hello {
using System;
public class HelloWorld {

public static void Main(string[] args) {


Console.WriteLine("HelloWorld"); csc HelloWorld.cs
}

public override string ToString() {


return "Example HelloWorld"; HelloWorld.exe
}
}
}

• Loading the assembly "HelloWorld.exe":


Assembly a = Assembly.Load("HelloWorld");

61
Example Reflection (2)
• Print all existing types in a given assembly

Type[] types = a.GetTypes();


foreach (Type t in types)
Console.WriteLine(t.FullName);
Hello.HelloWorld

• Print all existing methods of a given type

Type hw = a.GetType("Hello.HelloWorld");
MethodInfo[] methods = hw.GetMethods();
foreach (MethodInfo m in methods)
Console.WriteLine(m.Name);
Main
ToString
62
Example Reflection (3)
• Create a new instance of a given type

Assembly a = Assembly.Load("HelloWorld");
object o = a.CreateInstance("Hello.HelloWorld");

• Get method ToString(), which has no parameters


• Invoke the method

Type hw = a.GetType("Hello.HelloWorld");
MethodInfo mi = hw.GetMethod("ToString");
object retVal = mi.Invoke(o, null);

63
Attributes
• GetCustomAttributes returns attributes of type or type member
public abstract class MemberInfo : ICustomAttributeProvider {
public abstract object[] GetCustomAttributes( bool inherit );
public abstract object[] GetCustomAttributes( Type attributeType, bool inherit);

}

• Those can be used at run-time

64
Example Attributes
• Definition of MyAttribute class • Reading the attributes and printing them out
using System; public class MemberInfo_GetCustomAttributes {
using System.Reflection; public static void Main() {
Type t = typeof(MyClass1);
[AttributeUsage(AttributeTargets.All)] MemberInfo[] membs = t.GetMembers();
public class MyAttribute : Attribute {
private string myName; for(int i = 0; i < myMembers.Length; i++) {
public MyAttribute(string name) { Console.WriteLine("\Member {0} \n", membs[i]);
myName = name; Object[] attrs =
} membs[i].GetCustomAttributes(true);
public string Name {
get { for(int j = 0; j < attrs.Length; j++)
return myName; Console.WriteLine("attribute is {0}.", attrs[j]);
} }
} }
} }
• Using the attribute
public static void Main() {
public class MyClass1 { Type t = typeof(MyClass1);
[MyAttribute("This is an example attribute.")] MethodInfo m = t.GetMethod("MyMethod");
public void MyMethod(int i) { object[] attr =
return; m. GetCustomAttributes(typeof(MyAttribute), false);
} …
} 65
Reflection.Emit
• Reflection.Emit allows creation of assemblies and types at run-time
– creation of assemblies
– creation of new modules
– creation of new types
– creation of symbolic meta-information of existing modules

• System.Reflection.Emit supports realization of .NET compilers und interpreters

• Important classes of Reflection.Emit are


– AssemblyBuilder to define assemblies
– ModuleBuilder to define modules
– TypeBuilder to define types
– MethodBuilder to define methods
– ILGenerator to emit IL-code

66
Example Reflection.Emit (1)
• Creation of a new assembly and module
AssemblyName assemblyName
public class HelloWorld { = new AssemblyName();
assemblyName.Name
public virtual string =SayHelloTo(string
"HelloWorldAssembly";
name) {
AssemblyBuilder newAssembly
return “Hello “ + name; = Thread.GetDomain().DefineDynamicAssembly(
} assemblyName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder
} newModule =
newAssembly.DefineDynamicModule("HelloWorldModule");

• Definition of a new type


TypeBuilder newType = newModule.DefineType ("HelloWorld", TypeAttributes.Public);

• Definition of a new method with parameter and return types


Type[] paramTypes = new Type[]{ typeof(string) };
Type retType = Type.GetType("System.String");
MethodBuilder newMethod = newType.DefineMethod("SayHelloTo",
MethodAttributes.Public | MethodAttributes.Virtual, retType, paramTypes);

67
Example Reflection.Emit (2)
• Defining the MSIL code for the new method
ILGenerator ilGen = newMethod.GetILGenerator ();
ilGen.Emit (OpCodes.Ldstr, "Hello ");
ilGen.Emit (OpCodes.Ldarg_1);
Type t = Type.GetType ("System.String");
MethodInfo mi = t.GetMethod ("Concat", new Type[]{typeof(string),typeof(string)});
ilGen.Emit (OpCodes.Call, mi);
ilGen.Emit (OpCodes.Ret);

• Creating the new type


newType.CreateType();

• Creating an instance of the new type and calling SayHelloTo method


MethodInfo method = newType.GetMethod ("SayHelloTo", new Type[]{typeof(string)});
object obj = Activator.CreateInstance (newType);
object ret = method.Invoke (obj, new string[] {"Wolfgang"});
Console.WriteLine (ret);
Hello Wolfgang
68
.NET Framework Class Library
Overview
Collections
Reflection
Threading
Streaming
Processing XML Data
Networking
Windows Forms
Summary
Threading
• Name space System.Threading supports light-weight processes
– run-time control
– synchronisation
– thread pooling

• Important types of System.Threading are


– classes Thread and ThreadPool
– enumerations TreadState and ThreadPriority
– class Monitor
– exceptions ThreadAbortException and ThreadInterruptedException
– delegates ThreadStart, WaitCallback, TimerCallback,
IOCompletionCallback, …
– …

70
Class Thread
public sealed class Thread {

public Thread(ThreadStart start); • Constructor with ThreadStart delegate

public ThreadPriority Priority {get; set;} • Setting/getting the priority


public ThreadState ThreadState {get;} • Current state

public bool IsAlive {get;} • Properties liveliness,


public bool IsBackground {get; set;} background

public void Start();


public static void Sleep(int time);
public void Suspend(); • Methods for controlling the thread
public void Resume();
public void Join();
public void Interrupt();
public void Abort();
public static void ResetAbort();

public static Thread CurrentThread {get;} • Gets the currently running thread
}
71
ThreadStart, ThreadPriority and ThreadState
public delegate void ThreadStart();

public sealed class Thread { public enum ThreadPriority {


public Thread( ThreadStart start); Highest,
AboveNormal,
Normal,
public ThreadPriority Priority {get; set;} BelowNormal,
Lowest,
public ThreadState ThreadState {get;} }

} public enum ThreadState {
Unstarted,
Running,
Background,
WaitSleepJoin,
SuspendRequested,
Suspended,
AbortRequested,
Stopped
}
72
Creating a New Thread
• Implementing method for ThreadStart

using System.Threading
public class ThreadExample {
public static void RunT0() {
for(int i=0; i<10000; i++) {
Console.Write(“x“);
Thread.Sleep(100);
}
}

• Creating Thread with delegate to method RunT0 and starting it

public static void main(string[] args) {


// main thread starts a new thread which runs RunT0 method
Thread t0 = new Thread( new ThreadStart(RunT0));
t0.Start();
}

73
Thread States
• Enumeration ThreadState defines the states of a thread

State diagram (simplified)

public enum ThreadState { Resume()


Unstarted, Unstarted
Running,
Background, Suspend() Suspend
WaitSleepJoin, Running Suspended
Start() Requested
SuspendRequested,
Suspended,
AbortRequested, Wait(),Sleep(),Join()
Stopped Interrupt()
WaitSleepJoin
} Pulse()

AbortRequested
Abort()

Stopped
end of thread method
74
Foreground and Background Threads
• Two different types of threads: Foreground und Background
– As long as a foreground thread is running, the program will not
terminate
– running background threads cannot prevent the program from
terminating
• A background thread is created by setting the property IsBackground

Thread bgThread = new Thread(new ThreadStart(…));


bgThread.IsBackground = true;

75
Thread Pools
• ThreadPool provides set of threads
– For efficient execution of a set of registered tasks
– Management and optimization of execution of tasks done by pool
– For short running tasks which are inactive most of the time.

• But:
– No control of threads by application program (e.g. no priorities)

76
Class ThreadPool
public sealed class ThreadPool {

public static void GetAvailableThreads(out int w, out int aIOs); • Number of available worker
and IO threads

public static void GetMaxThreads(out int w, out int aIOs); • Maximum number of worker
and IO threads

public static bool QueueUserWorkItem( WaitCallback task); • Registration of a task as


public static bool QueueUserWorkItem( WaitCallback task, WaitCallback delegate
object state);
}

• WaitCallback delegate
public delegate void WaitCallback(object state );

77
Example ThreadPool
• Definition of the task
public static void WorkerTask(object state) {
while (…) {
… // do something short
Thread.Sleep(…); // then sleep
}
}

• Getting the number worker and IO threads


int maxWorkers, availWorkers;
int maxIOs, availIOs;
ThreadPool.GetMaxThreads(out maxWorkers, out maxIOs);
ThreadPool.GetAvailableThreads(out availWorkers, out availIOs);

• Adding a new task to the pool


object state = …;
ThreadPool.QueueUserWorkItem(new WaitCallback(WorkerTask), state);

78
Synchronisation with lock
• lock statement is used for synchronisation of threads when accessing
common resources
• lock statement sets lock for an object
• for realizing of mutual exclusion

public class LockExample {


public static void RunT0() {
lock(Console.Out) {
for(int i = 0; i < 10; i++) {
// Console can be used exclusively
Console.Write("x");
Thread.Sleep(100);
}
}
}
}
79
Class Monitor
• Class Monitor realizes basic mechanism for synchronisation

public sealed class Monitor {


public static void Enter(object obj); • tries to get lock for obj and blocks
public static bool TryEnter(object obj); • tries to get lock for obj and returns

public static void Exit(object obj); • releases lock for obj

public static void Wait(object obj); • brings thread into the waiting state, releases locks
public static bool Pulse(object obj); • awakens next thread waiting for obj
public static void PulseAll(object obj); • awakens all threads waiting for obj
}

• lock statement is realized using Monitor; is short form for:

Monitor.Enter(obj)
lock (obj) { try {

…  } finally {
}
Monitor.Exit(obj)
}
80
Using Monitor
• Enter blocks when lock is not available
• TryEnter tries to get lock without blocking; returns false when lock is
not available

Enter: with blocking TryEnter: without blocking


public class MonitorExample {
private Queue lpt; public bool AddElemNonBlocking (object elem) {
try {
public void AddElemBlocking (object elem) { if (! Monitor.TryEnter (lpt.SyncRoot))
try { return false;
Monitor.Enter (lpt.SyncRoot); lpt.Enqueue (elem);
lpt.Enqueue (elem); } catch (Exception e) {
} catch (Exception e) { …
… }
} finally {
finally { Monitor.Exit (lpt.SyncRoot);
Monitor.Exit (lpt.SyncRoot); }
} return true;
} }
}

81
Wait and Pulse
• With Wait and Pulse threads can be synchronized based on an object
state
public static void Wait(object obj);
public static bool Wait(object obj, int millies);
Releases lock and waits to be waked up

public static bool Pulse(object obj);


public static void PulseAll(object obj);

Wakes up next or all threads waiting for obj

lock (obj) { lock (obj) {


... ...
Monitor.Wait(obj); Monitor.Pulse(obj);
... ...
} }

82
Example Wait and Pulse: Buffer
public class Buffer {
const int size = 16;
char[ ] buf = new char[size];
int head = 0, tail = 0, n = 0;

public void Put(char ch) { thread 1


lock(this) { Lock buffer to add a character
while (n >= size) Monitor.Wait(this); While buffer is full, release lock and wait
buf[tail] = ch; tail = (tail + 1) % size; n++;
Monitor.Pulse(this); Wake up waiting threads
}
}

public char Get() {


lock(this) { thread 2
Lock buffer to retrieve character
while (n <= 0) Monitor.Wait(this); While buffer is empty, release lock and wait
char ch = buf[head]; head = (head + 1) % size; n--;
Monitor.Pulse(this); Wake up waiting threads
return ch;
}
}
}

83
.NET Framework Class Library
Overview
Collections
Reflection
Threading
Streaming
Processing XML Data
Networking
Windows Forms
Summary
Streaming Framework
• System.IO contains types for input and output
• Base class Stream: abstract protocol for byte-oriented input and output
• Specializations for different media

Stream

FileStream NetworkStream MemoryStream BufferedStream CryptoStream

• Streams support synchronous and asynchronous protocols


• Readers and Writers for formatting

85
Class Stream
public abstract class Stream : MarshalByRefObject, IDisposable {

public abstract bool CanRead { get; }


public abstract bool CanSeek { get; } • Elementary properties of
public abstract bool CanWrite { get; } stream
public abstract int Read(out byte[] buff, int offset, int count);
public abstract void Write(byte[] buff, int offset, int count);
• Synchronous reading and
public virtual int ReadByte(); writing
public virtual void WriteByte(byte value);

public virtual IAsyncResult BeginRead(…);


public virtual IAsyncResult BeginWrite(…); • Asynchronous reading and
public virtual int EndRead(…); writing
public virtual int EndWrite(…);

public abstract long Length { get; }


• Length
public abstract long Position { get; set; } and actual position
public abstract long Seek(long offset, SeekOrigin origin); • Positioning
public abstract void Flush();
public virtual void Close(); • Flush and close
...
}
86
Stream Classes
(Stream)
long Length Sequential byte streams on
long Position different media
int Read(byte[] buf, int pos, int len)
int ReadByte()
Write(byte[] buf, int pos, int len)
WriteByte(byte x) namespace System.IO
long Seek(long pos, SeekOrigin org)
SetLength(long len)
Flush()
Close()

FileStream MemoryStream NetworkStream BufferedStream CryptoStream


string Name int Capacity bool DataAvailable
Lock(int pos, int len) byte[] GetBuffer()
Unlock(int pos, int len) WriteTo(Stream s) Decorators

87
Readers and Writers
• Readers and Writers overtake formatting tasks

– BinaryReader and BinaryWriter for


binary data
TextReader
– TextReader and TextWriter for character
data

StreamReader StringReader

TextWriter
BinaryReader

Stream
BinaryWriter
StreamWriter StringWriter


FileStream MemoryStream NetworkStream

88
Reader Classes
(TextReader) BinaryReader
int Read() BinaryReader(Stream s)
int ReadBlock(char[] buf, int pos, int len) BinaryReader(Stream s, Encoding e)
int Peek() byte ReadByte()
string ReadLine() bool ReadBoolean()
string ReadToEnd() char ReadChar()
Close() short ReadInt16()
int ReadInt32()
...
Close()
StreamReader StringReader
Stream BaseStream StringReader(string s)
StreamReader(Stream s)

TextReader BinaryReader
reads char-based reads standard types in binary format

89
Writer Classes
(TextWriter) BinaryWriter
string NewLine Stream BaseStream
Write(bool b) BinaryWriter(Stream s)
Write(char c) BinaryWriter(Stream s, Encoding e)
Write(int i) Write(bool b)
... Write(char c)
Write(string format, params object[] arg) Write(int i)
WriteLine() ...
WriteLine(bool b) long Seek(int pos, SeekOrigin org)
WriteLine(char c) Flush()
WriteLine(int i) Close()
...
WriteLine(string format, params object[] arg)
Output of standard types in
Flush() binary format
Close()

StreamWriter StringWriter
Stream BaseStream StringWriter()
StreamWriter(Stream s) string ToString()

formatted text output


90
Classes TextReader and TextWriter
public abstract class TextReader : MarshalByRefObject, IDisposable {
public virtual int Read();
public virtual int Read(out char[] buf, int idx, int count); • Different reading operations
public virtual int ReadBlock(out char[] buf, int index, int count);
public virtual string ReadLine();
public virtual string ReadToEnd();
public virtual int Peek();

}

public abstract class TextWriter : MarshalByRefObject, IDisposable {


public virtual void Write(bool val); • Writing operations for all the
public virtual void Write(string s); primitive data types
public virtual void Write(int val);
... // + overloades methods
public virtual void WriteLine(); • Writing operations with line
public virtual void WriteLine(bool val); breaks
... // + overloaded methods

public virtual string NewLine { get; set; } • Characters for new line

public abstract Encoding Encoding { get; } • Used encoding



}
91
Example StreamWriter
using System;
using System.IO;
using System.Text; // for encoding definitions
public class StreamWriterExample {
public static void Main() {

• Creating FileStream
FileStream fs;
fs = new FileStream("log.txt", FileMode.OpenOrCreate, FileAccess.Write);

• Creating StreamWriter for text output


StreamWriter sw = new StreamWriter(fs, Encoding.Unicode);

• Putting out some text


sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("log entry 1");
sw.WriteLine("log entry 2");

• Closing writer and stream


sw.Close();
fs.Close();
}
} 92
Asynchronous Operations
• BeginRead and BeginWrite emit • BeginRead and BeginWrite have
asynchronous read and write operations AsyncCallback delegate parameter
• Delegate will be called upon completion of
public virtual IAsyncResult BeginRead(
byte[] buffer, operation with IAsyncResult object
int offset,
int count, public delegate void AsyncCallback(
AsyncCallback callback, IAsyncResult ar
object state ); );
public virtual IAsyncResult BeginWrite(
byte[] buffer,
public interface IAsyncResult {
int offset,
object AsyncState {get;}
int count,
WaitHandle AsyncWaitHandle {get;}
AsyncCallback callback,
bool CompletedSynchronously {get;}
object state );
bool IsCompleted {get;}
);
• With EndRead and EndWrite
asynchronous operation is completed
public virtual int EndRead(
IAsyncResult asyncResult );
public virtual void EndWrite(
IAsyncResult asyncResult);
93
Example Asynchronous Read
• Declaring fields for stream, buffer and callback
namespace AsyncIO {
public class AsyncIOTester {
private Stream inputStream;
private byte[] buffer = new byte[256];
private AsyncCallback callback;

• Calling BeginRead of input stream with callback delegate


public static void Main() {
inputStream = File.OpenRead("...");
callback = new AsyncCallback(this.OnCompletedRead)
inputStream.BeginRead(buffer, 0, buffer.Length, callback, null);
… // continue with some other tasks
}

• Callback method:
– Getting number of read bytes by EndRead
– Processing data
void OnCompletedRead(IAsyncResult result) {
int bytesRead = inputStream.EndRead(result);
… // process the data read
}
… 94
Files and Directories
Classes in System.IO for working with files and directories

Directory:
– static methods for manipulating directories

File:
– static methods for manipulating files

DirectoryInfo:
– represents a directory

FileInfo:
– represents a file

95
Class Directory
public sealed class Directory {
public static DirectoryInfo CreateDirectory(string path); // creates directories and subdirectories
public static void Move(string src, string dest); // moves directory src to dest
public static void Delete(string path); // deletes an empty directory
public static void Delete(string path, bool recursive); // deletes directory with contents
public static bool Exists(string path); // checks if directory exists
public static string[] GetFiles(string path); // returns all file names in path
public static string[] GetFiles(string path, string searchPattern);
public static string[] GetDirectories(string path); // returns all directory names in path
public static string[] GetDirectories(string path, string searchPattern);
public static DirectoryInfo GetParent(string path); // returns the parent directory
public static string GetCurrentDirectory(); // returns current working directory
public static void SetCurrentDirectory(string path); // sets current working directory
public static string[] GetLogicalDrives(); // returns names of logical drives (e.g. “c:\”)
public static DateTime GetCreationTime(string path); // returns creation date & time
public static DateTime GetLastAccessTime(string path); // returns last access date & time
public static DateTime GetLastWriteTime(string path); // returns last write date & time
public static void SetCreationTime(string path, DateTime t); // sets creation date & time
public static void SetLastAccessTime(string path, DateTime t); // sets last access date & time
public static void SetLastWriteTime(string path, DateTime t); // sets last write date & time
}

96
Class DirectoryInfo
public sealed class DirectoryInfo : FileSystemInfo {
//----- constructor
public DirectoryInfo(string path); // constructor; path specifies the directory
//----- properties
public override string Name { get; } // returns directory name without the path
public override bool Exists { get; } // indicates if this directory exists
public DirectoryInfo Parent { get; } // returns the parent directory
public DirectoryInfo Root { get; } // returns the root directory
//----- methods
public void Create(); // create directory, if it does not exist
public DirectoryInfo CreateSubdirectory(string path); // creates a subdirectory
public void MoveTo(string destDir); // moves this directory to destDir
public void Delete(); // deletes this directory, if it is empty
public void Delete(bool recursive); // deletes this directory and its contents
public FileInfo[] GetFiles(); // returns all files in this directory
public FileInfo[] GetFiles(string pattern); // returns matching files in this directory
public DirectoryInfo[] GetDirectories(); // returns all directories in this directory
public DirectoryInfo[] GetDirectories(string pattern); // returns all matching directories
public FileSystemInfo[] GetFileSystemInfos(); // returns all files and directories
public FileSystemInfo[] GetFileSystemInfos(string pattern); // returns files and directories for pattern
public override ToString(); // returns the path given in the constructor
}

97
Class File
public sealed class File {
public static FileStream Open(string path, FileMode mode);
public static FileStream Open(string path, FileMode m, FileAccess a);
public static FileStream Open(string p, FileMode m, FileAccess a, FileShare s);
public static FileStream OpenRead(string path);
public static FileStream OpenWrite(string path);
public static StreamReader OpenText(string path); // returns Reader for reading text
public static StreamWriter AppendText(string path); // returns Writer for appending text
public static FileStream Create(string path); // create a new file
public static FileStream Create(string path, int bufferSize);
public static StreamWriter CreateText(string path);
public static void Move(string src, string dest);
public static void Copy(string src, string dest); // copies file src to dest
public static void Copy(string src, string dest, bool overwrite);
public static void Delete(string path);
public static bool Exists(string path);
public static FileAttributes GetAttributes(string path);
public static DateTime GetCreationTime(string path);
public static DateTime GetLastAccessTime(string path);
public static DateTime GetLastWriteTime(string path);
public static void SetAttributes(string path, FileAttributes fileAttributes);
public static void SetCreationTime(string path, DateTime creationTime);
public static void SetLastAccessTime(string path, DateTime lastAccessTime);
public static void SetLastWriteTime(string path, DateTime lastWriteTime);
} 98
Class FileInfo
public sealed class FileInfo : FileSystemInfo {
//----- constructors
public FileInfo(string fileName); // creates a new FileInfo object for a file fileName
//----- properties
public override string Name { get; } // name of this file
public long Length { get; } // size of this file
public override bool Exists { get; } // indicates if this file exists
public DirectoryInfo Directory { get; } // directory containing this file
public string DirectoryName { get; } // name of the directory containing this file
//----- methods
public FileStream Open(FileMode m); // open a FileStream to this file
public FileStream Open(FileMode m, FileAccess a);
public FileStream Open(FileMode m, FileAccess a, FileShare s);
public FileStream OpenRead(); // opens a read-only FileStream to this file
public FileStream OpenWrite(); // open a write-only FileStream to this file
public StreamReader OpenText(); // returns a UTF8 reader for reading text
public StreamWriter AppendText(); // returns a StreamWriter for appending text
public FileStream Create(); // returns FileStream to this newly created file
public StreamWriter CreateText(); // returns Writer to this newly created text file
public void MoveTo(string dest); // move this file to dest
public FileInfo CopyTo(string dest); // copies this file to dest
public FileInfo CopyTo(string dest, bool overwrite); // copies to and overwrites dest
public override Delete(); // deletes this file
public override string ToString(); // returns entire path of this file
}
99
Example Directories and Files
• Printing out the directories and files in "c:\\" Output

using System; using System.IO; ---------- Directories ----------


public class DirectoryExample { Documents and Settings
I386
public static void Main() { Program Files
DirectoryInfo dir = Directory.CreateDirectory("c:\\"); System Volume Information
WINNT
Console.WriteLine("---------- Directories ----------"); ---------- Files ----------
DirectoryInfo[] dirs = dir.GetDirectories(); AUTOEXEC.BAT
foreach (DirectoryInfo d in dirs) boot.ini
Console.WriteLine(d.Name); CONFIG.SYS
IO.SYS
Console.WriteLine ("---------- Files ----------"); MSDOS.SYS
FileInfo[] files = dir.GetFiles(); NTDETECT.COM
foreach (FileInfo f in files) ntldr
Console.WriteLine(f.Name); pagefile.sys
}

100
FileSystemWatcher
• Monitoring the file system using FileSystemWatcher
• Changes are signaled by events

public class FileSystemWatcher : Component, …{

public FileSystemWatcher(string path);

public string Path { get; set; } • Setting path and filter to define the
public string Filter { get; set; } part of the file system to monitor
public bool IncludeSubdirectories { get; set; } • Include/exclude subdirectories
public event FileSystemEventHandler Changed;
public event FileSystemEventHandler Created; • Events which signal changes
public event FileSystemEventHandler Deleted;
public event RenamedEventHandler Renamed;

public WaitForChangedResult WaitForChanged( • Waiting for particular events


WatcherChangeTypes types);

101
Example FileSystemWatcher
• Defining event methods
public static void Changed(object sender, FileSystemEventArgs args) {
Console.WriteLine("Changed -> {0}", args.Name);
}
public static void Created(object sender, FileSystemEventArgs args) {…}
public static void Deleted(object sender, FileSystemEventArgs args) {…}
public static void Renamed(object sender, RenamedEventArgs args) {…}

• Creating FileWatcher and registering event methods


public static void Main() {
FileSystemWatcher fsw = new FileSystemWatcher("c:\\");
fsw.IncludeSubdirectories = true;
fsw.Changed += new FileSystemEventHandler(Changed);
fsw.Created += new FileSystemEventHandler(Created);

• Setting filters and waiting for events


fsw.Filter = "*.cs";
while ( ... ) fsw.WaitForChanged(WatcherChangeTypes.All);
}
}

102
Example FileSystemWatcher
• Defining event methods
public static void Changed(object sender, FileSystemEventArgs args) {
Console.WriteLine("Changed -> {0}", args.Name);
}
public static void Created(object sender, FileSystemEventArgs args) {…}
public static void Deleted(object sender, FileSystemEventArgs args) {…}
public static void Renamed(object sender, RenamedEventArgs args) {…}
• Creating FileWatcher and registering event methods
public static void Main() {
FileSystemWatcher fsw = new FileSystemWatcher("c:\\");
fsw.IncludeSubdirectories = true;
fsw.Changed += new FileSystemEventHandler(Changed);
fsw.Created += new FileSystemEventHandler(Created);

• Setting filters and waiting for events


All
fsw.Filter = "*.cs"; Changed
while ( ... ) fsw.WaitForChanged(WatcherChangeTypes.All); Created
} Deleted
}
Renamed
103
.NET Framework Class Library
Overview
Collections
Reflection
Threading
Streaming
Processing XML Data
Networking
Windows Forms
Summary
XML in .NET
• .NET makes heavy use of XML
– see ADO.NET, WSDL, UDDI, SOAP, …

• The .NET class library provides implementations for standards like:


– XML, XSL, XPath, ...

• Both XML processing models are supported:


– DOM (Document Object Model)
– serial access similar to SAX

• Namespaces
– System.Xml
– System.Xml.Xsl
– System.Xml.XPath
– System.Xml.Schema
– System.Xml.Serialization
105
Processing XML Data
XSLT Stylesheet XslTransform

XPathNavigator
XPath

XmlDocument
XmlReader XmlWriter
XmlPathDocument
XmlDataDocument

XmlDocument

• XmlReader: Reading XML data


• XmlDocument, XmlNode: Object model for XML data (DOM)
• XmlWriter: Wrting XML data
• XPathNavigator: XPath selections
• XslTransform: Transformation of XML documents
106
XmlReader
• XmlReader for serial parsing
• Similar to SAX, but works with a pull mode
• Implementations are:
– XmlTextReader: efficient, no immediate storage of elements
– XmlValidatingReader: validates document against DTD or XSD
– XmlNodeReader: reading from an XmlNode (DOM)

107
Class XmlReader

public abstract class XmlReader {


• Properties of current element
public abstract string Name { get; } - full name
public abstract string LocalName { get; } - local name
public abstract string Value { get; } - value
public abstract XmlNodeType NodeType { get; } - type
- number of attributes
public abstract int AttributeCount { get; } - depth in document
public abstract int Depth { get; }
• Reading of next element
public abstract bool Read(); • Skipping the current element and its subs
public virtual void Skip(); • Getting the element‘s attributes
public abstract string GetAttribute(int i);
• Closing the reader
public abstract void Close();
...
}

108
Example XmlTextReader
• Reading the file addressbook.xml XML file
• Output of the values of all lastname <?xml version='1.0' encoding="utf-8"?>
elements <addressbook owner="1">
<person id="1">
XmlTextReader r; <firstname>Wolfgang</firstname>
r = new XmlTextReader("addressbook.xml"); <lastname>Beer</lastname>
<email>beer@uni-linz.at</email>
while (r.Read()) { </person>
if (r.IsStartElement("lastname")) { <person id="2">
r.Read(); // read the name <firstname>Dietrich</firstname>
Console.Write("{0}, ", r.Value); <lastname>Birngruber</lastname>
} <email>birngruber@uni-linz.at</email>
} </person>
<person id="3">
r.Close(); <firstname>Hanspeter</firstname>
<lastname>Moessenboeck</lastname>
<email>moessenboeck@uni-linz.at</email>
</person>
• Output <person id="4">
<firstname>Albrecht</firstname>
<lastname>Woess</lastname>
Beer, Birngruber, Moessenboeck, Woess, <email>woess@uni-linz.at</email>
</person>
</addressbook>

109
DOM – Document Object Model
• Construction of object structure in main memory
+ efficient manipulation of XML data
– size limitations

• XML elements are represented by XmlNode objects


• XmlDocument object represents whole XML document

Example: Loading an XML document:

XmlDocument xDoc = new XmlDocument();


xDoc.Load("file.xml");

110
Example DOM
<?xml version='1.0' encoding="utf-8"?>
<addressbook owner="1">
document <person id="1">
<firstname>Wolfgang</firstname>
<lastname>Beer</lastname>
<email>beer@uni-linz.at</email>
</person>
xml addressbook <person id="2">
<firstname>Dietrich</firstname>
owner <lastname>Birngruber</lastname>
<email>birngruber@uni-linz.at</email>
</person>
</addressbook>

person person
id id
firstname firstname

lastname lastname

email email

111
Class XmlNode (1)
public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable • Properties of node
{ - full name
- local name
public abstract string Name { get; }
- type
public abstract string LocalName { get; }
public abstract XmlNodeType NodeType { get; } - value
public virtual string Value { get; set; } - attributes
public virtual XmlAttributeCollection Attributes { get; } -…
public virtual XmlDocument OwnerDocument { get; }
public virtual bool IsReadOnly { get; }
public virtual bool HasChildNodes { get; }
public virtual string Prefix { get; set; }
• Accessing adjacent nodes
public virtual XmlNodeList ChildNodes { get; } - children
public virtual XmlNode FirstChild { get; } - siblings
public virtual XmlNode LastChild { get; } - parent
public virtual XmlNode NextSibling { get; }
public virtual XmlNode PreviousSibling { get; } - named subnodes
public virtual XmlNode ParentNode { get; }
public virtual XmlElement this[string name] { get; }
public virtual XmlElement this[string localname, string ns] { get; }

112
Class XmlNode (2)
...
public virtual XmlNode AppendChild(XmlNode newChild); • Adding and removing
public virtual XmlNode PrependChild(XmlNode newChild); nodes
public virtual XmlNode InsertAfter(XmlNode newChild,
XmlNode refChild);
public virtual XmlNode InsertBefore(XmlNode newChild,
XmlNode refChild);
public virtual XmlNode RemoveChild(XmlNode oldChild);
public virtual void RemoveAll();

public XPathNavigator CreateNavigator(); • Selection of nodes


public XmlNodeList SelectNodes(string xpath);
public XmlNode SelectSingleNode(string xpath);

public abstract void WriteContentTo(XmlWriter w); • Writing


public abstract void WriteTo(XmlWriter w);
...
}

public enum XmlNodeType {


Attribute, CDATA, Comment, Document, DocumentFragment, DocumentType, Element,

EndElement, EndEntity, Entity, EntityReference, None, Notation, ProcessingInstruction,


SignificantWhitespace, Text, Whitespace, XmlDeclaration
} 113
Class XmlDocument (1)

public class XmlDocument : XmlNode {

public XmlDocument();

public XmlElement DocumentElement { get; } • Root element


public virtual XmlDocumentType DocumentType { get; } • Document type

public virtual void Load(Stream in); • Loading the XML data


public virtual void Load(string url);
public virtual void LoadXml(string data);

public virtual void Save(Stream out); • Saving


public virtual void Save(string url);

114
Class XmlDocument (2)

• Creation of
public virtual XmlDeclaration CreateXmlDeclaration - declaration
(string version, string encoding, string standalone);
public XmlElement CreateElement(string name);
public XmlElement CreateElement - elements
(string qualifiedName, string namespaceURI);
public virtual XmlElement CreateElement
(string prefix, string lName, string nsURI);
public virtual XmlText CreateTextNode(string text); - text nodes
public virtual XmlComment CreateComment(string data); - comments

public event XmlNodeChangedEventHandler NodeChanged;


public event XmlNodeChangedEventHandler NodeChanging; • Events for changes
public event XmlNodeChangedEventHandler NodeInserted;
public event XmlNodeChangedEventHandler NodeInserting;
public event XmlNodeChangedEventHandler NodeRemoved;
public event XmlNodeChangedEventHandler NodeRemoving;
}

115
Example Creation of XML Document
XmlDocument enables building XML documents
• Create document and add declaration
XmlDocument doc = new XmlDocument();
XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(decl);

• Create root element


XmlElement rootElem = doc.CreateElement("addressbook");
rootElem.SetAttribute("owner", "1");
doc.AppendChild(rootElem);

• Create and add Person element and subelements


XmlElement person = doc.CreateElement("person");
<?xml version="1.0" encoding="IBM437"?>
person.SetAttribute("id", "1"); <addressbook owner="1">
XmlElement f = doc.CreateElement("firstname"); <person id="1">
f.AppendChild(doc.CreateTextNode("Wolfgang")); <firstname>Wolfgang</firstname>
person.AppendChild(f); <lastname>Beer</lastname>
XmlElement l = doc.CreateElement("lastname"); <email>beer@uni-linz.at</email>
... </person>
</addressbook> 116
XPath
• XPath is language for identification of elements in an XML document
• XPath expression (location path) selects a set of nodes
• A location path consists of location steps, which are separated by "/"
//step/step/step/

Examples of location paths are:


"*" selects all nodes
"/addressbook/*" selects all elements under the addressbook
elements
"/addressbook/person[1]" returns the first person element of the
addressbook elements
"/addressbook/*/firstname“ returns the firstname elements under the
addressbook elements
117
XPathNavigator
• Class XPathNavigator allows navigation in document
public abstract class XPathNavigator : ICloneable {

public abstract string Name { get; } • Properties of current
public abstract string Value { get; }
public abstract bool HasAttributes { get; }
node
public abstract bool HasChildren { get; }

public virtual XPathNodeIterator Select(string xpath); • Selection of nodes by


public virtual XPathNodeIterator Select(XPathExpression expr); XPath expression
public virtual XPathExpression Compile(string xpath); • Compilation of XPath
expression
public abstract bool MoveToNext();
public abstract bool MoveToFirstChild();
public abstract bool MoveToParent(); • Moving to adjacent nodes

}

• IXPathNavigable (implemented by XmlNode) returns XPathNavigator


public interface IXPathNavigable {
XPathNavigator CreateNavigator();
}
118
Example XPathNavigator
• Load XmlDocument and create XPathNavigator
XmlDocument doc = new XmlDocument();
doc.Load("addressbook.xml");
XPathNavigator nav = doc.CreateNavigator();

• Select firstname elements, iterate over selected elements and put out
name values
XPathNodeIterator iterator = nav.Select("/addressbook/*/firstname");
while (iterator.MoveNext())
Console.WriteLine(iterator.Current.Value);
Wolfgang Dietrich Hanspeter Albrecht
• For better run-time efficiency compile expression and use compiled
expression
XPathExpression expr =
nav.Compile("/addressbook/person[firstname='Wolfgang']/email");
iterator = nav.Select(expr);
while (iterator.MoveNext()) Console.WriteLine(iterator.Current.Value);
beer@uni-linz.at
119
XML Transformation with XSL
• XSLT is XML language for transformation of XML documents
• XSL stylesheet is an XML document with a set of rules
• Rules (templates) define transformation of XML elements
• XSLT is based on XPath;
XPath expressions define the premises of the rules (match)
• In the rule body the generation of the transformation result is defined

XSL stylesheet
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template
match=xpath-expression>
construction of transformed elements
</xsl:template>
</xsl:stylesheet>

120
Example Transformation

• Original XML document • generated HTML document


<?xml version='1.0' encoding="utf-8"?> <html>
<addressbook owner="1"> <head>
<person id="1"> <META http-equiv="Content-Type"
<firstname>Wolfgang</firstname> content="text/html; charset=utf-8">
<lastname>Beer</lastname> <title>XML-AddressBook</title>
<email>beer@uni-linz.at</email> </head>
</person> <body>
<person id="2"> <table border="3" cellspacing="10" cellpadding="5">
<firstname>Dietrich</firstname> <tr>
<lastname>Birngruber</lastname> <td>Wolfgang</td>
<email>birngruber@uni-linz.at</email> <td><b>Beer</b></td>
</person> <td>beer@uni-linz.at</td>
</addressbook> </tr>
<tr>
<td>Dietrich</td>
<td><b>Birngruber</b></td>
<td>birngruber@uni-linz.at</td>
</tr>
</table>
</body>
</html>
121
Example XSL Stylesheet
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<head> <title>XML Address Book</title> </head>
<body>
<table border="3" cellspacing="10" cellpadding="5">
<xsl:apply-templates/>
</table>
</body>
</html>
</xsl:template>

<xsl:template match="addressbook">
<xsl:apply-templates select="person"/>
</xsl:template>

<xsl:template match="person">
<tr>
<td> <xsl:value-of select="firstname"/> </td>
<td> <b><xsl:value-of select="lastname"/></b> </td>
<td> <xsl:value-of select="email"/> </td>
</tr>
</xsl:template>
</xsl:stylesheet> 122
Class XslCompiledTransform
• Class XslCompiledTransform in namespace System.Xml.Xsl
realizes XSL transformation
XslCompiledTransform xslt = new XslCompiledTransform();

xslt.Load("addressbook.xslt"); • Loading the stylesheet

xslt.Transform( • Transformation with


"addressbook.xml", reading of XML file
"addressbook.html" writing HTML file
);

123
.NET Framework Class Library
Overview
Collections
Reflection
Threading
Streaming
Processing XML Data
Networking
Windows Forms
Summary
Network Communication
• Namespace System.Net supports the implementation of
typical client/server applications

• System.Net offers implementation of:


– Internet protocols, e.g.: TCP, UDP, HTTP
– Internet services, e.g.: DNS (Domain Name System)
– other protocols, e.g.: IrDA

• System.Net.Sockets offers support for the creation of data


streams over networks

125
Addressing
• Addressing is done by classes
IPAddress: represents IP address
IPEndPoint: represents end point with IP address and port

Example:

IPAddress ipAdr = new IPAddress("254.10.120.3");


// Create a new IPEndPoint with port number 80 (HTTP)
IPEndPoint ep = new IPEndPoint(ipAdr, 80);

126
DNS (Domain Name System)
• DNS offers an IP into domain name mapping service
• Class Dns supports DNS mapping
• Class IPHostEntry is container class for address information

Example:

// Get all the addresses of a given DNS name


IPHostEntry host = Dns.Resolve("dotnet.jku.at“);
foreach (IPAddress ip in host.AddressList)
Console.WriteLine(ip.ToString());

127
Sockets

Internet 13

132.163.4.104 13 Daten 80

...
Client Server
132.163.4.104

• Sockets represent bidirectional communication channels, which allow


sending and receiving streamed data
• Client/server architectures
– client sends request to the server
– server handles request and
– sends back response
• Addressing by IP addresses and ports
• Data exchange by streams (see Streaming)
128
Sockets in .NET (1)
Server Client
– Create socket and bind it to end – Create socket und end point for
point client
– Open socket for maximal 10 clients
Socket s0 = new Socket();
IPAddress ip = IPAddress.parse(…); Socket s2 = new Socket();
IPEndPoint ep = new IPEndPoint(ip,5000); IPAddress ip = IPAddress.Parse(…);
s0.Bind(ep); IPEndPoint ep = new IPEndPoint(ip,5000);
s0.Listen(10);

… s0 s2
Server 5000
… Client

129
Sockets in .NET (2)
– Wait for connection – Connect to end point
Socket s1 = s0.Accept(); s2.Connect(ep);

… s0
Server 5000 s2
… Client
s1

– Communicate with client and – Communicate with server and


disconnect disconnect
s1.Receive(msg1); s2.Send(msg1);
... ...
s1.Send(msg2); s2.Receive(msg2);
s1.Shutdown(SocketShutdown.Both); s2.Shutdown(SocketShutdown.Both);
s1.Close(); s2.Close();

130
Example EchoServer
• Implements simple client/server application
• EchoServer accepts arbitrary data from client
and returns them unchanged to client

EchoClient_1

„test echo“
EchoServer
„test echo“

Port 5000
EchoClient_N
„hello“

„hello“

131
Example EchoServer: Class EchoServer (1)
class EchoServer {
socket s;

public bool StartUp(IPAddress ip, int port) {


try {
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
s.Bind(new IPEndPoint(ip, port));
s.Listen(10); // maximal 10 clients in queue
} catch (Exception e) { ... }
for(;;) {
Communicate(s.Accept()); // waits for connecting clients
}
}

132
Example EchoServer: Class EchoServer (2)
class EchoServer {
...
// returns all the received data back to the client
public void Communicate(Socket clSock) {
try {
byte[] buffer = new byte[1024];
while (clSock.Receive(buffer) > 0) // receive data
clSock.Send(buffer); // send back the data
clSock.Shutdown(SocketShutdown.Both); // close sockets
clSock.Close();
} catch (Exception e) { ... }
}

public static void Main() {


EchoServer = new EchoServer();
server.StartUp(IPAddress.Loopback, 5000); // start the echo server
}
}

133
Example EchoServer: Class EchoClient
class EchoClient {
...
public static void Main() {
try {
// connect to the server
Socket s = new Socket( AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
s.Connect(new InetEndPoint(IPAddress.Loopback, 5000));
s.Send(Encoding.ASCII.GetBytes("This is a test“)); // send the message
byte[] echo = new byte[1024];
s.Receive(echo); // receive the echo message
Console.WriteLine(Encoding.ASCII.GetString(echo));
} catch (Exception e) { ... }
}

134
NetworkStream
• Socket provides interface for transmitting byte or byte arrays
• Class NetworkStream provides stream for reading and writing
• Reader and Writer can be used to read and write complex data
structures
– E.g., XmlTextReader reads data in XML format

135
Example NetworkStream and XmlTextReader
• Define Socket and connect to end point
Socket s = new Socket(...);
s.Connect( new IPEndPoint(ip, port));

• Create NetworkStream for socket


NetworkStream ns = new NetworkStream(s);

• Create XmlTextReader for NetworkStream


XmlTextReader r = new XmlTextReader(ns);

• Read XML data


for (int i = 0; i<r.AttributeCount; i++) {
r.MoveToAttribute();
Console.Write(„{0} = {1}“, r.Name, r.Value);
}

136
WebRequest und WebResponse
• For loading resources from the Web

• Abstract classes with concrete implementations:

HttpWebRequest und HttpWebResponse


 communication based on HTTP protocol

FileWebRequest und FileWebResponse


 communication based on Microsoft file protocol

137
Classes WebRequest and WebResponse
public abstract class WebRequest {
public static WebRequest Create(string uri); • Creation of Web request with URI

public virtual string Method { get; set; } • HTTP method type (GET or POST)

public virtual string ContentType { get; set; } • Mime type


public virtual WebHeaderCollection Headers { get; set; } • Headers

public virtual Stream GetRequestStream(); • Stream for writing the request


public virtual WebResponse GetResponse(); • Response object

}

public abstract class WebResponse {


public virtual long ContentLength { get; set; } • Length of response

public virtual string ContentType { get; set; } • Mime Type


public virtual WebHeaderCollection Headers { get; set; } • Headers

public virtual Uri ResponseUri { get; } • URI of response

public virtual Stream GetResponseStream(); • Stream for reading the response



}
138
Example WebRequest and WebResponse
• Load the HTML page "http://dotnet.jku.at"

WebRequest rq = WebRequest.Create("http://dotnet.jku.at");
WebResponse rsp = rq.GetResponse();

// Read the lines of the HTML page


StreamReader r = new StreamReader(rsp.GetResponseStream());
for (string line = r.ReadLine(); line!=null; line = ReadLine())
Console.WriteLine(line);

139
.NET Framework Class Library
Overview
Collections
Reflection
Threading
Streaming
Processing XML Data
Networking
Windows Forms
Summary
Implementations of GUI Applications
• Window Forms is GUI framework for desktop applications
(in distinction to Web Forms for Web applications)

• Namespaces
– System.Windows.Forms: GUI controls and windows
– System.Drawing: Drawing functionality

141
Design of Windows Forms
• Forms
– A Form represents any window of an application
– The property BorderStyle defines how the Form appears:
• Standard
• Tool
• Borderless
• Floating Window
– Forms can contain other Forms = MDI (Multiple Document Interface)
– Forms can appear as modal dialogs
• Controls
– standard controls, e.g. Button, Label, Radiobutton, TextBox, ...
– custom controls, e.g. DataGrid, MonthCalendar
– user controls are controls which are assembled from other controls

142
Event-based GUI Applications
• Application waits for events triggered by:
– Users (Keyboard, Mouse, ...)
– Controls
– Operating system (Idle, ...)
• The class Application is responsible for starting a standard application
message loop.

public sealed class Application {


static void Run(Form mainForm);
static void Exit();
static event EventHandler ApplicationExit;
static event EventHandler Idle;
}

143
Example HelloWorld
class HelloWorldForm : Form {
Label lab;

HelloWorldForm() {
this.Text = "HelloWorldForm Titel";
this.Size = new Size(200,100);
lab = new Label();
lab.Text = "HelloWorld";
lab.Location = new Point(20, 20);
this.Controls.Add(lab);
}

public static void Main(string[] argv) {


Application.Run(new HelloWorldForm());
}
}

csc /t:winexe HelloWorldForm

144
GUI Events
• Control changes its state  Event
• Registration of EventHandler delegates at the event source object
(Control)
      
public delegate void EventHandler( object sender, EventArgs e );

Example: Register for a button click event:

Button b = new Button();


b.Click += new EventHandler(clickHandler);
...
private void clickHandler(object sender, EventArgs evArgs) { ... }

145
Example Menu
• Design of a menu for a Form object:
MainMenu m = new MainMenu();
MenuItem mi = new MenuItem("&File");
mi.MenuItems.Add(new MenuItem("&Open"));
mi.MenuItems.Add(new MenuItem("&Close"));
m.MenuItems.Add(mi);
this.Menu = m;

• Design of a context menu for a control object


ContextMenu m = new ContextMenu();
MenuItem mi = new MenuItem("&File");
mi.MenuItems.Add(new MenuItem("&Open"));
mi.MenuItems.Add(new MenuItem("&Close"));
m.MenuItems.Add(mi);
label.ContextMenu = m;

146
GUI Layout Design
• Three different ways to define layout:
– Anchor: The distance between the control and its container
remains proportionally equal
– Docking: Control remains directly docked on another component
– Custom: Implementing its own layout manager

147
Example Dynamic Layout: Anchor
• Creation of a Button that should be anchored on the left
and right side of its container:

public class AnchorExample : Form {


// ...
private void InitializeComponent() {
this.Size = new Size(200,200);
Button b = new Button();
b.Text = "Button";
b.Anchor = AnchorStyles.Left | AnchorStyles.Right;
b.Location = new Point(60,60);
this.Controls.Add(b);
}
// ...
}

148
Example Dynamic Layout: Docking
• Creation of a Button, that should dock on the left of its
container:

public class AnchorExample : Form {

public AnchorExample() {
InitializeComponent();
}

private void InitializeComponent() {


this.Size = new Size(200,200);
Button b = new Button();
b.Text = "Button";
b.Dock = DockStyle.Left;
this.Controls.Add(b);
}

149
Multiple Document Interface
• Creation of child forms inside a form = MDI
• Set the property IsMdiContainer = true in the parent form

class MdiForm : Form {

private void InitComponent() {


this.IsMdiContainer = true;
this.Size = new Size(250,250);

Form childForm = new Form();


childForm.MdiParent = this;
childForm.Size = new Size(200,200);
childForm.Show();
}
...
}

150
.NET Framework Class Library
Overview
Collections
Reflection
Threading
Streaming
Processing XML Data
Networking
Windows Forms
Summary
Summary
• .NET class library provides comprehensive support for
software development
– GUI
– networking and remoting
– XML
– multi-threading
– input and output
– text processing
– interoperating with COM
– …
• strong integration with Windows operating system
• optimized for Windows

152

Вам также может понравиться