Transcript
Page 1: NET Framework, C# et .NET Remoting

.NET Framework, C# et .NET Framework, C# et .NET Remoting .NET Remoting

Sébastien BoulaySébastien [email protected]@the-gnou-community.net

Master GI – option SRRMaster GI – option SRR25 novembre 200425 novembre 2004

Page 2: NET Framework, C# et .NET Remoting

SommaireSommaire .NET Framework.NET Framework

IntroductionIntroduction Architecture et fonctionnementArchitecture et fonctionnement Standardisation et interopérabilitéStandardisation et interopérabilité

C#C# Concepts de baseConcepts de base Types et variablesTypes et variables ClassesClasses Fonctionnalités avancéesFonctionnalités avancées

.NET Remoting.NET Remoting PrincipePrincipe ConfigurationConfiguration

DemosDemos

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 22

Page 3: NET Framework, C# et .NET Remoting

IntroductionIntroduction

Technologie proposée par MicrosoftTechnologie proposée par Microsoft Plateforme de développement et d’exécutionPlateforme de développement et d’exécution Orientée environnements distribuésOrientée environnements distribués

ObjectifsObjectifs Contexte d’exécution robuste et sécuriséContexte d’exécution robuste et sécurisé Déploiement et administration simplifiéDéploiement et administration simplifié Intégration de l’existantIntégration de l’existant Développement d’applications simplifiéDéveloppement d’applications simplifié

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 33.NET Framework.NET Framework

Page 4: NET Framework, C# et .NET Remoting

ArchitectureArchitecture

Visual Basic

CLS (Common Language Specification)

ASP.NET

CLR (Common Language Runtime)

Système d’exploitation

C# J# Managed C++ JScript …

ADO.NET et XMLClasses .NET Framework

Windows Forms

Windows Red Hat DebianFree BSD …

Plateforme .NET, C# et .NET RemotingPlateforme .NET, C# et .NET Remoting 44Plateforme .NETPlateforme .NET

Page 5: NET Framework, C# et .NET Remoting

Microsoft Intermediate LanguageMicrosoft Intermediate Language

Format intermédiaireFormat intermédiaire Indépendant de la machineIndépendant de la machine Converti en langage machine par le CLRConverti en langage machine par le CLR

Code managéCode managé

Assemblage (assembly)Assemblage (assembly) ManifestManifest Meta donnéesMeta données Code MSILCode MSIL RessourcesRessources

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 55.NET Framework.NET Framework

Page 6: NET Framework, C# et .NET Remoting

Common Language RuntimeCommon Language Runtime

Plateforme .NET, C# et .NET RemotingPlateforme .NET, C# et .NET Remoting 66Plateforme .NETPlateforme .NET

Class Loader

IL to NativeCompilers

CodeManager

GarbageCollector

Security Engine Debug Engine

Type Checker Exception Manager

Thread Support COM Marshaler

Base Class Library Support

Page 7: NET Framework, C# et .NET Remoting

CTS (Common Type Specification)CTS (Common Type Specification)Système de types uniqueSystème de types uniquePartagé par les compilateurs, outils et le CLRPartagé par les compilateurs, outils et le CLR

Ensemble de règles Ensemble de règles interopérabilité des langages interopérabilité des langages

Common Language SpecificationCommon Language Specification

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 77.NET Framework.NET Framework

Object

Unmanaged

Managed

InterfaceBuilt-in

Reference Type

Structural Equivalent

Boxed Value Type

Boxed Enum

Array

Built-in Value Type

StringInteger Type

Floating Point Type

Typed Reference

User Defined

Enum

Value Type

Name Equivalent

Delegate

Self-Describing

Function

Pointer

Reference Type

Type

Page 8: NET Framework, C# et .NET Remoting

FonctionnementFonctionnement

Plateforme .NET, C# et .NET RemotingPlateforme .NET, C# et .NET Remoting 88Plateforme .NETPlateforme .NET

Code source

Code natif

Compilateur

Compilateur JIT

Compilation

Exécution

Code MSILMeta données

A l’installationou

A la première exécution

Page 9: NET Framework, C# et .NET Remoting

Common Language InfrastructureCommon Language Infrastructure

Basé sur le CLR et la CLSBasé sur le CLR et la CLS

Défini comme un standardDéfini comme un standard ECMA-334, C# (C sharp) Language Specification.ECMA-334, C# (C sharp) Language Specification. ECMA-335, Common Language Infrastructure, ECMA-335, Common Language Infrastructure,

approved by the ECMA General Assembly of 13th approved by the ECMA General Assembly of 13th December 2001. December 2001. 

ECMA TR/84, related to Standard ECMA-335ECMA TR/84, related to Standard ECMA-335

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 99.NET Framework.NET Framework

Page 10: NET Framework, C# et .NET Remoting

Multi-langagesMulti-langages

MicrosoftMicrosoft Visual BasicVisual Basic C#C# J#J# Managed C++Managed C++ JScriptJScript

AutresAutres AdaAda PascalPascal

SchemeScheme PerlPerl FortranFortran

MercuryMercury PythonPython SmallTalkSmallTalk OzOz CobolCobol CamlCaml

