Ejemplo n.º 1
0
        public RemoteDeploymentManager(string serviceUrl)
        {
            serviceUrl = UrlUtility.EnsureTrailingSlash(serviceUrl);
            _client = HttpClientHelper.Create(serviceUrl);

            // Raise the event when data comes in
            _connection = new Connection(serviceUrl + "status");
            _connection.Received += data => {
                if (StatusChanged != null) {
                    var result = JsonConvert.DeserializeObject<DeployResult>(data);
                    StatusChanged(result);
                }
            };

            _connection.Error += exception => {
                // If we get a 404 back stop listening for changes
                WebException webException = exception as WebException;
                if (webException != null) {
                    var webResponse = (HttpWebResponse)webException.Response;
                    if (webResponse != null &&
                        webResponse.StatusCode == HttpStatusCode.NotFound) {
                        _connection.Stop();
                    }
                }
            };

            _connection.Closed += () => {
                Debug.WriteLine("SignalR connection to {0} was closed.", serviceUrl);
            };

            _connection.Start().Wait();
        }
Ejemplo n.º 2
0
        private static Task ConnectBatch(string url, int batchSize, ConcurrentBag<Connection> connections)
        {
            var options = new ParallelOptions
            {
                MaxDegreeOfParallelism = batchSize
            };

            var tcs = new TaskCompletionSource<object>();
            long remaining = batchSize;
            Parallel.For(0, batchSize, options, i =>
            {
                var connection = new Connection(url);

                connection.Start().ContinueWith(task =>
                {
                    remaining = Interlocked.Decrement(ref remaining);

                    if (task.IsFaulted)
                    {
                        Console.WriteLine("Failed to start client. {0}", task.Exception.GetBaseException());
                    }
                    else
                    {
                        connections.Add(connection);

                        var clientId = connection.ConnectionId;

                        //connection.Received += data =>
                        //{
                        //    Console.WriteLine("Client {0} RECEIVED: {1}", clientId, data);
                        //};

                        connection.Error += e =>
                        {
                            Debug.WriteLine(String.Format("SIGNALR: Client {0} ERROR: {1}", clientId, e));
                        };

                        connection.Closed += () =>
                        {
                            Debug.WriteLine(String.Format("SIGNALR: Client {0} CLOSED", clientId));
                        };

                    }

                    if (Interlocked.Read(ref remaining) == 0)
                    {
                        // When all connections are connected, mark the task as complete
                        tcs.TrySetResult(null);
                    }
                });
            });

            return tcs.Task;
        }
Ejemplo n.º 3
0
            public void FailedNegotiateShouldNotBeActive()
            {
                var connection = new Connection("http://test");
                var transport = new Mock<IClientTransport>();
                transport.Setup(m => m.Negotiate(connection))
                         .Returns(TaskAsyncHelper.FromError<NegotiationResponse>(new InvalidOperationException("Something failed.")));

                var aggEx = Assert.Throws<AggregateException>(() => connection.Start(transport.Object).Wait());
                var ex = aggEx.Unwrap();
                Assert.IsType(typeof(InvalidOperationException), ex);
                Assert.Equal("Something failed.", ex.Message);
                Assert.Equal(ConnectionState.Disconnected, connection.State);
            }
Ejemplo n.º 4
0
            public void FailsIfProtocolVersionIsNull()
            {
                var connection = new Connection("http://test");
                var transport = new Mock<IClientTransport>();
                transport.Setup(m => m.Negotiate(connection)).Returns(TaskAsyncHelper.FromResult(new NegotiationResponse
                {
                    ProtocolVersion = null
                }));

                var aggEx = Assert.Throws<AggregateException>(() => connection.Start(transport.Object).Wait());
                var ex = aggEx.Unwrap();
                Assert.IsType(typeof(InvalidOperationException), ex);
                Assert.Equal("Incompatible protocol version.", ex.Message);
            }
Ejemplo n.º 5
0
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            var connection = new Connection("http://mxm-signalr.azurewebsites.net/raw-connection");

            connection.Received += data => Report(data);

            connection.Reconnected += () => Report("[{0}]: Connection restablished", DateTime.Now);

            connection.StateChanged += change => Report(change.OldState + " => " + change.NewState);

            connection.Error += ex =>
            {
                Report("========ERROR==========" + ex.Message + "=======================");
            };

            connection.Start();
        }
