1 Application Servers G22.3033-011 Session 5 - Sub-Topic 4 Introduction to .Net/C# Dr. Jean-Claude Franchitti New York University Computer 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. Oberg Prentice Hall, ISBN: 0-13-041801-3 • Other – C# Language Specification http://msdn.microsoft.com/vstudio/techinfo/articles/upgrade/Cshar pdownload.asp – Websites… • Rotor – Search for it in Google!
62
Embed
Application Servers G22.3033-011€¦ · Session 5 - Sub-Topic 4 Introduction to .Net/C# Dr. Jean-Claude Franchitti New York University Computer Science Department Courant Institute
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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
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
• 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
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
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
– 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));
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);
• 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.
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