Kshitij’s Blog .NET/ CSLA.NET / ASP.NET / VB.NET / C# / SQL Server / MySql ..
  • Jun
    5

    Creating a Pingback (Windows) service with VB.NET

    Filed under: .NET, VB.NET;

    Recently i faced lots of problem with my hosting company as almost daily my site was down due to some problems in their servers. They usually send me a link to trace my site. Basically that site provide service to ping back any URL from their servers which are located in different countries. So it is like first their US server pings the URL and sends back the results weather site is responding or not and then all of the servers located in different part of the word do the same thing and finally giving a summery. For me it was annoying to go again and again to that site and then type URL to trace it back. Furthermore they charge for their services if you wants to check your site (or any other URL) 24×7. So i decided to write my own service. In this service i write the ping back results to windows log but you can always enhance this code to send mails or even SMS if your site is down.

    So lets start and create a Windows Web Service Project

    New_prj_WinService

    Now rename your service1.vb file to PingBackSvr.vb and add another class code file to your project and name it PingBack.vb. After doing this your solution explorer should look like

    prjview

    Now lets start code PingBack.vb

    'Namespace References
    Imports System
    Imports System.Runtime.InteropServices
    Imports System.Net
    Imports System.Net.NetworkInformation
    Imports System.Net.Sockets
    
    Public Class PingBack
    
    <DllImport("wininet", CharSet:=CharSet.Auto)> _
    Private Shared Function InternetGetConnectedState(ByRef flags As ConnectionStatusEnum, ByVal dw As Integer) As Boolean
    End Function
    
    ''' <summary>
    ''' enum to hold the possible connection states
    ''' </summary>
    <Flags()> _
    Private Enum ConnectionStatusEnum As Integer
    INTERNET_CONNECTION_MODEM = &H1
    INTERNET_CONNECTION_LAN = &H2
    INTERNET_CONNECTION_PROXY = &H4
    INTERNET_RAS_INSTALLED = &H10
    INTERNET_CONNECTION_OFFLINE = &H20
    INTERNET_CONNECTION_CONFIGURED = &H40
    End Enum
    
    ''' <summary>
    ''' method to check the status of the pinging machines internet connection
    ''' </summary>
    ''' <returns></returns>
    Private Function HasConnection() As Boolean
    'instance of out ConnectionStatusEnum
    Dim state As ConnectionStatusEnum = 0
    
    'call the API
    InternetGetConnectedState(state, 0)
    
    'check the status, if not offline and the returned state
    'isnt 0 then we have a connection
    If (CInt(ConnectionStatusEnum.INTERNET_CONNECTION_OFFLINE) And CInt(state)) <> 0 Then
    'return true, we have a connection
    Return False
    End If
    'return false, no connection available
    Return True
    End Function
    
    ''' <summary>
    ''' method for retrieving the IP address from the host provided
    ''' </summary>
    ''' <param name="host">the host we need the address for</param>
    ''' <returns></returns>
    Private Function GetIpFromHost(ByRef host As String) As IPAddress
    Dim returnMessage As String = String.Empty
    'IPAddress instance for holding the returned host
    Dim address As IPAddress = Nothing
    
    'wrap the attempt in a try..catch to capture
    'any exceptions that may occur
    Try
    'get the host IP from the name provided
    address = Dns.GetHostEntry(host).AddressList(0)
    Catch ex As SocketException
    'some DNS error happened, return the message
    returnMessage = String.Format("DNS Error: {0}", ex.Message)
    End Try
    Return address
    End Function
    
    ''' <summary>
    ''' method to check the ping status of a provided host
    ''' </summary>
    ''' <param name="host">the host we need to ping</param>
    ''' <returns></returns>
    Protected Friend Function CheckSiteStatus(ByVal host As String) As String
    'string to hold our return messge
    Dim returnMessage As String = String.Empty
    
    'IPAddress instance for holding the returned host
    Dim address As IPAddress = GetIpFromHost(host)
    
    'set the ping options, TTL 128
    Dim options As New PingOptions(128, True)
    
    'create a new ping instance
    Dim ping As New Ping()
    
    '32 byte buffer
    Dim data As Byte() = New Byte(31) {}
    
    'first make sure we actually have an internet connection
    If HasConnection() Then
    'here we will ping the host 4 times (standard)
    For i As Integer = 0 To 3
    Try
    'send the ping 4 times to the host and record the returned data
    Dim reply As PingReply = ping.Send(address, 1000, data, options)
    
    'make sure we dont have a null reply
    If Not (reply Is Nothing) Then
    Select Case reply.Status
    Case IPStatus.Success
    returnMessage = String.Format("Reply from {0}: bytes={1} time={2}ms TTL={3}", reply.Address, reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl)
    Exit Select
    Case IPStatus.TimedOut
    returnMessage = "Connection has timed out..."
    Exit Select
    Case Else
    returnMessage = String.Format("Ping failed: {0}", reply.Status.ToString())
    Exit Select
    End Select
    Else
    returnMessage = "Connection failed for an unknown reason..."
    End If
    Catch ex As PingException
    returnMessage = String.Format("Connection Error: {0}", ex.Message)
    Catch ex As SocketException
    returnMessage = String.Format("Connection Error: {0}", ex.Message)
    End Try
    Next
    Else
    returnMessage = "No Internet connection found..."
    End If
    
    'return the message
    Return returnMessage
    End Function
    End Class
    

    Now let’s code our Service class which in this case is PinbBackSvr.vb.

    Public Class PingBackSvr
    Private _objPingback As PingBack
    Private _status As String
    Private WithEvents timer1 As New System.Timers.Timer
    Private PingLog As New EventLog
    Protected Overrides Sub OnStart(ByVal args() As String)
    ' Add code here to start your service. This method should set things
    ' in motion so your service can do its work.
    'Uncomment this line to Debug this service
    Debugger.Launch()
    timer1.Enabled = True
    timer1.Interval = 6000
    ' Me.TracePing()
    End Sub
    
    Protected Overrides Sub OnStop()
    ' Add code here to perform any tear-down necessary to stop your service.
    Me.Timer1.Enabled = False
    End Sub
    
    Private Sub OnTimerElapsed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timer1.Elapsed
    Me.TracePing()
    End Sub
    
    Private Sub TracePing()
    Try
    If Not Diagnostics.EventLog.SourceExists("PingBackSvr") Then
    Diagnostics.EventLog.CreateEventSource("PingBackSvr", "KshitijSharma.Net Ping Service Log")
    End If
    PingLog.Source = "PingBackSvr"
    Me._objPingback = New PingBack
    Me._status = Me._objPingback.CheckSiteStatus("www.kshitijsharma.net")
    If InStr(Me._status, "failed") > 0 OrElse InStr(Me._status, "Error") > 0 OrElse InStr(Me._status, "timed out") > 0 Then
    PingLog.WriteEntry(Me._status, EventLogEntryType.FailureAudit)
    Else
    PingLog.WriteEntry(Me._status, EventLogEntryType.SuccessAudit)
    End If
    Catch ex As Exception
    PingLog.WriteEntry(ex.Message, EventLogEntryType.Error)
    Finally
    Me._objPingback = Nothing
    PingLog = Nothing
    End Try
    End Sub
    End Class
    


    Now add a ‘Service Installer by right clicking design view of service.

    screenhunter_06-jun-06-1656

    Now Build your project

    After building this service we need to install it on server.  we can do this with installUtil.exe utility. you can use

    To Install
    <pathofInstallUtil>\installUtil.exe /i <pathtoyourexe>

    To Uninstall
    <pathofInstallUtil>\installUtil.exe /u <pathtoyourexe>

    ScreenHunter_04 Jun. 06 16.43

    Please let me know if you need help any part of this code!
    Enjoy Coding!
    Kshitij


    5 Comments

5 Responses to “Creating a Pingback (Windows) service with VB.NET”

  1. Hi, gr8 post thanks for posting. Information is useful!

  2. Hi,
    Thanks for the post. Really Helpful!.

    Bayley

  3. Thanks!.
    Excellent article.

  4. great article.. thanks a lot. It really helps me a lot.

  5. My Pleasure John :)

Leave a Reply