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 :

wmi problème d'insertion dans une DB


Sujet :

VB.NET

  1. #1
    Membre confirmé
    Inscrit en
    Décembre 2006
    Messages
    158
    Détails du profil
    Informations forums :
    Inscription : Décembre 2006
    Messages : 158
    Par défaut wmi problème d'insertion dans une DB
    Re bonjour,
    voilà j'ai modifié mon code pour l'insérer dans mon application. J'arrive à récuppérer les infos dont j'ai besoin, à l'exeption de la date du dernier reboot avec wmi . Il m'affiche dans la DB la même date et la même heure pour toutes les machines , à savoir 01/01/1900 00:00:00.
    Soit ma fonction restart () est défectueuse, soit je n'arrive pas du tout à me connecter avec wmi à toutes les machines de mon réseau pour avoir l'info demandée.
    S'il vous plait cela fait plusieurs jours que je suis dessus je sais plus quoi faire, Si quelqu'un pouvait m'aider cela serait sympa. Je sais que je pose beaucoup de questions sur ce forum, mais un bon ça fait à peine un mois que j'apprends le VB.NET et c'est la première fois que je developpe une application de ce genre.
    Merci pour votre aide,
    Bien à vous.
    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
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
     
    <%@ Page Language="VB" %>
    <%@ Register TagPrefix="wmx" Namespace="Microsoft.Matrix.Framework.Web.UI" Assembly="Microsoft.Matrix.Framework, Version=0.6.0.0, Culture=neutral, PublicKeyToken=6f763c9966660626" %>
    <%@ import Namespace="System.Data" %>
    <%@ import Namespace="System.Data.SqlClient" %>
    <%@ import Namespace="System.Web.Mail" %>
    <%@ import Namespace="System.IO" %>
    <%@ import Namespace="System.DirectoryServices" %>
    <%@ import Namespace="System.Configuration" %>
    <%@ import Namespace="System.Net" %>
    <%@ import Namespace="System" %>
    <%@ import Namespace="System.Net.DNS" %>
    <%@ import Namespace="System.ComponentModel" %>
    <%@ import Namespace="System.Management" %>
    <%@ import Namespace="System.Runtime.InteropServices" %>
    <%@ import Namespace="System" %>
    <%@ import Namespace="ActiveDs" %>
    <%@ import Namespace="System.Text" %>
    <%@ import Namespace="System.Net.NetworkInformation" %>
    <%@ import Namespace="System.Net.Sockets" %>
    <script runat="server">
     
        ' Insert page code here
             '
     
     
              Sub Page_Load()
     
     
                     Dim Ldap As DirectoryEntry = New DirectoryEntry("LDAP://scoot.local", "toto", "toto")
                     Dim searcher As DirectorySearcher = New DirectorySearcher(Ldap)
                     searcher.Filter = "(objectClass=computer)"
                     Dim DirEntry As DirectoryEntry
                     Dim nom As String
                     Dim OsVersion As String
                     Dim Os As String
                     Dim ServicePack As String
                     Dim Ip As String
                     Dim largeInteger As Object
                     Dim lastLoggedOnDate As Date
                     Dim reboot As Date
                     Dim rebootTime As Object
     
                     SqlDataSourceControl2.ConnectionString="server='(local)'; trusted_connection=true; database='pspintranet'"
                     SqlDataSourceControl2.SelectCommand="Select * from Servers"
     
     
                     call SQLExecuteQuery("TRUNCATE TABLE Servers")
     
                     'call restart(reboot)
     
     
     
                     For Each result As SearchResult In searcher.FindAll
     
                      DirEntry = result.GetDirectoryEntry
                       'Response.Write("Nom : " + DirEntry.Properties("Name").value)
                       'Response.write("Os_version : " + DirEntry.Properties("operatingSystemVersion").value)
                       'Response.write(" Os : " + DirEntry.Properties("operatingSystem").value)
                       'Response.write("ServicePack :" + DirEntry.Properties("operatingSystemServicePack").value)
                        'Response.write("userPrincipalName :" + DirEntry.Properties("userPrincipalName").value)
     
     
                      nom = DirEntry.Properties("Name").value
                      'insertion des ip dans la DB.
                      Dim IPHost As IPHostEntry = Dns.Resolve(DirEntry.Properties("Name").value)
                      Dim addressList As IPAddress() = IPHost.AddressList
                      Dim b As IPAddress = addressList(0) ' récupère la première adresse
                      Ip = b.ToString()
     
     
                      OsVersion    =  DirEntry.Properties("operatingSystemVersion").value
                      Os           =   DirEntry.Properties("operatingSystem").value
                      ServicePack  =    DirEntry.Properties("operatingSystemServicePack").value
     
                      'Test avec WMI
     
                      'Dim co As ConnectionOptions = New ConnectionOptions()
     
             'With co
              '.Impersonation = System.Management.ImpersonationLevel.Impersonate
              '* Use next line for XP
              '.Authentication = System.Management.AuthenticationLevel.Packet
              '* Use next line for Win prior XP
              '.Authentication = System.Management.AuthenticationLevel.Connect
            'End With
     
               'co.Username = "toto"
               'co.Password = "toto"
               'Dim theScope As New ManagementScope("\\ 192.168.1.7 \root\cimv2",co)
               'Dim theQuery As New System.Management.ObjectQuery("SELECT * From Win32_OperatingSystem")
               'Dim theSearcher As New ManagementObjectSearcher(theScope, theQuery)
               'Dim theCollectionOfResults As ManagementObjectCollection = theSearcher.Get()
               'For Each currentResult As ManagementObject In theCollectionOfResults
               'reboot = currentResult("LastBootUpTime")
               'Next
     
               'Try
                'Dim time As New ManagementObject("Win32_OperatingSystem")
                'time.Get() ' throws ManagementException
                'response.write("This shouldn't be displayed.")
     
                'Catch e As ManagementException
     
                'response.Write("ErrorCode :" & e.ErrorCode)
                'response.Write("Message :" & e.Message)
                'response.Write("Source :" & e.Source)
                'If e.ErrorInformation <> Nothing Then 'extended error object
                  ' response.Write("Extended Description : " & e.ErrorInformation("Description"))
                'End If
            'End Try
     
     
     
     
        'Test avec WMI
     
     
     
     
     
                      'reboot = restart()
     
                      call restart(reboot)
     
                      'lastLoggedOnDate = ConvertLargeIntToDate(largeInteger)
                      'largeInteger = DirEntry.Properties("lastLogOn").Value
                      'lastLoggedOnDate = ConvertLargeIntToDate(largeInteger)
                      'last_logon = lastLoggedOnDate
     
     
                      'lblError.Text += nom & " - " & OsVersion & " - " & Os & " - " & ServicePack & "<br>"
                           'Dim IPHost As IPHostEntry = Dns.Resolve(DirEntry.Properties("Name").value)
                           'Dim addressList As IPAddress() = IPHost.AddressList
                           'Dim a As IPAddress = addressList(0) ' récupère la première adresse
     
                      'lblError.Text += "INSERT INTO Servers (nom,Ip,ServicePack,OsVersion,OsName) VALUES('"& nom &"','" & Ip & "','" & ServicePack &"','" & OsVersion &"', '" &  Os  &"' )" & "<br>"
                      call SQLExecuteQuery("INSERT INTO Servers (nom,Ip,Reboot,ServicePack,OsVersion,OsName) VALUES('"& nom &"','" & Ip & "','" & reboot & "','" & ServicePack &"','" & OsVersion &"', '" &  Os  &"' )")
     
                      Next
     
                      MxDataGrid1.DataBind()
     
     
             End Sub
     
             Function SQLExecuteQuery(ByVal sqlQuery As String) As String
     
                      Dim a As String
     
                      Dim objConnect As New SqlConnection("server='(local)'; trusted_connection=true; database='pspintranet'")
                      objConnect.Open()
     
                      Dim objCommand As New SqlCommand(sqlQuery, objConnect)
                      a = objCommand.ExecuteNonQuery()
                      Return a
     
             End Function
     
             Function restart (Byval reboot As Object) As Date
     
               Dim Ip As String
               Dim TestConnection As Boolean
     
     
             Dim Ldap As DirectoryEntry = New DirectoryEntry("LDAP://scoot", "toto", "toto")
             Dim searcher As DirectorySearcher = New DirectorySearcher(Ldap)
             searcher.Filter = "(objectClass=computer)"
             Dim DirEntry As DirectoryEntry
     
                      For Each result As SearchResult In searcher.FindAll
                      DirEntry = result.GetDirectoryEntry
     
                      Dim IPHost As IPHostEntry = Dns.Resolve(DirEntry.Properties("Name").value)
                      Dim addressList As IPAddress() = IPHost.AddressList
                      Dim b As IPAddress = addressList(0) ' récupère la première adresse
                      Ip = b.ToString()
                      Next
     
             Dim co As ConnectionOptions = New ConnectionOptions()
     
           With co
            .Impersonation = System.Management.ImpersonationLevel.Impersonate
            '* Use next line for XP
            .Authentication = System.Management.AuthenticationLevel.Packet
            '* Use next line for Win prior XP
            '.Authentication = System.Management.AuthenticationLevel.Connect
           End With
     
            co.Username = "toto"
            co.Password = "toto"
     
           'For Each result As SearchResult In searcher.FindAll
     
              'TestConnection = theScope.IsConnected
     
            ' ici je tente de me connecter aux machine de mon réseau
            Dim theScope As New ManagementScope("\\ + Ip +  \root\cimv2",co)
            TestConnection = theScope.IsConnected
     
            if TestConnection = false Then
     
                response.write("Machines :" & Ip)
     
                Else
     
               'For Each currentResult As ManagementObject In theCollectionOfResults
     
            Dim theQuery As New System.Management.ObjectQuery("SELECT * From Win32_OperatingSystem")
            Dim theSearcher As New ManagementObjectSearcher(theScope, theQuery)
            Dim theCollectionOfResults As ManagementObjectCollection = theSearcher.Get()
            For Each currentResult As ManagementObject In theCollectionOfResults
            reboot = currentResult ("LastBootUpTime").ToString()
            'currentResult("LastBootUpTime").ToString()
            return reboot
            Next
     
            End if
     
            End Function
     
     
     
     
     
     
     
     
     
     
             'Private Function ConvertLargeIntToDate(ByVal largeInteger As Object) As Date
                  ' Dim typ As Type = largeInteger.GetType()
                   'Dim highPart As Integer = CInt(typ.InvokeMember("HighPart", Reflection.BindingFlags.GetProperty, Nothing, largeInteger, Nothing))
                   'Dim lowPart As Integer = CInt(typ.InvokeMember("LowPart", Reflection.BindingFlags.GetProperty, Nothing, largeInteger, Nothing))
                   'Dim fileTime As Int64 = Convert.ToInt64(highPart * (2 ^ 32))
                   'Return (DateTime.FromFileTime(fileTime))
               'End Function
     
     
     
     
             Sub Button1_Click(sender As Object, e As EventArgs)
              'txtPing.Text = Nothing
              'pingopts.Ttl = Convert.ToInt32(txtTTL.Text)
     
             Dim ping As Ping = New Ping()
             Dim pingreply As PingReply = ping.Send(TextBox1.Text)
                 response.write("Reply from : " & TextBox1.Text)
                 Response.Write("<br>")
                 Response.Write("<br>")
                 response.write("Time :" & pingreply.RoundtripTime)
                 Response.Write("<br>")
                 Response.Write("<br>")
                 'response.write("TTL :" &  Pingreplay.Ttl.ToString())
                 'Response.Write("<br>")
                 'Response.Write("<br>")
                 response.write("Buffer Size :" & pingreply.Buffer.Length.ToString())
                 Response.Write("<br>")
                 Response.Write("<br>")
     
     
     
     
     
             End Sub
     
        Sub Button2_Click(sender As Object, e As EventArgs)
     
            Dim Sql As String
            'Sql = "INSERT INTO Servers (nom, Ip, Reboot, ServicePack, OsVersion, OsName, FreeSpace_Go) "
            'Sql += "VALUES ( 'TAMAC01', 'Ip', '20020101', 'ServicePack','OsVersion', 'OsName', 200)"
     
            Sql = "UPDATE Servers SET FreeSpace_Go=250 WHERE nom = 'TAMACIT' "
            SQLExecuteQueryConnect(Sql, SqlDataSourceControl2.ConnectionString)
     
        End Sub
     
        Function SQLExecuteQueryConnect(ByVal sqlQuery As String, sqlConnect as String) As String
     
                 Dim a As String
                 ' CREER LA CONNEXION
                 Dim objConnect As New SqlConnection(sqlConnect)
                 objConnect.Open()
     
                 ' CREER LA COMMANDE
                 Dim objCommand As New SqlCommand(sqlQuery, objConnect)
                 ' EXECUTER LA COMMANDE
                 a = objCommand.ExecuteNonQuery()
                 Return a
     
         End Function
     
    </script>
    <html>
    <head>
    </head>
    <body>
        <form runat="server">
            <p>
                <wmx:SqlDataSourceControl id="SqlDataSourceControl2" runat="server" DeleteCommand="" UpdateCommand=""></wmx:SqlDataSourceControl>
                <wmx:MxDataGrid id="MxDataGrid1" runat="server" AllowPaging="False" AllowSorting="True" CellPadding="3" DataKeyField="nom_id" DataSourceControlID="SqlDataSourceControl2" DataMember="Servers" BackColor="White" BorderColor="#CCCCCC" BorderWidth="1px" BorderStyle="None">
                    <FooterStyle backcolor="White" forecolor="#000066"></FooterStyle>
                    <HeaderStyle backcolor="#006699" font-bold="True" forecolor="White"></HeaderStyle>
                    <ItemStyle forecolor="#000066"></ItemStyle>
                    <PagerStyle mode="NumericPages" horizontalalign="Center" backcolor="White" forecolor="#000066"></PagerStyle>
                    <SelectedItemStyle backcolor="#669999" font-bold="True" forecolor="White"></SelectedItemStyle>
                </wmx:MxDataGrid>
                <asp:Label id="lblError" runat="server"></asp:Label>&nbsp;&nbsp;&nbsp;
            </p>
            <p>
            </p>
            <p>
            </p>
            <p>
            </p>
            <p>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
            </p>
            <p>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Ping"></asp:Button>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <asp:Button id="Button2" onclick="Button2_Click" runat="server" Text="Udate"></asp:Button>
            </p>
            <p>
            </p>
        </form>
    </body>
    </html>

  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 fonction restart fonctionne peut-être correctement, c'est la façon dont tu renvoies son resultat qui ne va pas. Ca ne sert à rien de renvoyer une valeur ET de la passer par un paramètre de sortie. Dans un cas comme ça, le paramètre de sortie ne sert à rien, d'ailleurs il faudrait le déclarer en ByRef pour que la fonction puisse le modifier.

    D'autre part, le mot clé Call est inutile (et ce depuis très longtemps, au moins depuis VB6 si je ne me trompe pas...).

    Enfin, il faut que tu récupères la valeur de retour de la fonction restart.

    Ah, et aussi, utilise DateTime plutôt que Date (qui est un ancien type de données héritées des versions pré-.NET de VB)

    Au final, tu peux déclarer restart comme ça :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    Function restart() As DateTime
    ...
        Return Convert.ToDateTime(currentResult ("LastBootUpTime"))
    End Function
    Et l'appeler comme ça :


    Sinon, il faudrait passer en paramètre la machine dont tu veux récupérer l'heure de reboot, sinon ça va toujours récupérer les infos de la même machine... d'autre part, cette ligne n'a aucun sens :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Dim theScope As New ManagementScope("\\ + Ip +  \root\cimv2",co)
    Tu as mis "+ IP +" à l'intérieur de la chaine, donc ça va être interprété tel quel, et ça va essayer d'accéder à une machine appelée "+ IP +"...

    Fais plutôt comme ça :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Dim theScope As New ManagementScope("\\" + Ip +  "\root\cimv2",co)
    Et passe l'IP (ou le hostname) en paramètre de restart

  3. #3
    Membre confirmé
    Inscrit en
    Décembre 2006
    Messages
    158
    Détails du profil
    Informations forums :
    Inscription : Décembre 2006
    Messages : 158
    Par défaut
    Bonjour tomlev,
    je viens de tester ta solution, et apparemment il me renvoit toujours le même résultat pour toutes les machines : 01/01/1900 00:00:00 . Ce que j'essaie de faire c'est de passer en revue toutes les machines du réseau et de passer en paramètre le hostname ou l'ip de la machine. Je me demande s'il n'y a pas un disfonctionnement dans la fonction restart() ? Je vai encore continuer à checker ça pour trouver la solution. Si tu as d'autres propositions je suis toujours prenneur .
    Un grand merci pour ton aide en tout cas.
    Bien à toi.

  4. #4
    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
    tu as fait comme je t'ai dit ? fais voir le nouveau code de ta fonction restart, et la façon dont tu l'appelles

  5. #5
    Membre confirmé
    Inscrit en
    Décembre 2006
    Messages
    158
    Détails du profil
    Informations forums :
    Inscription : Décembre 2006
    Messages : 158
    Par défaut
    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
    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
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
     
    <%@ Page Language="VB" %>
    <%@ Register TagPrefix="wmx" Namespace="Microsoft.Matrix.Framework.Web.UI" Assembly="Microsoft.Matrix.Framework, Version=0.6.0.0, Culture=neutral, PublicKeyToken=6f763c9966660626" %>
    <%@ import Namespace="System.Data" %>
    <%@ import Namespace="System.Data.SqlClient" %>
    <%@ import Namespace="System.Web.Mail" %>
    <%@ import Namespace="System.IO" %>
    <%@ import Namespace="System.DirectoryServices" %>
    <%@ import Namespace="System.Configuration" %>
    <%@ import Namespace="System.Net" %>
    <%@ import Namespace="System" %>
    <%@ import Namespace="System.Net.DNS" %>
    <%@ import Namespace="System.ComponentModel" %>
    <%@ import Namespace="System.Management" %>
    <%@ import Namespace="System.Runtime.InteropServices" %>
    <%@ import Namespace="System" %>
    <%@ import Namespace="ActiveDs" %>
    <%@ import Namespace="System.Text" %>
    <%@ import Namespace="System.Net.NetworkInformation" %>
    <%@ import Namespace="System.Net.Sockets" %>
    <script runat="server">
     
        ' Insert page code here
             '
     
     
              Sub Page_Load()
     
     
                     Dim Ldap As DirectoryEntry = New DirectoryEntry("LDAP://scoot.local", "toto", "toto")
                     Dim searcher As DirectorySearcher = New DirectorySearcher(Ldap)
                     searcher.Filter = "(objectClass=computer)"
                     Dim DirEntry As DirectoryEntry
                     Dim nom As String
                     Dim OsVersion As String
                     Dim Os As String
                     Dim ServicePack As String
                     Dim Ip As String
                     Dim largeInteger As Object
                     Dim lastLoggedOnDate As Date
                     Dim reboot As Date
                     Dim rebootTime As Object
     
                     SqlDataSourceControl2.ConnectionString="server='(local)'; trusted_connection=true; database='pspintranet'"
                     SqlDataSourceControl2.SelectCommand="Select * from Servers"
     
     
                     call SQLExecuteQuery("TRUNCATE TABLE Servers")
     
                     'call restart(reboot)
     
     
     
                     For Each result As SearchResult In searcher.FindAll
     
                      DirEntry = result.GetDirectoryEntry
                       'Response.Write("Nom : " + DirEntry.Properties("Name").value)
                       'Response.write("Os_version : " + DirEntry.Properties("operatingSystemVersion").value)
                       'Response.write(" Os : " + DirEntry.Properties("operatingSystem").value)
                       'Response.write("ServicePack :" + DirEntry.Properties("operatingSystemServicePack").value)
                        'Response.write("userPrincipalName :" + DirEntry.Properties("userPrincipalName").value)
     
     
                      nom = DirEntry.Properties("Name").value
                      'insertion des ip dans la DB.
                      Dim IPHost As IPHostEntry = Dns.Resolve(DirEntry.Properties("Name").value)
                      Dim addressList As IPAddress() = IPHost.AddressList
                      Dim b As IPAddress = addressList(0) ' récupère la première adresse
                      Ip = b.ToString()
     
     
                      OsVersion    =  DirEntry.Properties("operatingSystemVersion").value
                      Os           =   DirEntry.Properties("operatingSystem").value
                      ServicePack  =    DirEntry.Properties("operatingSystemServicePack").value
     
                      'Test avec WMI
     
                      'Dim co As ConnectionOptions = New ConnectionOptions()
     
             'With co
              '.Impersonation = System.Management.ImpersonationLevel.Impersonate
              '* Use next line for XP
              '.Authentication = System.Management.AuthenticationLevel.Packet
              '* Use next line for Win prior XP
              '.Authentication = System.Management.AuthenticationLevel.Connect
            'End With
     
               'co.Username = "toto"
               'co.Password = "toto"
               'Dim theScope As New ManagementScope("\\ 192.168.1.7 \root\cimv2",co)
               'Dim theQuery As New System.Management.ObjectQuery("SELECT * From Win32_OperatingSystem")
               'Dim theSearcher As New ManagementObjectSearcher(theScope, theQuery)
               'Dim theCollectionOfResults As ManagementObjectCollection = theSearcher.Get()
               'For Each currentResult As ManagementObject In theCollectionOfResults
               'reboot = currentResult("LastBootUpTime")
               'Next
     
               'Try
                'Dim time As New ManagementObject("Win32_OperatingSystem")
                'time.Get() ' throws ManagementException
                'response.write("This shouldn't be displayed.")
     
                'Catch e As ManagementException
     
                'response.Write("ErrorCode :" & e.ErrorCode)
                'response.Write("Message :" & e.Message)
                'response.Write("Source :" & e.Source)
                'If e.ErrorInformation <> Nothing Then 'extended error object
                  ' response.Write("Extended Description : " & e.ErrorInformation("Description"))
                'End If
            'End Try
     
     
     
     
        'Test avec WMI
     
     
     
     
     
                      reboot = restart()
     
                      'call restart(result("LastBootUpTime").ToString())
     
                      'lastLoggedOnDate = ConvertLargeIntToDate(largeInteger)
                      'largeInteger = DirEntry.Properties("lastLogOn").Value
                      'lastLoggedOnDate = ConvertLargeIntToDate(largeInteger)
                      'last_logon = lastLoggedOnDate
     
     
                      'lblError.Text += nom & " - " & OsVersion & " - " & Os & " - " & ServicePack & "<br>"
                           'Dim IPHost As IPHostEntry = Dns.Resolve(DirEntry.Properties("Name").value)
                           'Dim addressList As IPAddress() = IPHost.AddressList
                           'Dim a As IPAddress = addressList(0) ' récupère la première adresse
     
                      'lblError.Text += "INSERT INTO Servers (nom,Ip,ServicePack,OsVersion,OsName) VALUES('"& nom &"','" & Ip & "','" & ServicePack &"','" & OsVersion &"', '" &  Os  &"' )" & "<br>"
                      call SQLExecuteQuery("INSERT INTO Servers (nom,Ip,Reboot,ServicePack,OsVersion,OsName) VALUES('"& nom &"','" & Ip & "','" & reboot & "','" & ServicePack &"','" & OsVersion &"', '" &  Os  &"' )")
     
                      Next
     
                      MxDataGrid1.DataBind()
     
     
             End Sub
     
             Function SQLExecuteQuery(ByVal sqlQuery As String) As String
     
                      Dim a As String
     
                      Dim objConnect As New SqlConnection("server='(local)'; trusted_connection=true; database='pspintranet'")
                      objConnect.Open()
     
                      Dim objCommand As New SqlCommand(sqlQuery, objConnect)
                      a = objCommand.ExecuteNonQuery()
                      Return a
     
             End Function
             ' je passe en paramètre le hostname des différentes machines du réseau puisque je veux les passer en revues.
     
             Function restart (Byval  nom As String) As DateTime
     
               Dim Ip As String
               Dim TestConnection As Boolean
     
     
             Dim Ldap As DirectoryEntry = New DirectoryEntry("LDAP://scoot.local", "toto", "toto")
             Dim searcher As DirectorySearcher = New DirectorySearcher(Ldap)
             searcher.Filter = "(objectClass=computer)"
             Dim DirEntry As DirectoryEntry
     
                      For Each result As SearchResult In searcher.FindAll
                      DirEntry = result.GetDirectoryEntry
     
                      Dim IPHost As IPHostEntry = Dns.Resolve(DirEntry.Properties("Name").value)
                      Dim addressList As IPAddress() = IPHost.AddressList
                      Dim b As IPAddress = addressList(0) ' récupère la première adresse
                      Ip = b.ToString()
                      Next
     
             Dim co As ConnectionOptions = New ConnectionOptions()
     
           With co
            .Impersonation = System.Management.ImpersonationLevel.Impersonate
            '* Use next line for XP
            .Authentication = System.Management.AuthenticationLevel.Packet
            '* Use next line for Win prior XP
            '.Authentication = System.Management.AuthenticationLevel.Connect
           End With
     
            co.Username = "Administrator"
            co.Password = "casarca632"
     
           'For Each result As SearchResult In searcher.FindAll
     
              'TestConnection = theScope.IsConnected
     
     
            Dim theScope As New ManagementScope("\\" + Ip + \root\cimv2",co)
            TestConnection = theScope.IsConnected
     
            if TestConnection = false Then
     
                response.write("Machines :" & Ip)
     
                Else
     
            Dim theQuery As New System.Management.ObjectQuery("SELECT * From Win32_OperatingSystem")
            Dim theSearcher As New ManagementObjectSearcher(theScope, theQuery)
            Dim theCollectionOfResults As ManagementObjectCollection = theSearcher.Get()
            For Each currentResult As ManagementObject In theCollectionOfResults
            'reboot = ManagementObject("LastBootUpTime").ToString()
            'currentResult("LastBootUpTime").ToString()
            'return reboot
             Return Convert.ToDateTime(currentResult ("LastBootUpTime"))
     
            Next
     
            End if
     
            End Function
     
     
     
     
     
     
     
     
     
     
             'Private Function ConvertLargeIntToDate(ByVal largeInteger As Object) As Date
                  ' Dim typ As Type = largeInteger.GetType()
                   'Dim highPart As Integer = CInt(typ.InvokeMember("HighPart", Reflection.BindingFlags.GetProperty, Nothing, largeInteger, Nothing))
                   'Dim lowPart As Integer = CInt(typ.InvokeMember("LowPart", Reflection.BindingFlags.GetProperty, Nothing, largeInteger, Nothing))
                   'Dim fileTime As Int64 = Convert.ToInt64(highPart * (2 ^ 32))
                   'Return (DateTime.FromFileTime(fileTime))
               'End Function
     
     
     
     
             Sub Button1_Click(sender As Object, e As EventArgs)
              'txtPing.Text = Nothing
              'pingopts.Ttl = Convert.ToInt32(txtTTL.Text)
     
             Dim ping As Ping = New Ping()
             Dim pingreply As PingReply = ping.Send(TextBox1.Text)
                 response.write("Reply from : " & TextBox1.Text)
                 Response.Write("<br>")
                 Response.Write("<br>")
                 response.write("Time :" & pingreply.RoundtripTime)
                 Response.Write("<br>")
                 Response.Write("<br>")
                 'response.write("TTL :" &  Pingreplay.Ttl.ToString())
                 'Response.Write("<br>")
                 'Response.Write("<br>")
                 response.write("Buffer Size :" & pingreply.Buffer.Length.ToString())
                 Response.Write("<br>")
                 Response.Write("<br>")
     
     
     
     
     
             End Sub
     
        Sub Button2_Click(sender As Object, e As EventArgs)
     
            Dim Sql As String
            'Sql = "INSERT INTO Servers (nom, Ip, Reboot, ServicePack, OsVersion, OsName, FreeSpace_Go) "
            'Sql += "VALUES ( 'TAMAC01', 'Ip', '20020101', 'ServicePack','OsVersion', 'OsName', 200)"
     
            Sql = "UPDATE Servers SET FreeSpace_Go=250 WHERE nom = 'TAMACIT' "
            SQLExecuteQueryConnect(Sql, SqlDataSourceControl2.ConnectionString)
     
        End Sub
     
        Function SQLExecuteQueryConnect(ByVal sqlQuery As String, sqlConnect as String) As String
     
                 Dim a As String
                 ' CREER LA CONNEXION
                 Dim objConnect As New SqlConnection(sqlConnect)
                 objConnect.Open()
     
                 ' CREER LA COMMANDE
                 Dim objCommand As New SqlCommand(sqlQuery, objConnect)
                 ' EXECUTER LA COMMANDE
                 a = objCommand.ExecuteNonQuery()
                 Return a
     
         End Function
     
    </script>
    <html>
    <head>
    </head>
    <body>
        <form runat="server">
            <p>
                <wmx:SqlDataSourceControl id="SqlDataSourceControl2" runat="server" DeleteCommand="" UpdateCommand=""></wmx:SqlDataSourceControl>
                <wmx:MxDataGrid id="MxDataGrid1" runat="server" AllowPaging="False" AllowSorting="True" CellPadding="3" DataKeyField="nom_id" DataSourceControlID="SqlDataSourceControl2" DataMember="Servers" BackColor="White" BorderColor="#CCCCCC" BorderWidth="1px" BorderStyle="None">
                    <FooterStyle backcolor="White" forecolor="#000066"></FooterStyle>
                    <HeaderStyle backcolor="#006699" font-bold="True" forecolor="White"></HeaderStyle>
                    <ItemStyle forecolor="#000066"></ItemStyle>
                    <PagerStyle mode="NumericPages" horizontalalign="Center" backcolor="White" forecolor="#000066"></PagerStyle>
                    <SelectedItemStyle backcolor="#669999" font-bold="True" forecolor="White"></SelectedItemStyle>
                </wmx:MxDataGrid>
                <asp:Label id="lblError" runat="server"></asp:Label>&nbsp;&nbsp;&nbsp;
            </p>
            <p>
            </p>
            <p>
            </p>
            <p>
            </p>
            <p>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
            </p>
            <p>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Ping"></asp:Button>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <asp:Button id="Button2" onclick="Button2_Click" runat="server" Text="Udate"></asp:Button>
            </p>
            <p>
            </p>
        </form>
    </body>
    </html>

  6. #6
    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
    tu as ajouté un paramètre "nom" à la fonction restart, mais si tu ne l'utilises pas ça ne sert à rien... en plus tu appelles restart sans lui indiquer le paramètre "nom", ça ne doit même pas compiler ton truc !

    Et la boucle sur les résultats du LDAP, c'est pas dans restart que tu dois la mettre, puisque c'est la fonction qui te permet de récupérer la date de rédémarrage pour un PC donné !

    Et tu devrais réécrire entièrement ton code, il est illisible...

    Pour écrire un code propre, découpe ton problème en petits sous problèmes, et crée une fonction ou procédure pour chaque sous problème. Sinon tu ne vas jamais t'y retrouver...

Discussions similaires

  1. [VB6/mysql]:Problème d'insertion dans une bdd
    Par gaetan.tranvouez dans le forum VB 6 et antérieur
    Réponses: 5
    Dernier message: 14/06/2006, 10h15
  2. [MySQL] Problème d'insertion dans une table
    Par ph_anrys dans le forum PHP & Base de données
    Réponses: 7
    Dernier message: 06/03/2006, 17h43
  3. problème d'insertion dans une base de données
    Par belmansour tidjani dans le forum JDBC
    Réponses: 7
    Dernier message: 18/01/2006, 22h13
  4. Problème d'insertion dans une table MYSQL
    Par greg69 dans le forum Requêtes
    Réponses: 4
    Dernier message: 24/10/2005, 11h34
  5. probléme d'insert dans une page asp !
    Par tomtom25 dans le forum ASP
    Réponses: 5
    Dernier message: 31/03/2005, 16h04

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