98
C# .NET Migration Moving from Visual Basic to C# Jon Flanders [email protected] Kirk Fertitta [email protected] Jason Masterman [email protected] Ted Pattison [email protected] Doug Turnure [email protected] Jason Whittington [email protected] Brought to you by Microsoft

C# .NET Migration - A2Z Dotnet · PDF fileDateTime System-defined types ... Type Description Special format for literals ... – Waterfall construction model for C# allows derived

Embed Size (px)

Citation preview

2

News updates

• #1 : Attendee toolkits will be sent to you in the mail– .NET t-shirts– More special edition books

• #2: The “Slammer” Patch– http://www.microsoft.com/security/

3

Agenda

• The .NET Framework, The CLR and Obfuscation• Common Type System (CTS) and Common Language

Specification (CLS)• Language Basics of C#• Unique Features of C#• Assembly Versioning and Deployment in the GAC• Windows Forms and why you need to get Delegates and Events• Interoperability – COM/Win32• Writing data access code with ADO.NET

• Start at 9:00 AM• Break 10:15 till 10:30• Lunch 12:00 – 1:00• Break 2:30 – 2:45• End at 4:00

4

Developing with .NET

• Three ways to get a development environment• 1 – Download the Framework SDK

– http://msdn.microsoft.com/downloads/default.asp?url=/downloads/sample.asp?url=/msdn-files/027/000/976/msdncompositedoc.xml&frame=true

– FREE!– Does not include an IDE, use Notepad, EMACS, Ultra Edit, etc.

• 2 – Visual Studio .NET– Comes with the Framework SDK– Includes a visual development environment– Not free– Beta version of VS.NET 2003 is also available and includes lots of new

support for mobile devices• 3 – Windows Server 2003

– Ships with the Framework included in the OS– No visual IDE

5

Managed and Unmanaged Code

Unmanaged CodeManaged Code

CLR (Common Language Runtime)

x86 Machine Code

CIL(Common Intermediate Language)

Managed Code(C#, VB.NET, etc.)

.NET Compiler

x86 Machine Code

Unmanaged Code(VB 6, C++, etc.)

Generated at compile time!Compiler

Depending on the version of the CLR different machine code can be generated.

Generated at RUN time!

6

The .NET Framework is a development platform

• .NET Framework provides– Choice of several different language compilers– Debugger– Large number of Framework Class Libraries– Several different tools for inspection, security, deployment– Common Language Runtime (CLR) for Windows – Common Language Runtime for lightweight devices

7

Why a Runtime?

• MTS and COM+ were just better runtimes for COM objects– better threading support– better security– better transaction support

• .NET is just another runtime– With a whole lot more added value– Much more open/exposed architecture– Huge class library– Better threading story– Better memory management story– Better deployment story – xcopy deployments– Better configuration story - No registry dependencies– Better security story – Based on components not process/threads

8

Common Language Runtime

• CLR is your new Runtime– In a way it’s like a new Operating System– It deals with memory layout– Provides your type system– Provides an additional layer of security– Provides a threading model– Provides ability to run code on other platforms

• Knowing how the CLR works is they key to building applications with .NET

9

Run on Any Platform

• Today mainly Windows machines• Handheld devices are also supported• Rotor – Open Source Project for Linux and other platforms

Your code

Handheld device

Compact Framework (CF)

Operating System

Hardware

Your code

Framework Class Libraries

Desktop Computer

Common Language Runtime (CLR)

Operating System

Hardware

Your code

Framework Class Libraries

Server Computer

Common Language Runtime (CLR)

Operating System

Hardware

Your code

Framework Class Libraries

Windows Server 2003

CF-compatible deviceWindows XP Professional

10

Talk to Any Platform

• Running code on any platform may be desirable• Running code that can talk to any platform is often more desirable

Linux Server

IBM Mainframe

.NET Web Service Client

Oracle DB

Windows Server

11

Platforms That Support .NET Framework

• Client-side Windows platforms– Windows XP– Windows 2000– Windows NT– Windows 98/Windows ME

• Server-side Windows platforms (ASP.NET)– Windows Server 2003– Windows 2000 Server– Windows XP – for development purposes

• ASP.NET Helpful Install Utility– aspnet_regiis.exe /i will install ASP.NET on a machine after

VS.NET was installed

12

Many Languages – one runtime

• All .NET languages compile to Common Intermediate Language

C# Compiler

J# Source Code

J# Compiler

Managed C++

C++ Compiler

VB.NET Source Code C# Source Code

VB.NET Compiler

MSIL AssemblyWith Metadata

App.exe

13

Concerns with MSIL

• Easy to decompile!• Easy to see any hard coded database connection strings• How does one hide intellectual property, proprietary algorithms

and such?

14

Code Obfuscation

• Not build into current release of VS .NET • Part of future release of VS .NET 2003

15

Obfuscated Code

//Original Source Code Before Obfuscationprivate void CalcPayroll(SpecialList employeeGroup){

while (employeeGroup.HasMore()){

employee = employeeGroup.GetNext(true);employee.UpdateSalary();DistributeCheck(employee);

}}//Reverse-Engineered Source Code //After Overload Induction Dotfuscation private void a(a b){

