Results 1 to 7 of 7

Thread: Windows Service

  1. #1

    Thread Starter
    New Member
    Join Date
    Feb 2006
    Posts
    3

    Windows Service

    Hi Folks,

    I am designing a windows service which will query a database and send out automated emails on a daily basis. So far the service can send out automated emails, however when I tried to query the database it failed, despite the fact I used the same code that I had used within an .aspx page of my web application. I am usure whether i can use features such as a dataset within a windows service.

    Any hints or tips would be greatly appreciated

    Regards

    Grant

    Working Automated Emails Code

    VB Code:
    1. Option Explicit On
    2. Option Strict On
    3.  
    4. Imports System.ServiceProcess
    5. Imports System.Xml
    6. Imports System.Text
    7. Imports System.IO
    8. Imports System.Diagnostics
    9. Imports System.Data
    10. Imports System.Web.Mail
    11. Imports Microsoft.VisualBasic.ControlChars
    12. Imports System.Timers
    13. Imports System.Data.SqlClient
    14.  
    15.  
    16.  
    17. Public Class Service1
    18.     Inherits System.ServiceProcess.ServiceBase
    19.  
    20. #Region " Component Designer generated code "
    21.  
    22.     Public Sub New()
    23.         MyBase.New()
    24.  
    25.         ' This call is required by the Component Designer.
    26.         InitializeComponent()
    27.  
    28.         ' Add any initialization after the InitializeComponent() call
    29.  
    30.     End Sub
    31.  
    32.     'UserService overrides dispose to clean up the component list.
    33.     Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
    34.         If disposing Then
    35.             If Not (components Is Nothing) Then
    36.                 components.Dispose()
    37.             End If
    38.         End If
    39.         MyBase.Dispose(disposing)
    40.     End Sub
    41.  
    42.     ' The main entry point for the process
    43.     <MTAThread()> _
    44.     Shared Sub Main()
    45.         Dim ServicesToRun() As System.ServiceProcess.ServiceBase
    46.  
    47.         ' More than one NT Service may run within the same process. To add
    48.         ' another service to this process, change the following line to
    49.         ' create a second service object. For example,
    50.         '
    51.         '   ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
    52.         '
    53.         ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}
    54.  
    55.         System.ServiceProcess.ServiceBase.Run(ServicesToRun)
    56.     End Sub
    57.  
    58.     'Required by the Component Designer
    59.     Private components As System.ComponentModel.IContainer
    60.  
    61.     ' NOTE: The following procedure is required by the Component Designer
    62.     ' It can be modified using the Component Designer.  
    63.     ' Do not modify it using the code editor.
    64.     Friend WithEvents Timer1 As System.Timers.Timer
    65.     <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
    66.         Me.Timer1 = New System.Timers.Timer
    67.         CType(Me.Timer1, System.ComponentModel.ISupportInitialize).BeginInit()
    68.         '
    69.         'Timer1
    70.         '
    71.         Me.Timer1.Enabled = True
    72.         Me.Timer1.Interval = 10000
    73.         '
    74.         'Service1
    75.         '
    76.         Me.ServiceName = "Service1"
    77.         CType(Me.Timer1, System.ComponentModel.ISupportInitialize).EndInit()
    78.  
    79.     End Sub
    80.  
    81. #End Region
    82.  
    83.     Protected Overrides Sub OnStart(ByVal args() As String)
    84.         ' Add code here to start your service. This method should set things
    85.         ' in motion so your service can do its work.
    86.         Timer1.Enabled = True
    87.  
    88.  
    89.  
    90.  
    91.     End Sub
    92.  
    93.     Protected Overrides Sub OnStop()
    94.         ' Add code here to perform any tear-down necessary to stop your service.
    95.         Timer1.Enabled = False
    96.     End Sub
    97.  
    98.     Private Sub Timer1_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles Timer1.Elapsed
    99.  
    100.         Working()
    101.  
    102.     End Sub
    103.  
    104.     Private Sub Working()
    105.  
    106.         ' Local variables
    107.         Dim sFrom As String = String.Empty
    108.         Dim sTo As String = String.Empty
    109.         Dim sCc As String = String.Empty
    110.         Dim sBcc As String = String.Empty
    111.         Dim sSubject As String = String.Empty
    112.         Dim sBody As String = String.Empty
    113.         Dim nSleep As Integer = 15
    114.         Dim nPause As Integer = 1000
    115.  
    116.         'Create a var. named rightNow and set it to the current date/time
    117.         Dim rightNow As DateTime = DateTime.Now
    118.         Dim s As String 'create a string
    119.  
    120.         s = rightNow.ToString("dd/MM/yy")
    121.  
    122.  
    123.         'Database
    124.         Dim testvariable As String = String.Empty
    125.  
    126.         ' Enter the infinite loop
    127.         Try
    128.             ' First, sleep for a while
    129.             'mWorker.Sleep(nSleep * 60 * 1000)
    130.             'mWorker.Sleep(2000)
    131.             ' Woke up
    132.             'LogInfo("Service woke up")
    133.             Dim i As Integer = 0
    134.             ' Prepare e-mail fields
    135.             sFrom = "[email protected]"
    136.             sTo = "[email protected]"
    137.                        Dim oMailMsg As MailMessage = New MailMessage
    138.             oMailMsg.From = sFrom
    139.             oMailMsg.To = sTo
    140.             oMailMsg.Cc = sCc
    141.             ' Call a stored procedure to process the current item
    142.             ' The success message
    143.             oMailMsg.Subject = sSubject + "Emergency Response Rota"
    144.             oMailMsg.BodyFormat = MailFormat.Html
    145.  
    146.             oMailMsg.Body = sBody + "<HTML><BODY>Dear All,<BR><BR>The Rota for the week beginning the " + s + " is as follows: <br>" + testvariable + "</BODY></HTML>"
    147.             SmtpMail.SmtpServer = "mailhost.wfc.domain.net"
    148.  
    149.  
    150.             ' Send the message
    151.             If Not (oMailMsg.To = String.Empty) Then
    152.                 SmtpMail.Send(oMailMsg)
    153.             End If
    154.             ' Pause to avoid hogging the CPU
    155.             'mWorker.Sleep(nPause)
    156.         Catch obug As Exception
    157.             'LogEvent(obug.Message)
    158.         Finally
    159.  
    160.         End Try
    161.  
    162.     End Sub
    163.  
    164. End Class

  2. #2
    Frenzied Member d3gerald's Avatar
    Join Date
    Jan 2006
    Posts
    1,348

    Re: Windows Service

    welcome to vbforums
    On error goto Trap

    Trap:
    in case of emergency, drop the case...

    ****************************************
    If this post has been resolved. Please mark it as "Resolved" by going through the "Thread Tools" above and clicking on the "Mark Thread Resolved " option.
    if a post is helpful to you, Please Rate it by clicking on the Rate link right below the avatar

  3. #3
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,709

    Re: Windows Service

    Moved from Classic VB forum.
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Windows Service

    "Failed" could mean any of a number of different things. Describe the nature of the failure.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    New Member
    Join Date
    Feb 2006
    Posts
    3

    Re: Windows Service

    The service when the following code is added compiles successfully, it is possible to install the service and it will also start. But after adding in the db code it stops sending out emails and doesnt appear to do anything. See code including db functionality below

    VB Code:
    1. Option Explicit On
    2. Option Strict On
    3.  
    4. Imports System.ServiceProcess
    5. Imports System.Xml
    6. Imports System.Text
    7. Imports System.IO
    8. Imports System.Diagnostics
    9. Imports System.Data
    10. Imports System.Web.Mail
    11. Imports Microsoft.VisualBasic.ControlChars
    12. Imports System.Timers
    13. Imports System.Data.SqlClient
    14.  
    15.  
    16.  
    17. Public Class Service1
    18.     Inherits System.ServiceProcess.ServiceBase
    19.  
    20. #Region " Component Designer generated code "
    21.  
    22.     Public Sub New()
    23.         MyBase.New()
    24.  
    25.         ' This call is required by the Component Designer.
    26.         InitializeComponent()
    27.  
    28.         ' Add any initialization after the InitializeComponent() call
    29.  
    30.     End Sub
    31.  
    32.     'UserService overrides dispose to clean up the component list.
    33.     Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
    34.         If disposing Then
    35.             If Not (components Is Nothing) Then
    36.                 components.Dispose()
    37.             End If
    38.         End If
    39.         MyBase.Dispose(disposing)
    40.     End Sub
    41.  
    42.     ' The main entry point for the process
    43.     <MTAThread()> _
    44.     Shared Sub Main()
    45.         Dim ServicesToRun() As System.ServiceProcess.ServiceBase
    46.  
    47.         ' More than one NT Service may run within the same process. To add
    48.         ' another service to this process, change the following line to
    49.         ' create a second service object. For example,
    50.         '
    51.         '   ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
    52.         '
    53.         ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}
    54.  
    55.         System.ServiceProcess.ServiceBase.Run(ServicesToRun)
    56.     End Sub
    57.  
    58.     'Required by the Component Designer
    59.     Private components As System.ComponentModel.IContainer
    60.  
    61.     ' NOTE: The following procedure is required by the Component Designer
    62.     ' It can be modified using the Component Designer.  
    63.     ' Do not modify it using the code editor.
    64.     Friend WithEvents Timer1 As System.Timers.Timer
    65.     <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
    66.         Me.Timer1 = New System.Timers.Timer
    67.         CType(Me.Timer1, System.ComponentModel.ISupportInitialize).BeginInit()
    68.         '
    69.         'Timer1
    70.         '
    71.         Me.Timer1.Enabled = True
    72.         Me.Timer1.Interval = 10000
    73.         '
    74.         'Service1
    75.         '
    76.         Me.ServiceName = "Service1"
    77.         CType(Me.Timer1, System.ComponentModel.ISupportInitialize).EndInit()
    78.  
    79.     End Sub
    80.  
    81. #End Region
    82.  
    83.     Protected Overrides Sub OnStart(ByVal args() As String)
    84.         ' Add code here to start your service. This method should set things
    85.         ' in motion so your service can do its work.
    86.         Timer1.Enabled = True
    87.  
    88.  
    89.  
    90.  
    91.     End Sub
    92.  
    93.     Protected Overrides Sub OnStop()
    94.         ' Add code here to perform any tear-down necessary to stop your service.
    95.         Timer1.Enabled = False
    96.     End Sub
    97.  
    98.     Private Sub Timer1_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles Timer1.Elapsed
    99.  
    100.         Working()
    101.  
    102.     End Sub
    103.  
    104.     Private Sub Working()
    105.  
    106.         ' Local variables
    107.         Dim sFrom As String = String.Empty
    108.         Dim sTo As String = String.Empty
    109.         Dim sCc As String = String.Empty
    110.         Dim sBcc As String = String.Empty
    111.         Dim sSubject As String = String.Empty
    112.         Dim sBody As String = String.Empty
    113.         Dim nSleep As Integer = 15
    114.         Dim nPause As Integer = 1000
    115.  
    116.         'Create a var. named rightNow and set it to the current date/time
    117.         Dim rightNow As DateTime = DateTime.Now
    118.         Dim weekValue As String 'create a string
    119.  
    120.         weekValue = rightNow.ToString("dd/MM/yy")
    121.  
    122.  
    123.         'Database
    124.         Dim testvariable As String = String.Empty
    125.  
    126.         Dim Conn As SqlConnection
    127.  
    128.         'for basic querying like SELECT
    129.         Dim Cmd As SqlDataAdapter
    130.  
    131.         'for other types of query like INSERT, UPDATE and DELETE...
    132.         Dim Cmd2 As SqlCommand
    133.  
    134.  
    135.         Dim myquery As String = "SELECT * FROM Roles, Employees CROSS JOIN Rota WHERE (Rota.EmergencyManager = Employees.CAI) AND Week = '" + weekValue + "' AND (Roles.Role = Employees.Role) OR (Rota.SiteContact = Employees.CAI) AND Week = '" + weekValue + "' AND (Roles.Role = Employees.Role) OR (Rota.Logger = Employees.CAI) AND Week = '" + weekValue + "' AND (Roles.Role = Employees.Role) OR (Rota.Logistics = Employees.CAI) AND Week = '" + weekValue + "' AND (Roles.Role = Employees.Role) OR (Rota.Agency = Employees.CAI) AND Week = '" + weekValue + "' AND (Roles.Role = Employees.Role) OR (Rota.POB = Employees.CAI) AND Week = '" + weekValue + "' AND (Roles.Role = Employees.Role) OR (Rota.HR = Employees.CAI) AND Week = '" + weekValue + "' AND (Roles.Role = Employees.Role) OR (Rota.PGA = Employees.CAI) AND Week = '" + weekValue + "' AND (Roles.Role = Employees.Role)"
    136.  
    137.  
    138.         Conn = New SqlConnection("server=abentgapw7; trusted_connection=true; database=ERR")
    139.         Cmd = New SqlDataAdapter(myquery, Conn)
    140.  
    141.         ' Create a new DataSet
    142.         Dim ds As DataSet = New DataSet("theEmployee")
    143.  
    144.         ' Call the Fill method to load the DataSet
    145.         Cmd.Fill(ds, "theEmployee")
    146.  
    147.         ' Add DataBinding to variable
    148.  
    149.         testvariable = ds.Tables("theEmployee").Rows(0)("FirstName").ToString() + " " + ds.Tables("theEmployee").Rows(0)("LastName").ToString()
    150.        
    151.  
    152.         ' Enter the infinite loop
    153.         Try
    154.             ' First, sleep for a while
    155.             'mWorker.Sleep(nSleep * 60 * 1000)
    156.             'mWorker.Sleep(2000)
    157.             ' Woke up
    158.             'LogInfo("Service woke up")
    159.             Dim i As Integer = 0
    160.             ' Prepare e-mail fields
    161.             sFrom = "[email protected]"
    162.             sTo = "[email protected]"
    163.            
    164.             Dim oMailMsg As MailMessage = New MailMessage
    165.             oMailMsg.From = sFrom
    166.             oMailMsg.To = sTo
    167.             oMailMsg.Cc = sCc
    168.             ' Call a stored procedure to process the current item
    169.             ' The success message
    170.             oMailMsg.Subject = sSubject + "Emergency Response Rota"
    171.             oMailMsg.BodyFormat = MailFormat.Html
    172.  
    173.             oMailMsg.Body = sBody + "<HTML><BODY>Dear All,<BR><BR>The Rota for the week beginning the " + weekValue + " is as follows: <br>" + testvariable + "</BODY></HTML>"
    174.             SmtpMail.SmtpServer = "mailhost.wfc.domain.net"
    175.  
    176.  
    177.             ' Send the message
    178.             If Not (oMailMsg.To = String.Empty) Then
    179.                 SmtpMail.Send(oMailMsg)
    180.             End If
    181.             ' Pause to avoid hogging the CPU
    182.             'mWorker.Sleep(nPause)
    183.         Catch obug As Exception
    184.             'LogEvent(obug.Message)
    185.         Finally
    186.  
    187.         End Try
    188.  
    189.     End Sub
    190.  
    191. End Class

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Windows Service

    You either need to add some sort of logging to your code or else debug it. Read this to learn how to debug a service.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  7. #7

    Thread Starter
    New Member
    Join Date
    Feb 2006
    Posts
    3

    Re: Windows Service

    I generated an event log for my service and I wrapped a try catch statement around my db code and this is what I get "The error is as follows Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'."

    Obvioulsy now the service will send out emails again as the exception has now been caught, however the error is preventing me pulling data from the database.

    Any Ideas?????

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width