+ All Categories
Home > Documents > The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System...

The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System...

Date post: 12-Jan-2016
Category:
Upload: diana-thompson
View: 213 times
Download: 0 times
Share this document with a friend
Popular Tags:
103
The .NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz University of Linz, Institute for System Software, 2004 blished under the Microsoft Curriculum License
Transcript
Page 1: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

The .NET Framework Class Library

Dr. Wolfgang BeerDr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz

© University of Linz, Institute for System Software, 2004published under the Microsoft Curriculum License

Page 2: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

.NET Framework Class LibraryOverview Collections StringsReflectionThreading StreamingProcessing XML Data NetworkingWindows FormsSummary

Page 3: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

3

.NET Class Library

.NET Technology

Betriebssystem (WinXP, 2000, ...)

Common Language Runtime

VB C++ C# JScript J#

MS VisualStudio.NET

Text Editor

WebMatrix

WebServiceStudio

.NET Framework .NET Development Tools

.NET Base Class Library (BCL)

ADO.NET and XML

ASP.NETWeb Forms Web Services

Mobile Internet Toolkit

WindowsForms

Page 4: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

6

ADO.NET and XML

.NET Base Class Library (BCL)

.NET Class Library

Web Forms Web ServicesMobile Internet Toolkit

WindowsForms

ASP.NETSystem.Web

Configuration SessionState

Caching Security

ServicesDescription

Discovery

Protocols

UIHtmlControls

WebControls

Design ComponentModel

System.Windows.Forms

Imaging

Drawing2D

Text

Printing

System.Drawing

System.Data

Common

OleDb

SQLTypes

SqlClient

System.Xml

XPath

XSLT Serialization

Globalization

Diagnostics

Configuration

Collections

Resources

Reflection

Net

IO

Threading

Text

ServiceProcess

Security Runtime

InteropServices

Remoting

Serialization

Page 5: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

.NET Framework Class LibraryOverview Collections StringsReflectionThreading StreamingProcessing XML Data NetworkingWindows FormsSummary

Page 6: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

11

Collections

• Types for dealing with sets, lists and dictionaries

<<interface>>IEnumerable

<<interface>>ICollection

<<interface>>IList

<<interface>>IDictionary

BitArray Queue Stack

Hashtable SortedListArrayList Array

<<interface>>IEnumerator

Page 7: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

12

<<interface>>IEnumerable

<<interface>>IEnumerator

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

}

IEnumerable and IEnumerator (1)

• Anything which is enumerable is represented by interface IEnumerable

• IEnumerator realizes an iterator

interface IEnumerable { IEnumerator GetEnumerator(); }

Page 8: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

13

int[] a = {1, 6, 8, 9, 15}; // object of abstract type Arrayforeach (int i in a) System.Console.WriteLine(i);

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:

Page 9: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

14

<<interface>>IEnumerable

<<interface>>ICollection

Interface ICollection

• Basic interface for collections

int Count {get;}– number of elements

bool IsSynchronized {get;}– collection synchronised?

object SyncRoot {get;}– returns object for synchronisation

void CopyTo(Array a, int index);– copies the elements into array

(starting at position index)

interface ICollection {//---- Properties int Count {get;}bool IsSynchronized {get;}object SyncRoot {get;}//---- Methods void CopyTo(Array a, int index);

}

Page 10: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

15

Interface IList

• Interface for object collections with a defined order

<<interface>>IEnumerable

<<interface>>ICollection

<<interface>>IList

<<interface>>IDictionary

interface IList {object this [ int index ] {get; set;}

int Add(object value);void Insert(int index,object value);void Remove(object value); void RemoveAt(int index); void Clear();

bool Contains(object value);

bool IsFixedSize {get;}bool IsReadOnly {get;}...

}

• Indexer for accessing elements based on position

• Adding, inserting and removing elements

• Testing containment of elements

• Is list of fixed length?• Is list read-only?

Page 11: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

16

<<interface>>IEnumerable

<<interface>>ICollection

<<interface>>IList

Array ArrayList

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 : ICloneable, IList, ICollection, IEnumerable {

//---- Propertiespublic int Length {get;} public int Rank {get;}

//----- Methodenpublic int GetLength(int dimension); public int GetLowerBound(int dimension); public int GetUpperBound(int dimension); public object GetValue(int idx); public object GetValue(int[] idx); public void SetValue(object val, int idx); public void SetValue(object val, int[] idx);

• Getting length and number of dimensions

• Getting length and lower and upper bound for each dimension

• Getting and setting values

Page 12: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

17

Class Array (2)

…//----- statische Methodenpublic static int IndexOf(Array a, object val);public static int LastIndexOf(Array a, object value);

public static void Sort(Array a); public static void Sort(Array a, IComparer comparer); public static void Reverse(Array a);

public static int BinarySearch(Array a, object val);public static int BinarySearch(Array a, object val, IComparer c);

public static void Copy(Array srcArray, Array destArray, int len);public static Array CreateInstance(Type elementType, int len);public static Array CreateInstance(Type elementType, int[] len);…

}

