Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 273
  • Last Modified:

Windows services

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
DaFou
Asked:
DaFou
  • 6
  • 4
  • 2
  • +1
1 Solution
 
JigitCommented:
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
 
DaFouAuthor Commented:
'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
 
hatukazeCommented:
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
DaFouAuthor Commented:
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
 
hatukazeCommented:

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
 
gregoryyoungCommented:
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
 
gregoryyoungCommented:
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
 
DaFouAuthor Commented:
does making the method static make it thread safe?
0
 
DaFouAuthor Commented:
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
 
gregoryyoungCommented:
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
 
DaFouAuthor Commented:
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
 
DaFouAuthor Commented:
0

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

  • 6
  • 4
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now