Solved

Windows services

Posted on 2004-08-16
13
259 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
ID: 11808762
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
ID: 11809213
'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
ID: 11809401
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
ID: 11809440
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
ID: 11809544

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
ID: 11810473
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 37

Expert Comment

by:gregoryyoung
ID: 11810501
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
ID: 11810513
does making the method static make it thread safe?
0
 
LVL 2

Author Comment

by:DaFou
ID: 11810657
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
ID: 11810666
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
ID: 11810744
0
 
LVL 2

Author Comment

by:DaFou
ID: 11832030
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
ID: 11836118
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

867 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

17 Experts available now in Live!

Get 1:1 Help Now