Post on 23-Jan-2016
description
.NET Framework Library
A language independent universe of classes and components for your applications
Objectives
Provide an overview about various aspects of the .NET framework libraries not covered elsewhere in the Microsoft .NET Developer Tools Readiness Kit
Contents
Section 1: Introduction
Section 2: The System Namespace
Section 3: Collection Classes
Section 4: I/O and Networking
Section 5: Process Management
Section 6: Miscelleaneous Services
Summary
Section 1: Introduction
Looking Back
The Microsoft .NET Framework Library
Looking Back
Language Dependent Runtime Libraries C-Runtime library C++ Standard Template Library Visual Basic Runtime
API holes plugged with ActiveX controls
Discriminatory access to functionality Many APIs unsupported by Visual Basic Advanced tasks often require C/C++
Core functionality scattered all over Windows ActiveX controls, System DLLs, SDKs, IE
The .NET Framework Library
One-stop, well-organized class framework OS-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 Dev Web Forms, Web Services, Networking for Net Dev Supports Active Directory, WMI, MSMQ, Services
Section 2: The System Namespace
System.Object
The not-so-primitive "primitive" types
String and text classes
Dates, times and calendars
System console support
The Root of Everything .NET: 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
System.Object's Methods 1/2
bool System.Object.Equals(Object o) Reference identity for reference types (default) Overridden for value types to test value identity
void System.Object.Finalize() To be overridden by subclasses Called when object is garbage collected
int System.Object.GetHashCode() i.e. used with System.Collections.HashTable Should be overriden to return good hashes
Good hash distribution speeds up hash tables
Default implementation: Identity-based hash
System.Object's Methods 2/2
System.Type System.Object.GetType() Retrieves the type object for the object's class GetType() is the entry point for .NET Reflection
System.Object System.Object.MemberwiseClone() Creates a exact clone of "this" object Works through Reflection with any class
System.String ToString() To be overriden; Returns text representation Default returns qualified name of "this" class Not designed for user messages (use IFormattable)
The "Primitive" Types Traditionally perceived as "magic" or "special"
There is no primitive-type magic-ness in .NET! Very SmallTalk-like model "Primitive" types are regular framework types
However, 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
Integer Numerics
System.Int16, System.Int32, System.Int64 Standard integer (whole number) types 16,32 and 64 bit wide. Highest bit is sign Int32 is typically default language-mapped Integer Implemented framework interfaces
IFormattable: locale specific text formatting
IConvertible: standard conversion into other core types
IComparable: standard value-comparison with other objects
Parse() method provides rich from-text conversions
System.UInt16, System.UInt32, System.UInt64 Unsigned equivalents
Floating Point Numerics 1/3
System.Single, System.Double IEEE 754 floating point numbers
As used in most common programming languages
Values internally represented as fractions (narrowed values)
Good for scientific/technical use, not for business numerals
System.Single: single precision, 32-bit System.Double: double precision, 64-bit IFormattable, IComparable, IConvertible
Floating Point Numerics 2/3
System.Decimal 128 bit, 28 significant and precise digits Good for business numerals, monetary amounts IFormattable, IComparable, IConvertible
System.Double, System.Single specials Support positive and negative infinity
PositiveInfinity and NegativeInfinity constants on class
Can represent not-a-number (NaN) values NaN constant on class. NaN always compares false
Floating Point Numerics 3/3
System.Decimal specials Static value manipulation methods
Abs(d), Negate(d) – Positive/Negative sign
Truncate(d), Floor(d), Round(d,n) – Fractional part
Static arithmetic methods Add(d,d), Multiply(d,d), Subtract(d,d),Divide(d,d),Mod(d,d)
All equivalent operators are defined for the class
Doing Numerics: System.Math
System.Math class mainly supports IEEE types
Some operations for all numerics Abs(), Log(), Max(), Min(), Round(), Sign()
Operations Trigonometry: Sin(),Cos(), Tan(), Acos(), Asin() Powers and Logarithms: Pow(), Log(), Sqrt() Extremes: Min(), Max() Rouning: Floor(), Ceil(), Rint(), Round()
System.String System.String is the cross-language string
One storage method, one API, unified handling Locale-aware, always Unicode
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() and
Format() much like C's printf but safe
More Strings: System.Text Namespace
StringBuilder Super-efficient for assembling large strings
Encoders and Decoders Support character encoding and conversions ASCII, UTF-8, UTF-7, Windows Codepages Unicode encoder for full UTF-16 compliant streams
Encoder can write and decoder detect byte-order marks
Supports big-endian and little-endian Unicode encoding
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 from and to strings
The "Nothings" System.DBNull – database-equivalent NULL type System.Empty – like COM's VT_EMPTY System.Missing – used with optional args
Date and Time Support
System.DateTime class 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 for durations Can represent arbitrary timespans Can express span in arbitary units by conversion
System.TimeZone for time-zone support
Date and Time to the Max
System.Globalization.Calendar namespace
Correct date expressions based on local calendars GregorianCalendar – standard western calendar JulianCalendar HebrewCalendar JapaneseCalendar KoreanCalendar ThaiBuddhistCalendar HijriCalendar
Two-way 2/4 digit-year windowed conversion
The 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
Console.Write("Snowwhite and the {0} dwarfs", 7)
Reading from the console Read() reads on characters ReadLine() reads one full line
Other System Goodies
System.URI class Two-way parsing and construction of URIs
System.Random class Random number generator
System.Radix class Numeric base-system conversions (eg. Dec/Hex)
System.Convert class One-stop place for core type conversions
Section 3: Collection Classes
Arrays
Collection Interfaces
The Collection Classes
The Array 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
Collection Interfaces 1/2
IEnumerable Implements enumerable value set GetEnumerator() returns IEnumerator iterator
IEnumerator: Current, MoveNext(), Reset()
ICollection (inherits IEnumerable) Basic collection interface: Count(), CopyTo()
Collection Interfaces 2/2
IDictionary (inherits ICollection) Basic association container interface
Keys / Values table implementation
Add(), Remove(), Contains() and Clear() methods
IList (inherits ICollection) Basic list container interface
Add(), Remove(), Contains() and Clear() methods
Collection Classes 1/3
System.Collections.ArrayList / ObjectList Dynamic arrays implementing IList Can grow and shrink in size (unlike System.Array)
System.Collections.BitArray Super-compact array of bits
System.Collections.HashTable Fast hash-table implementing IDictionary There is no Dictionary class. Use HashTable
System.Collections.SortedList Auto-sorted, string-indexed collection
Collection Classes 2/3
System.Collections.Stack Stack implementation with Push() and Pop() Still, fully enumerable (IEnumerable)
System.Collections.Queue Queue with Dequeue() and Enqueue() Fully enumerable
Collection Classes 3/3
System.NameObjectCollectionBase Abstract class, indexed view on Hashtable Combines indexed order with Hashtable-speed Base for quite a few subsystem collections
System.NameValueCollection Comma separated string lists for same key entries
Section 4: I/O and Networking
Directories and Files
Streams, Stream Readers and Stream Writers
Isolated Storage
Networking Support
Directories and Files
Fully object-oriented way to explore the file system
System.IO.Directory represents a directory GetDirectories([mask]) gets subdirectories GetFiles([mask]) gets contained files
System.IO.File represents a file Can construct directly by providing a path Or returned from GetFiles() enumeration
Unifies file system entries and stream access!
All Open...() methods return System.IO.Stream Open(), OpenRead(), OpenWrite(), OpenText()
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
Stream Readers 1/2
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
Stream Readers 2/2
System.IO.StreamReader (implements TextReader) ReadLine() reads to newline ReadToEnd() reads full stream into string
System.IO.StringReader (implements TextReader) Simulates stream input from string
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 (implements TextWriter) Writes strings to streams with encoding support
System.IO.StringWriter Simulates streams-writes on an output string
Isolated Storage
Scoped, isolated virtual file system Scoped to User, Assembly or Application Domain Great as temporary storage location Sandboxed environment
Storage location managed by runtime system
System.IO.IsolatedStorage.IsolatedStorageFile Container for virtual file system Static methods for access/creation of storages
[...] IsolatedStorageFileStream Stream implementation on isolated storage Behaves like any ordinary file
The Net in .NET: 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
Request and Response Classes
System.Net.WebRequest class Base class for network request/response protocols Abstract base for HttpWebRequest
Create requests through WebRequest.Create()
Plug in new protocol handlers with RegisterPrefix() System.Net natively supports HTTP and HTTPS
Request can be populated through stream WebRequest.GetRequestStream()
Request is executed on GetResponse() Data through WebResponse.GetReponseStream()
Protocol Support Classes
Manage connectivity through ServicePoint Connections managed by ServicePointManager Per-Endpoint configuration of connection params
System.Net.EndPoint information in ServicePoint Base class for endpoints System.Net.IPEndPoint
Represents an IP endpoint with IPAdress and port
System.Net.IpxEndPoint Represents an IPX endpoint
System.Net.DNS Access to DNS nameservers and name resolution
IP Sockets
System.Net.Sockets.Socket for raw sockets send with Send(), receive with Receive()
Socket.Connect() connects to EndPoint Supports TCP, UDP, IP Multicast, IPX and others
Socket.Bind() and Socket.Listen() create listener
High-Level wrappers for TCP, UDP TcpClient, UdpClient provide NetworkStream
Usable with System.IO's stream readers/writers
TcpListener implements TCP listener Can pickup connection requests as Socket or TcpClient
Section 5: Process Management
Process control
Threading support
Processes System.Diagnostics.Process class
Allows creating/monitoring other processes Monitoring: All Task-Manager stats accessible
Process.Start() equivalent to Win32 ShellExecute Arguments are set via ProcessStartInfo class Supports shell verbs (print,open)
Supports waiting for termination (WaitForExit) Can register event handlers for "Exited" event
Explicit termination supported in two ways Rambo method: Kill() Nice-guy method: CloseMainWindow()
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
ThreadPool implicitly created for each process
Creating Threads
// instantiate class that will execute on threadPulsar pulsar = new Pulsar();
// create delegate for entry point on instance ThreadStart threadStart = new ThreadStart(pulsar.Run);
// create new thread object and start the threadThread thread = new Thread(threadStart);
thread.Start();
// do other things ...
// wait for thread to complete thread.Join();
Thread Synchronization Monitor System.Threading.Monitor class
Supports Wait/Pulse coordination model One thread enters Wait()
Other thread calls Pulse() to release Wait() lock
Similar to Win32 critical sections model Can synchronize on every managed object
// enter critical section or waitMonitor.Enter(this);// perform guarded actioninternalState = SomeAction( );// release lockMonitor.Exit(this);
// C# intrinsic equivalentlock (this) { internalState = SomeAction( );}
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
Threading Timers for timed callbacks
Interlocked class for lightweight locking Interlocked.Increment( ref i )
Section 6: Advanced Services
Windows 2000 Services
Diagnostics and Profiling
Windows 2000 Services System.Management
Windows Management Instrumentation (WMI)
System.Messaging Microsoft Message Queue
System.DirectoryServices Active Directory Services
System.ServiceProcess Expose .NET applications as Windows Services
Windows 2000 Event Log System.Diagnostics.EventLog class
Reading event logs Static EventLog.GetEventLogs() gets all machine logs EventLog.Log indicates the type of event log
Application, System, Security, etc.
EventLog.Entries retrieves all entries for a log EventLog.EventLogEntryCollection
Contains EventLogEntry elements
Can register event handler to monitor log continuously
Writing event logs Create new source with CreateEventSource() Write to log with WriteEntry()
Other Diagnostic Services
System.Diagnostics.PerformanceCounter Access and create performance counters
System.Diagnostics.StackTrace Creates call stack traces programmatically
System.Diagnostics.Trace Allows code instrumentation with diagnostic output Register listeners to receive trace events Visual Studio.NET automatically registers listeners Trace code can be conditionally disabled
No code is not generated, although calls remain
Summary
Everthing is based on System.Object
Rich set of foundation classes
Comprehensive set of general-purpose, object-oriented classes for Networking and I/O
Great access to Windows 2000 services
Rich diagnostic and monitoring facilities
Questions?