Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Create Windows Services in the .Net Framework


Create Windows Services in the .Net Framework

Example 1:
The main source module for SqlServiceMonitor

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;

namespace SqlMonitorService
{
    public class SqlMonitorService : 
System.ServiceProcess.ServiceBase
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;
        private bool m_IsRunning=false;
        private MonitorThread monitorThread = null;

        public SqlMonitorService()
        {
            // This call is required by the Windows.Forms 
//    Component Designer.
            InitializeComponent();

// TODO: Add any initialization after the 
//     InitComponent call
            monitorThread = new MonitorThread();
            monitorThread.ServerName="Dell933";
            monitorThread.DatabaseName="TEST";
            monitorThread.SQLUser="sa";
            monitorThread.SQLPassword="badpassword";
            monitorThread.interval=120;
            monitorThread.eventSource="SqlServiceMonitor";
        }

        // The main entry point for the process
        static void Main()
        {
            System.ServiceProcess.ServiceBase[] ServicesToRun;
    
            ServicesToRun = new 
                        System.ServiceProcess.ServiceBase[] { 
                        new SqlMonitorService() };

            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
        }

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            // 
            // SqlMonitorService
            // 
            this.ServiceName = "SqlServiceMonitor";


        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        /// <summary>
        /// Set things in motion so your service can do its work.
        /// </summary>
        protected override void OnStart(string[] args)
        {
            // Create the thread object, passing in the 
//    monitorThread.workerThread method
            // using a ThreadStart delegate.
            Thread InstanceCaller = 
new Thread(
new ThreadStart(
monitorThread.workerThread)
);

            IsRunning=true;
            // Start the thread.
            InstanceCaller.Start();

        }
 
        /// <summary>
        /// Stop this service.
        /// </summary>
        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down 
            //     necessary to stop your service.
            IsRunning=false;
        }

        /// <summary>
        /// Used to trigger service stop
        /// </summary>
        public bool IsRunning
        {
            get
            {
                return m_IsRunning;
            }
            set
            {
                m_IsRunning=value;
                monitorThread.IsRunning=value;
            }
        }
    }
    class MonitorThread
    {
        public bool IsRunning = false;
        public string ServerName;
        public string DatabaseName;
        public string SQLUser;
        public string SQLPassword;
        public string eventSource;
        public int interval;

        public void onSuccess(string message)
        {
            if (!EventLog.SourceExists(eventSource))
            {
                EventLog.CreateEventSource(eventSource,"Application");
            }
            EventLog MyLog=new EventLog();
            MyLog.Source=eventSource;
            MyLog.WriteEntry(
                message,System.Diagnostics.EventLogEntryType.Information);
        }
        public void onFailure(string message)
        {
            if (!EventLog.SourceExists(eventSource))
            {
                EventLog.CreateEventSource(eventSource,"Application");
            }
            EventLog MyLog=new EventLog();
            MyLog.Source=eventSource;
            MyLog.WriteEntry(
                message,System.Diagnostics.EventLogEntryType.Error);
        }

        public void workerThread()
        {
            int Seconds;
            string SqlString;
            string message;
            System.Data.SqlClient.SqlConnection cn;
            while ( IsRunning )
            {
                // While being responsive, wait interval seconds...
                //        Alternatives: Use Mutex or some other
                //        object, and do wait with timeout for 
                //        longer period...
                Seconds=0;
                while ( IsRunning && Seconds<(interval) )
                {
                    System.Threading.Thread.Sleep(1000);
                    Seconds++;
                }
                // We waited interval seconds, now see if we can connect...

                SqlString="User ID="+SQLUser+";Pwd="+SQLPassword+";
                        Initial Catalog="+DatabaseName+";Server="+ServerName;
                try
                {
                    cn=new SqlConnection(SqlString);
                    cn.Open();
                    message="Connection Successful!";
                    this.onSuccess(message);
                    
                }
                catch ( System.Exception e)
                {
                    ServiceController 
                        sc=new ServiceController("MSSQLSERVER",ServerName);
                    try
                    {
                        message="SQL Server Service status on "+ServerName+
                            " is "+sc.Status.ToString();
                    }
                    catch ( System.Exception ex )
                    {
                        message=
                            "Cannot get status of SQL Server 
                            Service!  Exception: "+
                            ex.ToString();
                    }
                    message=message+"\nFailure: "+e.ToString();
                    this.onFailure(message);
                }

            }
        }
    }
}

Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.