[VB.NET] Récupérer le nom de l'instance d'un service

Récupérer le nom de l'instance d'un service [VB.NET] - VB/VBA/VBS - Programmation

Marsh Posté le 26-04-2007 à 15:10:18    

Bonjour,
 
j'ai une petite question,
j'ai créé un service en VB.NET qui est multi instance en suivant cette page: http://www.codeproject.com/dotnet/ [...] nstall.asp
 
Est-il possible de récupérer le nom de l'instance du service qui tourne pour les messages de l'event viewer par exemple ?
 
Merci

Reply

Marsh Posté le 26-04-2007 à 15:10:18   

Reply

Marsh Posté le 27-04-2007 à 11:42:21    

En fait j'ai mon service, par exemple, service1.vb:
 

Code :
  1. Public Class Service1
  2.     Protected Overrides Sub OnStart(ByVal args() As String)
  3.         EventLog.WriteEntry("Service démarré" )
  4.     End Sub
  5.     Protected Overrides Sub OnStop()
  6.         EventLog.WriteEntry("Service arrété" )
  7.     End Sub
  8. End Class


 
et service1.designer.vb:
 

Code :
  1. Imports System.ServiceProcess
  2. <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
  3. Partial Class Service1
  4.     Inherits System.ServiceProcess.ServiceBase
  5.     'UserService overrides dispose to clean up the component list.
  6.     <System.Diagnostics.DebuggerNonUserCode()> _
  7.     Protected Overrides Sub Dispose(ByVal disposing As Boolean)
  8.         If disposing AndAlso components IsNot Nothing Then
  9.             components.Dispose()
  10.         End If
  11.         MyBase.Dispose(disposing)
  12.     End Sub
  13.     ' The main entry point for the process
  14.     <MTAThread()> _
  15.     <System.Diagnostics.DebuggerNonUserCode()> _
  16.     Shared Sub Main()
  17.         Dim ServicesToRun() As System.ServiceProcess.ServiceBase
  18.         ' More than one NT Service may run within the same process. To add
  19.         ' another service to this process, change the following line to
  20.         ' create a second service object. For example,
  21.         '
  22.         '   ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
  23.         '
  24.         ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}
  25.         System.ServiceProcess.ServiceBase.Run(ServicesToRun)
  26.     End Sub
  27.     'Required by the Component Designer
  28.     Private components As System.ComponentModel.IContainer
  29.     ' NOTE: The following procedure is required by the Component Designer
  30.     ' It can be modified using the Component Designer. 
  31.     ' Do not modify it using the code editor.
  32.     <System.Diagnostics.DebuggerStepThrough()> _
  33.     Private Sub InitializeComponent()
  34.         components = New System.ComponentModel.Container()
  35.         Me.ServiceName = "Service1"
  36.     End Sub
  37. End Class


 
J'ai ajouté à ce service un class ProjectInstaller.VB pour pouvoir faire du multiinstance:
 

