Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,"— Presentation transcript:

1 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 published under the Microsoft Curriculum License

2 .NET Framework Class Library Overview Collections Strings Reflection Threading Streaming Processing XML Data Networking Windows Forms Summary

3 3.NET Class Library.NET Technology Betriebssystem (WinXP, 2000,...) Common Language Runtime VBC++C#JScriptJ# MS Visual Studio.NET Text Editor WebMatrix WebService Studio.NET Framework.NET Development Tools.NET Base Class Library (BCL) ADO.NET and XML ASP.NET Web Forms Web Services Mobile Internet Toolkit Windows Forms

4 4 Motivation Class Library Building blocks in the form of classes and components –Input/output –GUI programming –Networking –Sets and lists –Strings –… robust, stable and high quality basis enables simple and productive software development

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

6 6 ADO.NET and XML.NET Base Class Library (BCL).NET Class Library Web Forms Web Services Mobile Internet Toolkit Windows Forms ASP.NET System.Web ConfigurationSessionState CachingSecurity Services Description Discovery Protocols UI HtmlControls WebControls DesignComponent Model 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 SecurityRuntime InteropServices Remoting Serialization

7 7 Class Math (1) public sealed class Math { public const double PI = 3.14...; public const double E = 2.71...; public static T Abs(T val); // T sbyte, short, int, long, float, double, decimal public static T Sign(T val); public static T1 Min(T1 x, T1 y); // T1... T, byte, ushort, uint, ulong public static T1 Max(T1 x, T1 y); public static double Round(double x); public static double Floor(double x); public static double Ceiling(double x); …

8 8 Class Math (2) … public static double Sqrt(double x); public static double Pow(double x, double y); public static double Exp(double x); public static double Log(double x); public static double Log10(double x); public static double Sin(double x); public static double Cos(double x); public static double Tan(double x); public static double Asin(double x); public static double Acos(double x); public static double Atan(double x); }

