Link Search Menu Expand Document

Generate Barcode from Service - C#

BarCode SDK sample in C# demonstrating ‘Generate Barcode from Service’

readme.txt
This is simple .NET service created by Microsoft guidelines ( http://msdn.microsoft.com/en-us/library/d56de412(v=vs.80).aspx )
"ServiceController" - simple GUI application that starts and stops the service;
"WindowsService1" - service itself.

This sample service generates PDF files with random GS1-128 barcode every five seconds 
and puts them to "c:\barcodes" folder.

Check the Service1.vb file. 
There is barcode generation and email sending example code.

ServiceController requries Administrator rights to run, so you should run the Visual Studio as Administrator to be able to run the ServiceController from Debug. 
Or run the compiled executable directly. It will ask for Administrative rights on start.
Form1.Designer.cs
��namespace ServiceController

{

    partial class Form1

    {

        /// <summary>

        /// Required designer variable.

        /// </summary>

        private System.ComponentModel.IContainer components = null;



        /// <summary>

        /// Clean up any resources being used.

        /// </summary>

        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>

        protected override void Dispose(bool disposing)

        {

            if (disposing && (components != null))

            {

                components.Dispose();

            }

            base.Dispose(disposing);

        }



        #region Windows Form Designer generated code



        /// <summary>

        /// Required method for Designer support - do not modify

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()

        {

			this.btnInstallService = new System.Windows.Forms.Button();

			this.btnUninstallService = new System.Windows.Forms.Button();

			this.btnExit = new System.Windows.Forms.Button();

			this.SuspendLayout();

			// 

			// btnInstallService

			// 

			this.btnInstallService.Location = new System.Drawing.Point(12, 12);

			this.btnInstallService.Name = "btnInstallService";

			this.btnInstallService.Size = new System.Drawing.Size(125, 23);

			this.btnInstallService.TabIndex = 0;

			this.btnInstallService.Text = "Install Service";

			this.btnInstallService.UseVisualStyleBackColor = true;

			this.btnInstallService.Click += new System.EventHandler(this.btnInstallService_Click);

			// 

			// btnUninstallService

			// 

			this.btnUninstallService.Location = new System.Drawing.Point(143, 12);

			this.btnUninstallService.Name = "btnUninstallService";

			this.btnUninstallService.Size = new System.Drawing.Size(125, 23);

			this.btnUninstallService.TabIndex = 1;

			this.btnUninstallService.Text = "Uninstall Service";

			this.btnUninstallService.UseVisualStyleBackColor = true;

			this.btnUninstallService.Click += new System.EventHandler(this.btnUninstallService_Click);

			// 

			// btnExit

			// 

			this.btnExit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));

			this.btnExit.DialogResult = System.Windows.Forms.DialogResult.OK;

			this.btnExit.Location = new System.Drawing.Point(193, 77);

			this.btnExit.Name = "btnExit";

			this.btnExit.Size = new System.Drawing.Size(75, 23);

			this.btnExit.TabIndex = 3;

			this.btnExit.Text = "Exit";

			this.btnExit.UseVisualStyleBackColor = true;

			this.btnExit.Click += new System.EventHandler(this.btnExit_Click);

			// 

			// Form1

			// 

			this.AcceptButton = this.btnExit;

			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);

			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

			this.ClientSize = new System.Drawing.Size(282, 112);

			this.Controls.Add(this.btnExit);

			this.Controls.Add(this.btnUninstallService);

			this.Controls.Add(this.btnInstallService);

			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;

			this.MaximizeBox = false;

			this.Name = "Form1";

			this.Text = "Service Controller";

			this.ResumeLayout(false);



        }



        #endregion



        private System.Windows.Forms.Button btnInstallService;

        private System.Windows.Forms.Button btnUninstallService;

		private System.Windows.Forms.Button btnExit;

    }

}




Form1.cs
using System;
using System.IO;
using System.Management;
using System.Windows.Forms;
using System.ServiceProcess;

