Monday, July 19, 2010

Gradient Form - Function

A simple function to make your form background gradient.

First you need to :

Import System.Drawing.Drawing2D

In the method New() or Load :



' Optimize Painting.
  SetStyle(ControlStyles.AllPaintingInWmPaint Or _
              ControlStyles.DoubleBuffer Or _
              ControlStyles.ResizeRedraw Or _
              ControlStyles.UserPaint, _
              True)

In the OnPaint Method :



Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
 
        'Creating a new Rectangle as similar width and height of the base form 
        Dim oRAngle As Rectangle = New Rectangle(0, 0, Me.Width, Me.Height)
 
        'Creating a new Gradient style brush.
        'Change the colors here to get different color combination.
        '"Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal" can be changed accordingly to get different styles like
        'ForwardDiagonal, Horizontal, Vertical.
        Dim oGradientBrush As Brush = New Drawing.Drawing2D.LinearGradientBrush(oRAngle, Color.Silver, Color.WhiteSmoke, Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal)
 
        'With the help of fillrectangle function drawing rectangle in to form
        e.Graphics.FillRectangle(oGradientBrush, oRAngle)
 
End Sub


Or if you want a function to use for your controls :



Private Function DrawGradientBackground(ByVal Ctrl As Control, ByVal color1 As Color, ByVal color2 As Color, ByVal mode As System.Drawing.Drawing2D.LinearGradientMode) As Boolean
    Try
        Dim a As New System.Drawing.Drawing2D.LinearGradientBrush(New RectangleF(0, 0, Ctrl.Width, Ctrl.Height), color1, color2, mode)
        Dim g As Graphics = Ctrl.CreateGraphics
        g.FillRectangle(a, New RectangleF(0, 0, Ctrl.Width, Ctrl.Height))
        g.Dispose()
        Return True
    Catch ex As Exception
        MsgBox("Error Creating Gradient!" + Environment.NewLine + ex.Message)
        Return False
    End Try
End Function

VB.NET Is Admin Function

Did you ever want to know if the user has Administrator rights?
Some programs rely on the user to be an administrator, this simple function does just that.

Credits Digital Thunder : http://www.codeproject.com/KB/vb/SysInfo.aspx

Imports System.Security.Principal
Imports System.Threading
 
' A function to return the Admin status of the user running our program.
   Public Function IsAdmin() As Boolean
 
       IsAdmin = False
       Dim securityGroup As WindowsPrincipal
 
       ' Get the security credentials of the user that is running our program.
       AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
       securityGroup = CType(Thread.CurrentPrincipal, WindowsPrincipal)
 
       ' Are they a member of the Administrators Group?
       If securityGroup.IsInRole(WindowsBuiltInRole.Administrator) Then
           IsAdmin = True
       End If
       Return IsAdmin
 
   End Function

Retrieve Windows Product Key Function

I found a nice little function to retrieve the Windows Product Key.
Credits go to Digital Thunder : http://www.codeproject.com/KB/vb/SysInfo.aspx

' Usage : GetProductKey("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\")
' A function that retrieves the product key used to install Windows.
 
    Public Function GetProductKey(ByVal regKey As String) As String
 
        ' This function will retreive the digital product ID from the registry 
        ' and decode it into the CD key used to install a Microsoft product.
        ' All that is needed is the registry path to the digital proudct ID block
        ' for the product in question.
 
        Dim validChars() As String = {"B", "C", "D", "F", "G", "H", "J", "K", "M", _
                                      "P", "Q", "R", "T", "V", "W", "X", "Y", "2", _
                                      "3", "4", "6", "7", "8", "9"}
        Dim CDKey As String = ""
 
        Dim encodedKey(15) As Byte
        Dim digitalProductID As Byte()
        Dim dpidDataBlock As Object
 
        ' Get the Digital Product ID data-block from the registry.
        dpidDataBlock = My.Computer.Registry.GetValue(regKey, "DigitalProductId", 0)
 
        If dpidDataBlock Is Nothing Then Return "Not Available"
 
        digitalProductID = DirectCast(dpidDataBlock, Byte())
 
        ' Extract the encoded CD key (15 bytes) from the digital product ID block.
        For n As Integer = 52 To 67
            encodedKey(n - 52) = digitalProductID(n)
        Next
 
        ' Decode the CD key.
        ' Note: The actual CD key is not stored in the registry; only the positions  
        ' within the validChars() array of the characters that make up the CD key
        ' are stored and encoded.
 
        For i As Integer = 28 To 0 Step -1
            ' Calculate where the dashes are.
            If ((i + 1) Mod 6) = 0 Then
                CDKey += " - "
            Else
                Dim j As Integer = 0
                For k As Integer = 14 To 0 Step -1
                    Dim Value As Integer = CInt(CLng(j * 2 ^ 8) Or encodedKey(k))
                    encodedKey(k) = CByte(Value \ 24)
                    ' Position within the validChar() array of the character to add to the CD key string.
                    j = Value Mod 24
                Next
                CDKey += validChars(j)
            End If
        Next
        Return StrReverse(CDKey)
 
    End Function