Ejemplo n.º 6
0
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            var connection = new Connection("http://signalr-sample.azurewebsites.net/raw-connection/");
            connection.Received += data =>
            {
                Dispatcher.BeginInvoke(() =>
                {
                    App.ViewModel.Items.Add(new ItemViewModel { LineOne = data });
                });
            };

            connection.Error += ex =>
            {
                Dispatcher.BeginInvoke(() =>
                {
                    var aggEx = (AggregateException)ex;
                    App.ViewModel.Items.Add(new ItemViewModel { LineOne = aggEx.InnerExceptions[0].Message });
                });
            };

            connection.Reconnected += () =>
            {
                Dispatcher.BeginInvoke(() =>
                {
                    App.ViewModel.Items.Add(new ItemViewModel { LineOne = "Connection restored" });
                });
            };

            var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
            connection.Start().ContinueWith(task =>
            {
                var ex = task.Exception.InnerExceptions[0];
                App.ViewModel.Items.Add(new ItemViewModel { LineOne = ex.Message });
            },
            CancellationToken.None,
            TaskContinuationOptions.OnlyOnFaulted,
            scheduler);
        }
Ejemplo n.º 7
0
            public void FailedStartShouldNotBeActive()
            {
                var connection = new Connection("http://test");
                var transport = new Mock<IClientTransport>();
                transport.Setup(m => m.Negotiate(connection))
                         .Returns(TaskAsyncHelper.FromResult(new NegotiationResponse
                         {
                             ProtocolVersion = "1.1",
                             ConnectionId = "Something"
                         }));

                transport.Setup(m => m.Start(connection, null, It.IsAny<CancellationToken>()))
                         .Returns(TaskAsyncHelper.FromError(new InvalidOperationException("Something failed.")));

                var aggEx = Assert.Throws<AggregateException>(() => connection.Start(transport.Object).Wait());
                var ex = aggEx.Unwrap();
                Assert.IsType(typeof(InvalidOperationException), ex);
                Assert.Equal("Something failed.", ex.Message);
                Assert.Equal(ConnectionState.Disconnected, connection.State);
            }
Ejemplo n.º 8
0
        private async Task RunStreaming(string serverUrl)
        {
            string url = serverUrl + "streaming-connection";

            var connection = new Connection(url);
            connection.TraceWriter = _traceWriter;

            await connection.Start();
            connection.TraceWriter.WriteLine("transport.Name={0}", connection.Transport.Name);
        }
Ejemplo n.º 9
0
        private async Task RunRawConnection(string serverUrl)
        {
            string url = serverUrl + "raw-connection";

            var connection = new Connection(url);
            connection.TraceWriter = _traceWriter;

            await connection.Start();
            connection.TraceWriter.WriteLine("transport.Name={0}", connection.Transport.Name);

            await connection.Send(new { type = 1, value = "first message" });
            await connection.Send(new { type = 1, value = "second message" });
        }