namespace ServiceController
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnInstallService_Click(object sender, EventArgs e)
        {
            try
            {
                // Install the service
                ServiceInstaller.Install("Service1", "Service1", Path.GetFullPath("WindowsService1.exe"));
            
                // Set the service option "Allow desktop interaction".
                ConnectionOptions co = new ConnectionOptions();
                co.Impersonation = ImpersonationLevel.Impersonate;
                ManagementScope mgmtScope = new ManagementScope(@"root\CIMV2", co);
                mgmtScope.Connect();
                ManagementObject wmiService = new ManagementObject("Win32_Service.Name='Service1'");
                ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");
                InParam["DesktopInteract"] = true;
                ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);

				// Start the service
                ServiceInstaller.StartService("Service1");
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void btnUninstallService_Click(object sender, EventArgs e)
        {
            try
            {
                ServiceInstaller.Uninstall("Service1");
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

		private void btnExit_Click(object sender, EventArgs e)
		{
			this.Close();
		}
    }
}

Program.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace ServiceController
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

ServiceInstaller.cs
using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace ServiceController
{
    public static class ServiceInstaller
    {
        private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
        private const int SERVICE_WIN32_OWN_PROCESS = 0x00000010;

        [StructLayout(LayoutKind.Sequential)]
        private class SERVICE_STATUS
        {
            public int dwServiceType = 0;
            public ServiceState dwCurrentState = 0;
            public int dwControlsAccepted = 0;
            public int dwWin32ExitCode = 0;
            public int dwServiceSpecificExitCode = 0;
            public int dwCheckPoint = 0;
            public int dwWaitHint = 0;
        }

        #region OpenSCManager
        [DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
        static extern IntPtr OpenSCManager(string machineName, string databaseName, ScmAccessRights dwDesiredAccess);
        #endregion

        #region OpenService
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceAccessRights dwDesiredAccess);
        #endregion

        #region CreateService
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern IntPtr CreateService(IntPtr hSCManager, string lpServiceName, string lpDisplayName, ServiceAccessRights dwDesiredAccess, int dwServiceType, ServiceBootFlag dwStartType, ServiceError dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lp, string lpPassword);
        #endregion

        #region CloseServiceHandle
        [DllImport("advapi32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool CloseServiceHandle(IntPtr hSCObject);
        #endregion

        #region QueryServiceStatus
        [DllImport("advapi32.dll")]
        private static extern int QueryServiceStatus(IntPtr hService, SERVICE_STATUS lpServiceStatus);
        #endregion

        #region DeleteService
        [DllImport("advapi32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool DeleteService(IntPtr hService);
        #endregion

        #region ControlService
        [DllImport("advapi32.dll")]
        private static extern int ControlService(IntPtr hService, ServiceControl dwControl, SERVICE_STATUS lpServiceStatus);
        #endregion

        #region StartService
        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern int StartService(IntPtr hService, int dwNumServiceArgs, int lpServiceArgVectors);
        #endregion

        public static void Uninstall(string serviceName)
        {
            IntPtr scm = OpenSCManager(ScmAccessRights.AllAccess);

            try
            {
                IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.AllAccess);
                if (service == IntPtr.Zero)
                    throw new ApplicationException("Service not installed.");

                try
                {
                    StopService(service);
                    if (!DeleteService(service))
                        throw new ApplicationException("Could not delete service " + Marshal.GetLastWin32Error());
                }
                finally
                {
                    CloseServiceHandle(service);
                }
            }
            finally
            {
                CloseServiceHandle(scm);
            }
        }

        public static bool ServiceIsInstalled(string serviceName)
        {
            IntPtr scm = OpenSCManager(ScmAccessRights.Connect);

            try
            {
                IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.QueryStatus);

                if (service == IntPtr.Zero)
                    return false;

                CloseServiceHandle(service);
                return true;
            }
            finally
            {
                CloseServiceHandle(scm);
            }
        }

        public static void Install(string serviceName, string displayName, string fileName)
        {
            IntPtr scm = OpenSCManager(ScmAccessRights.AllAccess);

            try
            {
                IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.AllAccess);

                if (service == IntPtr.Zero)
                    service = CreateService(scm, serviceName, displayName, ServiceAccessRights.AllAccess, SERVICE_WIN32_OWN_PROCESS, ServiceBootFlag.AutoStart, ServiceError.Normal, fileName, null, IntPtr.Zero, null, null, null);

                if (service == IntPtr.Zero)
                    throw new ApplicationException("Failed to install service.");
            }
            finally
            {
                CloseServiceHandle(scm);
            }
        }

        public static void InstallAndStart(string serviceName, string displayName, string fileName)
        {
            IntPtr scm = OpenSCManager(ScmAccessRights.AllAccess);

            try
            {
                IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.AllAccess);

                if (service == IntPtr.Zero)
                    service = CreateService(scm, serviceName, displayName, ServiceAccessRights.AllAccess, SERVICE_WIN32_OWN_PROCESS, ServiceBootFlag.AutoStart, ServiceError.Normal, fileName, null, IntPtr.Zero, null, null, null);

                if (service == IntPtr.Zero)
                    throw new ApplicationException("Failed to install service.");

                try
                {
                    StartService(service);
                }
                finally
                {
                    CloseServiceHandle(service);
                }
            }
            finally
            {
                CloseServiceHandle(scm);
            }
        }

        public static void StartService(string serviceName)
        {
            IntPtr scm = OpenSCManager(ScmAccessRights.Connect);

            try
            {
                IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.QueryStatus | ServiceAccessRights.Start);
                if (service == IntPtr.Zero)
                    throw new ApplicationException("Could not open service.");

                try
                {
                    StartService(service);
                }
                finally
                {
                    CloseServiceHandle(service);
                }
            }
            finally
            {
                CloseServiceHandle(scm);
            }
        }

        public static void StopService(string serviceName)
        {
            IntPtr scm = OpenSCManager(ScmAccessRights.Connect);

            try
            {
                IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.QueryStatus | ServiceAccessRights.Stop);
                if (service == IntPtr.Zero)
                    throw new ApplicationException("Could not open service.");

                try
                {
                    StopService(service);
                }
                finally
                {
                    CloseServiceHandle(service);
                }
            }
            finally
            {
                CloseServiceHandle(scm);
            }
        }

        private static void StartService(IntPtr service)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();
            StartService(service, 0, 0);
            var changedStatus = WaitForServiceStatus(service, ServiceState.StartPending, ServiceState.Running);
            if (!changedStatus)
                throw new ApplicationException("Unable to start service");
        }

        private static void StopService(IntPtr service)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();
            ControlService(service, ServiceControl.Stop, status);
            var changedStatus = WaitForServiceStatus(service, ServiceState.StopPending, ServiceState.Stopped);
            if (!changedStatus)
                throw new ApplicationException("Unable to stop service");   
        }

        public static ServiceState GetServiceStatus(string serviceName)
        {
            IntPtr scm = OpenSCManager(ScmAccessRights.Connect);

            try
            {
                IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.QueryStatus);
                if (service == IntPtr.Zero)
                    return ServiceState.NotFound;

                try
                {
                    return GetServiceStatus(service);
                }
                finally
                {
                    CloseServiceHandle(service);
                }
            }
            finally
            {
                CloseServiceHandle(scm);
            }
        }

        private static ServiceState GetServiceStatus(IntPtr service)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();

            if (QueryServiceStatus(service, status) == 0)
                throw new ApplicationException("Failed to query service status.");

            return status.dwCurrentState;
        }

        private static bool WaitForServiceStatus(IntPtr service, ServiceState waitStatus, ServiceState desiredStatus)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();

            QueryServiceStatus(service, status);
            if (status.dwCurrentState == desiredStatus) return true;

            int dwStartTickCount = Environment.TickCount;
            int dwOldCheckPoint = status.dwCheckPoint;

            while (status.dwCurrentState == waitStatus)
            {
                // Do not wait longer than the wait hint. A good interval is
                // one tenth the wait hint, but no less than 1 second and no
                // more than 10 seconds.

                int dwWaitTime = status.dwWaitHint / 10;

                if (dwWaitTime < 1000) dwWaitTime = 1000;
                else if (dwWaitTime > 10000) dwWaitTime = 10000;

                Thread.Sleep(dwWaitTime);

                // Check the status again.

                if (QueryServiceStatus(service, status) == 0) break;

                if (status.dwCheckPoint > dwOldCheckPoint)
                {
                    // The service is making progress.
                    dwStartTickCount = Environment.TickCount;
                    dwOldCheckPoint = status.dwCheckPoint;
                }
                else
                {
                    if (Environment.TickCount - dwStartTickCount > status.dwWaitHint)
                    {
                        // No progress made within the wait hint
                        break;
                    }
                }
            }
            return (status.dwCurrentState == desiredStatus);
        }

        private static IntPtr OpenSCManager(ScmAccessRights rights)
        {
            IntPtr scm = OpenSCManager(null, null, rights);
            if (scm == IntPtr.Zero)
                throw new ApplicationException("Could not connect to service control manager.");

            return scm;
        }
    }

    public enum ServiceState
    {
        Unknown = -1, // The state cannot be (has not been) retrieved.
        NotFound = 0, // The service is not known on the host server.
        Stopped = 1,
        StartPending = 2,
        StopPending = 3,
        Running = 4,
        ContinuePending = 5,
        PausePending = 6,
        Paused = 7
    }

    [Flags]
    public enum ScmAccessRights
    {
        Connect = 0x0001,
        CreateService = 0x0002,
        EnumerateService = 0x0004,
        Lock = 0x0008,
        QueryLockStatus = 0x0010,
        ModifyBootConfig = 0x0020,
        StandardRightsRequired = 0xF0000,
        AllAccess = (StandardRightsRequired | Connect | CreateService |
                     EnumerateService | Lock | QueryLockStatus | ModifyBootConfig)
    }

    [Flags]
    public enum ServiceAccessRights
    {
        QueryConfig = 0x1,
        ChangeConfig = 0x2,
        QueryStatus = 0x4,
        EnumerateDependants = 0x8,
        Start = 0x10,
        Stop = 0x20,
        PauseContinue = 0x40,
        Interrogate = 0x80,
        UserDefinedControl = 0x100,
        Delete = 0x00010000,
        StandardRightsRequired = 0xF0000,
        AllAccess = (StandardRightsRequired | QueryConfig | ChangeConfig |
                     QueryStatus | EnumerateDependants | Start | Stop | PauseContinue |
                     Interrogate | UserDefinedControl)
    }

    public enum ServiceBootFlag
    {
        Start = 0x00000000,
        SystemStart = 0x00000001,
        AutoStart = 0x00000002,
        DemandStart = 0x00000003,
        Disabled = 0x00000004
    }

    public enum ServiceControl
    {
        Stop = 0x00000001,
        Pause = 0x00000002,
        Continue = 0x00000003,
        Interrogate = 0x00000004,
        Shutdown = 0x00000005,
        ParamChange = 0x00000006,
        NetBindAdd = 0x00000007,
        NetBindRemove = 0x00000008,
        NetBindEnable = 0x00000009,
        NetBindDisable = 0x0000000A
    }

    public enum ServiceError
    {
        Ignore = 0x00000000,
        Normal = 0x00000001,
        Severe = 0x00000002,
        Critical = 0x00000003
    }
}