Monday, July 12, 2010

Service Management Controller Class

This is a nice class the manage services local or remote.

Provides the ability to view information install/remove/start/stop/pause/restart and change the startup type of services on a local or remote machine.

Imports System.Collections.Generic
Imports System.ServiceProcess
Imports System.Management
Imports System.Runtime.InteropServices
 
 
''' <summary>
''' ServiceManagementController is an object that will control/display/manage Services
''' </summary>
''' <remarks></remarks>
Public Class ServiceManagementController
 
#Region "Values for Services"
 
    <DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
    Public Shared Function OpenSCManager(ByVal sMachineName As String, ByVal sDbName As String, ByVal iAccess As Integer) As IntPtr
    End Function
    <DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
    Public Shared Function CreateService(ByVal hSCM As IntPtr, ByVal sName As String, ByVal sDisplay As String, ByVal iAccess As Integer, ByVal iServiceType As Integer, ByVal iStartType As Integer, ByVal iError As Integer, ByVal sPath As String, ByVal sGroup As String, ByVal iTag As Integer, ByVal sDepends As String, ByVal sUser As String, ByVal sPass As String) As IntPtr
    End Function
    <DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
    Public Shared Function CloseServiceHandle(ByVal iHandle As IntPtr) As Integer
    End Function
    <DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
    Public Shared Function OpenService(ByVal hSCM As IntPtr, ByVal sServiceName As String, ByVal iDesiredAccess As Integer) As IntPtr
    End Function
    <DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
    Public Shared Function DeleteService(ByVal hService As IntPtr) As Boolean
    End Function
 
    Private Enum ServiceControlManagerEnum
        Connect = &H1
        CreateService = &H2
        EnumerateService = &H4
        Lock = &H8
        QueryLockStatus = &H10
        ModifyBootConfig = &H20
        AllAccess = (StandardRightsRequired Or Connect Or ServiceControlManagerEnum.CreateService Or EnumerateService Or ServiceControlManagerEnum.Lock Or QueryLockStatus Or ModifyBootConfig)
        StandardRightsRequired = &HF0000
    End Enum
    Private Enum ServiceAccessTypeEnum
        QueryConfig = &H1
        ChangeConfig = &H2
        QueryStatus = &H4
        EnumerateDependents = &H8
        Start = &H10
        [Stop] = &H20
        PauseContinue = &H40
        Interrogate = &H80
        UserDefinedControl = &H100
        AllAccess = (StandardRightsRequired Or QueryConfig Or ChangeConfig Or QueryStatus Or EnumerateDependents Or Start Or [Stop] Or PauseContinue Or Interrogate Or UserDefinedControl)
        StandardRightsRequired = &HF0000
    End Enum
    Private Enum ServiceTypeEnum
        Win32OwnProcess = &H10
        AutoStart = &H2
        ErrorNormal = &H1
    End Enum
    Private Enum ServiceControlTypeEnum
        OwnProcess = &H10
        ShareProcess = &H20
        KernelDriver = &H1
        FileSystemDriver = &H2
        InteractiveProcess = &H100
    End Enum
    Private Const c_sBefore As String = "<IDEAConfiguration><Group><Name>Global</Name><BATList uselist=""No""/>"
    Private Const c_sAfter As String = "</Group></IDEAConfiguration>"
 
#End Region
 
