public override void StartConnect()
        {
            if (this.State != TransportStates.Initial)
            {
                return;
            }

            HTTPManager.Logger.Information("LongPollingTransport", "StartConnect");

            this.State = TransportStates.Connecting;

            // https://github.com/aspnet/SignalR/blob/dev/specs/HubProtocol.md#overview
            // When our connection is open, send the 'negotiation' message to the server.

            var request = new HTTPRequest(BuildUri(this.connection.Uri), HTTPMethods.Post, OnHandshakeRequestFinished);

            this.stream.Write(JsonProtocol.WithSeparator(string.Format("{{\"protocol\":\"{0}\", \"version\": 1}}", this.connection.Protocol.Encoder.Name)));

            request.UploadStream = this.stream;

            if (this.connection.AuthenticationProvider != null)
            {
                this.connection.AuthenticationProvider.PrepareRequest(request);
            }

            request.Send();
        }
Example #2
0
        public void Should_be_able_to_stream(int count)
        {
            var jsonProtocol     = new JsonProtocol();
            var jsonPacketStream = new JsonPacketStream();

            var messages = new List <byte[]>
            {
                jsonProtocol.SetPacketContents(1, "The quick brown fox jumped over the lazy dog"),
                jsonProtocol.SetPacketContents(2, "Second message to be appended")
            };

            var message = messages[0].Concat(messages[1]).ToArray();

            var messageResult = new List <byte[]>();

            for (int i = 0; i < message.Length; i += count)
            {
                var array  = message.Skip(i).Take(count).ToArray();
                var result = jsonPacketStream.ParseBytes(array);

                if (result != null)
                {
                    messageResult.AddRange(result);
                }
            }

            Assert.That(messageResult, Is.EqualTo(messages));
        }
Example #3
0
        /// <summary>
        /// GUI button callback
        /// </summary>
        public void OnConnectButton()
        {
            IProtocol protocol = null;

#if BESTHTTP_SIGNALR_CORE_ENABLE_GAMEDEVWARE_MESSAGEPACK
            protocol = new MessagePackProtocol();
#else
            protocol = new JsonProtocol(new LitJsonEncoder());
#endif
            // Crete the HubConnection
            hub = new HubConnection(new Uri(this.sampleSelector.BaseURL + this._path), protocol);

            // Optionally add an authenticator
            //hub.AuthenticationProvider = new BestHTTP.SignalRCore.Authentication.HeaderAuthenticator("<generated jwt token goes here>");

            // Subscribe to hub events
            hub.OnConnected += Hub_OnConnected;
            hub.OnError     += Hub_OnError;
            hub.OnClosed    += Hub_OnClosed;

            hub.OnTransportEvent += (hub, transport, ev) => AddText(string.Format("Transport(<color=green>{0}</color>) event: <color=green>{1}</color>", transport.TransportType, ev));

            // Set up server callable functions
            hub.On("Send", (string arg) => AddText(string.Format("On '<color=green>Send</color>': '<color=yellow>{0}</color>'", arg)).AddLeftPadding(20));
            hub.On <Person>("Person", (person) => AddText(string.Format("On '<color=green>Person</color>': '<color=yellow>{0}</color>'", person)).AddLeftPadding(20));
            hub.On <Person, Person>("TwoPersons", (person1, person2) => AddText(string.Format("On '<color=green>TwoPersons</color>': '<color=yellow>{0}</color>', '<color=yellow>{1}</color>'", person1, person2)).AddLeftPadding(20));

            // And finally start to connect to the server
            hub.StartConnect();

            AddText("StartConnect called");

            SetButtons(false, false);
        }
