Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Windows service

Status
Not open for further replies.

buxtonicer1

Programmer
Sep 20, 2006
82
0
0
GB
Has anyone ever used a windows service to run commands like for example DOS commands. I want to write 4 separate services that can been used to start and stop particular processes running on the same machine.
At the moment I have to do this using DOS commands at the command prompt.

E.G.

psadmin -p start -d psdmo (This is an example of the command.
Any suggestions would be great ?
Or even if I could put the commands in a batch file and call the batch file from windows service that would be useful as well.
 
A Windows Service is intended to run without any user interaction (yes, you can check the checkbox to allow interaction with the desktop, but the guys at Microsoft regret ever putting that in)

This is because services generally start when the OS starts, and not when a user logs in. As a consequence, a desktop (windowstation, technically) has not been built, so many of the things that a UI-oriented program relies on simply aren't there.

It sounds like you just want to put something in the startup folder, which gets executed when the user logs in. At this time, the desktop has already been built, so things should work naturally.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Well what I want is a windows service to run a dos command. This is what I have so far. It works in a console application but not at the moment in the windows service.

Code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;

namespace PrscShedCtrl
{
	public class Service1 : System.ServiceProcess.ServiceBase
	{
		private System.Diagnostics.EventLog eventLog1;
		/// <summary> 
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Service1()
		{
			// This call is required by the Windows.Forms Component Designer.
			InitializeComponent();
			if(!System.Diagnostics.EventLog.SourceExists("DoDyLogSourse"))
				System.Diagnostics.EventLog.CreateEventSource("DoDyLogSourse",
					"DoDyLog");

			eventLog1.Source = "DoDyLogSourse";
			// the event log source by which 

			//the application is registered on the computer

			eventLog1.Log = "DoDyLog";

			// TODO: Add any initialization after the InitComponent call
		}

		// The main entry point for the process
		static void Main()
		{
			System.ServiceProcess.ServiceBase[] ServicesToRun;
	
			// More than one user Service may run within the same process. To add
			// another service to this process, change the following line to
			// create a second service object. For example,
			//
			//   ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
			//
			ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };

			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()
		{
			this.eventLog1 = new System.Diagnostics.EventLog();
			((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
			// 
			// Service1
			// 
			this.ServiceName = "Service1";
			((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();

		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		/// <summary>
		/// Set things in motion so your service can do its work.
		/// </summary>
		protected override void OnStart(string[] args)
		{
			// TODO: Add code here to start your service.

			eventLog1.WriteEntry("my service started"); 
			
		//	/**
			System.Diagnostics.ProcessStartInfo sinf = new System.Diagnostics.ProcessStartInfo ("cmd", @"/c copy H:\temp\*.* H:\temp2");
			// The following commands are needed to redirect the standard output. 
			// This means that it will be redirected to the Process.StandardOutput StreamReader.
			sinf.RedirectStandardOutput = true;
			sinf.UseShellExecute = false;
			// Do not create that ugly black window, please...
			sinf.CreateNoWindow = true;
			// Now we create a process, assign its ProcessStartInfo and start it
			System.Diagnostics.Process p = new System.Diagnostics.Process ();
			p.StartInfo = sinf;
			p.Start (); 
			// well, we should check the return value here...
			// We can now capture the output into a string...
			string return_value = p.StandardOutput.ReadToEnd ();
		//	**/
			

			
		}
 
		/// <summary>
		/// Stop this service.
		/// </summary>
		protected override void OnStop()
		{
			// TODO: Add code here to perform any tear-down necessary to stop your service.
			 eventLog1.WriteEntry("my service stoped"); 
		}

		
	}
}
 
hmm....you may have to force an enter into the input. I had a similar problem, but unfortunately I'm not with that company any more so have no access to the code...but the gist was that I had to mimic the user pressing enter after the command. I wish I could help more than that, but I honestly can't remember the specifics.

Good luck!
-Kevin

- "The truth hurts, maybe not as much as jumping on a bicycle with no seat, but it hurts.
 
Your not serious, anyone else know how to do that I wonder. Guess more googling is required . Thanks for the help
 
One thing though - why does it work with a console application though ???? I don't hit the return type there
 
Ahh...good question...I have no idea. :) The great mysteries of working with a command prompt from an application. :) If I remember correctly, I didn't have this problem with c++, just said System("something here") and it pushed it into dos. But that was an older version (VS 6), so it may not be able to do that anymore.

Anyway,

Good luck!
-Kevin

- "The truth hurts, maybe not as much as jumping on a bicycle with no seat, but it hurts.
 
I think you missed the point of my earlier reply.

Creating this to run as a Windows Service is a bad idea, for the reasons I outlined above. And the problems you're having are a direct consequence of this.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
I did a little. Thanks for clarifying. Any other suggestion then.
 
Why would you run this as a Windows Service? Chip is right - this is a very bad idea.

If those commands need to be run after the user logs in then put them in a simple batch script file and put it into the startup folder in windows.

If you want some more control then I would create a notification icon that sits in your system tray and menu items can run these commands by sending out shell commands.
 
This web service is not related to users logging in each time. I'm probably not explaining the situation clearly enough. Here goes again.

I've got my machine, lets call it X and another machine Y (This is a server accessed using MS Terminal Services). There are certain process schedulers than run on machine Y. To access Y from X I use MS Terminal services. I only ever login to Y (using MS Terminal Services) when the process scheduler needs to be started or stopped. To start or stop the process scheduler I navigate to the relevant directory using Cmd.exe and execute certain commands. That is the as is situation at the moment.

So here is what I thought was possible but you guys think not :)

I want to create a windows service (e.g. the code in the above post that will run one command when the user right clicks on the service and hits start and one command that runs when the user right clicks on the service and clicks stop.) The windows service will be installed on machine Y (but accessed remotely from X).
Why I hear you ask ?

Well, in Windows XP you can connect remotely to windows services. So from machine X I will select the remote service access option and login to machine Y to the service in question. If the process scheduler is running I don't need to do anything. If it is not running I right click and select start to run the command in the start command. If I want to stop the process scheduler I right click the windows service, click stop and the command I need is called.

So If I want to control 4 separate process schedulers I can create 4 services, 1 to Control each of them. This gives me control of each one. The reason I'm using a windows service is the remote access feature that it gives.

But if what I'm trying to do is not possible I'm open to other suggestions. And with the issue I've encountered already I don't think it is possible.





 
hmmmm.

So here's what Chip and I have said that is probably causing you problems.

You really can't have a gui item to click on that is a Windows Service itself.

HOWEVER,

You can create a regular windows app that sits in your system tray that interacts with running services. Just do a google search on a windows service manager in C#.

Then to connect to this app remotely, you might want to look into remoting or sockets. Then your client computer can use an application that you write to interact with your system tray application which, in turn, interacts with your windows services.

Does that make any sense?
 
OK, now I understand a little better.

This will work, *as long as* the programs you're controlling on the remote servers are console apps, and do not require a desktop to interact with.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Try this

Write a batch file with the commands you want to execute and modify your code to execute this batch file instead. Only one line of code need to be modified for this test

Code:
System.Diagnostics.ProcessStartInfo sinf = new System.Diagnostics.ProcessStartInfo("cmd", @"/c C:\myBat");

Hope it will work, please let me know.

Walid Magd (MCP)

The primary challenge of every software development team is to engineer the illusion of simplicity in the face of essential complexity.
-Grady Booch
 
One issue with this is security. I'm having difficulty accessing the contents of the file. Any idea ?
 
I'm having difficulty accessing the contents of the file

Please explain

Walid Magd (MCP)

The primary challenge of every software development team is to engineer the illusion of simplicity in the face of essential complexity.
-Grady Booch
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top