0

I'm using a windows service and a windows form. I have been trying to send custom commands to a service in order to create an isolated storage file. However when I click my "btnSubmit" no file is created. For some reason it doesn't seem to execute the command

Code in Form

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);
        }
    }
}

}

My Service Controller

       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 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;
    }
}
Craig Gallagher
  • 235
  • 1
  • 5
  • 19
  • Did you confirm that the ServiceController is properly connected in your form? When you refresh the sc, does the status say the service is running? Also, did you confirm that the correct code value is being received in `OnCustomCommand` (either through a log file, or by connecting to the service in the debugger)? – Nathan C Jan 20 '16 at 18:55
  • You're going to have to show more code... You have a windows service that is deployed on your local machine, and you're trying to execute methods inside of it from a windows forms application? Did you place a breakpoint in that method? I'm going to guess it's not getting executed. You need to provide complete methods and signatures as well and not just code fragments. – ragerory Jan 20 '16 at 18:56
  • Updated my `OnCustomCommand` method @ragerory anf tes my service does run and it is properly connected to the form @Nathan C – Craig Gallagher Jan 20 '16 at 19:05
  • Have you put a break point in the form to make sure that it is reaching the `ExecuteCommand` line? Have you put a break point in the service's `OnCustomCommand` to make sure it is entering the function? – Nathan C Jan 20 '16 at 19:16
  • I put a brake point in the form and for some reason it's not reaching the `OnCustomCommand` method. The button methods is executing and the if statement is working however the `sc.ExecuteCommand(128);` is not working – Craig Gallagher Jan 20 '16 at 19:40
  • Can you post your code where you instantiate the communication with your windows service? See http://stackoverflow.com/questions/4451216/how-to-communicate-with-a-windows-service – David P Jan 20 '16 at 19:44
  • I added code @David P – Craig Gallagher Jan 20 '16 at 20:01
  • @CraigGallagher I believe DavidP is asking for the code in your Forms application that establishes the communication with your service. – ragerory Jan 20 '16 at 20:02
  • Added all code I have in the From. Thanks guys for the help :) – Craig Gallagher Jan 20 '16 at 20:18
  • Are you sure it's deployed and running as `Project2Service`? – ragerory Jan 20 '16 at 21:55
  • The service is running as `Project2Service` – Craig Gallagher Jan 20 '16 at 22:02

1 Answers1

0

I think you need to add ServieControllerPermission:

ServiceController sc = new ServiceController("YOURServiceName", Environment.MachineName);
ServiceControllerPermission scp = new ServiceControllerPermission(ServiceControllerPermissionAccess.Control,   Environment.MachineName, "YOURServiceName");//this will grant permission to access the Service
scp.Assert();
sc.Refresh();

sc.ExecuteCommand((int)YourMethods.methodX);
David P
  • 2,027
  • 3
  • 15
  • 27