Example #4
0
        public void OnConnectButton()
        {
            IProtocol protocol = null;

#if BESTHTTP_SIGNALR_CORE_ENABLE_GAMEDEVWARE_MESSAGEPACK
            protocol = new MessagePackProtocol();
#else
            protocol = new JsonProtocol(new LitJsonEncoder());
#endif

            // Crete the HubConnection
            hub = new HubConnection(new Uri("http://localhost:5000" + this._path), protocol);

            // Subscribe to hub events
            hub.OnConnected += Hub_OnConnected;
            hub.OnError     += Hub_OnError;
            hub.OnClosed    += Hub_OnClosed;

            hub.OnRedirected += Hub_Redirected;

            hub.OnTransportEvent += (hub, transport, ev) => AddText(string.Format("Transport(<color=green>{0}</color>) event: <color=green>{1}</color>", transport.TransportType, ev));

            // And finally start to connect to the server
            hub.StartConnect();

            AddText("StartConnect called");

            SetButtons(false, false);
        }
        public void OnConnectButton()
        {
            // Server side of this example can be found here:
            // https://github.com/Benedicht/BestHTTP_DemoSite/blob/master/BestHTTP_DemoSite/Hubs/

            IProtocol protocol = null;

#if BESTHTTP_SIGNALR_CORE_ENABLE_GAMEDEVWARE_MESSAGEPACK
            protocol = new MessagePackProtocol();
#else
            protocol = new JsonProtocol(new LitJsonEncoder());
#endif

            // Crete the HubConnection
            hub = new HubConnection(new Uri(base.sampleSelector.BaseURL + this._hubPath), protocol);

            hub.AuthenticationProvider = new PreAuthAccessTokenAuthenticator(new Uri(base.sampleSelector.BaseURL + this._jwtTokenPath));

            hub.AuthenticationProvider.OnAuthenticationSucceded += AuthenticationProvider_OnAuthenticationSucceded;
            hub.AuthenticationProvider.OnAuthenticationFailed   += AuthenticationProvider_OnAuthenticationFailed;

            // Subscribe to hub events
            hub.OnConnected += Hub_OnConnected;
            hub.OnError     += Hub_OnError;
            hub.OnClosed    += Hub_OnClosed;

            hub.OnTransportEvent += (hub, transport, ev) => AddText(string.Format("Transport(<color=green>{0}</color>) event: <color=green>{1}</color>", transport.TransportType, ev));

            // And finally start to connect to the server
            hub.StartConnect();

            AddText("StartConnect called");
            SetButtons(false, false);
        }
Example #6
0
        private BlyncTcpClient.OnConnectedEvent SendIdentityOnConnectedEvent()
        {
            return((sender, eventArgs) =>
            {
                Console.WriteLine("Connected");

                var devices = new List <Device>();
                for (int i = 0; i < _blyncClient.NumberOfDevices; i++)
                {
                    devices.Add(new Device {
                        DeviceId = i, DeviceType = _blyncClient.GetDeviceType(i).ToString()
                    });
                }

                var status = new JsonIdentityPacket
                {
                    Name = Environment.MachineName,
                    Devices = devices
                };

                var protocol = new JsonProtocol();

                var json = protocol.Serialize(status);
                var packet = protocol.SetPacketContents(0, json);

                _blyncTcpClient.Send(packet, new CancellationToken()).Wait();
            });
        }