while (b.a()) {

a = b.a(true);a.a();a(a);

}}

16

Common Type System - CTS

• The CLR defines the type system, CTS• All .NET languages map into the CTS• CLR types defined under the System Namespace• All .NET languages provide their own keywords that map to the

underlying CTS types– C# int keyword == System.Int32– VB.NET integer keyword = System.Int32

17

Common Type System (CTS)

• CLR programming model is based on the CTS– CTS provides backbone for the CLR– CTS defines a core set of system types– CTS defines set of object-oriented programming features– CTS defines rules for creating user-defined types– all managed languages must map to the CTS

18

Core CTS types• System.Object is root of type system

– All types derive from Object– Some types treated special with regard to memory layout

(ValueTypes)

String Array ValueType Exception Delegate Class1

MulticastDelegate

Class2

Class3

Object

Enum1

Structure1EnumPrimitive types

Boolean

Byte

Int16

Int32

Int64

Char

Single

Double

Decimal

DateTime

System-defined types

User-defined types

Delegate1

TimeSpan

Guid

19

Common Language Specification (CLS)

• Ensures language interoperability• Defines a subset of the CTS• Most of the Framework Class Libraries are CLS compliant• Cannot overload based on return type• Unsigned integral types are not allowed on public methods• Can use the CLSCompliantAttribute to enforce checks

20

CLSCompliantAttributeusing System;// Assembly marked as compliant.[assembly: CLSCompliantAttribute(true)]// Class marked as compliant.[CLSCompliantAttribute(true)]public class MyCompliantClass {

// ChangeValue exposes UInt32, which is not in CLS.// A compile-time error results.public void Method1(UInt32 var){ }//not a problem because scope is local to appinternal void Method2(UInt32 var){}//tell compiler to ignore CSLCompliant//attribute for this method[CLSCompliant(false)]public void Method3(UInt32 var){}

}

21

C# Types – extend CLS Types

• Comprehensive set of simple types available

"hello"character sequencestring

M or m suffixno suffix

F or f suffixU/u and L/l suffixL or l suffixU suffixnone

none

none

none

none

'A' '\x0041' '\u0041'

true false

Special format for literalsDescriptionType

128 bit high precisiondecimal

64 bit signed integerlong

64 bit floating pointdouble

16 bit Unicode characterchar

32 bit floating pointfloat

64 bit unsigned integerulong

32 bit unsigned integeruint

32 bit signed integerint

16 bit unsigned integerushort

16 bit signed integershort

8 bit unsigned integerbyte

8 bit signed integersbyte

BooleanboolBoolean

character

integer

floating point

string

22

Agenda

The .NET Framework and the CLRCommon Type System (CTS) and Common Language Specification (CLS)

• Language Basics of C#• Unique Features of C#• Assembly Versioning and Deployment in the GAC• Windows Forms and why you need to get Delegates and Events• Interoperability – COM/Win32• Writing data access code with ADO.NET

23

C# and VB.NET – not as different as you might think

• Both have:– Support structured exception handling– Support for Interfaces– Support for Inheritance– Support for virtual functions– Support for static functions– Support for method overloading– Support for constructors/destructors– Support for indexers– Support FCL

24

Class Basics