OberonOberon EiffelEiffel Haskell Haskell ……

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 1010.NET Framework.NET Framework

Page 11: NET Framework, C# et .NET Remoting

Multi-plateformesMulti-plateformes

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 1111.NET Framework.NET Framework

Microsoft .NETMicrosoft .NET MonoMono RotorRotor

Windows 98 / NT4Windows 98 / NT4

Windows 2000 / XP / 2003Windows 2000 / XP / 2003

FreeBSDFreeBSD

Red HatRed Hat

Fedora CoreFedora Core

Suse LinuxSuse Linux

Mac OS XMac OS X

Et d’autres projets en cours comme DotGNU Portable.NET

Page 12: NET Framework, C# et .NET Remoting

SommaireSommaire .NET Framework.NET Framework

IntroductionIntroduction Architecture et fonctionnementArchitecture et fonctionnement Standardisation et interopérabilitéStandardisation et interopérabilité

C#C# Concepts de baseConcepts de base Types et variablesTypes et variables ClassesClasses Fonctionnalités avancéesFonctionnalités avancées

.NET Remoting.NET Remoting PrincipePrincipe ConfigurationConfiguration

DemosDemos

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 1212

Page 13: NET Framework, C# et .NET Remoting

PrésentationPrésentation

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 1313C#C#

Orienté objet, jusqu’au bout, tout est objetOrienté objet, jusqu’au bout, tout est objet

Similaire au C++ et au JavaSimilaire au C++ et au Java

Premier langage orienté composant parmi la Premier langage orienté composant parmi la famille C / C++famille C / C++

Dédié à la plateforme .NETDédié à la plateforme .NET Conforme aux spécifications (CLS-compliant)Conforme aux spécifications (CLS-compliant) Permet d’exploiter l’ensemble des fonctionnalitésPermet d’exploiter l’ensemble des fonctionnalités

Page 14: NET Framework, C# et .NET Remoting

OpérateursOpérateurs

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 1414C#C#

Unaires :Unaires : + - ! ~ ++x --x (T)x+ - ! ~ ++x --x (T)x

Arithmétiques :Arithmétiques : * / % + -* / % + -

Décalage :Décalage : << >><< >>

Relationnels :Relationnels : < > <= >= == !=< > <= >= == !=

Logiques :Logiques : & ^ |& ^ |

Conditionnels :Conditionnels : && || ?:&& || ?:

Assignation :Assignation : = *= /= %= += -== *= /= %= += -= <<= >>= &= ^= |=<<= >>= &= ^= |=

Condition ? Expression 1 : Expression 2

Page 15: NET Framework, C# et .NET Remoting

InstructionsInstructions

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 1515C#C#

BlocsBlocs{ ... }{ ... } ;;

LibellésLibellésx: instruction;x: instruction;

SelectionsSelectionsif(x == 1)if(x == 1) switch(i)switch(i)

{{ {{

if(y == 2)if(y == 2) case 0:case 0:

{{ case 1:case 1:

F();F(); Choix();Choix();

}} break;break;

elseelse

{{ default:default:

G();G(); ChoixAutre();ChoixAutre();

}} break;break;

}} }}

Page 16: NET Framework, C# et .NET Remoting

InstructionsInstructions

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 1616C#C#

ItérationsItérationswhile(x != 0) { ... }while(x != 0) { ... } for(int i = 0; i < n; i++) { ... }for(int i = 0; i < n; i++) { ... }

do { ... } while(x == 0);do { ... } while(x == 0); foreach(object o in collection) foreach(object o in collection) { ... }{ ... }

SautsSautsbreak;break; continue;continue;

goto libelle;goto libelle; return value;return value;

Gestion des exceptionsGestion des exceptionstrytry throw new Exception();throw new Exception();

{ ... }{ ... }

catch(ArgumentException e)catch(ArgumentException e)

{ ... }{ ... }

catch(Exception e)catch(Exception e)

{ ... }{ ... }

finallyfinally

{ ... }{ ... }

Page 17: NET Framework, C# et .NET Remoting

TypesTypes

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 1717C#C#

ValeursValeurs Types prédéfinisTypes prédéfinis EnumérationsEnumérations StructuresStructures

Allocation dans la pile (stack)Allocation dans la pile (stack) Ne peut être nullNe peut être null

RéférencesRéférences TableauxTableaux DéléguésDélégués ClassesClasses InterfacesInterfaces

Allocation dans le tas (heap)Allocation dans le tas (heap) Peut être nullPeut être null

Page 18: NET Framework, C# et .NET Remoting

Types prédéfinisTypes prédéfinis

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 1818C#C#

TypeType DescriptionDescription ExempleExemple

objectobject Type de base de tous les autres typesType de base de tous les autres types object o = null;object o = null;

stringstring Séquence de caractères UnicodeSéquence de caractères Unicode string s = "Hello";string s = "Hello";

sbytesbyte Entier signé de 8 bitsEntier signé de 8 bits sbyte val = 12;sbyte val = 12;

shortshort Entier signé de 16 bitsEntier signé de 16 bits short val = 12;short val = 12;

intint Entier signé de 32 bitsEntier signé de 32 bits int val = 12;int val = 12;