Example #7
0
        // The websocket connection is open
        private void OnOpen(WebSocket.WebSocket webSocket)
        {
            HTTPManager.Logger.Verbose("WebSocketTransport", "OnOpen");

            // https://github.com/aspnet/SignalR/blob/dev/specs/HubProtocol.md#overview
            // When our websocket connection is open, send the 'negotiation' message to the server.
            (this as ITransport).Send(JsonProtocol.WithSeparator(string.Format("{{\"protocol\":\"{0}\", \"version\": 1}}", this.connection.Protocol.Name)));
        }
        private void OnOpen(WebSocket.WebSocket webSocket)
        {
            // When our websocket connection is open, send the 'negotiation' message to the server.
            // It's not a real negotiation step, as we don't expect an answer to this.

            string json = this.connection.ComposeNegotiationMessage();

            byte[] buffer = JsonProtocol.WithSeparator(json);

            Send(buffer);
        }
        public void OnConnectButton()
        {
            // Server side of this example can be found here:
            // https://github.com/Benedicht/BestHTTP_DemoSite/blob/master/BestHTTP_DemoSite/Hubs/

#if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
            try
            {
                MessagePack.Resolvers.StaticCompositeResolver.Instance.Register(
                    MessagePack.Resolvers.DynamicEnumAsStringResolver.Instance,
                    MessagePack.Unity.UnityResolver.Instance,
                    //MessagePack.Unity.Extension.UnityBlitWithPrimitiveArrayResolver.Instance,
                    //MessagePack.Resolvers.StandardResolver.Instance,
                    MessagePack.Resolvers.ContractlessStandardResolver.Instance
                    );

                var options = MessagePack.MessagePackSerializerOptions.Standard.WithResolver(MessagePack.Resolvers.StaticCompositeResolver.Instance);
                MessagePack.MessagePackSerializer.DefaultOptions = options;
            }
            catch
            { }
#endif

            IProtocol protocol = null;
#if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
            protocol = new MessagePackCSharpProtocol();
#elif BESTHTTP_SIGNALR_CORE_ENABLE_GAMEDEVWARE_MESSAGEPACK
            protocol = new MessagePackProtocol();
#else
            protocol = new JsonProtocol(new LitJsonEncoder());
#endif

            // Crete the HubConnection
            hub = new HubConnection(new Uri(base.sampleSelector.BaseURL + this._hubPath), protocol);

            hub.AuthenticationProvider = new PreAuthAccessTokenAuthenticator(new Uri(base.sampleSelector.BaseURL + this._jwtTokenPath));

            hub.AuthenticationProvider.OnAuthenticationSucceded += AuthenticationProvider_OnAuthenticationSucceded;
            hub.AuthenticationProvider.OnAuthenticationFailed   += AuthenticationProvider_OnAuthenticationFailed;

            // Subscribe to hub events
            hub.OnConnected += Hub_OnConnected;
            hub.OnError     += Hub_OnError;
            hub.OnClosed    += Hub_OnClosed;

            hub.OnTransportEvent += (hub, transport, ev) => AddText(string.Format("Transport(<color=green>{0}</color>) event: <color=green>{1}</color>", transport.TransportType, ev));

            // And finally start to connect to the server
            hub.StartConnect();

            AddText("StartConnect called");
            SetButtons(false, false);
        }
        /// <summary>
        /// GUI button callback
        /// </summary>
        public void OnConnectButton()
        {
#if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
            try
            {
                MessagePack.Resolvers.StaticCompositeResolver.Instance.Register(
                    MessagePack.Resolvers.DynamicEnumAsStringResolver.Instance,
                    MessagePack.Unity.UnityResolver.Instance,
                    //MessagePack.Unity.Extension.UnityBlitWithPrimitiveArrayResolver.Instance,
                    //MessagePack.Resolvers.StandardResolver.Instance,
                    MessagePack.Resolvers.ContractlessStandardResolver.Instance
                    );

                var options = MessagePack.MessagePackSerializerOptions.Standard.WithResolver(MessagePack.Resolvers.StaticCompositeResolver.Instance);
                MessagePack.MessagePackSerializer.DefaultOptions = options;
            }
            catch
            { }
#endif

            IProtocol protocol = null;
#if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
            protocol = new MessagePackCSharpProtocol();
#elif BESTHTTP_SIGNALR_CORE_ENABLE_GAMEDEVWARE_MESSAGEPACK
            protocol = new MessagePackProtocol();
#else
            protocol = new JsonProtocol(new LitJsonEncoder());
#endif
            // Crete the HubConnection
            hub = new HubConnection(new Uri(base.sampleSelector.BaseURL + this._path), protocol);

            // Optionally add an authenticator
            //hub.AuthenticationProvider = new BestHTTP.SignalRCore.Authentication.HeaderAuthenticator("<generated jwt token goes here>");

            // Subscribe to hub events
            hub.OnConnected += Hub_OnConnected;
            hub.OnError     += Hub_OnError;
            hub.OnClosed    += Hub_OnClosed;

            hub.OnTransportEvent += (hub, transport, ev) => AddText(string.Format("Transport(<color=green>{0}</color>) event: <color=green>{1}</color>", transport.TransportType, ev));

            // Set up server callable functions
            hub.On("Send", (string arg) => AddText(string.Format("On '<color=green>Send</color>': '<color=yellow>{0}</color>'", arg)).AddLeftPadding(20));
            hub.On <Person>("Person", (person) => AddText(string.Format("On '<color=green>Person</color>': '<color=yellow>{0}</color>'", person)).AddLeftPadding(20));
            hub.On <Person, Person>("TwoPersons", (person1, person2) => AddText(string.Format("On '<color=green>TwoPersons</color>': '<color=yellow>{0}</color>', '<color=yellow>{1}</color>'", person1, person2)).AddLeftPadding(20));

            // And finally start to connect to the server
            hub.StartConnect();

            AddText("StartConnect called");

            SetButtons(false, false);
        }
        // The websocket connection is open
        private void OnOpen(WebSocket.WebSocket webSocket)
        {
            HTTPManager.Logger.Verbose("WebSocketTransport", "OnOpen");

            // https://github.com/aspnet/SignalR/blob/dev/specs/HubProtocol.md#overview
            // When our websocket connection is open, send the 'negotiation' message to the server.

            string json = string.Format("{{'protocol':'{0}', 'version': 1}}", this.connection.Protocol.Encoder.Name);

            byte[] buffer = JsonProtocol.WithSeparator(json);

            (this as ITransport).Send(buffer);
        }
