Presentation is loading. Please wait.

Presentation is loading. Please wait.

.NET Framework Class Library

Similar presentations


Presentation on theme: ".NET Framework Class Library"— Presentation transcript:

1 .NET Framework Class Library
Mark Sapossnek CS 594 Computer Science Department Metropolitan College Boston University This session will provide an overview of the .NET Framework Class Library, starting with the System Namespace, the System.Object and other system types, and will cover other topics such as collections, I/O and Network, Threading and Synchronization, Reflection, Remoting, Transactions, and Exceptions.

2 Prerequisites This module assumes you understand the fundamentals of:
Programming Variables Statements Functions Loops Object-oriented programming Classes Inheritance Polymorphism Members C#

3 Learning Objectives Gain an overview of various .NET Framework classes and interfaces Be able to write programs using these classes and interfaces

4 Agenda Introduction System Namespace Collection Classes
I/O and Networking Threading and Synchronization Transactions Exceptions

5 Introduction Looking Back The Microsoft .NET Framework Class Library
Benefits of the .NET Framework Class Library

6 Introduction Looking Back
Language-dependent runtime libraries C Runtime Library C++ Standard Template Library Visual Basic Runtime Discriminatory access to functionality Many APIs unsupported by Visual Basic Advanced tasks often require C/C++ Core functionality scattered all over Windows COM/COM+, ActiveX controls, System DLLs, SDKs, IE Multi-language development was difficult COM/COM+ Libraries were unorganized Extending existing classes was difficult Multi-language development was difficult: COM provided us with the ability to develop and instantiate objects in virtually any language. However, the lack of shared system defined data types made cross-language communiction between clients and COM objects difficult. Additionally, because every language provided its own language-specific runtime and class library, developers were required to learn and entire new object model in order to write code in another language. COM/COM+ Libraries were unorganized: With COM there was no way to organize a set of related components other than building the components within the same library. This limitation made it difficult to create a sophisticated library containing a large number of classes without also creating a maintenance nightmare. Extending existing classes was difficult With COM, it was difficult to extend the functionality provided by a component unless you owned the source code. A much better solution would be to simply inherit the behavior and functionality of the existing component and override the methods you want to extend.

7 Introduction .NET Framework Class Library
One-stop, well-organized class framework O/S-independent subset submitted to ECMA Standardization backed by Microsoft, HP, Intel Subset includes most things covered here Integrates all current Windows technologies Everything in one place – for all languages Windows Forms, GDI+, printing for Windows development Web Forms, Web Services, networking for web development Supports Active Directory, WMI, MSMQ, Services You don't have to design all your .NET types from the ground up. The .NET Framework includes classes, interfaces, and value types that help expedite and optimize the development process and give you access to system functionality. To facilitate interoperability between languages, the .NET Framework types are CLS-compliant and can be used from any language compiler that targets the Common Language Runtime. The .NET Framework includes types that encapsulate data structures, perform I/O, give you access to information about a loaded class, and provide a way to invoke .NET Framework security checks, as well as classes that encapsulate exceptions, and other helpful functionality such as data access, server controls and rich GUI generation. These types are designed to be the foundation on which .NET applications, components, and controls are built. The .NET Framework provides both abstract base classes and class implementations derived from those base classes. You can use these derived classes "as is" or derive your own classes from them. Also provided are interfaces and default implementations of those interfaces. To get the interface's functionality, you can either implement the interface yourself or you can use or derive a class from one of the runtime-based classes that implements the interface. Notes on ECMA Standardization: On October 31, 2000, Hewlett-Packard, Intel Corporation, and Microsoft jointly submitted proposed draft standards to ECMA, an international standards organization, for use in defining the C# Programming Language (ECMA TC39/TG2) and the Common Language Infrastructure (ECMA TC39/TG3). The official submissions are available from the ECMA web site at

8 Introduction Benefits
Cross-language interoperability Simplifies multi-language development, effectively providing a common language API Supplies a standard set of classes, interfaces, and structures for any language targeting .NET CLR Consistent and unified programming model Replaces many existing COM libraries Object-oriented and extensible class library Inheritance, polymorphism and method overloading Abstract base classes, Interfaces

9 Agenda Introduction System Namespace Collection Classes
I/O and Networking Threading and Synchronization Transactions Exceptions

10 System Namespace System.Object The not-so-primitive "primitive" types
String and text classes Dates, times, and calendars System console support Standard interfaces A namespace can be seen as a container for some classes in much the same way that a folder on your file system contains files. It is also possible for namespaces to contain other namespaces, just as folders on your file system can contain other folders as well. The root namespace for the types in the .NET Framework is the System namespace. This namespace includes classes that represent the base data types used by all applications: Object (the root of the inheritance hierarchy), Byte, Char, Array, Int32, String, etc. Many of these types correspond to the primitive data types that your language compiler uses. When you write code using .NET Framework types, you can, if you wish, use your language's corresponding type when a runtime-based type is expected.

11 System Namespace Namespaces Example
Namespace MyProject { using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; Using System.Data Public class Form1 : Form } The initial namespace command indicates that everything following the opening curly brace is part of a namespace called MyProject. Later on in the same file, a class called Form1 is declared. Because this class been declared inside the namespace, its ‘real’ name not Form1 but MyProject.Form1. This name is commonly known as its fully-qualified name.

12 System Namespace System.Object
Base class for each and every type Inheritance from System.Object is typically implicit All simple and complex types share the same base Single base class makes framework consistent Collection classes can be used for everything Intrinsic model for handling variant types Strongly typed--no pointers, no structures Much less error-prone than COM's VARIANT type System.Object is a reference type Value types (internally) inherit from ValueType Special class derived from Object

13 System Namespace System.Object Methods
System.Object.Equals(Object o) Test if two types are equal System.Object.ReferenceEquals(Object o) Test if two references are to the same object System.Object.Finalize() To be overridden by subclasses. Called when object is garbage collected System.Object.GetHashCode() Used with System.Collections.HashTable Should be overriden to return good hashes Good hash distribution speeds up hash tables Default implementation: identity-based hash

