Dailycode.info

Short solution for short problems

Creating a service for your class library

During development, I always use a small WPF client to test the program, when test are going ok I create the service.

This week I used this tutorial twice, it only took me 1 hour to set it up correctly and needly (with event logging etc).

http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.80).aspx

Logging I do with the aidf of a simple extra class (code found at the end of this post)

EventLogWriter.Instance.WriteToLog("Service Stopped", EventLogEntryType.Information);

I use this simple singleton class to help with the event logging:

 

/// <summary>

    /// Class enabling writing to the eventlog

    /// </summary>

    public class EventLogWriter

    {

        private System.Diagnostics.EventLog eventWriter;

 

        #region Singleton Pattern

 

        // Singleton.

        private static EventLogWriter _instance;

 

        /// <summary>

        /// Singleton Pattern.

        /// </summary>

        public static EventLogWriter Instance

        {

            get

            {

                if (EventLogWriter._instance == null)

                {

                    EventLogWriter._instance = new EventLogWriter();

                }

 

                return EventLogWriter._instance;

            }

        }

 

        #endregion

 

        /// <summary>

        /// Constructor

        /// </summary>

        public EventLogWriter()

        {

            // 

            // init eventWriter

            // 

            eventWriter = new EventLog();

            eventWriter.Log = "Application";

            eventWriter.Source = "SFIAutoMeasurementService";

        }

 

        /// <summary>

        /// Writes an entry to the eventlog

        /// </summary>

        /// <param name="msg">Message to write</param>

        /// <param name="entryType">Eventlog entry type</param>

        public void WriteToLog(string msg, EventLogEntryType entryType)

        {

 

            try

            {

                if (System.Diagnostics.EventLog.SourceExists("SFIAutoMeasurementService"))

                {

                    eventWriter.WriteEntry(msg, entryType);

                }

            }

            catch { }

 

        }

    }