Ejemplo n.º 10
0
        private async Task RunAuth(string serverUrl)
        {
            string url = serverUrl + "cookieauth";

            var handler = new HttpClientHandler();
            handler.CookieContainer = new CookieContainer();
            using (var httpClient = new HttpClient(handler))
            {
                var content = string.Format("UserName={0}&Password={1}", "user", "password");
                var response = httpClient.PostAsync(url + "/Account/Login", new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded")).Result;
            }

            var connection = new Connection(url + "/echo");
            connection.TraceWriter = _traceWriter;
            connection.Received += (data) => connection.TraceWriter.WriteLine(data);
#if !ANDROID && !iOS
            connection.CookieContainer = handler.CookieContainer;
#endif
            await connection.Start();
            await connection.Send("sending to AuthenticatedEchoConnection");

            var hubConnection = new HubConnection(url);
            hubConnection.TraceWriter = _traceWriter;
#if !ANDROID && !iOS
            hubConnection.CookieContainer = handler.CookieContainer;
#endif
            var hubProxy = hubConnection.CreateHubProxy("AuthHub");
            hubProxy.On<string, string>("invoked", (connectionId, date) => hubConnection.TraceWriter.WriteLine("connectionId={0}, date={1}", connectionId, date));

            await hubConnection.Start();
            hubConnection.TraceWriter.WriteLine("transport.Name={0}", hubConnection.Transport.Name);

            await hubProxy.Invoke("InvokedFromClient");
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Crank v{0}", typeof(Program).Assembly.GetName().Version);
            if (args.Length < 2)
            {
                Console.WriteLine("Usage: crank [url] [numclients]");
                return;
            }

            ServicePointManager.DefaultConnectionLimit = Int32.MaxValue;

            string url = args[0];
            int clients = Int32.Parse(args[1]);

            TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;

            var connections = new ConcurrentBag<Connection>();

            var sw = Stopwatch.StartNew();

            Task.Factory.StartNew(() =>
            {
                Parallel.For(0, clients, i =>
                {
                    try
                    {
                        var connection = new Connection(url);
                        connection.Received += data =>
                        {
                            Console.WriteLine(data);
                        };

                        connection.Error += e =>
                        {
                            Console.WriteLine("ERROR: Client {0}, {1}", i, e.GetBaseException());
                        };

                        connection.Closed += () =>
                        {
                            Console.WriteLine("CLOSED: {0}", i);
                        };

                        connection.Start().Wait();
                        connections.Add(connection);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Failed to start client {0}. {1}", i, e);
                    }
                });
                Console.WriteLine("Started {0} connection(s).", connections.Count);
            });

            Console.WriteLine("Press any key to stop running...");
            Console.Read();
            sw.Stop();

            Console.WriteLine("Total Running time: {0}s", sw.Elapsed);
            Console.WriteLine("End point: {0}", url);
            Console.WriteLine("Total connections: {0}", clients);
            Console.WriteLine("Active connections: {0}", connections.Count(c => c.IsActive));
            Console.WriteLine("Stopped connections: {0}", connections.Count(c => !c.IsActive));
        }
Ejemplo n.º 12
0
 private void button1_Click(object sender, EventArgs e)
 {
     if (!int.TryParse(textPort.Text, out port))
     {
         MessageBox.Show("Please enter a number in the port section.");
         DialogResult = DialogResult.None;
         return;
     }
     Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     try
     {
         socket.Connect(Hostname, port);
     }
     catch
     {
         MessageBox.Show("Unable to connect to chosen server on specified port.");
         DialogResult = DialogResult.None;
         return;
     }
     try
     {
         Connection con = new Connection(socket, ParentShard);
         player.Name = textUsername.Text;
         SHA256 hasher = SHA256.Create();
         player.PasswordHash = hasher.ComputeHash(Encoding.Unicode.GetBytes(textPassword.Text));
         player.Connection = con;
         con.Player = player;
         con.Start();
         HelloResponse res = (HelloResponse)con.SendMessage(new HelloMessage());
         if (!res.Success)
         {
             MessageBox.Show("Client version incompatible with selected server.");
             DialogResult = DialogResult.None;
             return;
         }
         byte[] publicKeyData = res.PublicKeyData;
         byte[] nonce = res.Nonce;
         Message response = con.SendMessage(new LoginPlayerMessage(player.Name, player.PasswordHash, publicKeyData, nonce));
         LoginPlayerResponseMessage realResponse = response as LoginPlayerResponseMessage;
         if (realResponse != null)
         {
             if (!realResponse.Success)
             {
                 if (MessageBox.Show("Username does not exist or password wrong, should I attempt to create a new player?", "Login failure.", MessageBoxButtons.YesNo) == DialogResult.Yes)
                 {
                     // TODO - confirm password.
                     response = con.SendMessage(new CreatePlayerMessage(player.Name, player.PasswordHash, publicKeyData, nonce));
                     CreatePlayerResponseMessage realResponse2 = response as CreatePlayerResponseMessage;
                     if (realResponse2 != null)
                     {
                         if (realResponse2.Success)
                         {
                             MessageBox.Show("Player successfully created.");
                             return;
                         }
                         else
                         {
                             MessageBox.Show("Name already exists, choose another.");
                             DialogResult = DialogResult.None;
                             return;
                         }
                     }
                     else
                         throw new NotSupportedException("Unexpected response type from server.");
                 }
                 else
                 {
                     DialogResult = DialogResult.None;
                     return;
                 }
             }
         }
         else
             throw new NotSupportedException("Unexpected response received from server.");
     }
     catch
     {
         MessageBox.Show("Unexpected error occured while logging in.");
         DialogResult = DialogResult.None;
         return;
     }
 }
Ejemplo n.º 13
0
        private async Task RunBasicAuth(string serverUrl)
        {
            string url = serverUrl + "basicauth";

            var connection = new Connection(url + "/echo");
            connection.TraceWriter = _traceWriter;
            connection.Received += (data) => connection.TraceWriter.WriteLine(data);
            connection.Credentials = new NetworkCredential("user", "password");
            await connection.Start();
            await connection.Send("sending to AuthenticatedEchoConnection");

            var hubConnection = new HubConnection(url);
            hubConnection.TraceWriter = _traceWriter;
            hubConnection.Credentials = new NetworkCredential("user", "password");

            var hubProxy = hubConnection.CreateHubProxy("AuthHub");
            hubProxy.On<string, string>("invoked", (connectionId, date) => hubConnection.TraceWriter.WriteLine("connectionId={0}, date={1}", connectionId, date));

            await hubConnection.Start();            
            hubConnection.TraceWriter.WriteLine("transport.Name={0}", hubConnection.Transport.Name);

            await hubProxy.Invoke("InvokedFromClient");            
        }