#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Community.Community
File: BaseServiceClient.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Community
{
using System;
using System.ServiceModel;
using Ecng.Common;
using Ecng.Net;
///
/// The base client for access to the WCF services.
///
/// WCF service type.
public abstract class BaseServiceClient : Disposable
where TService : class
{
private readonly string _endpointName;
private readonly bool _hasCallbacks;
private TService _service;
private ChannelFactory _factory;
///
/// Initialize .
///
/// Server address.
/// The access point name in the configuration file.
/// Whether the has events.
protected BaseServiceClient(Uri address, string endpointName, bool hasCallbacks = false)
{
Address = address ?? throw new ArgumentNullException(nameof(address));
_endpointName = endpointName;
_hasCallbacks = hasCallbacks;
}
///
/// Server address.
///
public Uri Address { get; }
///
/// Whether the connection has been established.
///
public bool IsConnected { get; private set; }
///
/// Create WCF channel.
///
/// WCF channel.
protected virtual ChannelFactory CreateChannel()
{
return new ChannelFactory(new WSHttpBinding
{
Security =
{
Mode = SecurityMode.Transport,
//Message =
//{
// ClientCredentialType = MessageCredentialType.Certificate,
// AlgorithmSuite = SecurityAlgorithmSuite.Default
//}
},
UseDefaultWebProxy = true
}, new EndpointAddress(Address));
}
///
/// To connect. The connection is established automatically when the method or is called.
///
public virtual void Connect()
{
_factory = ChannelHelper.Create(_endpointName, CreateChannel);
if (_hasCallbacks)
_service = _factory.CreateChannel();
OnConnect();
IsConnected = true;
}
///
/// Connect.
///
protected virtual void OnConnect()
{
}
///
/// To call the service method.
///
/// The result type returning the service method.
/// The handler in which the method is called.
/// The result returning the service method.
protected virtual TResult Invoke(Func handler)
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
if (!IsConnected)
Connect();
return _hasCallbacks ? handler(_service) : _factory.Invoke(handler);
}
///
/// To call the service method.
///
/// The handler in which the method is called.
protected void Invoke(Action handler)
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
Invoke