• Searching for positions of elements

• Sorting of arrays

• Binary search in sorted arrays

• Copying and creating arrays

Page 13: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

18

Example: Array

• Creation of array with Array.CreateInstance

which is equivalent to

• Setting values and sorting

• Output of elements with foreach statement

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

int[] i = new int[6];

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

Elemente: 1 2 3 4 5 9

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

Page 14: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

19

<<interface>>IEnumerable

<<interface>>ICollection

<<interface>>IList

Array ArrayList

Class ArrayList (1)

• ArrayList realizes dynamically growing list

public class ArrayList : IList, ICollection, IEnumerable, ICloneable {

public ArrayList();public ArrayList(ICollection c);public ArrayList(int capacity);

virtual int Capacity {get;set;}

public virtual ArrayList GetRange(int index, int count); public virtual void AddRange(ICollection c); public virtual void InsertRange(int index, ICollection c);

public virtual void SetRange(int i, ICollection c); public virtual void RemoveRange(int index, int count); …

• Constructors

• Capacity

• Accessing,inserting, setting, removing elements

Page 15: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

20

Class ArrayList (2)

…public virtual void Sort(); public virtual void Reverse(); public virtual int BinarySearch(object o); public virtual int LastIndexOf(object o);

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

public virtual void CopyTo(Array a); public virtual object[] ToArray();

public virtual void TrimToSize(); }

• Sorting and searching

• Creation of wrappers

• Copying elements

• Trimming to actual size

Page 16: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

21

Example: ArrayList

• Creating ArrayList and adding values

• Sorting the elements in the ArrayList

• Inverting the elements in the ArrayList

ArrayList a = new ArrayList(); a.Add(3); al.Add(1); al.Add(2); al.Add(4); al.Add(9);

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

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

Elemente: 1 2 3 4 5 9

Elemente: 9 4 3 2 1

Page 17: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

22

Sorting: IComparable and IComparer

• IComparable is interface for types with order

Classes implementing IComparable are– values 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

IComparer implementations:– Comparer, CaseInsensitiveComparer: for string comparisons

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

}

public interface IComparable {int CompareTo(object obj); // -1 if x < y, 0 if x == y, 1 if x > y

}

Page 18: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

23

Example: IComparer

• Creation of an array of strings

• Sorting the strings using a case-insensitive comparer

• Binary search for a name

• Inverting the array

string[] names = string[] {“frank”, “john”, “Bill”, “paul”, “Frank”};

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

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

names = Array.Reverse(names, ciComparer);

Page 19: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

26

<<interface>>IEnumerable

<<interface>>ICollection

<<interface>>IList

<<interface>>IDictionary

Interface IDictionary

• IDictionary is interface for collections of key-value pairs

interface IDictionary : ICollection, IEnumerable {

ICollection Keys {get;};ICollection Values {get;};

object this[object key] {get; set;}

void Add(object key, object value);void Remove(object key);bool Contains(object key);

IDictionaryEnumerator GetEnumerator();

…}

• Keys• Values

• Indexer for accessing elements by key

• Adding,removing,containment

• Accessing an iterator for key-value pairs

Page 20: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

28

<<interface>>IEnumerable

<<interface>>ICollection

<<interface>>IDictionary

Hashtable SortedList

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 : IDictionary, ICollection, IEnumerable, … {

public Hashtable(); public Hashtable(IDictionary d); public Hashtable(int capacity);

public virtual object this[object key] {get; set;}

public virtual bool ContainsKey(object key); public virtual bool ContainsValue(object val);

protected IHashCodeProvider Hcp {get; set;}…

}

• Constructors

• Indexer for accessing elements by key

• Testing, if key and value contained

• Setting and getting a HashCodeProviders !

Page 21: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

30

HashCodeProvider

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

• On creation of Hashtable the HashCodeProvider can be set (has to be done together with compatible comparer)

Example:

public interface IHashCodeProvider {int GetHashCode( object obj );

}

public class Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, … {public Hashtable(IHashCodeProvider hcp, IComparer cmp); …

}

Hashtable table = new Hashtable( new CaseInsensitiveHashCodeProvider(), new CaseInsensitiveComparer());

Page 22: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

31

<<interface>>IEnumerable

<<interface>>ICollection

<<interface>>IDictionary

Hashtable SortedList

Dictionary SortedList

• SortedList is second implementation of IDictionary• dynamic list of key-value pairs sorted by key!

public class SortedList : IDictionary, ICollection, … {public SortedList();public SortedList(IComparer c);

public virtual object this[object key] {get; set;};

public virtual object GetByIndex(int i); public virtual object GetKey(int i);

public virtual IList GetKeyList(); public virtual IList GetValueList();

public virtual int IndexOfKey(object key); public virtual int IndexOfValue(object value);

public virtual void RemoveAt(int i); …

}

• Constructors

• Indexer for accessing elements by key

• Accessing values and keys based on index position

• List of keys and values

• Position of key and value

• Removing an entry at a given position

Page 23: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

32

<<interface>>IEnumerable

<<interface>>IEnumerable

