Windows service communication with application

Tutorial: Get started with Windows Communication Foundation applications

The following series of tutorials introduce you to the Windows Communication Foundation (WCF) programming experience. Working through these tutorials in order will give you an introductory understanding of the steps required to create WCF applications. After you finish, you’ll have a running WCF service and a WCF client that calls the service.

The tutorial assumes you’re using Visual Studio as the development environment. If you’re using another development environment, ignore the Visual Studio-specific instructions.

For sample WCF applications that you can download and run, see Windows Communication Foundation samples. For an introduction to the samples, see Getting started sample.

For more in-depth information about creating services and clients, see Basic WCF programming.

WCF tutorials

The first three tutorials describe how to define a WCF service contract, how to implement it, and how to host it. The service that you create is self-hosted within a console application. You can also host services under Microsoft Internet Information Services (IIS). For more information, see How to: Host a WCF Service in IIS. Although you use code to configure the service in the tutorial, you can also configure services within a configuration file.

You create a WCF contract with a user-defined interface. This contract defines the functionality that the service exposes.

After you define a contract, you must implement it with a service class.

Configure an endpoint for the service and host the service in a console application. For a service to become active, you must configure it and host it within a run-time environment. This run-time environment creates the service and controls its context and lifetime.

The next two tutorials describe how to create, configure, and use a client application to call the operations the service exposes. Services publish metadata that define the information a client application needs to communicate with the service. Visual Studio automates the process of accessing this metadata and uses it to construct the client application for the service. If you decide not to use Visual Studio, you can use the ServiceModel Metadata Utility tool (Svcutil.exe) instead.

Retrieve metadata for creating a WCF client proxy from a WCF service. You retrieve metadata by using Visual Studio to add a service reference or you can use the ServiceModel Metadata Utility tool. You specify the endpoint that the client uses to access the service.

Use the WCF client proxy to call the service operations.

Introduction to Windows Service Applications

Microsoft Windows services, formerly known as NT services, enable you to create long-running executable applications that run in their own Windows sessions. These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface. These features make services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer. You can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account. For more information about services and Windows sessions, see the Windows SDK documentation.

You can easily create services by creating an application that is installed as a service. For example, suppose you want to monitor performance counter data and react to threshold values. You could write a Windows Service application that listens to the performance counter data, deploy the application, and begin collecting and analyzing data.

You create your service as a Microsoft Visual Studio project, defining code within it that controls what commands can be sent to the service and what actions should be taken when those commands are received. Commands that can be sent to a service include starting, pausing, resuming, and stopping the service; you can also execute custom commands.

Читайте также:  Windows hyper v sp1

After you create and build the application, you can install it by running the command-line utility InstallUtil.exe and passing the path to the service’s executable file. You can then use the Services Control Manager to start, stop, pause, resume, and configure your service. You can also accomplish many of these same tasks in the Services node in Server Explorer or by using the ServiceController class.

Service Applications vs. Other Visual Studio Applications

Service applications function differently from many other project types in several ways:

The compiled executable file that a service application project creates must be installed on the server before the project can function in a meaningful way. You cannot debug or run a service application by pressing F5 or F11; you cannot immediately run a service or step into its code. Instead, you must install and start your service, and then attach a debugger to the service’s process. For more information, see How to: Debug Windows Service Applications.

Unlike some types of projects, you must create installation components for service applications. The installation components install and register the service on the server and create an entry for your service with the Windows Services Control Manager. For more information, see How to: Add Installers to Your Service Application.

The Main method for your service application must issue the Run command for the services your project contains. The Run method loads the services into the Services Control Manager on the appropriate server. If you use the Windows Services project template, this method is written for you automatically. Note that loading a service is not the same thing as starting the service. See «Service Lifetime» below for more information.

Windows Service applications run in a different window station than the interactive station of the logged-on user. A window station is a secure object that contains a Clipboard, a set of global atoms, and a group of desktop objects. Because the station of the Windows service is not an interactive station, dialog boxes raised from within a Windows service application will not be seen and may cause your program to stop responding. Similarly, error messages should be logged in the Windows event log rather than raised in the user interface.

The Windows service classes supported by the .NET Framework do not support interaction with interactive stations, that is, the logged-on user. The .NET Framework also does not include classes that represent stations and desktops. If your Windows service must interact with other stations, you will need to access the unmanaged Windows API. For more information, see the Windows SDK documentation.

The interaction of the Windows service with the user or other stations must be carefully designed to include scenarios such as there being no logged on user, or the user having an unexpected set of desktop objects. In some cases, it may be more appropriate to write a Windows application that runs under the control of the user.

Windows service applications run in their own security context and are started before the user logs into the Windows computer on which they are installed. You should plan carefully what user account to run the service within; a service running under the system account has more permissions and privileges than a user account.

Service Lifetime

A service goes through several internal states in its lifetime. First, the service is installed onto the system on which it will run. This process executes the installers for the service project and loads the service into the Services Control Manager for that computer. The Services Control Manager is the central utility provided by Windows to administer services.

After the service has been loaded, it must be started. Starting the service allows it to begin functioning. You can start a service from the Services Control Manager, from Server Explorer, or from code by calling the Start method. The Start method passes processing to the application’s OnStart method and processes any code you have defined there.

