public void Stop() { using (Trace.Log()) { hubConnection?.Stop(); } }
private async Task<ApiResultBase> StartRealtimeConnection(ConnectExtruderModel connectExtruderModel) { try { _connection = new HubConnection(SOS_URL); _proxy = _connection.CreateHubProxy("SosHub"); _proxy.On<int?, TimeSpan?>("setLights", OnSetLightsEventReceived); _proxy.On<int?, TimeSpan?>("setAudio", OnSetAudioEventReceived); _proxy.On<ModalDialogEventArgs>("modalDialog", OnModalDialogEventReceived); _proxy.On("forceDisconnect", OnForceDisconnect); _proxy.On<TrayIcon>("setTrayIcon", OnSetTrayIcon); _proxy.On<TrayNotifyEventArgs>("trayNotify", OnTrayNotify); _connection.Error += ConnectionOnError; _connection.StateChanged += ConnectionOnStateChanged; _connection.Closed += ConnectionOnClosed; await _connection.Start(); var result = await _proxy.Invoke<ApiResultBase>("connectExtruder", connectExtruderModel); if (!result.Success) { _connection.Stop(); } return result; } catch (Exception ex) { _log.Error("Unable to start realtime connection to SoS Online", ex); return new ApiResultBase {Success = false, ErrorMessage = ex.Message}; } }
void CallToServer() { Console.WriteLine("Input your name ==>"); string inputName = Console.ReadLine(); var hubConnection = new HubConnection("http://localhost:50515/"); hubConnection.Error += hubConnection_Error; IHubProxy consoleHubProxy = hubConnection.CreateHubProxy("HubCenter"); consoleHubProxy.On("broadcastMessage", (string name, string message) => { Console.WriteLine("{0} say: {1}", name, message); }); hubConnection.Start().Wait(); string sayWhat; Console.WriteLine("Say something."); while ((sayWhat = Console.ReadLine()) != "") { try { consoleHubProxy.Invoke("CallFromConsole", new ClientModel { Name = inputName, Message = sayWhat }).Wait(); } catch(Exception ex) { } } hubConnection.Stop(); }
private static async Task SendCompleteNotification(Message message, string uri) { var hubConnection = new HubConnection(url); hub = hubConnection.CreateHubProxy("GifServerHub"); await hubConnection.Start(); Console.WriteLine("Invoked GifGenerationCompleted with URL: {0}", uri); await hub.Invoke("GifGenerationCompleted", message.HubId, uri); hubConnection.Stop(); }
private async Task MainAsync() { _hubConnection = CreateConnection(); Console.WriteLine("Created connection, waiting 1 minute to start it."); Thread.Sleep(TimeSpan.FromMinutes(1)); await _hubConnection.Start(); Console.WriteLine("Press any key to exit."); Console.ReadKey(); _hubConnection.Stop(); }
static void Main(string[] args) { var con = new HubConnection("http://localhost/SignalRDemo"); var adminHub = con.CreateHubProxy("admin"); con.Start().ContinueWith(t => Console.WriteLine("Connected")).Wait(); adminHub.On<dynamic>("orderReceived", order => Console.WriteLine(order)); Console.Read(); con.Stop(); }
static void Main(string[] args) { var url = "http://localhost:8080/"; var connection = new HubConnection(url); //必须在Connection连接之前创建Hub var serviceHub = connection.CreateHubProxy("MyServiceHub"); //注册该Hub的Hit方法对应的客户端处理程序 serviceHub.On<string,string>("pushMessage", (p,q) => { Console.WriteLine(p+":"+q); }); Console.WriteLine("正在连接服务器..."); connection.Start().Wait(); if (connection.State == ConnectionState.Disconnected) { Console.WriteLine("连接服务器失败"); } else { Console.WriteLine("连接服务器成功"); serviceHub.Invoke("HelloWorld").Wait(); while (true) { Console.WriteLine("请选择:\n1.发送消息\n2.发送测试对象\n3.获取SessionID\n0.退出"); string key = Console.ReadLine(); if (key == "1") { Console.WriteLine("请输入消息内容:"); serviceHub.Invoke("SendMessage", Console.ReadLine()).Wait(); } else if (key == "2") { var obj = new { Name = "小明", Age = 18 }; serviceHub.Invoke("SendObject",obj).Wait(); } else if (key == "3") { Console.WriteLine("SessionID:" + serviceHub.Invoke<string>("GetSessionId").Result); } else if (key == "0") { connection.Stop(); return; } } } }
/// <summary> /// 互动发送消息 /// </summary> /// <param name="HubName"></param> /// <param name="HubAction"></param> public void Signal_Excute(String HubName, Action<IHubProxy> HubAction) { var HubUrl = ConfigurationManager.AppSettings["AdminSiteUrl"] + "/signalr"; var Connection = new HubConnection(HubUrl); var HubItem = Connection.CreateHubProxy(HubName); Connection.Start().ContinueWith(task => { if (!task.IsFaulted) { HubAction(HubItem); } }).Wait(); Connection.Stop(); }
static void Main(string[] args) { String hub = ConfigurationManager.AppSettings["hub"]; HubConnection myHubConn; IHubProxy myHub; myHubConn = new HubConnection(hub); myHub = myHubConn.CreateHubProxy("resultatServiceHub"); myHubConn.Error += ex => Console.WriteLine("SignalR error: {0}", ex.Message, ex.InnerException); myHubConn.TraceLevel = TraceLevels.None; myHubConn.TraceWriter = Console.Out; myHubConn.Start() .ContinueWith((prevTask) => { myHub.Invoke("Join", "ResultService"); myHub.Invoke("AddtoGroup", ""); }).Wait(); myHub.On<Participant>("newPass", (data) => { foreach (ParticipantClass c in data.Classes) { myHub.Invoke<ICollection<Participant>>("GetCurrentResults", c.Id) .ContinueWith((result) => { var d = result.Result; var json = JsonConvert.SerializeObject(d, Formatting.Indented); System.IO.File.WriteAllText(@"c:\temp\" + c.Name + ".json", json); }); } } ); Console.ReadLine(); myHubConn.Stop(); Console.WriteLine("Stopped"); }
public async Task<ActionResult> Upload(string site) { for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; Guid id = Guid.NewGuid(); byte[] logo = new byte[file.ContentLength]; file.InputStream.Read(logo, 0, file.ContentLength); _dataPersistor.SaveImage(logo, site, id); var hubConnection = new HubConnection("http://localhost:4785/"); IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("NotificationHub"); await hubConnection.Start(); await stockTickerHubProxy.Invoke("NotifyPostedImage", new NotifyPostedImageCommand { Id = id, Secret = _secret, Image = logo, Timestamp = DateTime.Now, SiteName = (string)RouteData.Values["site"] }); hubConnection.Stop(); } return Json(new { success = true }, JsonRequestBehavior.AllowGet); }
static void Main(string[] args) { Console.Title = "Drawing Board Virtual"; Console.SetWindowSize(80, 60); Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); var server = "http://localhost:52234/"; var hubConn = new HubConnection(server); var hubProxy = hubConn.CreateHubProxy("board"); hubProxy.On("clear", () => { Console.BackgroundColor = ConsoleColor.White; Console.Clear(); }); hubProxy.On("drawPoint", (int x, int y, int color) => DrawPoint(x, y, color)); hubProxy.On("update", (int[,] buffer) => { for (int x = 0; x < buffer.GetLength(0); x++) { for (int y = 0; y < buffer.GetLength(1); y++) { if (buffer[x, y] != 0) { DrawPoint(x, y, buffer[x, y]); } } } }); hubConn.Start().ContinueWith(c => { if (c.IsFaulted) { Console.WriteLine("Error to conect"); } }); Console.ReadLine(); hubConn.Stop(); }
private static void Main(string[] args) { Console.Title = "Console drawing board viewer"; Console.SetWindowSize(80, 50); Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); var server = "http://localhost:52682/signalr"; var hubConn = new HubConnection(server, false); var hubProxy = hubConn.CreateHubProxy("drawingBoard"); hubProxy.On("clear", () => { Console.BackgroundColor = ConsoleColor.White; Console.Clear(); }); hubProxy.On("drawPoint", (int x, int y, int color) => { DrawPoint(x, y, color); }); hubProxy.On("update", (int[,] buffer) => { for (int x = 0; x < buffer.GetLength(0); x++) { for (int y = 0; y < buffer.GetLength(1); y++) { if (buffer[x, y] != 0) DrawPoint(x, y, buffer[x, y]); } } }); hubConn.Start().ContinueWith(t => { if (t.IsFaulted) { Console.WriteLine("Error connecting to " + server + ". Are you using the right URL?"); } }); Console.ReadLine(); hubConn.Stop(); }
private static void Main(string[] args) { Console.Clear(); Console.WriteLine("(Enter port number"); var port = Console.ReadLine(); string host = "http://localhost:" + port; while (true) { var connection = new HubConnection(host); Console.Clear(); Console.WriteLine("(Enter 'adam' or 'admin' as username to access private methods)"); Console.Write("Enter your username: "******"Enter your password: "******"/account/login", username, password).Result; if (authCookie == null) { Console.WriteLine("Impossible to get the token. Press a key to try again."); Console.ReadKey(); continue; } Console.WriteLine("Token obtained"); connection.CookieContainer = new CookieContainer(); connection.CookieContainer.Add(authCookie); var proxy = connection.CreateHubProxy("EchoHub"); proxy.On<string>("Message", msg => Console.WriteLine(" Received: " + msg)); connection.Start().Wait(); Invoke(proxy, "PublicMessage", username); Invoke(proxy, "MembersMessage", username); Invoke(proxy, "AdminsMessage", username); Invoke(proxy, "PrivateMessage", username); Console.WriteLine("\n\nPress any key to try again, Ctrl-C to exit"); Console.ReadKey(); connection.Stop(); } }
public static void Main(string[] args) { var connection = new HubConnection("http://127.0.0.1:8088/"); var myHub = connection.CreateHubProxy("ChatHub"); connection.Start().ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException()); } else { Console.WriteLine("Connected"); } }).Wait(); myHub.On<string>("addMessage", param => { Console.WriteLine(param); }); Console.Write("Your name: "); string name = Console.ReadLine(); myHub.Invoke<string>("Chat", "Online: " + name).Wait(); while (true) { string message = Console.ReadLine(); myHub.Invoke<string>("Chat", name + ":" + message).Wait(); if (message == "quit") break; } connection.Stop(); }
static void Main(string[] args) { String hub = ConfigurationManager.AppSettings["hub"]; String name = ConfigurationManager.AppSettings["name"]; HubConnection myHubConn; IHubProxy myHub; myHubConn = new HubConnection(hub); myHub = myHubConn.CreateHubProxy("resultatServiceHub"); myHubConn.Start() .ContinueWith((prevTask) => { myHub.Invoke("Join", "Printer - " + name); myHub.Invoke("AddtoGroup", "0"); myHub.Invoke("AddtoGroup", "248"); }).Wait(); myHub.On<Participant>("newPass", (data) => { PrintParticiant(data); }); myHubConn.Start().ContinueWith(task => { if (task.IsFaulted) Console.WriteLine("Error opening connection", task.Exception.Message); else Console.WriteLine("Connected"); }).Wait(); Console.Read(); myHubConn.Stop(); Console.WriteLine("Stopped"); }
static void Main(string[] args) { var connection = new HubConnection("http://localhost:57459/"); connection.TraceLevel = TraceLevels.All; connection.TraceWriter = System.Console.Out; var proxy = connection.CreateHubProxy("ChatHub"); connection.Start() .ContinueWith(t => { throw t.Exception.GetBaseException(); },TaskContinuationOptions.OnlyOnFaulted) .ContinueWith(_ => { for (int i = 0; i < 1000; i++) { Thread.Sleep(TimeSpan.FromMilliseconds(new Random().Next(1, 15))); var message = string.Format("Message number {0}", i); System.Console.WriteLine(message); proxy.Invoke("MessageGroup", "SignalR", message).Wait(); } }).ContinueWith(_ => connection.Stop()); System.Console.ReadLine(); }
public void ReturningNullFromReconnectAccepted() { var mockHub = new Mock<SomeHub>() { CallBase = true }; mockHub.Setup(h => h.OnReconnected()).Returns<Task>(null).Verifiable(); using (var host = new MemoryHost()) { host.Configure(app => { var config = new HubConfiguration { Resolver = new DefaultDependencyResolver() }; app.MapSignalR("/signalr", config); var configuration = config.Resolver.Resolve<IConfigurationManager>(); // The following sets the heartbeat to 1 s configuration.DisconnectTimeout = TimeSpan.FromSeconds(6); configuration.KeepAlive = null; configuration.ConnectionTimeout = TimeSpan.FromSeconds(2); config.Resolver.Register(typeof(SomeHub), () => mockHub.Object); }); var connection = new HubConnection("http://foo"); var hub = connection.CreateHubProxy("SomeHub"); connection.Start(host).Wait(); // Force Reconnect Thread.Sleep(TimeSpan.FromSeconds(3)); hub.InvokeWithTimeout("AllFoo"); Thread.Sleep(TimeSpan.FromSeconds(3)); connection.Stop(); mockHub.Verify(); } }
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(); } } }
static void Main(string[] args) { String hub = ConfigurationManager.AppSettings["hub"]; String name = ConfigurationManager.AppSettings["name"]; String smsPass = ConfigurationManager.AppSettings["pass"]; Boolean copy = true; HubConnection myHubConn; IHubProxy myHub; myHubConn = new HubConnection(hub); myHub = myHubConn.CreateHubProxy("resultatServiceHub"); myHubConn.Start() .ContinueWith((prevTask) => { myHub.Invoke("Join", "SMS - " + name); myHub.Invoke("AddtoGroup", ""); }).Wait(); myHub.On<Participant>("newPass", (data) => { // In production? StringBuilder sb = new StringBuilder(); sb.Append("Klasse: "); sb.Append(data.Classes[0].Name); sb.Append(" Etapper: "); foreach (Result r in data.Splits(data.Classes[0].Id)) { sb.Append(r.Leg.Replace("å", "a")); sb.Append(" "); sb.Append(r.Time); sb.Append(" ("); sb.Append(r.Position); sb.Append(" plass) "); } sb.Append(" Totaltid: "); sb.Append(data.TotalTime); sb.Append(" SMS-tjenestene levert av Difi i samarbeid med Linkmobility"); foreach (String tlf in data.Telephone.Distinct()) { try { String url = String.Format(@"http://sms.pswin.com/http4sms/send.asp?USER=kjeringiopen&{0}&RCV=47{1}&TXT={2}&snd=Kjeringi", "PW=0DgFPq2k3", tlf, sb.ToString()); WebClient webClient = new WebClient(); Stream stream = webClient.OpenRead(url); StreamReader reader = new StreamReader(stream); String request = reader.ReadToEnd(); Console.WriteLine("Success: " + url); } catch (WebException ex) { } } } ); Console.ReadLine(); myHubConn.Stop(); Console.WriteLine("Stopped"); }
private static void InitializeConnection() { _connection = new HubConnection(Configuration.ServantIoHost, new Dictionary<string, string>() { {"installationGuid", Configuration.InstallationGuid.ToString()}, {"organizationGuid", Configuration.ServantIoKey}, {"servername", Environment.MachineName}, {"version", Configuration.Version.ToString()}, }); _myHub = _connection.CreateHubProxy("ServantClientHub"); _myHub.On<CommandRequest>("Request", request => { var deployer = TinyIoCContainer.Current.Resolve<Deployer>(); try { switch (request.Command) { case CommandRequestType.Unauthorized: IsStopped = true; MessageHandler.LogException("Servant.io key was not recognized."); _connection.Stop(); break; case CommandRequestType.GetSites: var sites = SiteManager.GetSites(); var result = Json.SerializeToString(sites); ReplyOverHttp(new CommandResponse(request.Guid) { Message = result, Success = true }); break; case CommandRequestType.UpdateSite: var site = Json.DeserializeFromString<IisSite>(request.JsonObject); var originalSite = SiteManager.GetSiteByName(request.Value); if (originalSite == null) { ReplyOverHttp(new CommandResponse(request.Guid) { Message = Json.SerializeToString(new ManageSiteResult { Result = SiteResult.SiteNameNotFound }), Success = false }); return; } var validationResult = Validators.ValidateSite(site, originalSite); if (validationResult.Errors.Any()) { ReplyOverHttp(new CommandResponse(request.Guid) { Message = Json.SerializeToString(validationResult) }); return; } site.IisId = originalSite.IisId; var updateResult = SiteManager.UpdateSite(site); ReplyOverHttp(new CommandResponse(request.Guid) { Message = Json.SerializeToString(updateResult), Success = true }); break; case CommandRequestType.GetAll: ReplyOverHttp(new CommandResponse(request.Guid) { Message = Json.SerializeToString(new AllResponse { Sites = SiteManager.GetSites().ToList(), FrameworkVersions = NetFrameworkHelper.GetAllVersions().ToList(), ApplicationPools = SiteManager.GetApplicationPools(), Certificates = SiteManager.GetCertificates().ToList(), DefaultApplicationPool = SiteManager.GetDefaultApplicationPool() }), Success = true }); break; case CommandRequestType.GetApplicationPools: var appPools = SiteManager.GetApplicationPools(); ReplyOverHttp(new CommandResponse(request.Guid) { Message = Json.SerializeToString(appPools), Success = true }); break; case CommandRequestType.GetCertificates: ReplyOverHttp(new CommandResponse(request.Guid) { Message = Json.SerializeToString(SiteManager.GetCertificates()), Success = true }); break; case CommandRequestType.StartSite: var startSite = SiteManager.GetSiteByName(request.Value); var startResult = SiteManager.StartSite(startSite); ReplyOverHttp(new CommandResponse(request.Guid) { Success = startResult == SiteStartResult.Started, Message = Json.SerializeToString(startResult) }); break; case CommandRequestType.StopSite: var stopSite = SiteManager.GetSiteByName(request.Value); SiteManager.StopSite(stopSite); ReplyOverHttp(new CommandResponse(request.Guid) { Success = true }); break; case CommandRequestType.RestartSite: var restartSite = SiteManager.GetSiteByName(request.Value); SiteManager.RestartSite(restartSite.IisId); ReplyOverHttp(new CommandResponse(request.Guid) { Message = "ok", Success = true }); break; case CommandRequestType.DeleteSite: var deleteSite = SiteManager.GetSiteByName(request.Value); SiteManager.DeleteSite(deleteSite.IisId); ReplyOverHttp(new CommandResponse(request.Guid) { Message = "ok", Success = true }); break; case CommandRequestType.CreateSite: var createSite = Json.DeserializeFromString<IisSite>(request.JsonObject); var createResult = SiteManager.CreateSite(createSite); ReplyOverHttp(new CommandResponse(request.Guid) { Message = Json.SerializeToString(createResult), Success = true }); break; case CommandRequestType.ForceUpdate: Servant.Update(); ReplyOverHttp(new CommandResponse(request.Guid) { Message = "Started", Success = true }); break; case CommandRequestType.DeploySite: Task.Factory.StartNew(() => deployer.Deploy(Json.DeserializeFromString<Deployment>(request.JsonObject))); break; case CommandRequestType.RollbackDeployment: Task.Factory.StartNew(() => deployer.Rollback(int.Parse(request.Value))); break; case CommandRequestType.CmdExeCommand: if (!Configuration.DisableConsoleAccess) { var manager = TinyIoCContainer.Current.Resolve<ConsoleManager>(); manager.SendCommand(request.Value); } break; case CommandRequestType.UpdateApplicationPool: var applicationPool = Json.DeserializeFromString<ApplicationPool>(request.JsonObject); var originalName = request.Value; SiteManager.UpdateApplicationPool(originalName, applicationPool); ReplyOverHttp(new CommandResponse(request.Guid) { Success = true }); break; case CommandRequestType.StartApplicationPool: SiteManager.StartApplicationPool(request.Value); ReplyOverHttp(new CommandResponse(request.Guid) { Success = true }); break; case CommandRequestType.StopApplicationPool: SiteManager.StopApplicationPool(request.Value); ReplyOverHttp(new CommandResponse(request.Guid) { Success = true }); break; case CommandRequestType.RecycleApplicationPool: SiteManager.RecycleApplicationPool(request.Value); ReplyOverHttp(new CommandResponse(request.Guid) { Message = "ok", Success = true }); break; case CommandRequestType.DeleteApplicationPool: SiteManager.DeleteApplicationPool(request.Value); ReplyOverHttp(new CommandResponse(request.Guid) { Message = "ok", Success = true }); break; case CommandRequestType.CreateApplicationPool: var applicationPoolToCreate = Json.DeserializeFromString<ApplicationPool>(request.JsonObject); SiteManager.CreateApplicationPool(applicationPoolToCreate); ReplyOverHttp(new CommandResponse(request.Guid) { Message = "ok", Success = true }); break; } } catch (Exception exception) { MessageHandler.LogException(exception); } }); _connection.StateChanged += change => { MessageHandler.Print("State changed to: " + change.NewState); switch (change.NewState) { case ConnectionState.Disconnected: Connect(); break; case ConnectionState.Connected: SendServerInfo(Configuration); break; } }; _connection.Error += MessageHandler.LogException; }
public async Task DisconnectFiresForHubsWhenClientCallsStop() { using (var host = new MemoryHost()) { var dr = new DefaultDependencyResolver(); var configuration = dr.Resolve<IConfigurationManager>(); var connectWh = new AsyncManualResetEvent(); var disconnectWh = new AsyncManualResetEvent(); host.Configure(app => { var config = new HubConfiguration { Resolver = dr }; app.MapSignalR("/signalr", config); configuration.DisconnectTimeout = TimeSpan.FromSeconds(6); dr.Register(typeof(MyHub), () => new MyHub(connectWh, disconnectWh)); }); var connection = new HubConnection("http://foo/"); connection.CreateHubProxy("MyHub"); // Maximum wait time for disconnect to fire (3 heart beat intervals) var disconnectWait = TimeSpan.FromTicks(configuration.HeartbeatInterval().Ticks * 3); await connection.Start(host); Assert.True(await connectWh.WaitAsync(TimeSpan.FromSeconds(10)), "Connect never fired"); connection.Stop(); Assert.True(await disconnectWh.WaitAsync(disconnectWait), "Disconnect never fired"); } }
public void Stop() { hubConnection.Stop(); }
public static IDisposable BrodcastFromServer() { var host = new MemoryHost(); IHubContext context = null; host.Configure(app => { var config = new HubConfiguration() { Resolver = new DefaultDependencyResolver() }; app.MapSignalR(config); var configuration = config.Resolver.Resolve<IConfigurationManager>(); // The below effectively sets the heartbeat interval to five seconds. configuration.KeepAlive = TimeSpan.FromSeconds(10); var connectionManager = config.Resolver.Resolve<IConnectionManager>(); context = connectionManager.GetHubContext("SimpleEchoHub"); }); var cancellationTokenSource = new CancellationTokenSource(); var thread = new Thread(() => { while (!cancellationTokenSource.IsCancellationRequested) { context.Clients.All.echo(); } }); thread.Start(); var connection = new HubConnection("http://foo"); var proxy = connection.CreateHubProxy("SimpleEchoHub"); try { connection.Start(host).Wait(); Thread.Sleep(1000); } finally { connection.Stop(); } return new DisposableAction(() => { cancellationTokenSource.Cancel(); thread.Join(); host.Dispose(); }); }
public static IDisposable RunConnectDisconnect(bool scaleout, int nodes = 1, int connections = 1000) { IHttpClient client; IDisposable disposable = TryGetClient(scaleout, nodes, out client); for (int i = 0; i < connections; i++) { var connection = new HubConnection("http://foo"); var proxy = connection.CreateHubProxy("SimpleEchoHub"); var wh = new ManualResetEventSlim(false); proxy.On("echo", _ => wh.Set()); try { connection.Start(client).Wait(); proxy.Invoke("Echo", "foo").Wait(); if (!wh.Wait(TimeSpan.FromSeconds(10))) { Debugger.Break(); } } finally { connection.Stop(); } } return disposable; }
public static IDisposable StressGroups(int max = 100) { var host = new MemoryHost(); host.Configure(app => { var config = new HubConfiguration() { Resolver = new DefaultDependencyResolver() }; app.MapSignalR(config); var configuration = config.Resolver.Resolve<IConfigurationManager>(); // The below effectively sets the heartbeat interval to five seconds. configuration.KeepAlive = TimeSpan.FromSeconds(10); }); var countDown = new CountDownRange<int>(Enumerable.Range(0, max)); var connection = new HubConnection("http://foo"); var proxy = connection.CreateHubProxy("HubWithGroups"); proxy.On<int>("Do", i => { if (!countDown.Mark(i)) { Debugger.Break(); } }); try { connection.Start(new Client.Transports.LongPollingTransport(host)).Wait(); proxy.Invoke("Join", "foo").Wait(); for (int i = 0; i < max; i++) { proxy.Invoke("Send", "foo", i).Wait(); } proxy.Invoke("Leave", "foo").Wait(); for (int i = max + 1; i < max + 50; i++) { proxy.Invoke("Send", "foo", i).Wait(); } if (!countDown.Wait(TimeSpan.FromSeconds(10))) { Console.WriteLine("Didn't receive " + max + " messages. Got " + (max - countDown.Count) + " missed " + String.Join(",", countDown.Left.Select(i => i.ToString()))); Debugger.Break(); } } finally { connection.Stop(); } return host; }
public static void SendLoop() { var host = new MemoryHost(); host.Configure(app => { var config = new HubConfiguration() { Resolver = new DefaultDependencyResolver() }; config.Resolver.Resolve<IConfigurationManager>().ConnectionTimeout = TimeSpan.FromDays(1); app.MapSignalR(config); }); var connection = new HubConnection("http://foo"); var proxy = connection.CreateHubProxy("SimpleEchoHub"); var wh = new ManualResetEventSlim(false); proxy.On("echo", _ => wh.Set()); try { connection.Start(new Client.Transports.LongPollingTransport(host)).Wait(); while (true) { proxy.Invoke("Echo", "foo").Wait(); if (!wh.Wait(TimeSpan.FromSeconds(10))) { Debugger.Break(); } wh.Reset(); } } catch { connection.Stop(); } }
private void Invoke(string method, params object[] args) { var token = Common.Utils.Signature.Create(string.Join(",", Tenant.TenantId, CurrentAccountId, Tenant.TenantAlias)); var hubConnection = new HubConnection(hubUrl, string.Format("token={0}&numberId={1}", token, numberId)); hubConnection.Headers.Add("voipConnection", "true"); var voipHubProxy = hubConnection.CreateHubProxy(hubName); hubConnection.Start().ContinueWith(r => { voipHubProxy.Invoke(method, args).Wait(); hubConnection.Stop(); }); }
static void Main() { using (var i = new Impersonation("igsdomain", "jolmos", "JPol.291179")) { var connection = new HubConnection("http://localhost:34080/"); connection.Credentials = CredentialCache.DefaultCredentials; var hub = connection.CreateHubProxy("LogsHub"); connection.Start().Wait(); //.ContinueWith(task => //{ // if (task.IsFaulted) // { // Console.WriteLine("There was an error opening the connection:{0}", // task.Exception.GetBaseException()); // Console.ReadLine(); // Environment.Exit(1); // } // else // { // Console.WriteLine("Connected"); // } //}).Wait(); var hardCodedGuid = new Guid("63ff8081-b43b-474a-a493-f8c3534f7324"); var existingLogMessageId = new Guid("60D8E681-BE51-4934-B883-28037E6CC328"); var ff = new Guid("011CCAB6-D901-469B-9DDC-15E08383CCE7"); //.ContinueWith(task => //{ // if (task.IsFaulted) // { // Console.WriteLine("There was an error calling send: {0}", // task.Exception.GetBaseException()); // } // else // { // Console.WriteLine("done"); // } //}).RunSynchronously(); hub.Invoke("NewLog", hardCodedGuid.ToString(), new LogMessageModel { LogMessageId = Guid.NewGuid(), Message = "1", DeploymentLogId = hardCodedGuid, TimeStamp = DateTime.Now }).Wait(); hub.Invoke("NewLog", hardCodedGuid.ToString(), new LogMessageModel { LogMessageId = existingLogMessageId, Message = "2", DeploymentLogId = hardCodedGuid, TimeStamp = DateTime.Now }).Wait(); hub.Invoke("NewLog", hardCodedGuid.ToString(), new LogMessageModel { LogMessageId = ff, Message = "3", DeploymentLogId = hardCodedGuid, TimeStamp = DateTime.Now }).Wait(); hub.Invoke("NewLog", hardCodedGuid.ToString(), new LogMessageModel { LogMessageId = Guid.NewGuid(), Message = "4", DeploymentLogId = hardCodedGuid, TimeStamp = DateTime.Now }).Wait(); //hub.On<string>("NewLog", // (name) => Console.WriteLine("{0} - {1}", name)); Console.Read(); connection.Stop(); } }
static void Main(string[] args) { var serviceConnection = new HubConnection("http://localhost:8080"); var hub = serviceConnection.CreateHubProxy("MathHub"); //serviceConnection.StateChanged += e => // { // Console.WriteLine( // "Connection state from {0} to {1}", // e.OldState.ToString(), e.NewState.ToString()); // }; // register event handler. hub.On("notifyUserJoined", () => { Console.WriteLine("A new user is joined."); hub.Invoke("GetUsers"); }); hub.On("notifyUserLeaved", () => { Console.WriteLine("A user is leaved."); hub.Invoke("GetUsers"); }); hub.On("privateMethodCallback", (m) => { Console.WriteLine(m); }); hub.On<IEnumerable<OnlineUser>>("createUsers", (c) => { var users = new StringBuilder(); foreach (var user in c) { if (users.Length == 0) users.Append(user.Name); else users.Append(", ").Append(user.Name); } Console.WriteLine("Currently online users: {0}", users); }); // use Windows Authentication account to connect. serviceConnection.Credentials = CredentialCache.DefaultCredentials; // begin connection. serviceConnection.Start().Wait(); // invoke method needs authorization. hub.Invoke("PrivateMethod").Wait(); Console.WriteLine("Please provide your name to join:"); string userName = Console.ReadLine(); hub.Invoke("Join", userName); Console.WriteLine("Please press ENTER to exit."); while (true) { // press enter to exit. if (string.IsNullOrEmpty(Console.ReadLine())) break; } serviceConnection.Stop(); }
public static void Main(string[] args) { Console.WriteLine("Press any key to start and a second time to exit the program"); Console.ReadKey(); // Authenticate on the platform Client.Post(new Authenticate { UserName = UserName, Password = Password }); // Create a connection against the nofications system and configure it to use the obtained credentials con = new HubConnection(NOTIFICATIONS_URL) { CookieContainer = Client.CookieContainer }; con.StateChanged += change => { switch (change.NewState) { case ConnectionState.Connected: Console.WriteLine("Connected!"); // Methods to call on server must be camel case installationHub.Invoke("joinGroup", INSTALLATION_ID); sensorHub.Invoke("joinGroup", SENSOR_ID); break; case ConnectionState.Disconnected: Console.WriteLine("Disconnected!"); break; } }; // Hub names must be camel case installationHub = con.CreateHubProxy("installationHub"); sensorHub = con.CreateHubProxy("sensorHub"); // Subscribe to desired events on each Hub installationHub.On<string, string, string, string>(INSTALLATION_SECURITY_EVENT, (installationId, date, status, trigger) => { Console.WriteLine("Received Security Status change notification"); Console.WriteLine("Installation Id: " + installationId); Console.WriteLine("Date: " + date); Console.WriteLine("Status: " + status); Console.WriteLine("Trigger: " + trigger); }); sensorHub.On<string, string, string>(SENSOR_NEW_VALUE_EVENT, (sensorId, date, value) => { Console.WriteLine("Received New Sensor value notification"); Console.WriteLine("Sensor Id: " + sensorId); Console.WriteLine("Date: " + date); Console.WriteLine("Value: " + value); }); con.Start(); Console.ReadKey(); con.Stop(); }
public virtual async Task<DesktopAppConnectionResult> StartRealtimeConnection(SirenOfShameSettings settings) { try { if (!settings.GetSosOnlineContent()) { InvokeOnSosOnlineStatusChange("Disabled"); return new DesktopAppConnectionResult { Success = false }; } InvokeOnSosOnlineStatusChange("Connecting"); _connection = new HubConnection(SOS_URL); _proxy = _connection.CreateHubProxy("SosHub"); _proxy.On("addChatMessageToDesktopClients", InvokeOnOnNewSosOnlineNotification); _connection.Error += ConnectionOnError; _connection.StateChanged += ConnectionOnStateChanged; _connection.Closed += ConnectionOnClosed; await _connection.Start(); var credentialApiModel = new CredentialApiModel { UserName = settings.SosOnlineUsername, Password = settings.SosOnlinePassword, }; var result = await _proxy.Invoke<DesktopAppConnectionResult>("connectDesktopApp", credentialApiModel); if (!result.Success) { _connection.Stop(); } return result; } catch (Exception ex) { _log.Error("Unable to start realtime connection to SoS Online", ex); } return new DesktopAppConnectionResult { Success = false }; }
public void ReturningNullFromConnectAndDisconnectAccepted() { var mockHub = new Mock<SomeHub>() { CallBase = true }; mockHub.Setup(h => h.OnConnected()).Returns<Task>(null).Verifiable(); mockHub.Setup(h => h.OnDisconnected()).Returns<Task>(null).Verifiable(); using (var host = new MemoryHost()) { host.Configure(app => { var config = new HubConfiguration { Resolver = new DefaultDependencyResolver() }; app.MapSignalR("/signalr", config); var configuration = config.Resolver.Resolve<IConfigurationManager>(); // The below effectively sets the heartbeat interval to one second. configuration.KeepAlive = TimeSpan.FromSeconds(2); config.Resolver.Register(typeof(SomeHub), () => mockHub.Object); }); var connection = new HubConnection("http://foo"); var hub = connection.CreateHubProxy("SomeHub"); connection.Start(host).Wait(); connection.Stop(); Thread.Sleep(TimeSpan.FromSeconds(3)); } mockHub.Verify(); }