.NET Framework Class Library - PowerPoint PPT Presentation

1 / 77
About This Presentation
Title:

.NET Framework Class Library

Description:

Supplies a standard set of classes, interfaces, and structures for any language ... Copy the first two elements from the int array to the Object array. ... – PowerPoint PPT presentation

Number of Views:1564
Avg rating:3.0/5.0
Slides: 78
Provided by: walsonleem
Category:
Tags: net | class | framework | keys | library

less

Transcript and Presenter's Notes

Title: .NET Framework Class Library


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.C
omponentModel using System.Windows.Forms Using S
ystem.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 NamespacePrimitive 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
shouldnt 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(0U,
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 int5 1, 2,
3, 4, 5 Object myObjArray new Object5
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 enumerators 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("\t0", 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(
"\t0", 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(
"\t0", 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
  • gt15 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) Stream
Read 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()
51
I/O and NetworkingSystem.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 NetworkingRequest 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()

53
I/O and NetworkingSystem.Net.HttpWebRequest
HttpWebRequest HttpWReq (HttpWebRequest)WebReq
uestFactory.Create( "http//www.contoso.com
") HttpWebResponse HttpWResp
(HttpWebResponse)HttpWReq.GetResponse()
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()

57
ThreadingSystem.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

58
ThreadingCreating Thread
  • // Instantiate class that shall execute on
    threadPulsar pulsar new Pulsar()pulsar.SomeDa
    ta 1234
  • // Create delegate for entry point on instance
  • ThreadStart threadStart new ThreadStart(pulsar.R
    un)// Create new thread object and start the
    threadThread thread new Thread(threadStart)
  • thread.Start()
  • // Do other things ...// Wait for thread to
    complete
  • thread.Join()

59
SynchronizationSystem.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 waitMonitor.Enter(th
is)// Perform guarded action internalState
SomeAction( )// Release lock Monitor.Exit(this)
// C intrinsic equivalentlock (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

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

64
Transactions Manual Transactions -- ADO.NET
  • Connection object has BeginTransaction method
    that returns a Transaction object
  • Call Commit or Rollback on Transaction object

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

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.
67
Automatic Transactions and Web Services
  • Using the TransactionMode enumeration property on
    the WebMethod metadata attribute

lt_at_ WebService LanguageC gt using System
using System.Data using System.Data.SQL using
System.Web.Services public class
TransactionStuff WebService
WebMethod(TransactionModeTransactionMode.Require
d) public void DeleteDatabase()
SQLConnection sqlConn new SQLConnection( "Bar",
"sa", "", "northwind")
SQLDataSetCommand sqlAdapter1 new
SQLDataSetCommand( "delete orders", sqlConn)
SqlConn.Execute()
68
Automatic Transactions and Framework Class
Library
  • Programming Model
  • TransactionAttribute Constructor Variations

Transaction(TransactionOption.Required) public
class Bar() //. . .
TransactionAttribute(TransactionOption.NotSupport
ed) TransactionAttribute(TransactionOption.Suppo
rt) TransactionAttribute(TransactionOption.Requi
red) TransactionAttribute(TransactionOption.Requ
iresNew)
69
Transactions Voting in Automatic Transactions
  • Using AutoCompleteAttribute
  • Using SetAbort and SetComplete

// try to do something crucial to transaction
completing if ( !DoSomeWork() )
ContextUtil.SetAbort()
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

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

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

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) 
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 lt 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
  • http//msdn.microsoft.com/net
  • .NET Framework SDK
Write a Comment
User Comments (0)
About PowerShow.com