使用Windows窗体将自定义命令发送到服务

时间:2016-01-20 21:09:25

标签: c# windows forms service isolatedstorage

我正在尝试使用Windows窗体向服务发送自定义命令。我尝试发送的命令是尝试将文件放在隔离存储中。以下是我的源代码。

表格

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Project2Service;

namespace Project2
{
    public partial class Form1 : Form
    {
        public Service1 s = new Service1();
        public ServiceInstaller si = new ServiceInstaller();
        public ProjectInstaller pi = new ProjectInstaller();
        public ServiceController sc = new ServiceController("Project2Service");

        private string[] isoType;

        string machineName = System.Windows.Forms.SystemInformation.ComputerName;

        public Form1()
        {
            InitializeComponent();

            isoType = new string[] { "User", "Assembly And Domain"};
            cboIsoType.Items.AddRange(isoType);

            cboIsoType.SelectedIndex = 0;

            btnContinue.Enabled = false;
            btnPause.Enabled = false;
            btnStop.Enabled = false;
        }

        public void Labels()
        {
            lblMachine.Text = machineName;
            lblSName.Text = s.ServiceName;
            lblSType.Text = si.StartType.ToString();

            lblSStatus.Text = sc.Status.ToString();
            lblPause.Text = sc.CanPauseAndContinue.ToString();
            lblShutdown.Text = sc.CanShutdown.ToString();
            lblStop.Text = sc.CanStop.ToString();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            //Controller.Refresh(); //Gets the current status of service
            //if (Controller.Status == ServiceControllerStatus.Stopped)
            //{
            //    Controller.Start();
            //}

            sc.Start();
            sc.WaitForStatus(ServiceControllerStatus.Running);
            Labels();

            btnStart.Enabled = false;
            btnContinue.Enabled = false;
            btnStop.Enabled = true;
            btnPause.Enabled = true;

        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            sc.Stop();
            sc.WaitForStatus(ServiceControllerStatus.Stopped);
            Labels();

            btnStart.Enabled = true;
            btnContinue.Enabled = false;
            btnPause.Enabled = false;
            btnStop.Enabled = false;
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            sc.Pause();
            sc.WaitForStatus(ServiceControllerStatus.Paused);
            Labels();

            btnPause.Enabled = false;
            btnContinue.Enabled = true;
            btnStart.Enabled = false;
            btnStop.Enabled = true;
        }

        private void btnContinue_Click(object sender, EventArgs e)
        {
            sc.Continue();
            sc.WaitForStatus(ServiceControllerStatus.Running);
            Labels();

            btnStop.Enabled = true;
            btnStart.Enabled = false;
            btnPause.Enabled = true;
            btnContinue.Enabled = false;
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {  
            if (cboIsoType.SelectedItem.ToString() == "User")   
            {

                sc.ExecuteCommand(128);
            }
        }
    }
}

服务

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace Project2Service
{
    public partial class Service1 : ServiceBase
    {
        public enum ServiceCustomCommands { Command1 = 128, Command2 = 129 };
        //private IsolatedStorageScope iso;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            //iso = IsolatedStorageScope.User | IsolatedStorageScope.Domain;
            FileSystemWatcher Watcher = new FileSystemWatcher(@"C:\Users\Martin\Desktop\Project2\ServiceTest");
            Watcher.EnableRaisingEvents = true;
            Watcher.NotifyFilter = NotifyFilters.LastAccess
                        | NotifyFilters.LastWrite
                        | NotifyFilters.FileName
                        | NotifyFilters.DirectoryName;

            Watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
            Watcher.Created += new FileSystemEventHandler(Watcher_Created);
            Watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
            Watcher.Renamed += new RenamedEventHandler(Watcher_Renamed);
            WriteServiceInfo("Service Started!");
        }

        // This event is raised when a file is changed
        private void Watcher_Changed(object sender, FileSystemEventArgs e)
        {
            WriteServiceInfo("File Changed!");

            DirectoryInfo d = new DirectoryInfo(@"C:\Users\Martin\Desktop\Project2\ServiceTest");//Assuming Watch is your Folder
            FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
            string str = "";
            foreach (FileInfo file in Files)
            {
                str = str + ", " + file.Name;
                str = str + ", " + file.LastWriteTime;
                str = str + ", " + file.CreationTime;
                str = str + ", " + file.Length;

                WriteServiceInfo(file.Name);
                WriteServiceInfo(file.LastWriteTime.ToString());
                WriteServiceInfo(file.CreationTime.ToString());
                WriteServiceInfo(file.Length.ToString());
            }
        }

        private void Watcher_Created(object sender, FileSystemEventArgs e)
        {
            WriteServiceInfo("File Created!");
        }

        private void Watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            WriteServiceInfo("File Deleted!");
        }
        private void Watcher_Renamed(object sender, FileSystemEventArgs e)
        {
            WriteServiceInfo("File Renamed!");
        }