9 9 Class Random public class Random { public Random(); public Random(int seed); public virtual int Next();// 0 <= res <= int.MaxVal public virtual int Next(int x);// 0 <= res < x public virtual int Next(int x, int y);// x <= res < y public virtual double NextDouble();// 0.0 <= res < 1.0 public virtual void NextBytes(byte[] b);// fills b with random numbers }

10 .NET Framework Class Library Overview Collections Strings Reflection Threading Streaming Processing XML Data Networking Windows Forms Summary

11 11 Collections Types for dealing with sets, lists and dictionaries

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

13 13 int[] a = {1, 6, 8, 9, 15}; // object of abstract type Array foreach (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 IEnumerable s foreach –statement can be used Example:

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

15 15 Interface IList Interface for object collections with a defined order 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?

16 16 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 { //---- Properties public int Length {get;} public int Rank {get;} //----- Methoden public 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

17 17 Class Array (2) … //----- statische Methoden public 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

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

19 19 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

20 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

21 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

22 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 } public interface IComparable { int CompareTo(object obj); // -1 if x y }

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

24 24 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 { private double x, y; public Vector(double x, double y) { this.x = x; this.y = y; } public double Length { get { return Math.Sqrt( x*x + y*y ); } } public int CompareTo(object obj) { if(obj is Vector) { if(this.Length < ((Vector)obj).Length) return -1; else if(this.Length > ((Vector)obj).Length) return 1; else return 0; } throw new ArgumentException(); }

25 25 Example: IComparable (2) Creation of array of Vector objects Vector[] vArray = { new Vector(1.5,2.3), new Vector(3,6), new Vector(2,2) }; Elements in array are sorted based on length of vectors Array.Sort(vArray); dumpArray(vArray); Array.Reverse(vArray); dumpArray(vArray);

26 26 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

27 27 IDictionaryEnumerator and DictionaryEntry IDictionaryEnumerator is iterator over key-value pairs IDictionaryEntry represents key-value pair interface IDictionary : ICollection, IEnumerable { … IDictionaryEnumerator GetEnumerator(); … } public interface IDictionaryEnumerator : IEnumerator { //----- Properties public DictionaryEntry Entry {get;}; public object Key {get;}; public object Value {get;}; } public struct DictionaryEntry { //----- Constructor public DictionaryEntry (object key, object value); //----- Properties public object Key {get;}; public object Value {get;}; }

28 28 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 !

29 29 Example: Hashtable Creating Hashtable and adding Person objects using the social security number as key Iterating over the entries and printing out values and keys Testing for containment of an entry with a particular key Hashtable h = new Hashtable(); h.Add(3181030750, new Person("Mike", "Miller")); h.Add(1245010770, new Person("Susanne", "Parker")); h.Add(2345020588, new Person("Roland", "Howard")); h.Add(1245300881, new Person("Douglas", "Adams")); foreach (DictionaryEntry x in h) Console.WriteLine(x.Value + ": " + x.Key); if (h.Contains(1245010770)) Console.WriteLine("Person mit SNr. 1245010770: " + h[1245010770]); public class Person { public Person(string fn, string ln) { … } public override string ToString() { … }... }

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

31 31 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

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

33 .NET Framework Class Library Overview Collections Strings Reflection Threading Streaming Processing XML Data Networking Windows Forms Summary

34 34 Working with Strings Classes System.String and System.Text.StringBuilder Objects of type String are immutable! Example „String": string s = "Hello"; s += ", There"; char c = s[5]; // Indexer returns ',' Operation == compares the values not the references (  Java)! string s2 = "Hello, There"; if(s == s2) // liefert true! Compare references as follows: if((object)s == (object)s2) // returns false!

35 35 Class String public sealed class String : IComparable, ICloneable, IConvertible, IEnumerable public char this[int index] {get;} public int Length {get;} public static int Compare(string strA, string strB); // Culture! public static int CompareOrdinal(string strA, string strB); // without Culture! public static string Format(string format, object arg0); public int IndexOf(string); public int IndexOfAny(char[] anyOf); public int LastIndexOf(string value); public string PadLeft(int width, char c); // s.PadLeft(10,'.');  ".....Hello" public string[] Split(params char[] separator); public string Substring(int startIndex, int length);... }

36 36 Class StringBuilder StringBuilder is more effective for manipulating strings Reserved size Length of the string Appending, inserting and removing characters Creating String object public sealed class StringBuilder { public int Capacity {get; set;} public int Length {get; set;} StringBuilder Append(...); StringBuilder AppendFormat(...); StringBuilder Insert(int index,...); StringBuilder Remove(int startIndex, int length); StringBuilder Replace(char oldChar, char newChar); string ToString(); }

37 37 String Formatting Console.WriteLine("{0,3:X}", 10); // returns " A" equivalent to: string f; f = string.Format("{0,3:X}",10); Console.WriteLine(f); CCurrency DInteger ENumeric E+ Representation FFixed-point Decimal P Percent Representation XHexadecimal Representation...

38 .NET Framework Class Library Overview Collections Strings Reflection Threading Streaming Processing XML Data Networking Windows Forms Summary

39 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

40 40 Reflection Class Hierarchy

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

42 42 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

43 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

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

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

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

47 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

48 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

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

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

51 .NET Framework Class Library Overview Collections Strings Reflection Threading Streaming Processing XML Data Networking Windows Forms Summary

52 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, … –…–…

53 53 Class Thread public 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

54 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 }

55 55 Creating a New Thread Implementing a ThreadStart d elegate using System.Threading public class ThreadExample { public static void RunT0() { for(int i=0; i<10000; i++) { Console.Write(„x“); Thread.Sleep(100); } } Creating Thread with delegate to method RunT0 and starting it public static void main(string[] args) { // main thread starts a new thread which runs RunT0 method Thread t0 = new Thread( new ThreadStart(RunT0)); t0.Start(); }

56 56 public enum ThreadState { Background, Running, Stopped, StopRequested, Suspended, SuspendRequested, Unstarted, WaitSleepJoin } Thread States Enumeration ThreadState defines the states of a thread unstarted Running Suspend Requested WaitSleepJoin AbortRequested Suspend() Wait(),Sleep(),Join() Abort() Suspended Resume() Interrupt() Stopped Pulse() Start() State diagram (simplified)

57 57 Foreground and Background Threads Two different types of threads: Foreground und Background –As long as a foreground thread is running, the program will not terminate –running background threads cannot prevent the program from terminating A background thread is created by setting the property IsBackground Thread bgThread = new Thread(new ThreadStart(…)); bgThread.IsBackground = true;

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

59 59 Class ThreadPool public 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

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

61 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

62 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

63 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

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

65 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 character While buffer is empty, release lock and wait Wake up waiting threads Lock buffer to add a character While buffer is full, release lock and wait Wake up waiting threads

66 .NET Framework Class Library Overview Collections Strings Reflection Threading Streaming Processing XML Data Networking Windows Forms Summary

67 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 Reader s and Writer s for formatting FileStreamMemoryStreamNetworkStreamCryptoStreamBufferedStream Stream

68 68 Class Stream public 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

69 69 Readers and Writers Reader s and Writer s overtake formatting tasks –BinaryReader and BinaryWriter for binary data –TextReader and TextWriter for character data FileStreamMemoryStreamNetworkStream Stream BinaryReader BinaryWriter … TextReader StreamReaderStringReader TextWriter StreamWriterStringWriter

70 70 Classes TextReader and TextWriter public abstract class TextReader : MarshalByRefObject, IDisposable { public virtual int Read(); public virtual int Read(out char[] buf, int idx, int count); 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

71 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 definitions public 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(); }

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

73 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 } …

74 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

75 75 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); public static DateTime GetLastWriteTime(string path); public static void SetCreationTime(string path, DateTime t); // sets creation date & time public static void SetLastAccessTime(string path, DateTime t); public static void SetLastWriteTime(string path, DateTime t); }

76 76 Class DirectoryInfo public sealed class DirectoryInfo : FileSystemInfo { //----- constructor public DirectoryInfo(string path); // 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 a new 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 }

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

78 78 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 }

79 79 Example: Directories and Files Putting out the directories and files in "c:\\" ---------- Directories ---------- Documents and Settings I386 Program Files System Volume Information WINNT ---------- Files ---------- AUTOEXEC.BAT boot.ini CONFIG.SYS IO.SYS MSDOS.SYS NTDETECT.COM ntldr pagefile.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); }

80 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

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

82 .NET Framework Class Library Overview Collections Strings Reflection Threading Streaming Processing XML Data Networking Windows Forms Summary

83 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

84 84 Processing XML Data XmlReader : Reading XML data XmlDocument, XmlNode : Object model of XML data (DOM) XmlWriter : Wrting XML data XPathNavigator : XPath selections XslTransform : Transformation of XML documents

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

86 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

87 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 name Console.Write("{0}, ", r.Value); } r.Close(); Wolfgang Beer beer@uni-linz.at Dietrich Birngruber birngruber@uni-linz.at Hanspeter Moessenboeck moessenboeck@uni-linz.at Albrecht Woess woess@uni-linz.at Beer, Birngruber, Moessenboeck, Woess, XML file

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