14 System Namespace System.Object Methods
System.Object.GetType() Retrieves the type object for the object's class GetType() is the entry point for .NET Reflection System.Object.MemberwiseClone() Creates an exact clone of this object Works through Reflection with any class ToString() To be overriden; returns text representation Default returns qualified name of this class Not designed for user messages (use IFormattable)

15 System Namespace System.Object Examples
Public class Person { String name; public override string ToString(){ return name; } Name n1 = new Name(“Fred”); Name n2 = new Name(“Fred”); Name n3 = n2; //n2 & n3 point to the same object if (n1 == n2) … // false if (n2 == n3) … // true if (n1.Equals(n2)) … // true if (n2.Equals(n3)) … // true The first example shows the typical usage of the ToString method. By default, the ToString method returns the name of the class, but you’ll frequently want to override it for your own class. For most value types it is pretty obvious what this will represent. For example, a Person class could use ToString() to return the anme of the Person represented by this object. The second example highlights the difference between the ‘==‘ operator and the Equals() method. Note that because Equals() is inherited from the top-level Object class, its argument is an object, which means that we need to case it to a Name class before we can access any member of the Name class.

16 System Namespace “Primitive” Types
Traditionally perceived as "magic" or "special" There is no primitive-type magic in .NET! Very Smalltalk-like model "Primitive" types are regular framework types Still exposed as language-intrinsic types C#: bool, int, long, string, double, float... Visual Basic.NET: Boolean, Integer, String... "Primitives" are mostly value-types Exception: System.String is reference type "Primitive" Types are not so primitive anymore Full-featured classes, rich functionality

17 System Namespace System.String
System.String is the cross-language string One storage method, one API, unified handling Locale-aware, always Unicode String is immutable Methods that appear to modify a String actually construct a new one Use String.Format or StringBuilder class instead of string concatenation Strings can be interned One standard copy is kept Can compare references An instance of String is "immutable" because its value cannot be modified once it has been created. Methods that appear to modify a String actually return a new instance of String containing the modification. Use the StringBuilder class if it is necessary to modify the contents of a string-like object directly. An "index" is the position of a character within a string, and is counted starting from zero. For example, the first character in a string is at index position zero. Comparison and search procedures are case-sensitive and use the CurrentCulture of the current thread unless otherwise specified. By definition, any String, including the empty string, compares greater than a null reference; and two null references compare equal to each other. When conducting textual comparisons one should use the Compare and Equals methods provided by String. These operators compare String objects for reference equality, unless they are overloaded by the language/compiler. However, the Environment makes it possible for String objects that are assigned literal values to be compared with the relational operators. This works for string literals only. A dynamically created string (one obtained via StringBuilder or one that has been created via the String methods such as Remove, Replace, and Trim) cannot be textually compared with the relational operators. The Compare and Equals methods must be used in this case, and should be used in general.

18 System Namespace System.String
Fully featured string-handling capabilities Forward and reverse substring searches IndexOf(), LastIndexOf(), StartsWith(), EndsWith() Whitespace stripping and padding Trim(), PadLeft(), PadRight() Range manipulation and extraction Insert(), Remove(), Replace(), Substring(), Join(), Split() Character casing and advanced formatting ToLower(), ToUpper() Format() much like C's printf but safe

19 System Namespace System.String Example
// string comparison Public static int Main() { string s =“abc”; string s1; s1 = s; // s1 and s refer to the same object string s2 = “abc”; if (s1 == s2) Console.WriteLine(“Strings are equal”); else Console.WriteLine(“This shouldn’t happen!”); return 0 } As mentioned earlier, you use the Equals() method to compare object content. The only exception to this rule is the string class, where the == and != operators have been overloaded to provide content comparison as shown in this example.

20 System Namespace System.Text.StringBuilder
Efficient way to build up a string by concatenating, replacing, inserting and removing substrings Automatically increases buffer size Can control manually too

21 System Namespace Other Core Types
System.Byte, System.SByte – Single byte numeric System.Char – Single Unicode character System.Boolean – True or False logical value System.Guid 128-bit, universally unique identifier Built-in generator: System.Guid.NewGuid() Intrinsic conversions to and from strings, byte arrays The "Nothings" System.DBNull – database-equivalent NULL type System.Empty – like COM's VT_EMPTY System.Missing – used with optional args

22 System Namespace Date and Time Support
System.DateTime struct for dates and times Virtually unlimited date values (100 AD to 9999 AD) Date and Time arithmetics built-in AddDays(), AddSeconds()... Sophisticated, locale-aware formatting and parsing System.TimeSpan struct for durations Can represent arbitrary timespans Can express span in aribitary units by conversion System.TimeZone for time-zone support

23 System Namespace System.Console
System.Console class for console I/O Supports standard in, standard out, standard error Writing to the console Write() or WriteLine() Supports String.Format syntax Reading from the console Read() reads on characters ReadLine() reads one full line Console.Write("Snow White and the {0} dwarfs", 7);

24 System Namespace Other System Goodies
System.URI class Two-way parsing and construction of URIs System.Random class Random number generator System.Convert class One-stop place for core type conversions

25 System Namespace Standard Interfaces
IFormattable: Provides functionality to format the value of an object Format method: Formats the value of the current instance as specified. IDisposable: Provides explicit control of releasing resources

26 System Namespace String.Format and IFormattable
Implement IFormattable for custom formatting of your own types Use IServiceProvider to get culturally-aware delimiters for numbers and date/time Implement ICustomFormatter to override default formatting for built-in types String.Format(“Please order {0} widgets at {1} each.”, i, f); String.Format(“{0:U}”, DateTime.Now); interface IFormattable { String Format(String format, IServiceObjectProvider sop); } You use the String.Format method to produce a formatted output. The String.Format takes a string containing a format and a variable number of objects. The {0} is the first argument; {1} is the second argument, and so on.

27 System Namespace IDisposable Example
class ResourceWrapper : IDisposable { private IntPrt handle; // Pointer to an external resource private OtherResource otherRes; bool disposed = false; private void freeState () { // Free your own state if (!disposed) { CloseHandle (handle); dispose = true; } } // Free your own state, call dispose on all state you hold, // and take yourself off the Finalization queue public void Dispose () { freeState(); OtherRes.Dispose(); GC.Suppress.Finalization(this); // Free your own state (NOT other state you hold) and // give your parent a chance to finalize public void Finalize () { freeState(); Base.Finalize(); } Class instances often encapsulate control over resources not managed by the runtime (Hwnds, Database connections etc). There needs to be both an explicit and an implicit way to free those resources. The implicit control is provided by implementing the protected method Finalize() on Object. The GC calls this method at some point after there are no longer any valid references to the object. The explicit control is provided by a Dispose() method from the IDisposable interface. The consumer of the object should call this method when he is done using the object and can be done even if other references to the object are alive. Relation with the C# Using Statement The using statement obtains one or more resources, executes a statement, and then disposes of the resource. using-statement: using ( resource-acquisition ) embedded-statement resource-acquisition: local-variable-declaration expression A resource is a class or struct that implements System.IDisposable, which includes a single parameterless method named Dispose. Code that is using a resource can call Dispose to indicate that the resource is no longer needed. If Dispose is not called, then automatic disposal eventually occurs as a consequence of garbage collection.

28 Agenda Introduction System Namespace Collection Classes
I/O and Networking Threading and Synchronization Transactions Exceptions

29 Collection Classes Arrays Collection Interfaces The Collection Classes
The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, arrays, hashtables and dictionaries.

30 Collection Classes Arrays
The only collection outside Collections namespace System.Array class Mapped to language-intrinsic arrays Polymorphic, stores System.Object elements Arbitrary number of dimensions, lengths Specified at creation time (CreateInstance) After construction, array dimensions are fixed Supports sorting Self-comparing IComparable objects External comparisons with IComparer Supports binary searches on sorted arrays An element is a value in the Array. The length of an Array is size of an Array; that is, the number of elements it can contain. The rank of an Array is the number of dimensions in the Array. The lower bound or lowbound of a dimension of an Array is the starting index of that dimension of the Array; a multidimensional Array can have different bounds for each dimension. Type objects provide information about array type declarations. Array objects with the same array type share the same Type object. The Array.Copy method can be used to copy elements not only between Array instances but also between standard arrays of different types; it handles type casting automatically.

31 Collection Classes Arrays Example
public static void Main() { // Create and initialize a new int array and a new Object array. int[] myIntArray = new int[5] { 1, 2, 3, 4, 5 }; Object[] myObjArray = new Object[5] { 26, 27, 28, 29, 30 }; // Copy the first two elements from the int array to the Object array. Array.Copy( myIntArray, myObjArray, 2 ); // Print the values of the modified arrays. Console.WriteLine( "\nAfter copying the first two elements of the int array to the Object array," ); Console.Write( "int array: " ); PrintValues( myIntArray ); Console.Write( "Object array:" ); PrintValues( myObjArray ); // Copy the last two elements from the Object array to the int array. Array.Copy( myObjArray, myObjArray.GetUpperBound(0) - 1, myIntArray, myIntArray.GetUpperBound(0) - 1, 2 ); } The example illustrates how Array.Copy can be used to copy elements between a standard array of type int and a standard array of type Object

32 Collection Classes Collections Interfaces
IEnumerable Supports simple iteration over the collection GetEnumerator() returns IEnumerator iterator IEnumerator: Current, MoveNext(), Reset() IEnumerator Iterator for enumerable collections Properties and methods: Current(), MoveNext(), Reset() IEnumerable must support the ForEach semantics of Microsoft Visual Basic and C#. COM classes that allow enumerators will also implement this interface.

33 Collection Classes Enumerating a Set of Items
All types offer standard mechanism for item iteration System.Collections.IEnumerable interface GetEnumerator returns object dedicated to item iteration public interface IEnumerable { IEnumerator GetEnumerator(); } Enumerators are intended to be used only to read data in the collection. Enumerators cannot be used to modify the underlying collection. When an enumerator is instantiated, it takes a snapshot of the current state of the collection. The enumerator does not have exclusive access to the collection and multiple enumerators can have access to the same collection at the same time. Therefore, any operation that involves writing to the collection, such as adding, modifying or deleting, can cause IEnumerator.Current or IEnumerator.MoveNext to throw an exception. Two enumerators instantiated from the same collection at the same time might not have exactly the same snapshots of the collection. public interface IEnumerator { Boolean MoveNext(); Object Current { get; } void Reset(); }

34 Collection Classes IEnumerable and IEnumerator
// Construct a type that manages a set of items // This type must offer a public GetEnumerator method SetType st = new SetType(...); // To enumerate items, request the enumerator IEnumerator e = st.GetEnumerator(); // Advance enumerator’s cursor until no more items while (e.MoveNext()) { // Cast the Current item to the proper type ItemType it = (ItemType) e.Current; // Use the item any way you want Console.WriteLine(“Do something with this item: “ + it); } This example shows how to use IEnumerable and IEnumerator interfaces and the usage of GetEnumerator().

35 Collection Classes Collections Interfaces
ICollection (derived from IEnumerable) Basic collection interface: Count(), CopyTo(), IsSynchronized() IDictionary (derived from ICollection) Basic association container interface Keys / Values table implementation Item indexer looks up a value given its key Add(), Remove(), Contains() and Clear() methods IList (derived from ICollection) A collection whose objects can be individually indexed Item indexer looks up a value given its index

36 Collection Classes Collection Classes
System.Collections.ArrayList Dynamic arrays implementing IList Can grow and shrink in size (unlike System.Array) System.Collections.BitArray Compact array of bits System.Collections.HashTable Fast hash-table implementing IDictionary Uses HashCode of object There is no Dictionary class; use HashTable System.Collections.SortedList Auto-sorted, string- and integer- indexed collection No duplicates The capacity of an ArrayList is the number of elements the list can hold. As elements are added to an ArrayList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly. Indexes in this collection are zero-based. The size of a BitArray is controlled by the client; indexing past the end of the BitArray throws an ArgumentException. Indexes in this collection are zero-based. The objects used as keys in a Hashtable must implement or inherit the Object.GetHashCode and Object.Equals methods. If key equality is simply reference equality, the inherited implementation of these methods would suffice. Furthermore, these methods must produce the same results when called with the same parameters while the key exists in the Hashtable. Key objects must be immutable, as long as they are used as keys in the Hashtable. A SortedList internally maintains two arrays to store the entries to the list; that is, one array for the keys and another array for the associated values. An entry is a key-and-value pair.

37 Collection Classes System.Collections.ArrayList
using System; using System.Collections; public class SampleArrayList { public static void Main() { // Create and initialize a new ArrayList. ArrayList myAL = new ArrayList(); myAL.Add("Hello"); myAL.Add("World"); myAL.Add("!"); // Display the properties and values. Console.WriteLine( "myAL" ); Console.WriteLine( "\tCount: {0}", myAL.Count ); Console.WriteLine( "\tCapacity: {0}", myAL.Capacity ); Console.Write( "\tValues:" ); PrintValues( myAL );} public static void PrintValues( IEnumerable myList ) { System.Collections.IEnumerator myEnumerator = myList.GetEnumerator(); while ( myEnumerator.MoveNext() ) Console.Write("\t{0}", myEnumerator.Current ); Console.WriteLine(); } This example illustrates how to create and initialize an ArrayList, and how to print out its values.

38 Collection Classes Other Collection Classes
System.Collections.Stack Stack implementation with Push() and Pop() Fully enumerable (implements IEnumerable) System.Collections.Queue Queue with Dequeue() and Enqueue() Fully enumerable Stack is implemented as a circular buffer. Push is an O(n) operation; Pop is an O(1) operation. Queues are useful for storing messages in the order they were received for sequential processing. This class implements a queue as a circular array. Objects stored in a Queue are inserted at one end and removed from the other. When the number of elements in the Queue reaches its capacity, the capacity is automatically increased to accommodate more elements. The NameObjectCollectionBase class creates a Hashtable and an associated array of zero-based indexes that refer to the elements of the Hashtable. Accessing a specific element using the array of indexes is faster than using the hash code of the element's key. In addition, the array of indexes preserves the order in which the elements were entered into the Hashtable. Unlike the Hashtable class, this class uses keys of type System.String, allows duplicate keys and supports keys that are a null reference (in Visual Basic Nothing). Hash codes are derived using a case-insensitive hashing algorithm. The NameValueCollection is based on the NameObjectCollectionBase class. But, unlike the NameObjectCollectionBase, this class stores multiple string values under a single key. This class is used for headers, query strings and form data.

39 Collection Classes System.Collections.Stack
using System; using System.Collections; public class SamplesStack { public static void Main() { // Create and initialize a new Stack. Stack myStack = new Stack(); myStack.Push("Hello"); myStack.Push("World"); myStack.Push("!"); Console.WriteLine( "myStack" ); Console.WriteLine( "\tCount: {0}", myStack.Count ); Console.Write( "\tValues:" ); PrintValues( myStack ); } public static void PrintValues( IEnumerable myCollection ) { System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator(); while ( myEnumerator.MoveNext() ) Console.Write( "\t{0}", myEnumerator.Current ); Console.WriteLine(); } This example illustrates how to create and add values to a Stack, and how to print out its values.

40 Collection Classes System.Collections.Queue
using System; using System.Collections; public class SamplesQueue { public static void Main() { Queue myQ = new Queue(); myQ.Enqueue("Hello"); myQ.Enqueue("World"); myQ.Enqueue("!"); Console.WriteLine( "myQ" ); Console.WriteLine( "\tCount: {0}", myQ.Count ); Console.Write( "\tValues:" ); PrintValues( myQ ); } public static void PrintValues( Ienumerable myCollection ) { System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator(); while ( myEnumerator.MoveNext() ) Console.Write( "\t{0}", myEnumerator.Current ); Console.WriteLine(); This example illustrates how to create and add values to a Queue, and how to print out its values.

41 Collection Classes System.Collections.Specialized
NameObjectCollectionBase Abstract class, indexed view on HashTable Combines indexed order with Hashtable-speed NameValueCollection Sorted collection of string values and string keys StringDictionary Unsorted, string values and string keys

42 Agenda Introduction System Namespace Collection Classes
I/O and Networking Threading and Synchronization Transactions Exceptions

43 I/O and Networking Directories and Files
Streams, Stream Readers and Stream Writers Networking Support The System.IO namespace contains types that allow synchronous and asynchronous reading from and writing to data streams and files. The difference between a file and a stream is not always hard and fast, but the following distinctions are useful. A file is an ordered and named collection of a particular sequence of bytes having persistent storage. Therefore, with files, one thinks in terms of directory paths, disk storage, and file and directory names. Streams provide a way to write and read bytes to and from a backing store that can be one of several storage mediums. Just as there are several backing stores other than disks, there are several kinds of streams other than file streams. For example, there are network, memory, and tape streams.

44 I/O and Networking Directories and Files
Provides a fully object-oriented way to explore the file system System.IO.Directory and System.IO.File provide static methods to manipulate directories and files, respectively System.IO.DirectoryInfo and System.IO.FileInfo provide instance methods to manipulate directories and files, respectively

45 I/O and Networking Directories and Files
System.IO.DirectoryInfo represents a directory GetDirectories([mask]) gets subdirectories GetFiles([mask]) gets contained files System.IO.FileInfo represents a file Can construct directly by providing a path Or returned from GetFiles() enumeration All OpenX() methods return System.IO.Stream Open(), OpenRead(), OpenWrite(), OpenText()

46 I/O and Networking Streams
Abstract base stream: System.IO.Stream Read(), Write() for basic synchronous access Full asynchronous support Call BeginRead() or BeginWrite() and pass callback Callback is invoked as soon as data is received. Asynchronous call completed with EndRead()/EndWrite() System.IO.FileStream Can open and access files directly Actual type returned by File.Open() System.IO.MemoryStream Constructs a stream in-memory The Stream class supports the mixing of synchronous and asynchronous reads and writes on the same stream, regardless of whether the operating system allows this. Stream provides default implementations of asynchronous read and write operations in terms of their synchronous implementations, and provides default implementations of synchronous read and write operations in terms of their asynchronous implementations. The design of the System.IO classes provides simplified stream composing. Base streams can be attached to one or more pass-through streams that provide the desired functionality. A reader or writer can be attached to the end of the chain so that the desired types can be read or written easily.

47 I/O and Networking Stream Readers
Higher level access to Stream reading functions System.IO.BinaryReader Designed for typed access to stream contents Read methods for most core data types ReadInt16(), ReadBoolean(), ReadDouble(), etc. System.IO.TextReader Abstract base class for reading strings from streams System.IO.StreamReader (inherits TextReader) ReadLine() reads to newline ReadToEnd() reads full stream into string System.IO.StringReader (inherits TextReader) Simulates stream input from string The StreamReader class implements a TextReader for reading characters from a Stream. StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. StreamReader defaults to UTF-8 encoding unless specified otherwise, instead of defaulting to the ANSI code page for the current system. UTF-8 handles Unicode characters correctly and gives consistent results on localized versions of the operating system.

48 I/O and Networking Stream Writers
High-level access to Stream writing functions System.IO.BinaryWriter Designed for typed writes to streams >15 strongly typed overloads for Write() method System.IO.TextWriter Abstract base class for writing strings to streams Includes placeholder-formatted strings System.IO.StreamWriter (inherits TextWriter) Writes strings to streams with encoding support System.IO.StringWriter Simulates streams--writes on an output string StreamWriter is designed for character output in a particular Encoding, whereas subclasses of Stream are designed for byte input and output. StreamWriter defaults to UTF8Encoding unless specified otherwise. UTF-8 handles Unicode characters correctly and gives consistent results on localized versions of the operating system.

49 I/O and Networking Stream Reader Example
// Reading Text Files File fIn = NewFile(“C:\\dotNet Projects\\Readme.txt”); StreamRead strm = fIn.OpenText(); String sLine; do { sLine = strm.ReadLine(); AddItem(sLine); } while (sLine != null); Strm.close(); This example illustrates an usage of Stream Reader.

50 I/O and Networking Stream Writer Example
public class MyWriter { private Stream s; public MyWriter(Stream stream) { s = stream; } public void WriteDouble(double myData) { byte[] b = myData.GetBytes(); // GetBytes is a binary representation of // a double data type. s.Write(b,0,b.Length); } public void Close() { s.Close(); } This example creates a writer, which is a class that can take data of some type and convert it to a byte array that can be passed to a stream. In this scenario, you create a class that has a constructor with a stream argument. From here, you can expose whatever write methods are necessary. You must convert whatever you are writing to a byte[]. After obtaining the byte[] b, it is written to the stream s by the Write method.

51 I/O and Networking System.Net
System.Net contains all network protocol support Low-level support for IP sockets and IPX Application level protocol implementations (HTTP) Authentication methods for HTTP Basic, Digest, NTLM Challenge/Reponse Full cookie support for HTTP

52 I/O and Networking Request and Response Classes
System.Net.WebRequest class Abstract base class for network request/response protocols Base class for HttpWebRequest Create requests through WebRequest.Create() Plug in new protocol handlers with RegisterPrefix() HttpWebRequest natively supports HTTP and HTTPS Request can be populated through stream WebRequest.GetRequestStream() Request is executed on GetResponse() Data through WebResponse.GetReponseStream() The HttpWebRequest class contains support for the properties and methods defined in WebRequest along with additional properties and methods that enable the user to interact directly with the HTTP protocol. You should never directly create an instance of HttpWebRequest. Instead, you should call WebRequestFactory.Create. If the scheme for the URI is " or " Create will return an HttpWebRequest instance. The HttpWebResponse class contains support for the properties and methods included in WebResponse with additional elements that enable the user to interact directly with the HTTP protocol.You should never directly create an instance of HttpWebResponse. It is returned as result of a call to HttpWebRequest.GetResponse.

53 I/O and Networking System.Net.HttpWebRequest
HttpWebRequest HttpWReq = (HttpWebRequest)WebRequestFactory.Create( " HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse(); The first example creates an HttpWebRequest for the URI " The second example returns an HttpWebResponse from an HttpWebRequest.

54 Agenda Introduction System Namespace Collection Classes
I/O and Networking Threading and Synchronization Transactions Exceptions

55 Threading and Synchronization
Process control Threading support Synchronization

56 Threading Process System.Diagnostics.Process class
Allows creating/monitoring other processes Monitoring: All Task Manager statistics accessible Process.Start() equivalent to Win32 ShellExecute Arguments are set via ProcessStartInfo class Supports shell verbs (print, open) Supports waiting for termination Can register event handlers for the Exited event Explicit termination supported in two ways Rambo method: Kill() Nice-guy method: CloseMainWindow() A Process component provides access to an executable running on a computer. A process, in the simplest terms, is a running application. A thread is the basic unit to which the operating system allocates processor time. A thread can execute any part of the process code, including parts currently being executed by another thread. The Process component is a useful tool to monitor applications. Using the Process component, you can obtain a list of processes that are running, or start a new process. A Process component is used to access system processes. Once a Process component has been initialized, it can then be used to obtain information about the running process, such as the set of threads, loaded modules (.dll or .exe's), or performance information such as the amount of memory the process is using. Once the Process component has obtained information about the associated process, it will not try to obtain it again until you call the Refresh method.

57 Threading System.Threading.Thread
Every .NET application is fully multi-threaded No more haggling with threading models Except in COM/Interop scenarios, of course. Trade-Off: Must take care of synchronization System.Thread represents a system thread Threads are launched with entry point delegate Object-oriented threading model No arguments passed to entry point Thread launch-state is set on object hosting the delegate Automatic ThreadPool for each app domain The System.Threading namespace provides classes and interfaces that enable multi-threaded programming. This namespace includes a ThreadPool class that manages groups of threads, a Timer class that enables a delegate to be called after a specified amount of time, and a Mutex class for synchronizing mutually-exclusive threads. System.Threading also provides classes for thread scheduling, wait notification, and deadlock resolution.

58 Threading Creating Thread
// Instantiate class that shall execute on thread Pulsar pulsar = new Pulsar(); pulsar.SomeData = 1234; // Create delegate for entry point on instance ThreadStart threadStart = new ThreadStart(pulsar.Run); // Create new thread object and start the thread Thread thread = new Thread(threadStart); thread.Start(); // Do other things ... // Wait for thread to complete thread.Join();

59 Synchronization System.Threading.Monitor
System.Threading.Monitor class Supports Enter/TryEnter/Exit coordination model Similar to Win32 critical sections model Supports Wait/Pulse/PulseAll coordination model One thread enters Wait(obj) Other thread calls Pulse(obj) to release Wait(obj) lock Can synchronize on any managed object // Enter critical section or wait Monitor.Enter(this); // Perform guarded action internalState = SomeAction( ); // Release lock Monitor.Exit(this); // C# intrinsic equivalent lock (this) { internalState = SomeAction( ); }

60 Synchronization More Threading
Synchronization with WaitHandle Mutex: Single synchronization point Mutex.WaitOne() waits for mutex to be available Mutex.ReleaseMutex() releases mutex lock AutoResetEvent, ManualResetEvent *.WaitOne() waits for event to be signaled Set() sets event, Reset() resets event state Static WaitAny() / WaitAll() for multiple waits Timer class for timed callbacks Interlocked class for lightweight locking Interlocked.Increment( ref i )

61 Agenda Introduction System Namespace Collection Classes
I/O and Networking Threading and Synchronization Transactions Exceptions

62 Transactions Transaction Fundamentals Manual Transactions
Automatic Transactions Transaction-based applications have been available for years. Early TP applications were extremely specialized programs that required a developer to have an in-depth knowledge operating systems and business logic. These systems were expensive, reliable, and costly to modify. Since those early days, TP programming has become less specialized and more widespread. ADO, OLE DB, ODBC, and MSMQ resource APIs enable manual transaction processing, which is one of two transaction models available to .NET Framework developers. A manual transaction allows the developer to explicitly begin a transaction boundary, control each connection and resource enlistment within the boundary, determine the outcome of the transaction (commit or abort), and end the transaction. Although this model offers measured control over a transaction, it lacks some of the ease built into the automatic transaction model. For example, there is no automatic enlistment and coordination between data stores in a manual transaction. Further, transactions do not flow from object to object, as is the case in automatic transactions. Microsoft Transaction Server (MTS), COM+ 1.0, and the Common Language Runtime support the same automatic, distributed transaction model. Once an ASP.NET page, WebMethod, or .NET Framework class is marked to participate in a transaction, it will automatically execute within the scope of a transaction. You can control an object's transactional behavior by setting a transaction attribute value on the page, Webmethod, or class. The attribute value, in turn, determines the transactional behavior of the instantiated object. Thus, based on the declared attribute value, an object will automatically participate in an existing or ongoing transaction, be the root of a new transaction, or never participate in a transaction at all. (The syntax to declare the transaction attribute varies slightly in a .NET Framework class, an ASP.NET page, and a WebMethod.) The declarative transaction attribute predicts how an object participates in a transaction, and is something you configure programmatically. Although this declarative level represents the logic of a transaction, it is one step removed from the physical transaction. A physical transaction occurs when a transactional object accesses a data resource, such as a database or message queue. The transaction boundary associated with the object automatically flows to the appropriate resource manager. An associated driver, such as OLE DB, ODBC, or ADO, looks up the transaction in the object's context and enlists in the transaction through the Distributed Transaction Coordinator (DTC). The entire physical transaction occurs automatically.

63 Transactions Transaction Fundamentals
ACID Properties: Atomicity, Consistency, Isolation, Durability Transaction Boundary Transaction boundary varies depending on the transaction model you select for your application: manual or automatic Distributed Transactions TP Monitors Transactions Manager Resource Manager Atomicity A transaction is a unit of work in which a series of operations occur between the BEGIN TRANSACTION and END TRANSACTION statements of an application. A transaction executes exactly once and is atomic — all the work is done or none of it is. Operations associated with a transaction usually share a common intent and are interdependent. By performing only a subset of these operations, the system could compromise the overall intent of the transaction. Atomicity eliminates the chance of processing a subset of operations. Consistency Since a transaction preserves the consistency of data, transforming one consistent state of data into another consistent state of data, you can regard a transaction as a unit of integrity. Consistency requires that data bound by a transaction be semantically preserved. Some of the responsibility for maintaining consistency falls to the application developer who must make sure that all known integrity constraints are enforced by the application. For example, in developing a money-transfer application, you should avoid arbitrarily moving decimal points during the transfer. Isolation A transaction is a unit of isolation — allowing concurrent transactions to behave as though each was the only transaction running in the system. Isolation requires that each transaction appear to be the only transaction manipulating the data store even though other transactions may be running at the same time. A transaction should never see the intermediate stages of another transaction. Transactions attain the highest level of isolation when they are serializable. At this level, the results obtained from a set of concurrent transactions are identical to the results obtained by running each transaction serially. Because a high degree of isolation can limit the number of concurrent transactions, some applications reduce the isolation level in exchange for better throughput. Durability A transaction is also a unit of recovery. If a transaction commits, the system guarantees that its updates will persist, even if the computer crashes immediately after the commit. Specialized logging allows the system's restart procedure to complete unfinished operations, making the transaction durable. A transaction has a beginning, an end, and occurs exactly once. As a transaction executes, various transaction-aware resources may participate or enlist into the transaction. If within the scope of a transaction your application connects to a database, for example, the transaction flows to that resource and extends the transaction boundary to include the database server. Within a given transaction boundary, all participating resources share the same transaction identifier. You can design transactions to span processes and computers. Thus, a transaction boundary is an abstraction for managing consistency across process and computer boundaries.

64 Transactions Manual Transactions -- ADO.NET
Connection object has BeginTransaction method that returns a Transaction object Call Commit or Rollback on Transaction object A manual transaction allows the developer to explicitly begin a transaction boundary, control each connection and resource enlistment within the boundary, determine the outcome of the transaction (commit or abort), and end the transaction. Although this model offers measured control over a transaction, it lacks some of the ease built into the automatic transaction model. For example, there is no automatic enlistment and coordination between data stores in a manual transaction. Further, transactions do not flow from object to object, as is the case in automatic transactions. If you choose to control a distributed transaction manually, you must manage recovery, concurrency, security, and integrity. In other words, you must apply all the programming technique necessary to maintain the ACID properties associated with transaction processing.

65 Transactions Automatic Transactions
Automatic Transactions and ASP.NET Automatic Transactions and Web Services Automatic Transactions and Framework Class Library Voting in an Automatic Transaction Transaction-based applications have been available for years. Early TP applications were extremely specialized programs that required a developer to have an in-depth knowledge operating systems and business logic. These systems were expensive, reliable, and costly to modify. Since those early days, TP programming has become less specialized and more widespread. ADO, OLE DB, ODBC, and MSMQ resource APIs enable manual transaction processing, which is one of two transaction models available to .NET Framework developers. A manual transaction allows the developer to explicitly begin a transaction boundary, control each connection and resource enlistment within the boundary, determine the outcome of the transaction (commit or abort), and end the transaction. Although this model offers measured control over a transaction, it lacks some of the ease built into the automatic transaction model. For example, there is no automatic enlistment and coordination between data stores in a manual transaction. Further, transactions do not flow from object to object, as is the case in automatic transactions. Microsoft Transaction Server (MTS), COM+ 1.0, and the Common Language Runtime support the same automatic, distributed transaction model. Once an ASP.NET page, WebMethod, or .NET Framework class is marked to participate in a transaction, it will automatically execute within the scope of a transaction. You can control an object's transactional behavior by setting a transaction attribute value on the page, Webmethod, or class. The attribute value, in turn, determines the transactional behavior of the instantiated object. Thus, based on the declared attribute value, an object will automatically participate in an existing or ongoing transaction, be the root of a new transaction, or never participate in a transaction at all. (The syntax to declare the transaction attribute varies slightly in a .NET Framework class, an ASP.NET page, and a WebMethod.) The declarative transaction attribute predicts how an object participates in a transaction, and is something you configure programmatically. Although this declarative level represents the logic of a transaction, it is one step removed from the physical transaction. A physical transaction occurs when a transactional object accesses a data resource, such as a database or message queue. The transaction boundary associated with the object automatically flows to the appropriate resource manager. An associated driver, such as OLE DB, ODBC, or ADO, looks up the transaction in the object's context and enlists in the transaction through the Distributed Transaction Coordinator (DTC). The entire physical transaction occurs automatically.

66 Transactions Automatic Transactions and ASP.NET
Directives Descriptions NotSupported This value indicates that the page does not run within the scope of transactions. Supported The page will run in the context of an existing transaction, if one exists. If not, it will run without a transaction. Required The page requires a transaction. It will run in the context of an existing transaction, if one exists. If not, it will start one. RequiredNew The page requires a transaction and a new transaction will be started for each request. The ASP.NET framework supports automatic transactions on Windows By inserting a transaction directive in your ASP.NET page, you can instruct the page to participate in an existing transaction, begin a new transaction, or never participate in a transaction. You can indicate the level of transaction support on a page by placing the directive in your code. For example, you can ensure that the page activities always execute in the scope of a transaction by inserting the following directive: page Transaction=”Required” %> The default transaction state is None, which indicates that the transaction context will be ignored by the ASP.NET framework. There is no explicit directive for this value; in other words, you cannot add page Transaction=”None” to your page. Instead, simply omit the transaction directive to apply the default value.

67 Automatic Transactions and Web Services
Using the TransactionMode enumeration property on the WebMethod metadata attribute WebService Language=”C#” %> using System; using System.Data; using System.Data.SQL; using System.Web.Services; public class TransactionStuff : WebService { [WebMethod(TransactionMode=TransactionMode.Required)] public void DeleteDatabase() { SQLConnection sqlConn = new SQLConnection( "Bar", "sa", "", "northwind"); SQLDataSetCommand sqlAdapter1 = new SQLDataSetCommand( "delete orders", sqlConn); SqlConn.Execute(); } Like ASP.NET Web Forms, ASP.NET Web Services offers a developer the option to execute their code within the scope of an automatic transaction. A transaction ensures that all interactions with resource managers like SQL Servers, MSMQ Servers, Oracle Servers, and SNA Servers maintain the ACID properties required to run robust distributed applications. You can declare an automatic transaction by using the custom enumeration property, Transaction, on the WebMethod metadata attribute of a WebMethod. The declaration begins a new transaction each time a client calls the WebMethod.

68 Automatic Transactions and Framework Class Library
Programming Model TransactionAttribute Constructor Variations [Transaction(TransactionOption.Required)] public class Bar() { //. . . } Instances of a .NET Framework class can participate in an automatic transaction, as long as you prepare the class to do so. Each resource accessed by a class instance, or object, enlists in the transaction. For example, if an object uses ADO.NET to post money on an account in a database, the resource manager for the database determines if it should execute in a transaction and, if so, it enlists the Instances of a .NET Framework class can participate in an automatic transaction, as long as you prepare the class to do so. Each resource accessed by a class instance, or object, enlists in the transaction. For example, if an object uses ADO.NET to post money on an account in a database, the resource manager for the database determines if it should execute in a transaction and, if so, it enlists the database in the transaction automatically. You can use Transaction, transaction, TransactionAttribute, and transactionattribute interchangeably [TransactionAttribute(TransactionOption.NotSupported)] [TransactionAttribute(TransactionOption.Support)] [TransactionAttribute(TransactionOption.Required)] [TransactionAttribute(TransactionOption.RequiresNew)]

69 Transactions Voting in Automatic Transactions
Using AutoCompleteAttribute Using SetAbort and SetComplete // try to do something crucial to transaction completing if ( !DoSomeWork() ) { ContextUtil.SetAbort(); } .NET Framework classes and ASP.NET pages can vote to commit or abort their current transaction. The absence of an explicit vote in your code casts a commit vote by default. The default commit, however, may decrease the performance of your application by lengthening the time it takes for each transaction to release expensive resources. Explicit voting also allows your class or page to abort a transaction if it encounters a significant error. Again, you can improve your application's performance by catching a fatal error early in the transaction, ending the transaction, and releasing resources. Using AutoComplete The AutoCompleteAttribute indicates that the transaction governing the object will automatically SetComplete() if the method call returns normally. If the method call throws an exception, the transaction will be aborted. For components marked with ComEmulate, AutoComplete must be marked on the interface implemented by the component, not on the method implementation. Using SetAbort and SetComplete You can use Microsoft.ComServices.ContextUtil, which exposes the SetComplete or SetAbort members, to explicitly commit or abort a transaction. SetComplete indicates that your object votes to commit its work; SetAbort indicates that your object encountered a problem and votes to abort the ongoing transaction. A transaction is neither committed nor aborted until it reaches the end of the page. Further, a single abort vote from any object participating in the transaction causes the entire transaction to fail.

70 Agenda Introduction System Namespace Collection Classes
I/O and Networking Threading and Synchronization Transactions Exceptions

71 Exceptions Introduction The Exception Object
Best Practices for Handling Exceptions Programs need to be able to uniformly handle errors and exceptions that occur during execution. The design of error-tolerant software is greatly assisted by the .NET Framework Common Language Runtime. First, the runtime eliminates many common errors that result from improperly using pointers and automatically converting types. It does this by insuring that any program executed by the runtime is type safe. Second, the runtime provides a platform for notifying programs of errors in a uniform way, even if the error occurs in a module written in a different language from the module catching the error. All .NET Framework methods indicate failure by throwing exceptions. Exceptions offer several advantages to other methods of error notification. Failures do not go unnoticed. Bad values do not continue to get propagated through the system. And finally, you don't have to remember to check return codes. The runtime provides excellent support for exception handling by allowing programs to check for program anomalies and to respond to these with minimum impact on the program's normal execution. Exception-handling code can be easily added to increase program reliability.

72 Exceptions What is an Exception?
An exception is any error condition or unexpected behavior encountered by an executing program Exceptions can come from an executing program or from the runtime environment To the runtime, an exception is an object that inherits from the System.Exception class An exception is any error condition or unexpected behavior encountered by an executing program. Exceptions can come from an executing program or from the runtime environment. As a developer, you are most concerned with program exceptions, which are thrown by the program or the runtime when a condition occurs that could potentially lead to a program malfunction. To the runtime, an exception is an object that inherits from the System.Exception class. It is thrown from an area of code where a problem has occurred to the part of code that is designed to handle the problem. The type of exception determines which area of code will handle the problem, as will the contents of the exception object.

73 Exceptions The Exception Object
An Exception object is an instance of the Exception class, the base class from which all exceptions inherit Properties of the Exception class: The StackTrace property The InnerException property The Message property The HelpLink property The Exception class has several properties that make debugging an exception easier. These properties include: The StackTrace property of the Exception class contains a stack trace that is invaluable when determining where an error occurred. The InnerException property can be used to create and preserve a series of exceptions during exception handling. It can be used to create a new exception that contains exception(s) previously caught. The original exception can be captured by the second exception in the InnerException property, allowing code that handles the second exception to examine the additional information. For example, suppose you have a function that reads a file and formats the data that it reads. The code tries to read from the file, but a FileException is thown. The function catches the FileException and throws a BadFormatException. In this case, the FileException could be saved in the InnerException property of the BadFormatException, enabling the code that catches the BadFormatException to examine the InnerException to discover what caused the initial error. To improve the caller’s ability to determine the reason an exception is thrown, it is desirable at times for a method to catch an exception thrown by a helper routine and, then to throw an exception more indicative of the error that has occurred. A new and more meaningful exception can be created, where the inner exception reference can be set to the original exception. This more meaningful exception can be thrown to the caller. Note that with this functionality, it is possible to create a series of linked exceptions that terminates with the exception that was first thrown. The Message property contains information that provides details concerning the cause of an exception. The HelpLink property can hold a URL (or URN) to a help file that can be used to provide extensive information concerning why the exception occurred. In most cases, it is a best practice to only throw and catch exception objects, though the runtime only requires that objects derive from System.Object (and not from System.ValueType). The CLS and C# require that exception objects are derived from System.Exception. Most of the classes that inherit from Exception do not implement additional members or provide additional functionality; they simply inherit from Exception. It is the hierarchy of the exception classes, their names, and the information they carry which allows the exceptional conditions to be handled and execution of the code to continue.

74 Exceptions Best Practices
Simple catch and display Catch block order matters Write most specific catch blocks first, then least specific catch (Exception e) { Console.WriteLine (e); }  A well thought out set of error handling code blocks can make a program more robust and less prone to crashing. The following are some suggestions on best practices concerning exception handling: Simple Catch and Display You can use console.writeline() to print the exception at a command prompt. catch (Exception e) { Console.WriteLine (e); }  Catch Block Order Always order exceptions from most specific to least specific. That way, you will handle the specific exception before it is passed to a more general catch block. Using StackTrace with an exception You can use the StackTrace object to obtain a stack trace from an exception. The following program creates a stack trace and the output is indicated at the end of the code snippet.

75 Exceptions Best Practices
Using StackTrace with an exception try { Level1(); } catch (Exception e) { StackTrace st = new StackTrace(e, true); Console.WriteLine("Stack Trace:"); for (int i = 0; i < st.FrameCount; i++) { // Display the stack frame…

76 Conclusion Everything is based on System.Object
Rich set of foundation classes Comprehensive set of general-purpose, object-oriented classes for networking and I/O Every .NET application is fully multi-threaded Use transactions selectively Follow best practices for handling exceptions

77 Resources .NET Framework SDK


Download ppt ".NET Framework Class Library"

Similar presentations


Ads by Google