BitArray Queue Stack

Special Collections

• Queue

• Stack

• BitArray

public class Stack : ICollection, IEnumerable, ICloneable {public virtual void Clear(); public virtual bool Contains(object o); public virtual object Peek(); public virtual object Pop(); public virtual void Push(object o); …

}

public class Queue : ICollection, IEnumerable, ICloneable {public virtual void Clear(); public virtual bool Contains(object o); public virtual object Dequeue(); public virtual void Enqueue(object o); public virtual object Peek(); …

}

public sealed class BitArray : ICollection, IEnumerable, ICloneable {public bool this[int index] {get; set;} public int Length {get; set;}public BitArray And(BitArray val); public BitArray Not(); public BitArray Or(BitArray a); …

}

Page 24: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

.NET Framework Class LibraryOverview Collections StringsReflectionThreading StreamingProcessing XML Data NetworkingWindows FormsSummary

Page 25: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

37

String FormattingConsole.WriteLine("{0,3:X}", 10); // returns " A"

equivalent to:

string f;f = string.Format("{0,3:X}",10); Console.WriteLine(f);

C CurrencyD IntegerE Numeric E+ RepresentationF Fixed-point DecimalP Percent RepresentationX Hexadecimal Representation ...

Page 26: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

.NET Framework Class LibraryOverview Collections StringsReflectionThreading StreamingProcessing XML Data NetworkingWindows FormsSummary

Page 27: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

39

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

Page 28: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

40

Reflection Class Hierarchy

*GetEvents()

GetFields()*

GetConstructors()*

GetMethods()*

GetProperties()*

MemberInfo ObjectGetCustomAttributes()*

ConstructorInfo

EventInfo

FieldInfo

MethodBase

PropertyInfo

MethodInfo

Type

Assembly

*GetTypes()

Interfaces*

BaseType1

Page 29: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

41

Class Assembly

• Class Assembly loads assemblies and their meta-data

• Provides access to its meta-data

• Loading an assembly

• Name,storage location, entry point of the assembly

• Getting modules and all in the assembly defined types

• Getting type with name typeName

• Creation of an object of type typeName

public class Assembly {

public static Assembly Load(string name);

public virtual string FullName {get;} public virtual string Location {get;} public virtual MethodInfo EntryPoint {get;}

public Module[] GetModules();public virtual Type[] GetTypes();public virtual Type GetType(string typeName);

public object CreateInstance(string typeName);...

}

Page 30: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

42

MemberInfo ObjectGetCustomAttributes()*

ConstructorInfo

EventInfo

FieldInfo

MethodBase

PropertyInfo

MethodInfo

Type

Assembly

*GetTypes()

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 {

public abstract Type BaseType {get;};public abstract string FullName {get;};public Type[] GetInterfaces();

public bool IsAbstract {get;}; public bool IsClass {get;}; public bool IsPublic {get;};

public ConstructorInfo[] GetConstructors(); public virtual EventInfo[] GetEvents(); public FieldInfo[] GetFields(); public MethodInfo[] GetMethods(); public PropertyInfo[] GetProperties();

...

• Direct base type • Type name• List of implemented interfaces

• Properties of type

• Getting constructors, events, fields, methods, properties

Page 31: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

43

Example: Reflection (1)

• C# program "HelloWorld"

namespace Hello {using System;public class HelloWorld {

public static void Main(string[] args) {Console.WriteLine("HelloWorld");

}

public override string ToString() { return "Example HelloWorld";

} }

}

• Loading the assembly "HelloWorld.exe":

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

csc HelloWorld.cs

HelloWorld.exe

• Compiling and creating assembly

Page 32: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

44

Example: Reflection (2)

• Print all existing types in a given assembly

Type[] types = a.GetTypes();

foreach (Type t in types)

Console.WriteLine(t.FullName);

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

Page 33: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

45

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

Type hw = a.GetType("Hello.HelloWorld");

MethodInfo mi = hw.GetMethod("ToString");

object retVal = mi.Invoke(o, null);

Page 34: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

46

Attributes

• GetCustomAttributes returns attributes of type or type member

• Those can be used at run-time

public abstract class MemberInfo : ICustomAttributeProvider {public abstract object[] GetCustomAttributes( bool inherit ); public abstract object[] GetCustomAttributes( Type attributeType, bool inherit);…

}

Page 35: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

47

Example: Attributes • Definition of MyAttribute class

• Using the attribute

using System;using System.Reflection;

[AttributeUsage(AttributeTargets.All)]public class MyAttribute : Attribute { private string myName; public MyAttribute(string name) { myName = name; } public string Name { get { return myName; } }}

public class MemberInfo_GetCustomAttributes {public static void Main() {

Type t = typeof(MyClass1);MemberInfo[] membs = myType.GetMembers();

for(int i = 0; i < myMembers.Length; i++) { Console.WriteLine("\Member {0} \n", membs[i]);

Object[] attrs = membs[i].GetCustomAttributes(true);

for(int j = 0; j < attrs.Length; j++)Console.WriteLine("attribute is {0}.", attrs[j]);

}}

}

public class MyClass1 { [MyAttribute("This is an example attribute.")] public void MyMethod(int i) { return; }}

• Reading the attributes and printing them out

Page 36: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

48

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 is intended for supporting realization of .NET compiler und interpreterd

• 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

Page 37: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

49

Example: Reflection.Emit (1)

• Creation of a new assembly and module

• Definition of a new type

• Definition of a new method with parameter and return types

AssemblyName assemblyName = new AssemblyName();assemblyName.Name = "HelloWorldAssembly";AssemblyBuilder newAssembly = Thread.GetDomain().DefineDynamicAssembly(

assemblyName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder newModule =

newAssembly.DefineDynamicModule("HelloWorldModule");

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

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

MethodAttributes.Public | MethodAttributes.Virtual, retType, paramTypes);

Page 38: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

50

Example: Reflection.Emit (2)

• Defining the MSIL code for the new method

• Creating the new type

• Creating an instance of the new type and calling SayHelloTo 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);

