1 Introduction to the .NET FrameworkRichard Grimes © 2004 Richard Grimes
2 Richard Grimes .NET contributer Dr Dobb’s JournalVisual C++ .NET columnist for Windows Developer Magazine C# Q&A column for C#Pro Contributor to MSDN Magazine Twice monthly .NET newsletter © 2004 Richard Grimes
3 Richard Grimes Developing Application with Visual Studio.NET, Addison Wesley, 2002 Programming with Managed Extensions for Microsoft Visual C++ .NET, Microsoft Press, 2003 © 2004 Richard Grimes
4 Aims For The Day Gain an understanding of the .NET architectureUnderstand the basic features and facilities of .NET Gain an overview of the .NET framework library © 2004 Richard Grimes
5 .NET Types and Objects Everything in .NET is an objectreference types value types (including enums) ‘boxed’ value types Reference types are created on the managed heap Value types are created on the managed stack © 2004 Richard Grimes
6 .NET Types Object Reference Types Value Types Interfaces DelegatesExceptions Attributes Enums © 2004 Richard Grimes
7 .NET Types and Objects Reference types have System.Object as the highest base class must be created on heap with new Value types have System.ValueType as base class, Enums have System.Enum as bass class must be created on stack or embedded as a member of a reference type © 2004 Richard Grimes
8 Memory Layout You should not care because data is accessed through members, not pointers For interop with native code you can use a value type as a .NET representation of native structures can specify the memory layout in this case © 2004 Richard Grimes
9 Exceptions Standard mechanism to handle ‘exceptional’ situationsCode can be ‘guarded’ clause to catch exception from guarded code clause that is run when guarded block is left for any reason Uncaught exceptions are passed up the call stack © 2004 Richard Grimes
10 Exception Handlers Can catch all exceptions or specific exceptionsCan provide exception handlers for many different exception types handler handles exception and the exception types derived from it © 2004 Richard Grimes
11 Type Members Reference and Value types have Interfacesmethods, fields, properties Interfaces have only methods and properties All types can have events metadata for delegate fields and a standard protocol to initialise them © 2004 Richard Grimes
12 Methods Can be overloaded on parametermethods with the same name differ by the parameters that they cannot have default values for parameters By default parameters are ‘by value’ value passed on the stack, if you pass a reference type the reference is passed ‘by value’ not the object can user modifier to pass by reference © 2004 Richard Grimes
13 Fields Data members Can define const fieldsread and write access Can define const fields C# can define readonly fields © 2004 Richard Grimes
14 Properties Metadata that identifies methods to be used for read/write access can implement either or both Can add extra logic in property method and can calculate values Can implement Indexers ‘indexed’ collection © 2004 Richard Grimes
15 Constructors Constructor is called when an object is createdcan overload constructors ‘Destructor’ is called when object is finalized you do not determine when this happens © 2004 Richard Grimes
16 Virtual Members When a member is marked as virtual the runtime uses the object type to determine what method to call Used in polymorphism allows you to pass a derived object through a base class parameter and the ‘right’ method will be called © 2004 Richard Grimes
17 Static and Instance Static members are not members of any particular instance static fields are available to all instances values of instance fields are specific to the instance Static methods are executed in the context where they are called instance methods are executed in the context where the object was created © 2004 Richard Grimes
18 Inheritance .NET only supports single type inheritanceonly reference types, value types are ‘sealed’ .NET supports multiple interface implementation and interfaces can have multiple ‘inheritance’ Can derive from classes written in any language © 2004 Richard Grimes
19 Access Modifiers Define whether the type is visible outside of the assembly Define access to a member from types within the same assembly types in another assembly Assembly Assembly public class public class internal class internal class
20 Access Modifiers - MembersAccess From .NET Modifier C# Modifier External Internal public public Any class Any class famorassem protected internal Only derived Any class assem internal None Any class family protected Only derived Only derived famandassem None Only derived private private None This class © 2004 Richard Grimes
21 Managed Heap Heap is managed by the garbage collectorcheap to allocate, expensive to compact The GC will periodically remove old objects and compact the heap objects that are not ‘reachable’ will be removed © 2004 Richard Grimes
22 Finalization Objects are removed when the GC works, no sooner‘Finalizers’ perform clean up work called when object is removed from heap can be a long time after the object was last used Use Dispose pattern instead clean up code called explicitly by your code © 2004 Richard Grimes
23 Interfaces Are ‘reference’ typesbut always refers to an object Object can force caller to call interface through interface reference, or allow call through object reference Interfaces do not contain storage, constructors, static members, method implementations © 2004 Richard Grimes
24 CLS Common Language Specification defines rules that allow code written by one language to be used by code written by another language not all code is CLS Compliant © 2004 Richard Grimes
25 Assemblies Types are contained in assemblieslibraries, DLLs, can be shared between processes EXEs are processes Typically libraries do not run ‘on their own’ but ASP.NET applications are libraries because .NET provides a host process © 2004 Richard Grimes
26 Executing Code All code is compiled to Intermediate Language.NET runtime will just-in-time compile this to native machine code at runtime on a per method basis, the compiled code is cached in memory Can pre-JIT the code © 2004 Richard Grimes
27 Architecture - LoadingAssembly Resolver .NET Runtime JIT Compiler Assembly Loader Validation Verification Permissions Compiled Code Libraries .NET Framework Libraries © 2004 Richard Grimes
28 Accessing Non .NET Code .NET Process Native Library Native LibraryPlatform Invoke COM Interop Native Library Web Services Native Process .NET Library COM Interop .NET Hosting .NET Library © 2004 Richard Grimes
29 Architecture - ExecutionProcess Application Domain Application Domain Thread .NET Remoting Process Application Domain © 2004 Richard Grimes
30 Basic Objects Primitive Types Collections Arrays Strings© 2004 Richard Grimes
31 Primitive Types Part of the framework library Used by all languagesthe CLS primitive types, that is Encapsulates operations on those types conversions to other types comparisons with other instances © 2004 Richard Grimes
32 Primitive Types CLS Types Non-Compliant Types Framework Type C# TypeBoolean bool Byte byte Char char UInt16 ushort SByte sbyte UInt32 uint Int16 short UInt64 ulong Int32 int Int64 long Single float Double double Decimal decimal String string © 2004 Richard Grimes
33 Collections Defines standard collection classes and interfacesICollection, has count and synchronised access IComparer, compare items in a sorted collection IDictionary, access to a key-value collection IList, items are accessed by index IEnumerable, exposes an enumerator that iterates over the collection © 2004 Richard Grimes
34 Arrays Single and multiple dimensions Typed, index is zero-basedSize specified at declaration Access given by index and via an enumerator implements IEnumerable, IList, ICollection All access is bounds checked © 2004 Richard Grimes
35 Strings Contains an array of Char (Unicode)Encapsulates all string operations copy, replace, insert, remove, trim, sub string, uppercase, lowercase, compare, format, split, index of, last index of, pad left and right Immutable Interned two string objects may be the same string, the string is interned © 2004 Richard Grimes
36 Metadata Metadata describes typesall types have metadata can extend metadata with ‘custom’ metadata Runtime can read custom metadata as ‘out of band’ information © 2004 Richard Grimes
37 Metadata The combination of metadata and IL means that anyone can ‘read’ your algorithm can alleviate this with obfuscation only solution is DRM with Longhorn © 2004 Richard Grimes
38 Attributes Changes the metadata on a typesome add runtime metadata (eg [Serializable] some add new metadata that is known by the runtime (eg [STAThread]) some add metadata that is not known by the runtime, but known by other classes and code (eg [Conditional]) © 2004 Richard Grimes
39 Metadata APIs The Reflection namespace allows you to read metadata at runtime allows you to dynamically invoke methods and properties, and access fields and can read attributes The Reflection Emit API allows you to write metadata at runtime create metadata and IL © 2004 Richard Grimes
40 Assemblies Unit of deployment and securitydefines the boundary of security and of type definition Can contain multiple modules each module is written in a single language assembly can consist of modules written in many different languages can also have other resource files © 2004 Richard Grimes
41 .NET Containers Assembly myfile.exe myPic.jpg myStrings.txtModule External Resources myfile.exe myPic.jpg Internal Resources myStrings.txt Configuration File myfile.exe.config © 2004 Richard Grimes
42 Assembly Names Assembly name contains four partsPE file name version culture public key/public key token EXEs don’t use culture other than neutral © 2004 Richard Grimes
43 Assembly Names Assembly name uniquely identifies a libraryUsually processes are ‘statically’ linked to libraries library name is stored in the manifest of the files that use it process will not load if the specific assembly cannot be found © 2004 Richard Grimes
44 EXEs and Libraries process.exe libTwo.dll libOne.dll ManifestlibOne, version= , culture=neutral, publicKeyToken=null libTwo, version= , culture=neutral, publicKeyToken=null libTwo.dll version= , culture=neutral, publicKeyToken=null libOne.dll version= , culture=neutral, publicKeyToken=null © 2004 Richard Grimes
45 Assembly Location In most cases the libraries will be in the same folder as the process can be in a folder with the name of the PE file if the file has culture specific resources, then it’ll be in a folder with the culture name Can be shared by putting it in the Global Assembly Cache © 2004 Richard Grimes
46 GAC Appears to contain multiple files with the same name but different version actually implemented with multiple folders Contains assemblies shared by other assemblies ‘publisher policy files’, used to alter the versioning policy © 2004 Richard Grimes
47 Satellite Assemblies Resource-only Culture specificRuntime ResourceManager class will load the assembly for the current thread culture or fallback, ultimately to ‘neutral’ resources © 2004 Richard Grimes
48 Security The most important part of .NET!All arrays and string access is bounds checked Stack is managed by .NET, so cannot overwrite return address Code access security checks whether the code has the permissions to run © 2004 Richard Grimes
49 Signing Assemblies Use the publisher public/private keyhash is created from assembly, encrypted with private key and appended to the assembly public key is added to assembly Assembly user can decrypt the signed hash, create its own hash from the assembly and compare the two © 2004 Richard Grimes
50 Assembly Validation Check that the PE file is valid‘everything is where it should be’, eg entry point, resources, dependencies Check that the metadata is valid that the tables are valid Check that the IL is valid check that it is ‘correct’ IL check that jumps are within a method © 2004 Richard Grimes
51 Assembly VerificationPerformed by the JITter Checks IL that is valid to see if it is doing something unsafe eg casting to an unrelated type, pointer access to data (which can be abused) No definite algorithm, so .NET uses a conservative algorithm that may fail safe code. © 2004 Richard Grimes
52 Code Access Security CAS is in addition to Win32 securityAssemblies have ‘evidence’ usually the location from where the assembly was downloaded .NET defines policies map evidence to permissions Permissions define what the code can do © 2004 Richard Grimes
53 Policy There are four defined policiesUser, Machine, Enterprise, AppDomain all but AppDomain are loaded from XML AppDomain is programmatic Total permissions are the intersection of the permissions given by each of the four policies because policies only grant permissions © 2004 Richard Grimes
54 Code Groups A policy uses a code group to determine what permission set results from a particular evidence Code group has membership condition permission set © 2004 Richard Grimes
55 Permissions Define some action that the code is allowed to performtrusted assemblies check that calling code has the permissions before performing the secured work Permission Sets are combinations of permissions © 2004 Richard Grimes
56 Enforcement Trusted code calls Demand on a permission setDemand causes a stack walk to check the permissions of every method the evidence of the method’s assembly is put through the policy the top of stack permissions comes from the intersection of the spawning thread’s call stack methods, or from AppDomain © 2004 Richard Grimes
57 Demand and LinkDemand Demand, the check is performed at runtime every time the method is called whole stack is walked LinkDemand is performed only at JIT time security check is only performed on the method being JITted © 2004 Richard Grimes
58 Imperative and DeclarativeImperative, code explicitly calls Demand allows fine grain checks within the method allows you to take remedial action in the method can use information known only at run time Declarative, methods are marked with permission attributes applies to whole method clear by looking at method what permissions are required © 2004 Richard Grimes
59 Other Enforcement Can explicitly Deny code with specific permissionsCan specify that only a specific permission set is allowed, PermitOnly Sometimes a full stack walk is unfeasible other code may not have the permission Assert indicates that a permission is granted for all methods higher in the stack (but calling code must have the Assertion permission) © 2004 Richard Grimes
60 Assembly Permissions Assemblies can be marked with a permission setif the calling code does not have the permissions the assembly is not loaded © 2004 Richard Grimes
61 Role Based Security Can rely on Win32 securitythe process access token is used to see if access is given to a secured object eg you cannot access access a file unless you have been given access Can use .NET to get user identity and do runtime role based checks © 2004 Richard Grimes
62 Configuration Configuration should be treated as read-only and non-dynamic essentially like command line switches Configuration is cached in each AppDomain so if the config files change between creation of AppDomains the change will be read © 2004 Richard Grimes
63 Configuration Files Specific to application assemblies
64 Configuration SectionsMany system classes read configuration when they are initialized Your code can read custom configuration through
65 Problems Essentially read-only No per-user settingsWhidbey offers classes to write configuration, but these are not a solution No per-user settings Not applied to libraries (always reads config for app) Not dynamic, because settings are cached if config changes during run, objects do not reflect this © 2004 Richard Grimes
66 Threads All execution is performed on a threadAll processes have at least one thread and have a thread pool each thread has a culture and can have a context Threads can be background or foreground app can close even while a beckground thread still runs © 2004 Richard Grimes
67 Threads A thread can be suspended and resumed You can kill a threadA thread can tell itself to sleep You can change the priority of a thread © 2004 Richard Grimes
68 Thread Procedure Thread object is initialised with a ThreadStart delegate Thread pool thread runs a WaitCallback delegate In both cases you have to take other steps to return a return value [Serializable] public delegate void ThreadStart(); [Serializable] public delegate void WaitCallback(object state); © 2004 Richard Grimes
69 Synchronization Framework provides classes to protect shared data and code Mutex, Monitor Provides classes for thread communication AutoResetEvent, ManualResetEvent © 2004 Richard Grimes
70 Synchronization Enterprise Services (COM+) can be used to ensure that a single thread is used to access a collection of objects Can also use MethodImplOptions.Synchronized to indicate that only one thread can access a method at a time Also allows thread local storage and thread static data © 2004 Richard Grimes
71 Threads and ExceptionsIf an exception is not caught by a thread, the thread will die If the thread is the only thread in the AppDomain, the AppDomain will die often this will kill the process ThreadAbortException can be caught, but thread will always die unless the thread calls ResetAbort © 2004 Richard Grimes
72 Contexts Contexts provide the environment in which your objects runevery object will run in a context, but not all objects care about the context Contexts belong to an Application Domain every Application Domain will have at least one context, called the default context Threads are not connected to a specific context a thread may execute code running in one or more contexts © 2004 Richard Grimes
73 Component Services Contexts are used to supply component servicesWhen an object in a context creates another object it will be created in the same context if its component services requirements do not clash with the context if the object doesn’t care about component services © 2004 Richard Grimes
74 Component Services .NET Component Services are applied through interception the object does not have to know that interception occurs Most component services are the Enterprise Services for objects that derive from ServiceComponent © 2004 Richard Grimes
75 Objects and Contexts Some objects are bound to a contextcan only be executed in the context where they were created derive from ContextBoundObject Others are context agile can move between contexts don’t care what context they are used in not derived from ContextBoundObject, or are marshal by value © 2004 Richard Grimes
76 .NET Remoting Gives access to context bound objectsArchitecture has many extensibility points Can add your own interception to monitor calls to an object to add your own component service © 2004 Richard Grimes
77 Delegates Type safe .NET ‘function’ pointers.NET methods are __clrcall, so C type function pointers do not work Multicast .NET automatically adds ‘thunks’ for delegates passed to native code © 2004 Richard Grimes
78 Delegates A delegate class is generated by the compilerderived from MulticastDelegate Delegate object contains a linked list of delegates when the top delegate is invoked, so are all delegates in the list © 2004 Richard Grimes
79 Delegates The methods in the delegate must be in the same processbut .NET remoting can marshal a delegate to another process and invoke the method if a suitable channel is created Delegates can be serialised © 2004 Richard Grimes
80 Asynchronous Calls Every delegate can be invoked asynchronouslywithout any extra code performed on a thread pool thread Some Framework APIs provide asynchronous methods that use Win32 asynchronous functions © 2004 Richard Grimes
81 Events Events are metadata that formalizes the protocol of adding delegates to an object that are used for notifications Compiler generates methods for the event and adds storage for the delegate methods to raise the event and add and remove a delegate can provide your own © 2004 Richard Grimes
82 Object Serialization Object serialization is important forpersistent storage of objects passing objects across contexts using the message queuing classes Framework provides classes to serialize to XML and to binary © 2004 Richard Grimes
83 Serialisation [Serializable] is used to mark a class that can be serialised fields are serialised [NonSerialized] is used on fields that should not be serialised Can use custom serialisation to handle fields that cannot be serialised © 2004 Richard Grimes
84 Serializers Framework provides classes to serialize tobinary: BinaryFormatter SOAP XML: SoapFormatter raw XML: XmlSerializer In general these will serialize an object to a stream and deserialize from a stream © 2004 Richard Grimes
85 Raw XML Serializer XmlSerializer is used to create XML from the state of an object does not need [Serializable] the object can have attributes to indicate how the state maps to XML, indicating node names and attributes It cannot handle circular references member objects are embedded as child nodes © 2004 Richard Grimes
86 Raw XML Serializer MySubObject MyObject test
87 Raw XML Serializer MySubObject MyObject[XmlAttribute("Age")] int x; [XmlAttribute("Name")] string s;
88 Formatters Do more work serializing objects Formatterstake into account references to objects Formatters implement IFormatter use the ObjectManager to determine the order that child objects are deserialised © 2004 Richard Grimes
89 IFormatter public interface IFormatter { SerializationBinder Binder {get; set;} StreamingContext Context {get; set;} ISurrogateSelector SurrogateSelector {get; set;} object Deserialize(Stream); void Serialize(Stream, object); } © 2004 Richard Grimes
90 IFormatter PropertiesContext used to determine where the object is being serialized Binder is an object used to determine the type of the class when the object is deserialised SurrogateSelector is a separate object to do serialization used in the remoting case for MarshalByRefObjects © 2004 Richard Grimes
91 ObjectManager Consulted by formatter while deserialising an objectkeeps a list of child objects Ensures that child object is deserialised only once ObjectManager returns child object if it has already been deserialised, otherwise child object is added to ObjectManager © 2004 Richard Grimes
92 Custom Serialization [Serializable] cannot be used with objects that hold handles or pointers because the items they refer to will not be serialized, only the opaque handle Can use custom serialization to control what is serialized © 2004 Richard Grimes
93 ISerializable This has just one method: GetObjectData(), used to get the state of the object The interface is unusual because if your class implements this interface then it must implement a constructor that takes the same parameters void GetObjectData(SerializationInfo info, StreamingContext ctx); © 2004 Richard Grimes
94 SerializationInfo This is a name-value collectionIt has Add* methods to add primitive types and objects interestingly, the objects that you add do not have to be [Serializable] It has Get* methods to retrieve values Also has GetEnumerator() © 2004 Richard Grimes
95 Streams Many of the framework uses streamsfiles sockets crypto-routines System.IO.Stream base class provides the common functionality both synchronously and asynchronously © 2004 Richard Grimes
96 Stream Classes Class Description FileStreamBuffered stream based on a disk file NetworkStream Unbuffered stream based on a socket BufferedStream Wrapper to add buffering to an unbuffered stream MemoryStream Stream based on memory CryptoStream Stream used for cryptographic transformations © 2004 Richard Grimes
97 Stream Support for reading and writing a single bytereading and writing an array of bytes determining if seeking a position within the stream is supported flushing the stream if it is buffered © 2004 Richard Grimes
98 Readers and Writers Stream access is by bytes onlymust make an intelligent interpretation of those bytes Readers and Writers are used to perform that interpretation Constructor takes stream reference and encoding for strings © 2004 Richard Grimes
99 Reader and Writers Class Description BinaryReaderRead various data types from a stream BinaryWriter Write various data types to a stream StreamReader Reads strings from a stream StreamWriter Writes strings to a stream TextReader Abstract class for reading strings TextWriter Abstract class for writing strings © 2004 Richard Grimes
100 Readers and Writers TextReader, TextWriter, abstract classes, convert between primitive types and strings write data as strings, read strings and convert to appropriate type StreamReader, StreamWriter, are TextReader/Writer that read and write strings BinaryReader, BinaryWriter read/write the underlying bytes of the data types © 2004 Richard Grimes
101 Text Encoding SupportsUTF7, UTF8, Unicode (bigendian, littleendian), ASCII Readers can be constructed with an encoding, or can guess the encoding Writers will write a ‘preamble’ that identifies the encoding use UTF7 or ASCII if you don’t want the preamble © 2004 Richard Grimes
102 File Access File and FileInfo return an FileStreamcan also use FileStream constructor Can specify the file access and sharing options similar to Win32 Can determine whether file is created or appended © 2004 Richard Grimes
103 File Access FileAccess, determine how you access the fileRead, ReadWrite, Write FileShare, determines whether the file can be accessed by anyone else © 2004 Richard Grimes
104 FileMode Value Description AppendOpens an existing file or creates a new one. Must be opened with FileAccess.Write Create Creates a file, if it exists then it will be overwritten CreateNew Creates a new file, if it exists an exception is thrown Open Opens an existing file OpenOrCreate Opens a file if it exists, creates a new one otherwise. Can be any FileAccess Truncate Opens an existing file and truncates its length to zero © 2004 Richard Grimes
105 Accessing Part of a FileCan use FileShare to determine if other users can access the file while you are using it If you allow ReadWrite access to a file then you should lock the regions that you write to FileStream.Lock(), FileStream.Unlock() © 2004 Richard Grimes
106 Diagnostics Diagnostics are used to add instrumentation to make it easier to debug conditional code tracing asserts stack traces © 2004 Richard Grimes
107 [Conditional] The [Conditional] attribute can be applied to a methodindicates that the method is called only if a specific symbol is defined Most compilers will simply ignore the method if the symbol is not defined however C++ is an exception © 2004 Richard Grimes
108 Conditional Code Use the language syntax to specify that a block of code will only be compiled if a symbol is defined Symbols are usually defined on the command line or in the source code can make the source code difficult to read © 2004 Richard Grimes
109 Trace and Debug Both contain code for tracing and assertsTrace methods are called only if TRACE is defined Debug methods are called only if DEBUG is defined C# wizards define TRACE for Debug and Release builds (ugh!) © 2004 Richard Grimes
110 Tracing Code Allows you to provide debugging messages at runtimeWriteLine and Write messages are sent to each listener in the trace listener collection Can specify a Boolean to control whether message is written WriteLineIf and WriteIf © 2004 Richard Grimes
111 Trace Listeners All trace messages are sent through the process’s trace listeners collection usually specified through the config file can be specified programmatically Trace listeners derive from the TraceListener class © 2004 Richard Grimes
112 Trace Listeners Class Description DefaultTraceListenerTrace messages go to OutputDebugString and to the attached debugger, asserts are displayed with a dialog. EventLogTraceListener Trace messages are sent to a specified EventLog, assert messages are sent to the EventLog. TextWriterTraceListener Trace messages and assert messages are written in a text file*. *Note that this works only for single threaded code. There is no thread synchonization. It fails for multiple AppDomain code. © 2004 Richard Grimes
113 Asserts Asserts indicate that the process is in an unstable state and should not continue in a debug session you can still decide to continue to execution Optionally, you can direct asserts through a listener to a file © 2004 Richard Grimes
114 Debug Symbols When the code is compiled for debugextra information is stored in symbol files with variable names, source line numbers etc turns off JIT optimization turns on runtime tracking of objects Makes stack traces useful © 2004 Richard Grimes
115 Stack Traces The StackTrace class can be used to dump information about the call stack For a command line app this is displayed when an exception is not caught For a GUI application this information is displayed in a dialog © 2004 Richard Grimes
116 Debugger Use [DebuggerHidden] to indicate that the debugger should not step into the method, nor allow breakpoints Use Debugger.Break in your code to force a breakpoint in the debugger users get the option of starting the debugger Use Debugger.Launch to force the debugger to start © 2004 Richard Grimes
117 The Framework Library © 2004 Richard Grimes
118 References Applied Microsoft .NET Framework Programming, Richter, Microsoft Press, 2002 Essential .NET, Volume 1, Box and Sells, Addison Wesley, 2002 © 2004 Richard Grimes