NET Framework C et NET Remoting Sbastien Boulay
. NET Framework, C# et. NET Remoting Sébastien Boulay sebastien. boulay@the-gnou-community. net Master GI – option SRR 25 novembre 2004
Sommaire l . NET Framework l C# l Introduction Architecture et fonctionnement Standardisation et interopérabilité Concepts de base Types et variables Classes Fonctionnalités avancées . NET Remoting Principe Configuration Demos. NET Framework, C# et. NET Remoting 2
Introduction l l l Technologie proposée par Microsoft Plateforme de développement et d’exécution Orientée environnements distribués Objectifs Contexte d’exécution robuste et sécurisé Déploiement et administration simplifié Intégration de l’existant Développement d’applications simplifié . NET Framework, C# et. NET Remoting . NET Framework 3
Architecture Visual Basic C# J# Managed C++ JScript … CLS (Common Language Specification) ASP. NET Classes. NET Framework Windows Forms ADO. NET et XML CLR (Common Language Runtime) Système d’exploitation Windows Free BSD Plateforme. NET, C# et. NET Remoting Red Hat Plateforme. NET Debian … 4
Microsoft Intermediate Language l l l Format intermédiaire Indépendant de la machine Converti en langage machine par le CLR Code managé Assemblage (assembly) Manifest Meta données Code MSIL Ressources . NET Framework, C# et. NET Remoting . NET Framework 5
Common Language Runtime Base Class Library Support Thread Support COM Marshaler Type Checker Exception Manager Security Engine Debug Engine IL to Native Compilers Code Manager Garbage Collector Class Loader Plateforme. NET, C# et. NET Remoting Plateforme. NET 6
Common Language Specification CTS (Common Type Specification) l. Système de types unique l. Partagé par les compilateurs, outils et le CLR Type Value Type Built-in Value Type Reference Type User Defined Integer Type Self-Describing Enum Interface Built-in Reference Type Pointer Name Equivalent Function String Object Floating Point Type Delegate Managed Typed Reference Boxed Value Type Unmanaged Boxed Enum Ensemble de règles interopérabilité des langages Structural Equivalent Array . NET Framework, C# et. NET Remoting . NET Framework 7
Fonctionnement Code source Compilateur Code MSIL Meta données Compilation Code natif Compilateur JIT A l’installation ou A la première exécution Exécution Plateforme. NET, C# et. NET Remoting Plateforme. NET 8
Common Language Infrastructure l Basé sur le CLR et la CLS l Défini comme un standard ECMA-334, C# (C sharp) Language Specification. ECMA-335, Common Language Infrastructure, approved by the ECMA General Assembly of 13 th December 2001. ECMA TR/84, related to Standard ECMA-335 . NET Framework, C# et. NET Remoting . NET Framework 9
Multi-langages l Microsoft l Visual Basic C# J# Managed C++ JScript Autres Ada Perl Python Cobol Eiffel Pascal Scheme Fortran Mercury Small. Talk Oz Caml Oberon Haskell … . NET Framework, C# et. NET Remoting . NET Framework 10
Multi-plateformes Microsoft. NET Mono Rotor Windows 98 / NT 4 Windows 2000 / XP / 2003 Free. BSD Red Hat Fedora Core Suse Linux Mac OS X Et d’autres projets en cours comme Dot. GNU Portable. NET Framework, C# et. NET Remoting . NET Framework 11
Sommaire l . NET Framework l C# l Introduction Architecture et fonctionnement Standardisation et interopérabilité Concepts de base Types et variables Classes Fonctionnalités avancées . NET Remoting Principe Configuration Demos. NET Framework, C# et. NET Remoting 12
Présentation l Orienté objet, jusqu’au bout, tout est objet l Similaire au C++ et au Java l Premier langage orienté composant parmi la famille C / C++ l Dédié à la plateforme. NET Conforme aux spécifications (CLS-compliant) Permet d’exploiter l’ensemble des fonctionnalités . NET Framework, C# et. NET Remoting C# 13
Opérateurs l l l l Unaires : + ! ~ ++x --x (T)x Arithmétiques : * / % + Décalage : << >> Relationnels : < > <= >= == != Logiques : ? & Expression ^ | Condition 1 : Expression 2 Conditionnels : && || ? : Assignation : = *= /= %= += -= <<= >>= . NET Framework, C# et. NET Remoting &= ^= |= C# 14
Instructions l Blocs {. . . } l ; Libellés x: instruction; l Selections if(x == 1) switch(i) { { case 0: if(y == 2) { case 1: F(); Choix(); break; } else { default: G(); Choix. Autre(); break; } } . NET Framework, C# et. NET Remoting } C# 15
Instructions l l Itérations while(x != 0) {. . . } for(int i = 0; i < n; i++) {. . . } do {. . . } while(x == 0); foreach(object o in collection) {. . . } Sauts break; continue; goto libelle; l return value; Gestion des exceptions try throw new Exception(); {. . . } catch(Argument. Exception e) {. . . } catch(Exception e) {. . . } finally {. . . } . NET Framework, C# et. NET Remoting C# 16
Types l Valeurs § § § l Types prédéfinis Enumérations Structures Allocation dans la pile (stack) Ne peut être null Références § § Tableaux Délégués Classes Interfaces Allocation dans le tas (heap) Peut être null . NET Framework, C# et. NET Remoting C# 17
Types prédéfinis Type Description Exemple object Type de base de tous les autres types object o = null; string Séquence de caractères Unicode string s = "Hello"; sbyte Entier signé de 8 bits sbyte val = 12; short Entier signé de 16 bits short val = 12; int Entier signé de 32 bits int val = 12; long Entier signé de 64 bits long val 1 = 12; long val 2 = 34 L; byte Entier non signé de 8 bits byte val = 12; ushort Entier non signé de 16 bits ushort val = 12; uint Entier non signé de 32 bits uint val 1 = 12; uint val 2 = 34 U; ulong Entier non signé de 64 bits ulong float Flottant simple précision (32 bits, 1. 7 E +/- 308 15 chiffres significatifs) float val = 1. 23 F; double Flottant double précision (64 bits, 3. 4 E +/- 38, 7 chiffres significatifs) double val 1 = 1. 23; double val 2 = 4. 56 D; bool Booléen bool val 1 = true; bool val 2 = false; char Caractère Unicode char val = 'h'; decimal Décimal (28 chiffres significatifs) decimal val = 1. 23 M; . NET Framework, C# et. NET Remoting C# val 1 val 2 val 3 val 4 = = 12; 34 U; 56 L; 78 UL; 18
Enumerations enum Color : long Color color; { switch(color) Red, { Green, case Color. Red: Blue. . . } break; case Color. Blue: . . . break; case Color. Green: . . . break; default: break; } . NET Framework, C# et. NET Remoting C# 19
Structures struct Point { public int x, y; } struct Point { public int x, y; public Point(int x, int y) { this. x = x; this. y = y; } } . NET Framework, C# et. NET Remoting C# 20
Tableaux l Une dimension int[] my. Array = new int[] {1, 3, 5, 7, 9}; string[] week. Days = {"Sun", "Sat", "Mon", "Tue", "Wed", "Thu", "Fri"}; l Plusieurs dimensions int[, , ] my. Array = new int[, ] my. Array = new l int [4, 2, 3]; int[, ] {{1, 2}, {3, 4}, {5, 6}, {7, 8}}; Jagged (tableau de tableaux) int[][, ] my. Jagged. Array = new int [3][, ] { new int[, ] { {1, 3}, {5, 7} }, new int[, ] { {0, 2}, {4, 6}, {8, 10} }, new int[, ] { {11, 22}, {99, 88}, {0, 9} } }; . NET Framework, C# et. NET Remoting C# 21
Classes l Nom l Attribut d’accessibilité § § § l l public non limité protected limité à la classe et aux classes dérivées private limité à la classe internal limité à l’assemblage protected internal limité à l’assemblage et aux classes dérivées Attribut abstract (abstrait) Attribut sealed (sellé) l Classe de base (héritage simple de classe) Interfaces implémentées (héritage multiple d’interfaces) l Membres l . NET Framework, C# et. NET Remoting C# 22
Membres l l l l l Constantes Champs Méthodes Constructeurs Destructeurs Types Propriétés Indexeurs Opérateurs Événements . NET Framework, C# et. NET Remoting C# 23
Constantes 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; }. NET Framework, C# et. NET Remoting C# 24
Champs public class Color { public static readonly Color Black = public static readonly Color White = private byte red, green, blue; public Color(byte r, byte g, byte b) red = r; green = g; blue = b; } } § { Attributs d’accessibilité § § § new Color(0, 0, 0); new Color(255, 255); public non limité protected limité à la classe et aux classes dérivées private limité à la classe internal limité à l’assemblage Attributs § § new champ cachant (classe dérivé) static champ de classe readonly champ en lecture seule (initialisé par le constructeur) volatile champ volatile . NET Framework, C# et. NET Remoting C# 25
Méthodes l Nom l Attribut d’accessibilité § § public protected private internal non limité à la classe et aux classes dérivées limité à la classe limité à l’assemblage l Attributs new, static, virtual (virtuel), abstract, sealed, override (surcharge), extern l Type de retour Paramètres l . NET Framework, C# et. NET Remoting C# 26
Méthodes abstraites public abstract class Shape { public abstract void Paint(Graphics g, Rectangle r); } public class Ellipse: Shape { public override void Paint(Graphics g, Rectangle r) { g. Draw. Ellipse(r); } } public class Box: Shape { public override void Paint(Graphics g, Rectangle r) { g. Draw. Rect(r); } } . NET Framework, C# et. NET Remoting C# 27
class Test { static void Main() { D d = new D(); A a = d; B b = d; C c = d; a. F(); class A b. F(); { c. F(); public virtual void F() { Console. Write. Line("A. F "); d. F (); } } } class B: A } { public override void F() { Console. Write. Line("B. F"); } B. F } class C: B B. F { D. F new public virtual void F() { Console. Write. Line("C. F"); } D. F } class D: C { public override void F() { Console. Write. Line("D. F"); } } Méthodes virtuelles . NET Framework, C# et. NET Remoting C# 28
Constructeurs (instance) l l Initialiser l’instance d’une classe En cas d’absence de constructeur, un constructeur sans paramètre est implicitement créé 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; } } . NET Framework, C# et. NET Remoting C# 29
Constructeur (classe) l l Initialiser une classe Ne peut être appelé explicitement Appelé automatiquement Pas d’attribut d’accessibilité, pas de paramètre 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. Write. Line("X = {0}, Y = {1}", A. X, B. Y); } } . NET Framework, C# et. NET Remoting C# 30
Destructeur l l l Appelé automatiquement lors du processus de garbage collection Ne peut être appelé explicitement Pas d’attribut d’accessibilité, pas de paramètre 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. Write. Line("X = {0}, Y = {1}", A. X, B. Y); } } . NET Framework, C# et. NET Remoting C# 31
Types l Déclaration d’un type à l’intérieur d’une classe 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 Add. To. Front(object o) {. . . } public void Add. To. Back(object o) {. . . } public object Remove. From. Front() {. . . } public object Remove. From. Back() {. . . } public int Count { get {. . . } } } . NET Framework, C# et. NET Remoting C# 32
Propriétés l Accéder aux caractéristiques d’un objet ou d’une classe § § § l Deux comportements l longueur d’une chaîne de caractères taille d’un tableau titre d’une fenêtre dimensions d’une image … Lecture (get) Écriture (set) Mêmes attributs que les méthodes . NET Framework, C# et. NET Remoting C# 33
Propriétés 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; } } }. NET Framework, C# et. NET Remoting C# 34
Indexeurs l Indexer une classe à la manière d’un tableau public class Stack { private Node Get. Node(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 Get. Node(index). Value; } set { Get. Node(index). Value = value; } } } . NET Framework, C# et. NET Remoting C# 35
Opérateurs public struct Digit { byte value; public Digit(byte value) { if (value < 0 || value > 9) throw new Argument. Exception(); 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); } } . NET Framework, C# et. NET Remoting C# 36
Opérateurs public struct Digit { byte value; public Digit(byte value) { if (value < 0 || value > 9) throw new Argument. Exception(); 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); } } . NET Framework, C# et. NET Remoting C# 37
Opérateurs public struct Digit { byte value; public Digit(byte value) { if (value < 0 || value > 9) throw new Argument. Exception(); 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 (Get. Type() == value. Get. Type()) return this == (Digit)value; return false; } }. NET Framework, C# et. NET Remoting C# 38
Délégués l l l Pointeurs de méthodes (vulgarisation) Encapsule à la fois un objet et une méthode Peut « pointer » vers plusieurs méthodes delegate void D(int x); class C { public static void M 1(int i) {. . . } public static void M 2(int i) {. . . } } class Test { static void Main() { D cd 1 = new D(C. M 1); // M 1 D cd 2 = new D(C. M 2); // M 2 D cd 3 = cd 1 + cd 2; // M 1 + M 2 D cd 4 = cd 3 + cd 1; // M 1 + M 2 + M 1 D cd 5 = cd 4 + cd 3; // M 1 + M 2 + M 1 + M 2 } } . NET Framework, C# et. NET Remoting C# 39
Événements l l Mécanisme de notification Basé sur les délégués Consommateur d’événements Traitant d’événements Générateur d’événements Événement registration callback Consommateur d’événements Traitant d’événements . NET Framework, C# et. NET Remoting C# 40
Événements public delegate void Event. Handler(object sender, Event. Args e); public class Button: Control { public event Event. Handler Click; protected void On. Click(Event. Args e) { if (Click != null) Click(this, e); } } public class Form { Button 1 = new Button(); public Form() { Button 1. Click += new Event. Handler(Button 1_Click); } ~Form() { Button 1. Click -= new Event. Handler(Button 1_Click); } void Button 1_Click(object sender, Event. Args e) { Console. Write. Line("Button 1 was clicked!"); } }. NET Framework, C# et. NET Remoting C# 41
Espaces de noms l Conteneur de classes ou d’espaces de nom l Organiser des classes hiérarchiquement Structurer les assemblages class A {} namespace X { class B { class C {} } namespace Y { class D {} } } namespace X. Y { class E {} } . NET Framework, C# et. NET Remoting // A // X. B. C // X. Y. D // X. Y. E C# 42
Interfaces l Nom l Attribut d’accessibilité § § public protected private internal non limité à la classe et aux classes dérivées limité à la classe limité à l’assemblage l Interfaces de base (héritage multiple d’interfaces) l Membres § § Méthodes Propriétés Indexeurs Événements . NET Framework, C# et. NET Remoting C# 43
Fonctionnalités avancées l Section critique, exclusion mutuelle class Account { int balance; public Account(int initial) { balance = initial; } int Withdraw(int amount) { if (balance < 0) throw new Exception("Negative Balance"); lock (this) { if (balance >= amount) { balance = balance - amount; return amount; } else { return 0; } } . NET Framework, C# et. NET Remoting C# 44
Fonctionnalités avancées l Contrôle de débordement lors d’opérations arithmétiques sur les entiers class Over. Flow. Test { static short x = 32767, y = 32767; public static int my. Method. Check() { int z = 0; try { z = checked((short)(x + y)); } catch (System. Overflow. Exception e) { System. Console. Write. Line(e. To. String()); } return z; } public static int my. Method. Uncheck() { int z = unchecked((short)(x + y)); return z; } } . NET Framework, C# et. NET Remoting C# 45
Fonctionnalités avancées l Boxing / Unboxing § Mécanisme de conversion entre un type valeur et un type référence boxing : : unboxing type référence valeur type référence type valeur Sur la pile Sur le tas i 123 int i = 123; object o = i; int j = (int)o; int i = 123; o (i boxed) 123 object o = i; int 123 j 123 int j = (box)o; . NET Framework, C# et. NET Remoting C# 46
Fonctionnalités avancées l Code unsafe Manipulation de bas niveau (pointeurs) Autorise les conversions de types Autorise les opérations arithmétiques sur les pointeurs Semblable à du code C inline Allocation sur la pile (stackalloc) class Test { unsafe void Method() { char* buf = stackalloc char[256]; for(char* p = buf; p < buf + 256; p++) *p = 0; . . . } } . NET Framework, C# et. NET Remoting C# 47
Fonctionnalités avancées l Code unsafe Fixer l’adresse mémoire d’une variable à l’exécution (fixed) class Test { static int x; int y; unsafe static void F(int* p) { *p = 1; } static void Main() { Test t = new Test(); int[] a = new int[10]; unsafe { fixed (int* p = &x) F(p); fixed (int* p = &t. y) F(p); fixed (int* p = &a[0]) F(p); fixed (int* p = a) F(p); } } } . NET Framework, C# et. NET Remoting C# 48
Sommaire l . NET Framework l C# l Introduction Architecture et fonctionnement Standardisation et interopérabilité Concepts de base Types et variables Classes Fonctionnalités avancées . NET Remoting Principe Configuration Demos. NET Framework, C# et. NET Remoting 49
Principe l l Invoquer des méthodes sur objets distants Deux rôles l Client Serveur Canal de communication (http, tcp) Canal Système distant Proxy Objet serveur . NET Framework, C# et. NET Remoting Objet client . NET Remoting 50
Principe l Formattage Binaire SOAP … Canal Formatteur Formatteur Canal Système distant Proxy Objet serveur . NET Framework, C# et. NET Remoting Objet client . NET Remoting 51
Principe l Deux types d’objets distants Marshall. By. Value § § Sérialisation Copie vers le client Marshall. By. Reference § § Utilisation de proxy Stocké sur le serveur . NET Framework, C# et. NET Remoting 52
Configuration l Deux modes de configuration Par fichier de configuration Par programmation . NET Framework, C# et. NET Remoting 53
Demos l l Hello World Simple Remoting Javanaise. NET Quake II. NET Framework, C# et. NET Remoting Demos 54
Hello World using System; namespace Hello { public class Hello { public static void Main(string[] args) { Console. Write. Line("Hello World !"); Console. Write. Line(); foreach(string s in args) { Console. Write(s); } } . NET Framework, C# et. NET Remoting Demos 55
Hello World l Compilation en ligne de commande csc /noconfig Hello. cs l Exécution sur plusieurs plateformes Windows XP § § Free. BSD 5. 2. 1 § § . NET Framework 1. 1 10. 0. 7. 50 Rotor 10. 0. 7. 251 Red Hat Linux 9. 1 § § Mono 1. 0. 4 10. 0. 7. 250 . NET Framework, C# et. NET Remoting Demos 56
Simple Remoting l Objet distribué (écrit en Visual Basic) 'Remotable. Type. vb Imports System Public Class Remotable. Type Inherits Marshal. By. Ref. Object Private _internal. String As String = "This is the Remotable. Type. " Public Function String. Method(param As String) As String Console. Write. Line("Call from " + param) Return _internal. String End Function 'String. Method End Class 'Remotable. Type l Compilation vbc /t: library Remotable. Type. vb . NET Framework, C# et. NET Remoting Demos 57
Simple Remoting l Serveur (écrit en C#) // Host. cs using System; using System. Runtime. Remoting; namespace Remoting { public class Host { public static void Main() { Remoting. Configuration. Configure("Host. exe. config"); Console. Write. Line("Listening for requests. Press Enter to exit. . . "); Console. Read. Line(); } } } l Compilation csc /noconfig /r: Remotable. Type. dll Host. cs . NET Framework, C# et. NET Remoting Demos 58
Simple Remoting l Configuration du serveur <? xml version="1. 0" encoding="utf-8" ? > <configuration> <system. runtime. remoting> <application> <service> <wellknown mode="Singleton" type="Remotable. Type, Remotable. Type" object. Uri="Remotable. Type. rem" /> </service> <channels> <channel ref="tcp" port="6969"/> </channels> </application> </system. runtime. remoting> </configuration> . NET Framework, C# et. NET Remoting Demos 59
Simple Remoting l Client (écrit en C#) // Client. cs using System; using System. Runtime. Remoting; namespace Remoting { public class Client { public static void Main(string[] args) { string param; if(args. Length != 1) { param = "nowhere : -/"; } else { param = args[0]; } Remoting. Configuration. Configure("Client. exe. config"); Remotable. Type remote. Object = new Remotable. Type(); Console. Write. Line(remote. Object. String. Method(param)); } } } l Compilation csc /noconfig /r: Remotable. Type. dll Client. cs . NET Framework, C# et. NET Remoting Demos 60
Simple Remoting l Configuration du client <? xml version="1. 0" encoding="utf-8" ? > <configuration> <system. runtime. remoting> <application> <client> <wellknown type="Remotable. Type, Remotable. Type" url="tcp: //10. 0. 7. 50: 6969/Remotable. Type. rem" /> </client> </application> </system. runtime. remoting> </configuration> . NET Framework, C# et. NET Remoting Demos 61
Simple Remoting l Exécution Serveur sous Windows XP Client sous Free. BSD 5. 2. 1 Client sous Red Hat Linux 9. 1 . NET Framework, C# et. NET Remoting Demos 62
Javanaise. NET l l Portage du projet Javanaise Java C# Exécution sous Windows XP (Win. Forms) . NET Framework, C# et. NET Remoting Demos 63
Quake II. NET l Observation de performances Version native § 69. 3 FPS Version managée § 56. 0 FPS . NET Framework, C# et. NET Remoting Demos 64
Ressources http: //msdn. microsoft. com/netframework/ http: //msdn. microsoft. com/net/ecma/ http: //www. ecma-international. org/publications/standards/ecma-334. htm http: //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/quake 2/ http: //www. gotdotnet. com/ http: //www. dotnetguru. org/ http: //www. dotnet-fr. org/ . NET Framework, C# et. NET Remoting 65
Discussion Questions ? . NET Framework, C# et. NET Remoting 66
- Slides: 66