Upload
others
View
9
Download
0
Embed Size (px)
Citation preview
1
Application Servers G22.3033-011
Session 5 - Sub-Topic 4Introduction to .Net/C#
Dr. Jean-Claude Franchitti
New York UniversityComputer Science Department
Courant Institute of Mathematical Sciences
Resources
• Visual Studio.NET Academic• Books
– Course textbook and books listed under references– Introduction to C# Using .NET
Robert J. ObergPrentice Hall, ISBN: 0-13-041801-3
• Other– C# Language Specification
http://msdn.microsoft.com/vstudio/techinfo/articles/upgrade/Csharpdownload.asp
– Websites…• Rotor
– Search for it in Google!
2
Topic 0:Introduction to .NET
Topic 0: Introduction to .NET
Challenges• Development: Which OS / Language?• Delivery: Media, Licenses, …• Stability: DLLs mess, Security• Maintenance: Who? What?
• Services: The new model
3
Topic 0: Introduction to .NET
What is .NET• The combination of:
– Framework• Common language runtime (CLR)• Class libraries• ADO.NET, ASP.NET, ...
– Web Services– .NET Enterprise Servers
Topic 0: Introduction to .NET
What is .NET (cont.)
Runtime
Operating System
.NET Framework
CommonType
System
Common LanguageRuntime
Building Blocks (e.g. for Services)
Services: .NET and COM+
SQL Server BizTalk ...
Languages:
C#, Visual Basic, etc
.NET Applications
Enterprise Servers
...Office.Net ...
Web Services
4
Topic 0: Introduction to .NET
What is .NET (cont.)
Base Classes
Data & XML
UserInterface
Common Language Runtime
WebServices
Bas
e Fr
ame
Topic 0: Introduction to .NET
What is the CLR?– Common type system
• Mapping of data types. Programming language Framework– Just-in-time (JIT) compilers
• JIT compiles intermediary language (MSIL) into native code• Highly optimized for platform or device
– Garbage collector– Permission and policy-based security– Exceptions– Threading– Diagnostics and profiling
5
Topic 0: Introduction to .NET
What is the CLR?
Class Loader
MSIL to NativeCompilers (JIT)
CodeManager
GarbageCollector (GC)
Security Engine Debug Engine
Type Checker Exception Manager
Thread Support COM Marshaler
Base Class Library Support
Topic 0: Introduction to .NET
More .NET• Namespaces and Classes
– Hierarchical, unified class libraries– Unified and extensible provide “system” and base functionality
and services– Object-oriented: everything is an object!– The systems uses the same classes offered to you
• Interfaces – The .NET (Service) contracts
• Types– Byte, Sbyte, Single, Double, String, Int16, etc.– These all map to the common type system
6
Topic 1:Memory Management
Topic 1: Memory Management
Doing it manually• Allocate memory for a resource• Initialize the resource• Use the resource• Clean up the state of the resource• Free the allocated memory
7
Topic 1: Memory Management
Garbage Collection (Why?)• C/C++ applications often leak memory
– Manual memory management– No clear rules for ownership of objects
• COM fixes this partly through ref-counts– AddRef/Release calls must be balanced– SmartPointers don't catch all problems
• Server applications must be leak free– Must run for months and years
• Solution: automatic memory management
Topic 1: Memory Management
Garbage Collection (Why not?)• Garbage Collection downside:
– Destructors called at some random future time– Finalization code is never synchronous– Breaks some established design patterns from C++
• Beware: Code should never depend on destructors to free external resources.
• Instead: Implement IDisposable with usingusing (File f = new File("c:\\xyz.xml")){
...}
– IDisposable.Dispose() called on object when scope is exited.
8
Topic 1: Memory Management
Garbage Collection (How?)• Developer creates new objects and data arrays
– Everything created/allocated using new keyword• The .NET runtime tracks all memory usage
automatically• GC automatically removes all unused objects• More efficient memory management• Ease of use and "zero memory leaks"
Topic 1: Memory Management
Garbage Collection (What?)• Garbage collection
– Generations– Resurrection– Disposability (Unmanaged Resources)– Finalization– Weak References
• Practice Assignment:– Study the GarbageCollection demo:
<FrameworkSDK>\Samples\Technologies\GarbageCollection
– Discover the objects reachable from a given object
9
Topic 1: Memory Management
Garbage Collection (Details)• GC Heap
– Allocated Address Space
• Allocation– Comparison C# vs. C/C++
Topic 1: Memory Management
Garbage Collection
• Trace the roots all the way down• Mark all objects that are still alive• Remove all dead objects (sweep)• Compact the heap to remove holes
10
Topic 1: Memory ManagementGarbage Collection (Finalization)
• Similar to C++ destructors:public class BaseObj {
public BaseObj() {}protected override void Finalize() {
// Perform resource cleanup code here... // Example: Close file/Close network connectionConsole.WriteLine("In Finalize."); base.Finalize();
}}
• Drawbacks in comparison to C++– Slower to allocate finalizable objects– Slower to collect dead finalizable objects
• Promotion• Actual method call
– Ordering and time of finalization uncontrollable– Finalize not always called
Topic 1: Memory ManagementGarbage Collection (Finalization)
• Finalization Queue• Freachable Queue• Resurrection• Forced clean-up
– GC.ReRegisterForFinalize(o)– GC.SupressFinalize(o)
11
Topic 1: Memory Management
Weak References• Types w.r.t. ressurection
– Short week references– Long week references
• Two different tables in the GC
Topic 1: Memory Management
Generations
12
Topic 1: Memory Management
Large Objects Heap• Separate GC Heap
– Marked – Sweeped– Never collected
• Too costly to move that much data
• Monitoring performance under NT
Topic 2:Common Type System
13
Topic 2: Common Type System
Looking Back• Why have types at all?
– Type-less vs. typed language– Type vs. instance
• Each language brings its own type system– Different types on different platforms
• Need for common types for interoperation– IDL uses smallest common denominator
Topic 2: Common Type System
The Unknown Type• What is a “Type” in the Object Oriented World?
– Allowable values– Operations defined
• Notions in the Common Type System:– Types are different
• ...if they have different representations– Types implement the same interface
• ...if they responds to the same set of messages – Types are identical
• ...if they have the same representation• ...and respond to the same messages
14
Topic 2: Common Type System
Locations• Values are stored in locations
– Local variables– Parameters– A storage place with a name– A location can hold a single value at a time
• Locations have a well defined type– Type defines which values can be stored
• The value must be assignment compatible to the location– Type defines usage of value
Topic 2: Common Type System
Contracts• Specify requirements on implementation of a type
– Type states which contracts must be supported– Contracts are shared assumptions on set of signatures
• Signatures define constraints on...– Types, locations, parameters, methods, etc– Define which values can be stored– Enumerate allowed operations
• Signatures are the enforceable part of a contract– Implementation of a type can be verified
15
Topic 2: Common Type System
Coercion• Assignment incompatible value must be
converted• Widening coercion
– Never loses information– Usually implemented as implicit conversion
• Narrowing coercion– Information might be lost– Usually implemented as explicit conversion
• Coercion changes the value
Topic 2: Common Type System
Defining Conversionsclass Point{
public int x, y;
public static implicit operator Rectangle (Point p){
Rectangle r = new Rectangle();
r.UL = r.LR = p;
return r;}
}
class Rectangle{
public Point UL, LR;}
16
Topic 2: Common Type System
Casting• A value has the type of its location• Casting allows use of value as if it had different
type• Usually casting is a compile time operation
– Unless exact type of value is unknown– Runtime check might result in exception
• Casting does not change the value or its type
Topic 2: Common Type System
CLS• Set of rules for interoperability
– „Subset“ of the Common Type System– Large enough to be expressive– Small enough that all languages can accommodate it – Guideline was only to include verifiable constructs
• Only applies to types that are externally visible– Assumes assemblies as subjects of interoperability
• Identifiers must follow certain rules– Case sensitivity
17
Topic 2: Common Type System
Typology• Value types
– Represented by sequence of bits in a location– Common built-in data types
• Reference types– Represented by a location and a sequence of
bits– Objects, Interfaces, Pointers
Topic 2: Common Type System
Build-in Value Types• Integer values
– int8, int16, int32, int64– unsigned counterparts
• Super long decimal value– decimal (28 digits)
• Floating point values– float32, float64
• Unicode character value– char
• Boolean value– bool
18
Topic 2: Common Type System
Build-in Reference Types• Object
– Base class for all types– Allows for polymorphism across all types
• String– Can hold up to 231 characters– Is immutable
• Changing creates new modified string
Topic 2: Common Type System
Boxing and Unboxing• Value types can be boxed and unboxed• Boxing allows value types to travel by-ref• Based on object-ness of all types
42 42
42
Unboxed: Copy
Boxed: Reference
double Value;
// Boxingobject BoxedValue = Value;// UnboxingValue = (double)BoxedValue;
19
Topic 2: Common Type System
Exceptions• When exception occurs an object is created
– Subclass of System.Exception• Protected block for exception handling : try
– Protected blocks may be nested– If exception occurs CLR searches for handler– Four kinds of handlers:
• Catch handler filters type of exception object• Filter handler determines if exception can be handled• Fault handler executes when exception occurs• Finally handler executes whenever protected block is left
Topic 2: Common Type System
Delegates & Events• Delegates
– Similar to function pointers found in C, C++• Use is type safe
– Multicast delegates call more than one method• Derive from System.MulticastDelegate• Result of Combine method is MulticastDelegate to call
• Events– Change of state of an object– Observer registers delegate with event as handler
• Event triggers MulticastDelegate when it is fired
20
Topic 2: Common Type System
Delegates Examplepublic delegate int operation (int x, int y);
int Add (int x, int y){
return x + y;}
void PrintResult (int x, int y, operation o){
Console.WriteLine(o(x, y));}
void Run (){
PrintResult(4, 7, new operation(Add));}
Topic 2: Common Type System
Events Exampledelegate void Listener (object o);
event Listener OnSomethingHeard;
void SomethingHeard (object o){
OnSomethingHeard(o);}
void SimpleListener (object o){
Console.WriteLine(o);}
void AddListener (){
OnSomethingHeard += new Listener(SimpleListener);}
21
Topic 2: Common Type System
Attributes• User-defined annotations to the metadata
– An instance of a type is stored along with metadata
• Declarative access to functionality• Can be of any type
– Mostly derived from System.Attribute
• CLR predefines some attribute types– Control of runtime behavior
Topic 2: Common Type System
Pointers• Pointer contains address of memory location
– Pointers are typed– Defined by specifying location signature
• Type safe operations defined– Loading the value from the location– Storing assignment compatible value to the location
• Address arithmetic is considered type unsafe– Such unmanaged pointers are not part of the CLS
22
Topic 2: Common Type System
Type Members• Allowable values of type may have substructure• Representation may be subdivided
– Named sub-values are called fields• Type is called compound type
– Indexed sub-values are called array elements• Type is called array
– Each field or element is typed– Array elements all have same type– These types do never change
• Type may declare static fields– Locations associated with type – not with instance
Topic 2: Common Type System
Type Members (cont.)• Methods are operations
– Defined to operate on the type: static method– Defined operate on an instance
• Method is passed the instance to operate on : this• Instance vs. virtual method
– Both methods may be overridden– Instance method is called on declared type
• Determined at compile time– Virtual method is called on exact type
• Determined at runtime
23
Topic 2: Common Type System
Visibility & Accessibility• Type must be visible to be referenced• Access to type member requires three conditions
– Type must be visible– The member must be accessible– Security demands are granted
• Six degrees of accessibility– Private, family, assembly, family and assembly– Family or assembly, public– Interface members are always public– Overriding methods may only widen accessibility
• Not under CLS!
Topic 2: Common Type System
Type Inheritance• Inheriting type supports all the contracts of base
type– May support additional or modified functionality
• All object types inherit explicitly or implicitly – Except System.Object which is the root– Objects have a single base class– Objects can implement several interfaces
24
Topic 2: Common Type System
Member Inheritance• All non-static fields are inherited
– Visibility and accessibility determine access
• All instance and virtual methods are inherited– Constructors and static methods are not– Non-virtual and static methods may be hidden– Virtual methods may be marked as final
• Properties and events are not inherited
Topic 3:Unsafe Mode
25
Topic 3: Unsafe Mode
Unsafe Contexts• “unsafe” modifier keyword• “unsafe” blocks
public unsafe struct Node{
public int Value;public Node* Left;public Node* Right;
}
public struct Node{
public int Value;public unsafe Node* Left;public unsafe Node* Right;
}
• Be careful when you need “unsafe”
Topic 3: Unsafe Mode
Unsafe Contexts (cont)• Does not automatically propagate
public class A{
public unsafe virtual void F() {char* p;...
}}
public class B: A{
public override void F() {base.F();...
}}
• When we have a pointer parameter…
26
Topic 3: Unsafe Mode
Pointer Types• Almost identical to C/C++• Operators for manipulating pointers (in unsafe context)
– The * operator may be used to perform pointer indirection– The -> operator may be used to access a member of a struct through a pointer– The [] operator may be used to index a pointer – The & operator may be used to obtain the address of a variable– The ++ and -- operators may be used to increment and decrement pointers– The + and - operators may be used to perform pointer arithmetic– The ==, !=, <, >, <=, and => operators may be used to compare pointers– The stackalloc operator may be used to allocate memory from the call stack– The fixed statement may be used to temporarily fix a variable so its address can be
obtained
Topic 3: Unsafe Mode
Pointer Type Conversions• Implicit
– To void*– From null
• Explicit– All pointer types From/To all pointer types– Primitive integer types From/To all pointer
types
27
Topic 3: Unsafe Mode
C-like Pointer Exampleunsafe static int* Find (int* pi, int size, int value) {
for (int i = 0; i < size; ++i) {
if (*pi == value) return pi;
++pi;}
return null;}
Topic 3: Unsafe Mode
Unmanaged Types• Not a reference• Does not contain references inside…• Formal definition
– sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool
– Any enum-type– Any pointer-type– Any user-defined struct-type that contains fields of
unmanaged-types only
28
Topic 3: Unsafe Mode
Fixed and Moveable• Fixed
– Unaffected by the garbage collector– Examples
• Locals variables• Value parameters• Pointer dereferences
• Moveable– Can be relocated– Examples
• Fields in objects• Elements of arrays• Static fields• ref and out parameters
Topic 3: Unsafe Mode
“fixed” Exampleunsafe class Test{
static int x;int y;static void F(int* p) {
*p = 1;}static void Main() {
Test t = new Test();int[] arr = new int[10];fixed (int* p = &x) F(p);fixed (int* p = &t.y) F(p);fixed (int* p = &arr[0]) F(p);fixed (int* p = arr) F(p);
}}
29
Topic 3: Unsafe Mode
“fixed” Exampleunsafe class Test{
static int x;int y;static void F(int* p) {
*p = 1;}static void Main() {
Test t = new Test();int[] arr = new int[10];fixed (int* p = &x) F(p);fixed (int* p = &t.y) F(p);fixed (int* p = &arr[0]) F(p);fixed (int* p = arr) F(p);
}}
Topic 3: Unsafe Mode
“stackalloc” Exampleclass Test{
unsafe static string IntToString(int value) {char* buffer = stackalloc char[16];char* p = buffer + 16;int n = value >= 0? value: -value;do {
*--p = (char)(n % 10 + '0');n /= 10;
} while (n != 0);if (value < 0) *--p = '-';return new string(p, 0, (int)(buffer + 16 - p));
}static void Main() {
Console.WriteLine(IntToString(12345));Console.WriteLine(IntToString(-999));
}}
30
Topic 3: Unsafe ModeDynamic Memory Management
• Not using the Garbage Collector?• Want something like?
class Test{
unsafe static void Main() {byte* buffer = (byte*)Memory.Alloc(256);for (int i = 0; i < 256; i++) buffer[i] = (byte)i;byte[] array = new byte[256];fixed (byte* p = array) Memory.Copy(buffer, p, 256); Memory.Free(buffer);for (int i = 0; i < 256; i++) Console.WriteLine(array[i]);
}}
• What is behind the scenes?
Topic 3: Unsafe Mode
Dynamic Memory Exampleusing System.Runtime.InteropServices;
public unsafe class Memory{
const int HEAP_ZERO_MEMORY = 0x00000008;
[DllImport("kernel32")]static extern int GetProcessHeap();
[DllImport("kernel32")]static extern void* HeapAlloc(int hHeap, int flags, int size);
[DllImport("kernel32")]static extern bool HeapFree(int hHeap, int flags, void* block);
[DllImport("kernel32")]static extern void* HeapReAlloc(int hHeap, int flags, void* block, int size);
[DllImport("kernel32")]static extern int HeapSize(int hHeap, int flags, void* block);
static int ph = GetProcessHeap();
private Memory() {}
………}
31
Topic 3: Unsafe ModeDynamic Memory Example (cont)
using System.Runtime.InteropServices;
public unsafe class Memory{
………
public static void* Alloc(int size) {void* result = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);if (result == null) throw new OutOfMemoryException();return result;
}
public static void Free(void* block) {if (!HeapFree(ph, 0, block)) throw new InvalidOperationException();
}
public static void* ReAlloc(void* block, int size) {void* result = HeapReAlloc(ph, HEAP_ZERO_MEMORY, block, size);if (result == null) throw new OutOfMemoryException();return result;
}
public static int SizeOf(void* block) {int result = HeapSize(ph, 0, block);if (result == -1) throw new InvalidOperationException();return result;
}}
Topic 3: Unsafe ModeDynamic Memory Example (cont)
using System.Runtime.InteropServices;
public unsafe class Memory{
………
public static void Copy(void* src, void* dst, int count) {byte* ps = (byte*)src;byte* pd = (byte*)dst;if (ps > pd) {
for (; count != 0; count--) *pd++ = *ps++;}else if (ps < pd) {
for (ps += count, pd += count; count != 0; count--) *--pd = *--ps;}
}}
32
Topic 4:Interoperability
Topic 4: Interoperability
Introduction• Introduction to interoperation between
– .NET and COM– COM and .NET– .NET and platform services
33
Topic 4: Interoperability
Existing Stuff Must Coexist • Transition to .NET will be a lasting process• Portions of systems will remain as they are now
– ...and even maintained in their current form• Interoperability increases the momentum of .NET• Goal is to achieve total transparency• Mere presence of .NET must not interfere with
COM• Performance should not be hit
Topic 4: Interoperability
Differences in the two Worlds?• Managed Code vs. Unmanaged Code
– Lifetime management– Metadata
• Common Type System• Inheritance concept• Threading model• Error handling mechanisms• Registration
34
Topic 4: InteroperabilityCalling COM Services from .NET
• Metadata for COM class must be available– Can be generated from Type Library– Can declare Custom Wrapper
• Use COM class like .NET class• Early and late bound activation• COM component must be registered locally
Topic 4: InteroperabilityConverting Type Library to Metadata
• Use SDK tool TlbImp– Or just add reference to server in Visual Studio
• Type library can be imported from executable• Reference resulting metadata file in project• Custom IDL attributes are preserved
35
Topic 4: InteroperabilityCalling an COM Server
namespace CallingCOMServer{
using System;using COMServerLib;
public class DotNET_COMClient{...
public static int Main(string[] args){
MyCOMServer myS = new MyCOMServer();return (myS.Add (17,4));
}}
};
Topic 4: Interoperability
Late Bound Activation• Accomplished by Reflection API
– No difference whether COM or .NET object
• Type can be obtained from ProgID or ClsID• InvokeMember to access methods and properties• Metadata is not needed, but useful
– COM object is wrapped by __ComObject
36
Topic 4: InteroperabilityLate Bound Call to COM Server
namespace LateBoundClient{
using System.Reflection;...Type typ;Object obj;Object[] prms = new Object[2];int r;typ = Type.GetTypeFromProgID(„MyLib.MyServer");obj = Activator.CreateInstance(typ);prms[0] = 10; prms[1] = 150; r = (int)typ.InvokeMember(„aMethod",
BindingFlags.InvokeMethod, null, obj, prms);...
}
Topic 4: InteroperabilityCalling .NET Services from COM
• Use .NET class like COM class– Type and methods must be public
• Early and late bound activation• Convert Metadata to Type Library• Wrapper of .NET component must be
registered– Can use RegAsm tool
37
Topic 4: InteroperabilityCalling Platform Services from .NET
• Calling static functions in DLLs• P/Invoke provides services
– Locates implementing DLL– Loads DLL– Finds function address
• Fuzzy name matching algorithm– Pushes arguments on stack– Performs marshalling– Enables pre-emptive garbage collection– Transfers control to unmanaged code
Topic 4: InteroperabilityP/Invoke Sample
namespace HelloWorld{using System;
class MyClass{[dllimport(„user32.dll“, CharSet=CharSet.Ansi)]static extern int MessageBox(int h, string m,
string c, int t);
public static int Main() {return MessageBox(0, "Hello World!", "Caption", 0);
}}
}
38
Topic 4: Interoperability
Introduction• Unmanaged code can call back to managed code
– Unmanaged parameter is function pointer– Must supply parameter as delegate– P/Invoke creates callback thunk
• Passes address of thunk as callback parameter
Managed Code
.NET Application
Call passes pointer to callback function
Implementation of callbackfunction
Unmanaged Code
DLL
DLL function
Topic 4: InteroperabilityCallback Sample
public class EnumReport{
public bool Report(int hwnd, int lParam) { // report the window handleConsole.Write("Window handle is ");Console.WriteLine(hwnd);return true;
}};public class SampleClass{
delegate bool CallBack(int hwnd, int lParam);
[DllImport("user32")]static extern int EnumWindows(CallBack x, int y);
public static void Main() {EnumReport er = new EnumReport();CallBack myCallBack = new CallBack(er.Report);EnumWindows(myCallBack, 0);
}}
39
Topic 5:C# Syntax Features
Topic 5: C# Syntax Features
@ Literals• Identifiers vs. Keywords
– @ to use keyword as identifier– E.g. @if, @while, @throw…
• @ String literals– Turn off character escaping– “c:\\temp\\test” vs. @“c:\temp\test”– “hello\\nworld” vs. @“hello\nworld”
40
Topic 5: C# Syntax Features
@ Literals (examples)string a = "hello, world"; // hello, worldstring b = @"hello, world"; // hello, worldstring c = "hello \t world"; // hello worldstring d = @"hello \t world"; // hello \t worldstring e = "Joe said \"Hello\" to me"; // Joe said "Hello" to mestring f = @"Joe said ""Hello"" to me"; // Joe said "Hello" to mestring g = "\\\\server\\share\\file.txt"; // \\server\share\file.txtstring h = @"\\server\share\file.txt"; // \\server\share\file.txtstring i = "one\ntwo\nthree";string j = @"onetwothree";
Topic 5: C# Syntax Features
Enumerations• Have underlying type• First class value (not int as in C/C++)• Defines conversions• Defines parsing• Runtime information
41
Topic 5: C# Syntax FeaturesReference and Output parameters
• ref keyword– Does not accept null– Needs to be initialized
• out keyword– Cannot be read inside the function– Need not be initialized outside
• Example:– Declaration: void f (int x, ref int y, out int z);– Call: f(5, ref a, out b);
Topic 5: C# Syntax Features
Operator Overloading• Overloadable
– Unary: + - ! ~ ++ -- true false– Binary: + - * / % & | ^ << >> == != < > <= >=
• Non-overloadable– . -> = && || ? : new typeof sizeof is as
• Implicit assignment overloading– E.g. *= when * is overloaded
• Cast overloading– Conversions
• [] Overloading– Indexer properties
• At least one parameter is the declaring class
42
Topic 5: C# Syntax Features
Operator Overloading (cont.)• Advanced cases:
– Operators “true” and “false”• Used in Boolean conditions and && ||
– && is T.false(x) ? x : T.&(x, y)– || is T.true(x) ? x : T.|(x, y)
Topic 5: C# Syntax Features
Variable argument lists• Conventional way
– void f (int x, int y, params float[] f);– Call: f(4, 5, 4.5, 2.3, …);
• Undocumented way– More general– Slower– void f(__arglist);
43
Topic 5: C# Syntax Features
checked and unchecked• Checked and unchecked contexts
– [un]checked(…) – [un]checked …;
• Affected:– ++ -- + - * /– Explicit conversions
Topic 5: C# Syntax Features
“is” and “as”• Dynamic type checking
– O is T– O as T
• Is can be very powerful– Knows about boxing and stuff…
• As in not like a cast– Returns null on error (not exception)
44
Topic 5: C# Syntax Features
foreach• Use of enumerators in the language
– IEnumerable– Enumeration patter…
• foreach (type identifier in expression) embedded-statement
Topic 5: C# Syntax Features
foreach (formal)• A type C is said to be a collection type if it implements the
System.IEnumerable interface or implements the collection pattern by meeting all of the following criteria:
• C contains a public instance method with the signature GetEnumerator() that returns a struct-type, class-type, or interface-type, which is called E in the following text.
• E contains a public instance method with the signature MoveNext() and the return type bool.
• E contains a public instance property named Current that permits reading the current value. The type of this property is said to be the element type of the collection type.
45
Topic 5: C# Syntax Features
Preprocessor• #define• #undef• #if• #else• #endif• #region• #endregion• #error• #warning• #line
Topic 5: C# Syntax Features
Preprocessor (examples)#warning Code review needed before check-in#if Debug && Retail
#error A build can't be both debug and retail#endifclass Test {...}
46
Topic 5: C# Syntax Features
Others• readonly keyword• Static constructors• “switch” works on strings • “using” keyword• “using” directives
– nesting– aliases
• “lock” keyword• “sealed” and “new” keywords
Topic 5: C# Syntax Features
Classes• Special Classes
– Array, Delegate, Enum, ValueType• “const” vs. “readonly” fields
– “static readonly” fields• “abstract”, “virtual”, “override” and “sealed”
methods• “external” methods• Strange constructor behavior
– Code for initialized fields executed before the constructor in object creation!
47
Topic 5: C# Syntax Features
Classes (cont.)• Constructors
– Instance– Class (static)
• Overloading– this(...)– base(…)
• Default constructors– base()
Topic 5: C# Syntax Features
Properties• Look like fields
– Access pattern
• Behave like functions– Can be virtual, …– Have “get” and “set” methods
• Can be static• Treated as a single member of the class
– “new” hiding example
48
Topic 5: C# Syntax Features
Properties (example)public class Button: Control{
private string caption;public string Caption {
get {
return caption;}set {
if (caption != value) {
caption = value;Repaint();
}}
}
public override void Paint(Graphics g, Rectangle r) {
// Painting code goes here}
}
Topic 5: C# Syntax Features
Indexers• Essentially overriding the [] operator• Behaves as a property
– With parameters – the index– “get”, “set” again
• Can be overloaded
49
Topic 5: C# Syntax Features
Indexers (example)using System;class BitArray{
int[] bits;int length;public BitArray(int length) {
if (length < 0) throw new ArgumentException();bits = new int[((length - 1) >> 5) + 1];this.length = length;
}public int Length {
get { return length; }}public bool this[int index] {
get {if (index < 0 || index >= length) {
throw new IndexOutOfRangeException();}return (bits[index >> 5] & 1 << index) != 0;
}set {
if (index < 0 || index >= length) {throw new IndexOutOfRangeException();
}if (value) {
bits[index >> 5] |= 1 << index;}else {
bits[index >> 5] &= ~(1 << index);}
}}
}
Topic 5: C# Syntax Features
Arrays• Inherit from System.Array• Initialization• “foreach” works• Jagged arrays• Multi-dimensional arrays• Array covariance
– Example to follow…– Runtime check in assignment
50
Topic 6:.Net Programming Best Practices
Agenda• .NET Design Guidelines• Memory Management• Data Access• Internet Services• Threading• Security
51
.NET Design GuidelinesNaming Conventions
• Hungarian notation is out!• For public interfaces, use PascalCasing• For private members, use camelCasing• Use underscore “_” character to denote private
class members• Use camelCasing for all method parameters
.NET Design GuidelinesNaming Conventions
public class Customer{
private string _password;
public void SetPassword(string newPassword)
{_password = newPassword;
}}
52
.NET Design GuidelinesClass Members Usage
• Don’t use public fields, use properties• No write-only properties, use a method• Only use properties for setting and retrieving
values• Allow properties to be set in any order• Use a consistent ordering and naming pattern for
parameters
.NET Design GuidelinesBase Classes vs. Interfaces
• Only Use Interfaces When…– Unrelated classes want to support a protocol– Aggregation is not appropriate
• Provide class customization through protected methods
53
.NET Design GuidelinesError Raising and Handling
• Exceptions are not for flow of control!• Exceptions are “exceptional”• Derive new custom exceptions from the
ApplicationException class
Agenda• .NET Design Guidelines• Memory Management• Data Access• Internet Services• Threading• Security
54
Memory Management• Avoid Destructors (Finalize() in VB .NET)• Use Dispose()
class SampleClass : IDisposable {public void Dispose(){
// Clean up unmanaged resourcesGC.SuppressFinalize(this);
}~SampleClass() // override … Finalize …{
// Clean up unmanaged resources// this.Dispose();
}}
Agenda• .NET Design Guidelines• Memory Management• Data Access• Internet Services• Threading• Security
55
Data AccessAccessing Relational Data
• Always use the optimal Managed Provider• Pick DataReader over DataSet when possible• Used stored procedures when possible• Do NOT use dynamic connection strings
Data AccessXML Data
• Use the XmlDataDocument for XML/DataSet integration– DOM DataSet DOM
• Don’t use DOM if you don’t need it– Only necessary for in-memory editing
• XmlReader is faster than DOM
56
Agenda
• .NET Design Guidelines• Memory Management• Data Access• Internet Services• Threading• Security
Internet ServicesWebClient vs. WebRequest
• Use WebClient for simple request and response operations
• Use WebRequest for more complex operations– Asynchronous requests, setting headers, etc.
• Use the class with the features you need:– WebClient– WebRequest– TCPClient– Socket
57
Internet ServicesGeneral Tips
• Don’t pass credentials every time• Don’t type cast to descendant classes, such as
HttpRequest• In ASP.NET, use the asynchronous methods of
GetResponse and GetResponseStream• As a good starting point, use 8
connections/processor
Agenda• .NET Design Guidelines• Memory Management• Data Access• Internet Services• Threading• Security
58
ThreadingGeneral Tips
• Avoid locks whenever possible• Don’t provide static methods that alter static state• Asynchronous invocation via delegates are the
preferred threading mechanism
ThreadingSynchronization
• Starvation is caused by multiple threads contending for a resource
• The Monitor and ReaderWriterLock are designed to prevent starvation
59
Agenda• .NET Design Guidelines• Memory Management• Data Access• Internet Services• Threading• Security
SecurityKey Concepts
• Use the principal of least privilege• Don’t run Visual Studio with admin privileges
– Use the runas utilityC:\>runas /user:timmc\administrator cmdEnter password for timmc\administrator:
• Lock down security policy early
60
SecurityCode Access Security
• Access to a protected resource • The ability to perform a protected
operation FileIOPermission permission = new
FileIOPermission(PermissionState.None);permission.AllLocalFiles = FileIOPermissionAccess.Read;
SecurityRole-Based Security
• Imperative (old way)public void DoTransaction(){
IPrincipal principal = Thread.CurrentPrincipal;
if (!principal.IsInRole("Managers")){
throw new SecurityException("Not a "+ "manager!");
}// OK, do the transaction...
}
61
SecurityRole-Based Security
• Imperative (new way)public void DoTransaction(){
PrincipalPermission permission = new PrincipalPermission(null,
"Managers");permission.Demand();// Now do the transaction...
}
SecurityRole-Based Security
• Declarative[PrincipalPermission(SecurityAction.Demand,
Role="Managers")]void DoTransaction(){
// this time, really// do the transaction...
}
62
Session Summary
• Write consistent and predictable code• Write scalable, high-performance code• Write secure code
What Was Covered• Design Guidelines• Memory Management• Data Access• Internet Services• Threading• Security