Saturday, August 21, 2010

Creating a perfect sample Windows Service......

Below you can find how to create a windows service and handling all its events for writing a perfect working service and proper CPU consumption by the windows service.


Summary:

The below service is used for creating a file in a specified location and write the time into it at a specific time interval continiously untill you stop the service.




Step1:
-------
Open Visualstudio-->New project-->windows-->service/windowsservice.


Step2:
-------

Now you see the below screen as


step3:
-------
RightClick and choose the add Installer



Step4:
--------
Now you can see the following



Step5:
--------
Now you need to change the properties of the installers..........

Step6:
--------
Now start the coding.


SERVICE1.VB
code:






Imports System
Imports System.IO
Imports System.Configuration

Public Class Service1

'Declaring the global variables
Dim tmTimer As System.Timers.Timer = Nothing

Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service.
' in motion so your service can do its work.
'Declaring the variable here
Dim itimeInterval As Integer = -1
Try
'geting time interval from app.config file
itimeInterval = CType(ConfigurationManager.AppSettings("TimeInterval"), Integer)
'initialiasing
tmTimer = New Timers.Timer(itimeInterval)
'starting the timer
tmTimer.Start()
'calling the function when timer finished
AddHandler tmTimer.Elapsed, AddressOf GenerateFile
'again resetting the properties
With tmTimer
.AutoReset = True
.Enabled = True
.Start()
End With
Catch ex As Exception
WriteEventlog(ex.ToString)
End Try
End Sub

Public Sub GenerateFile()
'Declaring the variables
Dim Fs As FileStream = Nothing
Dim Sw As StreamWriter = Nothing
Try
'Creating the objects to the variables
Fs = New FileStream("D:\NewtextFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
WriteEventlog("Done creating the file")
Sw = New StreamWriter(Fs)
Sw.WriteLine(DateTime.Now)
WriteEventlog("Done writing the data.")
Sw.Close()
Fs.Close()
Catch ex As Exception
WriteEventlog(ex.ToString)
Finally
Sw.Close()
Fs.Close()
If Sw IsNot Nothing Then Sw = Nothing
If Fs IsNot Nothing Then Fs = Nothing
End Try
End Sub

Private Sub WriteEventlog(ByVal tMsg As String)
'--------------------------------------------------------------------------------------------------
'Description : Logs the entries.
'------------------------------------------------------------------------------------------
Dim MyLog As New EventLog() ' create a new event log

Try
' Check if the the Event Log Exists
If Not Diagnostics.EventLog.SourceExists("File Writing") Then
Diagnostics.EventLog.CreateEventSource("File Writing", "File Writing Log")
End If
MyLog.Source = "File Writing"
' Write the Log
Diagnostics.EventLog.WriteEntry("File Writing Log", tMsg, EventLogEntryType.Information)
Catch ex As Exception

Finally
If MyLog IsNot Nothing Then MyLog = Nothing
End Try
End Sub

Protected Overrides Sub OnStop()
'The event is fired when the service is stopped.
tmTimer.Stop()
' Add code here to perform any tear-down necessary to stop your service.
End Sub

Protected Overrides Sub OnPause()
MyBase.OnPause()
'Handling the paused event of the serivce
tmTimer.Stop()
End Sub
Protected Overrides Sub OnContinue()
MyBase.OnContinue()
''Handling the on continue action of service
tmTimer.Start()
End Sub

Protected Overrides Sub OnShutdown()
MyBase.OnShutdown()
tmTimer.Stop()
End Sub
End Class






*Make sure you write all the events like the onshutdown, onpaused, onstop, onstart for the proper usage of the CPU memory.




The app.config file entry:
---------------------------



here the time is in milliseconds.................so to convert it into minutes, multiply the time with * 60000 and give the value in the below config key


< key ="TimeInterval" value="1">






now build the service. Now your service is ready for installing in services.

2 comments:

  1. All the logs are made into the event viewer.........you can view the event viewer by the command EVENTVWR.MSC from the run command.

    ReplyDelete
  2. The time interval can be changed by changing the value in the web.config entry.

    ReplyDelete