#Region "Properties"
    Private exceptioncaught As Integer
    ''' <summary>
    ''' Sorted Dictionary of all services on selected machine
    ''' </summary>
    ''' <remarks>Service DisplayName, ServiceObject</remarks>
    Private dicServiceObjects As New SortedDictionary(Of String, ServiceObject)
    Public Property ServiceObjects() As SortedDictionary(Of String, ServiceObject)
        Get
            Return dicServiceObjects
        End Get
        Set(ByVal value As SortedDictionary(Of String, ServiceObject))
            dicServiceObjects = value
        End Set
    End Property
 
    Private strMachineName As String
    Public Property MachineName() As String
        Get
            Return strMachineName
        End Get
        Set(ByVal value As String)
            strMachineName = value
        End Set
    End Property
 
#End Region
 
#Region "Constructor"
 
    Public Sub New(ByVal MachineName As String)
        Me.MachineName = MachineName
        GetServicesInfo()
    End Sub
 
#End Region
 
#Region "Private Methods"
 
 
    Private Sub GetServicesInfo()
        Dim ServObj As ServiceObject = Nothing
        Try
            ' Create a new ManagementClass object binded to the Win32_Service WMI class
            Dim mcServices As New ManagementClass("\\" & Me.MachineName & "\root\cimv2:Win32_Service")
 
            ' Loop through each service
            For Each moService As ManagementObject In mcServices.GetInstances()
 
 
                Dim PropList As New Dictionary(Of String, String)
                Dim test As PropertyDataCollection = mcServices.Properties
                For Each prop As PropertyData In test
                    Dim value As String
                    Try
                        value = moService.GetPropertyValue(prop.Name).ToString()
                    Catch ex As Exception
                        value = ""
                    End Try
                    PropList.Add(prop.Name, value)
                Next
                ServObj = New ServiceObject(Me, PropList("Name"))
                With ServObj
                    .DisplayName = PropList("Caption")
                    .Status = PropList("State")
                    .Path = PropList("PathName")
                    .StartUp = PropList("StartMode")
                    .Description = PropList("Description")
                    ' .Name = PropList("Name")
                End With
 
                If Not ServiceObjects.ContainsKey(ServObj.DisplayName) Then
                    ServiceObjects.Add(ServObj.DisplayName, ServObj)
                End If
 
            Next
        Catch ex As Exception
            MsgBox("Error retrieving services check the access rights." + vbCrLf + GetErrorInfo(ex))
        End Try
 
    End Sub
 
    Public Function InstallService(ByVal ServiceName As String, ByVal displayName As String, ByVal PathtoExecutable As String, Optional ByVal UserName As String = Nothing, Optional ByVal password As String = Nothing, Optional ByVal StartService As Boolean = True) As Boolean
        Try
 
            'Dim sUserID As String = sDomainName & "\" & sUserID
            'Dim sPassword As String = sPassword
            'put nothing if System account needed
            If IsServiceInstalled(ServiceName) Then _
               UninstallService(ServiceName)
 
            ' INSTALL
            Dim hSCM As IntPtr = OpenSCManager(Me.MachineName, Nothing, _
               ServiceControlManagerEnum.AllAccess)
            If hSCM.ToInt32 = 0 Then
                MsgBox("Could not install service. [1]")
                Return False
            Else
                Dim iServiceType As Integer = ServiceTypeEnum.Win32OwnProcess
 
                Dim hService As IntPtr = CreateService(hSCM, ServiceName, _
                   ServiceName, ServiceControlManagerEnum.AllAccess, _
                      iServiceType, ServiceTypeEnum.AutoStart, _
                      ServiceTypeEnum.ErrorNormal, PathtoExecutable, Nothing, Nothing, _
                      Nothing, UserName, password)
                If hService.ToInt32 = 0 Then
                    MsgBox("Could not install service. [2]")
                    Return False
                Else
                    CloseServiceHandle(hService)
                End If
 
                CloseServiceHandle(hSCM)
 
                If StartService = True Then
                    Call ControlServices(ServiceName, "Start")
                End If
 
            End If
            Return True
        Catch ex As Exception
            MsgBox("Error occured while trying to install service : " + ServiceName + GetErrorInfo(ex))
        End Try
    End Function
 
    Public Function UninstallService(ByVal ServiceName As String) As Boolean
 
        If IsServiceInstalled(ServiceName) Then
            ' STOP SERVICE
            Call ControlServices(ServiceName, "Stop")
        Else
            Return False
            Exit Function
        End If
 
        Dim hSCM As IntPtr = OpenSCManager(Me.MachineName, Nothing, ServiceControlManagerEnum.AllAccess)
        If hSCM.ToInt32 = 0 Then
            MsgBox("Could not delete service. [1]")
            Return False
        Else
            Dim hService As IntPtr = OpenService(hSCM, ServiceName, ServiceAccessTypeEnum.AllAccess)
            If hService.ToInt32 = 0 Then
                ' TODO: FAILED
                MsgBox("Unable to Delete Service : " + ServiceName)
                Return False
            Else
                If Not DeleteService(hService) Then
                    MsgBox("Could not delete service. [2]")
                    Return False
                End If
 
                CloseServiceHandle(hService)
            End If
 
            CloseServiceHandle(hSCM)
        End If
        Return True
    End Function
 
    Private Function IsServiceInstalled(ByVal sServiceName As String) As Boolean
        Dim bResult As Boolean = False
 
        Dim oServiceArray() As ServiceProcess.ServiceController
        oServiceArray = ServiceProcess.ServiceController.GetServices(Me.MachineName)
 
        For Each oServiceController As ServiceProcess.ServiceController In oServiceArray
            If oServiceController.ServiceName.Trim.ToUpper = sServiceName.Trim.ToUpper Then
                Dim i As New ServiceControllerPermissionAttribute(Security.Permissions.SecurityAction.Demand)
                Dim d As New ServiceControllerPermission
                Try
                    If Security.Permissions.ResourcePermissionBase.Any Then
                        d.ToString()
                    End If
                Catch
                End Try
                bResult = True
                Exit For
            End If
        Next
 
        Return bResult
    End Function
 
    Private Function CheckStatusOfService(ByVal ServiceName As String, ByVal MachineName As String) As Boolean
        Dim Status As Boolean = False
        Dim objWinServ As New ServiceController
        objWinServ.ServiceName = ServiceName
        objWinServ.MachineName = MachineName
 
        'If the service is stopped then the button to start it needs to be enabled
        If objWinServ.Status = ServiceControllerStatus.Stopped Then
            Status = True
        End If
 
        Return Status
    End Function
 
 
    Private Sub ControlServices(ByVal ServiceName As String, ByVal sTask As String)
        Dim Status As String = ""
        Dim objWinServ As New ServiceController
        Dim sServiceName As String = ServiceName
 
        objWinServ.MachineName = Me.MachineName
 
        objWinServ.ServiceName = sServiceName
 
        Try
 
            Select Case sTask
 
                Case "Reset"
                    If objWinServ.Status = ServiceControllerStatus.Running Then
                        'Service is currently running, so you will have to stop it before starting it
                        'First stop all it's child services, then stop the service itself
                        Call CheckForChildServices(sServiceName, "Stop")
                    End If
 
                    If objWinServ.Status = ServiceControllerStatus.Stopped Then 'This is satisfied if the service was running and then was stopped by code or if it was already stopped
                        'service is already stopped so just start it...so first start all it's parent services
                        Call CheckForParentServices(sServiceName, "Start")
                        ServiceStart(objWinServ.DisplayName)
                    End If
 
                Case "Start"
                    If objWinServ.Status = ServiceControllerStatus.Stopped Then 'This is satisfied if the service was running and then was stopped by code or if it was already stopped
                        Call CheckForParentServices(sServiceName, "Start")
                        If Not exceptioncaught = 0 Then
                            MsgBox("Could not Start " & objWinServ.DisplayName)
                            exceptioncaught = 0
                        End If
                    End If
 
                Case "Stop"
                    If objWinServ.Status <> ServiceControllerStatus.Stopped Then
                        Call CheckForChildServices(sServiceName, "Stop")
                        If Not exceptioncaught = 0 Then
                            MsgBox("Could not Stop " & objWinServ.DisplayName)
                            exceptioncaught = 0
                        End If
                    End If
                Case "Pause"
                    If objWinServ.Status = ServiceControllerStatus.Paused Then
                        Call CheckForParentServices(sServiceName, "Start")
                    Else
                        Call CheckForChildServices(sServiceName, "Pause")
                        'ServicePause()
                    End If
 
            End Select
        Catch ex As System.InvalidOperationException
            MsgBox("Service does not exist" + vbCrLf + GetErrorInfo(ex))
            Exit Sub
        Catch e As Exception
            MsgBox(GetErrorInfo(e))
            Exit Sub
        End Try
    End Sub
 
    Private Sub CheckForParentServices(ByVal ServiceName As String, ByVal NextService As String)
        Dim objService As New ServiceController
        objService.ServiceName = ServiceName
        objService.MachineName = Me.MachineName
 
        Dim objParentService As ServiceController
 
        For Each objParentService In objService.ServicesDependedOn
            CheckForParentServices(objParentService.DisplayName, NextService)
        Next
        If NextService = "Start" Then
            Call ServiceStart(ServiceName)
        ElseIf NextService = "Pause" Then
            Call ServicePause(ServiceName)
        End If
 
    End Sub
 
    Private Sub CheckForChildServices(ByVal ServiceName As String, ByVal NextService As String)
        Dim objService As New ServiceController
        objService.ServiceName = ServiceName
        objService.MachineName = Me.MachineName
        Dim objChildService As ServiceController
 
        For Each objChildService In objService.DependentServices
            CheckForChildServices(objChildService.DisplayName, NextService)
        Next
 
        If NextService = "Stop" Then
            Call ServiceStop(ServiceName)
        ElseIf NextService = "Pause" Then
            Call ServicePause(ServiceName)
        Else
            Call ContinueService(ServiceName)
        End If
 
    End Sub
 
    Private Function ServiceStart(Optional ByVal ServiceName As String = "") As Boolean
        Dim objService As New ServiceController
        objService.MachineName = Me.MachineName
 
        objService.ServiceName = ServiceName
 
 
 
        If objService.Status = ServiceControllerStatus.Stopped Then
            Try
                objService.Start()
                objService.WaitForStatus(ServiceControllerStatus.Running, System.TimeSpan.FromSeconds(20))
            Catch ex As TimeoutException
                MsgBox("Could not Start " & ServiceName & " - TimeOut expired" & GetErrorInfo(ex))
                Return False
            Catch e As Exception
                MsgBox("Could not Start " & ServiceName & GetErrorInfo(e))
                Return False
            End Try
        ElseIf objService.Status = ServiceControllerStatus.Paused Then
            Call ContinueService(objService.ServiceName)
        End If
        Return True
    End Function
 
    Private Function ServiceStop(Optional ByVal ServiceName As String = "") As Boolean
        Dim objService As New ServiceController
        objService.MachineName = Me.MachineName
        objService.ServiceName = ServiceName
 
        If objService.Status = ServiceControllerStatus.Running Then
            Try
                objService.Stop()
                objService.WaitForStatus(ServiceControllerStatus.Stopped, System.TimeSpan.FromSeconds(20))
            Catch ex As TimeoutException
                MsgBox("Could not Stop " & ServiceName & " - TimeOut expired" & GetErrorInfo(ex))
                Return False
            Catch e As Exception
                MsgBox("Could not Stop " & ServiceName & GetErrorInfo(e))
                Return False
            End Try
        End If
        Return True
    End Function
 
    Private Function ServicePause(ByVal ServiceName As String) As Boolean
        Dim objService As New ServiceController
        objService.MachineName = Me.MachineName
        objService.ServiceName = ServiceName
 
        If objService.Status = ServiceControllerStatus.Paused Then
            Try
                objService.Continue()
                objService.WaitForStatus(ServiceControllerStatus.Running, System.TimeSpan.FromSeconds(20))
            Catch ex As TimeoutException
                MsgBox("Could not change status from Paused To Continue for " & ServiceName & " - TimeOut expired" + GetErrorInfo(ex))
                Return False
            Catch e As Exception
                MsgBox("Could not change status from Paused To Continue for " & ServiceName & " - " + GetErrorInfo(e))
                Return False
            End Try
        ElseIf objService.Status = ServiceControllerStatus.Stopped Then
            Call ControlServices(ServiceName, "Start")
        ElseIf objService.Status = ServiceControllerStatus.Running Then
            Try
                objService.Pause()
                objService.WaitForStatus(ServiceControllerStatus.Paused, System.TimeSpan.FromSeconds(20))
            Catch ex As TimeoutException
                MsgBox("Could not change status from Running To Paused for " & ServiceName & " - TimeOut expired" + GetErrorInfo(ex))
                Return False
            Catch e As Exception
                MsgBox("Could not change status from Running To Paused for " & ServiceName & " - " + GetErrorInfo(e))
                Return False
            End Try
 
        End If
        Return True
    End Function
 
    Private Sub ContinueService(ByVal ServiceName As String)
        Dim objService As New ServiceController
        objService.ServiceName = ServiceName
        objService.MachineName = Me.MachineName
        If objService.Status = ServiceControllerStatus.Paused Then
            Try
                objService.[Continue]()
                objService.WaitForStatus(ServiceControllerStatus.Running, System.TimeSpan.FromSeconds(20))
            Catch ex As TimeoutException
 
                Console.WriteLine("Could not change status from Paused To Continue for " & ServiceName & " - TimeOut expired")
            Catch e As Exception
 
                Console.WriteLine("Could not change status from Paused To Continue for " & ServiceName & " - " & e.Message)
            End Try
        End If
 
        If objService.Status = ServiceControllerStatus.Stopped Then
            Call ServiceStop(ServiceName)
        End If
 
    End Sub