Example #12
0
        public void Connect(Uri uri)
        {
            var encoder  = new LitJsonEncoder();
            var protocol = new JsonProtocol(encoder);

            connection = new HubConnection(uri, protocol);

            connection.OnConnected += OnConnected;
            connection.OnClosed    += OnClosed;
            connection.OnError     += OnError;
            connection.OnMessage   += OnMessage;

            connection.StartConnect();
        }
Example #13
0
        public void Should_be_able_to_recieve_packet_from_server()
        {
            var packetProtocol = new JsonProtocol();

            var server = new BlyncTcpServer(new TcpServerSettings
            {
                ConnectionTimeoutPeriod = 5000,
                PacketStreamFactory     = new JsonPacketStreamFactory(),
                Port = Port
            });
            var client = new BlyncTcpClient(new TcpClientSettings
            {
                ConnectionTimeoutPeriod = 10000,
                Hostname            = "127.0.0.1",
                PacketStreamFactory = new JsonPacketStreamFactory(),
                Port = Port
            });

            var expectedMessage = packetProtocol.SetPacketContents(0, "Hello World!");

            server.ClientConnectedEvent += (sender, args) =>
            {
                var clientContext = sender as TcpClientContext;
                if (clientContext != null)
                {
                    clientContext.Send(expectedMessage, new CancellationToken()).Wait();
                }
            };

            byte[] actualMessage = null;
            client.MessageReceivedEvent += (sender, args) =>
            {
                actualMessage = args;
                client.Stop();
                server.Stop();
            };

            server.Start();
            client.Start();

            var timeoutTask = Task.Delay(TimeSpan.FromSeconds(1));

            while (!timeoutTask.IsCompleted && actualMessage == null)
            {
                // Wait
            }

            Assert.That(actualMessage, Is.EqualTo(expectedMessage));
        }
Example #14
0
        public void Should_be_able_to_serialize_and_deserialize_correctly()
        {
            const string expectedMessage = "Hello World!";
            const int    expectedType    = 4;

            var jsonProtocol = new JsonProtocol();
            var buffer       = jsonProtocol.SetPacketContents(expectedType, expectedMessage);

            var actualType    = jsonProtocol.GetPacketType(buffer);
            var length        = jsonProtocol.GetPacketLength(buffer);
            var actualMessage = jsonProtocol.GetPacketContents(buffer, length);

            Assert.That(actualType, Is.EqualTo(expectedType));
            Assert.That(actualMessage, Is.EqualTo(expectedMessage));
        }
Example #15
0
        public void OnConnectButton()
        {
#if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
            try
            {
                MessagePack.Resolvers.StaticCompositeResolver.Instance.Register(
                    MessagePack.Resolvers.DynamicEnumAsStringResolver.Instance,
                    MessagePack.Unity.UnityResolver.Instance,
                    //MessagePack.Unity.Extension.UnityBlitWithPrimitiveArrayResolver.Instance,
                    //MessagePack.Resolvers.StandardResolver.Instance,
                    MessagePack.Resolvers.ContractlessStandardResolver.Instance
                    );

                var options = MessagePack.MessagePackSerializerOptions.Standard.WithResolver(MessagePack.Resolvers.StaticCompositeResolver.Instance);
                MessagePack.MessagePackSerializer.DefaultOptions = options;
            }
            catch
            { }
#endif

            IProtocol protocol = null;
#if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
            protocol = new MessagePackCSharpProtocol();
#elif BESTHTTP_SIGNALR_CORE_ENABLE_GAMEDEVWARE_MESSAGEPACK
            protocol = new MessagePackProtocol();
#else
            protocol = new JsonProtocol(new LitJsonEncoder());
#endif

            // Crete the HubConnection
            hub = new HubConnection(new Uri(this.sampleSelector.BaseURL + this._path), protocol);

            // Subscribe to hub events
            hub.OnConnected += Hub_OnConnected;
            hub.OnError     += Hub_OnError;
            hub.OnClosed    += Hub_OnClosed;

            hub.OnRedirected += Hub_Redirected;

            hub.OnTransportEvent += (hub, transport, ev) => AddText(string.Format("Transport(<color=green>{0}</color>) event: <color=green>{1}</color>", transport.TransportType, ev));

            // And finally start to connect to the server
            hub.StartConnect();

            AddText("StartConnect called");

            SetButtons(false, false);
        }