89 89 Example DOM Document xmlAddressbuch Besitzer Person Vorname Nachname email id Person Vorname Nachname email id Wolfgang Beer beer@uni-linz.at Dietrich Birngruber birngruber@uni-linz.at

90 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

91 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

92 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

93 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

94 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");... Wolfgang Beer beer@uni-linz.at

95 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

96 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

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

98 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:template match=xpath-expression> construction of transformed elements

99 99 Example XSL Stylesheet XML Address Book

100 100 Example Transformation Original XML documentgenerated HTML document <META http-equiv="Content-Type" content="text/html; charset=utf-8"> XML-AddressBook Wolfgang Beer beer@uni-linz.at Dietrich Birngruber birngruber@uni-linz.at Wolfgang Beer beer@uni-linz.at Dietrich Birngruber birngruber@uni-linz.at

101 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

102 102 Example: Transformation with XSL XslTransform xt = new XslTransform(); xt.Load("addressbook.xsl"); xt.Transform("addressbook.xml", "addressbook.html");

103 .NET Framework Class Library Overview Collections Strings Reflection Threading Streaming Processing XML Dat Networking Windows Forms Summary

104 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

105 105 Adressing Addressing is done by classes IPAddress : represents IP address IPEndPoint : represents end point with IP address and port Example: IPAddress ipAdr = new IPAddress("254.10.120.3"); // Create a new IPEndPoint with port number 80 (HTTP) IPEndPoint ep = new IPEndPoint(ipAdr, 80);

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

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