longlong Entier signé de 64 bitsEntier signé de 64 bits long val1 = 12;long val1 = 12;

long val2 = 34L;long val2 = 34L;

bytebyte Entier non signé de 8 bitsEntier non signé de 8 bits byte val = 12;byte val = 12;

ushortushort Entier non signé de 16 bitsEntier non signé de 16 bits ushort val = 12;ushort val = 12;

uintuint Entier non signé de 32 bitsEntier non signé de 32 bits uint val1 = 12;uint val1 = 12;

uint val2 = 34U;uint val2 = 34U;

ulongulong Entier non signé de 64 bitsEntier non signé de 64 bits ulong val1 = 12;ulong val1 = 12;

ulong val2 = 34U;ulong val2 = 34U;

ulong val3 = 56L;ulong val3 = 56L;

ulong val4 = 78UL;ulong val4 = 78UL;

floatfloat Flottant simple précision (32 bits, 1.7E +/- 308 15 chiffres significatifs)Flottant simple précision (32 bits, 1.7E +/- 308 15 chiffres significatifs) float val = 1.23F;float val = 1.23F;

doubledouble Flottant double précision (64 bits, 3.4E +/- 38, 7 chiffres significatifs)Flottant double précision (64 bits, 3.4E +/- 38, 7 chiffres significatifs) double val1 = 1.23;double val1 = 1.23;

double val2 = 4.56D;double val2 = 4.56D;

boolbool BooléenBooléen bool val1 = true;bool val1 = true;

bool val2 = false;bool val2 = false;

charchar Caractère UnicodeCaractère Unicode char val = 'h';char val = 'h';

decimaldecimal Décimal (28 chiffres significatifs)Décimal (28 chiffres significatifs) decimal val = 1.23M;decimal val = 1.23M;

Page 19: NET Framework, C# et .NET Remoting

EnumerationsEnumerations

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 1919C#C#

enum Color : longenum Color : long Color color;Color color;

{{ switch(color)switch(color)

Red,Red, {{

Green,Green, case Color.Red:case Color.Red:

BlueBlue ......

}} break;break;

case Color.Blue:case Color.Blue:

......

break;break;

case Color.Green:case Color.Green:

......

break;break;

default:default:

break;break;

}}

Page 20: NET Framework, C# et .NET Remoting

StructuresStructures

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 2020C#C#

struct Pointstruct Point

{{

public int x,y;public int x,y;

}}

struct Pointstruct Point

{{

public int x,y;public int x,y;

public Point(int x, int y) { this.x = x; this.y = y; }public Point(int x, int y) { this.x = x; this.y = y; }

}}

Page 21: NET Framework, C# et .NET Remoting

TableauxTableaux

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 2121C#C#

Une dimensionUne dimensionint[] myArray = new int[] {1, 3, 5, 7, 9};int[] myArray = new int[] {1, 3, 5, 7, 9};

string[] weekDays = string[] weekDays = {"Sun","Sat","Mon","Tue","Wed","Thu","Fri"};{"Sun","Sat","Mon","Tue","Wed","Thu","Fri"};

Plusieurs dimensionsPlusieurs dimensionsint[,,] myArray = new int [4,2,3];int[,,] myArray = new int [4,2,3];

int[,] myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};int[,] myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};

Jagged (tableau de tableaux)Jagged (tableau de tableaux)int[][,] myJaggedArray = new int [3][,] int[][,] myJaggedArray = new int [3][,]

{{

new int[,] { {1,3}, {5,7} },new int[,] { {1,3}, {5,7} },

new int[,] { {0,2}, {4,6}, {8,10} },new int[,] { {0,2}, {4,6}, {8,10} },

new int[,] { {11,22}, {99,88}, {0,9} } new int[,] { {11,22}, {99,88}, {0,9} }

};};

Page 22: NET Framework, C# et .NET Remoting

ClassesClasses

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 2222C#C#

NomNom

Attribut d’accessibilitéAttribut d’accessibilité publicpublic non limiténon limité protectedprotected limité à la classe et aux classes limité à la classe et aux classes

dérivéesdérivées privateprivate limité à la classelimité à la classe internalinternal limité à l’assemblagelimité à l’assemblage protected internalprotected internal limité à l’assemblage et aux limité à l’assemblage et aux

classes dérivéesclasses dérivées

Attribut Attribut abstractabstract (abstrait) (abstrait) Attribut Attribut sealedsealed (sellé) (sellé)

Classe de base (héritage simple de classe)Classe de base (héritage simple de classe) Interfaces implémentées (héritage multiple d’interfaces)Interfaces implémentées (héritage multiple d’interfaces)

MembresMembres

Page 23: NET Framework, C# et .NET Remoting

MembresMembres

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 2323C#C#

ConstantesConstantes ChampsChamps MéthodesMéthodes ConstructeursConstructeurs DestructeursDestructeurs TypesTypes PropriétésPropriétés IndexeursIndexeurs OpérateursOpérateurs ÉvénementsÉvénements

Page 24: NET Framework, C# et .NET Remoting

ConstantesConstantes

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 2424C#C#

class A{ public const double X = 1.0; public const double Y = 2.0; public const double Z = 3.0;}