newType.CreateType();

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

Page 39: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

.NET Framework Class LibraryOverview Collections StringsReflectionThreading StreamingProcessing XML Data NetworkingWindows FormsSummary

Page 40: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

52

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 TreadStart, WaitCallback, TimerCallback, IOCompletionCallback, …

– …

Page 41: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

53

Class Threadpublic sealed class Thread {

public Thread(ThreadStart start);

public ThreadPriority Priority {get; set;}public ThreadState ThreadState {get;}

public bool IsAlive {get;}public bool IsBackground {get; set;}

public void Start();public static void Sleep(int time);public void Suspend();public void Resume();public void Join();public void Interrupt();public void Abort();public static void ResetAbort();

public static Thread CurrentThread {get;}}

• Constructor with ThreadStart delegate

• Setting/getting the priority • Current state

• Properties liveliness, background

• Methods for controlling the thread

• Gets the currently running thread

Page 42: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

54

ThreadStart, ThreadPriority and ThreadState

public sealed class Thread {

public Thread( ThreadStart start);

public ThreadPriority Priority {get; set;}

public ThreadState ThreadState {get;}

}

public delegate void ThreadStart();

public enum ThreadPriority {Highest,AboveNormal, Normal,BelowNormal, Lowest,

}

public enum ThreadState {Background, Unstarted, Running, WaitSleepJoin, SuspendRequested, Suspended, AbortRequested, Stopped

}

Page 43: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

55

Creating a New Thread• Implementing a ThreadStart delegate

using System.Threadingpublic 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(); }

Page 44: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

56

public enum ThreadState {Background,Running,Stopped,StopRequested,Suspended,SuspendRequested,Unstarted,WaitSleepJoin

}

Thread States

• Enumeration ThreadState defines the states of a thread

unstarted

RunningSuspend

Requested

WaitSleepJoin

AbortRequested

Suspend()

Wait(),Sleep(),Join()

Abort()

Suspended

Resume()

Interrupt()

Stopped

Pulse()

Start()

State diagram (simplified)

Page 45: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

58

Thread Pools

• Class ThreadPool enable the automatic management of a collection of threads

• Used for threads that spend most of their time in the waiting state

• The system uses a collection of worker threads to manage the registered tasks

• All the tasks that are registered in a thread pool are processed by the worker threads

• But:– No priorities

– No threads that use too much processor time

– No direct access to the threads (e.g.: to stop)

Page 46: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

59

Class ThreadPoolpublic sealed class ThreadPool {

public static void GetAvailableThreads(out int w, out int aIOs);

public static void GetMaxThreads(out int w, out int aIOs);

public static bool QueueUserWorkItem( WaitCallback task);public static bool QueueUserWorkItem( WaitCallback task,

object state);}

public delegate void WaitCallback(object state );

• Number of available worker and IO threads

• Maximal number of worker and IO threads

• Registration of a task as WaitCallback delegate

• WaitCallback delegate

Page 47: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

60

Example: ThreadPool

• Definition of the task

• Getting the number worker and IO threads

• Adding a new task to the pool

public static WorkerTask(object state) {while (…) {

… // do something short Thread.Sleep(…); // then sleep

}}

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

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

Page 48: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

61

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

}}

Synchronisation with lock

• lock statement is used for synchronisation of threads when accessing common resources

• lock statement sets lock for an object

• realizes mutual exclusion

Page 49: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

62

Class Monitor

• Class Monitor realizes basic mechanism for synchronisation

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

public sealed class Monitor {public static void Enter(object obj);public static bool TryEnter(object obj);

public static void Exit(object obj);

public static void Wait(object obj);public static bool Pulse(object obj); public static void PulseAll(object obj);

}

Monitor.Enter(obj) try {

…} finally {

Monitor.Exit(obj)}

lock (obj) {…

}

• tries to get lock for obj and blocks • tries to get lock for obj and returns

• releases lock for obj

• brings thread into the waiting state, releases locks • awakens next thread waiting for obj• awakens all threads waiting for obj

Page 50: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

63

Using Monitor

