.
NET Framework
Class Library
Web Application Development
Faculty of Mathematics
and Computer Science
University of Bucharest
Prerequisites
This module assumes you understand the fundamentals
of:
Programming
Variables
Statements
Functions
Loops
Object-oriented programming
Classes
Inheritance
Polymorphism
Members
C#
Learning Objectives
Gain an overview of various .NET Framework
classes and interfaces
Be able to write programs using these classes
and interfaces
Agenda
Introduction
System Namespace
Collection Classes
I/O and Networking
Threading and Synchronization
Transactions
Exceptions
Introduction
Looking Back
The Microsoft .NET Framework Class Library
Benefits of the .NET Framework Class Library
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
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
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
Agenda
Introduction
System Namespace
Collection Classes
I/O and Networking
Threading and Synchronization
Transactions
Exceptions
System Namespace
System.Object
The not-so-primitive "primitive" types
String and text classes
Dates, times, and calendars
System console support
Standard interfaces
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
…
}
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
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
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)
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
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
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
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
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
}
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
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
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
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
Console.Write("Snow White and the {0} dwarfs",
7);
Reading from the console
Read() reads on characters
ReadLine() reads one full line
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
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
System Namespace
String.Format and IFormattable
String.Format
String.Format(“Please order {0} widgets at {1} each.”, i, f);
String.Format(“{0:U}”, DateTime.Now);
Implement IFormattable for custom formatting of your
own types
interface IFormattable {
String Format(String format, IServiceObjectProvider sop);
}
Use IServiceProvider to get culturally-aware delimiters
for numbers and date/time
Implement ICustomFormatter to override default
formatting for built-in types
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(); }
Agenda
Introduction
System Namespace
Collection Classes
I/O and Networking
Threading and Synchronization
Transactions
Exceptions
Collection Classes
Arrays
Collection Interfaces
The Collection Classes
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
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 );
}
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()
Collection Classes
Enumerating a Set of Items
All types offer standard mechanism for item iteration
System.Collections.IEnumerable interface
public interface IEnumerable {
IEnumerator GetEnumerator();
}
GetEnumerator returns object dedicated to item
iteration
public interface IEnumerator {
Boolean MoveNext();
Object Current { get; }
void Reset();
}
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);
}
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
Add(), Remove(), Contains() and Clear() methods
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
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();
}
}
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
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();
}
}
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();
}
}
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
Agenda
Introduction
System Namespace
Collection Classes
I/O and Networking
Threading and Synchronization
Transactions
Exceptions
I/O and Networking
Directories and Files
Streams, Stream Readers and Stream Writers
Networking Support
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
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()
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
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
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
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();
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(); }
}
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
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()
I/O and Networking
System.Net.HttpWebRequest
HttpWebRequest HttpWReq =
(HttpWebRequest)WebRequestFactory.Create(
"http://www.contoso.com");
HttpWebResponse HttpWResp =
(HttpWebResponse)HttpWReq.GetResponse();
Agenda
Introduction
System Namespace
Collection Classes
I/O and Networking
Threading and Synchronization
Transactions
Exceptions
Threading and Synchronization
Process control
Threading support
Synchronization
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()
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
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();
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 // C# intrinsic equivalent
Monitor.Exit(this); lock (this) {
internalState = SomeAction( );
}
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 )
Agenda
Introduction
System Namespace
Collection Classes
I/O and Networking
Threading and Synchronization
Transactions
Exceptions
Transactions
Transaction Fundamentals
Manual Transactions
Automatic Transactions
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
Transactions
Manual Transactions -- ADO.NET
Connection object has BeginTransaction
method that returns a Transaction object
Call Commit or Rollback on Transaction
object
Transactions
Automatic Transactions
Automatic Transactions and ASP.NET
Automatic Transactions and Web Services
Automatic Transactions and Framework
Class Library
Voting in an Automatic Transaction
Transactions
Automatic Transactions and ASP.NET
Directives Descriptions
This value indicates that the page does not run within
NotSupported
the scope of transactions.
The page will run in the context of an existing
Supported transaction, if one exists. If not, it will run without a
transaction.
The page requires a transaction. It will run in the
Required context of an existing transaction, if one exists. If not,
it will start one.
The page requires a transaction and a new
RequiredNew
transaction will be started for each request.
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();
}
}
Automatic Transactions and
Framework Class Library
Programming Model
[Transaction(TransactionOption.Required)]
public class Bar() {
//. . .
}
TransactionAttribute Constructor
Variations
[TransactionAttribute(TransactionOption.NotSupported)]
[TransactionAttribute(TransactionOption.Support)]
[TransactionAttribute(TransactionOption.Required)]
[TransactionAttribute(TransactionOption.RequiresNew)]
Transactions
Voting in Automatic Transactions
Using AutoCompleteAttribute
Using SetAbort and SetComplete
// try to do something crucial to transaction completing
if ( !DoSomeWork() ) {
ContextUtil.SetAbort();
}
Agenda
Introduction
System Namespace
Collection Classes
I/O and Networking
Threading and Synchronization
Transactions
Exceptions
Exceptions
Introduction
The Exception Object
Best Practices for Handling Exceptions
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
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
Exceptions
Best Practices
Simple catch and display
catch (Exception e) {
Console.WriteLine (e);
}
Catch block order matters
Write most specific catch blocks first, then least specific
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…
}
}
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
Resources
http://msdn.microsoft.com/net
.NET Framework SDK