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

VB.NET Discussion :

Comment rendre une classe serializable [Débutant]


Sujet :

VB.NET

  1. #1
    Membre averti
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2012
    Messages
    640
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Bâtiment

    Informations forums :
    Inscription : Mars 2012
    Messages : 640
    Points : 372
    Points
    372
    Par défaut Comment rendre une classe serializable
    Bonjour à tous,
    Je ne parviens pas à sérialiser ma classe et je n'ai aucun message d'erreur, j'espère que vous pourrez m'aider.

    Voici ma classe :
    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
    <Serializable>
    Public Class SetupSys
        Private _Sections As New SortedList(Of String, SetupSysKeys)
        Public Sub Add(SectionName As String, Keys As SetupSysKeys)
            _Sections.Add(SectionName, Keys)
        End Sub
        Public ReadOnly Property Item(ByVal SectionName As String) As SetupSysKeys
            Get
                Return _Sections(SectionName)
            End Get
        End Property
     
    End Class
    <Serializable>
    Public Class SetupSysKeys
        Public Keys As New SortedList(Of String, SetupSysKey)
     
        Public Sub Add(Key As SetupSysKey)
            Keys.Add(Key.KeyName, Key)
        End Sub
     
    End Class
    <Serializable>
    Public Class SetupSysKey
        Private _KeyName As String
        Private _Min As Integer
        Private _Max As Integer
        Private _Step1 As Integer
        Public Sub New(KeyName As String)
            _KeyName = KeyName
        End Sub
        Public Sub New(KeyName As String, Optional Min As Integer = 0, Optional Max As Integer = 0, Optional Step1 As Integer = 0)
            Me.New(KeyName)
            _Min = Min
            _Max = Max
            _Step1 = Step1
        End Sub
        Public ReadOnly Property KeyName() As String
            Get
                Return _KeyName
            End Get
        End Property
     
        Public ReadOnly Property Min() As Integer
            Get
                Return _Min
            End Get
        End Property
     
        Public ReadOnly Property Max() As Integer
            Get
                Return _Max
            End Get
        End Property
     
        Public ReadOnly Property Step1() As Integer
            Get
                Return _Step1
            End Get
        End Property
     
    End Class
    Et voici comment je l'utilise :
    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
        Public SetupSys1 As New SetupSys
        Private Sub InitSetupData()
     
            Dim Key1 As New SetupSysKey("Clé1", 0, 100, 5)
            Dim Key2 As New SetupSysKey("Clé2", 0, 50, 2)
            Dim Key3 As New SetupSysKey("Clé3", 0, 30, 1)
            Dim Key4 As New SetupSysKey("Clé4", 0, 30, 1)
     
            Dim Keys1 As New SetupSysKeys
            Keys1.Add(Key1)
            Keys1.Add(Key2)
            Keys1.Add(Key3)
            Keys1.Add(Key4)
     
            SetupSys1.Add("SysSetup", Keys1)
            Call SerializeSysKeys(Application.StartupPath & "\" & SYSSETUP_XML, SetupSys1)
     
        End Sub
        Private Sub LoadSetupData()
            Dim Clé1Min As Integer = SetupSys1.Item("SysSetup").Keys("Clé1").Min
        End Sub
     
        Private Sub SerializeSysKeys(ByVal Path As String, ByVal Objet As Object)
            Try
                Call SaveXmlData(Path, Objet)
            Catch ex As Exception
     
            End Try
        End Sub
     
        Private Sub SaveXmlData(ByVal Path As String, ByVal Objet As Object)
            Dim Type As Type = Objet.GetType
            Dim Serializeur As New XmlSerializer(Type)
            Dim Fi As New FileInfo(Path)
            If Fi.Directory.Exists = False Then System.IO.Directory.CreateDirectory(Fi.DirectoryName)
            'Sérialization
            Using fs As New FileStream(Path, FileMode.Create, FileAccess.Write)
                Serializeur.Serialize(fs, Objet)
                fs.Close()
            End Using
        End Sub
    PS : Je ne suis qu'au début du codage et la structure de mon fichier XML ainsi que les classes ne sont pas encore figées donc je suis ouvert à toute suggestions.
    Le but étant de stocker et récupérer des clés avec des valeurs organisées ainsi un peu à la manière des fichiers INI sauf que les valeurs sont multiples et connues à l'avance (Min, Max, Step1):
    [SECTION1]
    Clé1: Min=0, Max=100, Step1=5
    Clé2: Min=0, Max=50, Step1=2
    Clé3: Min=0, Max=30, Step1=1
    [SECTION2]
    ....

    De plus je dois pouvoir accéder aux valeurs simplement en utilisant intellisense comme ceci par exemple :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Dim Clé1Min As Integer = SetupSys1.Item("SysSetup").Keys("Clé1").Min

  2. #2
    Modérateur

    Homme Profil pro
    Inscrit en
    Janvier 2007
    Messages
    1 722
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Janvier 2007
    Messages : 1 722
    Points : 5 100
    Points
    5 100
    Par défaut
    Bonjour,

    On ne peut pas serialiser les propriétés private, protected, readonly, writeonly, ou nulle.

    Le sujet a été traité (et revu/remonté) il y a peu.
    Un contournement est présenté ici : post 3 et pour laisser propre pour l'intellisense complété plus loin : post 5 avec un petit complément d'info sur les posts 9 et 10
    Traductions d'articles :
    La mémoire en .NET - Qu'est-ce qui va où ?
    Architecture DAL de haute performance et DTO ; Version C# : Partie 1,Partie 2,Partie 3 — Version VB.NET : Partie 1,Partie 2,Partie 3
    N'hésitez pas à consulter la FAQ VB.NET, le cours complet de Philippe Lasserre et tous les cours, articles et tutoriels.

  3. #3
    Membre averti
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2012
    Messages
    640
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Bâtiment

    Informations forums :
    Inscription : Mars 2012
    Messages : 640
    Points : 372
    Points
    372
    Par défaut
    Merci pour le lien Rv26t,
    Je crois que j'ai trouvé l'origine du problème, on ne peux pas sérializer les SortedList (of Key, T). Je vais devoir revoir de fond en comble toute ma classe et je reposterais celle-ci si ça fonctionne.

  4. #4
    Modérateur

    Homme Profil pro
    Inscrit en
    Janvier 2007
    Messages
    1 722
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Janvier 2007
    Messages : 1 722
    Points : 5 100
    Points
    5 100
    Par défaut
    Exact, les éléments de type dictionnaire ne peuvent pas être sérialisé.
    Mais j'avais vu une possibilité de le faire.

    Les tutoriels de TomLev (La sérialisation XML avec .NET et Aller plus loin avec la sérialisation XML) donnent pas mal d'info et notemment Sérialiser un dictionnaire (2ème tuto)
    Traductions d'articles :
    La mémoire en .NET - Qu'est-ce qui va où ?
    Architecture DAL de haute performance et DTO ; Version C# : Partie 1,Partie 2,Partie 3 — Version VB.NET : Partie 1,Partie 2,Partie 3
    N'hésitez pas à consulter la FAQ VB.NET, le cours complet de Philippe Lasserre et tous les cours, articles et tutoriels.

  5. #5
    Membre averti
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2012
    Messages
    640
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Bâtiment

    Informations forums :
    Inscription : Mars 2012
    Messages : 640
    Points : 372
    Points
    372
    Par défaut
    Bonjour, Voici une petite évolution de ma classe pour ceux que ça intéresse.
    Donc finalement en réfléchissant mieux je n'avais pas besoin des SortedList.

    Ma classe :
    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
    <Serializable>
    Public Class SetupSys
        Private _Sections As New List(Of SetupSysKeys)
        Private _SectionsIndex As New List(Of String)
     
        Public Sub Add(SectionName As String, Key As SetupSysKey)
            Dim Keys As SetupSysKeys
            If Not _SectionsIndex.Contains(SectionName) Then
                Keys = New SetupSysKeys
                Keys.SectionName = SectionName
                Keys.Add(Key)
                _Sections.Add(Keys)
                _SectionsIndex.Add(SectionName)
            Else
                Keys = _Sections(_SectionsIndex.IndexOf(SectionName))
                Keys.Add(Key)
            End If
     
        End Sub
        Public Sub Add(SectionName As String, Keys As SetupSysKeys)
            If Not _SectionsIndex.Contains(SectionName) Then
                Keys.SectionName = SectionName
                _Sections.Add(Keys)
                _SectionsIndex.Add(SectionName)
            Else
                Throw New Exception(String.Format("La section {0} existe déja et ne peux pas être ajouté", Keys.SectionName))
            End If
     
        End Sub
     
        Public ReadOnly Property Item(ByVal SectionName As String, KeyName As String) As SetupSysKey
            Get
                Return GetKey(SectionName, KeyName) 
            End Get
        End Property
     
        Private Function GetKey(SectionName As String, KeyName As String) As SetupSysKey
            If _SectionsIndex.Contains(SectionName) Then
                Dim Keys As SetupSysKeys = _Sections(_SectionsIndex.IndexOf(SectionName))
                Dim Key As SetupSysKey = Keys.Item(KeyName)
                If Not Key Is Nothing Then
                    Return Key
                Else
                    Return Nothing
                End If
            Else
                Throw New Exception(String.Format("La Section {0} n'a pas été trouvé", SectionName))
                Return Nothing
            End If
        End Function
     
        Public Property Sections() As List(Of SetupSysKeys)
            Get
                Return _Sections
            End Get
            Set(ByVal value As List(Of SetupSysKeys))
                _Sections = value
            End Set
        End Property
     
    End Class
    <Serializable>
    Public Class SetupSysKeys
        Private _SectionName As String
        Private _Keys As New List(Of SetupSysKey)
        Private _KeysIndex As New List(Of String)
     
        Public Sub Add(Key As SetupSysKey)
            If Not _KeysIndex.Contains(Key.KeyName) Then
                _Keys.Add(Key)
                _KeysIndex.Add(Key.KeyName)
            Else
                Throw New Exception(String.Format("La clé {0} existe déja et ne peux pas être ajouté", Key.KeyName))
            End If
        End Sub
     
        Public Property Keys() As List(Of SetupSysKey)
            Get
                Return _Keys
            End Get
            Set(ByVal value As List(Of SetupSysKey))
                _Keys = value
            End Set
        End Property
        Public ReadOnly Property Item(KeyName As String) As SetupSysKey
            Get
                Return GetKey(KeyName) 
            End Get
     
        End Property
        Private Function GetKey(KeyName As String) As SetupSysKey
            If _KeysIndex.Contains(KeyName) Then
                Return _Keys(_KeysIndex.IndexOf(KeyName))
            Else
                Throw New Exception(String.Format("La clé {0} n'a pas été trouvé", KeyName))
                Return Nothing
            End If
        End Function
     
        Public Property SectionName() As String
            Get
                Return _SectionName
            End Get
            Set(ByVal value As String)
                _SectionName = value
            End Set
        End Property
     
    End Class
    <Serializable>
    Public Class SetupSysKey
        Private _KeyName As String
        Private _Min As Integer
        Private _Max As Integer
        Private _Step1 As Integer
        Private Sub New()
     
        End Sub
        Public Sub New(KeyName As String)
            _KeyName = KeyName
        End Sub
        Public Sub New(KeyName As String, Optional Min As Integer = 0, Optional Max As Integer = 0, Optional Step1 As Integer = 0)
            Me.New(KeyName)
            _Min = Min
            _Max = Max
            _Step1 = Step1
        End Sub
        Public Property KeyName() As String
            Get
                Return _KeyName
            End Get
            Set(ByVal value As String)
                _KeyName = value
            End Set
        End Property
     
        Public Property Min() As Integer
            Get
                Return _Min
            End Get
            Set(ByVal value As Integer)
                _Min = value
            End Set
        End Property
     
        Public Property Max() As Integer
            Get
                Return _Max
            End Get
            Set(ByVal value As Integer)
                _Max = value
            End Set
        End Property
     
        Public Property Step1() As Integer
            Get
                Return _Step1
            End Get
            Set(ByVal value As Integer)
                _Step1 = value
            End Set
        End Property
     
    End Class
    Le code pour l'utiliser :
    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
    Public SetupSys1 As New SetupSys
        Private Sub InitSetupData()
     
            Dim Key1 As New SetupSysKey("Clé1", 0, 100, 5)
            Dim Key2 As New SetupSysKey("TYRES", 0, 50, 2)
            Dim Key3 As New SetupSysKey("BUMP", 3, 30, 1)
            Dim Key4 As New SetupSysKey("FUEL", 0, 30, 1)
     
            SetupSys1.Add("Section30", Key1)
            SetupSys1.Add("Section30", Key2)
            SetupSys1.Add("Section31", Key3)
            SetupSys1.Add("Section31", Key4)
     
            Call SerializeSysKeys(Application.StartupPath & "\" & SYSSETUP_XML, SetupSys1)
     
        End Sub
     
        Private Sub SerializeSysKeys(ByVal Path As String, ByVal Objet As Object)
            Try
                Call SaveXmlData(Path, Objet)
            Catch ex As Exception
     
            End Try
        End Sub
     
        Private Sub SaveXmlData(ByVal Path As String, ByVal Objet As Object)
            Dim Type As Type = Objet.GetType
            Dim Serializeur As New XmlSerializer(Type)
            Dim Fi As New FileInfo(Path)
            If Fi.Directory.Exists = False Then System.IO.Directory.CreateDirectory(Fi.DirectoryName)
            'Sérialization
            Using fs As New FileStream(Path, FileMode.Create, FileAccess.Write)
                Serializeur.Serialize(fs, Objet)
                fs.Close()
            End Using
        End Sub
    Le code pour lire une clé :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
            Dim Min As Integer = SetupSys1.Item("Section31", "BUMP").Min

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

Discussions similaires

  1. rendre une classe serializable sans les codes sources
    Par LittleBean dans le forum Langage
    Réponses: 2
    Dernier message: 19/04/2007, 10h47
  2. Réponses: 1
    Dernier message: 07/09/2005, 22h15
  3. Comment rendre une form transparente à certains endroits ?
    Par ludo5532 dans le forum Composants VCL
    Réponses: 4
    Dernier message: 21/08/2005, 15h28
  4. [ADO.NET] Comment rendre une certaine colonne "AutoIncrement" ?
    Par maitrebn dans le forum Accès aux données
    Réponses: 3
    Dernier message: 23/03/2005, 22h12

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