• Enter blocks when lock is not available

• TryEnter tries to get lock without blocking; returns false when lock is not available

public class MonitorExample {private Queue lpt;

public void AddElemBlocking (object elem) {try {

Monitor.Enter (lpt.SyncRoot);lpt.Enqueue (elem);

} catch (Exception e) {…

}finally {

Monitor.Exit (lpt.SyncRoot);}

}

public bool AddElemNonBlocking (object elem) {try {

if (! Monitor.TryEnter (lpt.SyncRoot)) return false;

lpt.Enqueue (elem);} catch (Exception e) {

…}finally {

Monitor.Exit (lpt.SyncRoot);}return true;

}}

Enter: with blocking TryEnter: without blocking

Page 51: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

64

Wait and Pulse

• With Wait and Pulse threads can be synchronized based on an object state

Releases locks and waits to be waked up

Wakes up next or all threads waiting for obj

public static void Wait(object obj);public static bool Wait(object obj, int millies);

public static bool Pulse(object obj);public static void PulseAll(object obj);

lock (obj) {...Monitor.Wait(obj); ...

}

lock (obj) {...Monitor.Pulse(obj);...

}

Page 52: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

65

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) {lock(this) {

while (n >= size) Monitor.Wait(this);buf[tail] = ch; tail = (tail + 1) % size; n++;Monitor.Pulse(this);

}}

public char Get() {lock(this) {

while (n <= 0) Monitor.Wait(this);char ch = buf[head]; head = (head + 1) % size; n--;Monitor.Pulse(this);return ch;

}}

}

Lock buffer to retrieve characterWhile buffer is empty, release lock and wait

Wake up waiting threads

Lock buffer to add a characterWhile buffer is full, release lock and wait

Wake up waiting threads

Page 53: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

.NET Framework Class LibraryOverview Collections StringsReflectionThreading StreamingProcessing XML Data NetworkingWindows FormsSummary

Page 54: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

67

Streaming Framework

• System.IO contains types for input and output

• Base class Stream defines an abstract protocol for byte-oriented input and output

• Specialization for different media

• Streams support synchronous and asynchronous protocol

• Readers and Writers for formatting

FileStream MemoryStreamNetworkStream CryptoStreamBufferedStream

Stream

Page 55: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

68

Class Streampublic abstract class Stream : MarshalByRefObject, IDisposable {

public abstract bool CanRead { get; } public abstract bool CanSeek { get; } public abstract bool CanWrite { get; }

public abstract int Read(out byte[] buff, int offset, int count); public abstract void Write(byte[] buff, int offset, int count); public virtual int ReadByte(); public virtual void WriteByte(byte value);

public virtual IAsyncResult BeginRead(…);public virtual IAsyncResult BeginWrite(…); public virtual int EndRead(…); public virtual int EndWrite(…);

public abstract long Length { get; } public abstract long Position { get; set; } public abstract long Seek(long offset, SeekOrigin origin);

public abstract void Flush(); public virtual void Close(); ...

}

• Elementary properties of stream

• Synchronous reading and writing

• Asynchronous reading and writing

• Length and actual position

• Positioning

• Flush and close

Page 56: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

69

Readers and Writers

• Readers and Writers overtake formatting tasks

– BinaryReader and BinaryWriter for binary data

– TextReader and TextWriter for character data

FileStream MemoryStream NetworkStream

Stream

BinaryReader

BinaryWriter

TextReader

StreamReader StringReader

TextWriter

StreamWriter StringWriter

Page 57: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

70

Classes TextReader and TextWriterpublic abstract class TextReader : MarshalByRefObject, IDisposable {

public virtual int Read(); public virtual int Read(out char[] buf, int idx, int count); 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); public virtual void Write(string s); public virtual void Write(int val); ... // + overloades methods public virtual void WriteLine(); public virtual void WriteLine(bool val); ... // + overloaded methods

public virtual string NewLine { get; set; }

public abstract Encoding Encoding { get; } …

}

• Different reading operations

• Writing operations for all the primitive data types

• Writing operations with line breaks

• Characters for new line • Used encoding

Page 58: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

71

Example: StreamWriter

• Creating FileStream

• Creating StreamWriter for text output

• Putting out some text

• Closing writer and stream

using System; using System.IO; using System.Text; // for encoding definitionspublic class StreamWriterExample {

public static void Main() {

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

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

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

sw.Close();fs.Close();

}}

Page 59: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

72

Asynchronous Operations

• BeginRead and BeginWrite emit asynchronous read and write operations

public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state );

public virtual IAsyncResult BeginWrite( byte[] buffer, int offset, int count, AsyncCallback callback, object state );

• BeginRead and BeginWrite have AsyncCallback delegate parameter

• Delegate will be called upon completion of operation with IAsyncResult object

public delegate void AsyncCallback( IAsyncResult ar

);

public interface IAsyncResult {object AsyncState {get;} WaitHandle AsyncWaitHandle {get;}bool CompletedSynchronously {get;} bool IsCompleted {get;}

); • With EndRead and EndWrite

asynchronous operation is completed