Читайте также:  Creative sound blaster x fi titanium drivers windows 10

A running service can exist in this state indefinitely until it is either stopped or paused or until the computer shuts down. A service can exist in one of three basic states: Running, Paused, or Stopped. The service can also report the state of a pending command: ContinuePending, PausePending, StartPending, or StopPending. These statuses indicate that a command has been issued, such as a command to pause a running service, but has not been carried out yet. You can query the Status to determine what state a service is in, or use the WaitForStatus to carry out an action when any of these states occurs.

You can pause, stop, or resume a service from the Services Control Manager, from Server Explorer, or by calling methods in code. Each of these actions can call an associated procedure in the service (OnStop, OnPause, or OnContinue), in which you can define additional processing to be performed when the service changes state.

Types of Services

There are two types of services you can create in Visual Studio using the .NET Framework. Services that are the only service in a process are assigned the type Win32OwnProcess. Services that share a process with another service are assigned the type Win32ShareProcess. You can retrieve the service type by querying the ServiceType property.

You might occasionally see other service types if you query existing services that were not created in Visual Studio. For more information on these, see the ServiceType.

Services and the ServiceController Component

The ServiceController component is used to connect to an installed service and manipulate its state; using a ServiceController component, you can start and stop a service, pause and continue its functioning, and send custom commands to a service. However, you do not need to use a ServiceController component when you create a service application. In fact, in most cases your ServiceController component should exist in a separate application from the Windows service application that defines your service.

For more information, see ServiceController.

Requirements

Services must be created in a Windows Service application project or another .NET Framework–enabled project that creates an .exe file when built and inherits from the ServiceBase class.

Projects containing Windows services must have installation components for the project and its services. This can be easily accomplished from the Properties window. For more information, see How to: Add Installers to Your Service Application.

Communication between Windows service and Windows form application

I am working on a project which is a sort of file uploader. In the project, there are certain log files which are created by an application and saved in a particular folder. The content of these files is always text. The contents of these files are uploaded to the server and this task is done by a windows service. The service reads the files one by one and then transfer their contents to the server.

Earlier this task used to be done by the application itself. But it was separated from application because it is possible that when the application is running the user is offline. So these files will remain pending for upload.

The advantage of using service is obvious that the user doesn’t have to worry about upload thing. Whenever the user is connected to internet the service will take care of it.

Now the requirement is that when service uploads the contents of the file and the application via which the files are created is running at that time, the service should send a message to the application that which file’s content is being uploaded.

Now the problem is that the service and the application are not communicating. I’ve spawn seperate threads from both service and application which are using namedpipes for communication.

Читайте также:  Windows hosts file sample

Here is the code which I’ve tried.

What is wrong with this piece of code?

The same logic works if I use another form application in place of service.

While googling about this, I came to know about Session 0 in Windows Vista onward versions of Windows which is used specially for windows services and is isolated from the other sessions used by logged on users. I’m using Windows 8 in my system. Can this be a problem? Please explain in detail.

How to communicate with a windows service?

I want to create a windows service that validates data and access it from another windows application, but I’m new to services and I’m not sure how to start.

So, while the service is running, a windows application should somehow connect to the service, send some data and get a response, true or false.

7 Answers 7

I could successfully handle the (almost) same issue as yours doing the following:

In your Class : ServiceBase, that represents your Service class, you might have:

Now, implement:

To handle custom commands calls:

Now, use this in the application where you’ll call the Windows Service:

Enum to reference your methods: (remember, Services custom methods always receive an int32 (128 to 255) as parameters and using Enum you make it easier to remember and control your methods

To call a specific method:

Doing this, you can control your service.

Here you can check how to create and install a Windows Service. More about the ExecuteCommand method.

If you are using .Net Framework 4, then memory mapped files provide a fairly easy way of implementing cross process communication.

It is fairly simple, and well described in documentation, and avoids the overhead (at runtime but also in terms of development effort) of using WCF or other connection/remoting based interactions, or of writing shared data to a central location and polling (database, file, etc).

See here for an overview.

You could accomplish this very easily by making the service host a WCF service and connecting to it from your application.

We use Named pipes for this purpose. But our client implemented with C++. If your service and application are implemented in .Net, you can use .Net remoting.

In older versions of Windows, you could configure your Windows service to interact with the desktop. This allowed you to add user interface elements directly to your service that could be presented to the user. Beginning with Windows Vista, services can no longer interact directly with users, i.e., no user interfaces.

To do this, what you want to do is write your Windows service and a front-end Windows application. To provide the communication bridge between the two, I would strongly recommend using Windows Communication Foundation (WCF).

To create a C# Windows service, you can follow the step-by-step instructions here.

Think it as a remote database owner. Say you have 1 database yet 10 applications that requires different data’s from the database and also you don’t want to open all your data to each of the applications.. Also your applications will be independent from your database, your data layer will only be implemented in your service, your applications will not hold that logic. You can write a service and open your service to your other applications.

Your service, while it is processing, can add events to the EventLog.

You can create another console application that runs paralel to the service, and that listens to that EventLog with the event handling mechanism:

Then you handle it immediately:

You can read the EntryWrittenEventArgs object to get all event details, and to show what you want in your console app. If you stop the console app the service continues to run, and still logs to the event log.

Оцените статью