public void BenchmarkMessages() { var port = new Random().Next(20000, 60000); GlobalHost.Configuration.DefaultMessageBufferSize = 2000; // maximum number of messages to buffer GlobalHost.Configuration.MaxIncomingWebSocketMessageSize = null; GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(15); // auto set keepalive to 5 var url = "http://localhost:" + port + "/"; var server = WebApp.Start<Startup>(url); var client = new HubConnection(url + "s1"); var proxy = client.CreateHubProxy("ISumService"); client.Start().Wait(); Assert.Equal(ConnectionState.Connected, client.State); const int randCnt = 100; var rand = new Random(42); var randoms = new int[randCnt]; for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000); var sw = new Stopwatch(); long timeFromClient = 0, timeToClient = 0; const int cnt = 1000; for (int j = 0; j < cnt; j++) { sw.Start(); var sum = proxy.Invoke<int>("Sum", randoms).Result; sw.Stop(); Assert.Equal(randoms.Sum(), sum); for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000); var times = proxy.Invoke<Tuple<long,long>>("TimeDiff", Stopwatch.GetTimestamp()).Result; timeFromClient += times.Item1; timeToClient += Stopwatch.GetTimestamp() - times.Item2; } _testOutputHelper.WriteLine("Completed {0} sum passes in {1}ms", cnt, sw.ElapsedMilliseconds); _testOutputHelper.WriteLine("Client to server latency: {0}us", timeFromClient / cnt / 10); _testOutputHelper.WriteLine("Server to client latency: {0}us", timeToClient / cnt / 10); sw.Reset(); var tree = new SumServiceTree(); SumServiceTree.FillTree(tree, rand, 2); _testOutputHelper.WriteLine("Starting large message transfer."); sw.Start(); var result = proxy.Invoke<SumServiceTree>("Increment", tree).Result; sw.Stop(); Assert.Equal(tree.Leaf + 1, result.Leaf); _testOutputHelper.WriteLine("Completed large transfer in {0}ms", sw.Elapsed.TotalMilliseconds); client.Dispose(); server.Dispose(); }
private async Task<bool> EnsureProxy() { if (HubProxy != null) return true; Connection = new HubConnection(ServerUri); HubProxy = Connection.CreateHubProxy("CustomerHub"); // Register callbacks HubProxy.On<Customer>("Saved", OnCustomerSaved); HubProxy.On<Guid>("Deleted", OnCustomerDeleted); try { await Connection.Start(); return true; } catch (HttpRequestException) { Connection.Dispose(); Connection = null; MessageBox.Show("Unable to connect to server: Start server before connecting clients."); return false; } }
private void StopService() { if (_Hub != null) { _Hub.Dispose(); } _ProxyAuth = null; }
public virtual void Dispose() { reconnect = false; Stop(); hubConnection?.Dispose(); hubConnection = null; }
public virtual void Dispose() { using (Trace.Log()) { reconnect = false; //Stop(); hubConnection.StateChanged -= OnStateChanged; hubConnection.Dispose(); hubConnection = null; } }
public async Task EndToEndHub () { var sessionId = Guid.NewGuid().ToString(); var clients = 0; var pubConn = new HubConnection(ThisAssembly.HubUrl); var pubProxy = pubConn.CreateHubProxy("FormsPlayer"); var subConn = new HubConnection(ThisAssembly.HubUrl); var subProxy = subConn.CreateHubProxy("FormsPlayer"); var xamls = new List<string>(); var jsons = new List<string>(); pubProxy.On<int> ("Connected", count => clients = count); subProxy.On<string> ("Xaml", xaml => xamls.Add (xaml)); subProxy.On<string> ("Json", json => jsons.Add (json)); await pubConn.Start (); await subConn.Start (); await pubProxy.Invoke ("Join", sessionId); await subProxy.Invoke ("Join", sessionId); SpinWait.SpinUntil (() => clients == 2, 1000); // Count will be 1+ than actual "clients", since the publisher/VS is also a client. Assert.Equal (2, clients); await pubProxy.Invoke ("Xaml", sessionId, "xaml"); await pubProxy.Invoke ("Xaml", Guid.NewGuid ().ToString (), "xaml"); await pubProxy.Invoke ("Json", sessionId, "json"); await pubProxy.Invoke ("Json", Guid.NewGuid ().ToString (), "json"); Assert.Equal (1, xamls.Count); Assert.Equal (1, jsons.Count); Assert.Equal ("xaml", xamls[0]); Assert.Equal ("json", jsons[0]); subConn.Dispose (); SpinWait.SpinUntil (() => clients == 1, 1000); Assert.Equal (1, clients); }
internal void Connect() { IsConnected = false; connection = new HubConnection ("http://formsplayer.azurewebsites.net/"); proxy = connection.CreateHubProxy ("FormsPlayer"); try { connection.Start ().Wait (3000); IsConnected = true; IdeApp.Workbench.StatusBar.ShowMessage (string.Format("Successfully connected to FormsPlayer. Session ID: {0}", SessionId)); } catch (Exception e) { IdeApp.Workbench.StatusBar.ShowMessage (string.Format("Error connecting to FormsPlayer: {0}", e.Message)); connection.Dispose (); Console.WriteLine (e); } }
void OnWrite(string message) { if (proxy == null) { if (string.IsNullOrEmpty (Parameters)) // throw new LoggerException ("No build identifier was specified as a logger parameter."); return; buildId = Parameters.Split (';') .Select (x => x.Split ('=')) .Where (x => x.Length == 2 && x[0].Equals ("buildId", StringComparison.OrdinalIgnoreCase)) .Select (x => x[1]) .FirstOrDefault (); if (string.IsNullOrEmpty (buildId)) throw new LoggerException ("No buildId parameter value was specified as a logger parameter. Use buildId=ID after the logger assembly."); hubUrl = Parameters.Split (';') .Select (x => x.Split ('=')) .Where (x => x.Length == 2 && x[0].Equals ("hubUrl", StringComparison.OrdinalIgnoreCase)) .Select (x => x[1]) .FirstOrDefault () ?? defaultHubUrl; connection = new HubConnection (hubUrl); proxy = connection.CreateHubProxy ("build"); try { connection.Start ().Wait (3000); proxy.On ("Shutdown", () => shutDown.Set ()); } catch (Exception e) { Trace.WriteLine ("Failed to connect to " + hubUrl + ": " + e.ToString ()); connection.Dispose (); connection = null; } } // If connection failed, the connection will be null. if (connection != null) { proxy.Invoke ("Message", buildId, message) .ContinueWith (t => Trace.WriteLine ("Failed to publish message."), CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); } }
protected virtual string ConnectToServer(Dev2.Data.ServiceModel.Connection connection) { // we need to grab the principle and impersonate to properly execute in context of the requesting user ;) var principle = Thread.CurrentPrincipal; var identity = principle.Identity as WindowsIdentity; WindowsImpersonationContext context = null; try { if(identity != null && connection.AuthenticationType == AuthenticationType.Windows) { context = identity.Impersonate(); } using(var client = new WebClient()) { if(connection.AuthenticationType == AuthenticationType.Windows) { client.UseDefaultCredentials = true; } else { client.UseDefaultCredentials = false; //// we to default to the hidden public user name of \, silly know but that is how to get around ntlm auth ;) if(connection.AuthenticationType == AuthenticationType.Public) { connection.UserName = GlobalConstants.PublicUsername; connection.Password = string.Empty; } client.Credentials = new NetworkCredential(connection.UserName, connection.Password); } // Need to do hub connect here to get true permissions ;) HubConnection hub = null; try { // Credentials = client.Credentials hub = new HubConnection(connection.FetchTestConnectionAddress()) { Credentials = client.Credentials }; ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; #pragma warning disable 168 var proxy = hub.CreateHubProxy("esb"); // this is the magic line that causes proper validation #pragma warning restore 168 hub.Start().Wait(); Dev2Logger.Log.Debug("Hub State : " + hub.State); return "Success"; } catch(Exception) { // Credentials = client.Credentials var hub2 = new HubConnectionWrapperOld(connection.FetchTestConnectionAddress()) { Credentials = client.Credentials }; ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; #pragma warning disable 168 var proxy = hub2.CreateHubProxy("esb"); // this is the magic line that causes proper validation #pragma warning restore 168 hub2.Start().Wait(); Dev2Logger.Log.Debug("Hub State : " + hub2.State); return "Success"; } finally { if(hub != null) { hub.Stop(); hub.Dispose(); } } } } finally { if(context != null && connection.AuthenticationType == AuthenticationType.Windows) { context.Undo(); } } }
private void UpdateClients() { IHubProxy _hub; string url = @"http://www.duser.net/"; var connection = new HubConnection(url); _hub = connection.CreateHubProxy("WeatherHub"); connection.Start().Wait(); _hub.Invoke("GetData").Wait(); connection.Dispose(); }