Imports System.Collections.Generic Public Class Job ' La classe Job doir contenir ces informations (pour l'exemple je ne les faits pas toutes, mais comme tu en parameters {entre autres} qui est optionnel, je te montre ' <Job name="P9999H0101" retained="0" family="UNIX"> ' <Script><![CDATA[#/opt/vtom/plan_production.sh]]></Script> ' <Node objectType="job" x="430" y="30"> ' </Node> ' ' <Job name="P9999H0102" retained="0" family="UNIX" comment=""> ' <Script><![CDATA[#/opt/vtom/envoi.sh]]></Script> ' <Parameters> ' <Parameter><![CDATA[TEST]]></Parameter> ' </Parameters> ' <Node objectType="job" x="430" y="140"> ' </Node> ' ' Public Property Name() As String Public Property Retained() As Integer Public Property Family() As String Public Property Script() As String Public Property Parameters() As List(Of String) End Class Public Class ApplicationJMO Public Property Name() As String Public Property Jobs() As List(Of Job) ' ' je te laisse faire les autres ' End Class
Private Sub xmlJMO() Dim xDoc As XDocument = XDocument.Load("testJMO.xml")'Chargement du fichier Dim maListe As List(Of ApplicationJMO) = ( From el In xDoc.Descendants("Application")'directement le noeud qui représente l'enregistrement Select New ApplicationJMO With {'on crée une instance d'ApplicationJMO .Name = el.Attribute("name").Value, .Jobs = ( From j In el.Descendants("Job")'idem, direct le noeud Job et pas Jobs Select New Job With'On crée une instance de Job { .Name = j.Attribute("name").Value,'les premières données sont systématiquement là .Retained = Convert.ToInt32(j.Attribute("retained").Value), .Family = j.Attribute("family").Value, .Script = j.Element("Script").ToString(),'là je t'ai mis ToSting() au lieu de Value, car Value vire "![CDATA[" et "]]", cependant avec ToString, tu as la balise en plus, à toi de voir .Parameters = If(j.Elements("Parameters").Count() = 0, Nothing, ( From p In j.Descendants("Parameter") Select p.Value).ToList())'pour les paramètres, il faut tester s'il y en a ou pas }).ToList() }).ToList() End Sub
Imports System.Collections.Generic
Public Class Environment
Public Property envName() As String
Public Property envHost() As String
Public Property Applications() As List(Of Application)
End Class
Public Class Application
Public Property appName() As String
Public Property appHost() As String
Public Property appComment() As String
Public Property Jobs() As List(Of Job)
End Class
Public Class Job
Public Property jobName() As String
Public Property jobHost() As String
Public Property jobComment() As String
Public Property Parameters() As List(Of String)
End Class
Dim maListe As List(Of Environment) = (
From el In xDoc.Descendants("Environment")
Select New Environment With {
.envName = CStr(el.Attribute("name").Value),
.envHost = CStr(el.Attribute("host").Value),
.Applications = (
From j In el.Descendants("Application")
Select New Application With {
.appName = j.Attribute("name").Value,
.appComment = j.Attribute("comment").Value,
.Jobs = (
From k In el.Descendants("Job")
Select New Job With {
.jobName = k.Attribute("name").Value,
.jobComment = k.Attribute("comment").Value
}).ToList()
}).ToList()
}).ToList()
Catch ex As Exception
TextBox2.Text = ex.Message
End Try
Aucune erreur mais maListe n'est pas reconnue par l'intellisense !!!c'est à dire?
Dim maListe As List(Of Environment) = (
From el In xDoc.Descendants("Environment")
Select New Environment With {
.envName = CStr(el.Attribute("name").Value),
.envHost = CStr(el.Attribute("host").Value)
}).ToList()
Vous n’avez pas trouvé la réponse que vous recherchez ?
Posez votre questionPublic Class PortéeDesVariables'Attention jamais d'accent dans les noms de variables, classes, propriétés, etc, là c'est pour que l'exemple ne prête pas à confusion 'toute variable déclarée (pas forcément initialisée) ici est accessible de toute la classe Dim variable1 as String Private Sub Quelconque1() Dim variable2 As Double 'accessible dans Sub Quelconque1 et ses sous blocs (boucle for.....) 'ici je peux lire et écrire le contenu de variable1 et variable2 mais pas variable3 End Sub Private Sub Quelconque1() Dim variable3 As Double 'accessible dans Sub Quelconque1 et ses sous blocs (boucle for.....) 'ici je peux lire et écrire le contenu de variable1 et variable3 mais pas variable2 End Sub End Class
Dim maListe As List(Of Environment)un cran au-dessus et l'initialiser dans la Sub
maListe = (From '.....
maListe = (From el In xDoc.Descendants("Environment")
Select New ENV With {
.envName = CStr(el.Attribute("name").Value),
.envHost = CStr(el.Attribute("host").Value)
}).ToList()
For Each test As ENV In maListe
TextBox2.Text = TextBox2.Text + test.envName.ToString + Environment.NewLine
TextBox2.Text = TextBox2.Text + test.envHost.ToString + Environment.NewLine
Next test
' Variable Host
If appHost = Nothing Then
appHost = envHost
Else
appHost = CStr(xEle.Element("Applications").Element("Application").Attribute("host").Value)
End If
If jobHost = Nothing Then
jobHost = appHost
Else
jobHost = CStr(xEle.Element("Applications").Element("Application").Element("Jobs").Element("Job").Attribute("host").Value)
End If
Try
maListe = (
From el In xDoc.Descendants("Environment")
Select New ENV With
{.envName = CStr(el.Attribute("name").Value),
.envHost = CStr(el.Attribute("host").Value),
.Applications = (
From j In el.Descendants("Application")
Select New APP With
{.appName = j.Attribute("name").Value,
.appHost = j.Attribute("host").Value,
.appComment = j.Attribute("comment").Value,
.Jobs = (
From k In el.Descendants("Job")
Select New JOB With
{.jobName = k.Attribute("name").Value,
.jobComment = k.Attribute("comment").Value
}).ToList()
}).ToList()
}).ToList()
Catch ex As Exception
TextBox2.Text = ex.Message
End Try
J'ai besoin de parcourir toutes les variables extraites pour modifier le contenu par plusieurs fonctions
Imports System Public Class Personne Public Sub New() 'Constructeur vide, nécessaire si on veut initiliaser avec "les accolades" End Sub Public Sub New(ByVal Nom As String, ByVal Prenom As String, ByVal Naissance As Date) 'Constructeur avec paramètres Me.Nom = Nom Me.Prenom = Prenom Me.Naissance = Me.privateNaissance 'j'affecte la propriété comme ça l'age sera calculé End Sub Private privateNaissance As Date Public Property Naissance() As Date 'propriété avec calcul sur la variable interne Get Return privateNaissance End Get Set(ByVal value As Date) privateNaissance = value Age = Date.Now.Year - privateNaissance.Year End Set End Property Public Property Nom() As String Public Property Prenom() As String Public ReadOnly Property NomComplet() As String 'Propriété en lecture seule qui retourne le nom complet au format Prénom NOM Get Return String.Format("{0} {1}", Prenom, Nom.ToUpper()) End Get End Property Private privateAge As Integer Public Property Age() As Integer 'Propriété en écriture interne uniquement Private Get Return privateAge End Get Set(ByVal value As Integer) privateAge = value End Set End Property Public Overrides Function ToString() As String 'Réécriture de la méthode ToString qui retourne l'initiale du Prénom.Nom Return String.Format("{0}.{1}", Prenom.Chars(0).ToString().ToUpper(), Nom.ToUpper()) End Function Public Shared Function NouvellePersonne(ByVal Nom As String, ByVal Prenom As String, ByVal Age As Integer) As Personne 'méthode de classe pour une autre façon d'initialiser Return New Personne With {.Nom = Nom, .Prenom = Prenom, .Age = Age} End Function End Class
Dim p1 As Personne = New Personne()'utilisation du constructeur vide, oblige ensuite d'initialiser les propriétés p1.Nom = "Dit" p1.Prenom = "Alain" p1.Naissance = DateTime.Parse("01/01/2000") Dim p2 As Personne = New Personne("Sors", "Jean", "01/02/2000")'hem constructeur Dim p3 As Personne = Personne.NouvellePersonne("Zètofrais", "Mélanie", 10)'Méthode de classe Dim p4 As Personne = New Personne With {.Nom = "Kenobi", .Prenom = "Ben"} 'De cette façon, on choisit quelles propriétés on intialise
maListe = (From el In xDoc.Descendants("Environment")
Select New ENV With {
.envName = CStr(el.Attribute("name").Value),
.envHost = CStr(el.Attribute("host").Value)
}).ToList()
For Each test As ENV In maListe
TextBox2.Text = TextBox2.Text + test.envName.ToString + Environment.NewLine
TextBox2.Text = TextBox2.Text + test.envHost.ToString + Environment.NewLine
Next test
maListe = (
From el In xDoc.Descendants("Environment")
Select New ENV With
{.envName = CStr(el.Attribute("name").Value),
.envHost = CStr(el.Attribute("host").Value),
.Applications = (
From j In el.Descendants("Application")
Select New APP With
{.appName = j.Attribute("name").Value,
.appHost = j.Attribute("host").Value,
.appComment = j.Attribute("comment").Value,
.Jobs = (
From k In el.Descendants("Job")
Select New JOB With
{.jobName = k.Attribute("name").Value,
.jobComment = k.Attribute("comment").Value
}).ToList()
}).ToList()
}).ToList()
Les variables envName et envHost me renvoyaient correctement leur contenu.
For Each test As ENV In maListe TextBox2.Text = TextBox2.Text + test.envName.ToString + Environment.NewLine TextBox2.Text = TextBox2.Text + test.envHost.ToString + Environment.NewLine Next testénumère maListe, les ToString sont inutiles car dans ta classe décrite au message 2, tu les a déclarés comme string.
J'ai besoin de parcourir toutes les variables extraites pour modifier le contenu par plusieurs fonctions (beginTime = temps en secondes depuis 1970, d'autres remplacer "E" par "Execution", etc).
j'ai besoin de la variable envHost, car si après dans la lecture de l'application la variable appHost n'existe pas, je dois récupérer envHost.à la première lecture, je l'ai interprété à l'envers. Si pas de Host dans Environement, je prends celui de Job, donc je t'ai peut-être embrouillé.
Dim xDoc As XDocument = XDocument.Load("testJMO.xml") 'je crée un tableau de 2 enregistrements que je caste en list pour la mettre dans le if à la place de Nothing Dim maListe As List(Of ApplicationJMO) = ( From el In xDoc.Descendants("Application") Let noms As List(Of String) = {"NomApplication", el.Attribute("name").Value}.ToList() Select New ApplicationJMO With { .Name = el.Attribute("name").Value, .Jobs = ( From j In el.Descendants("Job") Select New Job With { .Name = j.Attribute("name").Value, .Retained = Convert.ToInt32(j.Attribute("retained").Value), .Family = j.Attribute("family").Value, .Script = j.Element("Script").ToString(), .Parameters = If(j.Elements("Parameters").Count() = 0, noms, ( From p In j.Descendants("Parameter") Select p.Value).ToList()) }).ToList() }).ToList()
<Domain name="DEV" stamp="VTEXPORT 5.6.4a FR LINUX_X64 2014/06/15">
<Environments>
<Environment name="exploitation" host="localhost">
<Applications>
<Application name="BASCULE_test_EXPLOIT" >
<Jobs>
<Job name="P9999H0102" retained="0" family="UNIX" comment="">
<Script><![CDATA#/opt/vtom/envoi.sh]></Script>
<Parameters>
<Parameter><![CDATA[TEST]]></Parameter>
</Parameters>
</Job>
<Job name="PBASCULEDATE" retained="0" family="TR1|UNIX" comment="Bascule">
<Script><![CDATA#/opt/vtom/test_bascule_exploitation.sh]></Script>
</Job>
</Jobs>
</Application>
<Application name="A-P9999H01" retained="0" comment="">
<Jobs>
<Job name="P9999H0101" retained="0" family="UNIX">
</Job>
</Jobs>
</Application>
</Applications>
</Environment>
<Environment name="production" host="172...">
.....
.....
</Environments>
</Domain>
ENV APPLI HOST JOB
DEV APP1 local job1
DEV APP1 xxxx job2 ' xxxx car le job s'exécute sur un serveur distant
DEV APP1 local job3
DEV APP2 yyyy job1
PROD APP1 local job1
Try
maListe = (
From el In xDoc.Descendants("Environment")
Select New ENV With {
.envName = el.Attribute("name").Value,
.envHost = el.Attribute("host").Value,
.Applications = (
From j In el.Elements("Application")
Select New APP With {
.appName = j.Attribute("name").Value,
.appHost = j.Attribute("host").Value,
.appComment = j.Attribute("comment").Value,
.Jobs = (
From k In el.Descendants("Job")
Select New JOB With {
.jobName = k.Attribute("name").Value,
.jobComment = k.Attribute("comment").Value
}).ToList()
}).ToList()
}).ToList()
Catch ex As Exception
Try
For Each myENV As ENV In maListe
TextBox2.Text = TextBox2.Text & "envName" & _
Convert.ToChar(Keys.Tab) & myENV.envName + Environment.NewLine
TextBox2.Text = TextBox2.Text & "envHost" & _
Convert.ToChar(Keys.Tab) & myENV.envHost + Environment.NewLine
Next myENV
Catch ex As Exception
From j In el.Descendants("Application")par
From j In el.Elements("Application")car j'avais une erreur
Appli connait son Job, Job connait son EnvironnementNon puisque la lecture du fichier est séquentielle
Appli connait son Job et son Environnement, et Job s'en fout (au pire il regardera l'environnement d'une Appli)
Appli connait son Job et son Environnement,Job connait son Environnement
<Environments>
<Environment name="exploitation" date="date_exp" host="localhost">
'ici il faut créer 2 variables
'nameENV
'hostENV
<Applications>
<Application name="BASCULE_EXPLOIT" retained="0">
' ici on voit que l'appli n'a pas de host, on doit donc récupérer le host
' de l'environnement du name "exploitation", à savoir hostENV"
' ici je vais récupérer diverses variables de l'application name, retained '
' on va donc créer les variables
' nameAPP
' hostAPP
' etc, il y en a 8
'
<Jobs>
<Job name="PBASCULEDATE" retained="0" family="TR1|UNIX">
' ici on voit que le job n'a pas de host rattaché, il hérite du host de l'application. On doit donc récupérer le host de l'application, à savoir hostAPP.
' Si sur cette ligne il y a <Job name="xxxx' host="titi", on récupère titi pour hostJOB
' ici je vais récupérer diverses variables de l'application name, retained
' donc à ce niveau on dispose des variables
' nameENV
' nameAPP
' xxxxAPP
' yyyyAPP
' zzzzAPP
' nameJOB
'hostJOB
' familyJOB
' .... il y en a une vingtaine
' ces variables constitueront une ligne du datagridview sur x colonnes
' les variables hostENV et hostAPP ne seront pas écrites dans le datagridview puisque c'est le hostJOB qui sera récupéré
-Si le Host de l'environnement est modifié dans ton programme, doit-il l'être aussi dans la variable Job? (idem pour celui de Application par rapport à Job)pas de réponse
-Si j'affecte un autre Host au Job, que devient celui de l'environnement? (idem pour celui de Application par rapport à Job)
-Est ce que tu réécris le fichier xml?tu dis lecture seule, donc j'en déduis que non, bien qu'on pourrait écrire un autre fichier
-Au final est-ce que tu souhaites manipuler une arboressence Env->Appli->Job ou une collection d'Appli qui savent remonter l'arborescence si nécessaire? (Par exemple si ton but est d'afficher les Appli dans un datagridview, la réponse est plutôt oui),là aussi je déduis que oui.
-Si le Host de l'environnement est modifié dans ton programme, doit-il l'être aussi dans la variable Job? (idem pour celui de Application par rapport à Job)
-Si j'affecte un autre Host au Job, que devient celui de l'environnement? (idem pour celui de Application par rapport à Job)
-Est ce que tu réécris le fichier xml?
tu dis lecture seule, donc j'en déduis que non, bien qu'on pourrait écrire un autre fichier
-Au final est-ce que tu souhaites manipuler une arboressence Env->Appli->Job ou une collection d'Appli qui savent remonter l'arborescence si nécessaire? (Par exemple si ton but est d'afficher les Appli dans un datagridview, la réponse est plutôt oui),
<Domain name="DEV" stamp="VTEXPORT 5.6.4a FR LINUX_X64 2014/06/15"> <Environments> <Environment name="exploitation" host="localhost"> <Applications> <Application name="BASCULE_test_EXPLOIT" > <Jobs> <Job name="P9999H0102" retained="0" family="UNIX" comment=""> <Script><![CDATA[#/opt/vtom/envoi.sh]]></Script> <Parameters> <Parameter><![CDATA[TEST]]></Parameter> </Parameters> </Job> <Job name="PBASCULEDATE" retained="0" family="TR1|UNIX" comment="Bascule"> <Script><![CDATA[#/opt/vtom/test_bascule_exploitation.sh]]></Script> </Job> </Jobs> </Application> <Application name="A-P9999H01" retained="0" comment=""> <Jobs> <Job name="P9999H0101" retained="0" family="UNIX" host = "Host du Job"> </Job> </Jobs> </Application> </Applications> </Environment> </Environments> </Domain>
Imports System.Collections.Generic Public Class Job Public Property Name() As String Private privateHost As String Public Property Host() As String Get If String.IsNullOrWhiteSpace(privateHost) Then 'si mon host est vide, je retourne celui de mon parent Return parent.Host Else Return privateHost End If End Get Set(ByVal value As String) privateHost = value End Set End Property Private parent As ApplicationJMO Public ReadOnly Property EnvName() As String Get 'là je retourne directement le nom de l'environement, en lecture seule, si en cours d'exécution, celui=ci évolue, cette propriété sera à jour Return parent.Parent.Name End Get End Property Public Function AffecteParent(ByVal AppParent As ApplicationJMO, ByVal EnvParent As EnvironnementJMO) As Job 'cette métode permet d'affecter le parent tout en retourne un référence à l'instance en cours, elle servira à la 2eme requête parent = AppParent AppParent.Parent = EnvParent Return Me End Function End Class Public Class ApplicationJMO Public Property Name() As String Private privateHost As String Public Property Host() As String Get If String.IsNullOrWhiteSpace(privateHost) Then 'si mon host est vide, je retourne celui de mon parent Return Parent.Host End If Return privateHost End Get Set(ByVal value As String) privateHost = value End Set End Property Public Property Parent() As EnvironnementJMO Public Property Jobs() As List(Of Job) End Class Public Class EnvironnementJMO Public Property Name() As String Public Property Host() As String Public Property Applications() As List(Of ApplicationJMO) End Class
Dim xDoc As XDocument = XDocument.Load("testJMO.xml") 'Liste "copiée" sur l'arboressence Dim maListe As List(Of EnvironnementJMO) = ( From e In xDoc.Descendants("Environment") Select New EnvironnementJMO With {.Name = e.Attribute("name").Value, .Host = e.Attribute("host").Value, .Applications = ( From a In e.Descendants("Application") Select New ApplicationJMO With {.Name = a.Attribute("name").Value, .Host = If(a.Attributes("host").Count() > 0, a.Attribute("host").Value, Nothing), .Jobs = ( From j In a.Descendants("Job") Select New Job With {.Name = j.Attribute("name").Value, .Host = If(j.Attributes("host").Count() > 0, j.Attribute("host").Value, Nothing)}).ToList()}).ToList()}).ToList() 'liste de Jobs, avec les parents affectés Dim mesJobs As List(Of Job) = ( From e In maListe, a In e.Applications, j In a.Jobs Select j.AffecteParent(a, e)).ToList() dataGridView1.DataSource = mesJobs
Le fichier xml est en lecture seule.Je ne parlais pas d'un fichier temporaire, mais d'un fichier qui accueillerais les éventuelles modifications faites aux données par ton programme. C'est assez rares de juste vouloir lire des données, sans les trier, retoucher, etc...
Créer un fichier temp, pourquoi pas, mais à quoi servent ArrayList, Dictionary ou ListOf ?
Nul ne saurait valablement coder ce qu'il ne saurait exposer clairement.
Je ne parlais pas d'un fichier temporaire, mais d'un fichier qui accueillerais les éventuelles modifications faites aux données par ton programme. C'est assez rares de juste vouloir lire des données, sans les trier, retoucher, etc...
Select j.AffecteParent(a, e)).ToList()
Dans quel tutoriel ou bouquin, puis-je trouver, par exemple, l'explication deSelect j.AffecteParent(a, e)).ToList()