Resources.Designer.cs
��//------------------------------------------------------------------------------

// <auto-generated>

//     This code was generated by a tool.

//     Runtime Version:4.0.30319.17929

//

//     Changes to this file may cause incorrect behavior and will be lost if

//     the code is regenerated.

// </auto-generated>

//------------------------------------------------------------------------------



namespace ServiceController.Properties

{





    /// <summary>

    ///   A strongly-typed resource class, for looking up localized strings, etc.

    /// </summary>

    // This class was auto-generated by the StronglyTypedResourceBuilder

    // class via a tool like ResGen or Visual Studio.

    // To add or remove a member, edit your .ResX file then rerun ResGen

    // with the /str option, or rebuild your VS project.

    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]

    internal class Resources

    {



        private static global::System.Resources.ResourceManager resourceMan;



        private static global::System.Globalization.CultureInfo resourceCulture;



        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]

        internal Resources()

        {

        }



        /// <summary>

        ///   Returns the cached ResourceManager instance used by this class.

        /// </summary>

        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]

        internal static global::System.Resources.ResourceManager ResourceManager

        {

            get

            {

                if ((resourceMan == null))

                {

                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ServiceController.Properties.Resources", typeof(Resources).Assembly);

                    resourceMan = temp;

                }

                return resourceMan;

            }

        }



        /// <summary>

        ///   Overrides the current thread's CurrentUICulture property for all

        ///   resource lookups using this strongly typed resource class.

        /// </summary>

        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]

        internal static global::System.Globalization.CultureInfo Culture

        {

            get

            {

                return resourceCulture;

            }

            set

            {

                resourceCulture = value;

            }

        }

    }

}


