Пример создания WCF-сервиса, работающего внутри службы Windows

Windows Communication Foundation – Microsoft , . WCF-runtime System.ServiceModel, , , Windows . WCF-.



Visual Studio 2015 Class Library. WCFMyServiceLibrary.









Class1.cs MyService.cs , IMyService.cs.



System.ServiceModel.



IMyService.cs :
using System.ServiceModel;

namespace WCFMyServiceLibrary
{

[ServiceContract]
public interface IMyService
  {
    [OperationContract]
    string Method1(string x);
    [OperationContract]
    string Method2(string x);
  }
}

      
      







MyService.cs :
namespace WCFMyServiceLibrary
{
  public class MyService : IMyService
  {
    public string Method1(string x)
    {
      string s = $"1 You entered: {x} = = = 1";
      return s;
    }

    public string Method2(string x)
    {
      string s = $"2 you entered: {x} = = = 2";
      return s;
    }
  }
}
      
      





. Windows, .



(Solution) « Windows». WindowsServiceHostForMyService.







Service1.cs ( ) MyService.cs. System.ServiceModel, MyService.cs :



using System.ServiceModel;
using System.ServiceModel.Description;

      
      





MyService :



private ServiceHost service_host = null;
      
      





WCFMyServiceLibrary, :







MyService OnStart , (endpoint):



OnStart
    protected override void OnStart(string[] args)
    {
      if (service_host != null) service_host.Close();

      string address_HTTP = "http://localhost:9001/MyService";
      string address_TCP = "net.tcp://localhost:9002/MyService";

      Uri[] address_base = { new Uri(address_HTTP), new Uri(address_TCP) };
      service_host = new ServiceHost(typeof(WCFMyServiceLibrary.MyService), address_base);

      ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
      service_host.Description.Behaviors.Add(behavior);

      BasicHttpBinding binding_http = new BasicHttpBinding();
      service_host.AddServiceEndpoint(typeof(WCFMyServiceLibrary.IMyService), binding_http, address_HTTP);
      service_host.AddServiceEndpoint(typeof(IMetadataExchange),   MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

      NetTcpBinding binding_tcp = new NetTcpBinding();
      binding_tcp.Security.Mode = SecurityMode.Transport;
      binding_tcp.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
      binding_tcp.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
      binding_tcp.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
      service_host.AddServiceEndpoint(typeof(WCFMyServiceLibrary.IMyService), binding_tcp, address_TCP);
      service_host.AddServiceEndpoint(typeof(IMetadataExchange),  MetadataExchangeBindings.CreateMexTcpBinding(), "mex");

      service_host.Open();
    }

      
      





OnStop:



    protected override void OnStop()
    {
      if (service_host != null)
      {
        service_host.Close();
        service_host = null;
      }
    }

      
      





— MyService.cs ( WindowsServiceHostForMyService) (Design Mode).







( ) « ».







ProjectInstaller.cs

ProjectInstaller.cs MyServiceInstaller.cs.

, – «».







using System.ServiceProcess;

      
      





MyServiceInstaller:



    public MyServiceInstaller()
    {
      // InitializeComponent();
      serviceProcessInstaller1 = new ServiceProcessInstaller();
      serviceProcessInstaller1.Account = ServiceAccount.LocalSystem;
      serviceInstaller1 = new ServiceInstaller();
      serviceInstaller1.ServiceName = "WindowsServiceHostForMyService";
      serviceInstaller1.DisplayName = "WindowsServiceHostForMyService";
      serviceInstaller1.Description = "WCF Service Hosted by Windows NT Service";
      serviceInstaller1.StartType = ServiceStartMode.Automatic;
      Installers.Add(serviceProcessInstaller1);
      Installers.Add(serviceInstaller1);
    }

      
      





, InitializeComponent() .

Windows . (Build Solution) – Windows.



bat- ( , Install_Windows_Service.bat) :



C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe WindowsServiceHostForMyService.exe

      
      





bat- , WindowsServiceHostForMyService.exe ( , , Windows).



bat-, WindowsServiceHostForMyService.exe Windows.



.



– .



«» — Service Proxy – , .



SvcUtil.exe. Generate_Proxy.bat



SvcUtil  http://localhost:9001/MyService  /out:MyServiceProxy.cs  /config:App.config

      
      





( SvcUtil.exe C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin).



, .. , Windows WindowsServiceHostForMyService.



, SvcUtil.exe 2 — MyServiceProxy.cs App.config.



, ( , App.config — ).



. ,



SvcUtil net.tcp://localhost:9002/MyService /out:MyServiceProxy.cs /config:App.config

      
      





.. , , http net.tcp.



(Solution) Windows Forms. WindowsFormsApplication1







System.ServiceModel , ,



using System.ServiceModel   .

      
      





MyServiceProxy.cs ( SvcUtil.exe). MyServiceProxy.cs :



namespace ServiceReference1
{
  using System.Runtime.Serialization;
  using System;
  …     MyServiceProxy.cs …
 ,       namespace
}
      
      





, MyServiceClient ( SvcUtil.exe), .



 using ServiceReference1;

      
      





MyServiceProxy.cs ( ):
namespace ServiceReference1
{
  using System.Runtime.Serialization;
  using System;

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="IMyService")]
public interface IMyService
{
    