class B{ public const int X = C.Z + 1; public const int Y = 10;}

class C{ public const int Z = B.Y + 1;}

Page 25: NET Framework, C# et .NET Remoting

ChampsChamps

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 2525C#C#

public class Colorpublic class Color{{

public static readonly Color Black = new Color(0, 0, 0);public static readonly Color Black = new Color(0, 0, 0);public static readonly Color White = new Color(255, 255, 255);public static readonly Color White = new Color(255, 255, 255);private byte red, green, blue;private byte red, green, blue;public Color(byte r, byte g, byte b) {public Color(byte r, byte g, byte b) {

red = r;red = r;green = g;green = g;blue = b;blue = b;

}}}}

Attributs d’accessibilitéAttributs d’accessibilité publicpublic non limiténon limité protectedprotected limité à la classe et aux classes dérivéeslimité à la classe et aux classes dérivées privateprivate limité à la classelimité à la classe internalinternal limité à l’assemblagelimité à l’assemblage

AttributsAttributs newnew champ cachant (classe dérivé)champ cachant (classe dérivé) staticstatic champ de classechamp de classe readonlyreadonly champ en lecture seule (initialisé par le constructeur)champ en lecture seule (initialisé par le constructeur) volatilevolatile champ volatilechamp volatile

Page 26: NET Framework, C# et .NET Remoting

MéthodesMéthodes

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 2626C#C#

NomNom

Attribut d’accessibilitéAttribut d’accessibilité publicpublic non limiténon limité protectedprotected limité à la classe et aux classes limité à la classe et aux classes

dérivéesdérivées privateprivate limité à la classelimité à la classe internalinternal limité à l’assemblagelimité à l’assemblage

Attributs Attributs newnew, , staticstatic, , virtual virtual (virtuel), (virtuel), abstractabstract, , sealedsealed, , override override (surcharge), (surcharge), externextern

Type de retourType de retour ParamètresParamètres

Page 27: NET Framework, C# et .NET Remoting

Méthodes abstraitesMéthodes abstraites

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 2727C#C#

public abstract class Shapepublic abstract class Shape{{ public abstract void Paint(Graphics g, Rectangle r);public abstract void Paint(Graphics g, Rectangle r);}}

public class Ellipse: Shapepublic class Ellipse: Shape{{ public override void Paint(Graphics g, Rectangle r) {public override void Paint(Graphics g, Rectangle r) { g.DrawEllipse(r);g.DrawEllipse(r); }}}}

public class Box: Shapepublic class Box: Shape{{ public override void Paint(Graphics g, Rectangle r) {public override void Paint(Graphics g, Rectangle r) { g.DrawRect(r);g.DrawRect(r); }}}}

Page 28: NET Framework, C# et .NET Remoting

Méthodes virtuellesMéthodes virtuelles

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 2828C#C#

class Aclass A{{ public virtual void F() { Console.WriteLine("A.F"); }public virtual void F() { Console.WriteLine("A.F"); }}}class B: Aclass B: A{{ public override void F() { Console.WriteLine("B.F"); }public override void F() { Console.WriteLine("B.F"); }}}class C: Bclass C: B{{ new public virtual void F() { Console.WriteLine("C.F"); }new public virtual void F() { Console.WriteLine("C.F"); }}}class D: Cclass D: C{{ public override void F() { Console.WriteLine("D.F"); }public override void F() { Console.WriteLine("D.F"); }}}

class Testclass Test{{ static void Main() {static void Main() { D d = new D();D d = new D(); A a = d;A a = d; B b = d;B b = d; C c = d;C c = d; a.F();a.F(); b.F();b.F(); c.F();c.F(); d.F();d.F(); }}}}

B.FB.FD.FD.F

Page 29: NET Framework, C# et .NET Remoting

Constructeurs (instance)Constructeurs (instance)

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 2929C#C#

class Point{ public double x, y; public Point() { this.x = 0; this.y = 0; } public Point(double x, double y) { this.x = x; this.y = y; }}

Initialiser l’instance d’une classeInitialiser l’instance d’une classe En cas d’absence de constructeur, un constructeur sans En cas d’absence de constructeur, un constructeur sans

paramètre est implicitement crééparamètre est implicitement créé

Page 30: NET Framework, C# et .NET Remoting

Constructeur (classe)Constructeur (classe)

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 3030C#C#

class A{ public static int X; static A() { X = B.Y + 1; }}

class B{ public static int Y = A.X + 1; static B() {} static void Main() { Console.WriteLine("X = {0}, Y = {1}", A.X, B.Y); }}

Initialiser une classeInitialiser une classe Ne peut être appelé explicitementNe peut être appelé explicitement Appelé automatiquementAppelé automatiquement Pas d’attribut d’accessibilité, pas de paramètrePas d’attribut d’accessibilité, pas de paramètre

Page 31: NET Framework, C# et .NET Remoting

DestructeurDestructeur

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 3131C#C#

class A{ public static int X; static A() { X = B.Y + 1; }}

class B{ public static int Y = A.X + 1; static B() {} static void Main() { Console.WriteLine("X = {0}, Y = {1}", A.X, B.Y); }}

