Solved

Windows services

Posted on 2004-08-16
13
261 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
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
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
 
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

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Code works but it's slow 28 71
Install Problem 13 32
Call windows 10 virtual keyboard from windows forms app 2 36
What Does This C# Code Block Do? 5 33
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

831 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