Академический Документы
Профессиональный Документы
Культура Документы
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, ...)
3
Motivation Class Library
• Building blocks in the form of classes and components
– Input/output
– GUI programming
– Networking
– Sets and lists
– Strings
– …
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
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)
interface IEnumerable
<<interface>>{ <<interface>>
IEnumerator GetEnumerator();
IEnumerable IEnumerator
}
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.
Example:
12
Interface ICollection
• Basic interface for collections
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
16
Example Array
which is equivalent to
int[] i = new int[6];
Elemente: 1 2 3 4 5 9
17
Class ArrayList (1)
• ArrayList realizes dynamically growing list
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);
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);
Elemente: 1 2 3 4 5 9
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
}
21
Example IComparer
• Creation of an array of strings
string[] names = string[] {“frank”, “john”, “Bill”, “paul”, “Frank”};
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;
23
Example IComparable (2)
Array.Sort(vArray);
dumpArray(vArray);
Array.Reverse(vArray);
dumpArray(vArray);
24
Interface IDictionary
• IDictionary is interface for collections of key-value pairs
<<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
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);
28
HashCodeProvider
• HashCodeProvider allows the creation of hash codes independent of
key objects
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!
<<interface>> i);
public virtual object GetByIndex(int • Accessing values and keys based on
ICollection
public virtual object GetKey(int i); index position
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
}
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<<interface>>
interface IEnumerable<T> {
IEnumerator<T> GetEnumerator(); IEnumerator<T>
IEnumerable<T>
}
35
IEnumerable<T> and IEnumerator<T> (3)
• Use foreach-statement with IEnumarables
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
//---- 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
40
Example IComparer<T>
Base class Person
• Comparer for Persons
//----- 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
43
Example List<T> (1)
using System;
using System.Collections.Generic;
...
List<Person> list = new List<Person>();
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
//----- 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());
47
Class Stack<T>
• Stack<T> realizes generic stack with LIFO strategy
public class Stack<T> : ICollection, IEnumerable<T> {
//----- 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>
49
Generic Dictionary Classes
• Generic types for mappings from keys to values
//----- 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
//----- 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
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>();
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
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
PropertyInfo 60
Example Reflection (1)
• C# program "HelloWorld" • Compiling and
creating assembly
namespace Hello {
using System;
public class HelloWorld {
61
Example Reflection (2)
• Print all existing types in a given assembly
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");
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);
…
}
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
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");
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);
70
Class Thread
public sealed class Thread {
public static Thread CurrentThread {get;} • Gets the currently running thread
}
71
ThreadStart, ThreadPriority and ThreadState
public delegate void ThreadStart();
using System.Threading
public class ThreadExample {
public static void RunT0() {
for(int i=0; i<10000; i++) {
Console.Write(“x“);
Thread.Sleep(100);
}
}
73
Thread States
• Enumeration ThreadState defines the states of a thread
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
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
• 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
}
}
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 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
}
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
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
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;
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
85
Class Stream
public abstract class Stream : MarshalByRefObject, IDisposable {
87
Readers and Writers
• Readers and Writers overtake formatting tasks
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()
public virtual string NewLine { get; set; } • Characters for new line
• Creating FileStream
FileStream fs;
fs = new FileStream("log.txt", FileMode.OpenOrCreate, FileAccess.Write);
• 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
100
FileSystemWatcher
• Monitoring the file system using FileSystemWatcher
• Changes are signaled by events
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;
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) {…}
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);
…
• 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
107
Class XmlReader
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
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 XmlDocument();
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
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);
• 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
<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();
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
125
Addressing
• Addressing is done by classes
IPAddress: represents IP address
IPEndPoint: represents end point with IP address and port
Example:
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:
127
Sockets
Internet 13
132.163.4.104 13 Daten 80
...
Client Server
132.163.4.104
… 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
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;
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) { ... }
}
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));
136
WebRequest und WebResponse
• For loading resources from the Web
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)
WebRequest rq = WebRequest.Create("http://dotnet.jku.at");
WebResponse rsp = rq.GetResponse();
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.
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);
}
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 );
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;
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:
148
Example Dynamic Layout: Docking
• Creation of a Button, that should dock on the left of its
container:
public AnchorExample() {
InitializeComponent();
}
149
Multiple Document Interface
• Creation of child forms inside a form = MDI
• Set the property IsMdiContainer = true in the parent form
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