#End Region
 
#Region "Public Methods"
    Public Sub StartService(ByVal ServiceName As String)
        Me.ControlServices(ServiceName, "Start")
    End Sub
 
    Public Sub StopService(ByVal ServiceName As String)
        Me.ControlServices(ServiceName, "Stop")
    End Sub
 
    Public Sub PauseService(ByVal ServiceName As String)
        Me.ControlServices(ServiceName, "Pause")
    End Sub
 
    Public Sub RestartService(ByVal ServiceName As String)
        Me.ControlServices(ServiceName, "Reset")
    End Sub
#End Region
 
#Region "ServiceObject"
 
    ''' <summary>
    ''' Service Object is used to store all information about a specific service
    ''' </summary>
    ''' <remarks></remarks>
    Public Class ServiceObject
        Private exceptioncaught As Integer
        Private objWinServ As New ServiceController
 
        Public Sub New(ByVal ParentObject As ServiceManagementController, ByVal ServiceName As String)
            Me.Parent = ParentObject
            Me.Name = ServiceName
            objWinServ.MachineName = Me.Parent.MachineName
            objWinServ.ServiceName = Me.Name
        End Sub
 
#Region "Properties"
 
        Private objParent As ServiceManagementController
        Public Property Parent() As ServiceManagementController
            Get
                Return objParent
            End Get
            Set(ByVal value As ServiceManagementController)
                objParent = value
            End Set
        End Property
 
        Private strName As String
        Public Property Name() As String
            Get
                Return strName
            End Get
            Set(ByVal value As String)
                strName = value
            End Set
        End Property
 
        Private strDisplayName As String
        Public Property DisplayName() As String
            Get
                Return strDisplayName
            End Get
            Set(ByVal value As String)
                strDisplayName = value
            End Set
        End Property
 
        Private strDescription As String
        Public Property Description() As String
            Get
                Return strDescription
            End Get
            Set(ByVal value As String)
                strDescription = value
            End Set
        End Property
 
        Private strPath As String
        Public Property Path() As String
            Get
                Return strPath
            End Get
            Set(ByVal value As String)
                strPath = value
            End Set
        End Property
 
        Private strStartUp As String
        Public Property StartUp() As String
            Get
                Return strStartUp
            End Get
            Set(ByVal value As String)
                strStartUp = value
            End Set
        End Property
 
        Private strStatus As String
        Public Property Status() As String
            Get
                Return strStatus
            End Get
            Set(ByVal value As String)
                strStatus = value
            End Set
        End Property
 
