1 / 77

.NET Framework Class Library

.NET Framework Class Library. Mark Sapossnek CS 594 Computer Science Department Metropolitan College Boston University. Prerequisites. This module assumes you understand the fundamentals of: Programming Variables Statements Functions Loops Object-oriented programming Classes

lan
Download Presentation

.NET Framework Class Library

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. .NET Framework Class Library Mark SapossnekCS 594 Computer Science Department Metropolitan College Boston University

  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. IntroductionLooking 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

  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 • http://msdn.microsoft.com/net/ecma/ • 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

  8. IntroductionBenefits • 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

  11. System NamespaceNamespaces 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 … }

  12. System NamespaceSystem.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 NamespaceSystem.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 NamespaceSystem.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 NamespaceSystem.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

  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 NamespaceSystem.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

  18. System NamespaceSystem.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 NamespaceSystem.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 }

  20. System NamespaceSystem.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 NamespaceOther 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 NamespaceDate 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 NamespaceSystem.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 NamespaceOther 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 NamespaceStandard 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 NamespaceString.Format and IFormattable • String.Format • 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);}

  27. System NamespaceIDisposable Example class ResourceWrapper : IDisposable { private IntPrt handle; // Pointer to an external resourceprivate 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(); }

  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

  30. Collection ClassesArrays • 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

  31. Collection ClassesArrays 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 ); }

  32. Collection ClassesCollections 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()

  33. Collection ClassesEnumerating 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();} public interface IEnumerator { Boolean MoveNext(); Object Current { get; } void Reset();}

  34. Collection ClassesIEnumerable and IEnumerator // Construct a type that manages a set of items// This type must offer a public GetEnumerator methodSetType st = new SetType(...);// To enumerate items, request the enumeratorIEnumerator e = st.GetEnumerator();// Advance enumerator’s cursor until no more itemswhile (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);}

  35. Collection ClassesCollections 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 • Add(), Remove(), Contains() and Clear() methods

  36. Collection ClassesCollection 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

  37. Collection ClassesSystem.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(); } }

  38. Collection ClassesOther 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

  39. Collection ClassesSystem.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(); } }

  40. Collection ClassesSystem.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(); } }

  41. Collection ClassesSystem.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

  44. I/O and NetworkingDirectories 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 NetworkingDirectories 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 NetworkingStreams • 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

  47. I/O and NetworkingStream 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

  48. I/O and NetworkingStream 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

  49. I/O and NetworkingStream 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();

  50. I/O and NetworkingStream 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(); } }

More Related