Settings.Designer.cs
��//------------------------------------------------------------------------------

// <auto-generated>

//     This code was generated by a tool.

//     Runtime Version:4.0.30319.17929

//

//     Changes to this file may cause incorrect behavior and will be lost if

//     the code is regenerated.

// </auto-generated>

//------------------------------------------------------------------------------



namespace ServiceController.Properties

{





    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]

    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]

    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase

    {



        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));



        public static Settings Default

        {

            get

            {

                return defaultInstance;

            }

        }

    }

}


Program.cs
using System;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Text;

namespace WindowsService1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] servicesToRun = new ServiceBase[] { new Service1() };

            ServiceBase.Run(servicesToRun);
        }
    }
}

ProjectInstaller.Designer.cs
��namespace WindowsService1

{

    partial class ProjectInstaller

    {

        /// <summary>

        /// Required designer variable.

        /// </summary>

        private System.ComponentModel.IContainer components = null;



        /// <summary> 

        /// Clean up any resources being used.

        /// </summary>

        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>

        protected override void Dispose(bool disposing)

        {

            if (disposing && (components != null))

            {

                components.Dispose();

            }

            base.Dispose(disposing);

        }



        #region Component Designer generated code



        /// <summary>

        /// Required method for Designer support - do not modify

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()

        {

            this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();

            this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();

            // 

            // serviceProcessInstaller1

            // 

            this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

            this.serviceProcessInstaller1.Password = null;

            this.serviceProcessInstaller1.Username = null;

            // 

            // serviceInstaller1

            // 

            this.serviceInstaller1.ServiceName = "Service1";

            // 

            // ProjectInstaller

            // 

            this.Installers.AddRange(new System.Configuration.Install.Installer[] {

            this.serviceProcessInstaller1,

            this.serviceInstaller1});



        }



        #endregion



        private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;

        private System.ServiceProcess.ServiceInstaller serviceInstaller1;

    }

}