108 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 … … s0 Server s2 Client

109 109 Sockets in.NET (2) –Wait for connection Socket s1 = s0.Accept(); –Connect to end point s2.Connect(ep); s2 Client 5000 … … s0 Server 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();

110 110 Example: EchoServer Implements simple client/server application EchoServer accepts arbitrary data from client and returns them unchanged to client EchoServer EchoClient_1 EchoClient_N Port 5000 „test echo“ „hello“

111 111 Example EchoServer: Class EchoServer (1) class EchoServer { socket s; public bool StartUp(IPAddress ip, int port) { try { s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Bind(new IPEndPoint(ip, port)); s.Listen(10); // maximal 10 clients in queue } catch (Exception e) {... } for(;;) { Communicate(s.Accept()); // waits for connecting clients }

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

113 113 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) {... } }

114 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

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

116 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

117 117 Classes WebRequest and WebResponse public 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

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

119 .NET Framework Class Library Overview Collections Strings Reflection Threading Streaming Processing XML Data Networking Windows Forms Summary

120 120 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

121 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

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

123 123 Example: HelloWorld class HelloWorldForm : Form { Label lab; HelloWorldForm() { this.Text = "HelloWorldForm Titel"; this.Size = new Size(200,100); lab = new Label(); lab.Text = "HelloWorld"; lab.Location = new Point(20, 20); this.Controls.Add(lab); } public static void Main(string[] argv) { Application.Run(new HelloWorldForm()); } csc /t:winexe HelloWorldForm

124 124 GUI Events Control changes its state  Event Registration of EventHandler delegates at the event source object (Control) public delegate void EventHandler( object sender, EventArgs e ); Example: Register for a button click event: Button b = new Button(); b.Click += new EventHandler(clickHandler);... private void clickHandler(object sender, EventArgs evArgs) {... }

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

126 126 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

127 127 Example Dynamic Layout: Anchor Creation of a Button that should be anchored on the left and right side of its container : public class AnchorExample : Form { //... private void InitializeComponent() { this.Size = new Size(200,200); Button b = new Button(); b.Text = "Button"; b.Anchor = AnchorStyles.Left | AnchorStyles.Right; b.Location = new Point(60,60); this.Controls.Add(b); } //... }

128 128 Example Dynamic Layout: Docking Creation of a Button, that should dock on the left of its container : public class AnchorExample : Form { public AnchorExample() { InitializeComponent(); } private void InitializeComponent() { this.Size = new Size(200,200); Button b = new Button(); b.Text = "Button"; b.Dock = DockStyle.Left; this.Controls.Add(b); }

129 129 Multiple Document Interface Creation of child forms inside a form = MDI Set the property IsMdiContainer = true in the parent form class MdiForm : Form { private void InitComponent() { this.IsMdiContainer = true; this.Size = new Size(250,250); Form childForm = new Form(); childForm.MdiParent = this; childForm.Size = new Size(200,200); childForm.Show(); }... }

130 .NET Framework Class Library Overview Collections Strings Reflection Threading Streaming Processing XML Data Networking Windows Forms Summary

131 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

132 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 …


Download ppt "The.NET Framework Class Library Dr. Wolfgang Beer Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz © University of Linz,"

Similar presentations


Ads by Google