Code :
  1. Imports System.Collections
  2. Imports System.ComponentModel
  3. Imports System.Configuration.Install
  4. Imports System.Collections.Specialized
  5. Imports System.ServiceProcess
  6. Imports Microsoft.Win32
  7. <RunInstaller(True)> _
  8. Public Class ScriptedInstaller
  9.     Inherits Installer
  10.     'This is a custom project installer.
  11.     'Applies a unique name to the service using the /name switch.
  12.     'Sets user name and password using the /user and /password switches.
  13.     'Allows the use of a local account using the /account switch.
  14.     Private Const mServiceName As String = "MonitoredServiceExample"
  15.     Private Const mServiceDescription As String = "MonitoredServiceExample"
  16.     Private mServiceInstaller As ServiceInstaller
  17.     Private mProcessInstaller As ServiceProcessInstaller
  18.     Public Sub New()
  19.         mServiceInstaller = New ServiceInstaller
  20.         mProcessInstaller = New ServiceProcessInstaller
  21.         mProcessInstaller.Account = System.ServiceProcess.ServiceAccount.User
  22.         With mServiceInstaller
  23.             .StartType = ServiceStartMode.Manual
  24.             .ServiceName = mServiceName
  25.         End With
  26.         Installers.Add(mServiceInstaller)
  27.         Installers.Add(mProcessInstaller)
  28.     End Sub
  29.     Public Function GetContextParameter(ByVal Key As String) As String
  30.         Dim sValue As String
  31.         Try
  32.             sValue = Me.Context.Parameters(Key).ToString
  33.         Catch ex As Exception
  34.             sValue = ""
  35.         End Try
  36.         Return sValue
  37.     End Function
  38.     Protected Overrides Sub OnBeforeInstall(ByVal SavedState As IDictionary)
  39.         'This method is run before the install process.
  40.         'This method is overriden to set the following parameters:
  41.         '    service name (/name switch)
  42.         '    account type (/account switch)
  43.         '    for a user account user name (/user switch)
  44.         '    for a user account password (/password switch)
  45.         'Note that when using a user account, if the user name or password is not set,
  46.         'the installing user is prompted for the credentials to use.
  47.         Dim bIsUserAccount As Boolean = False
  48.         Dim sName As String = ""
  49.         Dim sAcct As String = ""
  50.         Dim sUsername As String = ""
  51.         Dim sPassword As String = ""
  52.         MyBase.OnBeforeInstall(SavedState)
  53.         'Decode the command line switches
  54.         sName = GetContextParameter("name" )
  55.         mServiceInstaller.ServiceName = sName
  56.         'What type of credentials to use to run the service
  57.         'The default is User
  58.         sAcct = GetContextParameter("account" )
  59.         If sAcct.Length = 0 Then
  60.             sAcct = "user"
  61.         End If
  62.         'Decode the type of account to use
  63.         Select Case sAcct
  64.             Case "user"
  65.                 mProcessInstaller.Account = ServiceAccount.User
  66.                 bIsUserAccount = True
  67.             Case "localservice"
  68.                 mProcessInstaller.Account = ServiceAccount.LocalService
  69.             Case "localsystem"
  70.                 mProcessInstaller.Account = ServiceAccount.LocalSystem
  71.             Case "networkservice"
  72.                 mProcessInstaller.Account = ServiceAccount.NetworkService
  73.             Case Else
  74.                 mProcessInstaller.Account = ServiceAccount.User
  75.                 bIsUserAccount = True
  76.         End Select
  77.         'User name and password
  78.         sUsername = GetContextParameter("user" )
  79.         sPassword = GetContextParameter("password" )
  80.         'Should I use a user account?
  81.         If bIsUserAccount Then
  82.             'If we need to use a user account, set the user name and password()
  83.             mProcessInstaller.Username = sUsername
  84.             mProcessInstaller.Password = sPassword
  85.         End If
  86.     End Sub
  87.     Public Overrides Sub Install(ByVal StateServer As IDictionary)
  88.         'Modify the registry to install the new service
  89.         Dim rkSystem As RegistryKey
  90.         'HKEY_LOCAL_MACHINE\Services\CurrentControlSet
  91.         Dim rkCurrentControlSet As RegistryKey
  92.         '...\Services
  93.         Dim rkServices As RegistryKey
  94.         '...\<Service Name>
  95.         Dim rkService As RegistryKey
  96.         '...\Parameters - this is where you can put service-specific Configuration()
  97.         Dim rkConfig As RegistryKey
  98.         Dim sImagePath As String = ""
  99.         MyBase.Install(StateServer)
  100.         'Define the registry keys
  101.         'Navigate to services
  102.         rkSystem = Registry.LocalMachine.OpenSubKey("System" )
  103.         rkCurrentControlSet = rkSystem.OpenSubKey("CurrentControlSet" )
  104.         rkServices = rkCurrentControlSet.OpenSubKey("Services" )
  105.         'Add the service
  106.         rkService = rkServices.OpenSubKey(mServiceInstaller.ServiceName, True)
  107.         'Default service description
  108.         rkService.SetValue("Description", mServiceDescription)
  109.         'Display the assembly image path and modify to add the service name
  110.         'The executable then strips the name out of the image
  111.         Console.WriteLine("ImagePath: " & CType(rkService.GetValue("ImagePath" ), String))
  112.         sImagePath = CType(rkService.GetValue("ImagePath" ), String)
  113.         sImagePath &= " -s" & mServiceInstaller.ServiceName
  114.         rkService.SetValue("ImagePath", sImagePath)
  115.         'Create a parameters subkey
  116.         rkConfig = rkService.CreateSubKey("Parameters" )
  117.         'Close keys
  118.         rkConfig.Close()
  119.         rkService.Close()
  120.         rkServices.Close()
  121.         rkCurrentControlSet.Close()
  122.         rkSystem.Close()
  123.     End Sub
  124.     Protected Overrides Sub OnBeforeUninstall(ByVal SavedState As IDictionary)
  125.         'Uninstall based on the service name
  126.         MyBase.OnBeforeUninstall(SavedState)
  127.         'Set the service name based on the command line
  128.         mServiceInstaller.ServiceName = GetContextParameter("name" )
  129.     End Sub
  130.     Public Overrides Sub Uninstall(ByVal StateServer As IDictionary)
  131.         'Modify the registry to remove the service
  132.         Dim rkSystem As RegistryKey
  133.         'HKEY_LOCAL_MACHINE\Services\CurrentControlSet
  134.         Dim rkCurrentControlSet As RegistryKey
  135.         '...\Services
  136.         Dim rkServices As RegistryKey
  137.         '...\<Service Name>
  138.         Dim rkService As RegistryKey
  139.         '...\Parameters - this is where you can put service-specific Configuration()
  140.         MyBase.Uninstall(StateServer)
  141.         'Navigate down the registry path
  142.         rkSystem = Registry.LocalMachine.OpenSubKey("System" )
  143.         rkCurrentControlSet = rkSystem.OpenSubKey("CurrentControlSet" )
  144.         rkServices = rkCurrentControlSet.OpenSubKey("Services" )
  145.         rkService = rkServices.OpenSubKey(mServiceInstaller.ServiceName, True)
  146.         'Remove the parameters key
  147.         rkService.DeleteSubKeyTree("Parameters" )
  148.         'Close keys
  149.         rkService.Close()
  150.         rkServices.Close()
  151.         rkCurrentControlSet.Close()
  152.         rkSystem.Close()
  153.     End Sub
  154. End Class


 