ProjectInstaller.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;


namespace WindowsService1
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : System.Configuration.Install.Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }
    }
}

Service1.Designer.cs
��namespace WindowsService1

{

    partial class Service1

    {

        /// <summary> 

        /// Required designer variable.

        /// </summary>

        private System.ComponentModel.IContainer components = null;



        /// <summary>

        /// Clean up any resources being used.

        /// </summary>

        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>

        protected override void Dispose(bool disposing)

        {

            if (disposing && (components != null))

            {

                components.Dispose();

            }

            base.Dispose(disposing);

        }



        #region Component Designer generated code



        /// <summary> 

        /// Required method for Designer support - do not modify 

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()

        {

            this.eventLog1 = new System.Diagnostics.EventLog();

            ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();

            // 

            // Service1

            // 

            this.ServiceName = "Service1";

            ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();



        }



        #endregion



        private System.Diagnostics.EventLog eventLog1;

    }

}


Service1.cs
using System;
using System.IO;
using System.ServiceProcess;
using System.Timers;
using Bytescout.BarCode;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
	    private Timer _timer = null;

        public Service1()
        {
            InitializeComponent();

            if (!System.Diagnostics.EventLog.SourceExists("MySource"))
            {
                System.Diagnostics.EventLog.CreateEventSource( "MySource", "MyNewLog");
            }
            
            eventLog1.Source = "MySource";
            eventLog1.Log = "MyNewLog";
        }

        protected override void OnStart(string[] args)
        {
            eventLog1.WriteEntry("In OnStart");

			if (_timer != null)
			{
				_timer.Stop();
				_timer.Elapsed -= Timer_Elapsed;
				_timer.Dispose();
			}

			_timer = new Timer(5000);
			_timer.Elapsed += Timer_Elapsed;
			_timer.Start();
        }

	    protected override void OnStop()
        {
			eventLog1.WriteEntry("In OnStop.");
			
			if (_timer != null)
			{
				_timer.Stop();
				_timer.Elapsed -= Timer_Elapsed;
				_timer.Dispose();
				_timer = null;
			}
        }

	    void Timer_Elapsed(object sender, ElapsedEventArgs e)
	    {
		    Barcode barcode = null;

		    try
		    {
		    	// Generate sample barcode value by random number
			    Random random = new Random();
				string barcodeValue = "(00)" + random.Next().ToString("000000000000000000");

				// Create Bytescout.BarCode object and setup the barcode
			    barcode = new Barcode("demo", "demo");
			    barcode.Symbology = SymbologyType.GS1_128;
			    barcode.Value = barcodeValue;

			    string outputDirectory = "c:\\barcodes";
		        if (!Directory.Exists(outputDirectory))
		            Directory.CreateDirectory(outputDirectory);

		        string fileName = barcodeValue + ".pdf";
			    string filePath = Path.Combine(outputDirectory, fileName);

                // Save barcode to new PDF file
				barcode.DrawToNewPDF(filePath, 500, 500, 50, 50);

				eventLog1.WriteEntry("Generated " + fileName);

				// Sending email message example:
				/*
				System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
				message.To.Add("luckyperson@online.microsoft.com");
				message.Subject = fileName;
				message.From = new System.Net.Mail.MailAddress("From@online.microsoft.com");
				message.Body = "This is the message body";
				message.Attachments.Add(new System.Net.Mail.Attachment(filePath));
				
				System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("your_smtp_host");
				smtp.Send(message);
				*/
		    }
			catch (Exception exception)
			{
				eventLog1.WriteEntry(exception.Message);
			}
		    finally
		    {
			    if (barcode != null)
			    {
				    barcode.Dispose();
			    }
		    }
	    }
    }
}

Download Source Code (.zip)

Return to the previous page Explore BarCode SDK