Example #16
0
        private BlyncTcpClient.OnMessageReceivedEvent ExcuteInstructionsOnMessageReceivedEvent()
        {
            return((sender, bytes) =>
            {
                Console.WriteLine("Message recieved");

                var protocol = new JsonProtocol();

                var type = protocol.GetPacketType(bytes);
                var length = protocol.GetPacketLength(bytes);
                var content = protocol.GetPacketContents(bytes, length);

                if (type == 1)
                {
                    var instruction = protocol.Deserialize <JsonInstructionPacket>(content);

                    _instructionExecuter.Execute(instruction);
                }
            });
        }
Example #17
0
        public void Should_be_notified_when_client_sends_a_message()
        {
            var expectedMessage = new JsonProtocol().SetPacketContents(0, "Hello world!");

            var server = new BlyncTcpServer(new TcpServerSettings
            {
                Port = Port,
                PacketStreamFactory = new JsonPacketStreamFactory()
            });

            byte[] actualMessage = null;

            server.MessageReceivedEvent += (sender, args) =>
            {
                var context = sender as TcpClientContext;
                if (context != null)
                {
                    actualMessage = args;
                }
                server.Stop();
            };

            server.Start();

            var tcpClient = new TcpClient("127.0.0.1", Port);
            var stream    = tcpClient.GetStream();

            stream.Write(expectedMessage, 0, expectedMessage.Length);

            var timeoutTask = Task.Delay(TimeSpan.FromSeconds(1));

            while (!timeoutTask.IsCompleted && actualMessage == null)
            {
                // Wait
            }

            Assert.That(actualMessage, Is.EqualTo(expectedMessage));
        }
        public static string JsonSerialize(ObservableCollection <PlayerEntry> players, int?tableN, int?gameN,
                                           ObservableCollection <int?> bestWayContainer, ObservableCollection <int?> killedAtNight, bool ugad, ObservableCollection <int?> ugadaykaContainer,
                                           bool redWin, bool techRed, bool blackWin, bool techBlack, bool sheriffFirstNight, bool threeZv, bool authomate, int?falseCom)
        {
            var convertedPlayers = players.Select(t => new JsonPlayerEntry
            {
                Result              = t.Result,
                Foul                = t.Foul,
                Role                = t.Role,
                Nick                = t.Nick,
                Reflection          = t.Reflection,
                PositionInKillQueue = t.PositionInKillQueue,
                KilledAtNight       = t.KilledAtNight,
                KilledAtDay         = t.KilledAtDay,
                CheckedAtNight      = t.CheckedAtNight
            });
            var target = new JsonProtocol
            {
                Players     = convertedPlayers.ToList(),
                FalseCom    = falseCom,
                Ugadayka    = ugadaykaContainer.ToList(),
                BestPlayers =
                    players.Where(p => p.Reflection >= 0 && (p.Foul < 4 || p.Foul == null)).Select(t => t.Nick).ToList(),
                BestWay           = bestWayContainer.ToList(),
                Date              = DateTime.Now,
                FirstNightSheriff = sheriffFirstNight,
                Game              = gameN,
                Table             = tableN,
                NightKill         = killedAtNight.ToList(),
                ThreeZv           = threeZv,
                UgadaykaOn        = ugad,
                Winner            = redWin ? techRed ? "TechRed" : "Red" : techBlack ? "TechBlack" : "Black"
            };

            return(JsonConvert.SerializeObject(target));
        }
