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

Langages Discussion :

System.InvalidCastException: Specified cast is not valid.


Sujet :

Langages

  1. #1
    Nouveau membre du Club
    Homme Profil pro
    Newbie
    Inscrit en
    Mars 2016
    Messages
    34
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : France, Lot et Garonne (Aquitaine)

    Informations professionnelles :
    Activité : Newbie

    Informations forums :
    Inscription : Mars 2016
    Messages : 34
    Points : 25
    Points
    25
    Par défaut System.InvalidCastException: Specified cast is not valid.
    Bonjour à tous,

    Je suis actuellement en train de faire une API pour accéder à une base de données MySQL (à titre d’exercice) avec une appli android. Je rencontre quelques problèmes (sinon je ne serai pas là). J'utilise Visual Studio.
    L'erreur généré lors du deboggage est System.InvalidCastException: Specified cast is not valid .
    Voici le code :

    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
    using System;
    using Android.App;
    using Android.Content;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.OS;
    using System.Json;
    using System.Net;
    using System.Threading.Tasks;
    using System.IO;
    using Newtonsoft.Json;
    using Microsoft.CSharp;
     
    namespace API_Test
    {
        [Activity(Label = "API_Test", MainLauncher = true, Icon = "@drawable/icon")]
        public class MainActivity : Activity
        {
     
            private Button button;
            private EditText reponseAPI;
     
            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);
     
                // Set our view from the "main" layout resource
                SetContentView(Resource.Layout.Main); 
     
                // Get the latitude/longitude EditBox and button resources:
                button = FindViewById<Button>(Resource.Id.btnCall);
     
                // When the user clicks the button ...
                button.Click += async (sender, e) => {
     
                    // Get the latitude and longitude entered by the user and create a query.
                    string url = "http://192.168.X.XX/API_xxxx.php?xxx"; 
     
                    // Fetch the weather information asynchronously, 
                    // parse the results, then update the screen:
                    JsonValue json = await FetchWeatherAsync(url);
                    //ParseAndDisplay (json);
                };         
            }
     
            // Gets weather data from the passed URL.
            private async Task<JsonValue> FetchWeatherAsync(string url)
            {
                // Create an HTTP web request using the URL:
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
                request.ContentType = "application/json";
                request.Method = "GET";
     
                // Send the request to the server and wait for the response:
                using (WebResponse response = await request.GetResponseAsync())
                {
                    // Get a stream representation of the HTTP web response:
                    using (Stream stream = response.GetResponseStream())
                    {
                        // Use this stream to build a JSON document object:
                        JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
                        Console.Out.WriteLine("Test3: {0}", jsonDoc.ToString());
     
                        // Return the JSON document:
                        return jsonDoc;
                    }
                }
            }
     
     
            private void ParseAndDisplay(JsonValue json)
            {
                reponseAPI = FindViewById<EditText>(Resource.Id.reponseAPI);
     
                //dynamic Toto = JsonObject.Parse(json);
                //string lolo = Toto.id;
                //reponseAPI.Text = lolo;
                //var m = JsonConvert.DeserializeObject<dynamic>(json);
                //Console.Out.WriteLine("oooo");
     
                //string name = m.id;       
     
     
            }
        }
    }
    Après avoir cliquer sur le bouton "call" le mode débogue signale:


    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
    08-22 12:25:30.250 D/Mono    ( 5720): Image addref System.Json[0x9d3c3e60] -> System.Json.dll[0x9c1dba00]: 1
    08-22 12:25:30.250 D/Mono    ( 5720): Assembly System.Json[0x9d3c3e60] added to domain RootDomain, ref_count=1
    08-22 12:25:30.250 D/Mono    ( 5720): AOT module 'System.Json.dll.so' not found: dlopen failed: library "/data/app/API_Test.API_Test-1/lib/x86/libaot-System.Json.dll.so" not found
    08-22 12:25:30.251 D/Mono    ( 5720): AOT module '/Users/builder/data/lanes/3540/1cf254db/source/monodroid/builds/install/mono-x86/lib/mono/aot-cache/x86/System.Json.dll.so' not found: dlopen failed: library "/data/app/API_Test.API_Test-1/lib/x86/libaot-System.Json.dll.so" not found
    08-22 12:25:30.251 D/Mono    ( 5720): Config attempting to parse: 'System.Json.dll.config'.
    08-22 12:25:30.251 D/Mono    ( 5720): Config attempting to parse: '/Users/builder/data/lanes/3540/1cf254db/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System.Json/System.Json.config'.
    08-22 12:25:30.251 D/Mono    ( 5720): Assembly Ref addref API_Test[0xad97bbe0] -> System.Json[0x9d3c3e60]: 2
    08-22 12:25:30.251 D/Mono    ( 5720): Assembly Ref addref System.Json[0x9d3c3e60] -> mscorlib[0xad97bb80]: 14
    Loaded assembly: System.Json.dll
    08-22 12:25:30.268 D/Mono    ( 5720): Assembly Ref addref API_Test[0xad97bbe0] -> System[0xb4099cc0]: 3
    08-22 12:25:30.328 D/Mono    ( 5720): Assembly Ref addref Mono.Android[0xb4099e40] -> System[0xb4099cc0]: 4
    08-22 12:25:30.359 D/Mono    ( 5720): DllImport searching in: '__Internal' ('(null)').
    08-22 12:25:30.359 D/Mono    ( 5720): Searching for 'java_interop_jnienv_call_int_method'.
    08-22 12:25:30.359 D/Mono    ( 5720): Probing 'java_interop_jnienv_call_int_method'.
    08-22 12:25:30.359 D/Mono    ( 5720): Found as 'java_interop_jnienv_call_int_method'.
    08-22 12:25:30.364 D/Mono    ( 5720): DllImport searching in: '__Internal' ('(null)').
    08-22 12:25:30.364 D/Mono    ( 5720): Searching for 'java_interop_jnienv_get_static_field_id'.
    08-22 12:25:30.364 D/Mono    ( 5720): Probing 'java_interop_jnienv_get_static_field_id'.
    08-22 12:25:30.364 D/Mono    ( 5720): Found as 'java_interop_jnienv_get_static_field_id'.
    08-22 12:25:30.365 D/Mono    ( 5720): DllImport searching in: '__Internal' ('(null)').
    08-22 12:25:30.365 D/Mono    ( 5720): Searching for 'java_interop_jnienv_get_static_object_field'.
    08-22 12:25:30.365 D/Mono    ( 5720): Probing 'java_interop_jnienv_get_static_object_field'.
    08-22 12:25:30.365 D/Mono    ( 5720): Found as 'java_interop_jnienv_get_static_object_field'.
    08-22 12:25:30.367 D/Mono    ( 5720): DllImport searching in: '__Internal' ('(null)').
    08-22 12:25:30.367 D/Mono    ( 5720): Searching for 'java_interop_jnienv_call_nonvirtual_boolean_method_a'.
    08-22 12:25:30.367 D/Mono    ( 5720): Probing 'java_interop_jnienv_call_nonvirtual_boolean_method_a'.
    08-22 12:25:30.367 D/Mono    ( 5720): Found as 'java_interop_jnienv_call_nonvirtual_boolean_method_a'.
    Thread started:  #2
    Thread started: <Thread Pool> #3
    Thread started: <Thread Pool> #4
    08-22 12:25:30.427 D/Mono    ( 5720): [0x9bb3f930] worker starting
    Thread started: <Thread Pool> #5
    08-22 12:25:30.512 D/Mono    ( 5720): [0x9b97f930] worker starting
    Thread started: <Thread Pool> #6
    08-22 12:25:30.617 D/Mono    ( 5720): [0x9bb3f930] hill climbing, change max number of threads 2
    08-22 12:25:30.697 D/Mono    ( 5720): Assembly Ref addref System.Json[0x9d3c3e60] -> System.Core[0x9d3c26c0]: 4
    08-22 12:25:30.713 D/Mono    ( 5720): Assembly Ref addref System.Json[0x9d3c3e60] -> System[0xb4099cc0]: 5
    ducon: [{"id": "1", "nom": "Dylan", "prenom": "Bob"}]
    08-22 12:25:30.766 D/Mono    ( 5720): DllImport attempting to load: '/system/lib/liblog.so'.
    08-22 12:25:30.767 D/Mono    ( 5720): DllImport loaded library '/system/lib/liblog.so'.
    08-22 12:25:30.767 D/Mono    ( 5720): DllImport searching in: '/system/lib/liblog.so' ('/system/lib/liblog.so').
    08-22 12:25:30.767 D/Mono    ( 5720): Searching for '__android_log_print'.
    08-22 12:25:30.767 D/Mono    ( 5720): Probing '__android_log_print'.
    08-22 12:25:30.767 D/Mono    ( 5720): Found as '__android_log_print'.
    08-22 13:55:08.394 I/mono-stdout( 3858): Test3: [{"id": "1", "nom": "Dylan", "prenom": "Bob"}]
    08-22 12:25:30.779 D/Mono    ( 5720): Assembly Ref addref API_Test[0xad97bbe0] -> Newtonsoft.Json[0xb077c640]: 2
    08-22 12:25:30.779 D/Mono    ( 5720): Assembly Ref addref Newtonsoft.Json[0xb077c640] -> System.Runtime[0xb077c700]: 3
    Unhandled Exception:
     
    System.InvalidCastException: Specified cast is not valid.
    Les posts de forum traitant de ce problème (stackoverflow) traite souvent d'une erreur de genre TypeValue ou de valeur nulle.

    Merci de votre aide.

  2. #2
    Membre expert
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Octobre 2013
    Messages
    1 563
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2013
    Messages : 1 563
    Points : 3 404
    Points
    3 404
    Par défaut
    Citation Envoyé par Mathaousse Voir le message
    Après avoir cliquer sur le bouton "call" le mode débogue signale:


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    Unhandled Exception:
     
    System.InvalidCastException: Specified cast is not valid.
    Quel est le code appelé au click sur "call"?

    Une InvalidCastException veux dire que le compilateur n'a pas réussi à convertir un objet. Il faut donc cibler la ligne en question et regarder si les types de donnée sont bons.

  3. #3
    Nouveau membre du Club
    Homme Profil pro
    Newbie
    Inscrit en
    Mars 2016
    Messages
    34
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : France, Lot et Garonne (Aquitaine)

    Informations professionnelles :
    Activité : Newbie

    Informations forums :
    Inscription : Mars 2016
    Messages : 34
    Points : 25
    Points
    25
    Par défaut
    Je tiens à préciser que je débute sur VM.,
    Comment faire pour voir si les données attendu sont bonnes ? Il me semblait que de voir
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    08-22 13:55:08.394 I/mono-stdout( 3858): Test3: [{"id": "1", "nom": "Dylan", "prenom": "Bob"}]
    signifie qu'il a bien récupérer un objet au format Json?

    Merci de votre aide.

  4. #4
    Membre expert
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Octobre 2013
    Messages
    1 563
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2013
    Messages : 1 563
    Points : 3 404
    Points
    3 404
    Par défaut
    Citation Envoyé par Mathaousse Voir le message
    Je tiens à préciser que je débute sur VM.,
    Qu'est-ce que VM?

    Citation Envoyé par Mathaousse Voir le message
    Comment faire pour voir si les données attendu sont bonnes ? Il me semblait que de voir
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    08-22 13:55:08.394 I/mono-stdout( 3858): Test3: [{"id": "1", "nom": "Dylan", "prenom": "Bob"}]
    signifie qu'il a bien récupérer un objet au format Json?
    Je ne pense pas que ces lignes là (celles qui commencent par un date:heure) soient liées à l'erreur. On dirait plus un rapport sur l'exécution d'une méthode. Quoi qu'il en soit, il faudrait pouvoir identifier la portion de code exécuté lors du clique sur le bouton. Hors, dans le code que tu met sur ton premier message je ne voit pas où c'est. Pourrais-tu le montrer?

Discussions similaires

  1. [VB] Webbrowser et "Specified cast is not valid."
    Par oliverell62 dans le forum Windows Forms
    Réponses: 7
    Dernier message: 22/06/2013, 07h57
  2. Specified cast is not valid
    Par Titi41 dans le forum ASP.NET
    Réponses: 11
    Dernier message: 29/05/2008, 17h38
  3. [VB.NET][ASP.Net]Specified cast is not valid
    Par Irish dans le forum ASP.NET
    Réponses: 2
    Dernier message: 13/12/2006, 12h35
  4. Réponses: 3
    Dernier message: 25/09/2006, 15h48
  5. Erreur "specified cast is not valid"
    Par [DreaMs] dans le forum Delphi .NET
    Réponses: 1
    Dernier message: 30/01/2006, 21h15

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