IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

un problème de Reflection.


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre très actif Avatar de Othana
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2007
    Messages
    188
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2007
    Messages : 188
    Par défaut un problème de Reflection.
    Bonjour ici.

    depuis ce code :
    Code cs : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    public void GetDriver(string model)
            {
                if (model.Contains("AVL VT-SERIAL"))
                    assembly = Assembly.LoadFrom("AVL_VT_SERIAL" + ".dll");
                //else if (model.Contains("Port de communication"))
                //    assembly = Assembly.LoadFrom("X8" + ".dll");
                type = assembly.GetType("Base");
                method = type.GetMethod("GetId");
            }
    Je cherche donc à charger une dll, et utiliser la méthode GetId() ou sa surcharge.
    Mais je n'obtiens rien. type et method restent "null".
    Sachez que tous les éléments là sont déclarés en début de classe :
    Code cs : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    public partial class GPSForm : Form
        {
            SerialPort mySerialPort;
            XElement trackerlist=new XElement(new XElement ("trackers"));
            Assembly assembly;
            Type type;
            MethodInfo method;
    ne connaissant pas bien la Reflection, je ne sais pas ce qui ne va pas. Et c'est pas msdn qui peut m'aider...

  2. #2
    Rédacteur/Modérateur


    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2004
    Messages
    19 875
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2004
    Messages : 19 875
    Par défaut
    Ta classe Base, elle est pas dans un namespace ? Il faut indiquer le nom complet de la classe, avec le namespace :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    type = assembly.GetType("MyNamespace.Base");

  3. #3
    Expert éminent Avatar de Pol63
    Homme Profil pro
    .NET / SQL SERVER
    Inscrit en
    Avril 2007
    Messages
    14 197
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 197
    Par défaut
    et si la méthode est privée il faut utiliser une surcharge de GetMethod pour dire qu'on cherche une méthode privée
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

  4. #4
    Membre très actif Avatar de Othana
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2007
    Messages
    188
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2007
    Messages : 188
    Par défaut
    Bon, là, maintenant, il n'y a plus que GetId qui soit "null". et GetId est public.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    namespace AVL_VT_SERIAL
    {
        public class Base
        {
            public string GetId()
            {
                return "$wp+uncfg=0000,?";
            }
     
            public string GetId(string message)
            {
                char[] separator=new char[]{' ',',','=','+',':'};
                string[] decoupe = message.Split(separator);
                return decoupe[3];
            }
        }
    }

  5. #5
    Inactif  
    Homme Profil pro
    Chef de projet NTIC
    Inscrit en
    Janvier 2007
    Messages
    6 604
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 64
    Localisation : France

    Informations professionnelles :
    Activité : Chef de projet NTIC

    Informations forums :
    Inscription : Janvier 2007
    Messages : 6 604
    Par défaut
    Accessoirement, pour ce genre de besoin (chargement dynamique de DLL avec des fonctionnalités distinctes mais exposant une/des interfaces communes) j'aurais plutôt opté pour un DP IoC plutôt qu'aller chercher les méthodes par Reflection.

  6. #6
    Membre très actif Avatar de Othana
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2007
    Messages
    188
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2007
    Messages : 188
    Par défaut
    C'est prévu pour que je puisse aller chercher la dll en fonction (normalement) de model. et model dépend de ce que je vais récupérer dans le scan des connexions séries.
    Pour le moment, rien ne marche. Et je ne sais pas ce qu'est DP IoC.

  7. #7
    Inactif  
    Homme Profil pro
    Chef de projet NTIC
    Inscrit en
    Janvier 2007
    Messages
    6 604
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 64
    Localisation : France

    Informations professionnelles :
    Activité : Chef de projet NTIC

    Informations forums :
    Inscription : Janvier 2007
    Messages : 6 604
    Par défaut
    Citation Envoyé par mcferson Voir le message
    Bon, là, maintenant, il n'y a plus que GetId qui soit "null". et GetId est public
    Il faut préciser qu'il s'agit d'une méthode d'instance.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    type.GetMethod("GetId", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

  8. #8
    Membre très actif Avatar de Othana
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2007
    Messages
    188
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2007
    Messages : 188
    Par défaut
    Citation Envoyé par Bluedeep Voir le message
    Il faut préciser qu'il s'agit d'une méthode d'instance.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    type.GetMethod("GetId", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
    ça reste "null"
    Bon, je vous poste tout le code. je craque là
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Windows.Forms;
    using System.IO.Ports;
    using System.IO;
    using System.Text;
    using System.Linq;
    using System.Xml.Linq;
    using System.Reflection;
    using System.Management;
    using Microsoft.Win32;
    using System.Globalization;
     
    namespace TrakerCfgSoft
    {
        /// <summary>
        /// Description of MainForm.
        /// </summary>
        public partial class GPSForm : Form
        {
            //List<string> listofport=new List<string>();
            //List<string> listofdevice=new List<string>();
            SerialPort mySerialPort;
            XElement trackerlist=new XElement(new XElement ("trackers"));
            Assembly assembly;
            Type type;
            MethodInfo method;
     
            public GPSForm()
            {
                InitializeComponent();
            }
     
            private void MainFormLoad(object sender, EventArgs e)
            {
                mySerialPort = new SerialPort();
            }
     
            private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
            {
                // Event for receiving data
                // Read the buffer to text box.
                this.Invoke(new EventHandler(DoUpdate));
            }
     
            private void DoUpdate(object s, EventArgs e)
            {
                //Then, the textbox always display new messages when they arrive.
                //txResponse.Text = txResponse.Text + mySerialPort.ReadExisting();
                txResponse.AppendText(mySerialPort.ReadExisting());
            }
     
            private void btSend_Click(object sender, EventArgs e)
            {
                // Button to send test data
                try
                {
                    string commandeaffiche = "===> " + txSend.Text+"\n";
                    txResponse.SelectionColor = Color.Firebrick;
                    txResponse.AppendText(commandeaffiche);
                    txResponse.SelectionColor = Color.Black;
     
                    string data = txSend.Text + (char)13; //where 13 is the <CR> ASCII code.
                    byte[] commande = Encoding.ASCII.GetBytes(data);
                    mySerialPort.Write(commande, 0, commande.Length);
                    //txResponse.Text = txResponse.Text + txSend.Text;                
                }
                catch (Exception sendex)
                {
                    MessageBox.Show(sendex.ToString());
                }
            }
     
            void BtOpenClick(object sender, EventArgs e)
            {
                if (mySerialPort.IsOpen == false)
                {
                    //paramètres de connexion
                    mySerialPort.PortName = txPort.Text.ToUpper();
                    mySerialPort.BaudRate = 57600;
                    mySerialPort.Parity = Parity.None;
                    mySerialPort.StopBits = StopBits.One;
                    mySerialPort.DataBits = 8;
                    mySerialPort.Handshake = Handshake.None;
                    mySerialPort.DtrEnable = true;
                    mySerialPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);//to get messages from the port.
     
                    mySerialPort.Open();
                    StatusLabel.Text = "Port Ouvert.";
                }
            }
     
            void BtCloseClick(object sender, EventArgs e)
            {
                //To close the connection
                mySerialPort.Close();
                StatusLabel.Text = "Port Fermé.";
            }
     
            private void portList_SelectedIndexChanged(object sender, EventArgs e)
            {
                //Send the selected item port(DeviceID from listofport) in the txPort textbox
                //
                //txPort.Text = (listofport[(portList.SelectedIndex)]).ToString();
                string port = (from element in trackerlist.Elements("port") where element.Attribute("ident").Value == (string)portList.SelectedItem select element.Attribute("port").Value).First().ToString();
                txPort.Text=port;
            }
     
            private void portList_Update(object sender, EventArgs e)
            {
                //empty the two lists
                //listofdevice.Clear();
                //listofport.Clear();
     
                //will scan the serialports to get DeviceID (ports COMx) and Name of the connected device
                try
                {
                    ManagementObjectSearcher searcher =
                        new ManagementObjectSearcher("root\\CIMV2",
                        "SELECT * FROM Win32_SerialPort");
     
                    foreach (ManagementObject queryObj in searcher.Get())
                    {
                        //listofport.Add(Convert.ToString(queryObj["DeviceID"]));
                        //listofdevice.Add(Convert.ToString(queryObj["Name"]));
     
                        string model = Convert.ToString(queryObj["Name"]);
     
                        GetDriver(model);
                        try
                        {
                            trackerlist.Add(
                                (new XElement("tracker",
                                    new XAttribute("model", model),
                                    new XAttribute("port", Convert.ToString(queryObj["DeviceID"])),
                                    new XAttribute("ident", method.ToString()))));
                        }
                        catch
                        {
                            trackerlist.Add(
                                (new XElement("tracker",
                                    new XAttribute("model", model),
                                    new XAttribute("port", Convert.ToString(queryObj["DeviceID"])),
                                    new XAttribute("ident", "Connexion non identifiable"))));
                        }
                    }
                }
                catch (ManagementException me)
                {
                    MessageBox.Show("An error occurred while querying for WMI data: " + me.Message);
                }
     
                //refill the porList with the ports scan result
                portList.Items.Clear();
                //portList.Items.AddRange((string[])listofdevice.ToArray());
                var tracklist = (from element in trackerlist.Elements("ident") select trackerlist.Attribute("ident").Value).ToList();
                tracklist.ToList().ForEach(v => portList.Items.Add(v));
            }
     
            private void txSend_KeyPress(object sender, KeyPressEventArgs e)
            {
                //initiate btSend_Click event when press the Return or Enter keys
                if (e.KeyChar == (char)Keys.Return || e.KeyChar == (char)Keys.Enter)
                    btSend_Click(sender,e);
            }
     
            private void txResponse_TextChanged(object sender, EventArgs e)
            {
                //to scroll the text to last line
                txResponse.SelectionStart = txResponse.Text.Length;
                txResponse.ScrollToCaret();
                txResponse.Refresh();
            }
     
            public void GetDriver(string model)
            {
                if (model.Contains("AVL VT-SERIAL"))
                {
                    assembly = Assembly.LoadFrom("AVL_VT_SERIAL.dll");
                    //else if (model.Contains("Port de communication"))
                    //    assembly = Assembly.LoadFrom("X8.dll");
                    type = assembly.GetType("AVL_VT_SERIAL.Base");
                    method = type.GetMethod("GetId", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                }
            }
        }
    }

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 1
    Dernier message: 27/01/2009, 13h30
  2. Problème d'installation oracle 8.1.7 sous NT
    Par Anonymous dans le forum Installation
    Réponses: 7
    Dernier message: 02/08/2002, 14h18
  3. Problème d'impression
    Par IngBen dans le forum C++Builder
    Réponses: 7
    Dernier message: 22/05/2002, 11h37
  4. Problème avec la mémoire virtuelle
    Par Anonymous dans le forum CORBA
    Réponses: 13
    Dernier message: 16/04/2002, 16h10
  5. Réponses: 6
    Dernier message: 25/03/2002, 21h11

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo