Solved

Windows services

Posted on 2004-08-16
13
257 Views
Last Modified: 2010-04-15
Ola,

I have made a service that can be started and stopped. But how do I run method in the service from asp.net?
I'd like an example in c# please.

This is some code of my service:

using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;

namespace DHTMLchatService
{
      public class DHTMLchatServer : System.ServiceProcess.ServiceBase
      {
            private System.ComponentModel.Container components = null;
            public DHTMLchatServer()
            {
                  InitializeComponent();
            }
            static void Main()
            {
                  System.ServiceProcess.ServiceBase[] ServicesToRun;
                  ServicesToRun = new System.ServiceProcess.ServiceBase[] { new DHTMLchatServer() };
                  System.ServiceProcess.ServiceBase.Run(ServicesToRun);
            }
            private void InitializeComponent()
            {
                  components = new System.ComponentModel.Container();
                  this.ServiceName = "DHTMLchatServer";
            }
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }
            protected override void OnStart(string[] args)
            {
                  FileStream fs = new FileStream(@"c:\tester.txt", FileMode.OpenOrCreate, FileAccess.Write);
                  StreamWriter m_streamWriter = new StreamWriter(fs);
                  m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                  m_streamWriter.WriteLine(" The service is started \n");
                  m_streamWriter.Flush();
                  m_streamWriter.Close();
            }
            protected override void OnStop()
            {
                  FileStream fs = new FileStream(@"c:\tester.txt", FileMode.OpenOrCreate, FileAccess.Write);
                  StreamWriter m_streamWriter = new StreamWriter(fs);
                  m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                  m_streamWriter.WriteLine(" The service is stopped \n");
                  m_streamWriter.Flush();
                  m_streamWriter.Close();
            }
            // this method should be accessable from ASP.NET.
            public void WriteToFile( string iStrTextToWrite )
            {
                  FileStream fs = new FileStream(@"c:\tester.txt", FileMode.OpenOrCreate, FileAccess.Write);
                  StreamWriter m_streamWriter = new StreamWriter(fs);
                  m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                  m_streamWriter.WriteLine( iStrTextToWrite + " \n" );
                  m_streamWriter.Flush();
                  m_streamWriter.Close();
            }
      }
}

how can this be done?
0
Comment
Question by:DaFou
  • 6
  • 4
  • 2
  • +1
13 Comments
 
LVL 4

Expert Comment

by:Jigit
Comment Utility
System.ServiceProcess.ServiceController sc2 =
  new System.ServiceProcess.ServiceController("ServiceName", "MACHINE_NAME");
if (sc2.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Running))
{
  sc2.Stop();
}

Don't forget to add reference to System.ServiceProcess.dll

HTH,
Jigit
0
 
LVL 2

Author Comment

by:DaFou
Comment Utility
'System.ServiceProcess.ServiceController' does not contain a definition for 'WriteToFile'

when using:

System.ServiceProcess.ServiceController sc2 = new System.ServiceProcess.ServiceController( "DHTMLchatServer", "PRIMUS" );
if ( sc2.Status.Equals( System.ServiceProcess.ServiceControllerStatus.Running ) )
{
      sc2.WriteToFile( "Does it work? no it does not" );
}

please keep in mind the code I posted in my original question
0
 

Expert Comment

by:hatukaze
Comment Utility
You want a web page to call a method on a windows service? Why not create a web service?

Take a look at this tutorial: http://www.15seconds.com/issue/010430.htm
0
 
LVL 2

Author Comment

by:DaFou
Comment Utility
I dont want to make it a web service because I am not making a web service.

I am making a windows service that collects incomming HTTP requests, stores them and responds to them. Imagine a hyper efficient DHTML only chat application.
0
 

Expert Comment

by:hatukaze
Comment Utility

Ok.. Here is an easy way to do it:

Open your asp page in Visual Studio. Locate your windows service in your service
explorer window. Drag it onto your webpage.

A automatically configured ServiceController will be added to your webpage.

You can then call any methods, including Start and Stop.
0
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
In order to do this you would need to setup up some form of IPC between your webserver and the service. An example of this would be to use remoting to call objects hosted in the service. A much simpler version would to communicate through MSMQ, files, or a database. Another method you may want to look into would be to just use sockets to communicate back and forth between the two, this could allow othe forms of clients to connect to the service as well.

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
I also notice that your method located in your service (WriteToFile) is not threadsafe which might cause you problems if you are calling it from IIS since it may have multiple threads calling it.
0
 
LVL 2

Author Comment

by:DaFou
Comment Utility
does making the method static make it thread safe?
0
 
LVL 2

Author Comment

by:DaFou
Comment Utility
I really would like an example of some code.
I added the service via drag and drop and the only code being generated is:
this.serviceController1 = new System.ServiceProcess.ServiceController();
this.serviceController1.MachineName = "primus";
this.serviceController1.ServiceName = "DHTMLchatServer";

IT still does not run.

How do I use remoting?
0
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
in that case no because you are accessing the same file, the second thread would fail because the file was open or even worse it could succeed and garble data being written to the file

putting a lock() { } around it would insure only one thread ran through at a time.
0
 
LVL 37

Accepted Solution

by:
gregoryyoung earned 500 total points
Comment Utility
0
 
LVL 2

Author Comment

by:DaFou
Comment Utility
Ok Remoting it is, but the biook i have has an example that does not do what I want.

In the example I created a client ( winForm ), a remotingObject ( classlib ) and a server ( win service ).
the client sets up the remote object with type of the RemoteObject and it connects to the server.
The server has already setup a ChannelService and listens for incomming procedure calls to the remote object.
The remote object now returns some integer to the client.

This is not what I want. I want the client to invoke a mothod from the server and pass it some parameter.
how do i adjust my code?

//client ( winform )
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using RemoteObject;


namespace RemoteClient
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            private System.Windows.Forms.Button button1;
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (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.button1 = new System.Windows.Forms.Button();
                  this.SuspendLayout();
                  //
                  // button1
                  //
                  this.button1.Location = new System.Drawing.Point(24, 24);
                  this.button1.Name = "button1";
                  this.button1.TabIndex = 0;
                  this.button1.Text = "button1";
                  this.button1.Click += new System.EventHandler(this.button1_Click);
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(292, 273);
                  this.Controls.Add(this.button1);
                  this.Name = "Form1";
                  this.Text = "Form1";
                  this.ResumeLayout(false);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  Application.Run(new Form1());
            }

            private void button1_Click(object sender, System.EventArgs e)
            {
                  RemoteObject.IDGenerator remObject = (RemoteObject.IDGenerator)Activator.GetObject(
                        typeof(RemoteObject.IDGenerator),
                        "http://localhost:8085/RemotingServer"
                        );
                  System.Windows.Forms.MessageBox.Show( Convert.ToString( remObject.getID() ) );
            }
      }
}


// Remote Object ( Class Library )
using System;

namespace RemoteObject
{
      public class IDGenerator : System.MarshalByRefObject
      {
            private int lastID = 0;
            public int getID()
            {
                  return( lastID++ );
            }
      }
}

// Server ( windows service )
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Configuration.Install;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Threading;

namespace RemoteService
{
      public class Service1 : System.ServiceProcess.ServiceBase
      {

            private System.ComponentModel.Container components = null;

            public Service1()
            {
                  InitializeComponent();
            }
            static void Main()
            {
                  System.ServiceProcess.ServiceBase[] ServicesToRun;
                  ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
                  System.ServiceProcess.ServiceBase.Run(ServicesToRun);
            }
            private void InitializeComponent()
            {
                  components = new System.ComponentModel.Container();
                  this.ServiceName = "Service1";
            }
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }
            Thread thdServer;
            protected override void OnStart(string[] args)
            {
                  thdServer = new Thread( new ThreadStart( serverThread ) );
                  thdServer.Start();
            }
            protected override void OnStop()
            {
                  thdServer.Abort();
            }
            public void serverThread()
            {
                  HttpChannel channel = new HttpChannel( 8085 );
                  ChannelServices.RegisterChannel( channel );
                  RemotingConfiguration.RegisterWellKnownServiceType(
                        typeof( RemoteObject.IDGenerator ),
                        "RemotingServer",
                        WellKnownObjectMode.Singleton
                  );

            }
                                // method that should be called from a client.
                                public void DoSomething()
                                {}
      }
}
0
 
LVL 2

Author Comment

by:DaFou
Comment Utility
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now