netmonitor/NetMonitorServer/SetService.cs

96 lines
3.2 KiB
C#
Raw Normal View History

2011-01-27 00:35:09 +01:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
namespace NetMonitorServer
{
class SetService
{
UdpClient net_send = new UdpClient();
IPEndPoint net_send_port = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 34524);
System.ServiceProcess.ServiceController serviceController;
public SetService(string data)
{
this.serviceController = new System.ServiceProcess.ServiceController();
if (data.Substring(0, 13).ToLower() == "service start")
this.setServiceStart(data);
if (data.Substring(0, 12).ToLower() == "service stop")
this.setServiceStop(data);
if (data.Substring(0, 14).ToLower() == "service status")
this.getServiceStatus(data);
}
private void setServiceStart(string data)
{
String[] par = data.Split(' ');
if (par.Length != 3)
return;
this.serviceController.ServiceName = par[2];
2011-01-27 11:19:41 +01:00
try
{
this.serviceController.Start();
this.serviceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, new TimeSpan(0, 0, 30));
}
catch (Exception)
{
this.sendStr("false");
}
2011-01-27 00:35:09 +01:00
if (this.serviceController.Status == System.ServiceProcess.ServiceControllerStatus.Running)
2011-01-27 11:19:41 +01:00
this.sendStr("true");
2011-01-27 00:35:09 +01:00
else
2011-01-27 11:19:41 +01:00
this.sendStr("false");
2011-01-27 00:35:09 +01:00
}
private void setServiceStop(string data)
{
String[] par = data.Split(' ');
if (par.Length != 3)
return;
this.serviceController.ServiceName = par[2];
2011-01-27 11:19:41 +01:00
try
{
this.serviceController.Stop();
this.serviceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30));
}
catch (Exception)
{
this.sendStr("false");
}
2011-01-27 00:35:09 +01:00
if (this.serviceController.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
2011-01-27 11:19:41 +01:00
this.sendStr("true");
2011-01-27 00:35:09 +01:00
else
2011-01-27 11:19:41 +01:00
this.sendStr("false");
2011-01-27 00:35:09 +01:00
}
private void getServiceStatus(string data)
{
String[] par = data.Split(' ');
if (par.Length != 3)
return;
2011-01-27 11:19:41 +01:00
try
{
this.serviceController.ServiceName = par[2];
if (this.serviceController.Status == System.ServiceProcess.ServiceControllerStatus.Running)
this.sendStr("true");
else
this.sendStr("false");
}
catch (Exception)
{
this.sendStr("false");
}
}
private void sendStr(string p)
{
byte[] answ = Encoding.UTF8.GetBytes(p);
2011-01-27 00:35:09 +01:00
net_send.Send(answ, answ.Length, net_send_port);
}
}
}