namrata's profileNashaPhotosBlogListsMore ![]() | Help |
|
|
December 23 Windows Services Part - 5 ( StartUp Parameters & Service Controller )
Hi Group, This is continuation to Windows Service. I was requested to discuss how to send startup Parameters and start and stop a windows service programmatically. Let us first see how we can send startup parameters to our MoveFile windows service and even control the service programmatically. When we created this windows service we had hard coded the windows service parameters We will now pass the target folder and the destination folder as startup parameters. For this we will have to make some changes in the existing code. In MoveFile.cs we will have to add two variables for storing the target and destination folder as follows: - public class MoveFile { Thread currThread; string targetFolderPath = null; string destinationFolderPath = null; public MoveFile(string targetFolder,string destinationFolder) { targetFolderPath= targetFolder; destinationFolderPath = destinationFolder; currThread = new Thread(new ThreadStart(StartMoving)); currThread.Start(); } We now need to modify the constructor of the MoveFIle Class to take values of these two parameters as shown above. If you take a look at the OnStart function of MoveFilesService you will notice that the function takes an array of strings as an input parameter. We will modify the implementation of this function to check whether parameters are passed or not. If parameters are not passed then we set a default value to them. protected override void OnStart(string[] args) { if(args.GetLength(0) != 2) { args = new string[2]; args[0] = @"E:\FilesToMove"; args[1] = @"E:\MovedFiles"; } oMoveFile = new MoveFile(args[0],args[1]); }
To control the service we will need a service controller. . NET Framework provides us with a service controller class. So let us prepare our service controller. Open a new windows application. Add a form to it and add four buttons and one label to the form. We will use the label to display the current service status and the four buttons to start, stop, pause and resume our win service. Add reference to System.ServiceProcess at the top as follows: using System.ServiceProcess; Create an object of the service controller at the class level private System.ServiceProcess.ServiceController sc; Go to the design of your Form and add check out the properties of your service controller. One of the properties is ServiceName. Select the Service Name as your MoveFilesService. ServiceController provides you with methods to control your service. So will call these methods in the each of these button click events. Rename the buttons as Start,Stop,Pause and Resume. Currently I m passing the parameters hard coded from my service controller program you can even pick them from app config file. This is code that we need to put into the click event of each of these buttons: - private void Start_Click(object sender, System.EventArgs e) { if(sc.Status == ServiceControllerStatus.Stopped) { sc.Start(new string[]{"E:\\MovedFiles","E:\\FilesToMove"}); label2.Text = "Service Started"; } } private void Stop_Click(object sender, System.EventArgs e) { sc.Stop(); label2.Text = "Service Stopped"; } private void Pause_Click(object sender, System.EventArgs e) { if(sc.Status == ServiceControllerStatus.Running) { sc.Pause(); label2.Text = "Service Paused"; } } private void Resume_Click(object sender, System.EventArgs e) { if(sc.Status == ServiceControllerStatus.Paused) { sc.Continue(); label2.Text = "Service Resumed"; } } Run the application and check out the functionality. If you explore other functions of Service Controller (static functions) you will find that it provides you with functions to enlist services, device services etc. e.g. ServiceController.GetServices ServiceController.GetDevices December 12 Windows Services Part - 4In the past 3 days we have created our windows service, added installers to it, Created event logged our service today we will add performance counters.
Windows Services Part - 3After creating our windows service today we will see how we can add event logging to it. Windows Services Part - 2Yesterday we created our MoveFiles Windows Service. Today we will add installers to our windows service, install our service and then go ahead and debug our service. Windows Services Part - 1Windows services are applications that start as soon as the OS starts although they can be configured to start manually. To view all the windows services available on your machine you can go to Start -> Settings-> Control Panel -> Admistrative Tools -> Services. A windows service can run under a specific user or under the system user. Generally all those applications that do not require any human intervention are preferred as windows service, say a background job. Today the service that we will create will move the files from one location to another location. Open a windows service application let the Service1.cs remain as it is now. We will come back to it a little later. Add a new class and name it MoveFile.cs So let us start by creating a simple class called MoveFile. Add the following references to MoveFile using System; using System.Threading; using System.IO; In this class we will create we will declare a private thread. This thread will initiate the file movement from one folder to another. public class MoveFile { Thread currThread; public MoveFile() { currThread = new Thread(new ThreadStart(StartMoving)); currThread.Start(); } } In the constructor of the class we create a new thread by setting its thread start and start the thread. As soon as our thread will be started StartMoving will be called. So Let us check out its implementation public void StartMoving() { while(1==1) { string[] files = Directory.GetFiles(@"E:\FilesToMove"); for(int i=0;i<files.GetUpperBound(0);i++) { File.Move(files[i],@"E:\MovedFiles" +files[i].Substring(files[i].LastIndexOf("\\"))); Console.WriteLine(files[i]); } } } Note : For the sake of simplicity and demo purpose the paths have been hardcoded. You can add an application config file and read the paths from there. Here I am having two folders FilesToMove and MovedFiles in my E: I am having a while loop which continuously checks for files in my FilestoMove folder and if there are any files in it I am moving them to MovedFiles. Since a windows service can be stopped, paused, resumed and abort we want our service to also exhibit the same behavior. So let us add functions to MoveFile for the same. public void PauseMoving() { currThread.Suspend(); } public void StopMoving() { currThread.Abort(); } public void ResumeMoving() { currThread.Resume(); } This class is a generic class, you can also use it with a normal windows or console application. But we will create a windows service using it. All the classes, which are required for creating a windows service, are present in System.ServiceProcess Namespace. Any service that we create has to inherit from ServiceBase class. This class is used to register the service and handle its events. Coming back to Service1.cs rename it to MoveFilesService. Please see to it that you change the name in solution explorer as well as the class constructor. In InitailizeCompoment function there is a statement which talks about the service name ( as shown below) please make the changes there also. this.ServiceName = "MoveFilesService"; In the Main function of your service class checkout Services added to your ServicesToRun Array change it to MoveFilesService ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MoveFilesService() }; Check out the name in properties of your MoveFilesService class. Compile your project , it should not give you any errors. Go to the properties of MoveFile and set AutoLog = true CanPauseAndContinue = true CanStop = true Add a private variable of MoveFile to MoveFileService class. public class MoveFilesService : System.ServiceProcess.ServiceBase { MoveFile oMoveFile; We will now add code to OnStart method of our Service Class where we will instantiate an object of MoveFile. protected override void OnStart(string[] args) { oMoveFile = new MoveFile(); } ServiceBase class has got methods to Pause, Stop and Resume a service. We will have to override them and provide an implementation to pause, stop and resume our service as follows. protected override void OnPause() { oMoveFile.PauseMoving(); } protected override void OnStop() { oMoveFile.StopMoving(); } protected override void OnContinue() { oMoveFile.ResumeMoving(); } The methods that we had made in our MoveFile class are called here. Hence whenever our windows service is paused our thread will also exhibit the same behavior. Compile the project and see that you don't get any errors will see how to install our windows service tomorrow. |
|
|