public class Human{

public int Age;

public string Name;

public void Speak(){

Console.WriteLine(“Name:{0} Age:{1}",Name,Age);

}

}

Simple class with public fields for properties

class Client{

static void Main(string[] args){

Human h = new Human();h.Age = 21;h.Name = "Rian Brandell";

}}

Client code working with Human classes

25

Propertiespublic class Human{

private int m_Age;public int Age{

set{

if (value > 0){

m_Age = value;}else{

throw new ArgumentOutOfRangeException("Age invalid");}

}get{return m_Age;}

}}

A better way of exposing data members, through a public property and private field for storage

26

Interfaces

• Interfaces are an explicit kind of type in the CLR– Express what is common across classes– Allow classes to share a common design– Include sufficient type information to program against, but not

enough to instantiate– Members may include methods, properties, indexers, and events– Cannot include implementation details or fields– Concrete type must supply all implementation details

27

using System;interface ICowboy {

void Draw();string Name { get; }object this[int n] { get; }

}

class Rancher : ICowboy {

public void Draw() { Console.WriteLine("Bang!"); }public string Name { get { return("Tex"); } }public object this[int n] { get { return(...); } }

}

class Wrangler : ICowboy {

public void Draw() { Console.WriteLine("Bang!"); }public string Name { get { return("Woody"); } }public object this[int n] { get { return(...); } }

}

ICowboy cb = new Rancher();

cb.Draw();

Console.WriteLine(cb.Name);

cb = new Wrangler();

cb.Draw();

Console.WriteLine(cb.Name);

Using the interfaces

Declaring and implementing the interfaces

Implementing and using interfaces

28

Type compatibility and navigation

• C# supports typical type compatibility– Types may implement multiple interfaces– A class must declare which interface it supports

• The CLR supports explicit runtime type navigation– An object is type-compatible with interface X if and only if the

object's class supports interface X– C# is, as, and typecast operators support explicit run-time type

navigation

29

Using Type Navigation Operatorsinterface ICowboy {}interface IArtist {}class Tex : ICowboy {}class LaRoche : IArtist {}

// What happens if DrawAndPaint is passed// a Tex or LaRoche instance?//void DrawAndPaint( object o ) {

// InvalidCastException on failure:IArtist a = (IArtist)o;a.Paint();

// False on failure:bool IsArmed = o is ICowboy;

// Null reference on failure:ICowboy cb = o as ICowboy;if( cb != null ) {

cb.Draw();}

}

Using explicit cast, is and as operations to perform type navigation

30

Explicit interface implementation

interface ICowboy { void Draw(); }

interface IArtist { void Draw(); }

class LaTex : ICowboy, IArtist

{

void ICowboy.Draw() { Console.WriteLine("Bang!"); }

void IArtist.Draw() { Console.WriteLine("Brush, brush"); }

}

LaTex starvingDrifter = new LaTex();

starvingDrifter.Draw(); // Compiler error - no public Draw()

ICowboy cb = starvingDrifter;

cb.Draw(); // Bang!

IArtist a = starvingDrifter;

a.Draw(); // Brush, brush

Implementation is not marked public so the only way to get to the implementation is through the interface

31

Base classes

• Every type has at most one base type– System.Object and interfaces have no base type– System.Enum for enums, System.Array for arrays– Base type for classes defaults to System.Object if not explicitly

specified– sealed class modifier prevents use as a base type– abstract class modifier mandates derivation

32

Specifying a base class in C#

public class MyClassName : BaseImpl, Itf1, Itf2{ // member definitions go here}

List of supported interfaces

Name of base type

33

Base/derived construction

• Constructors and base types have "issues"– Base type constructors not part of derived type's signature– Base type constructors must be called from derived constructors

using C++-like syntax– Overloaded constructor on self can be called using C++-like

syntax– Base type's constructor executes using the most-derived type (like

Java, not C++)– Waterfall construction model for C# allows derived members to be

accessed prior to initialization

34

Base types and constructors

interface IPerson {...}

interface ICowboy {...}

public class PersonImpl : IPerson

{

public PersonImpl(string name) {...}

public PersonImpl(string name, int age) {...}

}

public class Cowboy : PersonImpl, ICowboy

{

public Cowboy(string n, int a ) : base(n, a) {...}

public Cowboy(string n) : base(n) {...}

public Cowboy() : this("Tex", 34) {}

public void Draw() {...}

}

Chain call to base types constructor

35

public class Base { public int x = a(); public Base() { b(); }}

public class D1 : Base { public int y = c(); public D1() { d(); }}

public class D2 : D1 { public int z = e(); public D2() { f(); }}

public class D3 : D2 { public int w = g(); public D3() { h(); }}

D3..ctor()

g()

D2..ctor

h()

e()

D1..ctor

f()

c()

Base..ctor()

d()

a()

b()

Derivation and constructor flow of control

36

C# method dispatching modifiers

sealed

virtual

abstract

C# Syntax

From the perspective of a base class designer

Meaning

Method may be replaced by derived class.

Method must be replaced by a derived class (or redeclared abstract).

Method may not be replaced by a derived class.

override

new

C# Syntax

From the perspective of a derived class designer

Meaning

Method replaces a virtual/abstract/override method in the base with its ownimplementation, and is still overridable by further derived types.

Method is unrelated to a similarly defined method in the base class. Typicallyused to deal with a change to a base class that creates a collision where onedidn't exist before, and where it's not practical to just choose a different methodname.

37