public virtual int EndRead(IAsyncResult asyncResult );

public virtual void EndWrite(IAsyncResult asyncResult);

Page 60: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

73

Example: Asynchronous Read• Declaring fields for stream, buffer and callback

• Calling BeginRead of input stream with callback delegate

• Callback method: – Getting number of read bytes by EndRead– Processing data

namespace AsyncIO {public class AsyncIOTester {

private Stream inputStream; private byte[] buffer = new byte[256]; private AsyncCallback callback;

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

}

void OnCompletedRead(IAsyncResult result) {int bytesRead = inputStream.EndRead(result); … // process the data read

}…

Page 61: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

74

Files and Directories

Namespaces System.IO.File and System.IO.Directory 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

Page 62: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

79

Example: Directories and Files

• Putting out the directories and files in "c:\\"

---------- Directories ----------Documents and SettingsI386Program FilesSystem Volume InformationWINNT---------- Files ----------AUTOEXEC.BATboot.iniCONFIG.SYSIO.SYSMSDOS.SYSNTDETECT.COMntldrpagefile.sys

• Output

using System; using System.IO;public class DirectoryExample {

public static void Main() {DirectoryInfo dir = Directory.CreateDirectory("c:\\");

Console.WriteLine("---------- Directories ----------");DirectoryInfo[] dirs = dir.GetDirectories();foreach (DirectoryInfo d in dirs)

Console.WriteLine(d.Name);

Console.WriteLine ("---------- Files ----------");FileInfo[] files = dir.GetFiles();foreach (FileInfo f in files)

Console.WriteLine(f.Name);}

}

Page 63: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

80

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; } public string Filter { get; set; }

public bool IncludeSubdirectories { get; set; }

public event FileSystemEventHandler Changed; public event FileSystemEventHandler Created; public event FileSystemEventHandler Deleted; public event RenamedEventHandler Renamed;

public WaitForChangedResult WaitForChanged(WatcherChangeTypes types);

}

• Setting path and filter to define the part of the file system to monitor

• Include/exclude subdirectories

• Events which signal changes

• Waiting for particular events

Page 64: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

81

Example: FileSystemWatcher • Defining event methods

• Creating FileWatcher and registering event methods

• Setting filters and waiting for events

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) {…}

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

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

}}

Page 65: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

.NET Framework Class LibraryOverview Collections StringsReflectionThreading StreamingProcessing XML DataNetworkingWindows FormsSummary

Page 66: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

83

XML in .NET

• .NET makes heavy use of XML – see ADO.NET, WSDL, UDDI, SOAP, …

• The base 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

Page 67: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

84

Processing XML Data

XmlDocumentXmlPathDocumentXmlDataDocument

XmlWriter

XPathNavigator

XPath

• XmlReader: Reading XML data

• XmlDocument, XmlNode: Object model of XML data (DOM)

• XmlWriter: Wrting XML data

• XPathNavigator: XPath selections

• XslTransform: Transformation of XML documents

XSLT Stylesheet XslTransform

XmlDocument

XmlReader

Page 68: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

85

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)

Page 69: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

86

Class XmlReader

public abstract class XmlReader {

public abstract string Name { get; } public abstract string LocalName { get; } public abstract string Value { get; } public abstract XmlNodeType NodeType { get; }

public abstract int AttributeCount { get; } public abstract int Depth { get; }

public abstract bool Read(); public virtual void Skip(); public abstract string GetAttribute(int i);

public abstract void Close(); ...

}

• Properties of current element-full name-local name-value-type-number of attributes-depth in document

• Reading of next element • Skipping the current element and its subs • Getting the element‘s attributes

• Closing the reader

Page 70: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

87

Example: XmlTextReader

• Reading the file addressbook.xml• Output of the values of all lastname

elements

• Output

XmlTextReader r; r = new XmlTextReader("addressbook.xml");while (r.Read()) {

if (r.IsStartElement("lastname")) {r.Read(); // read the nameConsole.Write("{0}, ", r.Value);

}}r.Close();

<?xml version='1.0' encoding="utf-8"?><addressbook owner="1">

<person id="1"><firstname>Wolfgang</firstname><lastname>Beer</lastname><email>[email protected]</email>

</person><person id="2">

<firstname>Dietrich</firstname><lastname>Birngruber</lastname><email>[email protected]</email>

</person><person id="3">

<firstname>Hanspeter</firstname><lastname>Moessenboeck</lastname><email>[email protected]</email>

</person><person id="4">

<firstname>Albrecht</firstname><lastname>Woess</lastname><email>[email protected]</email>

</person></addressbook>

Beer, Birngruber, Moessenboeck, Woess,

• XML file

Page 71: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

88

DOM

• 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("datei.xml");

Page 72: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

89

Example DOM

Document

xml Addressbuch

Besitzer

Person

Vorname

Nachname

email

id

Person

Vorname

Nachname

email

id

<?xml version='1.0' encoding="utf-8"?><addressbook owner="1">

<person id="1"><firstname>Wolfgang</firstname><lastname>Beer</lastname><email>[email protected]</email>