Example #19
0
        static void Main(string[] args)
        {
            var port = Int32.Parse(args[0]);

            Console.WriteLine("Listening to port {0}", port);

            var protocol = new JsonProtocol();

            var server = new BlyncTcpServer(new TcpServerSettings
            {
                ConnectionTimeoutPeriod = 15000,
                PacketStreamFactory     = new JsonPacketStreamFactory(),
                Port = port
            });

            server.ClientConnectedEvent += (sender, eventArgs) =>
            {
                var client = sender as TcpClientContext;
                if (client != null)
                {
                    Console.WriteLine("Client connected [{0}]", client.Id);

                    var redPacket = protocol.SetPacketContents(1, protocol.Serialize(new JsonInstructionPacket {
                        Color = "red"
                    }));
                    var greenPacket = protocol.SetPacketContents(1, protocol.Serialize(new JsonInstructionPacket {
                        Color = "green"
                    }));

                    for (int i = 0; i < 10; i++)
                    {
                        if (i % 2 == 0)
                        {
                            client.Send(redPacket, new CancellationToken()).Wait();
                        }
                        else
                        {
                            client.Send(greenPacket, new CancellationToken()).Wait();
                        }
                        Thread.Sleep(2000);
                    }
                }
            };

            server.ClientDisconnectedEvent += (sender, eventArgs) =>
            {
                var client = sender as TcpClientContext;
                if (client != null)
                {
                    Console.WriteLine("Client disconnected [{0}]", client.Id);
                }
            };


            server.MessageReceivedEvent += (sender, bytes) =>
            {
                var client = sender as TcpClientContext;
                if (client != null)
                {
                    Console.WriteLine("Client disconnected [{0}]", client.Id);
                    var type    = protocol.GetPacketType(bytes);
                    var length  = protocol.GetPacketLength(bytes);
                    var content = protocol.GetPacketContents(bytes, length);
                    Console.WriteLine("    [{0}] {1}", type, content);
                }
            };

            try
            {
                server.Start();
                Thread.Sleep(400000);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
                if (exception.InnerException != null)
                {
                    foreach (var innerExceptionMessage in exception.InnerException.Message)
                    {
                        Console.WriteLine("    {0}", innerExceptionMessage);
                    }
                }
            }
        }
        void OnConnectButton()
        {
#if CSHARP_7_OR_LATER
#if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
            try
            {
                MessagePack.Resolvers.StaticCompositeResolver.Instance.Register(
                    MessagePack.Resolvers.DynamicEnumAsStringResolver.Instance,
                    MessagePack.Unity.UnityResolver.Instance,
                    //MessagePack.Unity.Extension.UnityBlitWithPrimitiveArrayResolver.Instance,
                    //MessagePack.Resolvers.StandardResolver.Instance,
                    MessagePack.Resolvers.ContractlessStandardResolver.Instance
                    );

                var options = MessagePack.MessagePackSerializerOptions.Standard.WithResolver(MessagePack.Resolvers.StaticCompositeResolver.Instance);
                MessagePack.MessagePackSerializer.DefaultOptions = options;
            }
            catch
            { }
#endif

            IProtocol protocol = null;
#if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
            protocol = new MessagePackCSharpProtocol();
#elif BESTHTTP_SIGNALR_CORE_ENABLE_GAMEDEVWARE_MESSAGEPACK
            protocol = new MessagePackProtocol();
#else
            protocol = new JsonProtocol(new LitJsonEncoder());
#endif
            // Crete the HubConnection
            hub = new HubConnection(new Uri(this.sampleSelector.BaseURL + this._path), protocol);

            // Subscribe to hub events
            hub.OnError += Hub_OnError;

            hub.OnTransportEvent += (hub, transport, ev) => AddText(string.Format("Transport(<color=green>{0}</color>) event: <color=green>{1}</color>", transport.TransportType, ev));

            // Set up server callable functions
            hub.On("Send", (string arg) => AddText(string.Format("On '<color=green>Send</color>': '<color=yellow>{0}</color>'", arg)).AddLeftPadding(20));
            hub.On <Person>("Person", (person) => AddText(string.Format("On '<color=green>Person</color>': '<color=yellow>{0}</color>'", person)).AddLeftPadding(20));
            hub.On <Person, Person>("TwoPersons", (person1, person2) => AddText(string.Format("On '<color=green>TwoPersons</color>': '<color=yellow>{0}</color>', '<color=yellow>{1}</color>'", person1, person2)).AddLeftPadding(20));

            AddText("StartConnect called");

            SetButtons(false, false);

            // And finally start to connect to the server
            await hub.ConnectAsync();

            SetButtons(false, true);
            AddText(string.Format("Hub Connected with <color=green>{0}</color> transport using the <color=green>{1}</color> encoder.", hub.Transport.TransportType.ToString(), hub.Protocol.Name));

            // Call a server function with a string param. We expect no return value.
            await hub.SendAsync("Send", "my message");

            // Call a parameterless function. We expect a string return value.
            try
            {
                string result = await hub.InvokeAsync <string>("NoParam");

                AddText(string.Format("'<color=green>NoParam</color>' returned: '<color=yellow>{0}</color>'", result))
                .AddLeftPadding(20);
            }
            catch (Exception ex)
            {
                AddText(string.Format("'<color=green>NoParam</color>' error: '<color=red>{0}</color>'", ex.Message)).AddLeftPadding(20);
            }

            // Call a function on the server to add two numbers. OnSuccess will be called with the result and OnError if there's an error.
            var addResult = await hub.InvokeAsync <int>("Add", 10, 20);

            AddText(string.Format("'<color=green>Add(10, 20)</color>' returned: '<color=yellow>{0}</color>'", addResult)).AddLeftPadding(20);

            var nullabelTestResult = await hub.InvokeAsync <int?>("NullableTest", 10);

            AddText(string.Format("'<color=green>NullableTest(10)</color>' returned: '<color=yellow>{0}</color>'", nullabelTestResult)).AddLeftPadding(20);

            // Call a function that will return a Person object constructed from the function's parameters.
            var getPersonResult = await hub.InvokeAsync <Person>("GetPerson", "Mr. Smith", 26);

            AddText(string.Format("'<color=green>GetPerson(\"Mr. Smith\", 26)</color>' returned: '<color=yellow>{0}</color>'", getPersonResult)).AddLeftPadding(20);

            // To test errors/exceptions this call always throws an exception on the server side resulting in an OnError call.
            // OnError expected here!

            try
            {
                var singleResultFailureResult = await hub.InvokeAsync <int>("SingleResultFailure", 10, 20);

                AddText(string.Format("'<color=green>SingleResultFailure(10, 20)</color>' returned: '<color=yellow>{0}</color>'", singleResultFailureResult)).AddLeftPadding(20);
            }
            catch (Exception ex)
            {
                AddText(string.Format("'<color=green>SingleResultFailure(10, 20)</color>' error: '<color=red>{0}</color>'", ex.Message)).AddLeftPadding(20);
            }

            // This call demonstrates IEnumerable<> functions, result will be the yielded numbers.
            var batchedResult = await hub.InvokeAsync <int[]>("Batched", 10);

            AddText(string.Format("'<color=green>Batched(10)</color>' returned items: '<color=yellow>{0}</color>'", batchedResult.Length)).AddLeftPadding(20);

            // OnItem is called for a streaming request for every items returned by the server. OnSuccess will still be called with all the items.
            hub.GetDownStreamController <int>("ObservableCounter", 10, 1000)
            .OnItem(result => AddText(string.Format("'<color=green>ObservableCounter(10, 1000)</color>' OnItem: '<color=yellow>{0}</color>'", result)).AddLeftPadding(20))
            .OnSuccess(result => AddText("'<color=green>ObservableCounter(10, 1000)</color>' OnSuccess.").AddLeftPadding(20))
            .OnError(error => AddText(string.Format("'<color=green>ObservableCounter(10, 1000)</color>' error: '<color=red>{0}</color>'", error)).AddLeftPadding(20));

            // A stream request can be cancelled any time.
            var controller = hub.GetDownStreamController <int>("ChannelCounter", 10, 1000);

            controller.OnItem(result => AddText(string.Format("'<color=green>ChannelCounter(10, 1000)</color>' OnItem: '<color=yellow>{0}</color>'", result)).AddLeftPadding(20))
            .OnSuccess(result => AddText("'<color=green>ChannelCounter(10, 1000)</color>' OnSuccess.").AddLeftPadding(20))
            .OnError(error => AddText(string.Format("'<color=green>ChannelCounter(10, 1000)</color>' error: '<color=red>{0}</color>'", error)).AddLeftPadding(20));

            // a stream can be cancelled by calling the controller's Cancel method
            controller.Cancel();

            // This call will stream strongly typed objects
            hub.GetDownStreamController <Person>("GetRandomPersons", 20, 2000)
            .OnItem(result => AddText(string.Format("'<color=green>GetRandomPersons(20, 1000)</color>' OnItem: '<color=yellow>{0}</color>'", result)).AddLeftPadding(20))
            .OnSuccess(result => AddText("'<color=green>GetRandomPersons(20, 1000)</color>' OnSuccess.").AddLeftPadding(20));
#endif
        }