#End Region
 
#Region "Public Methods"
 
        Public Sub StartService()
            Me.ControlServices("Start")
        End Sub
 
        Public Sub StopService()
            Me.ControlServices("Stop")
        End Sub
 
        Public Sub PauseService()
            Me.ControlServices("Pause")
        End Sub
 
        Public Sub RestartService()
            Me.ControlServices("Reset")
        End Sub
 
        Public Sub ChangeStartupMode(ByVal StartUp As String)
            Try
 
                Dim path As String = "\\" & Me.Parent.MachineName & "\root\cimv2:Win32_Service.Name='" & Me.Name & "'"
                Dim p As New ManagementPath(path)
                'construct the management object
                Dim ManagementObj As New ManagementObject(p)
                'we will use the invokeMethod method of the ManagementObject class
                Dim parameters As Object() = New Object(0) {}
                parameters(0) = StartUp
                ManagementObj.InvokeMethod("ChangeStartMode", parameters)
            Catch ex As Exception
                MsgBox("Error occured while trying to set StartUp Mode" + vbCrLf + "Check if you have the necessary access rights!" + GetErrorInfo(ex))
            End Try
 
 
        End Sub
 
 
 
#End Region
 
#Region "Private Methods"
 
        Private Sub ControlServices(ByVal sTask As String)
            Dim Status As String = ""
            'Dim objWinServ As New ServiceController
            Dim sServiceName As String = Me.Name
 
            'objWinServ.MachineName = Me.Parent.MachineName
 
            'objWinServ.ServiceName = sServiceName
 
            Try
 
                Select Case sTask
 
                    Case "Reset"
                        If objWinServ.Status = ServiceControllerStatus.Running Then
                            'Service is currently running, so you will have to stop it before starting it
                            'First stop all it's child services, then stop the service itself
                            Call CheckForChildServices(sServiceName, "Stop")
                        End If
 
                        If objWinServ.Status = ServiceControllerStatus.Stopped Then 'This is satisfied if the service was running and then was stopped by code or if it was already stopped
                            'service is already stopped so just start it...so first start all it's parent services
                            Call CheckForParentServices(sServiceName, "Start")
                            ' ServiceStart(objWinServ.ServiceName)
                        End If
 
                    Case "Start"
                        If objWinServ.Status = ServiceControllerStatus.Stopped Then 'This is satisfied if the service was running and then was stopped by code or if it was already stopped
                            Call CheckForParentServices(sServiceName, "Start")
                            If Not exceptioncaught = 0 Then
                                MsgBox("Could not Start " & objWinServ.DisplayName)
                                exceptioncaught = 0
                            End If
                        End If
 
                    Case "Stop"
                        If objWinServ.Status <> ServiceControllerStatus.Stopped Then
                            Call CheckForChildServices(sServiceName, "Stop")
                            If Not exceptioncaught = 0 Then
                                MsgBox("Could not Stop " & objWinServ.DisplayName)
                                exceptioncaught = 0
                            End If
                        End If
                    Case "Pause"
                        If objWinServ.Status = ServiceControllerStatus.Paused Then
                            Call CheckForParentServices(sServiceName, "Start")
                        Else
                            Call CheckForChildServices(sServiceName, "Pause")
                            'ServicePause()
                        End If
 
                End Select
            Catch ex As System.InvalidOperationException
                MsgBox("Service does not exist" + vbCrLf + GetErrorInfo(ex))
                Exit Sub
            Catch e As Exception
                MsgBox(GetErrorInfo(e))
                Exit Sub
            End Try
        End Sub
 
        Private Function ServiceStart(Optional ByVal ServiceName As String = "") As Boolean
            'Dim objService As New ServiceController
            'objService.MachineName = Me.Parent.MachineName
            If ServiceName = "" Then
                objWinServ.ServiceName = Me.Name
            Else
                objWinServ.ServiceName = ServiceName
            End If
 
 
            If objWinServ.Status = ServiceControllerStatus.Stopped Then
                Try
                    objWinServ.Start()
                    objWinServ.WaitForStatus(ServiceControllerStatus.Running, System.TimeSpan.FromSeconds(20))
                Catch ex As TimeoutException
                    MsgBox("Could not Start " & Me.Name & " - TimeOut expired" & GetErrorInfo(ex))
                    Return False
                Catch e As Exception
                    MsgBox("Could not Start " & Me.Name & GetErrorInfo(e))
                    Return False
                End Try
            ElseIf objWinServ.Status = ServiceControllerStatus.Paused Then
                Call ContinueService(objWinServ.ServiceName)
            End If
            Return True
        End Function
 
        Private Function ServiceStop(Optional ByVal ServiceName As String = "") As Boolean
            ' Dim objService As New ServiceController
            '  objService.MachineName = Me.Parent.MachineName
            If ServiceName = "" Then
                objWinServ.ServiceName = Me.Name
            Else
                objWinServ.ServiceName = ServiceName
            End If
 
 
            If objWinServ.Status = ServiceControllerStatus.Running Then
                Try
                    objWinServ.Stop()
                    objWinServ.WaitForStatus(ServiceControllerStatus.Stopped, System.TimeSpan.FromSeconds(20))
 
                Catch ex As TimeoutException
                    MsgBox("Could not Stop " & Me.Name & " - TimeOut expired" & GetErrorInfo(ex))
                    Return False
                Catch e As Exception
                    MsgBox("Could not Stop " & Me.Name & GetErrorInfo(e))
                    Return False
                End Try
            End If
            Return True
        End Function
 
        Private Function ServicePause() As Boolean
            'Dim objService As New ServiceController
            '  objService.MachineName = Me.Parent.MachineName
            ' objService.ServiceName = Me.Name
 
            If objWinServ.Status = ServiceControllerStatus.Paused Then
                Try
                    objWinServ.Continue()
                    objWinServ.WaitForStatus(ServiceControllerStatus.Running, System.TimeSpan.FromSeconds(20))
                Catch ex As TimeoutException
                    MsgBox("Could not change status from Paused To Continue for " & Me.Name & " - TimeOut expired" + GetErrorInfo(ex))
                    Return False
                Catch e As Exception
                    MsgBox("Could not change status from Paused To Continue for " & Me.Name & " - " + GetErrorInfo(e))
                    Return False
                End Try
            ElseIf objWinServ.Status = ServiceControllerStatus.Stopped Then
                Call ControlServices("Start")
            ElseIf objWinServ.Status = ServiceControllerStatus.Running Then
                Try
                    objWinServ.Pause()
                    objWinServ.WaitForStatus(ServiceControllerStatus.Paused, System.TimeSpan.FromSeconds(20))
                Catch ex As TimeoutException
                    MsgBox("Could not change status from Running To Paused for " & Me.Name & " - TimeOut expired" + GetErrorInfo(ex))
                    Return False
                Catch e As Exception
                    MsgBox("Could not change status from Running To Paused for " & Me.Name & " - " + GetErrorInfo(e))
                    Return False
                End Try
 
            End If
            Return True
        End Function
 
        Private Sub CheckForParentServices(ByVal sServiceName As String, ByVal NextService As String)
            '  Dim objService As New ServiceController
            objWinServ.ServiceName = sServiceName
            ' objService.MachineName = Me.Parent.MachineName
 
            Dim objParentService As ServiceController
 
            For Each objParentService In objWinServ.ServicesDependedOn
                CheckForParentServices(objParentService.DisplayName, NextService)
            Next
            If NextService = "Start" Then
                Call ServiceStart()
            ElseIf NextService = "Pause" Then
                Call ServicePause()
            End If
 
        End Sub
 
        Private Sub CheckForChildServices(ByVal sServiceName As String, ByVal NextService As String)
            'Dim objService As New ServiceController
            objWinServ.ServiceName = sServiceName
            'objService.MachineName = Me.Parent.MachineName
            Dim objChildService As ServiceController
 
            For Each objChildService In objWinServ.DependentServices
                CheckForChildServices(objChildService.DisplayName, NextService)
            Next
 
            If NextService = "Stop" Then
                Call ServiceStop()
            ElseIf NextService = "Pause" Then
                Call ServicePause()
            Else
                Call ContinueService(sServiceName)
            End If
 
        End Sub
 
        Private Sub ContinueService(ByVal sServiceName As String)
            '   Dim objService As New ServiceController
            objWinServ.ServiceName = sServiceName
            'objWinServ.MachineName = Me.Parent.MachineName
            If objWinServ.Status = ServiceControllerStatus.Paused Then
                Try
                    objWinServ.[Continue]()
                    objWinServ.WaitForStatus(ServiceControllerStatus.Running, System.TimeSpan.FromSeconds(20))
                Catch ex As TimeoutException
 
                    Console.WriteLine("Could not change status from Paused To Continue for " & sServiceName & " - TimeOut expired")
                Catch e As Exception
 
                    Console.WriteLine("Could not change status from Paused To Continue for " & sServiceName & " - " & e.Message)
                End Try
            End If
 
            If objWinServ.Status = ServiceControllerStatus.Stopped Then
                Call ServiceStop(sServiceName)
            End If
 
        End Sub
 
 
 
#End Region
    End Class
 
#End Region
 
 
End Class