Learner
Learner

Reputation: 1376

How to access the property of windows service from application

I have a windows service which contains a property of return type DataTable

public partial class ServiceForCount : ServiceBase
{
    public DataTable AllData
    {
        get;
        set;
    }
    public ServiceForCount()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
    }
    protected override void OnStop()
    {
    }
    protected override void OnCustomCommand(int sizeOfFile)
    {
        //base.OnCustomCommand(command);
    }
}

If I want to call events from my application I can call like

   ServiceController sc = new ServiceController("ServiceForCount");
  sc.ExecuteCommand(size);

I want to get the DataTable into my application. How can I do it.

Upvotes: 1

Views: 1839

Answers (2)

Marcel N.
Marcel N.

Reputation: 13976

You cannot do that with ServiceController.ExecuteCommand. It is one way only and its purpose is not that anyway.

You could do it by hosting a web service in the windows service (WCF self hosted, WebApi OWIN self hosted) or with remoting. All the web service needs to expose is a method that returns not the datatable but as list of objects. So you need to convert the DataTable to an IEnumerable<DataObject> where DataObject is your service contract.

You could look into these for starters:

  1. WebApi 2 Self Hosted Web Services.
  2. How to host a WCF Service in a managed application.

Upvotes: 4

Emond
Emond

Reputation: 50672

To communicate with a Windows Service the service needs to provide an endpoint.

The service could open a socket and start listening for incoming messages/requests. As a response the service could serialize the data table (or any other object) and pass it back.

See: Socket Server in Windows Service

As for the protocol: you could serialize data using standard Xml serialization or JSON. For the commands you could implement a REST API or SOAP API. Just be careful not to re-implement WCF; if you need all the features of WCF just use it.

Upvotes: 2

Related Questions