</person><person id="2">

<firstname>Dietrich</firstname><lastname>Birngruber</lastname><email>[email protected]</email>

</person></addressbook>

Page 73: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

90

Class XmlNode (1)

public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable {

public abstract string Name { get; }public abstract string LocalName { get; }public abstract XmlNodeType NodeType { get; }public virtual string Value { get; set; }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; }

public virtual XmlNodeList ChildNodes { get; }public virtual XmlNode FirstChild { get; }public virtual XmlNode LastChild { get; }public virtual XmlNode NextSibling { get; } public virtual XmlNode PreviousSibling { get; } public virtual XmlNode ParentNode { get; }public virtual XmlElement this[string name] { get; }public virtual XmlElement this[string localname, string ns] { get; }

• Properties of node-full name-local name-type-value-attributes-…

• Accessing adjacent nodes-children-siblings -parent

-named subnodes

Page 74: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

91

Class XmlNode (2)...public virtual XmlNode AppendChild(XmlNode newChild);public virtual XmlNode PrependChild(XmlNode newChild);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();public XmlNodeList SelectNodes(string xpath); public XmlNode SelectSingleNode(string xpath);

public abstract void WriteContentTo(XmlWriter w); 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

}

• Adding and removing nodes

• Selection of nodes

• Writing

Page 75: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

92

Class XmlDocument (1)

public class XmlDocument : XmlNode {

public XmlDocument();

public XmlElement DocumentElement { get; } public virtual XmlDocumentType DocumentType { get; }

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

public virtual void Save(Stream out); public virtual void Save(string url);

• Root element • Document type

• Loading the XML data

• Saving

Page 76: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

93

Class XmlDocument (2)

public event XmlNodeChangedEventHandler NodeChanged;public event XmlNodeChangedEventHandler NodeChanging;public event XmlNodeChangedEventHandler NodeInserted;public event XmlNodeChangedEventHandler NodeInserting;public event XmlNodeChangedEventHandler NodeRemoved;public event XmlNodeChangedEventHandler NodeRemoving;

}

public virtual XmlDeclaration CreateXmlDeclaration(string version, string encoding, string standalone);

public XmlElement CreateElement(string name);public XmlElement CreateElement

(string qualifiedName, string namespaceURI);public virtual XmlElement CreateElement

(string prefix, string lName, string nsURI);public virtual XmlText CreateTextNode(string text);public virtual XmlComment CreateComment(string data);

• Creation of -declaration

-elements

- text nodes -comments

• Events for changes

Page 77: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

94

Example: Creation of XML Document

XmlDocument enables to built up XML documents

• Create document and add declaration

• Create root element

• Create and add Person element and subelements

XmlDocument doc = new XmlDocument();XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", null, null);doc.AppendChild(decl);

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

XmlElement person = doc.CreateElement("person");person.SetAttribute("id", "1");XmlElement e = doc.CreateElement("firstname");e.AppendChild(doc.CreateTextNode("Wolfgang"));person.AppendChild(e);e = doc.CreateElement("lastname");...

<?xml version="1.0" encoding="IBM437"?><addressbook owner="1">

<person id="1"><firstname>Wolfgang</firstname><lastname>Beer</lastname><email>[email protected]</email>

</person></addressbook>

Page 78: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

95

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

Page 79: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

96

XPathNavigator

• Class XPathNavigator provides navigation in document

• IXPathNavigable (implemented by XmlNode) returns XPathNavigator

public interface IXPathNavigable {XPathNavigator CreateNavigator();

}

public abstract class XPathNavigator : ICloneable {

public abstract string Name { get; }public abstract string Value { get; }public abstract bool HasAttributes { get; }public abstract bool HasChildren { get; }

public virtual XPathNodeIterator Select(string xpath);public virtual XPathNodeIterator Select(XPathExpression expr);public virtual XPathExpression Compile(string xpath);

public abstract bool MoveToNext();public abstract bool MoveToFirstChild();public abstract bool MoveToParent();…

}

• Properties of current node

• Selection of nodes by XPath expression

• Compilation of XPath expression

• Moving to adjacent nodes

Page 80: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

97

Example: XPathNavigator

• Load XmlDocument and create XPathNavigator

• Select firstname elements, iterate over selected elements and put out name values

• For better run-time efficiency compile expression and use compiled expression

XmlDocument doc = new XmlDocument();doc.Load("addressbook.xml");XPathNavigator nav = doc.CreateNavigator();

XPathNodeIterator iterator = nav.Select("/addressbook/*/firstname");while (iterator.MoveNext())

Console.WriteLine(iterator.Current.Value);

XPathExpression expr = nav.Compile("/addressbook/person[firstname='Wolfgang']/email");iterator = nav.Select(expr);while (iterator.MoveNext()) Console.WriteLine(iterator.Current.Value);

Page 81: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

98

XML Transformation with XSL

• XSLT is XML language for transformations of XML documents

• XSL stylesheet is an XML document with a set of rules

• Rules (templates) define the 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 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>

Page 82: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

99

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>