        private void WriteServiceInfo(string info)
        {
            FileStream fs = new FileStream(@"C:\Users\Martin\Desktop\Project2\WindowsServiceLog.txt",
                                 FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(info + "\n");
            m_streamWriter.Flush();
            m_streamWriter.Close();
        }

        protected override void OnStop()
        {
            WriteServiceInfo("Service Stopped!");

        }

        protected override void OnCustomCommand(int command)
        {


            switch ((ServiceCustomCommands)command)
            {
                case ServiceCustomCommands.Command1:
                    //Command1 Implementation
                    IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
                    IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("LaptopInfo.txt", FileMode.Append, FileAccess.Write, isoFile);
                    using (StreamWriter writer = new StreamWriter(isoStream))
                    {
                        writer.WriteLine("Data");
                    }
                    //iso = IsolatedStorageScope.User;
                    break;
                case ServiceCustomCommands.Command2:
                    //iso = IsolatedStorageScope.User | IsolatedStorageScope.Assembly;
                    break;
                default:
                    break;

            }
        }
    }
}

sc.ExecuteCommand(128);在提交按钮方法似乎没有触发。

1 个答案:

答案 0 :(得分:1)

这对我来说很好,所以我猜测你的代码没有按下执行命令的调用。我拿了你的代码,让它更容易一些。

例如 - 删除上面的所有内容 - 下面的代码工作,文本文件出现在" Command Received"在它。

在您的情况下,可能是您没有关闭文件。试试这个:

using (
    IsolatedStorageFile isoFile =
        IsolatedStorageFile.GetStore(
            IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly,
            null, null))
{
    IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("LaptopInfo.txt",
        FileMode.Append, FileAccess.Write, isoFile);
    using (StreamWriter writer = new StreamWriter(isoStream))
    {
        writer.WriteLine("Data");
    }
    WriteServiceInfo("data written to isolated storage");
    isoFile.Close();
}

我更改了提交按钮以发送命令,我建议使用相同的

private void btnSubmit_Click(object sender, EventArgs e)
{
     sc.ExecuteCommand(128);
}

服务代码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace Project2Service
{
    public partial class Service1 : ServiceBase
    {
        public enum ServiceCustomCommands { Command1 = 128, Command2 = 129 };
        //private IsolatedStorageScope iso;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            WriteServiceInfo("Service Started!");
        }

        // This event is raised when a file is changed
        private void Watcher_Changed(object sender, FileSystemEventArgs e)
        {
            WriteServiceInfo("File Changed!");
        }

        private void Watcher_Created(object sender, FileSystemEventArgs e)
        {
            WriteServiceInfo("File Created!");
        }

        private void Watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            WriteServiceInfo("File Deleted!");
        }
        private void Watcher_Renamed(object sender, FileSystemEventArgs e)
        {
            WriteServiceInfo("File Renamed!");
        }

        private void WriteServiceInfo(string info)
        {
            FileStream fs = new FileStream(@"C:\Users\Adam\Desktop\WindowsServiceLog.txt",
                                 FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(info + "\n");
            m_streamWriter.Flush();
            m_streamWriter.Close();
        }

        protected override void OnStop()
        {
            WriteServiceInfo("Service Stopped!");

        }

        protected override void OnCustomCommand(int command)
        {

            WriteServiceInfo("Command received");
            switch ((ServiceCustomCommands)command)
            {
                case ServiceCustomCommands.Command1:
                    //Command1 Implementation
                    IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
                    IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("LaptopInfo.txt", FileMode.Append, FileAccess.Write, isoFile);
                    using (StreamWriter writer = new StreamWriter(isoStream))
                    {
                        writer.WriteLine("Data");
                    }
                    //iso = IsolatedStorageScope.User;
                    break;
                case ServiceCustomCommands.Command2:
                    //iso = IsolatedStorageScope.User | IsolatedStorageScope.Assembly;
                    break;
                default:
                    break;

            }
        }
    }
}