Appelé automatiquement lors du processus de garbage Appelé automatiquement lors du processus de garbage collectioncollection

Ne peut être appelé explicitementNe peut être appelé explicitement Pas d’attribut d’accessibilité, pas de paramètrePas d’attribut d’accessibilité, pas de paramètre

Page 32: NET Framework, C# et .NET Remoting

TypesTypes

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 3232C#C#

public class List{ // Private data structure private class Node { public object Data; public Node Next; public Node(object data, Node next) { this.Data = data; this.Next = next; } } private Node first = null; private Node last = null; // Public interface public void AddToFront(object o) {...} public void AddToBack(object o) {...} public object RemoveFromFront() {...} public object RemoveFromBack() {...} public int Count { get {...} }}

Déclaration d’un type à l’intérieur d’une classeDéclaration d’un type à l’intérieur d’une classe

Page 33: NET Framework, C# et .NET Remoting

PropriétésPropriétés

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 3333C#C#

Accéder aux caractéristiques d’un objet ou d’une classeAccéder aux caractéristiques d’un objet ou d’une classe longueur d’une chaîne de caractèreslongueur d’une chaîne de caractères taille d’un tableautaille d’un tableau titre d’une fenêtretitre d’une fenêtre dimensions d’une imagedimensions d’une image ……

Deux comportementsDeux comportements Lecture (get)Lecture (get) Écriture (set)Écriture (set)

Mêmes attributs que les méthodesMêmes attributs que les méthodes

Page 34: NET Framework, C# et .NET Remoting

PropriétésPropriétés

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 3434C#C#

abstract class A{ int y; public virtual int X { get { return 0; } } public virtual int Y { get { return y; } set { y = value; } } public abstract int Z { get; set; }}

class B: A{ int z; public override int X { get { return base.X + 1; } } public override int Y { set { base.Y = value < 0? 0: value; } } public override int Z { get { return z; } set { z = value; } }}

Page 35: NET Framework, C# et .NET Remoting

IndexeursIndexeurs

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 3535C#C#

Indexer une classe à la manière d’un tableauIndexer une classe à la manière d’un tableau

public class Stack{ private Node GetNode(int index) { Node temp = first; while (index > 0 && temp != null) { temp = temp.Next; index--; } if (index < 0 || temp == null) throw new Exception("Index out of range."); return temp; } public object this[int index] { get { return GetNode(index).Value; } set { GetNode(index).Value = value; } }}

Page 36: NET Framework, C# et .NET Remoting

OpérateursOpérateurs

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 3636C#C#

public struct Digit{ byte value; public Digit(byte value) { if (value < 0 || value > 9) throw new ArgumentException(); this.value = value; } public Digit(int value): this((byte) value) {}

public static implicit operator byte(Digit d) { return d.value; }

public static explicit operator Digit(byte b) { return new Digit(b); }}

Page 37: NET Framework, C# et .NET Remoting

OpérateursOpérateurs

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 3737C#C#

public struct Digit{ byte value; public Digit(byte value) { if (value < 0 || value > 9) throw new ArgumentException(); this.value = value; } public Digit(int value): this((byte) value) {}

public static Digit operator+(Digit a, Digit b) { return new Digit(a.value + b.value); }

public static Digit operator-(Digit a, Digit b) { return new Digit(a.value - b.value); }}

Page 38: NET Framework, C# et .NET Remoting

OpérateursOpérateurs

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 3838C#C#

public struct Digit{ byte value; public Digit(byte value) { if (value < 0 || value > 9) throw new ArgumentException(); this.value = value; } public Digit(int value): this((byte) value) {}

public static bool operator==(Digit a, Digit b) { return a.value == b.value; }

public static bool operator!=(Digit a, Digit b) { return a.value != b.value; }

public override bool Equals(object value) { if (value == null) return false; if (GetType() == value.GetType()) return this == (Digit)value; return false; }}

Page 39: NET Framework, C# et .NET Remoting

DéléguésDélégués

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 3939C#C#

Pointeurs de méthodes (vulgarisation)Pointeurs de méthodes (vulgarisation) Encapsule à la fois un objet et une méthodeEncapsule à la fois un objet et une méthode Peut « pointer » vers plusieurs méthodesPeut « pointer » vers plusieurs méthodes

delegate void D(int x);class C{ public static void M1(int i) {...} public static void M2(int i) {...}}class Test{ static void Main() { D cd1 = new D(C.M1); // M1 D cd2 = new D(C.M2); // M2 D cd3 = cd1 + cd2; // M1 + M2 D cd4 = cd3 + cd1; // M1 + M2 + M1 D cd5 = cd4 + cd3; // M1 + M2 + M1 + M1 + M2 }}

Page 40: NET Framework, C# et .NET Remoting

ÉvénementsÉvénements

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 4040C#C#

Mécanisme de notificationMécanisme de notification Basé sur les déléguésBasé sur les délégués

Générateur d’événements

Événement

Consommateur d’événements

Traitantd’événements

Consommateur d’événements

Traitantd’événements

registration

callback

Page 41: NET Framework, C# et .NET Remoting

ÉvénementsÉvénements

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 4141C#C#

public delegate void EventHandler(object sender, EventArgs e);

public class Button: Control{ public event EventHandler Click; protected void OnClick(EventArgs e) { if (Click != null) Click(this, e); } }

public class Form{ Button Button1 = new Button();

public Form() { Button1.Click += new EventHandler(Button1_Click); } ~Form() { Button1.Click -= new EventHandler(Button1_Click); }

void Button1_Click(object sender, EventArgs e) { Console.WriteLine("Button1 was clicked!"); }}

Page 42: NET Framework, C# et .NET Remoting

Espaces de nomsEspaces de noms

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 4242C#C#

Conteneur de classes ou d’espaces de nomConteneur de classes ou d’espaces de nom Organiser des classes hiérarchiquementOrganiser des classes hiérarchiquement

Structurer les assemblagesStructurer les assemblagesclass A {} // Anamespace X // X{ class B // X.B { class C {} // X.B.C } namespace Y // X.Y { class D {} // X.Y.D }}namespace X.Y // X.Y{ class E {} // X.Y.E}

Page 43: NET Framework, C# et .NET Remoting

InterfacesInterfaces

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 4343C#C#

NomNom

Attribut d’accessibilitéAttribut d’accessibilité publicpublic non limiténon limité protectedprotected limité à la classe et aux classes limité à la classe et aux classes

dérivéesdérivées privateprivate limité à la classelimité à la classe internalinternal limité à l’assemblagelimité à l’assemblage

Interfaces de base (héritage multiple d’interfaces)Interfaces de base (héritage multiple d’interfaces)

MembresMembres MéthodesMéthodes PropriétésPropriétés IndexeursIndexeurs ÉvénementsÉvénements

Page 44: NET Framework, C# et .NET Remoting

Fonctionnalités avancéesFonctionnalités avancées

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 4444C#C#

Section critique, exclusion mutuelleSection critique, exclusion mutuelle

class Account {class Account {

int balance;int balance;

public Account(int initial) {public Account(int initial) {

balance = initial;balance = initial;

}}

int Withdraw(int amount) {int Withdraw(int amount) {

if (balance < 0) throw new Exception("Negative Balance");if (balance < 0) throw new Exception("Negative Balance");

lock (this) {lock (this) {

if (balance >= amount) {if (balance >= amount) {

balance = balance - amount;balance = balance - amount;

return amount;return amount;

}}

else {else {

return 0;return 0;

}}

}}

}}

}}

Page 45: NET Framework, C# et .NET Remoting

Fonctionnalités avancéesFonctionnalités avancées

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 4545C#C#

Contrôle de débordement lors d’opérations Contrôle de débordement lors d’opérations arithmétiques sur les entiersarithmétiques sur les entiers

class OverFlowTest {class OverFlowTest {

static short x = 32767, y = 32767;static short x = 32767, y = 32767;

public static int myMethodCheck() {public static int myMethodCheck() {

int z = 0;int z = 0;

try {try {

z = checked((short)(x + y));z = checked((short)(x + y));

}}

catch (System.OverflowException e) {catch (System.OverflowException e) {

System.Console.WriteLine(e.ToString());System.Console.WriteLine(e.ToString());

}}

return z;return z;

}}

public static int myMethodUncheck() {public static int myMethodUncheck() {

int z = unchecked((short)(x + y));int z = unchecked((short)(x + y));

return z;return z;

}}

}}

Page 46: NET Framework, C# et .NET Remoting

unboxing :unboxing : type référence type référence type valeur type valeur boxing :boxing : type valeur type valeur type référence type référence

Fonctionnalités avancéesFonctionnalités avancées

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 4646C#C#

Boxing / UnboxingBoxing / Unboxing Mécanisme de conversion entre un type valeur et Mécanisme de conversion entre un type valeur et

un type référenceun type référence

123

i

int i = 123;

Sur la pile Sur le tas

123

o

object o = i;

int

(i boxed)

123

int i = 123;object o = i;

123

i

int i = 123;

Sur la pile Sur le tas

123

o

object o = i;

int

(i boxed)

123

int i = 123;object o = i;int j = (int)o;

123

j

int j = (box)o;

Page 47: NET Framework, C# et .NET Remoting

Fonctionnalités avancéesFonctionnalités avancées

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 4747C#C#

Code unsafeCode unsafe Manipulation de bas niveau (pointeurs)Manipulation de bas niveau (pointeurs) Autorise les conversions de typesAutorise les conversions de types Autorise les opérations arithmétiques sur les pointeursAutorise les opérations arithmétiques sur les pointeurs Semblable à du code C inlineSemblable à du code C inline Allocation sur la pile (Allocation sur la pile (stackallocstackalloc))

class Test {class Test { unsafe void Method() {unsafe void Method() { char* buf = stackalloc char[256];char* buf = stackalloc char[256]; for(char* p = buf; p < buf + 256; p++) *p = 0;for(char* p = buf; p < buf + 256; p++) *p = 0; ...... }}}}

Page 48: NET Framework, C# et .NET Remoting

Fonctionnalités avancéesFonctionnalités avancées

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 4848C#C#

Code unsafeCode unsafe Fixer l’adresse mémoire d’une variable à l’exécution (Fixer l’adresse mémoire d’une variable à l’exécution (fixedfixed))

class Test {class Test { static int x;static int x; int y;int y; unsafe static void F(int* p) {unsafe static void F(int* p) { *p = 1;*p = 1; }}

static void Main() {static void Main() { Test t = new Test();Test t = new Test(); int[] a = new int[10];int[] a = new int[10]; unsafe {unsafe { fixed (int* p = &x) F(p);fixed (int* p = &x) F(p); fixed (int* p = &t.y) F(p);fixed (int* p = &t.y) F(p); fixed (int* p = &a[0]) F(p);fixed (int* p = &a[0]) F(p); fixed (int* p = a) F(p);fixed (int* p = a) F(p); }} }}}}

Page 49: NET Framework, C# et .NET Remoting

SommaireSommaire .NET Framework.NET Framework

IntroductionIntroduction Architecture et fonctionnementArchitecture et fonctionnement Standardisation et interopérabilitéStandardisation et interopérabilité

C#C# Concepts de baseConcepts de base Types et variablesTypes et variables ClassesClasses Fonctionnalités avancéesFonctionnalités avancées

.NET Remoting.NET Remoting PrincipePrincipe ConfigurationConfiguration

DemosDemos

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 4949

Page 50: NET Framework, C# et .NET Remoting

PrincipePrincipe

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 5050.NET Remoting.NET Remoting

Invoquer des méthodes sur objets distantsInvoquer des méthodes sur objets distants Deux rôlesDeux rôles

ClientClient ServeurServeur

Canal de communication (http, tcp)Canal de communication (http, tcp)

Objet serveur

Système distant

Objet client

Système distant

Proxy

Canal

Page 51: NET Framework, C# et .NET Remoting

PrincipePrincipe

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 5151.NET Remoting.NET Remoting

FormattageFormattage BinaireBinaire SOAPSOAP ……

Objet serveur

Système distant

Objet client

Système distant

Proxy

Canal

Formatteur FormatteurFormatteur Formatteur

Objet serveur

Système distant

Objet client

Système distant

Proxy

Canal

Formatteur Formatteur

Page 52: NET Framework, C# et .NET Remoting

PrincipePrincipe

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 5252.NET Remoting.NET Remoting

Deux types d’objets distantsDeux types d’objets distants MarshallByValueMarshallByValue

SérialisationSérialisation Copie vers le clientCopie vers le client

MarshallByReferenceMarshallByReference Utilisation de proxyUtilisation de proxy Stocké sur le serveurStocké sur le serveur

Page 53: NET Framework, C# et .NET Remoting

ConfigurationConfiguration

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 5353.NET Remoting.NET Remoting

Deux modes de configurationDeux modes de configuration Par fichier de configurationPar fichier de configuration Par programmationPar programmation

Page 54: NET Framework, C# et .NET Remoting

DemosDemos Hello WorldHello World Simple RemotingSimple Remoting Javanaise .NETJavanaise .NET Quake II .NETQuake II .NET

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 5454DemosDemos

FreeBSD 5.2.1

Red Hat Linux 9.1

Windows XP

Page 55: NET Framework, C# et .NET Remoting

Hello WorldHello World

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 5555DemosDemos

using System;using System;

namespace Hellonamespace Hello

{{

public class Hellopublic class Hello

{{

public static void Main(string[] args)public static void Main(string[] args)

{{

Console.WriteLine("Hello World !");Console.WriteLine("Hello World !");

Console.WriteLine();Console.WriteLine();

foreach(string s in args)foreach(string s in args)

{{

Console.Write(s);Console.Write(s);

}}

}}

}}

}}

Page 56: NET Framework, C# et .NET Remoting

Hello WorldHello World

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 5656DemosDemos

Compilation en ligne de commandeCompilation en ligne de commandecsc /noconfig Hello.cscsc /noconfig Hello.cs

Exécution sur plusieurs plateformesExécution sur plusieurs plateformes Windows XPWindows XP

.NET Framework 1.1.NET Framework 1.1 10.0.7.5010.0.7.50

FreeBSD 5.2.1FreeBSD 5.2.1 RotorRotor 10.0.7.25110.0.7.251

Red Hat Linux 9.1Red Hat Linux 9.1 Mono 1.0.4Mono 1.0.4 10.0.7.25010.0.7.250

Page 57: NET Framework, C# et .NET Remoting

Simple RemotingSimple Remoting

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 5757DemosDemos

Objet distribué (écrit en Visual Basic)Objet distribué (écrit en Visual Basic)'RemotableType.vb'RemotableType.vb

Imports SystemImports System

Public Class RemotableTypePublic Class RemotableType

Inherits MarshalByRefObjectInherits MarshalByRefObject

Private _internalString As String = "This is the RemotableType."Private _internalString As String = "This is the RemotableType."

Public Function StringMethod(param As String) As StringPublic Function StringMethod(param As String) As String

Console.WriteLine("Call from " + param)Console.WriteLine("Call from " + param)

Return _internalStringReturn _internalString

End Function 'StringMethodEnd Function 'StringMethod

End Class 'RemotableTypeEnd Class 'RemotableType

CompilationCompilationvbc /t:library RemotableType.vbvbc /t:library RemotableType.vb

Page 58: NET Framework, C# et .NET Remoting

Simple RemotingSimple Remoting

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 5858DemosDemos

Serveur (écrit en C#)Serveur (écrit en C#)// Host.cs// Host.cs

using System;using System;

using System.Runtime.Remoting;using System.Runtime.Remoting;

namespace Remoting {namespace Remoting {

public class Host {public class Host {

public static void Main() {public static void Main() {

RemotingConfiguration.Configure("Host.exe.config");RemotingConfiguration.Configure("Host.exe.config");

Console.WriteLine("Listening for requests. Press Enter Console.WriteLine("Listening for requests. Press Enter to exit...");to exit...");

Console.ReadLine();Console.ReadLine();

}}

}}

}}

CompilationCompilationcsc /noconfig /r:RemotableType.dll Host.cscsc /noconfig /r:RemotableType.dll Host.cs

Page 59: NET Framework, C# et .NET Remoting

Simple RemotingSimple Remoting

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 5959DemosDemos

Configuration du serveurConfiguration du serveur

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

<configuration><configuration>

<system.runtime.remoting><system.runtime.remoting>

<application><application>

<service><service>

<wellknown<wellknown

mode="Singleton" mode="Singleton"

type="RemotableType, RemotableType" type="RemotableType, RemotableType"

objectUri="RemotableType.rem"objectUri="RemotableType.rem"

/>/>

</service></service>

<channels><channels>

<channel ref="tcp" port="6969"/><channel ref="tcp" port="6969"/>

</channels></channels>

</application></application>

</system.runtime.remoting></system.runtime.remoting>

</configuration></configuration>

Page 60: NET Framework, C# et .NET Remoting

Simple RemotingSimple Remoting

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 6060DemosDemos

Client (écrit en C#)Client (écrit en C#)// Client.cs // Client.cs

using System;using System;

using System.Runtime.Remoting;using System.Runtime.Remoting;

namespace Remoting {namespace Remoting {

public class Client {public class Client {

public static void Main(string[] args) {public static void Main(string[] args) {

string param;string param;

if(args.Length != 1) { param = "nowhere :-/"; }if(args.Length != 1) { param = "nowhere :-/"; }

else { param = args[0]; }else { param = args[0]; }

RemotingConfiguration.Configure("Client.exe.config");RemotingConfiguration.Configure("Client.exe.config");

RemotableType remoteObject = new RemotableType();RemotableType remoteObject = new RemotableType();

Console.WriteLine(remoteObject.StringMethod(param));Console.WriteLine(remoteObject.StringMethod(param));

}}

}}

}}

CompilationCompilationcsc /noconfig /r:RemotableType.dll Client.cscsc /noconfig /r:RemotableType.dll Client.cs

Page 61: NET Framework, C# et .NET Remoting

Simple RemotingSimple Remoting

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 6161DemosDemos

Configuration du clientConfiguration du client

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

<configuration><configuration>

<system.runtime.remoting><system.runtime.remoting>

<application><application>

<client><client>

<wellknown <wellknown

type="RemotableType, RemotableType"type="RemotableType, RemotableType"

url="tcp://10.0.7.50:6969/RemotableType.rem"url="tcp://10.0.7.50:6969/RemotableType.rem"

/>/>

</client></client>

</application></application>

</system.runtime.remoting></system.runtime.remoting>

</configuration></configuration>

Page 62: NET Framework, C# et .NET Remoting

Simple RemotingSimple Remoting

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 6262DemosDemos

ExécutionExécution Serveur sous Windows XPServeur sous Windows XP Client sous Windows XPClient sous Windows XP Client sous FreeBSD 5.2.1Client sous FreeBSD 5.2.1 Client sous Red Hat Linux 9.1Client sous Red Hat Linux 9.1

Page 63: NET Framework, C# et .NET Remoting

Javanaise .NETJavanaise .NET

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 6363DemosDemos

Portage du projet Javanaise Java Portage du projet Javanaise Java C# C# Exécution sous Windows XP (WinForms)Exécution sous Windows XP (WinForms)

Page 64: NET Framework, C# et .NET Remoting

Quake II .NETQuake II .NET

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 6464DemosDemos

Observation de performancesObservation de performances Version nativeVersion native

69.3 FPS69.3 FPS

Version managéeVersion managée 56.0 FPS56.0 FPS

Page 65: NET Framework, C# et .NET Remoting

RessourcesRessources

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 6565

http://msdn.microsoft.com/netframework/http://msdn.microsoft.com/net/ecma/

http://www.ecma-international.org/publications/standards/ecma-334.htmhttp://www.ecma-international.org/publications/standards/ecma-335.htm

http://msdn.microsoft.com/vcsharp/

http://msdn.microsoft.com/net/sscli/http://www.go-mono.com/

http://www.dotgnu.org/

http://www.vertigosoftware.com/quake2/

http://www.gotdotnet.com/http://www.dotnetguru.org/http://www.dotnet-fr.org/

Page 66: NET Framework, C# et .NET Remoting

DiscussionDiscussion

.NET Framework, C# et .NET Remoting.NET Framework, C# et .NET Remoting 6666

Questions ?


Top Related