Page 83: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

100

Example Transformation

• Original XML document • generated HTML document

<html><head>

<META http-equiv="Content-Type" content="text/html; charset=utf-8"><title>XML-AddressBook</title>

</head><body>

<table border="3" cellspacing="10" cellpadding="5"><tr>

<td>Wolfgang</td> <td><b>Beer</b></td> <td>[email protected]</td>

</tr><tr>

<td>Dietrich</td> <td><b>Birngruber</b></td><td>[email protected]</td>

</tr></table>

</body></html>

<?xml version='1.0' encoding="utf-8"?><addressbook owner="1">

<person id="1"><firstname>Wolfgang</firstname><lastname>Beer</lastname><email>[email protected]</email>

</person><person id="2">

<firstname>Dietrich</firstname><lastname>Birngruber</lastname><email>[email protected]</email>

</person></addressbook>

Page 84: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

101

Class XslTransform

• Namespace System.Xml.Xsl provides support for XSLT

• Class XslTransform realizes XSL transformation

public class XslTransform {

public void Load(string url);

public XslTransform();public void Transform(string infile, string outfile,

XmlResolver resolver);

... // + overloaded methodds Load and Transform}

• Loading an XSLT stylesheet

• Transformation

Page 85: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

102

Example: Transformation with XSLXslTransform xt = new XslTransform();

xt.Load("addressbook.xsl");

xt.Transform("addressbook.xml", "addressbook.html");

Page 86: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

.NET Framework Class LibraryOverview Collections StringsReflectionThreading StreamingProcessing XML DatNetworkingWindows FormsSummary

Page 87: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

104

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

Page 88: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

105

Adressing

• Addressing is done by classesIPAddress: 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);

Page 89: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

106

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

Page 90: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

107

Sockets

• Sockets represent bidirectional communication channels, which allow sending and receiving of 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)

13

80

...

13132.163.4.104 Daten

Internet

Server132.163.4.104

Client

Page 91: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

108

Sockets in .NET (1)

Server– Create socket and bind it to end

point

– Open socket for maximal 10 clients

Socket s0 = new Socket();IPAddress ip = IPAddress.parse(…);IPEndPoint ep = new IPEndPoint(ip,5000);s0.bind(ep);s0.Listen(10);

Client– Create socket und end point for

client

Socket s2 = new Socket();IPAddress ip = IPAddress.Parse(…);IPEndPoint ep = new IPEndPoint(ip,5000);

5000

… s0Server

s2

Client

Page 92: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

109

Sockets in .NET (2)

– Wait for connection

Socket s1 = s0.Accept();

– Connect to end point

s2.Connect(ep);

s2Client

5000

… s0Server

s1

– Communicate with client and disconnect

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

– Communicate with server and disconnect

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

Page 93: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

114

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

Page 94: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

115

Example: NetworkStream and XmlTextReader

• Define Socket and connect to end point

• Create NetworkStream for socket

• Create XmlTextReader for NetworkStream

• Read XML data

Socket s = new Socket(...);

s.Connect( new IPEndPoint(ip, port));

NetworkStream ns = new NetworkStream(s);

XmlTextReader r = new XmlTextReader(ns);

for (int i = 0; i<r.AttributeCount; i++) {

r.MoveToAttribute();

Console.Write(„{0} = {1}“, r.Name, r.Value);

}

Page 95: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

116

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

Page 96: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

117

Classes WebRequest and WebResponsepublic abstract class WebRequest {

public static WebRequest Create(string uri);

public virtual string Method { get; set; }

public virtual string ContentType { get; set; }public virtual WebHeaderCollection Headers { get; set; }

public virtual Stream GetRequestStream();public virtual WebResponse GetResponse();…

}

• Creation of Web request with URI

• HTTP method type (GET oder POST)

• Mime type • Headers

• Stream for writing the request• Response object

public abstract class WebResponse {public virtual long ContentLength { get; set; }

public virtual string ContentType { get; set; }public virtual WebHeaderCollection Headers { get; set; }

public virtual Uri ResponseUri { get; }

public virtual Stream GetResponseStream();…

}

• Length of response

• Mime Type • Headers

• URI of response

• Stream for reading the response

Page 97: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

118

Example: WebRequest and WebResponse

• Load the HTML page "www.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);

Page 98: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

.NET Framework Class LibraryOverview Collections StringsReflectionThreading StreamingProcessing XML Data NetworkingWindows FormsSummary

Page 99: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

121

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

Page 100: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

122

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;

}

Page 101: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

.NET Framework Class LibraryOverview Collections StringsReflectionThreading StreamingProcessing XML Data NetworkingWindows FormsSummary

Page 102: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

131

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

Page 103: The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,

132

Preview of Base Class Library 2.0

• In .NET 2.0 the following main improvements/extensions are introduced

– Generic collections

– Reflection for generic types

– Improved support for network protocols

• FTP support

• Support for Web server implementations

• Support for network statistics

– Encryption by Data Protection API (DPAI)

– Improvements in Window Forms

• WinBar

• Layout Management

• …


Recommended