Esempio n. 1
0
        public async Task Connect(string url, string username, string password, List <SupportedProtocol> protocols, CancellationToken token)
        {
            try
            {
                var auth = Authorization.Basic(username, password);
                m_client = EtpFactory.CreateClient(WebSocketType.WebSocket4Net, url, "ShellSquare ETP Client", "1.4.1.1", SUBPROTOCOL, auth);
                var protocol1Info = protocols.Where(x => x.Protocol == 1).FirstOrDefault();
                if (protocol1Info.Role.Equals("producer"))
                {
                    m_client.Register <IChannelStreamingConsumer, ChannelStreamingConsumerHandler>();
                    m_client.Handler <IChannelStreamingConsumer>().OnChannelMetadata   += HandleChannelMetadata;
                    m_client.Handler <IChannelStreamingConsumer>().OnProtocolException += HandleProtocolException;
                    m_client.Handler <IChannelStreamingConsumer>().OnChannelData       += HandleChannelData;
                }
                else
                {
                    m_client.Register <IChannelStreamingProducer, ChannelStreamingProducerHandler>();
                }

                m_client.Register <IDiscoveryCustomer, DiscoveryCustomerHandler>();
                m_client.Register <IStoreCustomer, StoreCustomerHandler>();
                m_client.Handler <ICoreClient>().OnOpenSession += HandleOpenSession;
                await CreateSession(protocols);

                await m_client.OpenAsync();
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    throw new Exception($"{ex.Message} {ex.InnerException.Message}");
                }
                throw;
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Creates an <see cref="IEtpSelfHostedWebServer"/> instance.
        /// </summary>
        /// <param name="port">The port number.</param>
        /// <returns>A new <see cref="IEtpSelfHostedWebServer"/> instance.</returns>
        protected IEtpSelfHostedWebServer CreateServer(int port)
        {
            var version = GetType().Assembly.GetName().Version.ToString();
            var server  = EtpFactory.CreateSelfHostedWebServer(port, GetType().AssemblyQualifiedName, version);

            return(server);
        }
        public async Task Connect(string url, string username, string password, CancellationToken token)
        {
            try
            {
                m_Time = DateTime.UtcNow;

                var protocols = new List <SupportedProtocol>();
                SupportedProtocol p;
                p = EtpHelper.ToSupportedProtocol(Protocols.ChannelStreaming, "consumer");
                protocols.Add(p);

                p = EtpHelper.ToSupportedProtocol(Protocols.Discovery, "store");
                protocols.Add(p);


                var auth = Authorization.Basic(username, password);
                m_client = EtpFactory.CreateClient(WebSocketType.WebSocket4Net, url, m_ApplicationName, m_ApplicationVersion, SUBPROTOCOL, auth);

                m_client.Register <IChannelStreamingProducer, ChannelStreamingProducerHandler>();

                m_client.Register <IDiscoveryCustomer, DiscoveryCustomerHandler>();
                m_client.Register <IStoreCustomer, StoreCustomerHandler>();
                m_client.Handler <ICoreClient>().OnOpenSession += HandleOpenSession;
                CreateSession(protocols);
                await m_client.OpenAsync();
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    throw new Exception($"{ex.Message} {ex.InnerException.Message}");
                }
                throw;
            }
        }
        public async Task SendChannelData(List <ChannelStreamingInfo> lstChannels)
        {
            //IDictionary<string, string> auth;
            //auth = Authorization.Basic(UserNameS, Password);
            //m_client = EtpFactory.CreateClient(WebSocketType.WebSocket4Net, URL, m_ApplicationName, m_ApplicationVersion, SUBPROTOCOL, auth);
            //m_client.Register<IChannelStreamingProducer, ChannelStreamingProducerHandler>();

            var auth = Authorization.Basic(UserNameS, Password);

            m_client = EtpFactory.CreateClient(WebSocketType.WebSocket4Net, URL, m_ApplicationName, m_ApplicationVersion, SUBPROTOCOL, auth);
            m_client.Register <IChannelStreamingProducer, ChannelStreamingProducerHandler>();

            while (true)
            {
                await SendChannelDataActual(lstChannels, m_client);

                await Task.Delay(TimeSpan.FromSeconds(10));

                ////New Code ..Need to check is this required or not
                //var handler = m_client.Handler<IChannelStreamingProducer>();
                ////index = index + 1;
                ////var timer = new System.Threading.Timer((e) =>
                ////{
                //    await Task.Run(async () =>
                //    {
                //        var receivedTime = DateTime.UtcNow;
                //        var timediff = receivedTime - m_Time;

                //        MessageHeader header = new MessageHeader();
                //        header.Protocol = (int)Protocols.ChannelStreaming;
                //        header.MessageType = 3;
                //        header.MessageId = EtpHelper.NextMessageId;
                //        header.MessageFlags = 0;
                //        header.CorrelationId = 0;
                //        var recordData = Activator.CreateInstance<ChannelData>();
                //        recordData.Data = new List<DataItem>();
                //        Random random = new Random();
                //        foreach (var item in lstChannels)
                //        {
                //            TimeSpan t = (receivedTime - m_Epoch);
                //            index = (long)t.TotalMilliseconds;
                //            DataItem d = new DataItem();
                //            d.ChannelId = item.ChannelId;
                //            d.Indexes = new List<long>();
                //            d.Indexes.Add(index);
                //            d.Value = new DataValue();
                //            d.Value.Item = Math.Round(random.NextDouble() * 1000, 2);//random.Next();
                //            d.ValueAttributes = new List<DataAttribute>();
                //            recordData.Data.Add(d);
                //        }
                //        m_client.Handler<IChannelStreamingProducer>().ChannelData(header, recordData.Data);
                //        string message = $"\nRequest: [Protocol {header.Protocol} MessageType {header.MessageType}]";
                //        Message?.Invoke(message + "\nChannel Data processed " + (receivedTime - m_Epoch).ToString(), 0, TraceLevel.Info);
                //    });
                //    await Task.Delay(TimeSpan.FromSeconds(10));
                ////}, null, startTimeSpan, periodTimeSpan);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Converts the message header to a string representing the protocol and message name.
        /// </summary>
        /// <param name="header">The message header.</param>
        /// <returns>The string representing the protocol and message name.</returns>
        public static string ToMessageName(this IMessageHeader header)
        {
            if (header == null)
            {
                return(null);
            }

            return($"{EtpFactory.GetProtocolName(header.EtpVersion, header.Protocol)}.{EtpFactory.GetMessageName(header.EtpVersion, header.Protocol, header.MessageType)}");
        }
Esempio n. 6
0
        /// <summary>
        /// Creates an <see cref="IEtpClient"/> instance configurated with the
        /// current connection and authorization parameters.
        /// </summary>
        /// <param name="url">The WebSocket URL.</param>
        /// <returns>A new <see cref="IEtpClient"/> instance.</returns>
        protected IEtpClient CreateClient(string url)
        {
            var version        = GetType().Assembly.GetName().Version.ToString();
            var headers        = Energistics.Etp.Security.Authorization.Basic(TestSettings.Username, TestSettings.Password);
            var etpSubProtocol = EtpSettings.Etp11SubProtocol;

            var client = EtpFactory.CreateClient(url ?? TestSettings.EtpServerUrl, GetType().AssemblyQualifiedName, version, etpSubProtocol, headers);

            return(client);
        }
Esempio n. 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EtpClient"/> class.
        /// </summary>
        /// <param name="uri">The ETP server URI.</param>
        /// <param name="etpVersion">The ETP version for the session.</param>
        /// <param name="encoding">The ETP encoding for the session.</param>
        /// <param name="info">The client's information.</param>
        /// <param name="parameters">The client's parameters.</param>
        /// <param name="authorization">The client's authorization details.</param>
        /// <param name="headers">The WebSocket headers.</param>
        public EtpClient(string uri, EtpVersion etpVersion, EtpEncoding encoding, EtpEndpointInfo info, EtpEndpointParameters parameters, Security.Authorization authorization = null, IDictionary <string, string> headers = null)
            : base(etpVersion, encoding, info, parameters, headers, true, null, false)
        {
            Headers.SetAuthorization(authorization);

            _socket = new W4N.WebSocket(uri,
                                        subProtocol: EtpFactory.GetSubProtocol(EtpVersion),
                                        cookies: null,
                                        customHeaderItems: Headers.ToList(),
                                        userAgent: info.ApplicationName);
        }
Esempio n. 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EtpClient"/> class.
        /// </summary>
        /// <param name="uri">The ETP server URI.</param>
        /// <param name="etpVersion">The ETP version for the session.</param>
        /// <param name="encoding">The ETP encoding for the session.</param>
        /// <param name="info">The client's information.</param>
        /// <param name="parameters">The client's parameters.</param>
        /// <param name="authorization">The client's authorization details.</param>
        /// <param name="headers">The WebSocket headers.</param>
        public EtpClient(string uri, EtpVersion etpVersion, EtpEncoding encoding, EtpEndpointInfo info, EtpEndpointParameters parameters = null, Security.Authorization authorization = null, IDictionary <string, string> headers = null)
            : base(etpVersion, encoding, new ClientWebSocket(), info, parameters, headers, true, null)
        {
            Headers.SetAuthorization(authorization);

            ClientSocket.Options.AddSubProtocol(EtpFactory.GetSubProtocol(EtpVersion));

            foreach (var item in Headers)
            {
                ClientSocket.Options.SetRequestHeader(item.Key, item.Value);
            }

            Uri = new Uri(uri);

            // NOTE: User-Agent cannot be set on a .NET Framework ClientWebSocket:
            // https://github.com/dotnet/corefx/issues/26627
        }
Esempio n. 9
0
        private void RunServer()
        {
            var supportedVersions = new List <EtpVersion> {
                EtpVersion.v11, EtpVersion.v12
            };
            var supportedEncodings = new List <EtpEncoding> {
                EtpEncoding.Binary, EtpEncoding.Json
            };
            var serverDetails = new EtpWebServerDetails(supportedVersions, supportedEncodings);
            var endpointInfo  = EtpFactory.CreateServerEndpointInfo(ServerAppName, AppVersion);

            using (var webServer = EtpFactory.CreateSelfHostedWebServer(WebSocketType.Native, ServerPort, endpointInfo, details: serverDetails))
            {
                webServer.ServerManager.ServerCreated += OnServerCreated;
                InitializeWebServer(webServer);
                HandleWebServer(webServer);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Creates an ETP client for the current connection
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="applicationName">Name of the application.</param>
        /// <param name="applicationVersion">The application version.</param>
        /// <returns>An <see cref="Energistics.Etp.Common.IEtpClient"/> instance.</returns>
        public static IEtpClient CreateEtpClient(this Connection connection, string applicationName, string applicationVersion)
        {
            var headers = connection.GetAuthorizationHeader();

            connection.UpdateEtpSettings(headers);
            connection.SetServerCertificateValidation();

            var client = EtpFactory.CreateClient(connection.WebSocketType, connection.Uri, applicationName, applicationVersion, connection.SubProtocol, headers);

            if (!string.IsNullOrWhiteSpace(connection.ProxyHost))
            {
                client.SetProxy(connection.ProxyHost, connection.ProxyPort,
                                connection.ProxyUsername, connection.ProxyPassword);
            }
            if (!string.IsNullOrWhiteSpace(connection.EtpCompression))
            {
                client.SetSupportedCompression(connection.EtpCompression);
            }

            return(client);
        }
Esempio n. 11
0
        /// <summary>
        /// Initializes the ETP client.
        /// </summary>
        public void InitEtpServer()
        {
            try
            {
                Runtime.Invoke(() => Runtime.Shell.StatusBarText = "Listening...");

                var message = $"Listening for ETP connections on port {Model.PortNumber}...";
                LogClientOutput(message, true);
                _log.Debug(message);

                SelfHostedWebServer = EtpFactory.CreateSelfHostedWebServer(Model.PortNumber, Model.ApplicationName, Model.ApplicationVersion);
                SelfHostedWebServer.SessionConnected += OnServerSessionConnected;
                SelfHostedWebServer.SessionClosed    += OnServerSessionClosed;
                SelfHostedWebServer.Start();
            }
            catch (Exception ex)
            {
                Runtime.Invoke(() => Runtime.Shell.StatusBarText = "Error");
                Runtime.ShowError("Error initializing ETP server.", ex);
            }
        }
Esempio n. 12
0
        private async Task InitChannelStreaming(CancellationToken token)
        {
            using (var server = EtpFactory.CreateSelfHostedWebServer(Model.PortNumber, ((IScreen)Parent).DisplayName, Model.Version))
            {
                var simulator = CreateEtpSimulator();
                simulator.Register(server);
                server.Start();

                Log("ETP Socket Server started, listening on port {0}.", Model.PortNumber);

                while (true)
                {
                    await Task.Delay(250, token);

                    if (token.IsCancellationRequested)
                    {
                        break;
                    }
                }
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EtpSelfHostedWebServer"/> class.
        /// </summary>
        /// <param name="port">The port.</param>
        /// <param name="endpointInfo">The web server's endpoint information.</param>
        /// <param name="endpointParameters">The web server's endpoint parameters.</param>
        /// <param name="details">The web server's details.</param>
        public EtpSelfHostedWebServer(int port, EtpEndpointInfo endpointInfo, EtpEndpointParameters endpointParameters = null, EtpWebServerDetails details = null)
        {
            Logger = LogManager.GetLogger(GetType());

            Details       = details ?? new EtpWebServerDetails();
            ServerManager = new EtpServerManager(Details, endpointInfo, endpointParameters);

            _server = new WebSocketServer(Details.SupportedVersions.Select(v => new BasicSubProtocol(EtpFactory.GetSubProtocol(v))));

            _server.Setup(new ServerConfig
            {
                Ip               = "Any",
                Port             = port,
                MaxRequestLength = int.MaxValue,
            });

            _server.NewSessionConnected += OnNewSessionConnected;
            _server.NewDataReceived     += OnNewDataReceived;
            _server.SessionClosed       += OnSessionClosed;

            Uri = new Uri($"http://localhost:{port}");
        }
Esempio n. 14
0
 /// <summary>
 /// Gets the server capabilities for the specified ETP version.
 /// </summary>
 /// <param name="version">The ETP version to get the capabilities for.</param>
 /// <returns>The server capabilities.</returns>
 public IServerCapabilities ServerCapabilities(EtpVersion version)
 {
     return(EtpFactory.CreateServerCapabilities(version, WebServerDetails, EndpointInfo, EndpointDetails));
 }
Esempio n. 15
0
        private void RunClient()
        {
            Authorization authorization = null;

            Console.WriteLine($"Enter a valid Web Socket URI [{DefaultClientUri}]:");
            var webSocketUri = Console.ReadLine();

            Console.WriteLine();

            Console.WriteLine("Select from the following options:");
            Console.WriteLine(" 1 - No credentials");
            Console.WriteLine(" 2 - User / Pass");
            Console.WriteLine(" 3 - Token");
            var info = Console.ReadKey();

            Console.WriteLine();

            if (IsKey(info, "1"))
            {
            }
            else if (IsKey(info, "2"))
            {
                Console.WriteLine("Enter username:"******"Enter password:"******"Enter token:");
                var token = Console.ReadLine();
                authorization = Authorization.Bearer(token);
            }
            Console.WriteLine();

            Console.WriteLine("Select from the following options:");
            Console.WriteLine(" 1 - ETP 1.1, JSON encoding");
            Console.WriteLine(" 2 - ETP 1.1, binary encoding");
            Console.WriteLine(" 3 - ETP 1.2, JSON encoding");
            Console.WriteLine(" 4 - ETP 1.2, binary encoding");
            info = Console.ReadKey();
            var version  = EtpVersion.Unknown;
            var encoding = EtpEncoding.Binary;

            if (IsKey(info, "1"))
            {
                version  = EtpVersion.v11;
                encoding = EtpEncoding.Json;
            }
            else if (IsKey(info, "2"))
            {
                version  = EtpVersion.v11;
                encoding = EtpEncoding.Binary;
            }
            else if (IsKey(info, "3"))
            {
                version  = EtpVersion.v12;
                encoding = EtpEncoding.Json;
            }
            else if (IsKey(info, "4"))
            {
                version  = EtpVersion.v12;
                encoding = EtpEncoding.Binary;
            }
            Console.WriteLine();

            var endpointInfo = EtpFactory.CreateClientEndpointInfo(ClientAppName, AppVersion, Assembly.GetExecutingAssembly().FullName);

            using (var client = EtpFactory.CreateClient(WebSocketType.Native, string.IsNullOrEmpty(webSocketUri) ? DefaultClientUri : webSocketUri, version, encoding, endpointInfo, authorization: authorization))
            {
                client.OnProtocolException += OnProtocolException;
                if (client.EtpVersion == EtpVersion.v12)
                {
                    client.OnPing += OnPing;
                    client.OnPong += OnPong;
                }
                InitializeClient(client);
                HandleClient(client);
            }
        }
Esempio n. 16
0
 /// <summary>
 /// Initializes a new <see cref="EtpCapabilities"/> instance.
 /// </summary>
 /// <param name="version">The ETP version the capabilities are for.</param>
 protected EtpCapabilities(EtpVersion version)
 {
     Dictionary = EtpFactory.CreateDataValueDictionary(version);
     InitializeFromDefaults();
 }
Esempio n. 17
0
 /// <summary>
 /// Initializes a new <see cref="EtpCapabilities"/> instance.
 /// </summary>
 /// <param name="version">The ETP version the capabilities are for.</param>
 /// <param name="capabilities">The capabilities to initialize this from.</param>
 protected EtpCapabilities(EtpVersion version, IReadOnlyDataValueDictionary capabilities)
 {
     Dictionary = EtpFactory.CreateDataValueDictionary(version);
     LoadFrom(capabilities);
 }