C#
  Home arrow C# arrow Page 2 - Creating a Windows Service with C#, contin...
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Moblin 
JMSL Numerical Library 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Creating a Windows Service with C#, continued
By: David Fells
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 26
    2006-03-07

    Table of Contents:
  • Creating a Windows Service with C#, continued
  • Creating the Windows Service Project
  • Coding the Service
  • Installing the Service

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Creating a Windows Service with C#, continued - Creating the Windows Service Project


    (Page 2 of 4 )

    Add a new project to the TimeApp solution called “TimeService” and rename the “Service1” class “TimeServerService.” Be sure to use the find and replace tool to rename “Service1” to TimeServerService in the class file itself, because it appears in several places: the class name, the constructor, and the ServicesToRun array in the Main() method. Next you need to change a few properties of the TimeServerService.cs in design view. Change the ServiceName property to “Time Server Service” and change “CanShutdown” to “True.”

    Once you have changed those properties, click the “Add Installer” link.  This will add a file named “ProjectInstaller.cs” to your project. In the “ProjectInstaller.cs” design view, you need to set the “StartType” property to “Manual” for the ServiceInstaller and set the “Account” property to “LocalSystem” for the ServiceProcessInstaller. Save and close the project installer files; they are finished.

    Now that the project is set up, we need to open up the TimeServer.cs file in the TimeApp project and get ready to move it over to the TimeServerService.cs class.

    First we need to add the System.Net, System.Net.Sockets, and System.Text namespaces to the TimeServerService class. Then copy over the listener field and the readonly fields ip and port from TimeServer. Copy the entire Start() method from TimeServer to TimeServerService next. Add a call to listener.Start() in the OnStart() method, which is called implicitly when a Windows Service is started, and in the TimeServerService constructor paste the line that instantiates the TcpListener from TimeServer.Main().

    Your service class should look like this when you’re done (note that I have removed the massive comment blocks that come with the Windows Service class):

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.ServiceProcess;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
     
    namespace TimeService
    {
       public class TimeServerService :
    System.ServiceProcess.ServiceBase
       {
           /// <summary> 
           /// Required designer variable.
           /// </summary>
           private System.ComponentModel.Container components = null;
     
           private readonly int port = 48888;
           private readonly IPAddress ip = IPAddress.Parse
    ("127.0.0.1");
          private TcpListener listener;
     
           public TimeServerService()
           {
              InitializeComponent();
              this.listener = new TcpListener(port, ip);
           }
     
           // The main entry point for the process
           static void Main()
           {
              System.ServiceProcess.ServiceBase[] ServicesToRun;
          
              ServicesToRun = new System.ServiceProcess.ServiceBase[]
    {                             new TimeServerService() };
     
              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()
           {
              //
              // TimeServerService
              //
              this.CanShutdown = true;
              this.ServiceName = "Time Server Service";
           }
     
           protected override void Dispose( bool disposing )
           {
              if( disposing )
              {
                 if (components != null)
                 {
                    components.Dispose();
                 }
              }
              base.Dispose( disposing );
           }
     
          protected override void OnStart(string[] args)
          {
             this.Start();
          }
     
          protected override void OnStop()
          {
          }
     
          public void Start()
          {
             this.listener.Start();
     
             Socket s;
             Byte[] incomingBuffer;
             Byte[] time;
             int bytesRead;
     
             while (true)
             {
                s = this.listener.AcceptSocket();
               
                incomingBuffer = new Byte[100];
                bytesRead = s.Receive(incomingBuffer);
     
                time = Encoding.ASCII.GetBytes(
                   System.DateTime.Now.ToString().ToCharArray());
                s.Send(time);
             }
          }
       }
    }



    Look at the Main() method. You will notice that it’s quite different from the Main() method of a console or form application. With a Windows Service, the Main() method creates an array of services to run and runs them. Of course, “running” simply means creating an instance of the class and calling the OnStart() method.

    More C# Articles
    More By David Fells


       · Thanks for reading!
       · I read this article as I was doing a similar thing to make a Quote of the day...
       · Hi,I followed this article in creating the windows service but it hangs. I...
       · I'm seeing the same problem, has any come up with a fix? It will not shutdown until...
       · Now I am not certain what the exact way to do this is in C#/.NET, however in Java...
       · Pls Could you tell me how can I use .Net 2005 with this project. I can,t find some...
       · Close the socket from the OnStop and any waiting operation on that socket will...
     

    C# ARTICLES

    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#
    - Working with Regular Expressions in C#
    - Sending Simple E-Mail in C#
    - Building C# Comparable Objects: IComparable ...
    - Color Transformation Applications in C# GDI+...
    - Performing Color Transformation Operations i...
    - Color Transformation in C# GDI+ Programming
    - Exceptions in C#
    - Overriding versus Overloading
    - Value Types and Reference Types
    - Defining Member and Type Visibility
    - Managing Files in C#





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway
    Stay green...Green IT