Using method dispatching modifiersabstract class Base {

public void a() {} // statically bound, cannot overridepublic virtual void b() {} // may be overriddenpublic abstract void c(); // must override or redeclare abstractpublic virtual void d() {} // may be overridden

}

class Derived : Base {

public override void a() {} // illegal: Base.a not overridablepublic override void b() {} // legal: Base.b override allowedpublic override void c() {} // legal: Base.c override requiredpublic new void d() {} // unrelated to Base.d, not overridable

}

class MoreDerived : Derived {

public override void c() {} // legal: Derived.c still overridable}

38

Combining method dispatching modifiers

sealed override

new virtual

C# Syntax

Method modifer combinations

Meaning

This method replaces a virtual/abstract/override method in the base with its ownimplementation, and terminates the overridability of this method as far as furtherderived types are concerned.

This method is unrelated to a similarly defined method in the base class andgets a new slot in the associated virtual method dispatching table for this class.Further derived types may choose to override this method.

new abstractThis method is unrelated to a similarly defined method in the base class andgets a new slot in the associated virtual method dispatching table for this class.Further derived types must to override this method.

39

Combining method modifiersabstract class Base {

public void a() {} // statically bound, cannot overridepublic virtual void b() {} // may be overriddenpublic abstract void c(); // must override or redeclare abstractpublic virtual void d() {} // may be overridden

}

abstract class Derived : Base {

public sealed override void b() {} // terminal override of Base.bpublic new virtual void d() {} // unrelated to Base.d, overridable

}

class MoreDerived : Derived {

public override void b() {} // illegal: Derived.b sealedpublic override void c() {} // overrides Base.cpublic override void d() {} // overrides Derived.d

}

40

Destructors

• Implemented by defining a method via ~ClassName, like C++• Not called directly by your code• Called by the Garbage Collector when needed• Often desirable to have cleanup code run before GC runs

– Implement IDisposable interface– Called by client when done using object

41

Destructors and IDisposableusing System;class Class1{

static void Main(string[] args){

Widget wg = new Widget();Console.WriteLine(wg.ToString());wg.Dispose(); //specific call to cleanupwg = null; //let go of reference and wait for GCConsole.ReadLine();

}}public class Widget : IDisposable{

~Widget(){

//cleanup code called by GC}public void Dispose(){

//perform cleanup}

}

Destructor called by GC

Dispose called by client!

42

Agenda

The .NET Framework and the CLRCommon Type System (CTS) and Common Language Specification (CLS)Language Basics of C#

• Unique Features of C#• Assembly Versioning and Deployment in the GAC• Windows Forms and why you need to get Delegates and Events• Interoperability – COM/Win32• Writing data access code with ADO.NET

43

Culturally Very Different ;-)

• C# is much a more disciplined/strict language than VB.NET– Case sensitive– No “Option Explicit Off” for variable declarations– No “Option Strict Off” for strict type checking– Required to initialize variables before use– Targeted towards C++ and Java developer– Not hard to switch too if coming from VB though

44

Unique C# Features

• Native support for Unsigned integral types• Operator overloading• Using statement

– Ensures IDisposable.Dispose is called• Unsafe code blocks

– Mainly used to support API’s that require pointers• Documentation Comments

– Used to generate XML or HTML documentation• Strict type checking is on and can’t be turned off

– VB.NET has Option Strict on/off with Off being the default

45

Operator Overloadingusing System;class Client{

static void Main(string[] args){Point p1 = new Point();p1.x = 10; p1.y=10;

Point p2 = new Point();p2.x = 10; p2.y=10;

Point p3 = p1 + p2;Console.WriteLine("p3.x:{0} p3.y:{1}",p3.x,p3.y);

}}class Point{

public int x;public int y;public static Point operator+(Point p1, Point p2){

Point p = new Point();p.x = p1.x + p2.x;p.y = p1.y + p2.y;return p;

}}

Use the operator keyword and whichever operator you wish to overload

46

Using Statementusing System;

class Class1{

static void Main(string[] args){

using(DataBaseManager dbm = new DataBaseManager()){

//use dbm

}//Dispose method of dbm called automatically!}

}

public class DataBaseManager : IDisposable{

void IDisposable.Dispose(){

//database cleanup code}

}

Using statement causes automatic call to Dispose to be generated at compile time

47

Unsafe Code Blocks

• Must set compiler option in project properties– Project->Properties->Configuration Properties->Build->Allow

Unsafe Code blocks – set to true

[DllImport("kernel32", SetLastError=true)]

static extern unsafe bool ReadFile(int hFile,

void* lpBuffer, int nBytesToRead,

int* nBytesRead, int overlapped);

public unsafe int Read(byte[] buffer, int index, int count)

{

int n = 0;

fixed (byte* p = buffer)

{

ReadFile(handle, p + index, count, &n, 0);

}

return n;

}

Marked as Unsafe due to pointers

Marked fixed to keep object from moving when GC runs

48

Documentation Comments

• Just type “///” above a method and VS.NET does the rest!• Project->Properties->Configuration Properties->Build->XML

Documentation Path• Tools->Build Comment Web Pages…• Generates XML and HTML page for viewing

/// <summary>

/// Class for managing checking account

/// </summary>

public class Checking{

/// <summary>

/// Called to make a deposit

/// </summary>

/// <param name="amount"></param>

/// <returns></returns>

public int MakeDeposit(int amount){

}

}

49

Documentation Comments-Output

50

Agenda

The .NET Framework and the CLRCommon Type System (CTS) and Common Language Specification (CLS)Language Basics of C#Unique Features of C#

• Assembly Versioning and Deployment in the GAC• Windows Forms and why you need to get Delegates and Events• Interoperability – COM/Win32• Writing data access code with ADO.NET

51

Assemblies and Versioning

• Assemblies by default are not strong named• Assemblies without strong name are not versionable• Must learn how to give an assembly a strong name• Requires knowledge of some other tools• Versioned assemblies can be installed in the Global Assembly

Cache – via “gacutil.exe –i yourassembly.dll”• Strong Named assemblies include:

– Name– Version– Culture– Public Key Token

52

Generating Strong Named Assembly• A strong named assembly must have:

– Name, version, culture and public key token– By default culture is “neutral”, which is a valid value if not specified

• Steps involved– Add Key attributes to your code

• AssemblyVersion• AssemblyKeyFile

– Generate key file with “sn.exe –k mykey.snk”– Compile code

using System;

using System.Reflection;

[assembly: AssemblyVersion("1.0.0.0")]

[assembly: AssemblyDelaySign(false)]

[assembly: AssemblyKeyFile("..\\..\\mykey.snk")]

class TheLibrary{

public void Method1()

{

//implementation

}

}

Version number

Assembly key file generated with sn.exe tool

53

Assembly without strong name

Notice lack of version number and public key

54

Client referencing weak assembly

Notice lack of version number and public key

Notice version number and key for strong name assembly

55

Assembly with strong name

Notice version number and public key

56

Client referencing strong named assembly

Notice version number and public key

57

Client and Versioning

• Client is compiled to version 1.0.0.0 of assembly• What happens if we need client to use version 2.0.0.0 of

assembly?• We don’t want to recompile the client –

– Use application configuration file– Redirect client to new version in configuration file

58

Client.exe.config for assembly redirect

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<runtime>

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

<dependentAssembly>

<assemblyIdentity name="assemblies"

publicKeyToken="115b9f99d2687875"

culture="neutral" />

<bindingRedirect oldVersion="1.0.0.0"

newVersion="2.0.0.0"/>

</dependentAssembly>

</assemblyBinding>

</runtime>

</configuration>

Assembly redirect to newer version. No need to recompile client!

59

Global Assembly Cache

• One of the first places searched for matching assembly by the assembly resolver

• Similar to the registry but very different• Only strong named assemblies can be placed in the GAC• Very helpful for shared assemblies

Our assembly installed in the GAC

60

Publisher policy

• Shared component “publishers” can automate version redirection for their assemblies– deployed as XML configuration files embedded in separate

assemblies– “policy assembly” itself must be installed in the GAC– one policy assembly per major/minor version number– policy.<major>.<minor>.<asmname>.dll– applications can disable publisher-driven version redirects

• application-wide• per-publisher

61

Creating a publisher policy assembly

csc /t:library acme.cs

using System.Reflection;[assembly: AssemblyKeyFile("acme.snk")][assembly: AssemblyVersion("1.0.0.1")]

acme.cs (new version 1.0.0.1)

acme.dll (new version 1.0.0.1)

<configuration> <runtime> <assemblyBinding ...> <dependentAssembly> <assemblyIdentity name="acme" publicKeyToken="abcd...." culture="" /> <bindingRedirect oldVersion="1.0.0.0" newVersion="1.0.0.1" /> </dependentAssembly> </assemblyBinding> </runtime></configuration>

acme.dll.config

al.exe /link:acme.dll.config /out:policy.1.0.acme.dll /keyf:acme.snk /v:1.0.0.0

policy.1.0.acme.dll

acme.snk

Installed in the GAC on target machines

62

Disabling publisher policy for a given publisher

<?xml version="1.0" ?>

<configuration xmlns:rt="urn:schemas-microsoft-com:asm.v1"><runtime>

<rt:assemblyBinding><dependentAssembly><assemblyIdentity name="child"

publicKeyToken="eef261d4ec06435a"culture="" />

<publisherPolicy apply="no"/></dependentAssembly>

</rt:assemblyBinding></runtime>

</configuration>

63

Agenda

The .NET Framework and the CLRCommon Type System (CTS) and Common Language Specification (CLS)Language Basics of C#Unique Features of C#Assembly Versioning and Deployment in the GAC

• Windows Forms and why you need to get Delegates and Events• Interoperability – COM/Win32• Writing data access code with ADO.NET

64

Delegates

• Provide a very loosely coupled notification/callback mechanism• Class based references are tightly coupled• Interfaces are better but still have drawbacks

– Must implement entire interface– May not be interested in all method notifications defined in the

interface• Delegates are the smallest piece of an interface

– A single method signature– Events are based on delegates– Can use delegates for asynchronous programming– Important aspect of .NET development to understand

• Great article on delegates– http://www.sellsbrothers.com/writing/default.aspx?content=delegat

es.htm

65

Pattern

• Notification typically involves registration and callback– target registers with caller– caller calls back target when state changes– pattern also called publish/subscribe

registerParent(target)

Student(caller)

callback

66

Delegates

• .NET Framework uses delegates to implement callbacks– intermediary between caller and target– declaration defines callback method signature– instance stores object reference and method token

targetobject

callercallbacktarget

methodcallback delegate

67

Delegate definition

• Define delegate with delegate keyword– syntax similar to method declaration without body– delegate name placed where method name usually goes

delegate void GradeChange(double gpa);

delegate keyword name of created delegate

callback method return type

callback methodparameter

68

Delegate as type

• Delegate name used as type name– can declare references– can create objects

delegate void GradeChange(double gpa);define delegate

GradeChange g = new GradeChange(...);

reference object

69

Target use of delegate

• Target defines method with signature specified by delegate– parameters and return type must match– method name not constrained

delegate definesrequired signature delegate void GradeChange(double gpa);

class Parent{public void Report(double gpa){...

}}

target

method signaturematches delegate

70

Caller use of delegate

• Caller typically defines delegate reference

class Student{public GradeChange Targets;...

}

caller

delegate reference

71

Registration

• Create delegate object and store in caller to register– pass target object and method to delegate constructor

void Run(){Student ann = new Student("Ann");

Parent mom = new Parent();

GradeChange g = new GradeChange(mom.Report);

ann.Targets = g;...

}

caller

target

create

store

targetobject

targetmethod

72

Invocation

• Caller invokes callback indirectly through delegate– uses method call syntax on delegate– delegate calls target method on target object

class Student{public GradeChange Targets;

public void RecordClass(int grade){// update gpa...Targets(gpa);

}}

invoke callbackthrough delegate

callback takesdouble argument

73

Summary of delegate use

delegate void GradeChange(double gpa);

class Parent{public void Report(double gpa) { ... }

}

class Student{public GradeChange Targets;

public void RecordClass(int grade){// update gpa...Targets(gpa);

}}

define delegate

target method

caller stores delegate

caller invokes delegate

Student ann = new Student("Ann");Parent mom = new Parent();

ann.Targets = new GradeChange(mom.Report);ann.RecordClass(4); // 4 == 'A'

create and install delegate

74

Multiple targets

• Can combine delegates using operator+= or operator+– creates invocation list of delegates– all targets called when delegate invoked– targets called in order added– use of += ok even when left-hand-side is null

Parent mom = new Parent();Parent dad = new Parent();

Student ann = new Student("Ann");

ann.Targets += new GradeChange(mom.Report);ann.Targets += new GradeChange(dad.Report);...

targets

firstsecond

75

Remove delegate

• Can remove delegate from invocation list– use operator-= or operator-– target object and method identity determines which is removed

Parent mom = new Parent();Parent dad = new Parent();

Student ann = new Student("Ann");

ann.Targets += new GradeChange(mom.Report);ann.Targets += new GradeChange(dad.Report);...ann.Targets -= new GradeChange(dad.Report);...

add

remove

targetobject

targetmethod

76

Public delegate

• Not common to have public delegate field– allows assignment: could overwrite existing registrants– allows external invocation: decision should be made internally

class Student{public GradeChange Targets;...

}

public delegate

Parent mom = new Parent();Parent dad = new Parent();Student ann = new Student("Ann");...ann.Targets = new GradeChange(mom.Report);ann.Targets = new GradeChange(dad.Report);...ann.Targets(4.0);...

overwrite mom handler

invoke

77

Events

• Events give private data/public accessor pattern for delegates– created by applying event keyword to delegate– external code can uses += and -=– no external assignment or invocation

class Student{public event GradeChange Targets;...

}

event

Parent mom = new Parent();Student ann = new Student("Ann");

ann.Targets += new GradeChange(mom.Report);

ann.Targets = new GradeChange(mom.Report);ann.Targets(4.0);...

ok to use +=

error to use =error to invoke

78

Agenda

The .NET Framework and the CLRCommon Type System (CTS) and Common Language Specification (CLS)Language Basics of C#Unique Features of C#Assembly Versioning and Deployment in the GACWindows Forms and why you need to get Delegates and Events

• Interoperability – COM/Win32• Writing data access code with ADO.NET

79

Interoperability

• Framework Class Libraries is what counts• Most of learning .NET is in the FCL!• Not all things possible with managed FCL classes• May need to call COM or C style DLL’s

– COM interoperability works very well from any .NET language– P/Invoke works well for C style DLL’s with few limitations

Three flavors of interoperability• Two for calling legacy code

– COM interoperability (COM Interop)– Platform Invoke (P/Invoke)

• One for calling .NET from Legacy Code– .NET Interoperability with COM clients

80

COM Interoperability

• Must deal with type transitions in/out of the runtime• Requires Interoperability assembly• Interoperability assembly generated two ways

– VS.NET Add Reference – easily generates interop assembly– TLBIMP.EXE utility – allow fine grain control over interop

assembly

81

Using a VB6 DLL from C# .NET

• CLR-to-COM interaction made possible by interop assemblies– interop assembly is a managed shim DLL that wraps a COM DLL– .NET client programs against managed types in interop assembly– CLR uses interop assembly at runtime to create/call COM objects

• How do you create an interop assembly?– using a .NET SDK Framework utility named TLBIMP.EXE– using Visual Studio .NET

BobsLibrary.dll

Type library

interface _Class1 coclass Class1

executable x86 instructions

TLBIMP.EXE

Interop.BobsLibrary.dll

Managed Type Information

interface _Class1 class Class1class Class1Class

Assembly ManifestMyApp.exe

Assembly Manifest

dependent assembly list

mscorlibMicrosoft.VisualBasicInterop.BobsLibrary

82

Creating an interop assembly with VS.NET

• Visual Studio .NET can build the interop assembly for you– use COM tab in project's Add Reference dialog– VS.NET cannot build an interop assembly with a strong name

83

Platform Invoke - P/Invoke

• P/Invoke is the technology that allows managed code to call out to unmanaged code– LoadLibrary/GetProcAddress automated using static methods

marked extern– Can control all aspects using DllImport attribute– No call to LoadLibrary until first invocation (a la delay load)– Unicode/ANSI issues handled explicitly or automatically based on

platform

84

Using P/Invoke

using System.Runtime.InteropServices;

public class K32Wrapper {

[ DllImport("kernel32.dll") ]public extern static void Sleep(uint msec);[ DllImport("kernel32.dll", EntryPoint = "Sleep") ]public extern static void Doze(uint msec);[ DllImport("user32.dll") ]public extern static uint MessageBox(int hwnd, String m,

String c, uint flags);[DllImport("user32.dll", EntryPoint="MessageBoxW",

ExactSpelling=true, CharSet=CharSet.Unicode)]public extern static uint UniBox(int hwnd, String m,

String c, uint flags);}

InteropServices namespace

DllImport attribute

85

MarshalAsAttribute parameters

• Controlling type transitions out of the runtime• Done via MarshalAsAttribute

ArraySubType UnmanagedType

Value UnmanagedType

SafeArraySubType VarType

SizeParamIndex short

SizeConst int

MarshalType String

MarshalCookie String

Parameter Name Type

Unmanaged type to marshal to (mandatory)

Unmanaged type of array elements

Unmanaged VARTYPE of safearray elements

Fixed size of unmanaged array

Index of parameter containing [size_is] value

Fully-qualified type name of custom marshaler

Cookie for custom marshaler

Description

86

Using MarshalAs on parametersusing System.Runtime.InteropServices;

public class FooBarWrapper {

// this routine wraps a native function declared as// void _stdcall DoIt(LPCWSTR s1, LPCSTR s2,// LPTSTR s3, BSTR s4);

[ DllImport("foobar.dll") ]public static extern void DoIt(

[MarshalAs(UnmanagedType.LPWStr)] String s1,[MarshalAs(UnmanagedType.LPStr)] String s2,[MarshalAs(UnmanagedType.LPTStr)] String s3,[MarshalAs(UnmanagedType.BStr)] String s4);

}

Controlling type transitions out of the runtime via MarshalAsattribute

87

.NET Interoperability with COM

• In the real world you will also need to expose your .NET components to COM clients

• TLBEXP.EXE can export .NET info to COM type libraries• REGASM.EXE will add .NET information to registry and generate

COM type libraries

mycsharpcode.dll mycsharpcode.tlb

interface IPatient {}

interface IBillee {}

struct ORGAN {}

class American:IPatient, IBillee {}

interface IPatient : IDispatch {}

interface IBillee : IDispatch {}

struct ORGAN {}

coclass American {_American,IPatient, IBillee}

interface _American : IDispatch {}

TLBEXP.EXE

TLBIMP.EXE

88

REGASM

• The SDK provides a tool to make managed types available to COM's CoCreateInstance– TLBIMP makes COM classes available to CLR via new operator– REGASM adds COM registry entries for all CLR classes in an

assembly– MSCOREE registered as actual InprocServer32– Can suppress exposure using ComVisible or NoComRegistration attributes

– Can write custom class factory if desired– Use REGASM /codebase for assemblies not in GAC

89

.NET Exposed for COM Clients

using System;

public interface IMath

{

int Add(int x, int y);

int Subtract(int x, int y);

}

// After building run: regasm /codebase /tlb Calc.dll

public class Calc : IMath

{

public int Add(int x, int y) { return x + y; }

public int Subtract(int x, int y) { return x - y; }

}

90

The Registry after REGASM

• Registry entries for .NET componentNotice that the registry points to mscoree.dll and it loads the calc.dll

91

Agenda

The .NET Framework and the CLRCommon Type System (CTS) and Common Language Specification (CLS)Language Basics of C#Unique Features of C#Assembly Versioning and Deployment in the GACWindows Forms and why you need to get Delegates and EventsInteroperability – COM/Win32

• Writing data access code with ADO.NET

92

ADO.NET

• ADO.NET shipped with two class hierarchies– One that is 100% managed for working with SQL Server– One that provides managed objects over any existing unmanaged

provider– Other managed providers exist now!

ADO.NET

SqlCommandOleDbCommand

OleDbConnection SqlConnection

Unmanaged Providers TDS Parser - managed

93

ADO.NET Examplepublic static void UseDataReader(){

SqlConnection conn = newSqlConnection("server=localhost;database=pubs;trusted_connection=true");SqlCommand cmd = new SqlCommand("select * from authors",conn);conn.Open();IDataReader rdr = cmd.ExecuteReader();while (rdr.Read()){

Console.WriteLine(rdr["au_lname"]);int col = rdr.GetOrdinal("au_lname");Console.WriteLine(rdr[col]);Console.WriteLine(rdr.GetString(col));

}}

SqlConnection and SqlCommand

IDataReader is used for reading data via an underlying stream

94

DataSets

• Provides a disconnected model• In memory representation similar to a Recordset• Not dependent on any specific resource manager!• Can be bound to controls• Provides easy edit and update functionality

DataSet

SqlDataAdapterOracleDataAdapter

ExchangeDataAdapter

Active DirectoryDataAdapter

SQL ServerOracle

DataSet is a stand alone data store!XML Data

ExchangeActive Directory

95

DataSet Example

public static void UseDataSet()

{

SqlConnection conn = new

SqlConnection("server=localhost;database=pubs;trusted_connection=true");

SqlCommand cmd = new SqlCommand("select * from authors",conn);

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

da.Fill(ds);

ds.WriteXml(Console.Out,System.Data.XmlWriteMode.IgnoreSchema);

}

DataAdapter executes statement and pours results into the dataset

DataAdapter is also smart enough to open the connection if needed and close it when finished

96

Agenda

The .NET Framework and the CLRCommon Type System (CTS) and Common Language Specification (CLS)Language Basics of C#Unique Features of C#Assembly Versioning and Deployment in the GACWindows Forms and why you need to get Delegates and EventsInteroperability – COM/Win32Writing data access code with ADO.NET

97

Call to Action

• Must master Framework Class Libraries• Many aspects to explore in more detail• Language is the easy part• ASP.NET will be next!• Take a look at the new platform - Windows Server 2003

– Many improvements, especially with IIS

98

Useful URLs

• http://portals.devx.com/SummitDays– valuable .NET resources including Ted's sample chapter

• http://msdn.microsoft.com/net– valuable .NET resources from Microsoft

• http://www.develop.com– Information about instructor-led training from DevelopMentor– http://discuss.develop.com – one the best list servers for .NET

information on the web• http://www.jmasterman.com/isvtour

– PDF version of slides and zip file of samples/labs