 [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMyService/Method1", ReplyAction="http://tempuri.org/IMyService/Method1Response")]
    string Method1(string x);
    
    [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMyService/Method2", ReplyAction="http://tempuri.org/IMyService/Method2Response")]
    string Method2(string x);
}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public interface IMyServiceChannel : IMyService, System.ServiceModel.IClientChannel
{
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class MyServiceClient : System.ServiceModel.ClientBase<IMyService>, IMyService
{
    public MyServiceClient()
    {
    }
    
    public MyServiceClient(string endpointConfigurationName) : 
            base(endpointConfigurationName)
    {
    }
    
    public MyServiceClient(string endpointConfigurationName, string remoteAddress) : 
            base(endpointConfigurationName, remoteAddress)
    {
    }
    
    public MyServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(endpointConfigurationName, remoteAddress)
    {
    }
    
    public MyServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(binding, remoteAddress)
    {
    }
    
    public string Method1(string x)
    {
        return base.Channel.Method1(x);
    }
    
    public string Method2(string x)
    {
        return base.Channel.Method2(x);
    }
}
}
      
      







– App.Config !



3 , textBox1 ( ) richTextbox1 ( – , , )



btn_Start –

btn_Send –

btn_Close –



:
using System;
using System.ServiceModel;
using System.Windows.Forms;
using ServiceReference1;

namespace WindowsFormsApplication1
{

  public partial class Form1 : Form
  {

    MyServiceClient client = null;

    public Form1()
    {
      InitializeComponent();
    }

    private void Print(string text)
    {
      richTextBox1.Text += text + "\n\n";
      richTextBox1.SelectionStart = richTextBox1.Text.Length;
      richTextBox1.ScrollToCaret();
    }

    private void Print(Exception ex)
    {
      if (ex == null) return;
      Print(ex.Message);
      Print(ex.Source);
      Print(ex.StackTrace);
    }

    private void Create_New_Client()
    {
      if (client == null)      
        try { Try_To_Create_New_Client(); }
        catch (Exception ex)
        {
          Print(ex);
          Print(ex.InnerException);
          client = null;
        }
      else
      {
        Print("Cannot create a new client. The current Client is active.");
      }
    }

    private void Try_To_Create_New_Client()
    {
      try
      {

        NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);

        binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
        binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
        binding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;

        string uri = "net.tcp://192.168.1.2:9002/MyService";

        EndpointAddress endpoint = new EndpointAddress(new Uri(uri));

        client = new MyServiceClient(binding, endpoint);

        client.ClientCredentials.Windows.ClientCredential.Domain = "";
        client.ClientCredentials.Windows.ClientCredential.UserName = "Vasya";
        client.ClientCredentials.Windows.ClientCredential.Password = "12345";

        Print("Creating new client ....");
        Print(endpoint.Uri.ToString());
        Print(uri);

        string test = client.Method1("test");

        if (test.Length < 1)
        {
          throw new Exception("   ");
        }
        else
        {
          Print("test is OK  ! " + test);
        }

      }
      catch (Exception ex)
      {
        Print(ex);
        Print(ex.InnerException);
        client = null;
      }
    }

    private void btn_Start_Click(object sender, EventArgs e)
    {
      Create_New_Client();
    }

    private void btn_Send_Click(object sender, EventArgs e)
    {
      Print("sending message . . .");
      string s = textBox1.Text;
      string x = "";
      if (client != null)
      {
        x = client.Method1(s);
        Print(x);
        x = client.Method2(s);
        Print(x);
      }
      else
      {
        Print("Error! Client does not exist!");
      }
    }

    private void btn_Close_Click(object sender, EventArgs e)
    {
      if (client != null)
      {
        Print("Closing a client ...");
        client.Close();
        client = null;
      }
      else
      {
        Print("Error! Client does not exist!");
      }
      this.Close();
    }
  }
}
      
      







– , btn_Start, btn_Send.







,



http://localhost:9001/MyService









net.tcp://localhost:9002/MyService





( – net.tcp , http- ).



, App.config, , C#. – – XML-, . !



. C# , C# ( Delphi MS Access).



All Articles