Avec un petit script d'installation installutil.bat:
 

Code :
  1. @echo off
  2. set SERVICE_HOME=C:\Documents and Settings\mgh\My Documents\Visual Studio 2005\Projects\InstanceName\InstanceName\bin\Debug
  3. set SERVICE_EXE=InstanceName.exe
  4. REM the following directory is for .NET 1.1, your mileage may vary
  5. set INSTALL_UTIL_HOME=C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
  6. REM Account credentials if the service uses a user account
  7. set PATH=%PATH%;%INSTALL_UTIL_HOME%
  8. cd %SERVICE_HOME%
  9. echo Installing Service...
  10. installutil /name=InstanceName1 /account=localsystem %SERVICE_EXE%
  11. REM installutil /name=InstanceName2 /account=localsystem %SERVICE_EXE%
  12. REM installutil /name=InstanceName3 /account=localsystem %SERVICE_EXE%
  13. echo Done.


 
Quand je l'installe, j'ai le bon nom de mon instance, à savoir InstanceName1 qui est donné dans mon fichier .bat
Donc dans la liste des services qui tournent, je vois bien ce nom d'instance.
Par contre, une fois que je vais dans event viewer, j'ai le nom "Service1" qui apparait, comme il est spécifié dans le fichier Service1.Designer.vb avec la ligne
 

Code :
  1. Private Sub InitializeComponent()
  2.         components = New System.ComponentModel.Container()
  3.         Me.ServiceName = "Service1"
  4.     End Sub


 
Au lieu de

Code :
  1. Me.ServiceName = "Service1"

, n'est-il pas possible de mettre autre chose qu'un nom fiche, et plutot le nom de mon instance ???
 
Merci d'avance :)

Reply

Sujets relatifs:

Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed